repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
MichaelRocks/lightsaber
processor/src/main/java/io/michaelrocks/lightsaber/processor/model/ProvisionPoint.kt
1
2057
/* * Copyright 2020 Michael Rozumyanskiy * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.michaelrocks.lightsaber.processor.model import io.michaelrocks.grip.mirrors.FieldMirror import io.michaelrocks.grip.mirrors.MethodMirror import io.michaelrocks.grip.mirrors.Type sealed class ProvisionPoint { abstract val containerType: Type.Object abstract val dependency: Dependency abstract val bridge: Method? interface AbstractMethod { val injectionPoint: InjectionPoint.Method val method: MethodMirror get() = injectionPoint.method } data class Constructor( override val dependency: Dependency, override val injectionPoint: InjectionPoint.Method ) : ProvisionPoint(), AbstractMethod { override val containerType: Type.Object get() = injectionPoint.containerType override val bridge: Method? get() = null } data class Method( override val dependency: Dependency, override val injectionPoint: InjectionPoint.Method, override val bridge: Method? ) : ProvisionPoint(), AbstractMethod { override val containerType: Type.Object get() = injectionPoint.containerType } data class Field( override val containerType: Type.Object, override val dependency: Dependency, override val bridge: Method?, val field: FieldMirror ) : ProvisionPoint() data class Binding( override val containerType: Type.Object, override val dependency: Dependency, val binding: Dependency ) : ProvisionPoint() { override val bridge: Method? get() = null } }
apache-2.0
c8a6239a91da71411d1a49c210049f40
30.166667
80
0.745746
4.622472
false
false
false
false
eugeis/ee
ee-lang/src/main/kotlin/ee/lang/Expression.kt
1
4511
package ee.lang fun not(predicate: Predicate): NotPredicate = NotPredicate { value(predicate) } infix fun Predicate.and(predicate: Predicate): AndPredicate = AndPredicate { left(this).right(predicate) } infix fun Predicate.or(predicate: Predicate): OrPredicate = OrPredicate { left(this).right(predicate) } infix fun LiteralI<*>.eq(value: LiteralI<*>): EqPredicate = EqPredicate { left(this@eq).right(value) } infix fun LiteralI<*>.eq(value: String?): EqPredicate = eq(Literal { value(value).type(n.String) }) infix fun LiteralI<*>.eq(value: Long): EqPredicate = eq(Literal { value(value).type(n.Long) }) infix fun LiteralI<*>.eq(value: Boolean): EqPredicate = eq(Literal { value(value).type(n.Boolean) }) fun LiteralI<*>.yes(): EqPredicate = eq(true) infix fun LiteralI<*>.ne(value: LiteralI<*>): NePredicate = NePredicate { left(this@ne).right(value) } infix fun LiteralI<*>.ne(value: String?): NePredicate = ne(Literal { value(value).type(n.String) }) infix fun LiteralI<*>.ne(value: Long): NePredicate = ne(Literal { value(value).type(n.Long) }) infix fun LiteralI<*>.ne(value: Boolean): NePredicate = ne(Literal { value(value).type(n.Boolean) }) fun LiteralI<*>.no(): EqPredicate = eq(false) infix fun LiteralI<*>.lt(value: LiteralI<*>): LtPredicate = LtPredicate { left(this@lt).right(value) } infix fun LiteralI<*>.lt(value: String?): LtPredicate = lt(Literal { value(value).type(n.String) }) infix fun LiteralI<*>.lt(value: Long): LtPredicate = lt(Literal { value(value).type(n.Long) }) infix fun LiteralI<*>.lte(value: LiteralI<*>): LtePredicate = LtePredicate { left(this@lte).right(value) } infix fun LiteralI<*>.lte(value: String?): LtePredicate = lte(Literal { value(value).type(n.String) }) infix fun LiteralI<*>.lte(value: Long): LtePredicate = lte(Literal { value(value).type(n.Long) }) infix fun LiteralI<*>.gt(value: LiteralI<*>): GtPredicate = GtPredicate { left(this@gt).right(value) } infix fun LiteralI<*>.gt(value: String?): GtPredicate = gt(Literal { value(value).type(n.String) }) infix fun LiteralI<*>.gt(value: Long): GtPredicate = gt(Literal { value(value).type(n.Long) }) infix fun LiteralI<*>.gte(value: LiteralI<*>): GtePredicate = GtePredicate { left(this@gte).right(value) } infix fun LiteralI<*>.gte(value: String?): GtePredicate = gte(Literal { value(value).type(n.String) }) infix fun LiteralI<*>.gte(value: Long): GtePredicate = gte(Literal { value(value).type(n.Long) }) infix fun LiteralI<*>.compareTo(value: LiteralI<*>): GtePredicate = GtePredicate { left(this@compareTo).right(value) } operator fun LiteralI<*>.plus(value: LiteralI<*>): LiteralI<*> = PlusExpression { left(this@plus).right(value) } operator fun LiteralI<*>.plus(value: Long): LiteralI<*> = plus(Literal { value(value).type(n.Long) }) operator fun LiteralI<*>.plus(value: Int): LiteralI<*> = plus(Literal { value(value).type(n.Int) }) operator fun LiteralI<*>.plus(value: Float): LiteralI<*> = plus(Literal { value(value).type(n.Float) }) operator fun LiteralI<*>.minus(value: LiteralI<*>): LiteralI<*> = MinusExpression { left(this@minus).right(value) } operator fun LiteralI<*>.minus(value: Long): LiteralI<*> = minus(Literal { value(value).type(n.Long) }) operator fun LiteralI<*>.minus(value: Int): LiteralI<*> = minus(Literal { value(value).type(n.Int) }) operator fun LiteralI<*>.minus(value: Float): LiteralI<*> = minus(Literal { value(value).type(n.Float) }) operator fun LiteralI<*>.inc(): LiteralI<*> = IncrementExpression { value(this@inc) } operator fun LiteralI<*>.dec(): LiteralI<*> = DecrementExpression { value(this@dec) } operator fun LiteralI<*>.times(value: LiteralI<*>): LiteralI<*> = TimesExpression { left(this@times).right(value) } operator fun LiteralI<*>.times(value: Long): LiteralI<*> = times(Literal { value(value).type(n.Long) }) operator fun LiteralI<*>.times(value: Int): LiteralI<*> = times(Literal { value(value).type(n.Int) }) operator fun LiteralI<*>.times(value: Float): LiteralI<*> = times(Literal { value(value).type(n.Float) }) operator fun LiteralI<*>.div(value: LiteralI<*>): LiteralI<*> = DivideExpression { left(this@div).right(value) } operator fun LiteralI<*>.div(value: Long): LiteralI<*> = div(Literal { value(value).type(n.Long) }) operator fun LiteralI<*>.div(value: Int): LiteralI<*> = div(Literal { value(value).type(n.Int) }) operator fun LiteralI<*>.div(value: Float): LiteralI<*> = div(Literal { value(value).type(n.Float) }) fun AttributeI<*>.assign(value: LiteralI<*>): ActionI<*> = AssignAction { target(this@assign).value(value) }
apache-2.0
dc376546b9a8a5a115b1ca819640ddc7
74.183333
118
0.704943
3.368932
false
false
false
false
pronghorn-tech/server
src/main/kotlin/tech/pronghorn/util/finder/HashFinder.kt
2
1417
/* * Copyright 2017 Pronghorn Technology LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.pronghorn.util.finder import tech.pronghorn.plugins.arrayHash.ArrayHasherPlugin import java.nio.ByteBuffer import java.util.HashMap internal class HashFinder<T : ByteBacked>(private val toLookup: Array<T>) : ByteBackedFinder<T> { private val hashMap = HashMap<Long, T>() private val hasher = ArrayHasherPlugin.get() init { toLookup.forEach { value -> hashMap.put(hasher(value.bytes), value) } } override fun find(buffer: ByteBuffer, offset: Int, size: Int): T? { val bytes = ByteArray(size) val prePosition = buffer.position() buffer.position(offset) buffer.get(bytes) buffer.position(prePosition) return find(bytes) } override fun find(bytes: ByteArray): T? = hashMap[hasher(bytes)] }
apache-2.0
e2c91711f82489969fdced8beb0e34dc
31.953488
97
0.699365
4.083573
false
false
false
false
christophpickl/kpotpourri
common4k/src/test/kotlin/com/github/christophpickl/kpotpourri/common/collection/NeighboursTest.kt
1
1552
package com.github.christophpickl.kpotpourri.common.collection import com.github.christophpickl.kpotpourri.test4k.assertThrown import com.natpryce.hamkrest.Matcher import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.testng.annotations.Test @Test class NeighboursTest { private val pivot = "pivot" fun `Given list with only pivot When find neighbours Then return empty pair`() { val actual = listOf(pivot).neighboursFor(pivot) { this } assertThat(actual, emptyPair()) } fun `Given full list When find neighbours Then return neighbours`() { val actual = listOf("a", pivot, "c").neighboursFor(pivot) { this } assertThat(actual, pairOf("a", "c")) } fun `Given list with previous When find neighbours Then return neighbours`() { val actual = listOf("a", pivot).neighboursFor(pivot) { this } assertThat(actual, pairOf("a", null)) } fun `Given list with next When find neighbours Then return neighbours`() { val actual = listOf(pivot, "b").neighboursFor(pivot) { this } assertThat(actual, pairOf(null, "b")) } fun `Given list When find neighbours by invalid pivot Then throw`() { assertThrown<IllegalArgumentException> { listOf("a", "b").neighboursFor(pivot) { this } } } private fun <T> pairOf(first: T?, second: T?): Matcher<Pair<T?, T?>> = equalTo(Pair<T?, T?>(first, second)) private fun <T> emptyPair(): Matcher<Pair<T?, T?>> = pairOf(null, null) }
apache-2.0
543f0b9425fa3bb176c8996147a0a8b5
32.73913
111
0.668814
3.989717
false
true
false
false
emce/smog
app/src/main/java/mobi/cwiklinski/smog/ui/WidgetProvider.kt
1
6845
package mobi.cwiklinski.smog.ui import android.app.PendingIntent import android.appwidget.AppWidgetManager import android.appwidget.AppWidgetProvider import android.appwidget.AppWidgetProviderInfo import android.content.ComponentName import android.content.Context import android.content.Intent import android.os.Build import android.os.Bundle import android.widget.RemoteViews import mobi.cwiklinski.bloodline.ui.extension.IntentFor import mobi.cwiklinski.smog.R import mobi.cwiklinski.smog.config.Constants import mobi.cwiklinski.smog.database.AppContract import mobi.cwiklinski.smog.database.Reading import mobi.cwiklinski.smog.ui.activity.MainActivity import org.joda.time.DateTime import java.util.* class WidgetProvider : AppWidgetProvider() { companion object { public fun refreshWidgets(context: Context) { var remoteViews = RemoteViews(AppContract.AUTHORITY, R.layout.widget_layout); var widget = ComponentName(context, WidgetProvider::class.java) var manager = AppWidgetManager.getInstance(context) fillWidgetViews(context, remoteViews) manager.updateAppWidget(widget, remoteViews) } public fun fillWidgetViews(context: Context, remoteViews: RemoteViews) { var date = DateTime() var sortOrder = "${AppContract.Readings.YEAR} DESC, ${AppContract.Readings.MONTH} DESC,"+ " ${AppContract.Readings.DAY} DESC, ${AppContract.Readings.HOUR} DESC LIMIT 3" var selection = "${AppContract.Readings.YEAR}=? AND ${AppContract.Readings.MONTH}=? AND ${AppContract.Readings.DAY}=?" var selectionArgs = arrayOf(date.year().get().toString(), date.monthOfYear().get().toString(), date.dayOfMonth().get().toString()) var data = context.contentResolver.query(AppContract.Readings.CONTENT_URI, null, selection, selectionArgs, sortOrder) try { var records = ArrayList<Reading>() while (data.moveToNext()) { records.add(Reading.fromCursor(data)) } var sum = 0 records.forEach { when (it.place) { Constants.Place.KRASINSKIEGO.ordinal -> { remoteViews.setTextViewText(R.id.widgetTime0, "${it.hour}.00") remoteViews.setTextViewText(R.id.widgetValue0, context.getString(R.string.value_value).format(it.amount)) remoteViews.setTextColor(R.id.widgetValue0, context.resources.getColor(Constants.Color.getResource(it.amount))) sum += it.amount } Constants.Place.NOWA_HUTA.ordinal -> { remoteViews.setTextViewText(R.id.widgetTime1, "${it.hour}.00") remoteViews.setTextViewText(R.id.widgetValue1, context.getString(R.string.value_value).format(it.amount)) remoteViews.setTextColor(R.id.widgetValue1, context.resources.getColor(Constants.Color.getResource(it.amount))) sum += it.amount } Constants.Place.KURDWANOW.ordinal -> { remoteViews.setTextViewText(R.id.widgetTime2, "${it.hour}.00") remoteViews.setTextViewText(R.id.widgetValue2, context.getString(R.string.value_value).format(it.amount)) remoteViews.setTextColor(R.id.widgetValue2, context.resources.getColor(Constants.Color.getResource(it.amount))) sum += it.amount } } } when (sum / 3) { 0 -> remoteViews.setImageViewResource(R.id.widgetImage, R.drawable.ic_bus_yellow) in (1 .. 149) -> remoteViews.setImageViewResource(R.id.widgetImage, R.drawable.ic_bus_red) else -> remoteViews.setImageViewResource(R.id.widgetImage, R.drawable.ic_bus_green) } remoteViews.setOnClickPendingIntent(R.id.widgetRoot, getPendingIntent(context)) } finally { data!!.close() } var iceWidget = ComponentName(context, WidgetProvider::class.java) var manager = AppWidgetManager.getInstance(context) manager.updateAppWidget(iceWidget, remoteViews) } public fun getPendingIntent(context: Context): PendingIntent { var intent = IntentFor<MainActivity>(context) return PendingIntent.getActivity(context, 0, intent, 0) } } override fun onUpdate(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetIds: IntArray?) { super.onUpdate(context, appWidgetManager, appWidgetIds) appWidgetIds!!.forEach { drawWidget(context!!, it) } } override fun onAppWidgetOptionsChanged(context: Context?, appWidgetManager: AppWidgetManager?, appWidgetId: Int, newOptions: Bundle?) { super.onAppWidgetOptionsChanged(context, appWidgetManager, appWidgetId, newOptions) drawWidget(context!!, appWidgetId) } override fun onReceive(context: Context?, intent: Intent?) { super.onReceive(context, intent) redrawWidgets(context!!) } private fun drawWidget(context: Context, id: Int) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { checkWidgetTypeAndGetView(context, id); } else { var remoteViews = RemoteViews(context.packageName, R.layout.widget_layout) fillWidgetViews(context, remoteViews) } } private fun redrawWidgets(context: Context) { var appWidgetIds = AppWidgetManager.getInstance(context).getAppWidgetIds( ComponentName(context, WidgetProvider::class.java)); appWidgetIds!!.forEach { drawWidget(context, it) } } private fun checkWidgetTypeAndGetView(context: Context, id: Int) { var appWidgetManager = AppWidgetManager.getInstance(context) var widgetOptions = appWidgetManager.getAppWidgetOptions(id) var category = widgetOptions.getInt(AppWidgetManager.OPTION_APPWIDGET_HOST_CATEGORY, -1) var isKeyguard = category == AppWidgetProviderInfo.WIDGET_CATEGORY_KEYGUARD if (!isKeyguard) { var remoteViews = RemoteViews(context.packageName, R.layout.widget_layout) fillWidgetViews(context, remoteViews) } } }
apache-2.0
30b13f4d23bb18e1c453d57772000a2f
46.874126
142
0.612856
4.938672
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/blocks/BlockMultiblock.kt
2
8190
package com.cout970.magneticraft.systems.blocks import com.cout970.magneticraft.AABB import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.t import com.cout970.magneticraft.misc.tileentity.getModule import com.cout970.magneticraft.misc.tileentity.getTile import com.cout970.magneticraft.misc.vector.* import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.systems.multiblocks.IMultiblockCenter import com.cout970.magneticraft.systems.multiblocks.IMultiblockModule import com.cout970.magneticraft.systems.multiblocks.MultiblockContext import com.cout970.magneticraft.systems.multiblocks.MultiblockManager import com.cout970.magneticraft.systems.tileentities.TileBase import net.minecraft.block.material.Material import net.minecraft.block.state.IBlockState import net.minecraft.client.Minecraft import net.minecraft.client.util.ITooltipFlag import net.minecraft.entity.Entity import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumBlockRenderType 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.util.math.Vec3d import net.minecraft.world.World import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks /** * Created by cout970 on 2017/07/03. */ class BlockMultiblock( factory: (World, IBlockState) -> TileEntity?, filter: ((IBlockState) -> Boolean)?, material: Material ) : BlockTileBase(factory, filter, material) { companion object { fun getBoxes(world: World, pos: BlockPos, module: IMultiblockModule): List<AABB> { val multiblock = module.multiblock ?: return emptyList() val facing = module.multiblockFacing ?: return emptyList() val center = module.centerPos ?: return emptyList() val main = world.getModule<IMultiblockCenter>(pos - center) val extra = main?.getDynamicCollisionBoxes(pos) ?: emptyList() return (multiblock.getGlobalCollisionBoxes() + extra).map { val origin = EnumFacing.SOUTH.rotateBox(vec3Of(0.5), it) facing.rotateBox(vec3Of(0.5), origin) } } fun getBoxesInBlock(world: World, pos: BlockPos, module: IMultiblockModule): List<AABB> { val center = module.centerPos ?: return emptyList() val boxes = getBoxes(world, pos, module) val thisBox = FULL_BLOCK_AABB + center return boxes.mapNotNull { it.cut(thisBox) } } fun getRelativeBoxesInBlock(world: World, pos: BlockPos, module: IMultiblockModule): List<AABB> { val relPos = module.centerPos?.unaryMinus() ?: return emptyList() return getBoxesInBlock(world, pos, module).map { it.offset(relPos) } } } @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun addCollisionBoxToList(state: IBlockState, worldIn: World, pos: BlockPos, entityBox: AxisAlignedBB, collidingBoxes: MutableList<AxisAlignedBB>, entityIn: Entity?, p_185477_7_: Boolean) { val active = state[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.active ?: true if (active) { val tile = worldIn.getTile<TileBase>(pos) val module = tile?.container?.modules?.find { it is IMultiblockModule } as? IMultiblockModule if (module?.multiblock != null) { val boxes = getRelativeBoxesInBlock(worldIn, pos, module).map { it.offset(pos) } boxes.filterTo(collidingBoxes) { entityBox.intersects(it) } return } } super.addCollisionBoxToList(state, worldIn, pos, entityBox, collidingBoxes, entityIn, p_185477_7_) } @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun getSelectedBoundingBox(state: IBlockState, worldIn: World, pos: BlockPos): AxisAlignedBB { val active = state[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.active ?: true if (active) { val tile = worldIn.getTile<TileBase>(pos) val module = tile?.container?.modules?.find { it is IMultiblockModule } as? IMultiblockModule if (module?.multiblock != null) { val player = Minecraft.getMinecraft().player val start = player.getPositionEyes(0f) val look = player.getLook(0f) val blockReachDistance = Minecraft.getMinecraft().playerController!!.blockReachDistance val end = start.addVector( look.x * blockReachDistance, look.y * blockReachDistance, look.z * blockReachDistance ) val res = getRelativeBoxesInBlock(worldIn, pos, module) .associate { it to rayTrace(pos, start, end, it) } .filter { it.value != null } .map { it.key to it.value } .sortedBy { it.second!!.hitVec.distanceTo(start) } .firstOrNull()?.first return res?.offset(pos) ?: EMPTY_AABB } } return super.getSelectedBoundingBox(state, worldIn, pos) } @Suppress("OverridingDeprecatedMember") override fun collisionRayTrace(blockState: IBlockState, worldIn: World, pos: BlockPos, start: Vec3d, end: Vec3d): RayTraceResult? { val active = blockState[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.active ?: true if (active) { val tile = worldIn.getTile<TileBase>(pos) val module = tile?.container?.modules?.find { it is IMultiblockModule } as? IMultiblockModule if (module?.multiblock != null) { return getRelativeBoxesInBlock(worldIn, pos, module) .associate { it to rayTrace(pos, start, end, it) } .filter { it.value != null } .map { it.key to it.value } .sortedBy { it.second!!.hitVec.distanceTo(start) } .firstOrNull()?.second } } return this.rayTrace(pos, start, end, blockState.getBoundingBox(worldIn, pos)) } //removedByPlayer @Suppress("OverridingDeprecatedMember", "DEPRECATION") override fun getRenderType(state: IBlockState): EnumBlockRenderType { val active = state[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.active ?: true return if (active) EnumBlockRenderType.INVISIBLE else super.getRenderType(state) } override fun breakBlock(worldIn: World, pos: BlockPos, state: IBlockState) { if (worldIn.isServer) { val active = state[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.active ?: true if (active) { val tile = worldIn.getTile<TileBase>(pos) val module = tile?.container?.modules?.find { it is IMultiblockModule } as? IMultiblockModule if (module?.multiblock != null) { val facing = state[Multiblocks.PROPERTY_MULTIBLOCK_ORIENTATION]?.facing ?: module.multiblockFacing if (module.multiblock != null && facing != null) { MultiblockManager.deactivateMultiblockStructure( MultiblockContext( multiblock = module.multiblock!!, world = worldIn, center = pos.subtract(module.centerPos!!), facing = facing, player = null ) ) } } } } super.breakBlock(worldIn, pos, state) } override fun addInformation(stack: ItemStack, player: World?, tooltip: MutableList<String>, advanced: ITooltipFlag) { tooltip.add(t("tooltip.magneticraft.multiblock.blueprint")) super.addInformation(stack, player, tooltip, advanced) } }
gpl-2.0
c06977fdbac9b611b9949360bed07d04
45.016854
121
0.630281
4.640227
false
false
false
false
toastkidjp/Jitte
image/src/main/java/jp/toastkid/image/list/ImageLoaderUseCase.kt
1
1610
/* * 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.image.list import androidx.annotation.VisibleForTesting import jp.toastkid.lib.preference.PreferenceApplier /** * @author toastkidjp */ internal class ImageLoaderUseCase( private val preferenceApplier: PreferenceApplier, private val adapter: Adapter?, private val bucketLoader: BucketLoader, private val imageLoader: ImageLoader, private val refreshContent: () -> Unit, @VisibleForTesting private val parentExtractor: ParentExtractor = ParentExtractor() ) { private var currentBucket: String? = null operator fun invoke() { invoke(currentBucket) } operator fun invoke(bucket: String?) { adapter?.clear() val excludedItemFilter = ExcludingItemFilter(preferenceApplier.excludedItems()) val sort = Sort.findByName(preferenceApplier.imageViewerSort()) if (bucket.isNullOrBlank()) { bucketLoader(sort) .filter { excludedItemFilter(parentExtractor(it.path)) } } else { imageLoader(sort, bucket).filter { excludedItemFilter(it.path) } } .forEach { adapter?.add(it) } currentBucket = bucket refreshContent() } fun clearCurrentBucket() { currentBucket = null } }
epl-1.0
6cfb70a580c92019fe230c99dbb23a61
29.396226
91
0.675776
4.834835
false
false
false
false
camsteffen/polite
src/main/java/me/camsteffen/polite/rule/edit/EditScheduleRuleFragment.kt
1
3772
package me.camsteffen.polite.rule.edit import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.core.os.ConfigurationCompat.getLocales import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProviders import me.camsteffen.polite.R import me.camsteffen.polite.databinding.DayButtonBinding import me.camsteffen.polite.databinding.EditScheduleRuleBinding import me.camsteffen.polite.model.ScheduleRule import me.camsteffen.polite.rule.ScheduleRuleSchedule import me.camsteffen.polite.util.TimePickerDialogFragment import org.threeten.bp.LocalTime import org.threeten.bp.format.TextStyle import org.threeten.bp.temporal.WeekFields class EditScheduleRuleFragment : EditRuleFragment<ScheduleRule>(), TimePickerDialogFragment.OnTimeSetListener { private lateinit var model: EditScheduleRuleViewModel override fun onCreateEditRuleViewModel(): EditScheduleRuleViewModel { model = ViewModelProviders .of(activity!!, viewModelProviderFactory)[EditScheduleRuleViewModel::class.java] return model } override fun onCreateEditRuleView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = DataBindingUtil.inflate<EditScheduleRuleBinding>( layoutInflater, R.layout.edit_schedule_rule, container, false ) binding.lifecycleOwner = this binding.handlers = this binding.model = model inflateDays(binding.days) return binding.root } private fun inflateDays(parent: ViewGroup) { val locale = getLocales(resources.configuration)[0] val firstDay = WeekFields.of(locale).firstDayOfWeek for (i in 0..6L) { val day = firstDay + i val binding = DataBindingUtil .inflate<DayButtonBinding>(layoutInflater, R.layout.day_button, parent, true) binding.text = day.getDisplayName(TextStyle.NARROW, locale) binding.checked = model.daysOfWeek[day] if (i < 6) { layoutInflater.inflate(R.layout.day_button_space, parent, true) } } } override fun ruleFromUi(id: Long, name: String, enabled: Boolean, vibrate: Boolean): ScheduleRule { val days = model.daysOfWeek.asSequence() .filter { it.value.get() } .map { it.key } .toSet() val schedule = ScheduleRuleSchedule(model.beginTime.get()!!, model.endTime.get()!!, days) return ScheduleRule(id, name, enabled, vibrate, schedule) } fun onClickBeginTime() { showTimePicker(TimePickerCodes.BEGIN, model.beginTime.get()!!) } fun onClickEndTime() { showTimePicker(TimePickerCodes.END, model.endTime.get()!!) } private fun showTimePicker(code: Int, localTime: LocalTime) { TimePickerDialogFragment.newInstance(this, code, localTime) .show(fragmentManager!!, TimePickerDialogFragment.FRAGMENT_TAG) } override fun validateSaveClose() { if (model.daysOfWeek.isEmpty()) { Toast.makeText(activity, R.string.no_days_selected, Toast.LENGTH_SHORT).show() } else { saveClose() } } override fun onTimeSet(hourOfDay: Int, minute: Int, requestCode: Int) { val timeOfDay = when (requestCode) { TimePickerCodes.BEGIN -> model.beginTime TimePickerCodes.END -> model.endTime else -> throw IllegalArgumentException() } timeOfDay.set(LocalTime.of(hourOfDay, minute)) } } private object TimePickerCodes { const val BEGIN = 0 const val END = 1 }
mpl-2.0
33aa2a5615a43173075d978357c7c10d
34.584906
97
0.684517
4.715
false
false
false
false
lapism/SearchView
src/main/kotlin/com/lapism/search/internal/FocusEditText.kt
1
1237
package com.lapism.search.internal import android.content.Context import android.util.AttributeSet import android.view.KeyEvent import androidx.appcompat.widget.AppCompatEditText class FocusEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatEditText(context, attrs, defStyleAttr) { // ********************************************************************************************* private var textClear: Boolean = false // ********************************************************************************************* override fun onKeyPreIme(keyCode: Int, event: KeyEvent?): Boolean { if (keyCode == KeyEvent.KEYCODE_BACK && event?.action == KeyEvent.ACTION_UP && textClear) { if (hasFocus()) { clearFocus() return true } } return super.onKeyPreIme(keyCode, event) } override fun clearFocus() { super.clearFocus() text?.clear() // TODO FIX } // ********************************************************************************************* fun setTextClearOnBackPressed(clear: Boolean) { textClear = clear } }
apache-2.0
b4665eebbb5df01318a199346988f05c
30.74359
100
0.490703
5.753488
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
example/src/androidTest/java/org/wordpress/android/fluxc/mocked/MockedStack_WCBaseStoreTest.kt
1
16216
package org.wordpress.android.fluxc.mocked import com.yarolegovich.wellsql.WellSql import org.greenrobot.eventbus.Subscribe import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.TestUtils import org.wordpress.android.fluxc.annotations.action.Action import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.WCSettingsModel import org.wordpress.android.fluxc.model.WCSettingsModel.CurrencyPosition import org.wordpress.android.fluxc.module.ResponseMockingInterceptor import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooCommerceRestClient import org.wordpress.android.fluxc.persistence.WCSettingsSqlUtils import org.wordpress.android.fluxc.persistence.WCSettingsSqlUtils.WCSettingsBuilder import org.wordpress.android.fluxc.store.WooCommerceStore import org.wordpress.android.fluxc.utils.WCCurrencyUtils import java.util.Locale import java.util.concurrent.CountDownLatch import javax.inject.Inject import kotlin.properties.Delegates.notNull /** * Tests using a Mocked Network app component. Test the network client itself and not the underlying * network component(s). */ class MockedStack_WCBaseStoreTest : MockedStack_Base() { @Inject internal lateinit var wcRestClient: WooCommerceRestClient @Inject internal lateinit var wooCommerceStore: WooCommerceStore @Inject internal lateinit var dispatcher: Dispatcher @Inject internal lateinit var interceptor: ResponseMockingInterceptor private var lastAction: Action<*>? = null private var countDownLatch: CountDownLatch by notNull() private val siteModel = SiteModel().apply { id = 5 siteId = 567 } @Throws(Exception::class) override fun setUp() { super.setUp() mMockedNetworkAppComponent.inject(this) dispatcher.register(this) lastAction = null } // This is a connected test instead of a unit test because some of the internals of java.util.Currency seem to be // stubbed in a unit test environment, giving results inconsistent with a normal running app @Test fun testGetLocalizedCurrencySymbolForCode() { Locale("en", "US").let { localeEnUS -> assertEquals("$", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("USD", localeEnUS)) assertEquals("CA$", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("CAD", localeEnUS)) assertEquals("€", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("EUR", localeEnUS)) assertEquals("¥", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("JPY", localeEnUS)) } Locale("en", "CA").let { localeEnCA -> assertEquals("US$", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("USD", localeEnCA)) assertEquals("$", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("CAD", localeEnCA)) assertEquals("€", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("EUR", localeEnCA)) assertEquals("JP¥", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("JPY", localeEnCA)) } Locale("fr", "FR").let { localeFrFR -> assertEquals("\$US", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("USD", localeFrFR)) assertEquals("\$CA", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("CAD", localeFrFR)) assertEquals("€", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("EUR", localeFrFR)) assertEquals("JPY", WCCurrencyUtils.getLocalizedCurrencySymbolForCode("JPY", localeFrFR)) } } @Test fun testGetSiteCurrency() { // Override device locale and use en_US so currency symbols can be predicted TestUtils.updateLocale(mAppContext, Locale("en", "US")) // -- Site using CAD val cadSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "CAD", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = ",", currencyDecimalSeparator = ".", currencyDecimalNumber = 2, couponsEnabled = true) WCSettingsSqlUtils.insertOrUpdateSettings(cadSettings) with(wooCommerceStore) { val formattedCurrencySymbol = getSiteCurrency(siteModel, "CAD") assertEquals("CA$", formattedCurrencySymbol) val formattedCurrencyUseSiteCurrency = getSiteCurrency(siteModel, null) assertEquals("CA$", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = getSiteCurrency(siteModel, "EUR") assertEquals("€", formattedCurrencyDifferentCurrency) val formattedCurrencyEmptyCodeUseSite = getSiteCurrency(siteModel, "") assertEquals("CA$", formattedCurrencyEmptyCodeUseSite) } // -- Site using EUR val eurSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "EUR", currencyPosition = CurrencyPosition.RIGHT_SPACE, currencyThousandSeparator = ".", currencyDecimalSeparator = ",", currencyDecimalNumber = 2, couponsEnabled = true) WCSettingsSqlUtils.insertOrUpdateSettings(eurSettings) with(wooCommerceStore) { val formattedCurrencyDouble = getSiteCurrency(siteModel, "EUR") assertEquals("€", formattedCurrencyDouble) val formattedCurrencyUseSiteCurrency = getSiteCurrency(siteModel, null) assertEquals("€", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = getSiteCurrency(siteModel, "USD") assertEquals("$", formattedCurrencyDifferentCurrency) } // -- Site using JPY val jpySettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "JPY", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = "", currencyDecimalSeparator = "", currencyDecimalNumber = 0, couponsEnabled = true) WCSettingsSqlUtils.insertOrUpdateSettings(jpySettings) with(wooCommerceStore) { val formattedCurrencyDouble = getSiteCurrency(siteModel, "JPY") assertEquals("¥", formattedCurrencyDouble) val formattedCurrencyUseSiteCurrency = getSiteCurrency(siteModel, null) assertEquals("¥", formattedCurrencyUseSiteCurrency) } // -- No site settings stored WellSql.delete(WCSettingsBuilder::class.java).execute() with(wooCommerceStore) { val formattedCurrencyDouble = getSiteCurrency(siteModel, "CAD") assertEquals("CA$", formattedCurrencyDouble) val formattedCurrencyUseSiteCurrency = getSiteCurrency(siteModel, null) assertEquals("", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = getSiteCurrency(siteModel, "INR") assertEquals("₹", formattedCurrencyDifferentCurrency) } } @Test fun testFormatCurrencyForDisplay() { // Override device locale and use en_US so currency symbols can be predicted TestUtils.updateLocale(mAppContext, Locale("en", "US")) // -- Site using CAD val cadSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "CAD", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = ",", currencyDecimalSeparator = ".", currencyDecimalNumber = 2, couponsEnabled = true) WCSettingsSqlUtils.insertOrUpdateSettings(cadSettings) with(wooCommerceStore) { val formattedCurrencyDouble = formatCurrencyForDisplay(1234.12, siteModel, "CAD", true) assertEquals("CA$1,234.12", formattedCurrencyDouble) val formattedCurrencyString = formatCurrencyForDisplay("1234.12", siteModel, "CAD", true) assertEquals("CA$1,234.12", formattedCurrencyString) val formattedCurrencyPretty = formatCurrencyForDisplay("1.2k", siteModel, "CAD", false) assertEquals("CA$1.2k", formattedCurrencyPretty) val formattedCurrencyNegative = formatCurrencyForDisplay(-1234.12, siteModel, "CAD", true) assertEquals("-CA$1,234.12", formattedCurrencyNegative) val formattedCurrencyUseSiteCurrency = formatCurrencyForDisplay(1234.12, siteModel, null, true) assertEquals("CA$1,234.12", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = formatCurrencyForDisplay(1234.12, siteModel, "EUR", true) assertEquals("€1,234.12", formattedCurrencyDifferentCurrency) val formattedCurrencyEmptyCodeUseSite = formatCurrencyForDisplay(1234.12, siteModel, "", true) assertEquals("CA$1,234.12", formattedCurrencyUseSiteCurrency) } // -- Site using EUR val eurSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "EUR", currencyPosition = CurrencyPosition.RIGHT_SPACE, currencyThousandSeparator = ".", currencyDecimalSeparator = ",", currencyDecimalNumber = 2, couponsEnabled = true) WCSettingsSqlUtils.insertOrUpdateSettings(eurSettings) with(wooCommerceStore) { val formattedCurrencyDouble = formatCurrencyForDisplay(1234.12, siteModel, "EUR", true) assertEquals("1.234,12 €", formattedCurrencyDouble) val formattedCurrencyString = formatCurrencyForDisplay("1234.12", siteModel, "EUR", true) assertEquals("1.234,12 €", formattedCurrencyString) val formattedCurrencyPretty = formatCurrencyForDisplay("1.2k", siteModel, "EUR", false) assertEquals("1.2k €", formattedCurrencyPretty) val formattedCurrencyNegative = formatCurrencyForDisplay(-1234.12, siteModel, "EUR", true) assertEquals("-1.234,12 €", formattedCurrencyNegative) val formattedCurrencyUseSiteCurrency = formatCurrencyForDisplay(1234.12, siteModel, null, true) assertEquals("1.234,12 €", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = formatCurrencyForDisplay(1234.12, siteModel, "USD", true) assertEquals("1.234,12 \$", formattedCurrencyDifferentCurrency) } // -- Site using JPY val jpySettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "JPY", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = "", currencyDecimalSeparator = "", currencyDecimalNumber = 0, couponsEnabled = true) WCSettingsSqlUtils.insertOrUpdateSettings(jpySettings) with(wooCommerceStore) { val formattedCurrencyDouble = formatCurrencyForDisplay(1234.0, siteModel, "JPY", true) assertEquals("¥1234", formattedCurrencyDouble) val formattedCurrencyString = formatCurrencyForDisplay("1234", siteModel, "JPY", true) assertEquals("¥1234", formattedCurrencyString) val formattedCurrencyPretty = formatCurrencyForDisplay("1.2k", siteModel, "JPY", false) assertEquals("¥1.2k", formattedCurrencyPretty) val formattedCurrencyNegative = formatCurrencyForDisplay(-1234.12, siteModel, "JPY", true) assertEquals("-¥1234", formattedCurrencyNegative) val formattedCurrencyUseSiteCurrency = formatCurrencyForDisplay(1234.0, siteModel, null, true) assertEquals("¥1234", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = formatCurrencyForDisplay(1234.0, siteModel, "USD", true) assertEquals("$1234", formattedCurrencyDifferentCurrency) } // -- No site settings stored WellSql.delete(WCSettingsBuilder::class.java).execute() with(wooCommerceStore) { val formattedCurrencyDouble = formatCurrencyForDisplay(1234.12, siteModel, "CAD", true) assertEquals("CA$1234.12", formattedCurrencyDouble) val formattedCurrencyString = formatCurrencyForDisplay("1234.12", siteModel, "CAD", true) assertEquals("CA$1234.12", formattedCurrencyString) val formattedCurrencyPretty = formatCurrencyForDisplay("1.2k", siteModel, "CAD", false) assertEquals("CA$1.2k", formattedCurrencyPretty) val formattedCurrencyNegative = formatCurrencyForDisplay(-1234.12, siteModel, "CAD", true) assertEquals("-CA$1234.12", formattedCurrencyNegative) val formattedCurrencyUseSiteCurrency = formatCurrencyForDisplay(1234.12, siteModel, null, true) assertEquals("1234.12", formattedCurrencyUseSiteCurrency) val formattedCurrencyDifferentCurrency = formatCurrencyForDisplay(1234.12, siteModel, "EUR", true) assertEquals("€1234.12", formattedCurrencyDifferentCurrency) } } @Test fun testGetStoreCountryBySite() { // -- Site using CAD val cadSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "CAD", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = ",", currencyDecimalSeparator = ".", currencyDecimalNumber = 2, countryCode = "CA:QC", couponsEnabled = true ) WCSettingsSqlUtils.insertOrUpdateSettings(cadSettings) with(wooCommerceStore) { assertEquals("CA:QC", getStoreCountryCode(siteModel)) } // -- No site settings stored WellSql.delete(WCSettingsBuilder::class.java).execute() with(wooCommerceStore) { assertNull(getStoreCountryCode(siteModel)) } // -- no country code in settings val siteSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "CAD", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = ",", currencyDecimalSeparator = ".", currencyDecimalNumber = 2, couponsEnabled = true ) WCSettingsSqlUtils.insertOrUpdateSettings(siteSettings) with(wooCommerceStore) { assertEquals("", getStoreCountryCode(siteModel)) } // -- Site without city i.e. "US" val usSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "CAD", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = ",", currencyDecimalSeparator = ".", currencyDecimalNumber = 2, countryCode = "US", couponsEnabled = true ) WCSettingsSqlUtils.insertOrUpdateSettings(usSettings) with(wooCommerceStore) { assertEquals("US", getStoreCountryCode(siteModel)) } // -- Site using IND val indSettings = WCSettingsModel( localSiteId = siteModel.id, currencyCode = "CAD", currencyPosition = CurrencyPosition.LEFT, currencyThousandSeparator = ",", currencyDecimalSeparator = ".", currencyDecimalNumber = 2, countryCode = "IN:TN", couponsEnabled = true ) WCSettingsSqlUtils.insertOrUpdateSettings(indSettings) with(wooCommerceStore) { assertEquals("IN:TN", getStoreCountryCode(siteModel)) } } @Suppress("unused") @Subscribe fun onAction(action: Action<*>) { lastAction = action countDownLatch.countDown() } }
gpl-2.0
db0dabc36c2fba10aa93d92de27ae9c7
42.609164
117
0.657025
5.299378
false
false
false
false
SergeyLukashevich/elektrum-lv-unofficial-api
cli/src/main/kotlin/command/CmdExportInfluxDb.kt
1
3326
package command import com.github.rvesse.airline.annotations.Command import com.github.rvesse.airline.annotations.Option import com.github.rvesse.airline.annotations.OptionType import com.github.rvesse.airline.annotations.help.Examples import com.github.rvesse.airline.annotations.restrictions.MutuallyExclusiveWith import command.base.CmdCommonOptions import command.base.CommandRunnable import org.influxdb.InfluxDB import org.influxdb.InfluxDB.ConsistencyLevel import org.influxdb.InfluxDBFactory import org.influxdb.dto.BatchPoints import org.influxdb.dto.Point import org.influxdb.dto.Query import org.slf4j.Logger import org.slf4j.LoggerFactory import settings.Settings import java.time.LocalDateTime import java.time.Month import java.time.ZoneOffset import java.time.format.DateTimeFormatter import java.util.concurrent.TimeUnit @Command(name = "influxdb", description = "Export into InfluxDB") @Examples(examples = arrayOf("influxdb --period day --debug 2017-07-01 2017-08-01", "influxdb --period day --recent")) class CmdExportInfluxDb: CmdCommonOptions(), CommandRunnable { @Option(type = OptionType.COMMAND, name = arrayOf("-r", "--recent"), description = "Get recent data") @MutuallyExclusiveWith(tag = "dates") private val recent: Boolean = false private val log: Logger = LoggerFactory.getLogger(this::class.java.canonicalName) lateinit private var db: InfluxDB lateinit private var dbName: String override fun run(settings: Settings.Data) { settings.influxdb.apply { db = InfluxDBFactory.connect(url, login, password.plain) dbName = database } db.createDatabase(dbName) db.setDatabase(dbName) if (recent) { val query = Query("SELECT LAST(value) FROM $periodStr", dbName) val result = db.query(query) val fromStr = result.results[0]?.series?.get(0)?.values?.get(0)?.get(0)?.toString() val from: LocalDateTime = if (fromStr != null) { LocalDateTime.parse(fromStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")) } else { log.warn("Incremental mode is on, but table '$periodStr' is empty. " + "Since we cannot find the start point, importing all from 1 Jan 2016.") LocalDateTime.of(2016, Month.JANUARY, 1, 0, 0) } export(fetch(settings, from.toLocalDate())) } else { export(fetch(settings)) } } private fun export(meters: Map<LocalDateTime, Double?>) { if (meters.isEmpty()) { log.info("No data to write") return } val batch = BatchPoints.database(dbName) .consistency(ConsistencyLevel.ALL) .build() meters.filter { it.value != null } .forEach { date, amount -> batch.point( Point.measurement(periodStr) .time(date.toEpochSecond(ZoneOffset.UTC), TimeUnit.SECONDS) .addField("value", amount) .build()) } val count = batch.points.count() db.write(batch) log.info("$count points have been written") } }
apache-2.0
86886317bd38a8f9ce7a163332b2bbab
36.370787
105
0.637703
4.141968
false
false
false
false
jhunovis/umlaut-search-intellij-plugin
src/main/kotlin/jhunovis/umlauts/TransliteratingNavigationContributor.kt
1
3225
/* * Copyright 2016 Jan Hackel * * 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 jhunovis.umlauts import com.intellij.ide.util.gotoByName.DefaultClassNavigationContributor import com.intellij.ide.util.gotoByName.DefaultFileNavigationContributor import com.intellij.ide.util.gotoByName.DefaultSymbolNavigationContributor import com.intellij.navigation.ChooseByNameContributorEx import com.intellij.navigation.NavigationItem import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.Processor import com.intellij.util.indexing.FindSymbolParameters import com.intellij.util.indexing.IdFilter /** * Search for variations of the class name patterned entered by the IDEA user by mapping German native characters to * their ASCII-transliteration and vice versa. * * @author <a href="mailto:[email protected]">Jan Hackel</a> */ open class TransliteratingNavigationContributor constructor(val delegate: ChooseByNameContributorEx) : ChooseByNameContributorEx by delegate { private val germanTransliteration = GermanTransliteration() final override fun processNames(processor: Processor<String>, scope: GlobalSearchScope, filter: IdFilter?) { delegate.processNames({ name -> val transliterated = transliterate(name) if (name != transliterated) { processor.process(name) processor.process(transliterated) } true }, scope, filter) } final override fun processElementsWithName(name: String, processor: Processor<NavigationItem>, parameters: FindSymbolParameters) { val completePattern = parameters.completePattern val transliteratedPattern = transliterate(completePattern) if (transliteratedPattern != completePattern) { val transliteratedName = transliterate(name) delegate.processElementsWithName( transliteratedName, processor, newParametersWith(parameters, transliteratedPattern, transliteratedName) ) } } private fun newParametersWith(parameters: FindSymbolParameters, pattern: String, name: String) = FindSymbolParameters(pattern, name, parameters.searchScope, parameters.idFilter) private fun transliterate(symbol: String) = germanTransliteration.transliterate(symbol) } class TransliteratingClassNavigationContributor : TransliteratingNavigationContributor(DefaultClassNavigationContributor()) class TransliteratingFileNavigationContributor : TransliteratingNavigationContributor(DefaultFileNavigationContributor()) class TransliteratingSymbolNavigationContributor : TransliteratingNavigationContributor(DefaultSymbolNavigationContributor())
apache-2.0
d2e2a91d03ec7493fce1a0d2b3bc86d3
45.085714
134
0.768372
4.673913
false
false
false
false
dushmis/dagger
java/dagger/hilt/android/plugin/src/main/kotlin/dagger/hilt/android/plugin/root/Aggregator.kt
1
15472
/* * Copyright (C) 2021 The Dagger 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 dagger.hilt.android.plugin.task import com.squareup.javapoet.ClassName import dagger.hilt.android.plugin.root.AggregatedAnnotation import dagger.hilt.android.plugin.util.forEachZipEntry import dagger.hilt.android.plugin.util.isClassFile import dagger.hilt.android.plugin.util.isJarFile import dagger.hilt.processor.internal.root.ir.AggregatedDepsIr import dagger.hilt.processor.internal.root.ir.AggregatedEarlyEntryPointIr import dagger.hilt.processor.internal.root.ir.AggregatedElementProxyIr import dagger.hilt.processor.internal.root.ir.AggregatedRootIr import dagger.hilt.processor.internal.root.ir.AggregatedUninstallModulesIr import dagger.hilt.processor.internal.root.ir.AliasOfPropagatedDataIr import dagger.hilt.processor.internal.root.ir.DefineComponentClassesIr import dagger.hilt.processor.internal.root.ir.ProcessedRootSentinelIr import java.io.File import java.io.InputStream import java.util.zip.ZipInputStream import org.objectweb.asm.AnnotationVisitor import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.Opcodes import org.objectweb.asm.Type import org.slf4j.Logger /** Aggregates Hilt dependencies. */ internal class Aggregator private constructor( private val logger: Logger, private val asmApiVersion: Int, ) { private val classVisitor = AggregatedDepClassVisitor(logger, asmApiVersion) val aggregatedRoots: Set<AggregatedRootIr> get() = classVisitor.aggregatedRoots val processedRoots: Set<ProcessedRootSentinelIr> get() = classVisitor.processedRoots val defineComponentDeps: Set<DefineComponentClassesIr> get() = classVisitor.defineComponentDeps val aliasOfDeps: Set<AliasOfPropagatedDataIr> get() = classVisitor.aliasOfDeps val aggregatedDeps: Set<AggregatedDepsIr> get() = classVisitor.aggregatedDeps val aggregatedDepProxies: Set<AggregatedElementProxyIr> get() = classVisitor.aggregatedDepProxies val allAggregatedDepProxies: Set<AggregatedElementProxyIr> get() = classVisitor.allAggregatedDepProxies val uninstallModulesDeps: Set<AggregatedUninstallModulesIr> get() = classVisitor.uninstallModulesDeps val earlyEntryPointDeps: Set<AggregatedEarlyEntryPointIr> get() = classVisitor.earlyEntryPointDeps private class AggregatedDepClassVisitor( private val logger: Logger, private val asmApiVersion: Int, ) : ClassVisitor(asmApiVersion) { val aggregatedRoots = mutableSetOf<AggregatedRootIr>() val processedRoots = mutableSetOf<ProcessedRootSentinelIr>() val defineComponentDeps = mutableSetOf<DefineComponentClassesIr>() val aliasOfDeps = mutableSetOf<AliasOfPropagatedDataIr>() val aggregatedDeps = mutableSetOf<AggregatedDepsIr>() val aggregatedDepProxies = mutableSetOf<AggregatedElementProxyIr>() val allAggregatedDepProxies = mutableSetOf<AggregatedElementProxyIr>() val uninstallModulesDeps = mutableSetOf<AggregatedUninstallModulesIr>() val earlyEntryPointDeps = mutableSetOf<AggregatedEarlyEntryPointIr>() var accessCode: Int = Opcodes.ACC_PUBLIC lateinit var annotatedClassName: ClassName override fun visit( version: Int, access: Int, name: String, signature: String?, superName: String?, interfaces: Array<out String>? ) { accessCode = access annotatedClassName = Type.getObjectType(name).toClassName() super.visit(version, access, name, signature, superName, interfaces) } override fun visitAnnotation(descriptor: String, visible: Boolean): AnnotationVisitor? { val nextAnnotationVisitor = super.visitAnnotation(descriptor, visible) val aggregatedAnnotation = AggregatedAnnotation.fromString(descriptor) val isHiltAnnotated = aggregatedAnnotation != AggregatedAnnotation.NONE // For non-public deps, a proxy might be needed, make a note of it. if (isHiltAnnotated && (accessCode and Opcodes.ACC_PUBLIC) != Opcodes.ACC_PUBLIC) { allAggregatedDepProxies.add( AggregatedElementProxyIr( fqName = annotatedClassName.peerClass("_" + annotatedClassName.simpleName()), value = annotatedClassName ) ) } when (aggregatedAnnotation) { AggregatedAnnotation.AGGREGATED_ROOT -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { lateinit var rootClass: String lateinit var originatingRootClass: String lateinit var rootAnnotationClassName: Type override fun visit(name: String, value: Any?) { when (name) { "root" -> rootClass = value as String "originatingRoot" -> originatingRootClass = value as String "rootAnnotation" -> rootAnnotationClassName = (value as Type) } super.visit(name, value) } override fun visitEnd() { aggregatedRoots.add( AggregatedRootIr( fqName = annotatedClassName, root = rootClass.toClassName(), originatingRoot = originatingRootClass.toClassName(), rootAnnotation = rootAnnotationClassName.toClassName() ) ) super.visitEnd() } } } AggregatedAnnotation.PROCESSED_ROOT_SENTINEL -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { val rootClasses = mutableListOf<String>() override fun visitArray(name: String): AnnotationVisitor? { return when (name) { "roots" -> visitValue { value -> rootClasses.add(value as String) } else -> super.visitArray(name) } } override fun visitEnd() { processedRoots.add( ProcessedRootSentinelIr( fqName = annotatedClassName, roots = rootClasses.map { it.toClassName() } ) ) super.visitEnd() } } } AggregatedAnnotation.DEFINE_COMPONENT -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { lateinit var componentClass: String override fun visit(name: String, value: Any?) { when (name) { "component", "builder" -> componentClass = value as String } super.visit(name, value) } override fun visitEnd() { defineComponentDeps.add( DefineComponentClassesIr( fqName = annotatedClassName, component = componentClass.toClassName() ) ) super.visitEnd() } } } AggregatedAnnotation.ALIAS_OF -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { lateinit var defineComponentScopeClassName: Type lateinit var aliasClassName: Type override fun visit(name: String, value: Any?) { when (name) { "defineComponentScope" -> defineComponentScopeClassName = (value as Type) "alias" -> aliasClassName = (value as Type) } super.visit(name, value) } override fun visitEnd() { aliasOfDeps.add( AliasOfPropagatedDataIr( fqName = annotatedClassName, defineComponentScope = defineComponentScopeClassName.toClassName(), alias = aliasClassName.toClassName(), ) ) super.visitEnd() } } } AggregatedAnnotation.AGGREGATED_DEP -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { val componentClasses = mutableListOf<String>() var testClass: String? = null val replacesClasses = mutableListOf<String>() var moduleClass: String? = null var entryPoint: String? = null var componentEntryPoint: String? = null override fun visit(name: String, value: Any?) { when (name) { "test" -> testClass = value as String } super.visit(name, value) } override fun visitArray(name: String): AnnotationVisitor? { return when (name) { "components" -> visitValue { value -> componentClasses.add(value as String) } "replaces" -> visitValue { value -> replacesClasses.add(value as String) } "modules" -> visitValue { value -> moduleClass = value as String } "entryPoints" -> visitValue { value -> entryPoint = value as String } "componentEntryPoints" -> visitValue { value -> componentEntryPoint = value as String } else -> super.visitArray(name) } } override fun visitEnd() { aggregatedDeps.add( AggregatedDepsIr( fqName = annotatedClassName, components = componentClasses.map { it.toClassName() }, test = testClass?.toClassName(), replaces = replacesClasses.map { it.toClassName() }, module = moduleClass?.toClassName(), entryPoint = entryPoint?.toClassName(), componentEntryPoint = componentEntryPoint?.toClassName() ) ) super.visitEnd() } } } AggregatedAnnotation.AGGREGATED_DEP_PROXY -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { lateinit var valueClassName: Type override fun visit(name: String, value: Any?) { when (name) { "value" -> valueClassName = (value as Type) } super.visit(name, value) } override fun visitEnd() { aggregatedDepProxies.add( AggregatedElementProxyIr( fqName = annotatedClassName, value = valueClassName.toClassName(), ) ) super.visitEnd() } } } AggregatedAnnotation.AGGREGATED_UNINSTALL_MODULES -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { lateinit var testClass: String val uninstallModulesClasses = mutableListOf<String>() override fun visit(name: String, value: Any?) { when (name) { "test" -> testClass = value as String } super.visit(name, value) } override fun visitArray(name: String): AnnotationVisitor? { return when (name) { "uninstallModules" -> visitValue { value -> uninstallModulesClasses.add(value as String) } else -> super.visitArray(name) } } override fun visitEnd() { uninstallModulesDeps.add( AggregatedUninstallModulesIr( fqName = annotatedClassName, test = testClass.toClassName(), uninstallModules = uninstallModulesClasses.map { it.toClassName() } ) ) super.visitEnd() } } } AggregatedAnnotation.AGGREGATED_EARLY_ENTRY_POINT -> { return object : AnnotationVisitor(asmApiVersion, nextAnnotationVisitor) { lateinit var earlyEntryPointClass: String override fun visit(name: String, value: Any?) { when (name) { "earlyEntryPoint" -> earlyEntryPointClass = value as String } super.visit(name, value) } override fun visitEnd() { earlyEntryPointDeps.add( AggregatedEarlyEntryPointIr( fqName = annotatedClassName, earlyEntryPoint = earlyEntryPointClass.toClassName() ) ) super.visitEnd() } } } else -> { logger.warn("Found an unknown annotation in Hilt aggregated packages: $descriptor") } } return nextAnnotationVisitor } fun visitValue(block: (value: Any) -> Unit) = object : AnnotationVisitor(asmApiVersion) { override fun visit(nullName: String?, value: Any) { block(value) } } } private fun process(files: Iterable<File>) { files.forEach { file -> when { file.isFile -> visitFile(file) file.isDirectory -> file.walkTopDown().filter { it.isFile }.forEach { visitFile(it) } else -> logger.warn("Can't process file/directory that doesn't exist: $file") } } } private fun visitFile(file: File) { when { file.isJarFile() -> ZipInputStream(file.inputStream()).forEachZipEntry { inputStream, entry -> if (entry.isClassFile()) { visitClass(inputStream) } } file.isClassFile() -> file.inputStream().use { visitClass(it) } else -> logger.debug("Don't know how to process file: $file") } } private fun visitClass(classFileInputStream: InputStream) { ClassReader(classFileInputStream).accept( classVisitor, ClassReader.SKIP_CODE and ClassReader.SKIP_DEBUG and ClassReader.SKIP_FRAMES ) } companion object { fun from( logger: Logger, asmApiVersion: Int, input: Iterable<File> ) = Aggregator(logger, asmApiVersion).apply { process(input) } // Converts this Type to a ClassName, used instead of ClassName.bestGuess() because ASM class // names are based off descriptors and uses 'reflection' naming, i.e. inner classes are split // by '$' instead of '.' fun Type.toClassName(): ClassName { val binaryName = this.className val packageNameEndIndex = binaryName.lastIndexOf('.') val packageName = if (packageNameEndIndex != -1) { binaryName.substring(0, packageNameEndIndex) } else { "" } val shortNames = binaryName.substring(packageNameEndIndex + 1).split('$') return ClassName.get(packageName, shortNames.first(), *shortNames.drop(1).toTypedArray()) } // Converts this String representing the canonical name of a class to a ClassName. fun String.toClassName(): ClassName { return ClassName.bestGuess(this) } } }
apache-2.0
f5a3eeaa13661416aa8fcf8d34594263
36.46247
100
0.613172
5.143617
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIScreenEdgePanGestureRecognizer.kt
1
1332
package com.yy.codex.uikit /** * Created by cuiminghui on 2017/1/13. */ class UIScreenEdgePanGestureRecognizer : UIPanGestureRecognizer { enum class Edge { Top, Left, Bottom, Right } var edge = Edge.Left var edgeLength = 22.0 constructor(target: Any, selector: String) : super(target, selector) {} constructor(triggerBlock: Runnable) : super(triggerBlock) {} override fun touchesBegan(touches: List<UITouch>, event: UIEvent) { super.touchesBegan(touches, event) if (!checkEdge(touches)) { state = UIGestureRecognizerState.Failed } } private fun checkEdge(touches: List<UITouch>): Boolean { touches.forEach { if (edge == Edge.Left && it.absolutePoint.x < edgeLength) { return true } else if (edge == Edge.Right && UIScreen.mainScreen.bounds().size.width - it.absolutePoint.x < edgeLength) { return true } else if (edge == Edge.Top && it.absolutePoint.y < edgeLength) { return true } else if (edge == Edge.Bottom && UIScreen.mainScreen.bounds().size.height - it.absolutePoint.y < edgeLength) { return true } } return false } }
gpl-3.0
1397d6f357644f470439450422b89e52
28.6
127
0.568318
4.484848
false
false
false
false
vitalybe/radio-stream
app/android/app/src/main/java/com/radiostream/player/Song.kt
1
11019
package com.radiostream.player import android.accounts.NetworkErrorException import android.content.Context import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.PowerManager import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.radiostream.Settings import com.radiostream.networking.metadata.MetadataBackendGetter import com.radiostream.networking.models.SongResult import com.radiostream.wrapper.UriInterface import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.delay import timber.log.Timber import java.io.IOException import java.io.UnsupportedEncodingException import java.net.URLEncoder import java.util.* import kotlin.coroutines.experimental.suspendCoroutine class Song { val id: Int val artist: String val album: String val title: String private val mPath: String private val mLastPlayed: Double private val mPlayCount: Int private var mRating: Int = 0 private var mContext: Context? = null private var mMetadataBackendGetter: MetadataBackendGetter? = null private var mSongLoadingJob: Deferred<Unit>? = null private var mMediaPlayer: MediaPlayerInterface? = null private var mSettings: Settings? = null private var mEventsListener: EventsListener? = null private lateinit var mUriWrapper: UriInterface private var mMarkAsPlayedScheduled = false private var markedAsPlayedDeferred: Deferred<Unit>? = null // if released val isPlaying: Boolean get() = if (mMediaPlayer != null) { mMediaPlayer!!.isPlaying } else { false } constructor(songResult: SongResult, mediaPlayer: MediaPlayerInterface, context: Context, settings: Settings, metadataBackend: MetadataBackendGetter, uriWrapper: UriInterface) { this.artist = songResult.artist this.album = songResult.album this.title = songResult.title this.id = songResult.id this.mRating = songResult.rating this.mLastPlayed = songResult.lastplayed this.mPlayCount = songResult.playcount // In various mock modes we will provide the full MP3 path if (!songResult.path.startsWith("android.resource")) { var pathBuilder = "" val pathParts = songResult.path.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (pathPart in pathParts) { try { pathBuilder += "/" + URLEncoder.encode(pathPart, "UTF-8").replace("+", "%20") } catch (e: UnsupportedEncodingException) { Timber.e(e, "failed to encode path part: %s", pathPart) } } this.mPath = settings.address + "/music/" + pathBuilder.substring(1) } else { this.mPath = songResult.path } initializeSong(mediaPlayer, context, settings, metadataBackend, uriWrapper) } constructor(otherSong: Song, mediaPlayer: MediaPlayerInterface, context: Context, settings: Settings, metadataBackend: MetadataBackendGetter, uriWrapper: UriInterface) { this.artist = otherSong.artist this.album = otherSong.album this.title = otherSong.title this.id = otherSong.id this.mRating = otherSong.mRating this.mLastPlayed = otherSong.mLastPlayed this.mPlayCount = otherSong.mPlayCount this.mPath = otherSong.mPath initializeSong(mediaPlayer, context, settings, metadataBackend, uriWrapper) } private fun initializeSong(mediaPlayer: MediaPlayerInterface, context: Context, settings: Settings, metadataBackend: MetadataBackendGetter, uriWrapper: UriInterface) { this.mMetadataBackendGetter = metadataBackend this.mContext = context this.mMediaPlayer = mediaPlayer this.mSettings = settings this.mUriWrapper = uriWrapper // NOTE: Wake lock will only be relevant when a song is playing mMediaPlayer!!.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK) mMediaPlayer!!.setAudioStreamType(AudioManager.STREAM_MUSIC) Timber.i("created new song: %s", this.toString()) } private suspend fun scheduleMarkAsPlayed() { Timber.i("markedAsPlayedDeferred: %h", markedAsPlayedDeferred) if (mMediaPlayer == null) { Timber.i("media player is null - song is no longer active - further scheduling cancelled") } else if (this.markedAsPlayedDeferred != null) { Timber.i("mark as played already in progress") } else if (mMediaPlayer!!.currentPosition >= markPlayedAfterMs) { Timber.i("marking song as played since its current position %d is after %d", mMediaPlayer!!.currentPosition, markPlayedAfterMs) this.markedAsPlayedDeferred = retryMarkAsPlayed() if (mEventsListener != null) { Timber.i("finished marking as played - notifying subscribers") mEventsListener!!.onSongMarkedAsPlayed() } } else { Timber.i("this is not the time to mark as played %dms, retrying again in %dms", mMediaPlayer!!.currentPosition, markPlayedRetryMs) delay(markPlayedRetryMs) Timber.i("retrying...") scheduleMarkAsPlayed() } } suspend fun waitForMarkedAsPlayed() { Timber.i("function start") if (markedAsPlayedDeferred != null) { Timber.i("returning existing promise") markedAsPlayedDeferred!!.join() } else { Timber.i("mark as played hasn't started - not waiting") } } private fun retryMarkAsPlayed(): Deferred<Unit> = async(CommonPool) { Timber.i("function start") try { mMetadataBackendGetter!!.get().markAsPlayed([email protected]) Timber.i("marked as played successfully") } catch (e: Exception) { Timber.i(e, "failed to mark as read - retrying again after sleep") delay(markPlayedRetryMs) Timber.i("sleep done - trying to mark again") retryMarkAsPlayed() } return@async Unit } fun subscribeToEvents(eventsListener: EventsListener) { Timber.i("function start") mEventsListener = eventsListener } suspend fun preload() { Timber.i("function start") if (mSongLoadingJob == null || mSongLoadingJob!!.isCompletedExceptionally) { Timber.i("creating a new deferred") mSongLoadingJob = async(CommonPool) { mediaPlayerPrepare(mPath) } } else { Timber.i("preload for this song already started. awaiting the deferred to complete") } Timber.i("waiting for preload to complete...") mSongLoadingJob!!.await() Timber.i("preload complete") } suspend fun mediaPlayerPrepare(path: String): Unit = suspendCoroutine { cont -> mMediaPlayer!!.setOnPreparedListener(MediaPlayer.OnPreparedListener { Timber.i("setOnPreparedListener callback for song: %s", [email protected]()) cont.resume(Unit) }) mMediaPlayer!!.setOnErrorListener(MediaPlayer.OnErrorListener { _, what, extra -> Timber.w("setOnErrorListener callback for song: %s", [email protected]()) val errorMessage = String.format(Locale.ENGLISH, "MediaPlayer failed to preload song: %d/%d", what, extra) cont.resumeWithException(NetworkErrorException(errorMessage)) true }) Timber.i("loading song from url: %s", this.mPath) try { mMediaPlayer!!.setDataSource(this.mContext!!, mUriWrapper.parse(path)) mMediaPlayer!!.prepareAsync() } catch (e: IOException) { cont.resumeWithException(NetworkErrorException("Failed to set data source", e)) } } suspend fun play() { Timber.i("function start") if (!mMarkAsPlayedScheduled) { Timber.i("this is the first play - schedule song to be marked as played") mMarkAsPlayedScheduled = true async(CommonPool) { try { scheduleMarkAsPlayed() } catch (e: Exception) { Timber.e(e, "Marking as played failed: ${e}") } } } mMediaPlayer!!.setOnErrorListener(MediaPlayer.OnErrorListener { _, what, extra -> async(CommonPool) { try { Timber.e("song error - %d, %d", what, extra) val errorMessage = String.format(Locale.ENGLISH, "Exception during playblack: %d/%d", what, extra) mEventsListener!!.onSongError(Exception(errorMessage)) } catch (e: Exception) { Timber.e(e, "Error: ${e}") } } true }) mMediaPlayer!!.setOnCompletionListener (MediaPlayer.OnCompletionListener { async(CommonPool) { try { mEventsListener!!.onSongFinish(this@Song) } catch (e: Exception) { Timber.e(e, "Error: ${e}") } } }) Timber.i("starting song...") mMediaPlayer!!.start() } fun pause() { if (mMediaPlayer!!.isPlaying) { mMediaPlayer!!.pause() } } fun close() { Timber.i("function start: %s", this.toString()) if (mMediaPlayer != null) { pause() Timber.i("resetting and releasing the media player") mMediaPlayer!!.reset() mMediaPlayer!!.release() mMediaPlayer = null } else { Timber.i("already closed") } } fun toBridgeObject(): WritableMap { val map = Arguments.createMap() map.putInt("id", id) map.putString("artist", artist) map.putString("title", title) map.putString("album", album) map.putInt("rating", mRating) map.putDouble("lastplayed", mLastPlayed) map.putInt("playcount", mPlayCount) map.putBoolean("isMarkedAsPlayed", markedAsPlayedDeferred != null && markedAsPlayedDeferred!!.isCompleted && !markedAsPlayedDeferred!!.isCompletedExceptionally) return map } override fun toString(): String = String.format("[%s - %s]", artist, title) fun setRating(newRating: Int) { mRating = newRating } interface EventsListener { suspend fun onSongFinish(song: Song) fun onSongMarkedAsPlayed() suspend fun onSongError(error: Exception) } companion object { val markPlayedAfterMs = 30000 val markPlayedRetryMs = 15000L } }
mit
4a5663bb6d2c656c2c1d336dfcdd00e6
34.204473
173
0.624921
4.766003
false
false
false
false
EPadronU/balin
src/main/kotlin/com/github/epadronu/balin/config/ConfigurationSetup.kt
1
3133
/****************************************************************************** * Copyright 2016 Edinson E. Padrón Urdaneta * * 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.epadronu.balin.config /* ***************************************************************************/ /* ***************************************************************************/ import org.openqa.selenium.WebDriver import org.openqa.selenium.firefox.FirefoxDriver /* ***************************************************************************/ /* ***************************************************************************/ const val DEFAULT_SLEEP_TIME_IN_MILLISECONDS = 1000L const val DEFAULT_TIME_OUT_TIME_IN_SECONDS = 10L /* ***************************************************************************/ /* ***************************************************************************/ /** * This interface describe the different configuration options that can be used * to customize Balin's behavior. */ interface ConfigurationSetup { /** * Control whether the driver quits at the end * of [com.github.epadronu.balin.core.Browser.drive]. * * autoQuit = false */ val autoQuit: Boolean /** * The factory that will create the driver to be used when invoking * [com.github.epadronu.balin.core.Browser.drive]. * * driverFactory = ::FirefoxDriver */ val driverFactory: () -> WebDriver /** * Control the amount of time between attempts when using * [com.github.epadronu.balin.core.WaitingSupport.waitFor]. * * waitForSleepTimeInMilliseconds = 1_000L // One second */ val waitForSleepTimeInMilliseconds: Long /** * Control the total amount of time to wait for a condition evaluated by * [com.github.epadronu.balin.core.WaitingSupport.waitFor] to hold. * * waitForTimeOutTimeInSecond = 10L // Ten seconds */ val waitForTimeOutTimeInSeconds: Long /** * Contains the default configuration setup used by Balin. */ companion object { /** * Define the default configuration setup used by Balin. */ internal val Default = Configuration( true, ::FirefoxDriver, DEFAULT_SLEEP_TIME_IN_MILLISECONDS, DEFAULT_TIME_OUT_TIME_IN_SECONDS) } } /* ***************************************************************************/
apache-2.0
0e3ade7dcb92b5dc6dfaebf6ddae9cc3
35.418605
79
0.503831
5.504394
false
true
false
false
kotlin-es/kotlin-JFrame-standalone
03-start-async-message-application/src/main/kotlin/components/textArea/TextAreaImpl.kt
3
1731
package components.progressBar import utils.ThreadMain import java.awt.Dimension import java.util.concurrent.CompletableFuture import javax.swing.JPanel import javax.swing.JScrollPane import javax.swing.JTextArea /** * Created by vicboma on 05/12/16. */ class TextAreaImpl internal constructor(val _text: String) : JTextArea() , TextArea { companion object { var scrollPane : JScrollPane? = null fun create(text: String): TextArea { return TextAreaImpl(text) } } init{ scrollPane = JScrollPane(this) scrollPane?.setPreferredSize(Dimension(380, 100)) scrollPane?.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS) this.lineWrap = true this.wrapStyleWord = true this.isEditable = false this.alignmentX = JPanel.CENTER_ALIGNMENT this.autoscrolls = true for ( i in 0.._text.length-1) { i.text() } } override fun asyncUI() { ThreadMain.asyncUI { CompletableFuture.runAsync { Thread.sleep(1500) text = "" for ( i in 0.._text.length-1) { Thread.sleep(50) i.text() } }.thenAcceptAsync { asyncUI() } } } private fun isMod(a : Int, b :Int) = (a % b) == 0 public fun Int.text() = when { //isMod(this,TextArea.MOD) -> caretPosition = getDocument().getLength() else -> { append(_text[this].toString()) caretPosition = getDocument().getLength() } } override fun component() : JScrollPane? { return scrollPane } }
mit
c7acb915a49abeb47ebddc143bd7f016
24.086957
85
0.56788
4.555263
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/style/ModifierOrderSpec.kt
1
4319
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.TestConfig import io.gitlab.arturbosch.detekt.test.compileAndLint import io.gitlab.arturbosch.detekt.test.lint import org.assertj.core.api.Assertions.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe class ModifierOrderSpec : Spek({ val subject by memoized { ModifierOrder(Config.empty) } describe("ModifierOrder rule") { context("kt classes with modifiers") { val bad1 = "data internal class Test(val test: String)" val bad2 = "actual private class Test(val test: String)" val bad3 = "annotation expect class Test" it("should report incorrectly ordered modifiers") { assertThat(subject.compileAndLint(bad1)).hasSize(1) assertThat(subject.lint(bad2)).hasSize(1) assertThat(subject.lint(bad3)).hasSize(1) } it("does not report correctly ordered modifiers") { assertThat(subject.compileAndLint("internal data class Test(val test: String)")).isEmpty() assertThat(subject.lint("private actual class Test(val test: String)")).isEmpty() assertThat(subject.lint("expect annotation class Test")).isEmpty() } it("should not report issues if inactive") { val rule = ModifierOrder(TestConfig(mapOf(Config.ACTIVE_KEY to "false"))) assertThat(rule.compileAndLint(bad1)).isEmpty() assertThat(rule.lint(bad2)).isEmpty() assertThat(rule.lint(bad3)).isEmpty() } } context("a kt parameter with modifiers") { it("should report wrongly ordered modifiers") { val code = "lateinit internal var test: String" assertThat(subject.compileAndLint(code)).hasSize(1) } it("should not report correctly ordered modifiers") { val code = "internal lateinit var test: String" assertThat(subject.compileAndLint(code)).isEmpty() } } context("an overridden function") { it("should report incorrectly ordered modifiers") { val code = """ abstract class A { abstract fun test() } abstract class Test : A() { override open fun test() {} }""" assertThat(subject.compileAndLint(code)).hasSize(1) } it("should not report correctly ordered modifiers") { val code = """ abstract class A { abstract fun test() } abstract class Test : A() { override fun test() {} }""" assertThat(subject.compileAndLint(code)).isEmpty() } } context("a tailrec function") { it("should report incorrectly ordered modifiers") { val code = """ public class A { tailrec private fun foo(x: Double = 1.0): Double = 1.0 } """ assertThat(subject.compileAndLint(code)).hasSize(1) } it("should not report correctly ordered modifiers") { val code = """ public class A { private tailrec fun foo(x: Double = 1.0): Double = 1.0 } """ assertThat(subject.compileAndLint(code)).isEmpty() } } context("a vararg argument") { it("should report incorrectly ordered modifiers") { val code = "class Foo(vararg private val strings: String) {}" assertThat(subject.compileAndLint(code)).hasSize(1) } it("should not report correctly ordered modifiers") { val code = "class Foo(private vararg val strings: String) {}" assertThat(subject.compileAndLint(code)).isEmpty() } } } })
apache-2.0
11c670d48c1da3b358efe0163d18f63e
37.221239
106
0.538782
5.332099
false
true
false
false
Gu3pardo/PasswordSafe-AndroidClient
lib_password/src/main/java/guepardoapps/password/StringExtension.kt
1
1375
package guepardoapps.password import guepardoapps.encryption.Constants @ExperimentalUnsignedTypes fun String.checkPasswordQuality(minCount: UInt = Constants.Passphrase.Chars.EachTypeDefaultMin, isWordConnection: Boolean = false): Pair<Boolean, String> { if (this.length < Constants.Passphrase.Length.Min) { return Pair(false, "Not long enough") } if (isWordConnection) { return Pair(true, "Good quality") } val numberCount = this.filter { char -> char.isDigit() }.length val lowerCaseCharCount = this.filter { char -> char.isLowerCase() }.length val upperCaseCharCount = this.filter { char -> char.isUpperCase() }.length val otherCount = this.filter { char -> !char.isDigit() && !char.isLowerCase() && !char.isUpperCase() }.length return if (numberCount >= minCount.toInt()) { if (lowerCaseCharCount >= minCount.toInt()) { if (upperCaseCharCount >= minCount.toInt()) { if (otherCount >= minCount.toInt()) { Pair(true, "Good quality") } else { Pair(false, "Not enough signs") } } else { Pair(false, "Not enough upper letters") } } else { Pair(false, "Not enough lower letters") } } else { Pair(false, "Not enough numbers") } }
mit
d094a5b79c08e6b7b310bf4ca956d139
36.162162
155
0.6
4.478827
false
false
false
false
sybila/CTL-Parser
src/test/java/com/github/sybila/huctl/FormulasTest.kt
1
2579
package com.github.sybila.huctl import com.github.sybila.huctl.dsl.* import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals class Misc { @Test fun booleanToString() { assertEquals("true", Formula.True.toString()) assertEquals("false", Formula.False.toString()) } @Test fun variableToString() { assertEquals("test", "test".toVar().toString()) } @Test fun constantToString() { assertEquals("3.140000", (!3.14).toString()) } @Test fun expressionToString() { assertEquals("((a + 12.000000) / ((3.000000 * 4.000000) - Var))", ( ("a".toVar() plus !12.0) div ((!3.0 times !4.0) minus "Var".toVar()) ).toString()) } @Test fun ctlFormulaToString() { assertEquals( "(!true && ({true}pEwX (false {true}EU true)))", (Not(Formula.True) and pEwX(Formula.False EU Formula.True)).toString() ) } @Test fun hybridFormulaToString() { assertEquals("(at x : (bind y : true))", At("x", Bind("y", Formula.True)).toString()) } @Test fun firstOrderFormulaToString() { assertEquals( "(forall x in false : (exists y in true : false))", ForAll("x", Formula.False, Exists("y", Formula.True, Formula.False)).toString() ) } @Test fun floatPropositionToString() { val prop = ("prop".toVar() gt !5.3) assertEquals("(prop > 5.300000)", prop.toString()) } @Test fun directionToString() { assertEquals("prop:in+", "prop".toPositiveIn().toString()) } @Test fun basicProperties() { val v1 = "v1".toVar() val v2 = "v2".toVar() assertNotEquals(v1.hashCode(), v2.hashCode()) assertNotEquals(v1, v2) val prop1 = ("prop1".toVar() gt !5.3) val prop2 = ("prop2".toVar() gt (!54.3 plus !3.2)) assertNotEquals(prop1.hashCode(), prop2.hashCode()) assertNotEquals(prop1, prop2) val dir1 = "v1".toPositiveIn() val dir2 = "v1".toNegativeOut() assertNotEquals(dir1.hashCode(), dir2.hashCode()) assertNotEquals(dir1, dir2) assertEquals("v1", dir1.name) assertEquals(Direction.POSITIVE, dir1.direction) assertEquals(Flow.IN, dir1.flow) val u = (prop1 EU prop2) as Formula.Until assertEquals(prop1, u.path) assertEquals(prop2, u.reach) } }
gpl-3.0
e383117ad93d66d211e2f41dc61b0482
26.731183
95
0.551764
3.826409
false
true
false
false
koreader/android-luajit-launcher
app/src/main/java/org/koreader/launcher/extensions/UriExtensions.kt
1
2490
package org.koreader.launcher.extensions import android.content.ContentResolver import android.content.Context import android.net.Uri import android.os.Build import android.provider.MediaStore import android.system.Os import java.io.File import java.io.FileNotFoundException import java.io.FileOutputStream import java.io.IOException fun Uri.absolutePath(context: Context): String? { return when (this.scheme) { ContentResolver.SCHEME_FILE -> { this.path?.let { filePath -> File(filePath) }?.absolutePath } ContentResolver.SCHEME_CONTENT -> { this.authority?.let { _ -> try { context.contentResolver.openFileDescriptor(this, "r")?.use { parcel -> try { val file = File("/proc/self/fd/" + parcel.fd) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { Os.readlink(file.absolutePath) } else { file.canonicalPath } } catch (e: IOException) { null } catch (e: Exception) { null } } } catch (e: FileNotFoundException) { e.printStackTrace() null } } } else -> null } } fun Uri.toFile(context: Context, path: String) { if (this.scheme != ContentResolver.SCHEME_CONTENT) { return } this.authority ?: return val nameColumn = arrayOf(MediaStore.MediaColumns.DISPLAY_NAME) val contentResolver = context.contentResolver val name: String? = contentResolver.query(this, nameColumn, null, null, null)?.use { it.moveToFirst() it.getString(it.getColumnIndex(nameColumn[0])) } name ?: return context.contentResolver.openInputStream(this)?.use { try { val file = File(path, name) FileOutputStream(file).use { target -> val buffer = ByteArray(8 * 1024) var len = it.read(buffer) while (len != -1) { target.write(buffer, 0, len) len = it.read(buffer) } } } catch (e: IOException) { e.printStackTrace() } } }
mit
7df907e2ae0c0a9653cf3cbddbc492ea
31.337662
90
0.508434
5.020161
false
false
false
false
V2Ray-Android/Actinium
app/src/main/kotlin/com/v2ray/actinium/ui/SettingsActivity.kt
1
5559
package com.v2ray.actinium.ui import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.os.IBinder import android.preference.CheckBoxPreference import android.preference.MultiSelectListPreference import android.preference.Preference import android.preference.PreferenceFragment import android.support.v7.app.AppCompatActivity import com.v2ray.actinium.R import com.v2ray.actinium.aidl.IV2RayService import com.v2ray.actinium.defaultDPreference import com.v2ray.actinium.extension.onClick import com.v2ray.actinium.service.V2RayVpnService import de.psdev.licensesdialog.LicensesDialogFragment import libv2ray.Libv2ray import org.jetbrains.anko.act import org.jetbrains.anko.defaultSharedPreferences import org.jetbrains.anko.startActivity class SettingsActivity : BaseActivity() { companion object { const val PREF_START_ON_BOOT = "pref_start_on_boot" const val PREF_PER_APP_PROXY = "pref_per_app_proxy" const val PREF_LICENSES = "pref_licenses" const val PREF_FEEDBACK = "pref_feedback" const val PREF_AUTO_RESTART = "pref_auto_restart" const val PREF_AUTO_RESTART_SET = "pref_auto_restart_set" const val PREF_FOREGROUND_SERVICE = "pref_foreground_service" const val PREF_CORE_VERSION = "pref_core_version" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) supportActionBar?.setDisplayHomeAsUpEnabled(true) } class SettingsFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener { val perAppProxy by lazy { findPreference(PREF_PER_APP_PROXY) as CheckBoxPreference } val autoRestart by lazy { findPreference(PREF_AUTO_RESTART_SET) as MultiSelectListPreference } val licenses: Preference by lazy { findPreference(PREF_LICENSES) } val feedback: Preference by lazy { findPreference(PREF_FEEDBACK) } val coreVersion: Preference by lazy { findPreference(PREF_CORE_VERSION) } var bgService: IV2RayService? = null val conn = object : ServiceConnection { override fun onServiceDisconnected(name: ComponentName?) { } override fun onServiceConnected(name: ComponentName?, service: IBinder?) { val service1 = IV2RayService.Stub.asInterface(service) bgService = service1 val isV2RayRunning = service1.isRunning autoRestart.isEnabled = !isV2RayRunning if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (isV2RayRunning) { perAppProxy.isEnabled = false } else { perAppProxy.setOnPreferenceClickListener { startActivity<PerAppProxyActivity>() perAppProxy.isChecked = true false } } } else { perAppProxy.isEnabled = false } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addPreferencesFromResource(R.xml.pref_settings) licenses.onClick { val fragment = LicensesDialogFragment.Builder(act) .setNotices(R.raw.licenses) .setIncludeOwnLicense(false) .build() fragment.show((act as AppCompatActivity).supportFragmentManager, null) } coreVersion.summary = Libv2ray.checkVersionX() } override fun onStart() { super.onStart() val intent = Intent(act.applicationContext, V2RayVpnService::class.java) act.bindService(intent, conn, BIND_AUTO_CREATE) perAppProxy.isChecked = defaultSharedPreferences.getBoolean(PREF_PER_APP_PROXY, false) autoRestart.summary = defaultSharedPreferences.getStringSet(PREF_AUTO_RESTART_SET, emptySet()).joinToString { it } defaultSharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onStop() { super.onStop() act.unbindService(conn) defaultSharedPreferences.unregisterOnSharedPreferenceChangeListener(this) } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) { when (key) { PREF_FOREGROUND_SERVICE -> { act.defaultDPreference.setPrefBoolean(key, sharedPreferences.getBoolean(key, false)) bgService?.onPrefForegroundServiceChanged(sharedPreferences.getBoolean(key, false)) } PREF_AUTO_RESTART -> act.defaultDPreference.setPrefBoolean(key, sharedPreferences.getBoolean(key, false)) PREF_PER_APP_PROXY -> act.defaultDPreference.setPrefBoolean(key, sharedPreferences.getBoolean(key, false)) PREF_AUTO_RESTART_SET -> { val set = sharedPreferences.getStringSet(key, null) act.defaultDPreference.setPrefStringSet(key, set) autoRestart.summary = set.joinToString { it } } } } } }
gpl-3.0
84f9b82743171ebde102b7187f26816e
38.714286
126
0.646699
5.190476
false
false
false
false
doubledeath/android.mvvm
mvvm/src/main/java/com/github/doubledeath/android/mvvm/impl/MvvmActivityDelegate.kt
1
1824
package com.github.doubledeath.android.mvvm.impl import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import com.github.doubledeath.android.mvvm.MvvmFacade import com.github.doubledeath.android.mvvm.base.MvvmBaseActivity import com.github.doubledeath.android.mvvm.base.MvvmBaseDelegate import kotlin.reflect.KClass @Suppress("UNCHECKED_CAST") internal class MvvmActivityDelegate<VM : MvvmActivityViewModel, B : ViewDataBinding, A : MvvmBaseActivity<VM, B>> /*constructor*/(private val activity: A, navigator: MvvmAppNavigator) : MvvmBaseDelegate<VM, B, MvvmBaseActivity<*, *>> /*super.constructor*/(MvvmFacade.viewMapper.toViewModel(activity::class) as KClass<VM>, navigator) { private var binding: B? = null private var context: MvvmBaseActivity<*, *>? = null override fun binding(): B { val binding = binding ?: DataBindingUtil.setContentView(activity, activity.providedLayoutId) if (this.binding === null) { binding.setVariable(activity.providedViewModelId, viewModel()) this.binding = binding } return binding } override fun context(): MvvmBaseActivity<*, *> { val context = context ?: activity if (this.context === null) { this.context = context } return context } override fun onViewActive() { selfNavigator().pool.putContext(tag, activity.fragmentManager) super.onViewActive() } override fun onViewInactive() { super.onViewInactive() selfNavigator().pool.cleanContext(tag) } override fun onDestroy() { if (activity.isFinishing) { super.onDestroy() } } internal fun selfNavigator(): MvvmActivityNavigator { return viewModel().selfNavigator } }
mit
de1887a6d2cecf23231da03d6447a2b0
28.419355
119
0.685307
4.571429
false
false
false
false
cronokirby/FlashKi
src/com/cronokirby/flashki/views/EditView.kt
1
4462
package com.cronokirby.flashki.views import com.cronokirby.flashki.controllers.DeckStore import com.cronokirby.flashki.events.ChangeViewEvent import com.cronokirby.flashki.events.ViewPages import com.cronokirby.flashki.models.Card import com.cronokirby.flashki.models.Category import com.cronokirby.flashki.models.Deck import com.cronokirby.flashki.models.DeckMeta import com.github.thomasnield.rxkotlinfx.actionEvents import com.github.thomasnield.rxkotlinfx.toObservable import io.reactivex.Observable import io.reactivex.rxkotlin.Observables import io.reactivex.rxkotlin.withLatestFrom import io.reactivex.subjects.PublishSubject import javafx.scene.control.Button import javafx.scene.control.TextField import tornadofx.* class EditView(oldDeck: Deck) : View() { val store: DeckStore by inject() private val startIndex = oldDeck.cards.size private val cards = oldDeck.cards.toMutableList() // the signal of current cards private val cardSubj = PublishSubject.create<Card>() // the past, and current navigation index private var index = PublishSubject.create<Pair<Int, Int>>() // nodes that we need to have globally available private var leftButton: Button by singleAssign() private var rightButton: Button by singleAssign() private var front: TextField by singleAssign() private var back: TextField by singleAssign() init { // keeping track of adding cards to the backing list index.withLatestFrom(cardSubj, { a, b -> Pair(a, b)}) .subscribe { (ind, card) -> val (past, now) = ind if (past in 0.until(cards.size)) { cards[past] = card } else if (past < now){ cards.add(card) } } } override val root = borderpane { val isNew = index.map { it.second >= cards.size } // only allow us to add cards if they're not empty and new val cannotAdd = Observables.combineLatest(cardSubj, isNew, { card, new -> !card.isFull() || (new && cards.contains(card)) }) top { hbox { val name = textfield { promptText = "Deck Name" text = oldDeck.metaData.name } val saveButton = button("Save") Observables.combineLatest( name.textProperty().toObservable(), saveButton.actionEvents() ).subscribe { (name, _) -> store.editOut(oldDeck, Deck(cards, DeckMeta(Category("category"), name))) fire(ChangeViewEvent(ViewPages.NotEditing())) } } } left { leftButton = button("Previous Card") { index.map { it.second <= 0 }.subscribe { this.disableProperty().set(it) } } } right { rightButton = button { isNew.map { if (it) "Add Card" else "Next Card" } .subscribe { this.textProperty().set(it) } cannotAdd.subscribe { this.disableProperty().set(it) } } } // keeping track of navigation Observable.merge( leftButton.actionEvents().map { -1 }, rightButton.actionEvents().map { 1 } ).scan(Pair(startIndex, startIndex)) { (_, acc), x -> Pair(acc, Math.max(0, acc + x)) }.subscribe(index) center { vbox { label("Front Side") front = textfield { this.actionEvents().subscribe { back.requestFocus() } } label("Back Side") back = textfield { this.actionEvents().subscribe { front.requestFocus() // this will be protected from advances by the button rightButton.fire() } } index.map { it.second }.subscribe { val newCard = cards.getOrNull(it) front.text = newCard?.front ?: "" back.text = newCard?.back ?: "" } Observables.combineLatest( front.textProperty().toObservable(), back.textProperty().toObservable(), ::Card ).subscribe(cardSubj) } } } }
mit
f3f5015ec349389b588e211875438ea0
36.504202
93
0.556701
4.691903
false
false
false
false
PaulWoitaschek/Voice
bookOverview/src/main/kotlin/voice/bookOverview/views/MigrateIcon.kt
1
853
package voice.bookOverview.views import androidx.compose.foundation.layout.Box import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.CompareArrows import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import voice.bookOverview.R @Composable internal fun MigrateIcon( withHint: Boolean, onClick: () -> Unit, onHintClick: () -> Unit, modifier: Modifier = Modifier, ) { Box { IconButton(modifier = modifier, onClick = onClick) { Icon( imageVector = Icons.Outlined.CompareArrows, contentDescription = stringResource(R.string.migration_hint_title), ) } if (withHint) { MigrateHint(onHintClick) } } }
gpl-3.0
84b6f44f28990f4575ce88384219b854
26.516129
75
0.750293
4.08134
false
false
false
false
FHannes/intellij-community
platform/script-debugger/backend/src/org/jetbrains/debugger/ObjectPropertyImpl.kt
7
1508
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.util.BitUtil import org.jetbrains.debugger.values.FunctionValue import org.jetbrains.debugger.values.Value class ObjectPropertyImpl(name: String, value: Value?, override val getter: FunctionValue? = null, override val setter: FunctionValue? = null, valueModifier: ValueModifier? = null, private val flags: Int = 0) : VariableImpl(name, value, valueModifier), ObjectProperty { companion object { val WRITABLE = 0x01 val CONFIGURABLE = 0x02 val ENUMERABLE = 0x04 } override val isWritable: Boolean get() = BitUtil.isSet(flags, WRITABLE) override val isConfigurable: Boolean get() = BitUtil.isSet(flags, CONFIGURABLE) override val isEnumerable: Boolean get() = BitUtil.isSet(flags, ENUMERABLE) }
apache-2.0
7938a24288b8cde4d26cc04ecac10220
34.928571
113
0.687003
4.358382
false
true
false
false
SalomonBrys/Kotson
src/main/kotlin/com/github/salomonbrys/kotson/Gson.kt
1
4663
package com.github.salomonbrys.kotson import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.stream.JsonToken import com.google.gson.TypeAdapter import com.google.gson.reflect.TypeToken import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.io.Reader inline fun <reified T: Any> Gson.getAdapter(): TypeAdapter<T> = getAdapter(object: TypeToken<T>() {}) inline fun <reified T: Any> Gson.getGenericAdapter(): TypeAdapter<T> = getAdapter(T::class.java) inline fun <reified T: Any> Gson.fromJson(json: String): T = fromJson(json, typeToken<T>()) inline fun <reified T: Any> Gson.fromJson(json: Reader): T = fromJson(json, typeToken<T>()) inline fun <reified T: Any> Gson.fromJson(json: JsonReader): T = fromJson(json, typeToken<T>()) inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = fromJson(json, typeToken<T>()) inline fun <reified T: Any> Gson.typedToJson(src: T): String = toJson(src, typeToken<T>()) inline fun <reified T: Any> Gson.typedToJson(src: T, writer: Appendable): Unit = toJson(src, typeToken<T>(), writer) inline fun <reified T: Any> Gson.typedToJson(src: T, writer: JsonWriter): Unit = toJson(src, typeToken<T>(), writer) inline fun <reified T: Any> Gson.typedToJsonTree(src: T): JsonElement = toJsonTree(src, typeToken<T>()) // Extensions to JsonReader for reading nullable values /** * Returns the {@link com.google.gson.stream.JsonToken#NUMBER int} value of the next token, * consuming it. If the next token is {@code NULL}, this method returns {@code null}. * If the next token is a string, it will attempt to parse it as an int. * If the next token's numeric value cannot be exactly represented by a Java {@code int}, * this method throws. * * @throws IllegalStateException if the next token is not a literal value. * @throws NumberFormatException if the next literal value is not null but * cannot be parsed as a number, or exactly represented as an int. */ fun JsonReader.nextIntOrNull(): Int? { if ( this.peek() != JsonToken.NULL ) { return this.nextInt() } else { this.nextNull() return null } } /** * Returns the {@link com.google.gson.stream.JsonToken#BOOLEAN boolean} value of the next token, * consuming it. If the next token is {@code NULL}, this method returns {@code null}. * * @throws IllegalStateException if the next token is not a boolean or if * this reader is closed. */ fun JsonReader.nextBooleanOrNull(): Boolean? { if ( this.peek() != JsonToken.NULL ) { return this.nextBoolean() } else { this.nextNull() return null } } /** * Returns the {@link com.google.gson.stream.JsonToken#NUMBER double} value of the next token, * consuming it. If the next token is {@code NULL}, this method returns {@code null}. * If the next token is a string, it will attempt to parse it as a double using {@link Double#parseDouble(String)}. * * @throws IllegalStateException if the next token is not a literal value. * @throws NumberFormatException if the next literal value cannot be parsed * as a double, or is non-finite. */ fun JsonReader.nextDoubleOrNull(): Double? { if ( this.peek() != JsonToken.NULL ) { return this.nextDouble() } else { this.nextNull() return null } } /** * Returns the {@link com.google.gson.stream.JsonToken#NUMBER long} value of the next token, * consuming it. If the next token is {@code NULL}, this method returns {@code null}. * If the next token is a string, this method will attempt to parse it as a long. * If the next token's numeric value cannot be exactly represented by a Java {@code long}, this method throws. * * @throws IllegalStateException if the next token is not a literal value. * @throws NumberFormatException if the next literal value cannot be parsed * as a number, or exactly represented as a long. */ fun JsonReader.nextLongOrNull(): Long? { if ( this.peek() != JsonToken.NULL ) { return this.nextLong() } else { this.nextNull() return null } } /** * Returns the {@link com.google.gson.stream.JsonToken#STRING string} value of the next token, * consuming it. If the next token is {@code NULL}, this method returns {@code null}. * If the next token is a number, it will return its string form. * * @throws IllegalStateException if the next token is not a string or if * this reader is closed. */ fun JsonReader.nextStringOrNull(): String? { if ( this.peek() != JsonToken.NULL ) { return this.nextString() } else { this.nextNull() return null } }
mit
5d515b2234a642e87f72ea7b1cb17899
35.716535
116
0.695904
3.898829
false
false
false
false
nickthecoder/paratask
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/ShortcutHelper.kt
1
2916
/* ParaTask Copyright (C) 2017 Nick Robinson 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 uk.co.nickthecoder.paratask.gui import javafx.event.EventHandler import javafx.scene.Node import javafx.scene.input.KeyCode import javafx.scene.input.KeyEvent import java.util.* class ShortcutHelper(val name: String, val node: Node, val filter: Boolean = true) { val actions = mutableListOf<Pair<ApplicationAction, () -> Unit>>() val keyHandler = EventHandler<KeyEvent> { keyPressed(it) } init { enable() } fun add(action: ApplicationAction, func: () -> Unit) { actions.add(Pair(action, func)) } fun keyPressed(event: KeyEvent) { try { actions.forEach { (action, func) -> if (action.keyCodeCombination?.match(event) == true) { try { func() } catch (e: Exception) { // If the event throws an exception, don't consume the event. // This allows other handlers to handle the event. return } event.consume() } } } catch (e: ConcurrentModificationException) { // Do nothing } } fun clear() { actions.clear() } fun enable() { if (filter) { node.addEventFilter(KeyEvent.KEY_PRESSED, keyHandler) } else { node.addEventHandler(KeyEvent.KEY_PRESSED, keyHandler) } } fun disable() { if (filter) { node.removeEventFilter(KeyEvent.KEY_PRESSED, keyHandler) } else { node.removeEventHandler(KeyEvent.KEY_PRESSED, keyHandler) } } companion object { val CONTEXT_MENU = ApplicationAction.createKeyCodeCombination(KeyCode.CONTEXT_MENU) val FOCUS_NEXT = ApplicationAction.createKeyCodeCombination(KeyCode.TAB) val INSERT_TAB = ApplicationAction.createKeyCodeCombination(KeyCode.TAB, control = true) /** * When called from an event handler of a shortcut, prevents the event from being consumed, so that * the event can be handled by another handler. */ fun ignore() { throw Exception( "Ignore shortcut event") } } }
gpl-3.0
ab972bed90dba2dbd81f060af1fb2bd6
30.695652
107
0.618656
4.621236
false
false
false
false
ExMCL/ExMCL
ExMCL Hooks/src/main/kotlin/com/n9mtq4/exmcl/hooks/GameLaunchHookUnsafe.kt
1
4303
/* * MIT License * * Copyright (c) 2016 Will (n9Mtq4) Bresnahan * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.n9mtq4.exmcl.hooks import com.n9mtq4.exmcl.api.hooks.events.DefaultGameLaunchEvent import com.n9mtq4.exmcl.api.hooks.events.GameLaunchEvent import com.n9mtq4.exmcl.api.hooks.events.PreDefinedSwingComponent import com.n9mtq4.exmcl.api.hooks.events.PreDefinedSwingHookEvent import com.n9mtq4.logwindow.BaseConsole import com.n9mtq4.logwindow.annotation.ListensFor import com.n9mtq4.logwindow.listener.GenericListener import java.awt.event.ActionEvent import java.awt.event.ActionListener import javax.swing.JButton /** * Created by will on 7/28/15 at 3:53 PM. * This class does some advanced and sneaky things to let * us process the play button action BEFORE the minecraft launcher * can. Because swing randomizes the order of ActionListeners we * can't just add us the first one in the list. We have to * remove all other listeners, while keeping a copy of the * listeners for us. When our ActionListener gets sent the event, * we send it to all the BaseConsole listener and then if none of them * set the canceled flag to true, then we will send it to the listeners * we removed from before. * * NOTE: THIS LISTENER IS FAR LESS COMPLEX WITH LogWindowFramework-5.1 */ class GameLaunchHookUnsafe : ActionListener, GenericListener { private var listeners: Array<ActionListener>? = null private lateinit var baseConsole: BaseConsole /** * Gets the play button and adds the GameLaunchHook onto it. */ @Suppress("unused") @ListensFor(PreDefinedSwingHookEvent::class) fun ListensForPlayButton(e: PreDefinedSwingHookEvent, baseConsole: BaseConsole) { // makes sure it is the playbutton if (e.type !== PreDefinedSwingComponent.PLAY_BUTTON) return // set the baseConsole this.baseConsole = baseConsole // get the button and listeners val playButton = e.component as JButton this.listeners = playButton.actionListeners // remove all the action listeners on the button // we will handle them for (listener in listeners!!) { playButton.removeActionListener(listener) } // add them into the DefaultActionListenerDispatcher val defaultGameRunner = DefaultMinecraftGameRunner(listeners as Array<ActionListener>) baseConsole.addListenerAttribute(defaultGameRunner) // now add us as the only action listener playButton.addActionListener(this) } /** * ActionListener actionPerformed - push the ActionEvent to the baseConsole, * then maybe send it to the listeners */ override fun actionPerformed(e: ActionEvent) { // send the event to people listening with the BaseConsole first. // baseConsole.push(e, "gamelaunch"); val gameLaunchEvent = GameLaunchEvent(e, baseConsole) baseConsole.pushEvent(gameLaunchEvent) if (!gameLaunchEvent.isCanceled) { baseConsole.pushEvent(DefaultGameLaunchEvent(e, baseConsole)) } } private inner class DefaultMinecraftGameRunner(private val listeners: Array<ActionListener>) : GenericListener { @Suppress("unused") @ListensFor fun onDefaultGameLaunch(event: DefaultGameLaunchEvent, baseConsole: BaseConsole) { for (listener in listeners) { listener.actionPerformed(event.actionEvent) } } } }
mit
7be1591d8bbf7192000fed597a0705ff
35.777778
113
0.768301
4.032802
false
false
false
false
Light-Team/ModPE-IDE-Source
editorkit/src/main/kotlin/com/brackeys/ui/editorkit/internal/SyntaxHighlightEditText.kt
1
16598
/* * Copyright 2021 Brackeys IDE 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.brackeys.ui.editorkit.internal import android.content.Context import android.text.Editable import android.text.Spannable import android.text.Spanned import android.text.style.BackgroundColorSpan import android.util.AttributeSet import androidx.core.text.PrecomputedTextCompat import androidx.core.text.getSpans import com.brackeys.ui.editorkit.R import com.brackeys.ui.editorkit.model.FindParams import com.brackeys.ui.editorkit.span.ErrorSpan import com.brackeys.ui.editorkit.span.FindResultSpan import com.brackeys.ui.editorkit.span.TabWidthSpan import com.brackeys.ui.language.base.Language import com.brackeys.ui.language.base.span.StyleSpan import com.brackeys.ui.language.base.span.SyntaxHighlightSpan import java.util.regex.Pattern import java.util.regex.PatternSyntaxException abstract class SyntaxHighlightEditText @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = R.attr.autoCompleteTextViewStyle ) : UndoRedoEditText(context, attrs, defStyleAttr) { var language: Language? = null private val syntaxHighlightSpans = mutableListOf<SyntaxHighlightSpan>() private val findResultSpans = mutableListOf<FindResultSpan>() private val delimiters = charArrayOf('{', '[', '(', '}', ']', ')') private var findResultStyleSpan: StyleSpan? = null private var openDelimiterSpan: BackgroundColorSpan? = null private var closedDelimiterSpan: BackgroundColorSpan? = null private var addedTextCount = 0 private var selectedFindResult = 0 private var isSyntaxHighlighting = false private var isErrorSpansVisible = false override fun colorize() { findResultStyleSpan = StyleSpan(color = colorScheme.findResultBackgroundColor) openDelimiterSpan = BackgroundColorSpan(colorScheme.delimiterBackgroundColor) closedDelimiterSpan = BackgroundColorSpan(colorScheme.delimiterBackgroundColor) super.colorize() } override fun setTextContent(textParams: PrecomputedTextCompat) { syntaxHighlightSpans.clear() findResultSpans.clear() super.setTextContent(textParams) syntaxHighlight() } override fun onSelectionChanged(selStart: Int, selEnd: Int) { super.onSelectionChanged(selStart, selEnd) if (selStart == selEnd) { checkMatchingBracket(selStart) } // invalidate() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { updateSyntaxHighlighting() super.onSizeChanged(w, h, oldw, oldh) } override fun onScrollChanged(horiz: Int, vert: Int, oldHoriz: Int, oldVert: Int) { super.onScrollChanged(horiz, vert, oldHoriz, oldVert) updateSyntaxHighlighting() } override fun doBeforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) { addedTextCount -= count cancelSyntaxHighlighting() if (!isSyntaxHighlighting) { super.doBeforeTextChanged(text, start, count, after) } abortFling() } override fun doOnTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) { addedTextCount += count if (!isSyntaxHighlighting) { super.doOnTextChanged(text, start, before, count) } } override fun doAfterTextChanged(text: Editable?) { super.doAfterTextChanged(text) if (!isSyntaxHighlighting) { shiftSpans(selectionStart, addedTextCount) } addedTextCount = 0 syntaxHighlight() } fun clearFindResultSpans() { selectedFindResult = 0 findResultSpans.clear() val spans = text.getSpans<FindResultSpan>(0, text.length) for (span in spans) { text.removeSpan(span) } } fun setErrorLine(lineNumber: Int) { if (lineNumber > 0) { val lineStart = getIndexForStartOfLine(lineNumber - 1) val lineEnd = getIndexForEndOfLine(lineNumber - 1) if (lineStart < text.length && lineEnd < text.length && lineStart > -1 && lineEnd > -1) { isErrorSpansVisible = true text.setSpan(ErrorSpan(), lineStart, lineEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } } } fun find(findText: String, findParams: FindParams) { if (findText.isNotEmpty()) { try { val pattern = if (findParams.regex) { if (findParams.matchCase) { Pattern.compile(findText) } else { Pattern.compile(findText, Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE) } } else { if (findParams.wordsOnly) { if (findParams.matchCase) { Pattern.compile("\\s$findText\\s") } else { Pattern.compile( "\\s" + Pattern.quote(findText) + "\\s", Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE ) } } else { if (findParams.matchCase) { Pattern.compile(Pattern.quote(findText)) } else { Pattern.compile( Pattern.quote(findText), Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE ) } } } val matcher = pattern.matcher(text) while (matcher.find()) { findResultStyleSpan?.let { val findResultSpan = FindResultSpan(it, matcher.start(), matcher.end()) findResultSpans.add(findResultSpan) text.setSpan( findResultSpan, findResultSpan.start, findResultSpan.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } if (findResultSpans.isNotEmpty()) { selectResult() } } catch (e: PatternSyntaxException) { // nothing } } } fun findNext() { if (selectedFindResult < findResultSpans.size - 1) { selectedFindResult += 1 selectResult() } } fun findPrevious() { if (selectedFindResult > 0 && selectedFindResult < findResultSpans.size) { selectedFindResult -= 1 selectResult() } } fun replaceFindResult(replaceText: String) { if (findResultSpans.isNotEmpty()) { val findResult = findResultSpans[selectedFindResult] text.replace(findResult.start, findResult.end, replaceText) findResultSpans.remove(findResult) if (selectedFindResult >= findResultSpans.size) { selectedFindResult-- } } } fun replaceAllFindResults(replaceText: String) { if (findResultSpans.isNotEmpty()) { val stringBuilder = StringBuilder(text) for (index in findResultSpans.size - 1 downTo 0) { val findResultSpan = findResultSpans[index] stringBuilder.replace(findResultSpan.start, findResultSpan.end, replaceText) findResultSpans.removeAt(index) } setText(stringBuilder.toString()) } } private fun selectResult() { val findResult = findResultSpans[selectedFindResult] setSelection(findResult.start, findResult.end) scrollToFindResult() } private fun scrollToFindResult() { if (selectedFindResult < findResultSpans.size) { val findResult = findResultSpans[selectedFindResult] val topVisibleLine = getTopVisibleLine() val bottomVisibleLine = getBottomVisibleLine() if (findResult.start >= layout.getLineStart(topVisibleLine) && findResult.end <= layout.getLineEnd(bottomVisibleLine)) { return } val height = layout.height - height + paddingBottom + paddingTop var lineTop = layout.getLineTop(layout.getLineForOffset(findResult.start)) if (lineTop > height) { lineTop = height } val scrollX = if (!editorConfig.wordWrap) { layout.getPrimaryHorizontal(findResult.start).toInt() } else scrollX scrollTo(scrollX, lineTop) } } private fun shiftSpans(from: Int, byHowMuch: Int) { for (span in syntaxHighlightSpans) { if (span.start >= from) { span.start += byHowMuch } if (span.end >= from) { span.end += byHowMuch } /*if (span.start > span.end) { syntaxHighlightSpans.remove(span) // FIXME may cause ConcurrentModificationException }*/ } for (findResult in findResultSpans) { /*if (from > findResult.start && from <= findResult.end) { findResultSpans.remove(findResult) // FIXME may cause IndexOutOfBoundsException }*/ if (findResult.start > from) { findResult.start += byHowMuch } if (findResult.end >= from) { findResult.end += byHowMuch } } if (isErrorSpansVisible) { val spans = text.getSpans<ErrorSpan>(0, text.length) for (span in spans) { text.removeSpan(span) } isErrorSpansVisible = false } } private fun updateSyntaxHighlighting() { if (layout != null) { val topVisibleLine = getTopVisibleLine() val bottomVisibleLine = getBottomVisibleLine() val lineStart = layout.getLineStart(topVisibleLine) val lineEnd = layout.getLineEnd(bottomVisibleLine) isSyntaxHighlighting = true val textSyntaxSpans = text.getSpans<SyntaxHighlightSpan>(0, text.length) for (span in textSyntaxSpans) { text.removeSpan(span) } for (span in syntaxHighlightSpans) { val isInText = span.start >= 0 && span.end <= text.length val isValid = span.start <= span.end val isVisible = span.start in lineStart..lineEnd || span.start <= lineEnd && span.end >= lineStart if (isInText && isValid && isVisible) { text.setSpan( span, if (span.start < lineStart) lineStart else span.start, if (span.end > lineEnd) lineEnd else span.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } isSyntaxHighlighting = false val textFindSpans = text.getSpans<FindResultSpan>(0, text.length) for (span in textFindSpans) { text.removeSpan(span) } for (span in findResultSpans) { val isInText = span.start >= 0 && span.end <= text.length val isValid = span.start <= span.end val isVisible = span.start in lineStart..lineEnd || span.start <= lineEnd && span.end >= lineStart if (isInText && isValid && isVisible) { text.setSpan( span, if (span.start < lineStart) lineStart else span.start, if (span.end > lineEnd) lineEnd else span.end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } } if (!editorConfig.useSpacesInsteadOfTabs) { // FIXME works pretty bad with word wrap val textTabSpans = text.getSpans<TabWidthSpan>(0, text.length) for (span in textTabSpans) { text.removeSpan(span) } val tabPattern = Pattern.compile("\t") val matcher = tabPattern.matcher(text.subSequence(lineStart, lineEnd)) while (matcher.find()) { val start = matcher.start() + lineStart val end = matcher.end() + lineStart if (start >= 0 && end <= text.length) { text.setSpan( TabWidthSpan(editorConfig.tabWidth), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE ) } } } } } private fun syntaxHighlight() { cancelSyntaxHighlighting() language?.getStyler()?.enqueue(text.toString(), colorScheme.syntaxScheme) { spans -> syntaxHighlightSpans.clear() syntaxHighlightSpans.addAll(spans) updateSyntaxHighlighting() } } private fun cancelSyntaxHighlighting() { language?.getStyler()?.cancel() } private fun checkMatchingBracket(pos: Int) { if (layout != null) { if (openDelimiterSpan != null && closedDelimiterSpan != null) { text.removeSpan(openDelimiterSpan) text.removeSpan(closedDelimiterSpan) } if (editorConfig.highlightDelimiters) { if (pos > 0 && pos <= text.length) { val c1 = text[pos - 1] for (i in delimiters.indices) { if (delimiters[i] == c1) { val open = i <= 2 val c2 = delimiters[(i + 3) % 6] var k = pos if (open) { var nob = 1 while (k < text.length) { if (text[k] == c2) { nob-- } if (text[k] == c1) { nob++ } if (nob == 0) { showBracket(pos - 1, k) break } k++ } } else { var ncb = 1 k -= 2 while (k >= 0) { if (text[k] == c2) { ncb-- } if (text[k] == c1) { ncb++ } if (ncb == 0) { showBracket(k, pos - 1) break } k-- } } } } } } } } private fun showBracket(i: Int, j: Int) { if (openDelimiterSpan != null && closedDelimiterSpan != null) { text.setSpan(openDelimiterSpan, i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) text.setSpan(closedDelimiterSpan, j, j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } } }
apache-2.0
afdff97ff5a1cdf24a098af91b897afc
37.512761
101
0.516388
5.240922
false
false
false
false
BOINC/boinc
android/BOINC/app/src/main/java/edu/berkeley/boinc/rpc/ProjectConfigReplyParser.kt
2
7531
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2021 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC 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 BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.util.Xml import edu.berkeley.boinc.utils.Logging import org.xml.sax.Attributes import org.xml.sax.SAXException class ProjectConfigReplyParser : BaseParser() { lateinit var projectConfig: ProjectConfig private set private var mPlatforms: MutableList<PlatformInfo?>? = null private var withinPlatforms = false private var platformName = "" private var platformFriendlyName = "" private var platformPlanClass = "" @Throws(SAXException::class) override fun startElement(uri: String?, localName: String, qName: String?, attributes: Attributes?) { super.startElement(uri, localName, qName, attributes) when { localName.equals(PROJECT_CONFIG_TAG, ignoreCase = true) -> { projectConfig = ProjectConfig() } localName.equals(ProjectConfig.Fields.PLATFORMS, ignoreCase = true) -> { withinPlatforms = true mPlatforms = mutableListOf() //initialize new list (flushing old elements) } else -> { // Another element, hopefully primitive and not constructor // (although unknown constructor does not hurt, because there will be primitive start anyway) mElementStarted = true mCurrentElement.setLength(0) } } } @Throws(SAXException::class) override fun endElement(uri: String?, localName: String, qName: String?) { super.endElement(uri, localName, qName) try { if (localName.equals(ProjectConfig.Fields.PLATFORMS, ignoreCase = true)) { // closing tag of platform names projectConfig.platforms = mPlatforms!! withinPlatforms = false } else { // Not the closing tag - we decode possible inner tags trimEnd() if (localName.equals(NAME, ignoreCase = true)) { projectConfig.name = mCurrentElement.toString() } else if (localName.equals(MASTER_URL, ignoreCase = true)) { projectConfig.masterUrl = mCurrentElement.toString() } else if (localName.equals(ProjectConfig.Fields.WEB_RPC_URL_BASE, ignoreCase = true)) { projectConfig.webRpcUrlBase = mCurrentElement.toString() } else if (localName.equals(ProjectConfig.Fields.LOCAL_REVISION, ignoreCase = true)) { projectConfig.localRevision = mCurrentElement.toString() } else if (localName.equals(ProjectConfig.Fields.MIN_PWD_LENGTH, ignoreCase = true)) { projectConfig.minPwdLength = mCurrentElement.toInt() } else if (localName.equalsAny(USER_NAME_TAG, USES_USER_NAME_TAG, ignoreCase = true)) { projectConfig.usesName = true } else if (localName.equals(ProjectConfig.Fields.WEB_STOPPED, ignoreCase = true)) { projectConfig.webStopped = mCurrentElement.toInt() != 0 } else if (localName.equals(ProjectConfig.Fields.SCHEDULER_STOPPED, ignoreCase = true)) { projectConfig.schedulerStopped = mCurrentElement.toInt() != 0 } else if (localName.equals(ProjectConfig.Fields.CLIENT_ACCOUNT_CREATION_DISABLED, ignoreCase = true)) { projectConfig.clientAccountCreationDisabled = true } else if (localName.equals(ProjectConfig.Fields.MIN_CLIENT_VERSION, ignoreCase = true)) { projectConfig.minClientVersion = mCurrentElement.toInt() } else if (localName.equals(ProjectConfig.Fields.RPC_PREFIX, ignoreCase = true)) { projectConfig.rpcPrefix = mCurrentElement.toString() } else if (localName.equals(PlatformInfo.Fields.NAME, ignoreCase = true) && withinPlatforms) { platformName = mCurrentElement.toString() } else if (localName.equals(USER_FRIENDLY_NAME, ignoreCase = true) && withinPlatforms) { platformFriendlyName = mCurrentElement.toString() } else if (localName.equals(PLAN_CLASS, ignoreCase = true) && withinPlatforms) { platformPlanClass = mCurrentElement.toString() } else if (localName.equals(ProjectConfig.Fields.TERMS_OF_USE, ignoreCase = true)) { projectConfig.termsOfUse = mCurrentElement.toString() } else if (localName.equals(PLATFORM_TAG, ignoreCase = true) && withinPlatforms) { // finish platform object and add to array mPlatforms!!.add(PlatformInfo(platformName, platformFriendlyName, platformPlanClass)) platformFriendlyName = "" platformName = "" platformPlanClass = "" } else if (localName.equals(ERROR_NUM, ignoreCase = true)) { // reply is not present yet projectConfig.errorNum = mCurrentElement.toInt() } else if (localName.equals(ProjectConfig.Fields.ACCOUNT_MANAGER, ignoreCase = true)) { projectConfig.accountManager = true } } mElementStarted = false } catch (e: Exception) { Logging.logException(Logging.Category.XML, "ProjectConfigReplyParser.endElement error: ", e) } } companion object { const val PLATFORM_TAG = "platform" const val PROJECT_CONFIG_TAG = "project_config" const val USER_NAME_TAG = "user_name" const val USES_USER_NAME_TAG = "uses_username" /** * Parse the RPC result (state) and generate vector of projects info * * @param rpcResult String returned by RPC call of core client * @return connected client state */ @JvmStatic fun parse(rpcResult: String): ProjectConfig? { return try { val parser = ProjectConfigReplyParser() //TODO report malformated XML to BOINC and remove String.replace here... //<boinc_gui_rpc_reply> //<?xml version="1.0" encoding="ISO-8859-1" ?> //<project_config> Xml.parse(rpcResult.replace("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>", ""), parser) parser.projectConfig } catch (e: SAXException) { Logging.logException(Logging.Category.RPC, "ProjectConfigReplyParser: malformed XML ", e) Logging.logDebug(Logging.Category.XML, "ProjectConfigReplyParser: $rpcResult") null } } } }
lgpl-3.0
2c0414c30b481cf65367f4ecdcc27df5
51.298611
119
0.612402
4.935125
false
true
false
false
equeim/tremotesf-android
app/src/main/kotlin/org/equeim/tremotesf/ui/torrentslistfragment/TorrentsListFragment.kt
1
14565
/* * Copyright (C) 2017-2022 Alexey Rochev <[email protected]> * * This file is part of Tremotesf. * * Tremotesf is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Tremotesf is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.equeim.tremotesf.ui.torrentslistfragment import android.graphics.drawable.LayerDrawable import android.os.Bundle import android.view.MenuItem import androidx.activity.result.ActivityResultLauncher import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.TooltipCompat import androidx.core.content.withStyledAttributes import androidx.core.view.children import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.navigation.navGraphViewModels import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.elevation.ElevationOverlayProvider import com.google.android.material.snackbar.Snackbar import kotlinx.coroutines.async import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.launch import org.equeim.libtremotesf.RpcConnectionState import org.equeim.libtremotesf.RpcError import org.equeim.tremotesf.R import org.equeim.tremotesf.databinding.TorrentsListFragmentBinding import org.equeim.tremotesf.rpc.GlobalRpc import org.equeim.tremotesf.rpc.GlobalServers import org.equeim.tremotesf.rpc.statusString import org.equeim.tremotesf.torrentfile.rpc.Server import org.equeim.tremotesf.torrentfile.rpc.ServerStats import org.equeim.tremotesf.ui.NavigationFragment import org.equeim.tremotesf.ui.Settings import org.equeim.tremotesf.ui.TorrentFileRenameDialogFragment import org.equeim.tremotesf.ui.utils.* class TorrentsListFragment : NavigationFragment( R.layout.torrents_list_fragment, 0, R.menu.torrents_list_fragment_menu ) { private val model by navGraphViewModels<TorrentsListFragmentViewModel>(R.id.torrents_list_fragment) private var notificationPermissionLauncher: ActivityResultLauncher<Array<String>>? = null private val binding by viewLifecycleObject(TorrentsListFragmentBinding::bind) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) TorrentFileRenameDialogFragment.setFragmentResultListenerForRpc(this) notificationPermissionLauncher = model.notificationPermissionHelper?.registerWithFragment(this) } override fun onViewStateRestored(savedInstanceState: Bundle?) { super.onViewStateRestored(savedInstanceState) viewLifecycleOwner.lifecycleScope.launch { if (Settings.quickReturn.get()) { toolbar.setOnClickListener { binding.torrentsView.scrollToPosition(0) } } } setupBottomBar() binding.swipeRefreshLayout.apply { requireContext().withStyledAttributes(attrs = intArrayOf(androidx.appcompat.R.attr.colorPrimary)) { setColorSchemeColors(getColor(0, 0)) } val elevation = resources.getDimension(R.dimen.swipe_refresh_progress_bar_elevation) setProgressBackgroundColorSchemeColor( ElevationOverlayProvider(requireContext()) .compositeOverlayWithThemeSurfaceColorIfNeeded(elevation) ) setOnRefreshListener { if (GlobalRpc.isConnected.value) { GlobalRpc.nativeInstance.updateData() } else { binding.swipeRefreshLayout.isRefreshing = false } } GlobalRpc.torrentsUpdatedEvent.launchAndCollectWhenStarted(viewLifecycleOwner) { isRefreshing = false } } binding.torrentsView.apply { layoutManager = LinearLayoutManager(requireContext()) (itemAnimator as DefaultItemAnimator).supportsChangeAnimations = false fastScroller.setSwipeRefreshLayout(binding.swipeRefreshLayout) } binding.detailedErrorMessageButton.setOnClickListener { navigate(TorrentsListFragmentDirections.toDetailedConnectionErrorDialogFragment()) } viewLifecycleOwner.lifecycleScope.launch { val compactView = async { Settings.torrentCompactView.get() } val multilineName = async { Settings.torrentNameMultiline.get() } if (compactView.await()) { binding.torrentsView.addItemDecoration( DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL) ) } val torrentsAdapter = TorrentsAdapter( this@TorrentsListFragment, compactView.await(), multilineName.await() ) binding.torrentsView.adapter = torrentsAdapter model.torrents.launchAndCollectWhenStarted(viewLifecycleOwner, torrentsAdapter::update) } GlobalRpc.isConnected.launchAndCollectWhenStarted(viewLifecycleOwner, ::onRpcConnectedChanged) combine(model.showAddTorrentButton, model.connectionButtonState) { showAddTorrentButton, connectionButtonState -> showAddTorrentButton || connectionButtonState != TorrentsListFragmentViewModel.ConnectionButtonState.Hidden }.distinctUntilChanged().launchAndCollectWhenStarted(viewLifecycleOwner) { binding.endButtonSpacer.isVisible = it } model.placeholderState.launchAndCollectWhenStarted(viewLifecycleOwner, ::updatePlaceholder) GlobalServers.currentServer.launchAndCollectWhenStarted(viewLifecycleOwner, ::updateTitle) model.subtitleUpdateData.launchAndCollectWhenStarted(viewLifecycleOwner, ::updateSubtitle) model.showAddTorrentDuplicateError.handleAndReset { binding.root.showSnackbar(R.string.torrent_duplicate, Snackbar.LENGTH_LONG) }.launchAndCollectWhenStarted(viewLifecycleOwner) model.showAddTorrentError.handleAndReset { binding.root.showSnackbar(R.string.torrent_add_error, Snackbar.LENGTH_LONG) }.launchAndCollectWhenStarted(viewLifecycleOwner) notificationPermissionLauncher?.let { launcher -> model.showNotificationPermissionRequest.handleAndReset { binding.root.showSnackbar( message = R.string.notification_permission_rationale, length = Snackbar.LENGTH_INDEFINITE, actionText = R.string.request_permission, action = { model.notificationPermissionHelper?.requestPermission(this, launcher) } ) }.launchAndCollectWhenStarted(viewLifecycleOwner) } } private fun setupBottomBar() { with(binding) { transmissionSettings.apply { TooltipCompat.setTooltipText(this, contentDescription) setOnClickListener { navigate(TorrentsListFragmentDirections.toTransmissionSettingsDialogFragment()) } } model.showTransmissionSettingsButton.launchAndCollectWhenStarted(viewLifecycleOwner) { transmissionSettings.isVisible = it } torrentsFilters.apply { TooltipCompat.setTooltipText(this, contentDescription) setOnClickListener { navigate(TorrentsListFragmentDirections.toTorrentsFiltersDialogFragment()) } val badgeDrawable = (drawable as LayerDrawable).getDrawable(1) model.sortOrFiltersEnabled.launchAndCollectWhenStarted(viewLifecycleOwner) { badgeDrawable.alpha = if (it) 192 else 0 } } model.showTorrentsFiltersButton.launchAndCollectWhenStarted(viewLifecycleOwner) { torrentsFilters.isVisible = it } searchView.apply { setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { model.nameFilter.set(newText.trim()) return true } override fun onQueryTextSubmit(query: String): Boolean { return false } }) setOnSearchClickListener { model.searchViewIsIconified.set(false) } setOnCloseListener { model.searchViewIsIconified.set(true) false } requiredActivity.onBackPressedDispatcher.addCustomCallback(viewLifecycleOwner) { collapse() } } model.showSearchView.launchAndCollectWhenStarted(viewLifecycleOwner) { if (!it) searchView.collapse() searchView.isVisible = it } TooltipCompat.setTooltipText(addTorrentButton, addTorrentButton.contentDescription) addTorrentButton.setOnClickListener { navigate(TorrentsListFragmentDirections.toAddTorrentMenuFragment()) } model.showAddTorrentButton.launchAndCollectWhenStarted(viewLifecycleOwner) { binding.addTorrentButton.apply { isVisible = it } } model.connectionButtonState.launchAndCollectWhenStarted(viewLifecycleOwner, ::updateConnectionButton) } } private fun updateConnectionButton(state: TorrentsListFragmentViewModel.ConnectionButtonState) { binding.connectionButton.apply { val text = when (state) { TorrentsListFragmentViewModel.ConnectionButtonState.AddServer -> { setOnClickListener { navigate(TorrentsListFragmentDirections.toServerEditFragment()) } R.string.add_server } TorrentsListFragmentViewModel.ConnectionButtonState.Connect -> { setOnClickListener { GlobalRpc.nativeInstance.connect() } R.string.connect } TorrentsListFragmentViewModel.ConnectionButtonState.Disconnect -> { setOnClickListener { GlobalRpc.nativeInstance.disconnect() } R.string.disconnect } TorrentsListFragmentViewModel.ConnectionButtonState.Hidden -> { setOnClickListener(null) null } } isVisible = if (text == null) { false } else { setText(text) true } } } override fun onToolbarMenuItemClicked(menuItem: MenuItem): Boolean { when (menuItem.itemId) { R.id.settings -> navigate(TorrentsListFragmentDirections.toSettingsFragment()) R.id.about -> navigate(TorrentsListFragmentDirections.toAboutFragment()) R.id.quit -> Utils.shutdownApp(requireContext()) else -> return false } return true } private fun onRpcConnectedChanged(connected: Boolean) { if (!connected) { requiredActivity.actionMode?.finish() when (navController.currentDestination?.id) { R.id.transmission_settings_dialog_fragment, R.id.detailed_connection_error_dialog_fragment -> Unit else -> navController.popDialog() } } with(binding) { swipeRefreshLayout.apply { isRefreshing = false isEnabled = connected } bottomToolbar.apply { hideOnScroll = connected if (!connected) performShow() } } } private fun updateTitle(currentServer: Server?) { toolbar.title = if (currentServer != null) { getString( R.string.current_server_string, currentServer.name, currentServer.address ) } else { getString(R.string.app_name) } } private fun updateSubtitle(subtitleData: Pair<ServerStats, Boolean>) { val (stats, isConnected) = subtitleData toolbar.subtitle = if (isConnected) { getString( R.string.main_activity_subtitle, FormatUtils.formatByteSpeed(requireContext(), stats.downloadSpeed), FormatUtils.formatByteSpeed(requireContext(), stats.uploadSpeed) ) } else { null } } private fun updatePlaceholder(data: TorrentsListFragmentViewModel.PlaceholderState) = with(binding) { val (status, hasTorrents) = data progressBar.isVisible = status.connectionState == RpcConnectionState.Connecting && !hasTorrents statusString.apply { text = when { hasTorrents -> null (status.connectionState == RpcConnectionState.Connected) -> getString(R.string.no_torrents) else -> status.statusString } isVisible = !text.isNullOrEmpty() } errorMessage.apply { text = if (status.error.error == RpcError.ConnectionError) { status.error.errorMessage } else { null } isVisible = !text.isNullOrEmpty() } detailedErrorMessageButton.apply { isVisible = status.error.detailedErrorMessage.isNotEmpty() } placeholderView.apply { isVisible = children.any { it.isVisible } } } } private fun SearchView.collapse(): Boolean { return if (!isIconified) { // We need to clear query before calling setIconified(true) setQuery(null, false) isIconified = true true } else { false } }
gpl-3.0
fe2ca518a384c9df4d720828e2174b8d
39.684358
121
0.648335
5.671729
false
false
false
false
is00hcw/anko
dsl/testData/functional/sdk19/InterfaceWorkaroundsTest.kt
3
35980
public final class InterfaceWorkarounds { public static interface DeletedContactsColumns { public static final java.lang.String CONTACT_ID = android.provider.ContactsContract.DeletedContacts.CONTACT_ID; public static final java.lang.String CONTACT_DELETED_TIMESTAMP = android.provider.ContactsContract.DeletedContacts.CONTACT_DELETED_TIMESTAMP; } public static interface ContactOptionsColumns { public static final java.lang.String TIMES_CONTACTED = android.provider.ContactsContract.RawContacts.TIMES_CONTACTED; public static final java.lang.String LAST_TIME_CONTACTED = android.provider.ContactsContract.RawContacts.LAST_TIME_CONTACTED; public static final java.lang.String STARRED = android.provider.ContactsContract.RawContacts.STARRED; public static final java.lang.String CUSTOM_RINGTONE = android.provider.ContactsContract.RawContacts.CUSTOM_RINGTONE; public static final java.lang.String SEND_TO_VOICEMAIL = android.provider.ContactsContract.RawContacts.SEND_TO_VOICEMAIL; } public static interface StreamItemsColumns { public static final java.lang.String CONTACT_ID = android.provider.ContactsContract.Contacts.StreamItems.CONTACT_ID; public static final java.lang.String CONTACT_LOOKUP_KEY = android.provider.ContactsContract.Contacts.StreamItems.CONTACT_LOOKUP_KEY; public static final java.lang.String RAW_CONTACT_ID = android.provider.ContactsContract.Contacts.StreamItems.RAW_CONTACT_ID; public static final java.lang.String RES_PACKAGE = android.provider.ContactsContract.Contacts.StreamItems.RES_PACKAGE; public static final java.lang.String ACCOUNT_TYPE = android.provider.ContactsContract.Contacts.StreamItems.ACCOUNT_TYPE; public static final java.lang.String ACCOUNT_NAME = android.provider.ContactsContract.Contacts.StreamItems.ACCOUNT_NAME; public static final java.lang.String DATA_SET = android.provider.ContactsContract.Contacts.StreamItems.DATA_SET; public static final java.lang.String RAW_CONTACT_SOURCE_ID = android.provider.ContactsContract.Contacts.StreamItems.RAW_CONTACT_SOURCE_ID; public static final java.lang.String RES_ICON = android.provider.ContactsContract.Contacts.StreamItems.RES_ICON; public static final java.lang.String RES_LABEL = android.provider.ContactsContract.Contacts.StreamItems.RES_LABEL; public static final java.lang.String TEXT = android.provider.ContactsContract.Contacts.StreamItems.TEXT; public static final java.lang.String TIMESTAMP = android.provider.ContactsContract.Contacts.StreamItems.TIMESTAMP; public static final java.lang.String COMMENTS = android.provider.ContactsContract.Contacts.StreamItems.COMMENTS; public static final java.lang.String SYNC1 = android.provider.ContactsContract.Contacts.StreamItems.SYNC1; public static final java.lang.String SYNC2 = android.provider.ContactsContract.Contacts.StreamItems.SYNC2; public static final java.lang.String SYNC3 = android.provider.ContactsContract.Contacts.StreamItems.SYNC3; public static final java.lang.String SYNC4 = android.provider.ContactsContract.Contacts.StreamItems.SYNC4; } public static interface RawContactsColumns { public static final java.lang.String CONTACT_ID = android.provider.ContactsContract.RawContacts.CONTACT_ID; public static final java.lang.String DATA_SET = android.provider.ContactsContract.RawContacts.DATA_SET; public static final java.lang.String AGGREGATION_MODE = android.provider.ContactsContract.RawContacts.AGGREGATION_MODE; public static final java.lang.String DELETED = android.provider.ContactsContract.RawContacts.DELETED; public static final java.lang.String RAW_CONTACT_IS_READ_ONLY = android.provider.ContactsContract.RawContacts.RAW_CONTACT_IS_READ_ONLY; public static final java.lang.String RAW_CONTACT_IS_USER_PROFILE = android.provider.ContactsContract.RawContacts.RAW_CONTACT_IS_USER_PROFILE; } public static interface ContactsColumns { public static final java.lang.String DISPLAY_NAME = android.provider.ContactsContract.Contacts.Entity.DISPLAY_NAME; public static final java.lang.String PHOTO_ID = android.provider.ContactsContract.Contacts.Entity.PHOTO_ID; public static final java.lang.String PHOTO_FILE_ID = android.provider.ContactsContract.Contacts.Entity.PHOTO_FILE_ID; public static final java.lang.String PHOTO_URI = android.provider.ContactsContract.Contacts.Entity.PHOTO_URI; public static final java.lang.String PHOTO_THUMBNAIL_URI = android.provider.ContactsContract.Contacts.Entity.PHOTO_THUMBNAIL_URI; public static final java.lang.String IN_VISIBLE_GROUP = android.provider.ContactsContract.Contacts.Entity.IN_VISIBLE_GROUP; public static final java.lang.String IS_USER_PROFILE = android.provider.ContactsContract.Contacts.Entity.IS_USER_PROFILE; public static final java.lang.String HAS_PHONE_NUMBER = android.provider.ContactsContract.Contacts.Entity.HAS_PHONE_NUMBER; public static final java.lang.String LOOKUP_KEY = android.provider.ContactsContract.Contacts.Entity.LOOKUP_KEY; public static final java.lang.String CONTACT_LAST_UPDATED_TIMESTAMP = android.provider.ContactsContract.Contacts.Entity.CONTACT_LAST_UPDATED_TIMESTAMP; } public static interface StreamItemPhotosColumns { public static final java.lang.String STREAM_ITEM_ID = android.provider.ContactsContract.StreamItemPhotos.STREAM_ITEM_ID; public static final java.lang.String SORT_INDEX = android.provider.ContactsContract.StreamItemPhotos.SORT_INDEX; public static final java.lang.String PHOTO_FILE_ID = android.provider.ContactsContract.StreamItemPhotos.PHOTO_FILE_ID; public static final java.lang.String PHOTO_URI = android.provider.ContactsContract.StreamItemPhotos.PHOTO_URI; public static final java.lang.String SYNC1 = android.provider.ContactsContract.StreamItemPhotos.SYNC1; public static final java.lang.String SYNC2 = android.provider.ContactsContract.StreamItemPhotos.SYNC2; public static final java.lang.String SYNC3 = android.provider.ContactsContract.StreamItemPhotos.SYNC3; public static final java.lang.String SYNC4 = android.provider.ContactsContract.StreamItemPhotos.SYNC4; } public static interface AttendeesColumns { public static final java.lang.String EVENT_ID = android.provider.CalendarContract.Attendees.EVENT_ID; public static final java.lang.String ATTENDEE_NAME = android.provider.CalendarContract.Attendees.ATTENDEE_NAME; public static final java.lang.String ATTENDEE_EMAIL = android.provider.CalendarContract.Attendees.ATTENDEE_EMAIL; public static final java.lang.String ATTENDEE_RELATIONSHIP = android.provider.CalendarContract.Attendees.ATTENDEE_RELATIONSHIP; public static final int RELATIONSHIP_NONE = android.provider.CalendarContract.Attendees.RELATIONSHIP_NONE; public static final int RELATIONSHIP_ATTENDEE = android.provider.CalendarContract.Attendees.RELATIONSHIP_ATTENDEE; public static final int RELATIONSHIP_ORGANIZER = android.provider.CalendarContract.Attendees.RELATIONSHIP_ORGANIZER; public static final int RELATIONSHIP_PERFORMER = android.provider.CalendarContract.Attendees.RELATIONSHIP_PERFORMER; public static final int RELATIONSHIP_SPEAKER = android.provider.CalendarContract.Attendees.RELATIONSHIP_SPEAKER; public static final java.lang.String ATTENDEE_TYPE = android.provider.CalendarContract.Attendees.ATTENDEE_TYPE; public static final int TYPE_NONE = android.provider.CalendarContract.Attendees.TYPE_NONE; public static final int TYPE_REQUIRED = android.provider.CalendarContract.Attendees.TYPE_REQUIRED; public static final int TYPE_OPTIONAL = android.provider.CalendarContract.Attendees.TYPE_OPTIONAL; public static final int TYPE_RESOURCE = android.provider.CalendarContract.Attendees.TYPE_RESOURCE; public static final java.lang.String ATTENDEE_STATUS = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS; public static final int ATTENDEE_STATUS_NONE = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_NONE; public static final int ATTENDEE_STATUS_ACCEPTED = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_ACCEPTED; public static final int ATTENDEE_STATUS_DECLINED = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_DECLINED; public static final int ATTENDEE_STATUS_INVITED = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_INVITED; public static final int ATTENDEE_STATUS_TENTATIVE = android.provider.CalendarContract.Attendees.ATTENDEE_STATUS_TENTATIVE; public static final java.lang.String ATTENDEE_IDENTITY = android.provider.CalendarContract.Attendees.ATTENDEE_IDENTITY; public static final java.lang.String ATTENDEE_ID_NAMESPACE = android.provider.CalendarContract.Attendees.ATTENDEE_ID_NAMESPACE; } public static interface CalendarAlertsColumns { public static final java.lang.String EVENT_ID = android.provider.CalendarContract.CalendarAlerts.EVENT_ID; public static final java.lang.String BEGIN = android.provider.CalendarContract.CalendarAlerts.BEGIN; public static final java.lang.String END = android.provider.CalendarContract.CalendarAlerts.END; public static final java.lang.String ALARM_TIME = android.provider.CalendarContract.CalendarAlerts.ALARM_TIME; public static final java.lang.String CREATION_TIME = android.provider.CalendarContract.CalendarAlerts.CREATION_TIME; public static final java.lang.String RECEIVED_TIME = android.provider.CalendarContract.CalendarAlerts.RECEIVED_TIME; public static final java.lang.String NOTIFY_TIME = android.provider.CalendarContract.CalendarAlerts.NOTIFY_TIME; public static final java.lang.String STATE = android.provider.CalendarContract.CalendarAlerts.STATE; public static final int STATE_SCHEDULED = android.provider.CalendarContract.CalendarAlerts.STATE_SCHEDULED; public static final int STATE_FIRED = android.provider.CalendarContract.CalendarAlerts.STATE_FIRED; public static final int STATE_DISMISSED = android.provider.CalendarContract.CalendarAlerts.STATE_DISMISSED; public static final java.lang.String MINUTES = android.provider.CalendarContract.CalendarAlerts.MINUTES; public static final java.lang.String DEFAULT_SORT_ORDER = android.provider.CalendarContract.CalendarAlerts.DEFAULT_SORT_ORDER; } public static interface CalendarContract_SyncColumns { public static final java.lang.String ACCOUNT_NAME = android.provider.CalendarContract.EventsEntity.ACCOUNT_NAME; public static final java.lang.String ACCOUNT_TYPE = android.provider.CalendarContract.EventsEntity.ACCOUNT_TYPE; public static final java.lang.String _SYNC_ID = android.provider.CalendarContract.EventsEntity._SYNC_ID; public static final java.lang.String DIRTY = android.provider.CalendarContract.EventsEntity.DIRTY; public static final java.lang.String MUTATORS = android.provider.CalendarContract.EventsEntity.MUTATORS; public static final java.lang.String DELETED = android.provider.CalendarContract.EventsEntity.DELETED; public static final java.lang.String CAN_PARTIALLY_UPDATE = android.provider.CalendarContract.EventsEntity.CAN_PARTIALLY_UPDATE; } public static interface SettingsColumns { public static final java.lang.String ACCOUNT_NAME = android.provider.ContactsContract.Settings.ACCOUNT_NAME; public static final java.lang.String ACCOUNT_TYPE = android.provider.ContactsContract.Settings.ACCOUNT_TYPE; public static final java.lang.String DATA_SET = android.provider.ContactsContract.Settings.DATA_SET; public static final java.lang.String SHOULD_SYNC = android.provider.ContactsContract.Settings.SHOULD_SYNC; public static final java.lang.String UNGROUPED_VISIBLE = android.provider.ContactsContract.Settings.UNGROUPED_VISIBLE; public static final java.lang.String ANY_UNSYNCED = android.provider.ContactsContract.Settings.ANY_UNSYNCED; public static final java.lang.String UNGROUPED_COUNT = android.provider.ContactsContract.Settings.UNGROUPED_COUNT; public static final java.lang.String UNGROUPED_WITH_PHONES = android.provider.ContactsContract.Settings.UNGROUPED_WITH_PHONES; } public static interface GroupsColumns { public static final java.lang.String DATA_SET = android.provider.ContactsContract.Groups.DATA_SET; public static final java.lang.String TITLE = android.provider.ContactsContract.Groups.TITLE; public static final java.lang.String NOTES = android.provider.ContactsContract.Groups.NOTES; public static final java.lang.String SYSTEM_ID = android.provider.ContactsContract.Groups.SYSTEM_ID; public static final java.lang.String SUMMARY_COUNT = android.provider.ContactsContract.Groups.SUMMARY_COUNT; public static final java.lang.String SUMMARY_WITH_PHONES = android.provider.ContactsContract.Groups.SUMMARY_WITH_PHONES; public static final java.lang.String GROUP_VISIBLE = android.provider.ContactsContract.Groups.GROUP_VISIBLE; public static final java.lang.String DELETED = android.provider.ContactsContract.Groups.DELETED; public static final java.lang.String SHOULD_SYNC = android.provider.ContactsContract.Groups.SHOULD_SYNC; public static final java.lang.String AUTO_ADD = android.provider.ContactsContract.Groups.AUTO_ADD; public static final java.lang.String FAVORITES = android.provider.ContactsContract.Groups.FAVORITES; public static final java.lang.String GROUP_IS_READ_ONLY = android.provider.ContactsContract.Groups.GROUP_IS_READ_ONLY; } public static interface CalendarColumns { public static final java.lang.String CALENDAR_COLOR = android.provider.CalendarContract.CalendarAlerts.CALENDAR_COLOR; public static final java.lang.String CALENDAR_COLOR_KEY = android.provider.CalendarContract.CalendarAlerts.CALENDAR_COLOR_KEY; public static final java.lang.String CALENDAR_DISPLAY_NAME = android.provider.CalendarContract.CalendarAlerts.CALENDAR_DISPLAY_NAME; public static final java.lang.String CALENDAR_ACCESS_LEVEL = android.provider.CalendarContract.CalendarAlerts.CALENDAR_ACCESS_LEVEL; public static final int CAL_ACCESS_NONE = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_NONE; public static final int CAL_ACCESS_FREEBUSY = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_FREEBUSY; public static final int CAL_ACCESS_READ = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_READ; public static final int CAL_ACCESS_RESPOND = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_RESPOND; public static final int CAL_ACCESS_OVERRIDE = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_OVERRIDE; public static final int CAL_ACCESS_CONTRIBUTOR = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_CONTRIBUTOR; public static final int CAL_ACCESS_EDITOR = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_EDITOR; public static final int CAL_ACCESS_OWNER = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_OWNER; public static final int CAL_ACCESS_ROOT = android.provider.CalendarContract.CalendarAlerts.CAL_ACCESS_ROOT; public static final java.lang.String VISIBLE = android.provider.CalendarContract.CalendarAlerts.VISIBLE; public static final java.lang.String CALENDAR_TIME_ZONE = android.provider.CalendarContract.CalendarAlerts.CALENDAR_TIME_ZONE; public static final java.lang.String SYNC_EVENTS = android.provider.CalendarContract.CalendarAlerts.SYNC_EVENTS; public static final java.lang.String OWNER_ACCOUNT = android.provider.CalendarContract.CalendarAlerts.OWNER_ACCOUNT; public static final java.lang.String CAN_ORGANIZER_RESPOND = android.provider.CalendarContract.CalendarAlerts.CAN_ORGANIZER_RESPOND; public static final java.lang.String CAN_MODIFY_TIME_ZONE = android.provider.CalendarContract.CalendarAlerts.CAN_MODIFY_TIME_ZONE; public static final java.lang.String MAX_REMINDERS = android.provider.CalendarContract.CalendarAlerts.MAX_REMINDERS; public static final java.lang.String ALLOWED_REMINDERS = android.provider.CalendarContract.CalendarAlerts.ALLOWED_REMINDERS; public static final java.lang.String ALLOWED_AVAILABILITY = android.provider.CalendarContract.CalendarAlerts.ALLOWED_AVAILABILITY; public static final java.lang.String ALLOWED_ATTENDEE_TYPES = android.provider.CalendarContract.CalendarAlerts.ALLOWED_ATTENDEE_TYPES; public static final java.lang.String IS_PRIMARY = android.provider.CalendarContract.CalendarAlerts.IS_PRIMARY; } public static interface ContactStatusColumns { public static final java.lang.String CONTACT_PRESENCE = android.provider.ContactsContract.Contacts.Entity.CONTACT_PRESENCE; public static final java.lang.String CONTACT_CHAT_CAPABILITY = android.provider.ContactsContract.Contacts.Entity.CONTACT_CHAT_CAPABILITY; public static final java.lang.String CONTACT_STATUS = android.provider.ContactsContract.Contacts.Entity.CONTACT_STATUS; public static final java.lang.String CONTACT_STATUS_TIMESTAMP = android.provider.ContactsContract.Contacts.Entity.CONTACT_STATUS_TIMESTAMP; public static final java.lang.String CONTACT_STATUS_RES_PACKAGE = android.provider.ContactsContract.Contacts.Entity.CONTACT_STATUS_RES_PACKAGE; public static final java.lang.String CONTACT_STATUS_LABEL = android.provider.ContactsContract.Contacts.Entity.CONTACT_STATUS_LABEL; public static final java.lang.String CONTACT_STATUS_ICON = android.provider.ContactsContract.Contacts.Entity.CONTACT_STATUS_ICON; } public static interface CalendarCacheColumns { public static final java.lang.String KEY = android.provider.CalendarContract.CalendarCache.KEY; public static final java.lang.String VALUE = android.provider.CalendarContract.CalendarCache.VALUE; } public static interface CommonColumns { public static final java.lang.String DATA = android.provider.ContactsContract.CommonDataKinds.Nickname.DATA; public static final java.lang.String TYPE = android.provider.ContactsContract.CommonDataKinds.Nickname.TYPE; public static final java.lang.String LABEL = android.provider.ContactsContract.CommonDataKinds.Nickname.LABEL; } public static interface EventDaysColumns { public static final java.lang.String STARTDAY = android.provider.CalendarContract.EventDays.STARTDAY; public static final java.lang.String ENDDAY = android.provider.CalendarContract.EventDays.ENDDAY; } public static interface PresenceColumns { public static final java.lang.String DATA_ID = android.provider.ContactsContract.StatusUpdates.DATA_ID; public static final java.lang.String PROTOCOL = android.provider.ContactsContract.StatusUpdates.PROTOCOL; public static final java.lang.String CUSTOM_PROTOCOL = android.provider.ContactsContract.StatusUpdates.CUSTOM_PROTOCOL; public static final java.lang.String IM_HANDLE = android.provider.ContactsContract.StatusUpdates.IM_HANDLE; public static final java.lang.String IM_ACCOUNT = android.provider.ContactsContract.StatusUpdates.IM_ACCOUNT; } public static interface PhoneLookupColumns { public static final java.lang.String NUMBER = android.provider.ContactsContract.PhoneLookup.NUMBER; public static final java.lang.String TYPE = android.provider.ContactsContract.PhoneLookup.TYPE; public static final java.lang.String LABEL = android.provider.ContactsContract.PhoneLookup.LABEL; public static final java.lang.String NORMALIZED_NUMBER = android.provider.ContactsContract.PhoneLookup.NORMALIZED_NUMBER; } public static interface ExtendedPropertiesColumns { public static final java.lang.String EVENT_ID = android.provider.CalendarContract.ExtendedProperties.EVENT_ID; public static final java.lang.String NAME = android.provider.CalendarContract.ExtendedProperties.NAME; public static final java.lang.String VALUE = android.provider.CalendarContract.ExtendedProperties.VALUE; } public static interface RemindersColumns { public static final java.lang.String EVENT_ID = android.provider.CalendarContract.Reminders.EVENT_ID; public static final java.lang.String MINUTES = android.provider.CalendarContract.Reminders.MINUTES; public static final int MINUTES_DEFAULT = android.provider.CalendarContract.Reminders.MINUTES_DEFAULT; public static final java.lang.String METHOD = android.provider.CalendarContract.Reminders.METHOD; public static final int METHOD_DEFAULT = android.provider.CalendarContract.Reminders.METHOD_DEFAULT; public static final int METHOD_ALERT = android.provider.CalendarContract.Reminders.METHOD_ALERT; public static final int METHOD_EMAIL = android.provider.CalendarContract.Reminders.METHOD_EMAIL; public static final int METHOD_SMS = android.provider.CalendarContract.Reminders.METHOD_SMS; public static final int METHOD_ALARM = android.provider.CalendarContract.Reminders.METHOD_ALARM; } public static interface ColorsColumns { public static final java.lang.String COLOR_TYPE = android.provider.CalendarContract.Colors.COLOR_TYPE; public static final int TYPE_CALENDAR = android.provider.CalendarContract.Colors.TYPE_CALENDAR; public static final int TYPE_EVENT = android.provider.CalendarContract.Colors.TYPE_EVENT; public static final java.lang.String COLOR_KEY = android.provider.CalendarContract.Colors.COLOR_KEY; public static final java.lang.String COLOR = android.provider.CalendarContract.Colors.COLOR; } public static interface DataColumns { public static final java.lang.String MIMETYPE = android.provider.ContactsContract.RawContacts.Entity.MIMETYPE; public static final java.lang.String RAW_CONTACT_ID = android.provider.ContactsContract.RawContacts.Entity.RAW_CONTACT_ID; public static final java.lang.String IS_PRIMARY = android.provider.ContactsContract.RawContacts.Entity.IS_PRIMARY; public static final java.lang.String IS_SUPER_PRIMARY = android.provider.ContactsContract.RawContacts.Entity.IS_SUPER_PRIMARY; public static final java.lang.String IS_READ_ONLY = android.provider.ContactsContract.RawContacts.Entity.IS_READ_ONLY; public static final java.lang.String DATA_VERSION = android.provider.ContactsContract.RawContacts.Entity.DATA_VERSION; public static final java.lang.String DATA1 = android.provider.ContactsContract.RawContacts.Entity.DATA1; public static final java.lang.String DATA2 = android.provider.ContactsContract.RawContacts.Entity.DATA2; public static final java.lang.String DATA3 = android.provider.ContactsContract.RawContacts.Entity.DATA3; public static final java.lang.String DATA4 = android.provider.ContactsContract.RawContacts.Entity.DATA4; public static final java.lang.String DATA5 = android.provider.ContactsContract.RawContacts.Entity.DATA5; public static final java.lang.String DATA6 = android.provider.ContactsContract.RawContacts.Entity.DATA6; public static final java.lang.String DATA7 = android.provider.ContactsContract.RawContacts.Entity.DATA7; public static final java.lang.String DATA8 = android.provider.ContactsContract.RawContacts.Entity.DATA8; public static final java.lang.String DATA9 = android.provider.ContactsContract.RawContacts.Entity.DATA9; public static final java.lang.String DATA10 = android.provider.ContactsContract.RawContacts.Entity.DATA10; public static final java.lang.String DATA11 = android.provider.ContactsContract.RawContacts.Entity.DATA11; public static final java.lang.String DATA12 = android.provider.ContactsContract.RawContacts.Entity.DATA12; public static final java.lang.String DATA13 = android.provider.ContactsContract.RawContacts.Entity.DATA13; public static final java.lang.String DATA14 = android.provider.ContactsContract.RawContacts.Entity.DATA14; public static final java.lang.String DATA15 = android.provider.ContactsContract.RawContacts.Entity.DATA15; public static final java.lang.String SYNC1 = android.provider.ContactsContract.RawContacts.Entity.SYNC1; public static final java.lang.String SYNC2 = android.provider.ContactsContract.RawContacts.Entity.SYNC2; public static final java.lang.String SYNC3 = android.provider.ContactsContract.RawContacts.Entity.SYNC3; public static final java.lang.String SYNC4 = android.provider.ContactsContract.RawContacts.Entity.SYNC4; } public static interface ContactsContract_SyncColumns { public static final java.lang.String ACCOUNT_NAME = android.provider.ContactsContract.RawContacts.ACCOUNT_NAME; public static final java.lang.String ACCOUNT_TYPE = android.provider.ContactsContract.RawContacts.ACCOUNT_TYPE; public static final java.lang.String SOURCE_ID = android.provider.ContactsContract.RawContacts.SOURCE_ID; public static final java.lang.String VERSION = android.provider.ContactsContract.RawContacts.VERSION; public static final java.lang.String DIRTY = android.provider.ContactsContract.RawContacts.DIRTY; } public static interface EventsColumns { public static final java.lang.String CALENDAR_ID = android.provider.CalendarContract.Reminders.CALENDAR_ID; public static final java.lang.String TITLE = android.provider.CalendarContract.Reminders.TITLE; public static final java.lang.String DESCRIPTION = android.provider.CalendarContract.Reminders.DESCRIPTION; public static final java.lang.String EVENT_LOCATION = android.provider.CalendarContract.Reminders.EVENT_LOCATION; public static final java.lang.String EVENT_COLOR = android.provider.CalendarContract.Reminders.EVENT_COLOR; public static final java.lang.String EVENT_COLOR_KEY = android.provider.CalendarContract.Reminders.EVENT_COLOR_KEY; public static final java.lang.String DISPLAY_COLOR = android.provider.CalendarContract.Reminders.DISPLAY_COLOR; public static final java.lang.String STATUS = android.provider.CalendarContract.Reminders.STATUS; public static final int STATUS_TENTATIVE = android.provider.CalendarContract.Reminders.STATUS_TENTATIVE; public static final int STATUS_CONFIRMED = android.provider.CalendarContract.Reminders.STATUS_CONFIRMED; public static final int STATUS_CANCELED = android.provider.CalendarContract.Reminders.STATUS_CANCELED; public static final java.lang.String SELF_ATTENDEE_STATUS = android.provider.CalendarContract.Reminders.SELF_ATTENDEE_STATUS; public static final java.lang.String SYNC_DATA1 = android.provider.CalendarContract.Reminders.SYNC_DATA1; public static final java.lang.String SYNC_DATA2 = android.provider.CalendarContract.Reminders.SYNC_DATA2; public static final java.lang.String SYNC_DATA3 = android.provider.CalendarContract.Reminders.SYNC_DATA3; public static final java.lang.String SYNC_DATA4 = android.provider.CalendarContract.Reminders.SYNC_DATA4; public static final java.lang.String SYNC_DATA5 = android.provider.CalendarContract.Reminders.SYNC_DATA5; public static final java.lang.String SYNC_DATA6 = android.provider.CalendarContract.Reminders.SYNC_DATA6; public static final java.lang.String SYNC_DATA7 = android.provider.CalendarContract.Reminders.SYNC_DATA7; public static final java.lang.String SYNC_DATA8 = android.provider.CalendarContract.Reminders.SYNC_DATA8; public static final java.lang.String SYNC_DATA9 = android.provider.CalendarContract.Reminders.SYNC_DATA9; public static final java.lang.String SYNC_DATA10 = android.provider.CalendarContract.Reminders.SYNC_DATA10; public static final java.lang.String LAST_SYNCED = android.provider.CalendarContract.Reminders.LAST_SYNCED; public static final java.lang.String DTSTART = android.provider.CalendarContract.Reminders.DTSTART; public static final java.lang.String DTEND = android.provider.CalendarContract.Reminders.DTEND; public static final java.lang.String DURATION = android.provider.CalendarContract.Reminders.DURATION; public static final java.lang.String EVENT_TIMEZONE = android.provider.CalendarContract.Reminders.EVENT_TIMEZONE; public static final java.lang.String EVENT_END_TIMEZONE = android.provider.CalendarContract.Reminders.EVENT_END_TIMEZONE; public static final java.lang.String ALL_DAY = android.provider.CalendarContract.Reminders.ALL_DAY; public static final java.lang.String ACCESS_LEVEL = android.provider.CalendarContract.Reminders.ACCESS_LEVEL; public static final int ACCESS_DEFAULT = android.provider.CalendarContract.Reminders.ACCESS_DEFAULT; public static final int ACCESS_CONFIDENTIAL = android.provider.CalendarContract.Reminders.ACCESS_CONFIDENTIAL; public static final int ACCESS_PRIVATE = android.provider.CalendarContract.Reminders.ACCESS_PRIVATE; public static final int ACCESS_PUBLIC = android.provider.CalendarContract.Reminders.ACCESS_PUBLIC; public static final java.lang.String AVAILABILITY = android.provider.CalendarContract.Reminders.AVAILABILITY; public static final int AVAILABILITY_BUSY = android.provider.CalendarContract.Reminders.AVAILABILITY_BUSY; public static final int AVAILABILITY_FREE = android.provider.CalendarContract.Reminders.AVAILABILITY_FREE; public static final int AVAILABILITY_TENTATIVE = android.provider.CalendarContract.Reminders.AVAILABILITY_TENTATIVE; public static final java.lang.String HAS_ALARM = android.provider.CalendarContract.Reminders.HAS_ALARM; public static final java.lang.String HAS_EXTENDED_PROPERTIES = android.provider.CalendarContract.Reminders.HAS_EXTENDED_PROPERTIES; public static final java.lang.String RRULE = android.provider.CalendarContract.Reminders.RRULE; public static final java.lang.String RDATE = android.provider.CalendarContract.Reminders.RDATE; public static final java.lang.String EXRULE = android.provider.CalendarContract.Reminders.EXRULE; public static final java.lang.String EXDATE = android.provider.CalendarContract.Reminders.EXDATE; public static final java.lang.String ORIGINAL_ID = android.provider.CalendarContract.Reminders.ORIGINAL_ID; public static final java.lang.String ORIGINAL_SYNC_ID = android.provider.CalendarContract.Reminders.ORIGINAL_SYNC_ID; public static final java.lang.String ORIGINAL_INSTANCE_TIME = android.provider.CalendarContract.Reminders.ORIGINAL_INSTANCE_TIME; public static final java.lang.String ORIGINAL_ALL_DAY = android.provider.CalendarContract.Reminders.ORIGINAL_ALL_DAY; public static final java.lang.String LAST_DATE = android.provider.CalendarContract.Reminders.LAST_DATE; public static final java.lang.String HAS_ATTENDEE_DATA = android.provider.CalendarContract.Reminders.HAS_ATTENDEE_DATA; public static final java.lang.String GUESTS_CAN_MODIFY = android.provider.CalendarContract.Reminders.GUESTS_CAN_MODIFY; public static final java.lang.String GUESTS_CAN_INVITE_OTHERS = android.provider.CalendarContract.Reminders.GUESTS_CAN_INVITE_OTHERS; public static final java.lang.String GUESTS_CAN_SEE_GUESTS = android.provider.CalendarContract.Reminders.GUESTS_CAN_SEE_GUESTS; public static final java.lang.String ORGANIZER = android.provider.CalendarContract.Reminders.ORGANIZER; public static final java.lang.String IS_ORGANIZER = android.provider.CalendarContract.Reminders.IS_ORGANIZER; public static final java.lang.String CAN_INVITE_OTHERS = android.provider.CalendarContract.Reminders.CAN_INVITE_OTHERS; public static final java.lang.String CUSTOM_APP_PACKAGE = android.provider.CalendarContract.Reminders.CUSTOM_APP_PACKAGE; public static final java.lang.String CUSTOM_APP_URI = android.provider.CalendarContract.Reminders.CUSTOM_APP_URI; public static final java.lang.String UID_2445 = android.provider.CalendarContract.Reminders.UID_2445; } public static interface ContactNameColumns { public static final java.lang.String DISPLAY_NAME_SOURCE = android.provider.ContactsContract.RawContacts.DISPLAY_NAME_SOURCE; public static final java.lang.String DISPLAY_NAME_PRIMARY = android.provider.ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY; public static final java.lang.String DISPLAY_NAME_ALTERNATIVE = android.provider.ContactsContract.RawContacts.DISPLAY_NAME_ALTERNATIVE; public static final java.lang.String PHONETIC_NAME_STYLE = android.provider.ContactsContract.RawContacts.PHONETIC_NAME_STYLE; public static final java.lang.String PHONETIC_NAME = android.provider.ContactsContract.RawContacts.PHONETIC_NAME; public static final java.lang.String SORT_KEY_PRIMARY = android.provider.ContactsContract.RawContacts.SORT_KEY_PRIMARY; public static final java.lang.String SORT_KEY_ALTERNATIVE = android.provider.ContactsContract.RawContacts.SORT_KEY_ALTERNATIVE; } public static interface StatusColumns { public static final java.lang.String PRESENCE = android.provider.ContactsContract.Contacts.Entity.PRESENCE; public static final java.lang.String PRESENCE_STATUS = android.provider.ContactsContract.Contacts.Entity.PRESENCE_STATUS; public static final int OFFLINE = android.provider.ContactsContract.Contacts.Entity.OFFLINE; public static final int INVISIBLE = android.provider.ContactsContract.Contacts.Entity.INVISIBLE; public static final int AWAY = android.provider.ContactsContract.Contacts.Entity.AWAY; public static final int IDLE = android.provider.ContactsContract.Contacts.Entity.IDLE; public static final int DO_NOT_DISTURB = android.provider.ContactsContract.Contacts.Entity.DO_NOT_DISTURB; public static final int AVAILABLE = android.provider.ContactsContract.Contacts.Entity.AVAILABLE; public static final java.lang.String STATUS = android.provider.ContactsContract.Contacts.Entity.STATUS; public static final java.lang.String PRESENCE_CUSTOM_STATUS = android.provider.ContactsContract.Contacts.Entity.PRESENCE_CUSTOM_STATUS; public static final java.lang.String STATUS_TIMESTAMP = android.provider.ContactsContract.Contacts.Entity.STATUS_TIMESTAMP; public static final java.lang.String STATUS_RES_PACKAGE = android.provider.ContactsContract.Contacts.Entity.STATUS_RES_PACKAGE; public static final java.lang.String STATUS_LABEL = android.provider.ContactsContract.Contacts.Entity.STATUS_LABEL; public static final java.lang.String STATUS_ICON = android.provider.ContactsContract.Contacts.Entity.STATUS_ICON; public static final java.lang.String CHAT_CAPABILITY = android.provider.ContactsContract.Contacts.Entity.CHAT_CAPABILITY; public static final int CAPABILITY_HAS_VOICE = android.provider.ContactsContract.Contacts.Entity.CAPABILITY_HAS_VOICE; public static final int CAPABILITY_HAS_VIDEO = android.provider.ContactsContract.Contacts.Entity.CAPABILITY_HAS_VIDEO; public static final int CAPABILITY_HAS_CAMERA = android.provider.ContactsContract.Contacts.Entity.CAPABILITY_HAS_CAMERA; } }
apache-2.0
b0ebb5c4757c3b2cd9db8fc767befeaf
95.983827
159
0.787604
4.608685
false
false
false
false
isuPatches/WiseFy
wisefysample/src/main/java/com/isupatches/wisefysample/internal/preferences/AddNetworkStore.kt
1
2761
/* * Copyright 2019 Patches Klinefelter * * 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.isupatches.wisefysample.internal.preferences import android.content.SharedPreferences import androidx.annotation.VisibleForTesting import androidx.core.content.edit import com.isupatches.wisefysample.internal.models.NetworkType @VisibleForTesting internal const val PREF_NETWORK_TYPE = "network type" @VisibleForTesting internal const val PREF_LAST_USED_NETWORK_NAME = "last used network name" @VisibleForTesting internal const val PREF_LAST_USED_NETWORK_PASSWORD = "last used network password" internal interface AddNetworkStore { fun clear() fun getNetworkType(): NetworkType fun getLastUsedNetworkName(): String fun getLastUsedNetworkPassword(): String fun setNetworkType(networkType: NetworkType) fun setLastUsedNetworkName(lastUsedNetworkName: String) fun setLastUsedNetworkPassword(lastUsedNetworkPassword: String) } internal class SharedPreferencesAddNetworkStore( private val sharedPreferences: SharedPreferences ) : AddNetworkStore { override fun clear() { sharedPreferences.edit { clear() } } /* * Network type */ override fun getNetworkType() = NetworkType.of( sharedPreferences.getInt(PREF_NETWORK_TYPE, NetworkType.WPA2.intVal) ) override fun setNetworkType(networkType: NetworkType) { sharedPreferences.edit { putInt(PREF_NETWORK_TYPE, networkType.intVal) } } /* * Last used network name */ override fun getLastUsedNetworkName() = sharedPreferences.getNonNullString( PREF_LAST_USED_NETWORK_NAME ) override fun setLastUsedNetworkName(lastUsedNetworkName: String) { sharedPreferences.edit { putString(PREF_LAST_USED_NETWORK_NAME, lastUsedNetworkName) } } /* * Last used network password */ override fun getLastUsedNetworkPassword() = sharedPreferences.getNonNullString( PREF_LAST_USED_NETWORK_PASSWORD ) override fun setLastUsedNetworkPassword(lastUsedNetworkPassword: String) { sharedPreferences.edit { putString(PREF_LAST_USED_NETWORK_PASSWORD, lastUsedNetworkPassword) } } }
apache-2.0
1b5eb5283e1b7e44d18974d0edb45757
30.375
100
0.732706
4.743986
false
false
false
false
apixandru/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/GrClosureDelegateTypeCalculator.kt
9
1836
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.typing import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.getDelegatesToInfo class GrClosureDelegateTypeCalculator : GrTypeCalculator<GrReferenceExpression> { override fun getType(expression: GrReferenceExpression): PsiType? { val method = expression.resolve() as? PsiMethod ?: return null if ("getDelegate" != method.name || method.parameterList.parametersCount != 0) return null val closureClass = JavaPsiFacade.getInstance(expression.project).findClass(GROOVY_LANG_CLOSURE, expression.resolveScope) if (closureClass == null || closureClass != method.containingClass) return null val closure = PsiTreeUtil.getParentOfType(expression, GrClosableBlock::class.java) ?: return null return getDelegatesToInfo(closure)?.typeToDelegate } }
apache-2.0
1b3a29f447d58be907e37b359f8394dd
46.076923
124
0.79085
4.424096
false
true
false
false
StoneMain/Shortranks
ShortranksCommon/src/main/kotlin/eu/mikroskeem/shortranks/common/scoreboard/AbstractScoreboardTeam.kt
1
4747
/* * This file is part of project Shortranks, licensed under the MIT License (MIT). * * Copyright (c) 2017-2019 Mark Vainomaa <[email protected]> * Copyright (c) Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package eu.mikroskeem.shortranks.common.scoreboard import eu.mikroskeem.shortranks.api.CollisionRule import eu.mikroskeem.shortranks.api.NameTagVisibility import eu.mikroskeem.shortranks.api.ScoreboardTeam import eu.mikroskeem.shortranks.api.player.ShortranksPlayer import eu.mikroskeem.shortranks.common.safe import eu.mikroskeem.shortranks.common.toUnmodifiableList import net.kyori.text.format.TextColor import java.util.UUID import java.util.concurrent.atomic.AtomicInteger /** * @author Mark Vainomaa */ private val TEAM_ID_COUNTER = AtomicInteger(0) abstract class AbstractScoreboardTeam<P>(private val player: ShortranksPlayer<P>): ScoreboardTeam { @get:JvmName("_GteamName") protected val teamName = "SR~~${TEAM_ID_COUNTER.getAndIncrement()}" @get:JvmName("_Gprefix") @set:JvmName("_Sprefix") protected var prefix: String = "" @get:JvmName("_Gsuffix") @set:JvmName("_Ssuffix") protected var suffix: String = "" @get:JvmName("_Gmembers") protected val members = HashSet<String>() @get:JvmName("_Gcolor") @set:JvmName("_Scolor") protected var color: TextColor = TextColor.WHITE @get:JvmName("_GallowFriendlyFire") @set:JvmName("_SallowFriendlyFire") protected var allowFriendlyFire = false @get:JvmName("_GcanSeeFriendlyInvisibles") @set:JvmName("_ScanSeeFriendlyInvisibles") protected var canSeeFriendlyInvisibles = false @get:JvmName("_GcollisionRule") @set:JvmName("_ScollisionRule") protected var collisionRule = CollisionRule.PUSH_OTHER_TEAMS @get:JvmName("_GnameTagVisibility") @set:JvmName("_SnameTagVisibility") protected var nameTagVisibility = NameTagVisibility.ALWAYS override fun toString() = "${this.javaClass.name}(" + "teamOwnerPlayer=$teamOwnerPlayer, " + "teamName='$teamName', " + "prefix='${prefix.safe()}', " + "suffix='${suffix.safe()}', " + "members=$members, " + "color=${color.name}, " + "allowFriendlyFire=$isAllowingFriendlyFire, " + "canSeeFriendlyInvisibles=${canSeeFriendlyInvisibles()}, " + "collisionRule=$collisionRule, " + "nameTagVisibility=$nameTagVisibility" + ")" override fun getTeamOwnerPlayer(): UUID = player.uniqueId override fun getTeamName() = teamName override fun getPrefix() = prefix override fun getSuffix() = suffix override fun getMembers(): List<String> = members.toUnmodifiableList() override fun setPrefix(prefix: String) { this.prefix = prefix } override fun setSuffix(suffix: String) { this.suffix = suffix } override fun getTeamColor() = color override fun setTeamColor(color: TextColor) { this.color = color } override fun isAllowingFriendlyFire() = allowFriendlyFire override fun setAllowingFriendlyFire(allowFriendlyFire: Boolean) { this.allowFriendlyFire = allowFriendlyFire } override fun canSeeFriendlyInvisibles() = canSeeFriendlyInvisibles override fun setCanSeeFriendlyInvisibles(canSeeFriendlyInvisibles: Boolean) { this.canSeeFriendlyInvisibles = canSeeFriendlyInvisibles } override fun getCollisionRule() = collisionRule override fun setCollisionRule(collisionRule: CollisionRule) { this.collisionRule = collisionRule } override fun getNameTagVisibility() = nameTagVisibility override fun setNameTagVisibility(nameTagVisibility: NameTagVisibility) { this.nameTagVisibility = nameTagVisibility } }
mit
e100893da23b5244bdd77a64cc7b657f
42.962963
140
0.733937
4.303717
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/util/version/Version.kt
1
1071
package ffc.app.util.version import java.util.regex.Pattern class Version(name: String) : Comparable<Version> { val major: Int val minor: Int val patch: Int init { val pattern = Pattern.compile("^v?(\\d+\\.)(\\d+\\.)(\\*|\\d+)(.*)") val matcher = pattern.matcher(name.trim()) if (matcher.matches()) { major = Integer.parseInt(matcher.group(1).replace(".", "")) minor = Integer.parseInt(matcher.group(2).replace(".", "")) patch = Integer.parseInt(matcher.group(3)) } else { throw IllegalArgumentException("version name not match pattern $name") } } override fun compareTo(other: Version): Int { val major = Integer.compare(this.major, other.major) if (major != 0) return major val cMinor = Integer.compare(minor, other.minor) return if (cMinor != 0) cMinor else Integer.compare(patch, other.patch) } override fun toString(): String { return major.toString() + "." + minor + "." + patch } }
apache-2.0
4bd9be7b6a8bf9f34833515cebdb0a79
30.5
82
0.577965
4.072243
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/util/extensions/Fragment.kt
2
1113
package chat.rocket.android.util.extensions import android.os.Looper import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch inline fun Fragment.ui(crossinline block: (activity: FragmentActivity) -> Unit): Job? { // Checking first for activity and view saves us from some synchronyzed and thread local checks if (activity != null && view != null && context != null) { // If we already are running on the Main Thread (UI Thread), just go ahead and execute the block return if (Looper.getMainLooper() == Looper.myLooper()) { block(activity!!) null } else { // Launch a Job on the UI context and check again if the activity and view are still valid GlobalScope.launch(Dispatchers.Main) { if (activity != null && view != null && context != null) { block(activity!!) } } } } return null }
mit
1a589c9247f37238ed05e9eed036949e
37.413793
104
0.652291
4.797414
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/holder/AccountViewHolder.kt
1
3403
/* * 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.view.holder import android.support.v7.widget.RecyclerView import android.view.View import android.widget.CompoundButton import android.widget.ImageView import android.widget.TextView import org.mariotaku.ktextension.spannable import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.AccountDetailsAdapter import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.util.AccountUtils import de.vanita5.twittnuker.view.ProfileImageView import de.vanita5.twittnuker.view.iface.IColorLabelView class AccountViewHolder( val adapter: AccountDetailsAdapter, itemView: View ) : RecyclerView.ViewHolder(itemView) { private val content = itemView as IColorLabelView private val name: TextView = itemView.findViewById(android.R.id.text1) private val screenName: TextView = itemView.findViewById(android.R.id.text2) private val profileImage: ProfileImageView = itemView.findViewById(android.R.id.icon) private val toggle: CompoundButton = itemView.findViewById(android.R.id.toggle) private val toggleContainer: View = itemView.findViewById(R.id.toggle_container) private val accountType: ImageView = itemView.findViewById(R.id.account_type) private val dragHandle: View = itemView.findViewById(R.id.drag_handle) init { profileImage.style = adapter.profileImageStyle } fun setAccountColor(color: Int) { content.drawEnd(color) } fun setSortEnabled(enabled: Boolean) { dragHandle.visibility = if (enabled) View.VISIBLE else View.GONE } fun display(details: AccountDetails) { name.spannable = details.user.name screenName.spannable = "@${details.user.screen_name}" setAccountColor(details.color) profileImage.visibility = View.VISIBLE adapter.requestManager.loadProfileImage(adapter.context, details, adapter.profileImageStyle, profileImage.cornerRadius, profileImage.cornerRadiusRatio).into(profileImage) accountType.setImageResource(AccountUtils.getAccountTypeIcon(details.type)) toggle.setOnCheckedChangeListener(null) toggle.isChecked = details.activated toggle.setOnCheckedChangeListener(adapter.checkedChangeListener) toggle.tag = layoutPosition toggleContainer.visibility = if (adapter.switchEnabled) View.VISIBLE else View.GONE setSortEnabled(adapter.sortEnabled) } }
gpl-3.0
94cfb3969bf37bb0a962c53b2c5497da
41.55
100
0.756685
4.318528
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/activity/CreateCardSourceActivity.kt
1
7459
package com.stripe.example.activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.stripe.android.ApiResultCallback import com.stripe.android.Stripe import com.stripe.android.model.CardBrand import com.stripe.android.model.CardParams import com.stripe.android.model.Source import com.stripe.android.model.SourceParams import com.stripe.android.model.SourceTypeModel import com.stripe.example.R import com.stripe.example.StripeFactory import com.stripe.example.adapter.SourcesAdapter import com.stripe.example.databinding.CreateCardSourceActivityBinding /** * Activity that lets you redirect for a 3DS source verification. */ class CreateCardSourceActivity : AppCompatActivity() { private val viewBinding: CreateCardSourceActivityBinding by lazy { CreateCardSourceActivityBinding.inflate(layoutInflater) } private val viewModel: SourceViewModel by viewModels() private val sourcesAdapter: SourcesAdapter by lazy { SourcesAdapter() } private val stripe: Stripe by lazy { StripeFactory(this).create() } private val keyboardController: KeyboardController by lazy { KeyboardController(this) } private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } private var alertDialog: AlertDialog? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewBinding.createButton.setOnClickListener { // If a field is invalid this will shift focus to that field viewBinding.cardWidget.cardParams?.let { createCardSource(it) } ?: showSnackbar("Enter a valid card.") } viewBinding.cardWidget.setCardValidCallback { isValid, invalidFields -> // We will not call cardParams unless it is valid because // this will cause the inFocus field to change. if (isValid) { Log.e("STRIPE", "Validity: $isValid, ${viewBinding.cardWidget.cardParams}") } else { Log.e("STRIPE", "Validity: $isValid, invalidField: $invalidFields") } } viewBinding.recyclerView.setHasFixedSize(true) viewBinding.recyclerView.layoutManager = LinearLayoutManager(this) viewBinding.recyclerView.adapter = sourcesAdapter } @Deprecated("Deprecated in Java") override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data != null && stripe.isAuthenticateSourceResult(requestCode, data)) { stripe.onAuthenticateSourceResult( data, object : ApiResultCallback<Source> { override fun onSuccess(result: Source) { sourcesAdapter.addSource(result) } override fun onError(e: Exception) { showSnackbar(e.message.orEmpty()) } } ) } } override fun onPause() { alertDialog?.dismiss() alertDialog = null super.onPause() } /** * To start the 3DS cycle, create a [Source] out of the user-entered [CardParams]. * * @param cardParams the [CardParams] used to create a source */ private fun createCardSource(cardParams: CardParams) { keyboardController.hide() viewBinding.createButton.isEnabled = false viewBinding.progressBar.visibility = View.VISIBLE val params = SourceParams.createCardParams(cardParams) viewModel.createSource(params).observe( this, { result -> viewBinding.createButton.isEnabled = true viewBinding.progressBar.visibility = View.INVISIBLE result.fold( onSuccess = ::onSourceCreated, onFailure = { showSnackbar(it.message.orEmpty()) } ) } ) } private fun onSourceCreated(source: Source) { // Because we've made the mapping above, we're now subscribing // to the result of creating a 3DS Source val cardData = source.sourceTypeModel as SourceTypeModel.Card // Making a note of the Card Source in our list. sourcesAdapter.addSource(source) // If we need to get 3DS verification for this card, we first create a 3DS Source. if (SourceTypeModel.Card.ThreeDSecureStatus.Required == cardData.threeDSecureStatus) { // The card Source can be used to create a 3DS Source createThreeDSecureSource(source) } } /** * Create the 3DS Source as a separate call to the API. This is what is needed * to verify the third-party approval. The only information from the Card source * that is used is the ID field. * * @param source the [CardParams]-created [Source]. */ private fun createThreeDSecureSource(source: Source) { // This represents a request for a 3DS purchase of 10.00 euro. val params = SourceParams.createThreeDSecureParams( amount = 1000L, currency = "EUR", returnUrl = RETURN_URL, cardId = source.id.orEmpty() ) viewModel.createSource(params).observe( this, { result -> viewBinding.progressBar.visibility = View.INVISIBLE result.fold( onSuccess = ::authenticateSource, onFailure = { showSnackbar(it.message.orEmpty()) } ) } ) } /** * Authenticate the [Source] */ private fun authenticateSource(source: Source) { if (source.flow == Source.Flow.Redirect) { createAuthenticateSourceDialog(source).let { alertDialog = it it.show() } } } private fun createAuthenticateSourceDialog(source: Source): AlertDialog { val typeData = source.sourceTypeData.orEmpty() val cardBrand = CardBrand.fromCode(typeData["brand"] as String?) return MaterialAlertDialogBuilder(this) .setTitle(this.getString(R.string.authentication_dialog_title)) .setMessage( getString( R.string.authentication_dialog_message, cardBrand.displayName, typeData["last4"] ) ) .setIcon(cardBrand.icon) .setPositiveButton(android.R.string.ok) { _, _ -> stripe.authenticateSource(this, source) } .setNegativeButton(android.R.string.cancel, null) .create() } private fun showSnackbar(message: String) { snackbarController.show(message) } private companion object { private const val RETURN_URL = "stripe://source_activity" } }
mit
bb272a1d7095c11658bc3249a37148d7
34.018779
137
0.624615
5.050102
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/GenerationAlgo.kt
1
17704
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * 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.sudoq.model.solverGenerator import de.sudoq.model.solverGenerator.FastSolver.BranchAndBound.FastBranchAndBound import de.sudoq.model.solverGenerator.FastSolver.FastSolverFactory import de.sudoq.model.solverGenerator.solution.SolveDerivation import de.sudoq.model.solverGenerator.solver.ComplexityRelation import de.sudoq.model.solverGenerator.solver.Solver import de.sudoq.model.sudoku.* import de.sudoq.model.sudoku.complexity.ComplexityConstraint import de.sudoq.model.sudoku.sudokuTypes.SudokuType import java.util.* /** * Bietet die Möglichkeit Sudokus zu generieren. * Die Klasse implementiert das [Runnable] interface * und kann daher in einem eigenen Thread ausgeführt werden. * * @property sudoku Das Sudoku auf welchem die Generierung ausgeführt wird * @property Das Objekt, auf dem nach Abschluss der Generierung die Callback-Methode aufgerufen wird */ class GenerationAlgo( private var sudoku: Sudoku, private var callbackObject: GeneratorCallback, random: Random ) : Runnable { /** * Das Zufallsobjekt für den Generator */ private var random: Random = random /** * Der Solver, der für Validierungsvorgänge genutzt wird */ private var solver: Solver = Solver(sudoku) /** * List of currently defined(occupied) Fields. * If we gave the current sudoku to the user tey wouldn't have to solve these fields * as they'd already be filled in. */ private var definedCells: MutableList<Position> = ArrayList() /** * Die noch freien, also nicht belegten Felder des Sudokus */ private var freeCells: MutableList<Position> = ArrayList(getPositions(sudoku)) /** * Das gelöste Sudoku */ private var solvedSudoku: Sudoku? = null /** * Die Anzahl der Felder, die fest zu definieren ist */ private var cellsToDefine = 0 /** * Anzahl aktuell definierter Felder */ //private int currentFieldsDefined; /** * ComplexityConstraint für ein Sudoku des definierten * Schwierigkeitsgrades */ private val desiredComplexityConstraint: ComplexityConstraint? = sudoku.sudokuType!!.buildComplexityConstraint(sudoku.complexity) /** * Die Methode, die die tatsächliche Generierung eines Sudokus mit der * gewünschten Komplexität generiert. */ override fun run() { /* 1. Finde Totalbelegung */ solvedSudoku = createSudokuPattern() createAllocation(solvedSudoku!!) // Call the callback val suBi = SudokuBuilder(sudoku.sudokuType) for (p in getPositions(solvedSudoku!!)) { val value = solvedSudoku!!.getCell(p)!!.solution suBi.addSolution(p, value) if (!sudoku.getCell(p)!!.isNotSolved) suBi.setFixed(p) } val res = suBi.createSudoku() //we want to know the solutions used, so quickly an additional solver val quickSolver = Solver(res) quickSolver.solveAll(true, false, false) res.complexity = sudoku.complexity if (callbackObject.toString() == "experiment") { callbackObject.generationFinished(res, quickSolver.solutions!!) } else { callbackObject.generationFinished(res) } } private fun createSudokuPattern(): Sudoku { //determine ideal number of prefilled fields cellsToDefine = getNumberOfCellsToDefine(sudoku.sudokuType, desiredComplexityConstraint) //A mapping from position to solution var solution = PositionMap<Int?>(sudoku.sudokuType!!.size!!) val iteration = 0 //System.out.println("Fields to define: "+fieldsToDefine); //define fields repeat(cellsToDefine + 1) { addDefinedCell() } var fieldsToDefineDynamic = cellsToDefine /* until a solution is found, remove 5 random fields and add new ones */ var fs = FastSolverFactory.getSolver(sudoku) while (!fs.hasSolution()) { //System.out.println("Iteration: "+(iteration++)+", defined Fields: "+definedFields.size()); // Remove some fields, because sudoku could not be validated removeDefinedCells(5) // Define average number of fields while (definedCells.size < fieldsToDefineDynamic) if (addDefinedCell() == null) //try to add field, if null returned i.e. nospace / invalid removeDefinedCells(5) //remove 5 fields if (fieldsToDefineDynamic > 0 && random.nextFloat() < 0.2) fieldsToDefineDynamic-- //to avoid infinite loop slowly relax fs = FastSolverFactory.getSolver(sudoku) } /* we found a solution i.e. a combination of nxn numbers that fulfill all constraints */ /* not sure what's happening why tmp-save complexity? is it ever read? maybe in solveall? maybe this is from previous debugging, wanting to see if it's invalid here already solver.validate is definitely needed but the complexity is from the superclass `Sudoku`, SolverSudoku has its own `complexityValue`... */ //PositionMap<Integer> solution2 = solver.getSudoku().getField(); //solution is filled with correct solution solution = fs.solutions /* We have (validated) filled `solution` with the right values */ // Create the sudoku template generated before val sub = SudokuBuilder(sudoku.sudokuType) for (p in getPositions(sudoku)) sub.addSolution(p, solution[p]!!) //fill in all solutions return sub.createSudoku() } private fun createAllocation(pattern: Sudoku) { //ensure all fields are defined while (freeCells.isNotEmpty()) { definedCells.add(freeCells.removeAt(0)) } // Fill the sudoku being generated with template solutions //TODO simplify: iterate over fields/positions for (pos in getPositions(sudoku)) { val fSudoku = sudoku.getCell(pos) val fSolved = pattern.getCell(pos) fSudoku!!.setCurrentValue(fSolved!!.solution, false) } val reallocationAmount = 2 //getReallocationAmount(sudoku.getSudokuType(), 0.05); var plusminuscounter = 0 var rel = ComplexityRelation.INVALID while (rel !== ComplexityRelation.CONSTRAINT_SATURATION) { //every 1000 steps choose another random subset if (plusminuscounter % 1000 == 0 && plusminuscounter > 0) { //while (!this.freeFields.isEmpty()) { // this.definedFields.add(this.freeFields.remove(0)); //} removeDefinedCells(definedCells.size) for (i in 0 until cellsToDefine) { addDefinedCell2() } } sudoku = removeAmbiguity(sudoku) //System.out.println(sudoku); /*solver = new Solver(sudoku); System.out.println("validate:"); rel = solver.validate(null); System.out.println("validate says: " + rel);*/ //fast validation where after 10 branchpoints we return too diificult val solver = FastBranchAndBound(sudoku) rel = solver.validate() when (rel) { ComplexityRelation.MUCH_TOO_EASY -> removeDefinedCells(reallocationAmount) ComplexityRelation.TOO_EASY -> removeDefinedCells(1) ComplexityRelation.INVALID, ComplexityRelation.TOO_DIFFICULT, ComplexityRelation.MUCH_TOO_DIFFICULT -> { var i = 0 while (i < reallocationAmount.coerceAtMost(freeCells.size)) { addDefinedCell2() i++ } } } plusminuscounter++ } } /* * While there are 2 solutions, add solution that is different in second sudoku * Careful! If looking for the 2nd solution takes longer than x min, sudoku is declared unambiguous */ private fun removeAmbiguity(sudoku: Sudoku): Sudoku { var fs = FastSolverFactory.getSolver(sudoku) //samurai take a long time -> try without uniqueness constraint //if (sudoku.getSudokuType().getEnumType() != SudokuTypes.samurai) while (fs.isAmbiguous) { val p = fs.ambiguousPos addDefinedCell2(p) fs = FastSolverFactory.getSolver(sudoku) } return sudoku } private fun reduceStringList(sl: List<String>): String { if (sl.isEmpty()) return "[]" else if (sl.size == 1) return "[" + sl[0] + "]" var s = "" val i = sl.iterator() var counter = 1 var last = i.next() while (i.hasNext()) { val current = i.next() if (last == current) counter++ else { s += ", $counter*$last" last = current counter = 0 } } s += ", $counter*$last" return '['.toString() + s.substring(2) + ']' } private fun gettypes(dl: List<SolveDerivation>): List<String> { val sl: MutableList<String> = Stack() for (sd in dl) { sl.add(sd.type.toString()) //sl.add(sd.toString()); } return sl } // Calculate the number of fields to be filled // the number is determined as the smaller of // - the standard allocation factor defined in the type // - the average #fields per difficulty level defined in the type private fun getNumberOfCellsToDefine( type: SudokuType?, desiredComplexityConstraint: ComplexityConstraint? ): Int { //TODO What do we have the allocation factor for??? can't it always be expressed through avg-fields? val standardAllocationFactor = type!!.getStandardAllocationFactor() val cellsOnSudokuBoard = type.size!!.x * type.size!!.y val cellsByType = (cellsOnSudokuBoard * standardAllocationFactor).toInt() //TODO wäre freeFields.size nicht passender? val cellsByComp = desiredComplexityConstraint!!.averageCells return Math.min(cellsByType, cellsByComp) } /** returns `percentage` percent of the #positions in the type * e.g. for standard 9x9 and 0.5 -> 40 */ private fun getReallocationAmount(st: SudokuType, percentage: Double): Int { var numberOfPositions = 0 for (p in sudoku.sudokuType!!.validPositions) numberOfPositions++ val reallocationAmount = (numberOfPositions * percentage).toInt() //remove/delete up to 10% of board return Math.max(1, reallocationAmount) // at least 1 } /** * Definiert ein weiteres Feld, sodass weiterhin Constraint Saturation * vorhanden ist. Die Position des definierten Feldes wird * zurückgegeben. Kann keines gefunden werden, so wird null * zurückgegeben. * * This method is to be used for initialization only, once a solution is found * please use addDefinedField2, with just chooses a free field to define * and assumes constraint saturation. * * @return Die Position des definierten Feldes oder null, falls keines * gefunden wurde */ private fun addDefinedCell(): Position? { //TODO not sure what they do val xSize = sudoku.sudokuType!!.size!!.x val ySize = sudoku.sudokuType!!.size!!.y // Ein Array von Markierungen zum Testen, welches Felder belegt werden können /*true means marked, i.e. already defined or not part of the game e.g. 0,10 for samurai *false means can be added */ val markings = Array(xSize) { BooleanArray(ySize) } //all false by default. //definierte Felder markieren for (p in definedCells) { markings[p.x][p.y] = true } /* avoids infitite while loop*/ var count = definedCells.size //find random {@code Position} p var p: Position? = null while (p == null && count < xSize * ySize) { val x = random.nextInt(xSize) val y = random.nextInt(ySize) if (sudoku.getCell(Position[x, y]) == null) { //position existiert nicht markings[x][y] = true count++ } else if (!markings[x][y]) { //pos existiert und ist unmarkiert p = Position[x, y] } } //construct a list of symbols starting at arbitrary point. there is no short way to do this without '%' val numSym = sudoku.sudokuType!!.numberOfSymbols val offset = random.nextInt(numSym) val symbols: Queue<Int> = LinkedList() for (i in 0 until numSym) symbols.add(i) for (i in 0 until offset) //rotate offset times symbols.add(symbols.poll()) //constraint-saturierende belegung suchen var valid = false for (s in symbols) { sudoku.getCell(p!!)!!.setCurrentValue(s, false) //alle constraints saturiert? valid = sudoku.sudokuType!!.all { it.isSaturated(sudoku) } if (!valid) sudoku.getCell(p)!!.setCurrentValue(Cell.EMPTYVAL, false) if (valid) { definedCells.add(p) freeCells.remove(p) //if it's defined it is no longer free break } } if (!valid) p = null return p } /** * choses a random free field and sets it as defined */ private fun addDefinedCell2(i: Int = random.nextInt(freeCells.size)) { val p = freeCells.removeAt(i) //used to be 0, random just in case val fSudoku = sudoku.getCell(p) val fSolved = solvedSudoku!!.getCell(p) fSudoku!!.setCurrentValue(fSolved!!.solution, false) definedCells.add(p) } private fun addDefinedCell2(p: Position) { val i = freeCells.indexOf(p) require(i >= 0) { "position is not free, so it cannot be defined." } addDefinedCell2(i) } /** * Removes one of the defined fields (random selection) * * @return position of removed field or null is nothing there to remove */ private fun removeDefinedCell(): Position? { if (definedCells.isEmpty()) return null val nr = random.nextInt(definedCells.size) val p = definedCells.removeAt(nr) sudoku.getCell(p)!!.setCurrentValue(Cell.EMPTYVAL, false) freeCells.add(p) return p } /** * Tries `numberOfFieldsToRemove` times to remove a defined field * @param numberOfCellsToRemove number of fields to remove * @return list of removed positions */ private fun removeDefinedCells(numberOfCellsToRemove: Int): List<Position> { return (0 until numberOfCellsToRemove).mapNotNull { removeDefinedCell() } } /* debugging, remove when done */ fun printDebugMsg() { println("This is the debug message from `Generator`") } /*fun saveSudokuAllInOne(path: String, filename: String, sudoku: Sudoku) { FileManager.initialize(File(path)) object : SudokuXmlHandler() { override fun getFileFor(s: Sudoku): File { return File(path + File.separator + filename) } override fun modifySaveTree(tree: XmlTree) { tree.addAttribute(XmlAttribute("id", "42")) } }.saveAsXml(sudoku) }*/ companion object { /** * returns all positions of non-null Fields of sudoku * @param sudoku a sudoku object * * @return list of positions whose corresponding `Field` objects are not null */ @JvmStatic ///todo Generator has same function... fun getPositions(sudoku: Sudoku): List<Position> { val p: MutableList<Position> = ArrayList() for (x in 0 until sudoku.sudokuType!!.size!!.x) for (y in 0 until sudoku.sudokuType!!.size!!.y) if (sudoku.getCell(Position[x, y]) != null) p.add(Position[x, y]) return p } //nono usage found /*fun getSudoku(path: String, st: SudokuTypes): Sudoku? { Profile.getInstance(File("/home/t/Code/SudoQ/DebugOnPC/profilefiles"))//todo is this used by the app??? try to delete FileManager.initialize( File("/home/t/Code/SudoQ/sudoq-app/sudoqapp/src/main/assets/sudokus/")) val f = File(path) val s = Sudoku(getSudokuType(st)!!) try { s.fillFromXml(XmlHelper().loadXml(f)!!) s.complexity = Complexity.arbitrary //justincase return s } catch (e: IOException) { e.printStackTrace() } return null }*/ } }
gpl-3.0
95af056d38e42ba1297c6ab40b5b89a6
37.622271
243
0.621777
4.360947
false
false
false
false
TeamWizardry/LibrarianLib
modules/facade/src/test/kotlin/com/teamwizardry/librarianlib/facade/test/screens/pastry/tests/PastryTestDynamicBackground.kt
1
3088
package com.teamwizardry.librarianlib.facade.test.screens.pastry.tests import com.teamwizardry.librarianlib.core.util.vec import com.teamwizardry.librarianlib.etcetera.eventbus.Hook import com.teamwizardry.librarianlib.facade.layer.GuiLayer import com.teamwizardry.librarianlib.facade.layer.GuiLayerEvents import com.teamwizardry.librarianlib.facade.layers.RectLayer import com.teamwizardry.librarianlib.facade.pastry.PastryBackgroundStyle import com.teamwizardry.librarianlib.facade.pastry.layers.PastryButton import com.teamwizardry.librarianlib.facade.pastry.layers.PastryDynamicBackground import com.teamwizardry.librarianlib.facade.pastry.layers.PastryLabel import com.teamwizardry.librarianlib.facade.pastry.layers.dropdown.DropdownTextItem import com.teamwizardry.librarianlib.facade.pastry.layers.dropdown.PastryDropdown import com.teamwizardry.librarianlib.facade.test.screens.pastry.PastryTestBase import com.teamwizardry.librarianlib.math.Vec2d import java.awt.Color import kotlin.math.max import kotlin.math.min class PastryTestDynamicBackground: PastryTestBase() { init { val background = DynamicBackgroundTestLayer() val dropdown: PastryDropdown<PastryBackgroundStyle> val stacks = PastryBackgroundStyle.values().toList() val dropdownWidth = PastryBackgroundStyle.values().map { PastryLabel(0, 0, it.name).widthi }.maxOrNull() ?: 50 dropdown = PastryDropdown(0, 0, dropdownWidth + 15) { background.background.style = it } dropdown.items.addAll(stacks.map { DropdownTextItem(it, it.name) }) dropdown.select(PastryBackgroundStyle.VANILLA) this.stack.add(dropdown, PastryButton("Reset", 0, 0) { background.reset() }, background) } class DynamicBackgroundTestLayer(): GuiLayer(0, 0, 175, 150) { var dragStart: Vec2d? = null var colorBG = RectLayer(Color.MAGENTA, widthi, heighti) var background = PastryDynamicBackground() init { this.add(colorBG, background) } fun reset() { background.forEachChild { it.removeFromParent() } background.shapeLayers.clear() } @Hook fun mouseDown(e: GuiLayerEvents.MouseDown) { if(!mouseOver) return dragStart = mousePos.round() } @Hook fun mouseUp(e: GuiLayerEvents.MouseUp) { dragStart?.also { dragStart -> val dragEnd = mousePos.round() val dragMin = vec(min(dragStart.x, dragEnd.x), min(dragStart.y, dragEnd.y)) val dragMax = vec(max(dragStart.x, dragEnd.x), max(dragStart.y, dragEnd.y)) val dragSize = dragMax - dragMin if(dragSize != vec(0, 0)) { val layer = GuiLayer() layer.pos = dragMin layer.size = dragSize background.add(layer) background.addShapeLayers(layer) } } dragStart = null } } }
lgpl-3.0
67583b9ac8a5d503471e3f9f5dce28e6
37.6125
96
0.665479
4.373938
false
true
false
false
Jonatino/JOGL2D
src/main/kotlin/org/anglur/joglext/jogl2d/GLGraphics2D.kt
1
14592
/* * Copyright 2016 Jonathan Beaudoin <https://github.com/Jonatino> * * 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.anglur.joglext.jogl2d import com.jogamp.opengl.GL import com.jogamp.opengl.GLContext import com.jogamp.opengl.GLDrawable import org.anglur.joglext.cacheable.CachedList import org.anglur.joglext.jogl2d.impl.GLGraphicsConfiguration import org.anglur.joglext.jogl2d.impl.gl2.* import java.awt.* import java.awt.RenderingHints.Key import java.awt.font.GlyphVector import java.awt.geom.AffineTransform import java.awt.geom.NoninvertibleTransformException import java.awt.geom.Rectangle2D import java.awt.image.BufferedImage import java.awt.image.BufferedImageOp import java.awt.image.ImageObserver import java.awt.image.RenderedImage import java.awt.image.renderable.RenderableImage import java.text.AttributedCharacterIterator import java.util.logging.Level import java.util.logging.Logger /** * Implements the standard `Graphics2D` functionality, but instead draws * to an OpenGL canvas. */ class GLGraphics2D : Graphics2D(), Cloneable { /** * The parent graphics object, if we have one. This reference is used to pass * control back to the parent. */ private var parent: GLGraphics2D? = null /** * When we are painting, this is the drawable/context we're painting into. */ private lateinit var glDrawable: GLDrawable lateinit var glContext: GLContext /** * Ensures we only dispose() once. */ private var isDisposed: Boolean = false /** * Keeps the current viewport height for things like painting text. */ var canvasHeight: Int = 0 private set /** * All the drawing helpers or listeners to drawing events. */ private var helpers = CachedList<G2DDrawingHelper>(5) /* * The following are specific drawing helpers used explicitly. */ val shapeHelper = addG2DDrawingHelper(GL2ShapeDrawer()) as GLG2DShapeHelper val imageHelper = addG2DDrawingHelper(GL2ImageDrawer()) as GLG2DImageHelper val stringHelper = addG2DDrawingHelper(GL2StringDrawer()) as GLG2DTextHelper val matrixHelper = addG2DDrawingHelper(GL2Transformhelper()) as GLG2DTransformHelper val colorHelper = addG2DDrawingHelper(GL2ColorHelper()) as GL2ColorHelper /** * The current clip rectangle. This implementation supports only rectangular * clip areas. This clip must be treated as immutable and replaced but never * changed. */ private var clip: Rectangle? = null private lateinit var graphicsConfig: GraphicsConfiguration /** * The set of cached hints for this graphics object. */ private var hints = RenderingHints(emptyMap<Key, Any>()) fun addG2DDrawingHelper(helper: G2DDrawingHelper): G2DDrawingHelper { helpers.add(helper) return helper } fun removeG2DDrawingHelper(helper: G2DDrawingHelper) = helpers.remove(helper) private fun setCanvas(context: GLContext) { glDrawable = context.glDrawable glContext = context for (helper in helpers) { helper.setG2D(this) } } /** * Sets up the graphics object in preparation for drawing. Initialization such * as getting the viewport */ fun prePaint(context: GLContext) { canvasHeight = GLG2DUtils.getViewportHeight(context.gl) setCanvas(context) setDefaultState() } companion object { private val defaultFont = Font("Arial", Font.PLAIN, 12) private val defaultStroke = BasicStroke() } private fun setDefaultState() { background = Color.black color = Color.white font = defaultFont stroke = defaultStroke composite = AlphaComposite.SrcOver setClip(null) setRenderingHints(null) graphicsConfig = GLGraphicsConfiguration.setDrawable(glDrawable) } fun postPaint() { // could glFlush here, but not necessary } fun glDispose() { for (helper in helpers) { helper.dispose() } } override fun draw(s: Shape) = shapeHelper.draw(s) override fun drawString(str: String, x: Int, y: Int) = stringHelper.drawString(str, x, y) override fun drawString(str: String, x: Float, y: Float) = stringHelper.drawString(str, x, y) override fun drawString(iterator: AttributedCharacterIterator, x: Int, y: Int) = stringHelper.drawString(iterator, x, y) override fun drawString(iterator: AttributedCharacterIterator, x: Float, y: Float) = stringHelper.drawString(iterator, x, y) override fun drawGlyphVector(g: GlyphVector, x: Float, y: Float) = shapeHelper.fill(g.getOutline(x, y)) override fun fill(s: Shape) = shapeHelper.fill(s) override fun hit(rect: Rectangle, s: Shape, onStroke: Boolean): Boolean { var rect = rect var s = s if (clip != null) { rect = clip!!.intersection(rect) } if (rect.isEmpty) { return false } if (onStroke) { s = shapeHelper.stroke.createStrokedShape(s) } s = transform.createTransformedShape(s) return s.intersects(rect) } override fun getDeviceConfiguration() = graphicsConfig override fun getComposite() = colorHelper.composite override fun setComposite(comp: Composite) { colorHelper.composite = comp } override fun setPaint(paint: Paint) { colorHelper.paint = paint } override fun setRenderingHint(hintKey: Key, hintValue: Any) { if (!hintKey.isCompatibleValue(hintValue)) { throw IllegalArgumentException("$hintValue is not compatible with $hintKey") } else { for (helper in helpers) { helper.setHint(hintKey, hintValue) } } } override fun getRenderingHint(hintKey: Key) = hints[hintKey] override fun setRenderingHints(hints: Map<*, *>?) { resetRenderingHints() if (hints != null) { addRenderingHints(hints) } } private fun resetRenderingHints() { hints.clear() for (helper in helpers) { helper.resetHints() } } override fun addRenderingHints(hints: Map<*, *>) { for ((key, value) in hints) { if (key is Key) { setRenderingHint(key, value!!) } } } override fun getRenderingHints() = hints override fun translate(x: Int, y: Int) = matrixHelper.translate(x, y) override fun translate(x: Double, y: Double) = matrixHelper.translate(x, y) override fun rotate(theta: Double) = matrixHelper.rotate(theta) override fun rotate(theta: Double, x: Double, y: Double) = matrixHelper.rotate(theta, x, y) override fun scale(sx: Double, sy: Double) = matrixHelper.scale(sx, sy) override fun shear(shx: Double, shy: Double) = matrixHelper.shear(shx, shy) override fun transform(Tx: AffineTransform) = matrixHelper.transform(Tx) override fun setTransform(transform: AffineTransform) { matrixHelper.transform = transform } override fun getTransform() = matrixHelper.transform override fun getPaint() = colorHelper.paint override fun getColor() = colorHelper.color override fun setColor(c: Color) { colorHelper.color = c } override fun setBackground(color: Color) { colorHelper.background = color } override fun getBackground() = colorHelper.background override fun getStroke() = shapeHelper.stroke override fun setStroke(s: Stroke) { shapeHelper.stroke = s } override fun setPaintMode() = colorHelper.setPaintMode() override fun setXORMode(c: Color) = colorHelper.setXORMode(c) override fun getFont() = stringHelper.font override fun setFont(font: Font) { stringHelper.font = font } override fun getFontMetrics(f: Font) = stringHelper.getFontMetrics(f) override fun getFontRenderContext() = stringHelper.fontRenderContext override fun getClipBounds(): Rectangle? { if (clip == null) { return null } else { try { val pts = DoubleArray(8) pts[0] = clip!!.minX pts[1] = clip!!.minY pts[2] = clip!!.maxX pts[3] = clip!!.minY pts[4] = clip!!.maxX pts[5] = clip!!.maxY pts[6] = clip!!.minX pts[7] = clip!!.maxY transform.inverseTransform(pts, 0, pts, 0, 4) val minX = Math.min(pts[0], Math.min(pts[2], Math.min(pts[4], pts[6]))).toInt() val maxX = Math.max(pts[0], Math.max(pts[2], Math.max(pts[4], pts[6]))).toInt() val minY = Math.min(pts[1], Math.min(pts[3], Math.min(pts[5], pts[7]))).toInt() val maxY = Math.max(pts[1], Math.max(pts[3], Math.max(pts[5], pts[7]))).toInt() return Rectangle(minX, minY, maxX - minX, maxY - minY) } catch (e: NoninvertibleTransformException) { // Not sure why this would happen Logger.getLogger(GLGraphics2D::class.java.name).log(Level.WARNING, "User transform is non-invertible", e) return clip!!.bounds } } } override fun clip(s: Shape) = setClip(s.bounds, true) override fun clipRect(x: Int, y: Int, width: Int, height: Int) = setClip(Rectangle(x, y, width, height), true) override fun setClip(x: Int, y: Int, width: Int, height: Int) = setClip(Rectangle(x, y, width, height), false) override fun getClip(): Shape? = clipBounds override fun setClip(clipShape: Shape?) { if (clipShape is Rectangle2D) { setClip(clipShape as Rectangle2D?, false) } else if (clipShape == null) { setClip(null, false) } else { setClip(clipShape.bounds2D) } } private fun setClip(clipShape: Rectangle2D?, intersect: Boolean) { if (clipShape == null) { clip = null scissor(false) } else if (intersect && clip != null) { val rect = transform.createTransformedShape(clipShape).bounds clip = rect.intersection(clip!!) scissor(true) } else { clip = transform.createTransformedShape(clipShape).bounds scissor(true) } } private fun scissor(enable: Boolean) { val gl = glContext.gl if (enable) { gl.glScissor(clip!!.x, canvasHeight - clip!!.y - clip!!.height, Math.max(clip!!.width, 0), Math.max(clip!!.height, 0)) gl.glEnable(GL.GL_SCISSOR_TEST) } else { clip = null gl.glDisable(GL.GL_SCISSOR_TEST) } } override fun copyArea(x: Int, y: Int, width: Int, height: Int, dx: Int, dy: Int) = colorHelper.copyArea(x, y, width, height, dx, dy) override fun drawLine(x1: Int, y1: Int, x2: Int, y2: Int) = shapeHelper.drawLine(x1, y1, x2, y2) override fun fillRect(x: Int, y: Int, width: Int, height: Int) = shapeHelper.drawRect(x, y, width, height, true) override fun clearRect(x: Int, y: Int, width: Int, height: Int) { val c = color colorHelper.setColorNoRespectComposite(background) fillRect(x, y, width, height) colorHelper.setColorRespectComposite(c) } override fun drawRect(x: Int, y: Int, width: Int, height: Int) = shapeHelper.drawRect(x, y, width, height, false) override fun drawRoundRect(x: Int, y: Int, width: Int, height: Int, arcWidth: Int, arcHeight: Int) = shapeHelper.drawRoundRect(x, y, width, height, arcWidth, arcHeight, false) override fun fillRoundRect(x: Int, y: Int, width: Int, height: Int, arcWidth: Int, arcHeight: Int) = shapeHelper.drawRoundRect(x, y, width, height, arcWidth, arcHeight, true) override fun drawOval(x: Int, y: Int, width: Int, height: Int) = shapeHelper.drawOval(x, y, width, height, false) override fun fillOval(x: Int, y: Int, width: Int, height: Int) = shapeHelper.drawOval(x, y, width, height, true) override fun drawArc(x: Int, y: Int, width: Int, height: Int, startAngle: Int, arcAngle: Int) = shapeHelper.drawArc(x, y, width, height, startAngle, arcAngle, false) override fun fillArc(x: Int, y: Int, width: Int, height: Int, startAngle: Int, arcAngle: Int) = shapeHelper.drawArc(x, y, width, height, startAngle, arcAngle, true) override fun drawPolyline(xPoints: IntArray, yPoints: IntArray, nPoints: Int) = shapeHelper.drawPolyline(xPoints, yPoints, nPoints) override fun drawPolygon(xPoints: IntArray, yPoints: IntArray, nPoints: Int) = shapeHelper.drawPolygon(xPoints, yPoints, nPoints, false) override fun fillPolygon(xPoints: IntArray, yPoints: IntArray, nPoints: Int) = shapeHelper.drawPolygon(xPoints, yPoints, nPoints, true) override fun drawImage(img: Image, xform: AffineTransform, obs: ImageObserver) = imageHelper.drawImage(img, xform, obs) override fun drawImage(img: BufferedImage, op: BufferedImageOp, x: Int, y: Int) = imageHelper.drawImage(img, op, x, y) override fun drawRenderedImage(img: RenderedImage, xform: AffineTransform) = imageHelper.drawImage(img, xform) override fun drawRenderableImage(img: RenderableImage, xform: AffineTransform) = imageHelper.drawImage(img, xform) override fun drawImage(img: Image, x: Int, y: Int, observer: ImageObserver) = imageHelper.drawImage(img, x, y, Color.WHITE, observer) override fun drawImage(img: Image, x: Int, y: Int, bgcolor: Color, observer: ImageObserver) = imageHelper.drawImage(img, x, y, bgcolor, observer) override fun drawImage(img: Image, x: Int, y: Int, width: Int, height: Int, observer: ImageObserver) = imageHelper.drawImage(img, x, y, width, height, Color.WHITE, observer) override fun drawImage(img: Image, x: Int, y: Int, width: Int, height: Int, bgcolor: Color, observer: ImageObserver) = imageHelper.drawImage(img, x, y, width, height, bgcolor, observer) override fun drawImage(img: Image, dx1: Int, dy1: Int, dx2: Int, dy2: Int, sx1: Int, sy1: Int, sx2: Int, sy2: Int, observer: ImageObserver) = imageHelper.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, Color.WHITE, observer) override fun drawImage(img: Image, dx1: Int, dy1: Int, dx2: Int, dy2: Int, sx1: Int, sy1: Int, sx2: Int, sy2: Int, bgcolor: Color, observer: ImageObserver) = imageHelper.drawImage(img, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, bgcolor, observer) override fun create(): Graphics { val newG2d = clone() for (helper in helpers) { helper.push(newG2d) } return newG2d } override fun dispose() { if (!isDisposed) { isDisposed = true if (parent != null) { /*for (i in helpers.indices.reversed()) { helpers[i].pop(parent!!) }*/ parent!!.scissor(parent!!.clip != null) } } } override fun clone(): GLGraphics2D { try { val clone = super.clone() as GLGraphics2D clone.parent = this clone.hints = hints.clone() as RenderingHints return clone } catch (exception: CloneNotSupportedException) { throw AssertionError(exception) } } }
apache-2.0
f0891133dbefed37f638f258fc3fd8d8
29.591195
142
0.705524
3.268817
false
false
false
false
HabitRPG/habitrpg-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/PromoWebFragment.kt
1
1836
package com.habitrpg.android.habitica.ui.fragments import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebChromeClient import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.databinding.FragmentNewsBinding import com.habitrpg.android.habitica.modules.AppModule import javax.inject.Inject import javax.inject.Named class PromoWebFragment : BaseMainFragment<FragmentNewsBinding>() { @field:[Inject Named(AppModule.NAMED_USER_ID)] lateinit var userID: String override var binding: FragmentNewsBinding? = null override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentNewsBinding { return FragmentNewsBinding.inflate(inflater, container, false) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { this.hidesToolbar = true return super.onCreateView(inflater, container, savedInstanceState) } @SuppressLint("SetJavaScriptEnabled") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val webSettings = binding?.newsWebview?.settings webSettings?.javaScriptEnabled = true webSettings?.domStorageEnabled = true binding?.newsWebview?.webChromeClient = object : WebChromeClient() { } arguments?.let { val args = PromoWebFragmentArgs.fromBundle(it) var url = args.url url = url.replace("USER_ID", userID) binding?.newsWebview?.loadUrl(url) } } override fun injectFragment(component: UserComponent) { component.inject(this) } }
gpl-3.0
6712eddafcabe88fcc4a57e86db4867d
36.469388
116
0.736928
5.030137
false
false
false
false
androidx/androidx
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/CameraMetadata.kt
3
5924
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java package androidx.camera.camera2.pipe import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CaptureRequest import android.hardware.camera2.CaptureResult import androidx.annotation.RequiresApi /** * [CameraMetadata] is a compatibility wrapper around [CameraCharacteristics]. * * Applications should, in most situations, prefer using this interface to using the * unwrapping and using the underlying [CameraCharacteristics] object directly. Implementation(s) of * this interface provide compatibility guarantees and performance improvements over using * [CameraCharacteristics] directly. This allows code to get reasonable behavior for all properties * across all OS levels and makes behavior that depends on [CameraMetadata] easier to test and * reason about. */ public interface CameraMetadata : Metadata, UnsafeWrapper { public operator fun <T> get(key: CameraCharacteristics.Key<T>): T? public fun <T> getOrDefault(key: CameraCharacteristics.Key<T>, default: T): T public val camera: CameraId public val isRedacted: Boolean public val keys: Set<CameraCharacteristics.Key<*>> public val requestKeys: Set<CaptureRequest.Key<*>> public val resultKeys: Set<CaptureResult.Key<*>> public val sessionKeys: Set<CaptureRequest.Key<*>> public val physicalCameraIds: Set<CameraId> public val physicalRequestKeys: Set<CaptureRequest.Key<*>> public suspend fun getPhysicalMetadata(cameraId: CameraId): CameraMetadata public fun awaitPhysicalMetadata(cameraId: CameraId): CameraMetadata } /** * Extension properties for querying the available capabilities of a camera device across all API * levels. */ var EMPTY_INT_ARRAY = IntArray(0) const val CAPABILITIES_MANUAL_SENSOR = 1 const val CAPABILITIES_MANUAL_POST_PROCESSING = 2 const val CAPABILITIES_RAW = 3 const val CAPABILITIES_PRIVATE_REPROCESSING = 4 const val CAPABILITIES_READ_SENSOR_SETTINGS = 5 const val CAPABILITIES_BURST_CAPTURE = 6 const val CAPABILITIES_YUV_REPROCESSING = 7 const val CAPABILITIES_DEPTH_OUTPUT = 8 const val CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO = 9 const val CAPABILITIES_MOTION_TRACKING = 10 const val CAPABILITIES_LOGICAL_MULTI_CAMERA = 11 const val CAPABILITIES_MONOCHROME = 12 const val CAPABILITIES_SECURE_IMAGE_DATA = 13 const val CAPABILITIES_SYSTEM_CAMERA = 14 const val CAPABILITIES_OFFLINE_REPROCESSING = 15 val CameraMetadata.availableCapabilities: IntArray get() = this[CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES] ?: EMPTY_INT_ARRAY val CameraMetadata.supportsManualSensor: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_MANUAL_SENSOR) val CameraMetadata.supportsManualPostProcessing: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_MANUAL_POST_PROCESSING) val CameraMetadata.supportsRaw: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_RAW) val CameraMetadata.supportsPrivateReprocessing: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_PRIVATE_REPROCESSING) val CameraMetadata.supportsSensorSettings: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_READ_SENSOR_SETTINGS) val CameraMetadata.supportsBurstCapture: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_BURST_CAPTURE) val CameraMetadata.supportsYuvReprocessing: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_YUV_REPROCESSING) val CameraMetadata.supportsDepthOutput: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_DEPTH_OUTPUT) val CameraMetadata.supportsHighSpeedVideo: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_CONSTRAINED_HIGH_SPEED_VIDEO) val CameraMetadata.supportsMotionTracking: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_MOTION_TRACKING) val CameraMetadata.supportsLogicalMultiCamera: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_LOGICAL_MULTI_CAMERA) val CameraMetadata.supportsMonochrome: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_MONOCHROME) val CameraMetadata.supportsSecureImageData: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_SECURE_IMAGE_DATA) val CameraMetadata.supportsSystemCamera: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_SYSTEM_CAMERA) val CameraMetadata.supportsOfflineReprocessing: Boolean get() = this.availableCapabilities.contains(CAPABILITIES_OFFLINE_REPROCESSING) val CameraMetadata.supportsAutoFocusTrigger: Boolean get() { val minFocusDistance = this[CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE] if (minFocusDistance != null) { return minFocusDistance > 0 } val availableAfModes = this[CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES] ?: return false return availableAfModes.contains(CaptureRequest.CONTROL_AF_MODE_AUTO) || availableAfModes.contains(CaptureRequest.CONTROL_AF_MODE_MACRO) || availableAfModes.contains(CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE) || availableAfModes.contains(CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO) }
apache-2.0
45eaf27bc6dd4e8b88819b65e8bd871b
42.240876
100
0.78815
4.50152
false
false
false
false
androidx/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/IconButton.kt
3
5490
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.selection.toggleable import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp /** * IconButton is a clickable icon, used to represent actions. An IconButton has an overall minimum * touch target size of 48 x 48dp, to meet accessibility guidelines. [content] is centered * inside the IconButton. * * This component is typically used inside an App Bar for the navigation icon / actions. See App * Bar documentation for samples of this. * * [content] should typically be an [Icon], using an icon from * [androidx.compose.material.icons.Icons]. If using a custom icon, note that the typical size for the * internal icon is 24 x 24 dp. * * @sample androidx.compose.material.samples.IconButtonSample * * @param onClick the lambda to be invoked when this icon is pressed * @param modifier optional [Modifier] for this IconButton * @param enabled whether or not this IconButton will handle input events and appear enabled for * semantics purposes * @param interactionSource the [MutableInteractionSource] representing the stream of * [Interaction]s for this IconButton. You can create and pass in your own remembered * [MutableInteractionSource] if you want to observe [Interaction]s and customize the * appearance / behavior of this IconButton in different [Interaction]s. * @param content the content (icon) to be drawn inside the IconButton. This is typically an * [Icon]. */ @Composable fun IconButton( onClick: () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit ) { Box( modifier = modifier .minimumTouchTargetSize() .clickable( onClick = onClick, enabled = enabled, role = Role.Button, interactionSource = interactionSource, indication = rememberRipple(bounded = false, radius = RippleRadius) ), contentAlignment = Alignment.Center ) { val contentAlpha = if (enabled) LocalContentAlpha.current else ContentAlpha.disabled CompositionLocalProvider(LocalContentAlpha provides contentAlpha, content = content) } } /** * An [IconButton] with two states, for icons that can be toggled 'on' and 'off', such as a * bookmark icon, or a navigation icon that opens a drawer. * * @sample androidx.compose.material.samples.IconToggleButtonSample * * @param checked whether this IconToggleButton is currently checked * @param onCheckedChange callback to be invoked when this icon is selected * @param modifier optional [Modifier] for this IconToggleButton * @param enabled enabled whether or not this [IconToggleButton] will handle input events and appear * enabled for semantics purposes * @param interactionSource the [MutableInteractionSource] representing the stream of * [Interaction]s for this IconToggleButton. You can create and pass in your own remembered * [MutableInteractionSource] if you want to observe [Interaction]s and customize the * appearance / behavior of this IconToggleButton in different [Interaction]s. * @param content the content (icon) to be drawn inside the IconToggleButton. This is typically an * [Icon]. */ @Composable fun IconToggleButton( checked: Boolean, onCheckedChange: (Boolean) -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, content: @Composable () -> Unit ) { Box( modifier = modifier .minimumTouchTargetSize() .toggleable( value = checked, onValueChange = onCheckedChange, enabled = enabled, role = Role.Checkbox, interactionSource = interactionSource, indication = rememberRipple(bounded = false, radius = RippleRadius) ), contentAlignment = Alignment.Center ) { val contentAlpha = if (enabled) LocalContentAlpha.current else ContentAlpha.disabled CompositionLocalProvider(LocalContentAlpha provides contentAlpha, content = content) } } // Default radius of an unbounded ripple in an IconButton private val RippleRadius = 24.dp
apache-2.0
a46da2e8840b4bd958aeef076cc6aefa
41.55814
102
0.735701
4.901786
false
false
false
false
goldmansachs/obevo
obevo-core/src/main/java/com/gs/obevo/impl/Changeset.kt
1
2570
/** * Copyright 2017 Goldman Sachs. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.gs.obevo.impl import org.eclipse.collections.api.RichIterable import org.eclipse.collections.api.block.predicate.Predicate import org.eclipse.collections.api.list.ImmutableList import org.eclipse.collections.impl.factory.Lists class Changeset( val inserts: ImmutableList<ExecuteChangeCommand>, val deferredChanges: ImmutableList<ExecuteChangeCommand>, val auditChanges: RichIterable<AuditChangeCommand>, val changeWarnings: RichIterable<ChangeCommandWarning>) { constructor(inserts: ImmutableList<ExecuteChangeCommand>, auditChanges: RichIterable<AuditChangeCommand>, changeWarnings: RichIterable<ChangeCommandWarning> ) : this(inserts, Lists.immutable.empty(), auditChanges, changeWarnings) val isDeploymentNeeded: Boolean get() = !this.inserts.isEmpty || !this.auditChanges.isEmpty fun applyDeferredPredicate(deferredChangePredicate: Predicate<in ExecuteChangeCommand>?): Changeset { val partition = inserts.partition(deferredChangePredicate ?: DEFAULT_DEFERRED_PREDICATE); return Changeset(partition.selected, deferredChanges.newWithAll(partition.rejected), auditChanges, changeWarnings) } fun validateForDeployment() { val fatalWarnings = this.changeWarnings.filter { it.isFatal } if (!fatalWarnings.isEmpty()) { // check for serious exceptions throw IllegalArgumentException("Found exceptions:\n" + fatalWarnings.map { it.commandDescription }.joinToString("\n")) } } companion object { /** * By default, we will always defer those predicates marked w/ the changeset attribute as the existence of that * indicates something that may not be good to run alongside a regular release. */ private val DEFAULT_DEFERRED_PREDICATE: Predicate<in ExecuteChangeCommand> = Predicate { command -> command.changes.any { it.changeset == null } } } }
apache-2.0
e67cd38ad22fc513b23de5c7d24ba3ca
43.310345
154
0.728794
4.630631
false
false
false
false
codehz/container
app/src/main/java/one/codehz/container/models/SpaceManagerModel.kt
1
1060
package one.codehz.container.models import one.codehz.container.R import one.codehz.container.base.SameAsAble import one.codehz.container.ext.virtualCore import kotlin.reflect.KClass class SpaceManagerModel(val title: String, val target: KClass<*>) : SameAsAble<SpaceManagerModel> { var amount: String = virtualCore.context.getString(R.string.calculating) constructor(model: SpaceManagerModel) : this(model.title, model.target) { amount = model.amount } fun clone() = SpaceManagerModel(this) override fun sameAs(other: SpaceManagerModel): Boolean = title == other.title override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as SpaceManagerModel if (title != other.title) return false if (amount != other.amount) return false return true } override fun hashCode(): Int { var result = title.hashCode() result = 31 * result + amount.hashCode() return result } }
gpl-3.0
0f7e69f2ed2197cb418fc167d7f21c3b
28.472222
99
0.683962
4.24
false
false
false
false
EventFahrplan/EventFahrplan
app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/TrackBackgrounds.kt
1
2979
package nerd.tuxmobil.fahrplan.congress.schedule import android.content.Context import nerd.tuxmobil.fahrplan.congress.R import org.xmlpull.v1.XmlPullParser object TrackBackgrounds { private fun getHashMapResource(context: Context, hashMapResId: Int): Map<String?, String?>? { var map: MutableMap<String?, String?>? = null val parser = context.resources.getXml(hashMapResId) var key: String? = null var value: String? = null try { var eventType = parser.eventType while (eventType != XmlPullParser.END_DOCUMENT) { when (eventType) { // XmlPullParser can also be START_DOCUMENT XmlPullParser.START_TAG -> { if (parser.name == "map") { val isLinked = parser.getAttributeBooleanValue(null, "linked", false) map = if (isLinked) linkedMapOf() else hashMapOf() } else if (parser.name == "entry") { key = parser.getAttributeValue(null, "key") if (null == key) { parser.close() return null } } } XmlPullParser.END_TAG -> { if (parser.name == "entry") { map!![key] = value key = null value = null } } XmlPullParser.TEXT -> { if (key != null) { value = parser.text.trim() } } } eventType = parser.next() } } catch (e: Exception) { e.printStackTrace() return null } return map } private fun buildTrackBackgroundHashMap( trackNamesMap: Map<String?, String?>, prefix: String, resourceType: String, context: Context ) = trackNamesMap.mapValues { var name = prefix // Handle empty track names // key can have the value: "" // See track_resource_names.xml if (!it.key.isNullOrEmpty()) { name += "_${it.value}" } context.resources.getIdentifier(name, resourceType, context.packageName) } fun getTrackNameBackgroundColorDefaultPairs(context: Context) = buildTrackBackgroundHashMap( getHashMapResource(context, R.xml.track_resource_names)!!, "track_background_default", "color", context ) fun getTrackNameBackgroundColorHighlightPairs(context: Context) = buildTrackBackgroundHashMap( getHashMapResource(context, R.xml.track_resource_names)!!, "track_background_highlight", "color", context ) }
apache-2.0
2a5e624de1b8d1985b36dd2e4344fd4d
34.464286
98
0.49614
5.357914
false
false
false
false
esofthead/mycollab
mycollab-esb/src/main/java/com/mycollab/module/project/esb/AddProjectCommand.kt
3
2134
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.esb import com.google.common.eventbus.AllowConcurrentEvents import com.google.common.eventbus.Subscribe import com.mycollab.common.dao.OptionValMapper import com.mycollab.common.domain.OptionVal import com.mycollab.common.domain.OptionValExample import com.mycollab.module.esb.GenericCommand import org.springframework.stereotype.Component import java.time.LocalDateTime /** * @author MyCollab Ltd * @since 6.0.0 */ @Component class AddProjectCommand(private val optionValMapper: OptionValMapper) : GenericCommand() { @AllowConcurrentEvents @Subscribe fun addProject(event: AddProjectEvent) { val ex = OptionValExample() ex.createCriteria().andIsdefaultEqualTo(true).andSaccountidEqualTo(event.accountId) val defaultOptions = optionValMapper.selectByExample(ex) defaultOptions.forEach { val prjOption = OptionVal() prjOption.createdtime = LocalDateTime.now() prjOption.description = it.description prjOption.extraid = event.projectId prjOption.isdefault = false prjOption.saccountid = event.accountId prjOption.type = it.type prjOption.typeval = it.typeval prjOption.fieldgroup = it.fieldgroup prjOption.refoption = it.id prjOption.color = "fdde86" optionValMapper.insert(prjOption) } } }
agpl-3.0
7c66b9650ff31082d4cedc7134a4734a
36.438596
91
0.720581
4.198819
false
false
false
false
googlearchive/android-ContentProviderPaging
kotlinApp/app/src/main/kotlin/com.example.android.contentproviderpaging/ImageAdapter.kt
4
3065
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.contentproviderpaging import android.content.Context import android.support.v4.content.res.ResourcesCompat import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.bumptech.glide.Glide import java.util.* /** * Adapter for RecyclerView, which manages the image documents. */ internal class ImageAdapter(private val mContext: Context) : RecyclerView.Adapter<ImageViewHolder>() { /** Holds the information for already retrieved images. */ private val mImageDocuments = ArrayList<ImageDocument>() /** * The total size of the all images. This number should be the size for all images even if * they are not fetched from the ContentProvider. */ private var mTotalSize: Int = 0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.viewholder_image, parent, false) return ImageViewHolder(view) } override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { val resources = mContext.resources if (mImageDocuments.size > position) { Glide.with(mContext) .load(mImageDocuments[position].absolutePath) .placeholder(R.drawable.cat_placeholder) .into(holder.mImageView) holder.mTextView.text = (position + 1).toString() } else { holder.mImageView.setImageDrawable( ResourcesCompat.getDrawable(resources, R.drawable.cat_placeholder, null)) } } /** * Add an image as part of the adapter. * @param imageDocument the image information to be added */ fun add(imageDocument: ImageDocument) { mImageDocuments.add(imageDocument) } /** * Set the total size of all images. * @param totalSize the total size */ fun setTotalSize(totalSize: Int) { mTotalSize = totalSize } /** * @return the number of images already fetched and added to this adapter. */ val fetchedItemCount: Int get() = mImageDocuments.size override fun getItemCount(): Int { return mTotalSize } /** * Represents information for an image. */ internal data class ImageDocument(val absolutePath: String, val displayName: String) }
apache-2.0
066e4636a4c5a82e73a0e0a328c867a5
31.956989
102
0.680914
4.595202
false
false
false
false
JayNewstrom/ViewMode
view-mode/src/main/java/com/jaynewstrom/viewmode/ViewModeView.kt
1
3314
package com.jaynewstrom.viewmode import android.content.Context import android.util.AttributeSet import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout class ViewModeView : CoordinatorLayout { private val cachedViewModes = LinkedHashMap<ViewMode, View>() private var currentViewMode: ViewMode? = null private var currentView: View? = null private var cacheViews: Boolean = false private var transitioning: Boolean = false constructor(context: Context) : super(context) { initialize(null) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { initialize(attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { initialize(attrs) } private fun initialize(attrs: AttributeSet?) { if (attrs == null) { cacheViews = true } else { val a = context.obtainStyledAttributes(attrs, R.styleable.ViewModeView) cacheViews = a.getBoolean(R.styleable.ViewModeView_view_mode_caching, true) a.recycle() } } fun showViewMode(viewMode: ViewMode, transition: ViewModeTransition = DefaultViewModeTransition) { if (transitioning) { throw IllegalStateException("A transition is already occurring.") } if (currentViewMode == null || currentViewMode != viewMode) { transitioning = true val previousViewMode = currentViewMode val previousView = currentView currentViewMode = viewMode val viewToShow = viewForViewMode(viewMode) currentView = viewToShow addView(viewToShow) transition.transition(previousViewMode, previousView, viewToShow) { var i = 0 while (i < childCount) { val childView = getChildAt(i) if (cacheViews) { childView.visibility = if (childView === viewToShow) View.VISIBLE else View.GONE i++ } else { if (childView === viewToShow) { i++ } else { removeViewAt(i) } } } transitioning = false } } } fun currentViewMode(): ViewMode? { return currentViewMode } /** * This will return the cached view for the given view mode, or create it if it isn't cached. */ fun viewForViewMode(viewMode: ViewMode): View { return if (cacheViews) { cachedViewModes.getOrPut(viewMode) { viewMode.createView(this) } } else { viewMode.createView(this) } } fun setCacheViews(cacheViews: Boolean) { this.cacheViews = cacheViews } fun preloadViewMode(viewMode: ViewMode) { if (!cacheViews) { throw IllegalStateException("Preloading is only applicable when caching views.") } // This creates the view, and caches it in our pool, to be added and shown when calling showViewMode. viewForViewMode(viewMode) } }
apache-2.0
497b1921a7a3fd34de6b0f3388a4c593
31.490196
114
0.583585
5.210692
false
false
false
false
CherryPerry/Amiami-kotlin-backend
src/main/kotlin/com/cherryperry/amiami/model/mongodb/ItemRepositoryImpl.kt
1
1546
package com.cherryperry.amiami.model.mongodb import com.cherryperry.amiami.model.lastmodified.LastModifiedValue import org.apache.logging.log4j.LogManager import org.springframework.data.domain.Sort import org.springframework.stereotype.Repository @Repository class ItemRepositoryImpl constructor( private val itemMongoRepository: ItemMongoRepository ) : ItemRepository { private val log = LogManager.getLogger(ItemRepositoryImpl::class.java) private val lastModifiedValue = LastModifiedValue() override val lastModified: Long get() = lastModifiedValue.value override fun items(): Collection<Item> { log.trace("items") return itemMongoRepository.findAll(Sort.by(Sort.Direction.DESC, "time")) } override fun compareAndSave(item: Item): Boolean { log.trace("compareAndSave item = $item") val optional = itemMongoRepository.findById(item.url) if (optional.isPresent && optional.get().equalsNoTimestamp(item)) { log.info("Old one not changed, old one = ${optional.get()}") return false } log.info("Old one not found or not changed, old one = ${optional.orElse(null)}") itemMongoRepository.save(item) lastModifiedValue.update() return true } override fun deleteOther(ids: Collection<String>) { log.trace("deleteOther size = ${ids.size}") val result = itemMongoRepository.deleteWhereIdNotInList(ids) log.info("Deleted = $result") lastModifiedValue.update() } }
apache-2.0
d294f1d105e8f8cad0bb7716280c70f4
34.953488
88
0.699871
4.429799
false
false
false
false
Knewton/dynamok
dynamok-core/src/main/kotlin/com/knewton/dynamok/connections/CloudWatchConnection.kt
1
4522
/* * Copyright 2015 Knewton * * 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.knewton.dynamok.connections import com.amazonaws.services.cloudwatch.model.Dimension import com.amazonaws.services.cloudwatch.model.GetMetricStatisticsRequest import com.amazonaws.services.cloudwatch.model.StandardUnit import com.amazonaws.services.cloudwatch.model.Statistic import com.knewton.dynamok.data.DynamoIndex import org.joda.time.DateTime import org.joda.time.Duration /** * Provides utility methods to query information from AWS CloudWatch * * @param clientFactory The AWSClientFactory to create the AmazonCloudWatchClient used to talk * to CloudWatch */ public open class CloudWatchConnection(clientFactory: AWSClientFactory) { val client = clientFactory.createCloudWatchClient() /** * Retrieves the average data of a given metric on a given index (either a table's primary * index or global secondary index) from (now - PERIOD_SECONDS - LOOKBACK_BUFFER_MINUTES) to * (now - LOOKBACK_BUFFER_MINUTES). * * @param index The primary or global secondary index * @param metric The AWS metric name to retrieve (ex: ConsumedReadCapacityUnits) * @return Returns the average of the metric or zero if no data points were retrieved * @throws AmazonClientException If the client request failed */ public open fun getTableMetricAverage(index: DynamoIndex, metric: String): Double { val end = DateTime.now() - Duration.standardMinutes( LOOKBACK_BUFFER_MINUTES) val start = end - Duration.standardSeconds(PERIOD_SECONDS.toLong()) val dimensions = arrayListOf(Dimension().withName("TableName") .withValue(index.tableName)) if (index.gsiName.isNotEmpty()) { dimensions.add(Dimension().withName("GlobalSecondaryIndexName") .withValue(index.gsiName)) } // Creates a metrics request, see // http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html // for more information. // Period is set to the interval, so we retrieve just one data point val request = GetMetricStatisticsRequest() .withPeriod(PERIOD_SECONDS) .withStartTime(start.toDate()) .withEndTime(end.toDate()) .withMetricName(metric) .withNamespace("AWS/DynamoDB") .withStatistics(Statistic.Sum) .withDimensions(dimensions) .withUnit(StandardUnit.Count) val result = client.getMetricStatistics(request) // We expect one data point, however, Dynamo does not record metrics if there is no activity // on the table (so there may be zero data points). val datapoint = result.getDatapoints().singleOrNull() return ((datapoint?.getSum()) ?: 0.0) / PERIOD_SECONDS.toDouble() } /** * Retrieves the average consumed read units of a given table's primary index or global * secondary index. * * @return Returns the average consumed read units or zero if no data points were retrieved * @throws AmazonClientException If the client request failed */ public open fun getConsumedReads(index: DynamoIndex): Double = getTableMetricAverage(index, "ConsumedReadCapacityUnits") /** * Retrieves the average consumed write units of a given table's primary index or global * secondary index. * * @return Returns the average consumed write units or zero if no data points were retrieved * @throws AmazonClientException If the client request failed */ public open fun getConsumedWrites(index: DynamoIndex): Double = getTableMetricAverage(index, "ConsumedWriteCapacityUnits") companion object { private val LOOKBACK_BUFFER_MINUTES = 5L private val PERIOD_SECONDS = 300 } }
apache-2.0
0ce95688d24bb5fbe235cbc314414732
41.669811
100
0.686422
4.740042
false
false
false
false
Yubico/yubioath-desktop
android/app/src/main/kotlin/com/yubico/authenticator/oath/OathViewModel.kt
1
3146
/* * Copyright (C) 2022 Yubico. * * 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.yubico.authenticator.oath import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel class OathViewModel: ViewModel() { private val _sessionState = MutableLiveData<Model.Session?>() val sessionState: LiveData<Model.Session?> = _sessionState fun setSessionState(sessionState: Model.Session?) { val oldDeviceId = _sessionState.value?.deviceId _sessionState.postValue(sessionState) if(oldDeviceId != sessionState?.deviceId) { _credentials.postValue(null) } } private val _credentials = MutableLiveData<List<Model.CredentialWithCode>?>() val credentials: LiveData<List<Model.CredentialWithCode>?> = _credentials fun updateCredentials(credentials: Map<Model.Credential, Model.Code?>): List<Model.CredentialWithCode> { val existing = _credentials.value?.associate { it.credential to it.code } ?: mapOf() val updated = credentials.map { Model.CredentialWithCode(it.key, it.value ?: existing[it.key]) } _credentials.postValue(updated) return updated } fun addCredential(credential: Model.Credential, code: Model.Code?): Model.CredentialWithCode { require(credential.deviceId == _sessionState.value?.deviceId) { "Cannot add credential for different deviceId" } return Model.CredentialWithCode(credential, code).also { _credentials.postValue(_credentials.value?.plus(it)) } } fun renameCredential( oldCredential: Model.Credential, newCredential: Model.Credential ) { val existing = _credentials.value!! val entry = existing.find { it.credential == oldCredential }!! require(entry.credential.deviceId == newCredential.deviceId) { "Cannot rename credential for different deviceId" } _credentials.postValue(existing.minus(entry).plus(Model.CredentialWithCode(newCredential, entry.code))) } fun removeCredential(credential: Model.Credential) { val existing = _credentials.value!! val entry = existing.find { it.credential == credential }!! _credentials.postValue(existing.minus(entry)) } fun updateCode(credential: Model.Credential, code: Model.Code?) { val existing = _credentials.value!! val entry = existing.find { it.credential == credential }!! _credentials.postValue(existing.minus(entry).plus(Model.CredentialWithCode(credential, code))) } }
apache-2.0
e95002daa27327a8848586d15e4d2db5
37.378049
111
0.69199
4.481481
false
false
false
false
edwardharks/Aircraft-Recognition
recognition/src/main/kotlin/com/edwardharker/aircraftrecognition/search/SearchState.kt
1
428
package com.edwardharker.aircraftrecognition.search import com.edwardharker.aircraftrecognition.model.Aircraft data class SearchState( val searchResults: List<Aircraft> = emptyList(), val error: Boolean = false ) { companion object { fun empty() = SearchState() fun success(aircraft: List<Aircraft>) = SearchState(searchResults = aircraft) fun error() = SearchState(error = true) } }
gpl-3.0
7b5ae2ff30fd851348ae45544e748a15
25.75
85
0.703271
4.703297
false
false
false
false
theScrabi/NewPipe
app/src/main/java/org/schabi/newpipe/local/subscription/item/FeedGroupReorderItem.kt
1
1896
package org.schabi.newpipe.local.subscription.item import android.view.MotionEvent import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper.DOWN import androidx.recyclerview.widget.ItemTouchHelper.UP import com.xwray.groupie.kotlinandroidextensions.GroupieViewHolder import com.xwray.groupie.kotlinandroidextensions.Item import kotlinx.android.synthetic.main.feed_group_reorder_item.group_icon import kotlinx.android.synthetic.main.feed_group_reorder_item.group_name import kotlinx.android.synthetic.main.feed_group_reorder_item.handle import org.schabi.newpipe.R import org.schabi.newpipe.database.feed.model.FeedGroupEntity import org.schabi.newpipe.local.subscription.FeedGroupIcon data class FeedGroupReorderItem( val groupId: Long = FeedGroupEntity.GROUP_ALL_ID, val name: String, val icon: FeedGroupIcon, val dragCallback: ItemTouchHelper ) : Item() { constructor (feedGroupEntity: FeedGroupEntity, dragCallback: ItemTouchHelper) : this(feedGroupEntity.uid, feedGroupEntity.name, feedGroupEntity.icon, dragCallback) override fun getId(): Long { return when (groupId) { FeedGroupEntity.GROUP_ALL_ID -> super.getId() else -> groupId } } override fun getLayout(): Int = R.layout.feed_group_reorder_item override fun bind(viewHolder: GroupieViewHolder, position: Int) { viewHolder.group_name.text = name viewHolder.group_icon.setImageResource(icon.getDrawableRes(viewHolder.containerView.context)) viewHolder.handle.setOnTouchListener { _, event -> if (event.actionMasked == MotionEvent.ACTION_DOWN) { dragCallback.startDrag(viewHolder) return@setOnTouchListener true } false } } override fun getDragDirs(): Int { return UP or DOWN } }
gpl-3.0
123606777748dd400bab421bea374612
36.92
101
0.734705
4.546763
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/ide/search/RustFindUsagesProvider.kt
1
665
package org.rust.ide.search import com.intellij.lang.HelpID import com.intellij.lang.findUsages.FindUsagesProvider import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustPatBinding class RustFindUsagesProvider : FindUsagesProvider { override fun getWordsScanner() = RustWordScanner() override fun canFindUsagesFor(element: PsiElement) = element is RustPatBinding override fun getHelpId(element: PsiElement) = HelpID.FIND_OTHER_USAGES override fun getType(element: PsiElement) = "" override fun getDescriptiveName(element: PsiElement) = "" override fun getNodeText(element: PsiElement, useFullName: Boolean) = "" }
mit
4d31c638571a751f7267f8c7f513e0a5
34
76
0.77594
4.52381
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustUseGlobImplMixin.kt
1
1023
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import org.rust.lang.core.psi.RustNamedElement import org.rust.lang.core.psi.RustQualifiedReferenceElement import org.rust.lang.core.psi.RustUseGlob import org.rust.lang.core.psi.RustUseItem import org.rust.lang.core.psi.impl.RustNamedElementImpl import org.rust.lang.core.psi.util.parentOfType import org.rust.lang.core.resolve.ref.RustUseGlobReferenceImpl import org.rust.lang.core.resolve.ref.RustReference abstract class RustUseGlobImplMixin(node: ASTNode) : RustNamedElementImpl(node), RustUseGlob { override fun getReference(): RustReference = RustUseGlobReferenceImpl(this) } val RustUseGlob.basePath: RustQualifiedReferenceElement? get() = parentOfType<RustUseItem>()?.let { it.viewPath.pathPart } val RustUseGlob.boundElement: RustNamedElement? get() = when { alias != null -> alias identifier != null -> this self != null -> basePath else -> null }
mit
9bb0484536cfcf0ef3d7366cbfa4ff50
36.888889
94
0.740958
3.860377
false
false
false
false
rafaelfiume/Prosciutto-Mob
test-support/src/main/kotlin/com/rafaelfiume/prosciutto/test/StubbedServer.kt
1
2513
package com.rafaelfiume.prosciutto.test import org.eclipse.jetty.server.Request import org.eclipse.jetty.server.Server import org.eclipse.jetty.server.handler.AbstractHandler import org.eclipse.jetty.server.handler.ContextHandler import org.eclipse.jetty.server.handler.HandlerCollection import java.io.IOException import javax.servlet.ServletException import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import java.lang.String.format import javax.servlet.http.HttpServletResponse.SC_OK class StubbedServer { private val server: Server private val handlerCollection = HandlerCollection(true) init { this.server = Server(8081) this.server.handler = handlerCollection } @Throws(Exception::class) fun start() { server.start() } @Throws(Exception::class) fun stop() { server.stop() } fun primeSuccessfulResponse(contextPath: String, response: String) { addHandler(contextPath, XmlResponseHandler(response)) } fun primeServerErrorWhenRequesting(contextPath: String) { addHandler(contextPath, ThrowsExceptionHandler()) } private fun addHandler(contextPath: String, handler: AbstractHandler) { val context = ContextHandler() context.contextPath = contextPath context.classLoader = Thread.currentThread().contextClassLoader context.handler = handler this.handlerCollection.addHandler(context) try { context.start() } catch (e: Exception) { throw RuntimeException("failed to prime $contextPath", e) } } internal class XmlResponseHandler(private val responseBody: String) : AbstractHandler() { @Throws(IOException::class, ServletException::class) override fun handle(target: String, baseRequest: Request, request: HttpServletRequest, response: HttpServletResponse) { response.contentType = "application/xml;charset=utf-8" response.status = SC_OK baseRequest.isHandled = true response.writer.append(responseBody) } } internal class ThrowsExceptionHandler : AbstractHandler() { @Throws(IOException::class, ServletException::class) override fun handle(target: String, baseRequest: Request, request: HttpServletRequest, response: HttpServletResponse) { throw RuntimeException("primed for throwing exception... don't blame the messenger ;)") } } }
mit
f9ebde36a3da7b0648b6363ef83de8c9
31.230769
127
0.705929
4.786667
false
false
false
false
androidstarters/androidstarters.com
templates/buffer-clean-architecture-components-kotlin/cache/src/main/java/org/buffer/android/boilerplate/cache/db/BufferoosDatabase.kt
1
1087
package <%= appPackage %>.cache.db import android.arch.persistence.room.Database import android.arch.persistence.room.Room import android.arch.persistence.room.RoomDatabase import android.content.Context import <%= appPackage %>.cache.dao.CachedBufferooDao import <%= appPackage %>.cache.model.CachedBufferoo import javax.inject.Inject @Database(entities = arrayOf(CachedBufferoo::class), version = 1) abstract class BufferoosDatabase @Inject constructor() : RoomDatabase() { abstract fun cachedBufferooDao(): CachedBufferooDao private var INSTANCE: BufferoosDatabase? = null private val sLock = Any() fun getInstance(context: Context): BufferoosDatabase { if (INSTANCE == null) { synchronized(sLock) { if (INSTANCE == null) { INSTANCE = Room.databaseBuilder(context.applicationContext, BufferoosDatabase::class.java, "bufferoos.db") .build() } return INSTANCE!! } } return INSTANCE!! } }
mit
d45e0c81815d37e9e97498d194ec2929
31
79
0.642134
4.918552
false
false
false
false
GunoH/intellij-community
java/debugger/impl/src/com/intellij/debugger/ui/tree/render/ArrayFilterInplaceEditor.kt
2
6616
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.debugger.ui.tree.render import com.intellij.debugger.DebuggerManagerEx import com.intellij.debugger.JavaDebuggerBundle import com.intellij.debugger.actions.ArrayAction import com.intellij.debugger.actions.ArrayFilterAction import com.intellij.debugger.engine.JavaValue import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.debugger.engine.events.SuspendContextCommandImpl import com.intellij.debugger.impl.DebuggerUtilsImpl import com.intellij.debugger.impl.PrioritizedTask import com.intellij.debugger.settings.NodeRendererSettings import com.intellij.icons.AllIcons import com.intellij.openapi.application.ReadAction import com.intellij.openapi.util.Pair import com.intellij.psi.JavaCodeFragment import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiType import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.util.ui.tree.TreeModelAdapter import com.intellij.util.ui.tree.TreeUtil import com.intellij.xdebugger.impl.XDebuggerUtilImpl import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreeInplaceEditor import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode import com.intellij.xdebugger.impl.ui.tree.nodes.XValueNodeImpl import com.sun.jdi.ArrayReference import com.sun.jdi.ArrayType import java.awt.Rectangle import javax.swing.event.TreeModelEvent import javax.swing.tree.TreeNode final class ArrayFilterInplaceEditor(node: XDebuggerTreeNode, private val myTemp: Boolean, thisType: PsiType?) : XDebuggerTreeInplaceEditor(node, "arrayFilter") { init { if (thisType != null) { myExpressionEditor.setDocumentProcessor({ d -> val psiFile = PsiDocumentManager.getInstance(project).getPsiFile(d) if (psiFile is JavaCodeFragment) psiFile.thisType = thisType d }) } val arrayRenderer = ArrayAction.getArrayRenderer((myNode.parent as XValueNodeImpl).valueContainer) myExpressionEditor.expression = if (arrayRenderer is ArrayRenderer.Filtered) arrayRenderer.expression else null } override fun cancelEditing() { super.cancelEditing() if (myTemp) (myNode.parent as XValueNodeImpl).removeTemporaryEditorNode(myNode) } override fun doOKAction() { myTree.model.addTreeModelListener(object : TreeModelAdapter() { override fun process(event: TreeModelEvent, type: EventType) { if (event.treePath?.lastPathComponent != myNode.parent) { myTree.model.removeTreeModelListener(this) } if (type == EventType.NodesInserted) { event.children?.filter { ArrayFilterAction.isArrayFilter(it as TreeNode) }?.forEach { myTree.selectionPath = TreeUtil.getPathFromRoot(it as TreeNode) myTree.model.removeTreeModelListener(this) } } } }) ArrayAction.setArrayRenderer(if (XDebuggerUtilImpl.isEmptyExpression(expression)) NodeRendererSettings.getInstance().arrayRenderer else ArrayRenderer.Filtered(expression), myNode.parent as XValueNodeImpl, DebuggerManagerEx.getInstanceEx(project).context) super.doOKAction() } override fun getEditorBounds(): Rectangle? { val bounds = super.getEditorBounds() ?: return null val nameLabel = SimpleColoredComponent() nameLabel.ipad.right = 0 nameLabel.ipad.left = 0 nameLabel.icon = myNode.icon nameLabel.append(JavaDebuggerBundle.message("message.node.filtered"), SimpleTextAttributes.REGULAR_ATTRIBUTES) val offset = nameLabel.preferredSize.width bounds.x += offset bounds.width -= offset return bounds } companion object { @JvmStatic fun edit(node: XDebuggerTreeNode, temp: Boolean) { val javaValue = (node.parent as XValueNodeImpl).valueContainer if (javaValue is JavaValue) { val debugProcess = javaValue.evaluationContext.debugProcess debugProcess.managerThread.schedule( object : SuspendContextCommandImpl(javaValue.evaluationContext.suspendContext) { override fun getPriority(): PrioritizedTask.Priority { return PrioritizedTask.Priority.NORMAL } override fun contextAction(suspendContext: SuspendContextImpl) { var type: String? = null val value = javaValue.descriptor.value if (value is ArrayReference) { type = (value.type() as ArrayType).componentTypeName() } else { val lastChildrenValue = ExpressionChildrenRenderer.getLastChildrenValue(javaValue.descriptor) if (lastChildrenValue is ArrayReference) { // take first non-null element for now for (v in lastChildrenValue.getValues(0, Math.min(lastChildrenValue.length(), 100))) { if (v != null) { type = v.type().name() break } } } } val pair = ReadAction.compute<Pair<PsiElement, PsiType>, Exception> { DebuggerUtilsImpl.getPsiClassAndType(type, javaValue.project) } DebuggerUIUtil.invokeLater({ ArrayFilterInplaceEditor(node, temp, pair.second).show() }) } override fun commandCancelled() { DebuggerUIUtil.invokeLater({ ArrayFilterInplaceEditor(node, temp, null).show() }) } }) } else { ArrayFilterInplaceEditor(node, temp, null).show() } } @JvmStatic fun editParent(parentNode: XValueNodeImpl) { var temp = false var node = parentNode.children.find { ArrayFilterAction.isArrayFilter(it) } if (node == null) { node = parentNode.addTemporaryEditorNode(AllIcons.General.Filter, JavaDebuggerBundle.message("message.node.filtered")) temp = true } edit(node as XDebuggerTreeNode, temp) } } }
apache-2.0
b7ba39dec390c1346e4867c72fbdf00b
43.106667
156
0.658404
4.989442
false
false
false
false
himikof/intellij-rust
src/main/kotlin/org/rust/cargo/runconfig/test/CargoTestRunConfigurationProducer.kt
1
3722
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.test import com.intellij.execution.Location import com.intellij.execution.PsiLocation import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.RunConfigurationProducer import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import org.rust.cargo.CargoConstants import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.runconfig.cargoArgumentSpeck import org.rust.cargo.runconfig.command.CargoCommandConfiguration import org.rust.cargo.runconfig.command.CargoCommandConfigurationType import org.rust.cargo.runconfig.mergeWithDefault import org.rust.cargo.toolchain.CargoCommandLine import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.* class CargoTestRunConfigurationProducer : RunConfigurationProducer<CargoCommandConfiguration>(CargoCommandConfigurationType()) { override fun isConfigurationFromContext( configuration: CargoCommandConfiguration, context: ConfigurationContext ): Boolean { val location = context.location ?: return false val test = findTest(location) ?: return false return configuration.configurationModule.module == context.module && configuration.cargoCommandLine == test.cargoCommandLine } override fun setupConfigurationFromContext( configuration: CargoCommandConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement> ): Boolean { val location = context.location ?: return false val test = findTest(location) ?: return false sourceElement.set(test.sourceElement) configuration.configurationModule.module = context.module configuration.name = test.configurationName configuration.cargoCommandLine = test.cargoCommandLine.mergeWithDefault(configuration.cargoCommandLine) return true } companion object { private fun findTest(location: Location<*>): TestConfig? = findTestFunction(location) ?: findTestMod(location) fun findTestFunction(location: Location<*>): TestConfig? { val fn = location.psiElement.parentOfType<RsFunction>(strict = false) ?: return null val name = fn.crateRelativePath.configPath() ?: return null val target = fn.containingCargoTarget ?: return null return if (fn.isTest) TestConfig(fn, "Test $name", name, target) else null } fun findTestMod(location: Location<*>): TestConfig? { val mod = location.psiElement.parentOfType<RsMod>(strict = false) ?: return null val testName = if (mod.modName == "test" || mod.modName == "tests") "Test ${mod.`super`?.modName}::${mod.modName}" else "Test ${mod.modName}" val testPath = mod.crateRelativePath.configPath() ?: "" val target = mod.containingCargoTarget ?: return null if (!mod.functionList.any { it.isTest }) return null return TestConfig(mod, testName, testPath, target) } } } class TestConfig( val sourceElement: RsCompositeElement, val configurationName: String, testPath: String, target: CargoWorkspace.Target ) { val cargoCommandLine: CargoCommandLine = CargoCommandLine( CargoConstants.Commands.TEST, target.cargoArgumentSpeck + testPath ) } // We need to chop off heading colon `::`, since `crateRelativePath` // always returns fully-qualified path private fun String?.configPath(): String? = this?.removePrefix("::")
mit
f74a0b25017c75ac14f8bc6917ae2cdd
38.178947
128
0.709296
5.140884
false
true
false
false
ktorio/ktor
ktor-shared/ktor-resources/common/src/io/ktor/resources/serialization/ResourcesFormat.kt
1
3590
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.resources.serialization import io.ktor.http.* import io.ktor.resources.* import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.modules.* /** * A format to (de)serialize resources instances */ @OptIn(ExperimentalSerializationApi::class) public class ResourcesFormat( override val serializersModule: SerializersModule = EmptySerializersModule ) : SerialFormat { /** * A query parameter description */ public data class Parameter( val name: String, val isOptional: Boolean ) /** * Builds a path pattern for a given [serializer] */ public fun <T> encodeToPathPattern(serializer: KSerializer<T>): String { val pathBuilder = StringBuilder() var current: SerialDescriptor? = serializer.descriptor while (current != null) { val path = current.annotations.filterIsInstance<Resource>().first().path val addSlash = pathBuilder.isNotEmpty() && !pathBuilder.startsWith('/') && !path.endsWith('/') if (addSlash) { pathBuilder.insert(0, '/') } pathBuilder.insert(0, path) val membersWithAnnotations = current.elementDescriptors.filter { it.annotations.any { it is Resource } } if (membersWithAnnotations.size > 1) { throw ResourceSerializationException("There are multiple parents for resource ${current.serialName}") } current = membersWithAnnotations.firstOrNull() } if (pathBuilder.startsWith('/')) { pathBuilder.deleteAt(0) } return pathBuilder.toString() } /** * Builds a description of query parameters for a given [serializer] */ public fun <T> encodeToQueryParameters(serializer: KSerializer<T>): Set<Parameter> { val path = encodeToPathPattern(serializer) val allParameters = mutableSetOf<Parameter>() collectAllParameters(serializer.descriptor, allParameters) return allParameters .filterNot { (name, _) -> path.contains("{$name}") || path.contains("{$name?}") || path.contains("{$name...}") } .toSet() } private fun collectAllParameters(descriptor: SerialDescriptor, result: MutableSet<Parameter>) { descriptor.elementNames.forEach { name -> val index = descriptor.getElementIndex(name) val elementDescriptor = descriptor.getElementDescriptor(index) if (!elementDescriptor.isInline && elementDescriptor.kind is StructureKind.CLASS) { collectAllParameters(elementDescriptor, result) } else { result.add(Parameter(name, descriptor.isElementOptional(index))) } } } /** * Builds [Parameters] for a resource [T] */ public fun <T> encodeToParameters(serializer: KSerializer<T>, value: T): Parameters { val encoder = ParametersEncoder(serializersModule) encoder.encodeSerializableValue(serializer, value) return encoder.parameters } /** * Builds a [T] resource instance from [parameters] */ public fun <T> decodeFromParameters(deserializer: KSerializer<T>, parameters: Parameters): T { val input = ParametersDecoder(serializersModule, parameters, emptyList()) return input.decodeSerializableValue(deserializer) } }
apache-2.0
0c1a27a8258610e6c8976c2108f70ecc
34.544554
119
0.646797
5.106686
false
false
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Generic/MutableTVec2.kt
1
13202
package glm data class MutableTVec2<T>(var x: T, var y: T) { // Initializes each element by evaluating init from 0 until 1 constructor(init: (Int) -> T) : this(init(0), init(1)) operator fun get(idx: Int): T = when (idx) { 0 -> x 1 -> y else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } operator fun set(idx: Int, value: T) = when (idx) { 0 -> x = value 1 -> y = value else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators inline fun map(func: (T) -> T): MutableTVec2<T> = MutableTVec2(func(x), func(y)) fun toList(): List<T> = listOf(x, y) // Predefined vector constants companion object Constants { } // Conversions to Float inline fun toVec(conv: (T) -> Float): Vec2 = Vec2(conv(x), conv(y)) inline fun toVec2(conv: (T) -> Float): Vec2 = Vec2(conv(x), conv(y)) inline fun toVec3(z: Float = 0f, conv: (T) -> Float): Vec3 = Vec3(conv(x), conv(y), z) inline fun toVec4(z: Float = 0f, w: Float = 0f, conv: (T) -> Float): Vec4 = Vec4(conv(x), conv(y), z, w) // Conversions to Float inline fun toMutableVec(conv: (T) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) inline fun toMutableVec2(conv: (T) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) inline fun toMutableVec3(z: Float = 0f, conv: (T) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), z) inline fun toMutableVec4(z: Float = 0f, w: Float = 0f, conv: (T) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), z, w) // Conversions to Double inline fun toDoubleVec(conv: (T) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) inline fun toDoubleVec2(conv: (T) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) inline fun toDoubleVec3(z: Double = 0.0, conv: (T) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), z) inline fun toDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (T) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), z, w) // Conversions to Double inline fun toMutableDoubleVec(conv: (T) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) inline fun toMutableDoubleVec2(conv: (T) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) inline fun toMutableDoubleVec3(z: Double = 0.0, conv: (T) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), z) inline fun toMutableDoubleVec4(z: Double = 0.0, w: Double = 0.0, conv: (T) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), z, w) // Conversions to Int inline fun toIntVec(conv: (T) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) inline fun toIntVec2(conv: (T) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) inline fun toIntVec3(z: Int = 0, conv: (T) -> Int): IntVec3 = IntVec3(conv(x), conv(y), z) inline fun toIntVec4(z: Int = 0, w: Int = 0, conv: (T) -> Int): IntVec4 = IntVec4(conv(x), conv(y), z, w) // Conversions to Int inline fun toMutableIntVec(conv: (T) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) inline fun toMutableIntVec2(conv: (T) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) inline fun toMutableIntVec3(z: Int = 0, conv: (T) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), z) inline fun toMutableIntVec4(z: Int = 0, w: Int = 0, conv: (T) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), z, w) // Conversions to Long inline fun toLongVec(conv: (T) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) inline fun toLongVec2(conv: (T) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) inline fun toLongVec3(z: Long = 0L, conv: (T) -> Long): LongVec3 = LongVec3(conv(x), conv(y), z) inline fun toLongVec4(z: Long = 0L, w: Long = 0L, conv: (T) -> Long): LongVec4 = LongVec4(conv(x), conv(y), z, w) // Conversions to Long inline fun toMutableLongVec(conv: (T) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) inline fun toMutableLongVec2(conv: (T) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) inline fun toMutableLongVec3(z: Long = 0L, conv: (T) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), z) inline fun toMutableLongVec4(z: Long = 0L, w: Long = 0L, conv: (T) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), z, w) // Conversions to Short inline fun toShortVec(conv: (T) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) inline fun toShortVec2(conv: (T) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) inline fun toShortVec3(z: Short = 0.toShort(), conv: (T) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), z) inline fun toShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (T) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), z, w) // Conversions to Short inline fun toMutableShortVec(conv: (T) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) inline fun toMutableShortVec2(conv: (T) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) inline fun toMutableShortVec3(z: Short = 0.toShort(), conv: (T) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), z) inline fun toMutableShortVec4(z: Short = 0.toShort(), w: Short = 0.toShort(), conv: (T) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), z, w) // Conversions to Byte inline fun toByteVec(conv: (T) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) inline fun toByteVec2(conv: (T) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) inline fun toByteVec3(z: Byte = 0.toByte(), conv: (T) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), z) inline fun toByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (T) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), z, w) // Conversions to Byte inline fun toMutableByteVec(conv: (T) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) inline fun toMutableByteVec2(conv: (T) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) inline fun toMutableByteVec3(z: Byte = 0.toByte(), conv: (T) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), z) inline fun toMutableByteVec4(z: Byte = 0.toByte(), w: Byte = 0.toByte(), conv: (T) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), z, w) // Conversions to Char inline fun toCharVec(conv: (T) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) inline fun toCharVec2(conv: (T) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) inline fun toCharVec3(z: Char, conv: (T) -> Char): CharVec3 = CharVec3(conv(x), conv(y), z) inline fun toCharVec4(z: Char, w: Char, conv: (T) -> Char): CharVec4 = CharVec4(conv(x), conv(y), z, w) // Conversions to Char inline fun toMutableCharVec(conv: (T) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) inline fun toMutableCharVec2(conv: (T) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) inline fun toMutableCharVec3(z: Char, conv: (T) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), z) inline fun toMutableCharVec4(z: Char, w: Char, conv: (T) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), z, w) // Conversions to Boolean inline fun toBoolVec(conv: (T) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) inline fun toBoolVec2(conv: (T) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) inline fun toBoolVec3(z: Boolean = false, conv: (T) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), z) inline fun toBoolVec4(z: Boolean = false, w: Boolean = false, conv: (T) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), z, w) // Conversions to Boolean inline fun toMutableBoolVec(conv: (T) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) inline fun toMutableBoolVec2(conv: (T) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) inline fun toMutableBoolVec3(z: Boolean = false, conv: (T) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), z) inline fun toMutableBoolVec4(z: Boolean = false, w: Boolean = false, conv: (T) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), z, w) // Conversions to String fun toStringVec(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec(conv: (T) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (T) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(z: String = ""): StringVec3 = StringVec3(x.toString(), y.toString(), z) inline fun toStringVec3(z: String = "", conv: (T) -> String): StringVec3 = StringVec3(conv(x), conv(y), z) fun toStringVec4(z: String = "", w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z, w) inline fun toStringVec4(z: String = "", w: String = "", conv: (T) -> String): StringVec4 = StringVec4(conv(x), conv(y), z, w) // Conversions to String fun toMutableStringVec(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec(conv: (T) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (T) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(z: String = ""): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z) inline fun toMutableStringVec3(z: String = "", conv: (T) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), z) fun toMutableStringVec4(z: String = "", w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z, w) inline fun toMutableStringVec4(z: String = "", w: String = "", conv: (T) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), z, w) // Conversions to T2 inline fun <T2> toTVec(conv: (T) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec2(conv: (T) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(z: T2, conv: (T) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), z) inline fun <T2> toTVec4(z: T2, w: T2, conv: (T) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), z, w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (T) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec2(conv: (T) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(z: T2, conv: (T) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), z) inline fun <T2> toMutableTVec4(z: T2, w: T2, conv: (T) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), z, w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: MutableTVec2<T> get() = MutableTVec2(x, x) var xy: MutableTVec2<T> get() = MutableTVec2(x, y) set(value) { x = value.x y = value.y } var yx: MutableTVec2<T> get() = MutableTVec2(y, x) set(value) { y = value.x x = value.y } val yy: MutableTVec2<T> get() = MutableTVec2(y, y) val xxx: MutableTVec3<T> get() = MutableTVec3(x, x, x) val xxy: MutableTVec3<T> get() = MutableTVec3(x, x, y) val xyx: MutableTVec3<T> get() = MutableTVec3(x, y, x) val xyy: MutableTVec3<T> get() = MutableTVec3(x, y, y) val yxx: MutableTVec3<T> get() = MutableTVec3(y, x, x) val yxy: MutableTVec3<T> get() = MutableTVec3(y, x, y) val yyx: MutableTVec3<T> get() = MutableTVec3(y, y, x) val yyy: MutableTVec3<T> get() = MutableTVec3(y, y, y) val xxxx: MutableTVec4<T> get() = MutableTVec4(x, x, x, x) val xxxy: MutableTVec4<T> get() = MutableTVec4(x, x, x, y) val xxyx: MutableTVec4<T> get() = MutableTVec4(x, x, y, x) val xxyy: MutableTVec4<T> get() = MutableTVec4(x, x, y, y) val xyxx: MutableTVec4<T> get() = MutableTVec4(x, y, x, x) val xyxy: MutableTVec4<T> get() = MutableTVec4(x, y, x, y) val xyyx: MutableTVec4<T> get() = MutableTVec4(x, y, y, x) val xyyy: MutableTVec4<T> get() = MutableTVec4(x, y, y, y) val yxxx: MutableTVec4<T> get() = MutableTVec4(y, x, x, x) val yxxy: MutableTVec4<T> get() = MutableTVec4(y, x, x, y) val yxyx: MutableTVec4<T> get() = MutableTVec4(y, x, y, x) val yxyy: MutableTVec4<T> get() = MutableTVec4(y, x, y, y) val yyxx: MutableTVec4<T> get() = MutableTVec4(y, y, x, x) val yyxy: MutableTVec4<T> get() = MutableTVec4(y, y, x, y) val yyyx: MutableTVec4<T> get() = MutableTVec4(y, y, y, x) val yyyy: MutableTVec4<T> get() = MutableTVec4(y, y, y, y) } val swizzle: Swizzle get() = Swizzle() } fun <T> mutableVecOf(x: T, y: T): MutableTVec2<T> = MutableTVec2(x, y)
mit
c52c9c8d7ec015eecbdbe25a577d13f2
64.356436
162
0.628693
3.27025
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/webtoon/WebtoonTransitionHolder.kt
2
5082
package eu.kanade.tachiyomi.ui.reader.viewer.webtoon import android.view.Gravity import android.view.ViewGroup.LayoutParams.MATCH_PARENT import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.LinearLayout import androidx.appcompat.widget.AppCompatButton import androidx.appcompat.widget.AppCompatTextView import androidx.core.view.isNotEmpty import androidx.core.view.isVisible import com.google.android.material.progressindicator.CircularProgressIndicator import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.ui.reader.model.ChapterTransition import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter import eu.kanade.tachiyomi.ui.reader.viewer.ReaderTransitionView import eu.kanade.tachiyomi.util.system.dpToPx import rx.Subscription import rx.android.schedulers.AndroidSchedulers /** * Holder of the webtoon viewer that contains a chapter transition. */ class WebtoonTransitionHolder( val layout: LinearLayout, viewer: WebtoonViewer ) : WebtoonBaseHolder(layout, viewer) { /** * Subscription for status changes of the transition page. */ private var statusSubscription: Subscription? = null private val transitionView = ReaderTransitionView(context) /** * View container of the current status of the transition page. Child views will be added * dynamically. */ private var pagesContainer = LinearLayout(context).apply { orientation = LinearLayout.VERTICAL gravity = Gravity.CENTER } init { layout.layoutParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT) layout.orientation = LinearLayout.VERTICAL layout.gravity = Gravity.CENTER val paddingVertical = 48.dpToPx val paddingHorizontal = 32.dpToPx layout.setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical) val childMargins = 16.dpToPx val childParams = LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { setMargins(0, childMargins, 0, childMargins) } layout.addView(transitionView) layout.addView(pagesContainer, childParams) } /** * Binds the given [transition] with this view holder, subscribing to its state. */ fun bind(transition: ChapterTransition) { transitionView.bind(transition) transition.to?.let { observeStatus(it, transition) } } /** * Called when the view is recycled and being added to the view pool. */ override fun recycle() { unsubscribeStatus() } /** * Observes the status of the page list of the next/previous chapter. Whenever there's a new * state, the pages container is cleaned up before setting the new state. */ private fun observeStatus(chapter: ReaderChapter, transition: ChapterTransition) { unsubscribeStatus() statusSubscription = chapter.stateObserver .observeOn(AndroidSchedulers.mainThread()) .subscribe { state -> pagesContainer.removeAllViews() when (state) { is ReaderChapter.State.Wait -> { } is ReaderChapter.State.Loading -> setLoading() is ReaderChapter.State.Error -> setError(state.error, transition) is ReaderChapter.State.Loaded -> setLoaded() } pagesContainer.isVisible = pagesContainer.isNotEmpty() } addSubscription(statusSubscription) } /** * Unsubscribes from the status subscription. */ private fun unsubscribeStatus() { removeSubscription(statusSubscription) statusSubscription = null } /** * Sets the loading state on the pages container. */ private fun setLoading() { val progress = CircularProgressIndicator(context) progress.isIndeterminate = true val textView = AppCompatTextView(context).apply { wrapContent() setText(R.string.transition_pages_loading) } pagesContainer.addView(progress) pagesContainer.addView(textView) } /** * Sets the loaded state on the pages container. */ private fun setLoaded() { // No additional view is added } /** * Sets the error state on the pages container. */ private fun setError(error: Throwable, transition: ChapterTransition) { val textView = AppCompatTextView(context).apply { wrapContent() text = context.getString(R.string.transition_pages_error, error.message) } val retryBtn = AppCompatButton(context).apply { wrapContent() setText(R.string.action_retry) setOnClickListener { val toChapter = transition.to if (toChapter != null) { viewer.activity.requestPreloadChapter(toChapter) } } } pagesContainer.addView(textView) pagesContainer.addView(retryBtn) } }
apache-2.0
969d1cf2591add1ec976192a8b8cdda2
31.576923
97
0.662928
5.061753
false
false
false
false
ClearVolume/scenery
src/main/kotlin/graphics/scenery/controls/behaviours/GamepadRotationControl.kt
2
4236
package graphics.scenery.controls.behaviours import graphics.scenery.Camera import graphics.scenery.Node import graphics.scenery.utils.LazyLogger import net.java.games.input.Component import org.joml.Quaternionf import kotlin.math.abs import kotlin.reflect.KProperty /** * Implementation of GamepadBehaviour for Camera Control * * @author Ulrik Günther <[email protected]> * @property[axis] List of axis that are assigned to this behaviour * @property[node] The node to control * @property[sensitivity] A multiplier applied to axis inputs. */ open class GamepadRotationControl(override val axis: List<Component.Identifier>, var sensitivity: Float = 1.0f, var invertX: Boolean = false, var invertY: Boolean = false, private val n: () -> Node?) : GamepadBehaviour { private var lastX: Float = 0.0f private var lastY: Float = 0.0f private var firstEntered = true private val logger by LazyLogger() /** The [graphics.scenery.Node] this behaviour class controls */ protected var node: Node? by NodeDelegate() protected inner class NodeDelegate { /** Returns the [graphics.scenery.Node] resulting from the evaluation of [n] */ operator fun getValue(thisRef: Any?, property: KProperty<*>): Node? { return n.invoke() } /** Setting the value is not supported */ operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Node?) { throw UnsupportedOperationException() } } /** Pitch angle calculated from the axis position */ private var pitch: Float = 0.0f /** Yaw angle calculated from the axis position */ private var yaw: Float = 0.0f /** Threshold below which the behaviour will not trigger */ var threshold = 0.05f private var inversionFactorX = 1.0f private var inversionFactorY = 1.0f /** * This function is trigger upon arrival of an axis event that * concerns this behaviour. It takes the event's value, as well as the * other axis' state to construct pitch and yaw angles and reorients * the camera. * * @param[axis] The gamepad axis. * @param[value] The absolute value of the gamepad axis. */ @Synchronized override fun axisEvent(axis: Component.Identifier, value: Float) { val n = node ?: return if(abs(value) < threshold) { return } inversionFactorX = if(invertX) { -1.0f } else { 1.0f } inversionFactorY = if(invertY) { -1.0f } else { 1.0f } val x: Float val y: Float if(axis == this.axis.first()) { x = value y = lastY } else { x = lastX y = value } if (firstEntered) { lastX = x lastY = y firstEntered = false } val xoffset: Float = x * sensitivity * inversionFactorX val yoffset: Float = y * sensitivity * inversionFactorY lastX = x lastY = y yaw += xoffset pitch += yoffset val frameYaw = xoffset / 180.0f * Math.PI.toFloat() val framePitch = yoffset / 180.0f * Math.PI.toFloat() logger.trace("Pitch={} Yaw={}", framePitch, frameYaw) if(n is Camera) { if (pitch > 89.0f) { pitch = 89.0f } if (pitch < -89.0f) { pitch = -89.0f } n.spatial { val yawQ = Quaternionf().rotateXYZ(0.0f, frameYaw, 0.0f) val pitchQ = Quaternionf().rotateXYZ(framePitch, 0.0f, 0.0f) rotation = pitchQ.mul(rotation).mul(yawQ).normalize() } } else { n.ifSpatial { if(axis != [email protected]()) { rotation = rotation.rotateLocalY(framePitch).normalize() } else { rotation = rotation.rotateLocalX(frameYaw).normalize() } } } } }
lgpl-3.0
de13e2cccd142bcd7bbe5f4d99122ce0
29.688406
87
0.560803
4.393154
false
false
false
false
pureal-code/pureal-os
android.backend/src/net/pureal/android/backend/GlScreen.kt
1
5454
package net.pureal.android.backend import android.opengl.GLSurfaceView import android.opengl.GLSurfaceView.Renderer import javax.microedition.khronos.opengles.GL10 import javax.microedition.khronos.egl.EGLConfig import android.opengl.GLES20 import android.app.Activity import net.pureal.traits.graphics.* import net.pureal.traits.math.* import net.pureal.traits.* import android.view.MotionEvent import net.pureal.traits.interaction.* import android.view.KeyEvent class GlScreen (activity: Activity, onReady: (GlScreen) -> Unit) : GLSurfaceView(activity), Screen { init { setEGLContextClientVersion(2) setEGLConfigChooser(8, 8, 8, 8, 16, 0) } init { setRenderer(object : Renderer { override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) { GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) GLES20.glEnable(GLES20.GL_BLEND) GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA) onReady(this@GlScreen) } override fun onSurfaceChanged(gl: GL10?, width: Int, height: Int) { GLES20.glViewport(0, 0, width, height) } override fun onDrawFrame(gl: GL10?) { GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT) glContent.draw(Transforms2.scale(2f / [email protected]().toFloat(), 2f / [email protected]().toFloat())) } }) //setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY) this.setFocusable(true); this.setFocusableInTouchMode(true); } private var glContent: GlComposed = GlComposed(composed(observableIterable(listOf())), this) override var content: Composed<*> get() = glContent.original set(value) { glContent = value as? GlComposed ?: GlComposed(value, this) } override val shape: Rectangle get() = rectangle(vector([email protected](), [email protected]())) val fontShader = GlShader( vertexShaderCode = """ uniform mat4 u_Matrix; attribute vec4 a_Position; attribute vec2 a_TexCoord; varying vec2 v_TexCoord; varying vec2 v_TexCoord2; void main() { v_TexCoord = a_TexCoord; v_TexCoord2 = 64.0*a_TexCoord; gl_Position = u_Matrix * a_Position; } """, fragmentShaderCode = """ #extension GL_OES_standard_derivatives : require precision mediump float; uniform vec4 u_Color; varying vec2 v_TexCoord; varying highp vec2 v_TexCoord2; uniform sampler2D u_Texture; void main() { float distance = texture2D(u_Texture, v_TexCoord).a; float smoothing = length(vec2(dFdx(v_TexCoord2.x), dFdy(v_TexCoord2.x))) + length(vec2(dFdx(v_TexCoord2.y), dFdy(v_TexCoord2.y))); float alpha = smoothstep(0.5 - smoothing, 0.5 + smoothing, distance); gl_FragColor = vec4(u_Color.rgb, alpha); } """) val flatShader = GlShader( vertexShaderCode = """ uniform mat4 u_Matrix; attribute vec4 a_Position; void main() { gl_Position = u_Matrix * a_Position; } """, fragmentShaderCode = """ precision mediump float; uniform vec4 u_Color; void main() { gl_FragColor = u_Color; } """) override fun onTouchEvent(event : MotionEvent) : Boolean { val location = Transforms2.scale(1, -1)(vector(event.getX(), event.getY()) - shape.halfSize) when(event.getAction()) { MotionEvent.ACTION_DOWN -> { pointer.move(location) ; touch.press() } MotionEvent.ACTION_UP -> { pointer.move(location) ; touch.release() } MotionEvent.ACTION_MOVE -> pointer.move(location) } return true } class AndroidKey(val command: Command) : Key { override val definition: KeyDefinition = keyDefinition(command) override var isPressed: Boolean = false override val pressed = trigger<Key>() override val released = trigger<Key>() fun press() { isPressed = true pressed(this) } fun release() { isPressed = false released(this) } } class TouchPointer : Pointer { override val moved = trigger<Pointer>() override var location: Vector2 = zeroVector2 fun move(location : Vector2) { this.location = location moved(this) } } val touch = AndroidKey(Commands.Touch.touch) val pointer = TouchPointer() val pointerKeys : PointerKeys = pointerKeys(pointer, listOf(touch)) val keyboard = observableList<Key>() override fun onKeyDown(keyCode: Int, event : KeyEvent) : Boolean { val key = AndroidKey(Commands.Keyboard.character(event.getKeyCharacterMap()!!.getDisplayLabel(keyCode))) keyboard.add(key) key.press() key.release() keyboard.remove(key) return true } }
bsd-3-clause
8e81a053833630bc8d5d8477b206ba87
34.647059
132
0.571507
4.419773
false
false
false
false
mdanielwork/intellij-community
uast/uast-common/src/org/jetbrains/uast/evaluation/UEvaluationInfo.kt
4
1358
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.uast.evaluation import org.jetbrains.uast.values.UValue data class UEvaluationInfo(val value: UValue, val state: UEvaluationState) { fun merge(otherInfo: UEvaluationInfo): UEvaluationInfo { // info with 'UNothingValue' is just ignored, if other is not UNothingValue if (!reachable && otherInfo.reachable) return otherInfo if (!otherInfo.reachable && reachable) return this // Regular merge val mergedValue = value.merge(otherInfo.value) val mergedState = state.merge(otherInfo.state) return UEvaluationInfo(mergedValue, mergedState) } fun copy(value: UValue): UEvaluationInfo = if (value != this.value) UEvaluationInfo(value, state) else this val reachable: Boolean get() = value.reachable }
apache-2.0
a1a38a7b93827eaf01426f803c15d87c
37.828571
109
0.745214
4.311111
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/IfExpr.kt
1
3236
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.KoresPart import com.github.jonathanxd.kores.operator.Operator /** * Condition evaluation. * * @property expr1 First expression * @property operation Operation * @property expr2 Second expression * @see IfStatement */ data class IfExpr( val expr1: Instruction, val operation: Operator.Conditional, val expr2: Instruction ) : KoresPart, Instruction { override fun builder(): Builder = Builder(this) class Builder() : com.github.jonathanxd.kores.builder.Builder<IfExpr, Builder> { lateinit var expr1: Instruction lateinit var operation: Operator.Conditional lateinit var expr2: Instruction constructor(defaults: IfExpr) : this() { this.expr1 = defaults.expr1 this.operation = defaults.operation this.expr2 = defaults.expr2 } /** * See [IfExpr.expr1] */ fun expr1(value: Instruction): Builder { this.expr1 = value return this } /** * See [IfExpr.operation] */ fun operation(value: Operator.Conditional): Builder { this.operation = value return this } /** * See [IfExpr.expr2] */ fun expr2(value: Instruction): Builder { this.expr2 = value return this } override fun build(): IfExpr = IfExpr(this.expr1, this.operation, this.expr2) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: IfExpr): Builder = Builder(defaults) } } }
mit
38e9e2372a3fa511d9ecca37066badfc
32.020408
118
0.646477
4.557746
false
false
false
false
CrystalLord/plounge-quoter
src/main/kotlin/org/crystal/ploungequoter/BackgroundRetriever.kt
1
2429
package org.crystal.ploungequoter import java.io.File import java.io.BufferedInputStream import java.io.FileOutputStream import java.net.URL import java.nio.file.Path import java.nio.file.Paths import org.apache.commons.io.FilenameUtils class BackgroundRetriever(input: String) { val downloaded: Boolean lateinit var path: Path lateinit var file: File init { val httpPrefix: String = "http://" val httpsPrefix: String = "https://" if (input.subSequence(0,httpPrefix.length) == httpPrefix || input.subSequence(0,httpsPrefix.length) == httpsPrefix) { this.downloaded = true File(System.getProperty("java.io.tmpdir")).mkdir() val downloadDirectory: Path = Paths.get( System.getProperty("java.io.tmpdir") ) download(URL(input), downloadDirectory) } else { this.downloaded = false this.path = Paths.get(input) this.file = File(input) } } /** * Download a file from a URL to */ fun download(url: URL, directory: Path) { // Use a hash as a basename to prevent unrelated overlaps. val basename: String = url.hashCode().toString() this.path = directory.resolve(basename) val hashName: String = url.hashCode().toString() this.file = File(directory.resolve(hashName).toString()) if (this.file.exists() && !this.file.isDirectory) { println("Download file already cached in: " + directory) return } println("Downloading background... this may take a bit.") // Retrieval stream for online content val bis: BufferedInputStream = BufferedInputStream(url.openStream()) // File write stream for local content val fis: FileOutputStream = FileOutputStream(this.file) val buffer: ByteArray = ByteArray(1024) var count: Int = bis.read(buffer, 0, 1024) while (count != -1) { fis.write(buffer, 0, count) count = bis.read(buffer, 0, 1024) } fis.close() bis.close() println("Downloaded to: " + directory) } fun deleteFile() { if (!this.downloaded) { throw RuntimeException("Attempted to delete non-downloaded file.") } else { println("Did not delete downloaded file yet...") } } }
apache-2.0
ceaaf7ac1ddec806f619b0fdd5e5b8f7
31.837838
78
0.603541
4.424408
false
false
false
false
chriswk/listicle
src/main/kotlin/com/chriswk/listicle/country/CountryController.kt
1
856
package com.chriswk.listicle.country import org.apache.log4j.LogManager import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RestController @RestController(value = "/country") class CountryController(val repository: CountryRepository) { val logger: Logger = LoggerFactory.getLogger("CountryController") @GetMapping("/country") fun findAll() = repository.findAll() @GetMapping("/country/alpha2/{code}") fun findByCode(@PathVariable("code") code: String) = repository.findByIso3166Alpha2(code.toUpperCase()) @GetMapping("/country/alpha3/{code}") fun findBy3LetterCode(@PathVariable("code") code: String) = repository.findByIso3166Alpha3(code.toUpperCase()) }
apache-2.0
d845e5e675c269e75760b8d4e1150c99
37.954545
114
0.783879
4.07619
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/notification/MessageNotification.kt
1
6874
package jp.juggler.subwaytooter.notification import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.provider.Settings import androidx.core.app.NotificationCompat import androidx.core.content.ContextCompat import jp.juggler.subwaytooter.ActCallback import jp.juggler.subwaytooter.EventReceiver import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.util.LogCategory import jp.juggler.util.encodePercent import jp.juggler.util.toMutableMap import jp.juggler.util.toUri object MessageNotification { private val log = LogCategory("MessageNotification") private const val NOTIFICATION_ID_MESSAGE = 1 const val TRACKING_NAME_DEFAULT = "" const val TRACKING_NAME_REPLY = "reply" /** * メッセージ通知を消す */ fun NotificationManager.removeMessageNotification(id: String?, tag: String) { when (id) { null -> cancel(tag, NOTIFICATION_ID_MESSAGE) else -> cancel("$tag/$id", NOTIFICATION_ID_MESSAGE) } } /** メッセージ通知をたくさん消す * */ fun NotificationManager.removeMessageNotification(account: SavedAccount, tag: String) { if (PrefB.bpDivideNotification()) { activeNotifications?.filterNotNull()?.filter { it.id == NOTIFICATION_ID_MESSAGE && it.tag.startsWith("$tag/") }?.forEach { log.d("cancel: ${it.tag} context=${account.acct.pretty} $tag") cancel(it.tag, NOTIFICATION_ID_MESSAGE) } } else { cancel(tag, NOTIFICATION_ID_MESSAGE) } } /** * 表示中のメッセージ通知の一覧 */ fun NotificationManager.getMessageNotifications(tag: String) = activeNotifications?.filterNotNull()?.filter { it.id == NOTIFICATION_ID_MESSAGE && it.tag.startsWith("$tag/") }?.map { Pair(it.tag, it) }?.toMutableMap() ?: mutableMapOf() fun NotificationManager.showMessageNotification( context: Context, account: SavedAccount, trackingName: String, trackingType: TrackingType, notificationTag: String, notificationId: String? = null, setContent: (builder: NotificationCompat.Builder) -> Unit, ) { log.d("showNotification[${account.acct.pretty}] creating notification(1)") // Android 8 から、通知のスタイルはユーザが管理することになった // NotificationChannel を端末に登録しておけば、チャネルごとに管理画面が作られる val channel = createMessageNotificationChannel( context, account, trackingName ) val builder = NotificationCompat.Builder(context, channel.id) builder.apply { val params = listOf( "db_id" to account.db_id.toString(), "type" to trackingType.str, "notificationId" to notificationId ).mapNotNull { when (val second = it.second) { null -> null else -> "${it.first.encodePercent()}=${second.encodePercent()}" } }.joinToString("&") val flag = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE PendingIntent.getActivity( context, 257, Intent(context, ActCallback::class.java).apply { data = "subwaytooter://notification_click/?$params".toUri() // FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY を付与してはいけない addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }, flag )?.let { setContentIntent(it) } PendingIntent.getBroadcast( context, 257, Intent(context, EventReceiver::class.java).apply { action = EventReceiver.ACTION_NOTIFICATION_DELETE data = "subwaytooter://notification_delete/?$params".toUri() }, flag )?.let { setDeleteIntent(it) } setAutoCancel(true) // 常に白テーマのアイコンを使う setSmallIcon(R.drawable.ic_notification) // 常に白テーマの色を使う builder.color = ContextCompat.getColor(context, R.color.Light_colorAccent) // Android 7.0 ではグループを指定しないと勝手に通知が束ねられてしまう。 // 束ねられた通知をタップしても pi_click が実行されないので困るため、 // アカウント別にグループキーを設定する setGroup(context.packageName + ":" + account.acct.ascii) } log.d("showNotification[${account.acct.pretty}] creating notification(3)") setContent(builder) log.d("showNotification[${account.acct.pretty}] set notification...") notify( notificationTag, NOTIFICATION_ID_MESSAGE, builder.build() ) } private fun createMessageNotificationChannel( context: Context, account: SavedAccount, trackingName: String, ) = when (trackingName) { "" -> NotificationHelper.createNotificationChannel( context, account.acct.ascii, // id account.acct.pretty, // name context.getString(R.string.notification_channel_description, account.acct.pretty), NotificationManager.IMPORTANCE_DEFAULT // : NotificationManager.IMPORTANCE_LOW; ) else -> NotificationHelper.createNotificationChannel( context, "${account.acct.ascii}/$trackingName", // id "${account.acct.pretty}/$trackingName", // name context.getString(R.string.notification_channel_description, account.acct.pretty), NotificationManager.IMPORTANCE_DEFAULT // : NotificationManager.IMPORTANCE_LOW; ) } fun openNotificationChannelSetting( context: Context, account: SavedAccount, trackingName: String, ) { val channel = createMessageNotificationChannel(context, account, trackingName) val intent = Intent("android.settings.CHANNEL_NOTIFICATION_SETTINGS") intent.putExtra(Settings.EXTRA_CHANNEL_ID, channel.id) intent.putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) context.startActivity(intent) } }
apache-2.0
04b38a8440a5e2a1331116a17ce79f14
34.784091
94
0.599784
4.667628
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/utils/IntentWrapper.kt
1
4752
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.utils import android.annotation.SuppressLint import android.app.Activity import android.app.ActivityOptions import android.content.ContextWrapper import android.content.Intent import android.os.Bundle import android.os.Parcelable import androidx.annotation.ColorRes import androidx.fragment.app.Fragment import android.view.View import de.dreier.mytargets.R import de.dreier.mytargets.utils.transitions.FabTransform class IntentWrapper( private var activity: Activity, var fragment: Fragment? = null, intentTargetClass: Class<*> ) { private val intent = Intent(activity, intentTargetClass) private var options: Bundle? = null private var requestCode: Int? = null private var animate = true fun with(key: String, value: Long): IntentWrapper { intent.putExtra(key, value) return this } fun with(key: String, value: Int): IntentWrapper { intent.putExtra(key, value) return this } fun with(key: String, value: Boolean): IntentWrapper { intent.putExtra(key, value) return this } fun with(key: String, value: String): IntentWrapper { intent.putExtra(key, value) return this } fun <T : Parcelable> with(key: String, value: T): IntentWrapper { intent.putExtra(key, value) return this } fun with(key: String, values: LongArray): IntentWrapper { intent.putExtra(key, values) return this } fun action(action: String): IntentWrapper { intent.action = action return this } @SuppressLint("NewApi") @JvmOverloads fun fromFab( fab: View, @ColorRes color: Int = R.color.colorAccent, icon: Int = R.drawable.ic_add_white_24dp ): IntentWrapper { if (Utils.isLollipop) { fab.transitionName = fab.context.getString(R.string.transition_root_view) FabTransform.addExtras(intent, color, icon) val options = ActivityOptions .makeSceneTransitionAnimation( getActivity(fab), fab, fab.context.getString(R.string.transition_root_view) ) this.options = options.toBundle() } return this } private fun getActivity(view: View): Activity? { var context = view.context while (context is ContextWrapper) { if (context is Activity) { return context } context = context.baseContext } return null } fun forResult(requestCode: Int): IntentWrapper { this.requestCode = requestCode return this } fun noAnimation(): IntentWrapper { intent.flags = intent.flags or Intent.FLAG_ACTIVITY_NO_ANIMATION animate = false return this } fun clearTopSingleTop(): IntentWrapper { intent.addFlags( intent.flags or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP ) return this } fun start() { if (fragment == null) { start(activity) } else { start(fragment!!) } animate(activity) } private fun start(fragment: Fragment) { if (requestCode == null) { fragment.startActivity(intent, options) } else { fragment.startActivityForResult(intent, requestCode!!, options) } } private fun start(activity: Activity) { if (Utils.isLollipop) { if (requestCode == null) { activity.startActivity(intent, options) } else { activity.startActivityForResult(intent, requestCode!!, options) } } else { if (requestCode == null) { activity.startActivity(intent) } else { activity.startActivityForResult(intent, requestCode!!) } } } private fun animate(activity: Activity) { if (!Utils.isLollipop && animate) { activity.overridePendingTransition(R.anim.right_in, R.anim.left_out) } } fun build(): Intent { return intent } }
gpl-2.0
67c6aee3bc6cee5e60fc1e941d9b44a8
27.285714
85
0.616162
4.636098
false
false
false
false
DreierF/MyTargets
shared/src/main/java/de/dreier/mytargets/shared/models/db/EndImage.kt
1
2012
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.shared.models.db import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.ForeignKey.CASCADE import androidx.room.Index import androidx.room.PrimaryKey import android.os.Parcel import android.os.Parcelable import de.dreier.mytargets.shared.models.Image @Entity( foreignKeys = [ ForeignKey( entity = End::class, parentColumns = ["id"], childColumns = ["endId"], onDelete = CASCADE ) ], indices = [ Index(value = ["endId"]) ] ) data class EndImage( @PrimaryKey(autoGenerate = true) var id: Long = 0, override var fileName: String = "", var endId: Long? = null ) : Image, Parcelable { constructor(imageFile: String) : this(fileName = imageFile) constructor(source: Parcel) : this( source.readLong(), source.readString()!!, source.readValue(Long::class.java.classLoader) as Long? ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeLong(id) writeString(fileName) writeValue(endId) } companion object { @JvmField val CREATOR: Parcelable.Creator<EndImage> = object : Parcelable.Creator<EndImage> { override fun createFromParcel(source: Parcel): EndImage = EndImage(source) override fun newArray(size: Int): Array<EndImage?> = arrayOfNulls(size) } } }
gpl-2.0
f06d1770a2aad6ee3fcd663ee230139f
27.338028
91
0.666998
4.345572
false
false
false
false
flesire/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/LabelProviderServiceImpl.kt
1
3753
package net.nemerosa.ontrack.service.labels import net.nemerosa.ontrack.model.labels.LabelProvider import net.nemerosa.ontrack.model.labels.LabelProviderService import net.nemerosa.ontrack.model.labels.ProjectLabelManagement import net.nemerosa.ontrack.model.labels.description import net.nemerosa.ontrack.model.security.SecurityService import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.repository.LabelRepository import net.nemerosa.ontrack.repository.ProjectLabelRepository import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional class LabelProviderServiceImpl( private val providers: List<LabelProvider>, private val securityService: SecurityService, private val labelRepository: LabelRepository, private val projectLabelRepository: ProjectLabelRepository ) : LabelProviderService { private val index: Map<String, LabelProvider> = providers.associateBy { it::class.java.name } override fun getLabelProvider(id: String): LabelProvider? = index[id] override fun collectLabels(project: Project) { securityService.checkProjectFunction(project, ProjectLabelManagement::class.java) // Computes labels for every provider providers.forEach { provider -> collectLabels(project, provider) } } private fun collectLabels(project: Project, provider: LabelProvider) { // Gets all labels for this project and provider val labels = provider.getLabelsForProject(project) // ID of the provider val providerId = provider.description.id // Gets all existing labels for this provider val existingLabels = labelRepository.findLabelsByProvider(providerId) // New labels (forms not found in existing) labels.filter { form -> existingLabels.none { existing -> existing.sameThan(form) } }.forEach { form -> labelRepository.overrideLabel(form, providerId) } // Updates (existing, found in forms with different attributes) existingLabels.filter { existing -> labels.any { form -> // Same category/name, but different attributes existing.sameThan(form) && existing.toLabelForm() != form } }.forEach { label -> // Gets the corresponding form val form = labels.find { label.sameThan(it) } // Saves it if (form != null) { labelRepository.updateAndOverrideLabel(label.id, form, providerId) } } // Deleted associations val existingAssociations = projectLabelRepository.getLabelsForProject(project.id()) .filter { it.computedBy == providerId } existingAssociations.forEach { association -> val existingForm = labels.any { it.category == association.category && it.name == association.name } if (!existingForm) { projectLabelRepository.unassociateProjectToLabel( project.id(), association.id ) } } // New or existing project associations labels.forEach { form -> // Gets record for this label labelRepository.findLabelByCategoryAndNameAndProvider(form.category, form.name, providerId) ?.let { record -> projectLabelRepository.associateProjectToLabel( project.id(), record.id ) } } } }
mit
09bb8870cc7aed9596e804f69f248018
40.711111
103
0.63709
5.278481
false
false
false
false
kmagiera/react-native-gesture-handler
android/lib/src/main/java/com/swmansion/gesturehandler/GestureHandler.kt
1
22881
package com.swmansion.gesturehandler import android.view.MotionEvent import android.view.MotionEvent.PointerCoords import android.view.MotionEvent.PointerProperties import android.view.View import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.UiThreadUtil import com.facebook.react.bridge.WritableArray import com.facebook.react.uimanager.PixelUtil import com.swmansion.gesturehandler.react.RNGestureHandlerTouchEvent import java.lang.IllegalStateException import java.util.* open class GestureHandler<ConcreteGestureHandlerT : GestureHandler<ConcreteGestureHandlerT>> { private val trackedPointerIDs = IntArray(MAX_POINTERS_COUNT) private var trackedPointersIDsCount = 0 var tag = 0 var view: View? = null private set var state = STATE_UNDETERMINED private set var x = 0f private set var y = 0f private set var isWithinBounds = false private set var isEnabled = true private set var usesDeviceEvents = false var changedTouchesPayload: WritableArray? = null private set var allTouchesPayload: WritableArray? = null private set var touchEventType = RNGestureHandlerTouchEvent.EVENT_UNDETERMINED private set var trackedPointersCount = 0 private set private val trackedPointers: Array<PointerData?> = Array(MAX_POINTERS_COUNT) { null } var needsPointerData = false private var hitSlop: FloatArray? = null var eventCoalescingKey: Short = 0 private set var lastAbsolutePositionX = 0f private set var lastAbsolutePositionY = 0f private set private var manualActivation = false private var lastEventOffsetX = 0f private var lastEventOffsetY = 0f private var shouldCancelWhenOutside = false var numberOfPointers = 0 private set private var orchestrator: GestureHandlerOrchestrator? = null private var onTouchEventListener: OnTouchEventListener? = null private var interactionController: GestureHandlerInteractionController? = null @Suppress("UNCHECKED_CAST") protected fun self(): ConcreteGestureHandlerT = this as ConcreteGestureHandlerT protected inline fun applySelf(block: ConcreteGestureHandlerT.() -> Unit): ConcreteGestureHandlerT = self().apply { block() } // set and accessed only by the orchestrator var activationIndex = 0 // set and accessed only by the orchestrator var isActive = false // set and accessed only by the orchestrator var isAwaiting = false open fun dispatchStateChange(newState: Int, prevState: Int) { onTouchEventListener?.onStateChange(self(), newState, prevState) } open fun dispatchHandlerUpdate(event: MotionEvent) { onTouchEventListener?.onHandlerUpdate(self(), event) } open fun dispatchTouchEvent() { if (changedTouchesPayload != null) { onTouchEventListener?.onTouchEvent(self()) } } open fun resetConfig() { needsPointerData = false manualActivation = false shouldCancelWhenOutside = false isEnabled = true hitSlop = null } fun hasCommonPointers(other: GestureHandler<*>): Boolean { for (i in trackedPointerIDs.indices) { if (trackedPointerIDs[i] != -1 && other.trackedPointerIDs[i] != -1) { return true } } return false } fun setShouldCancelWhenOutside(shouldCancelWhenOutside: Boolean): ConcreteGestureHandlerT = applySelf { this.shouldCancelWhenOutside = shouldCancelWhenOutside } fun setEnabled(enabled: Boolean): ConcreteGestureHandlerT = applySelf { // Don't cancel handler when not changing the value of the isEnabled, executing it always caused // handlers to be cancelled on re-render because that's the moment when the config is updated. // If the enabled prop "changed" from true to true the handler would get cancelled. if (view != null && isEnabled != enabled) { // If view is set then handler is in "active" state. In that case we want to "cancel" handler // when it changes enabled state so that it gets cleared from the orchestrator UiThreadUtil.runOnUiThread { cancel() } } isEnabled = enabled } fun setManualActivation(manualActivation: Boolean): ConcreteGestureHandlerT = applySelf { this.manualActivation = manualActivation } fun setHitSlop( leftPad: Float, topPad: Float, rightPad: Float, bottomPad: Float, width: Float, height: Float, ): ConcreteGestureHandlerT = applySelf { if (hitSlop == null) { hitSlop = FloatArray(6) } hitSlop!![HIT_SLOP_LEFT_IDX] = leftPad hitSlop!![HIT_SLOP_TOP_IDX] = topPad hitSlop!![HIT_SLOP_RIGHT_IDX] = rightPad hitSlop!![HIT_SLOP_BOTTOM_IDX] = bottomPad hitSlop!![HIT_SLOP_WIDTH_IDX] = width hitSlop!![HIT_SLOP_HEIGHT_IDX] = height require(!(hitSlopSet(width) && hitSlopSet(leftPad) && hitSlopSet(rightPad))) { "Cannot have all of left, right and width defined" } require(!(hitSlopSet(width) && !hitSlopSet(leftPad) && !hitSlopSet(rightPad))) { "When width is set one of left or right pads need to be defined" } require(!(hitSlopSet(height) && hitSlopSet(bottomPad) && hitSlopSet(topPad))) { "Cannot have all of top, bottom and height defined" } require(!(hitSlopSet(height) && !hitSlopSet(bottomPad) && !hitSlopSet(topPad))) { "When height is set one of top or bottom pads need to be defined" } } fun setHitSlop(padding: Float): ConcreteGestureHandlerT { return setHitSlop(padding, padding, padding, padding, HIT_SLOP_NONE, HIT_SLOP_NONE) } fun setInteractionController(controller: GestureHandlerInteractionController?): ConcreteGestureHandlerT = applySelf { interactionController = controller } fun prepare(view: View?, orchestrator: GestureHandlerOrchestrator?) { check(!(this.view != null || this.orchestrator != null)) { "Already prepared or hasn't been reset" } Arrays.fill(trackedPointerIDs, -1) trackedPointersIDsCount = 0 state = STATE_UNDETERMINED this.view = view this.orchestrator = orchestrator } private fun findNextLocalPointerId(): Int { var localPointerId = 0 while (localPointerId < trackedPointersIDsCount) { var i = 0 while (i < trackedPointerIDs.size) { if (trackedPointerIDs[i] == localPointerId) { break } i++ } if (i == trackedPointerIDs.size) { return localPointerId } localPointerId++ } return localPointerId } fun startTrackingPointer(pointerId: Int) { if (trackedPointerIDs[pointerId] == -1) { trackedPointerIDs[pointerId] = findNextLocalPointerId() trackedPointersIDsCount++ } } fun stopTrackingPointer(pointerId: Int) { if (trackedPointerIDs[pointerId] != -1) { trackedPointerIDs[pointerId] = -1 trackedPointersIDsCount-- } } private fun needAdapt(event: MotionEvent): Boolean { if (event.pointerCount != trackedPointersIDsCount) { return true } for (i in trackedPointerIDs.indices) { val trackedPointer = trackedPointerIDs[i] if (trackedPointer != -1 && trackedPointer != i) { return true } } return false } private fun adaptEvent(event: MotionEvent): MotionEvent { if (!needAdapt(event)) { return event } var action = event.actionMasked var actionIndex = -1 if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_POINTER_DOWN) { actionIndex = event.actionIndex val actionPointer = event.getPointerId(actionIndex) action = if (trackedPointerIDs[actionPointer] != -1) { if (trackedPointersIDsCount == 1) MotionEvent.ACTION_DOWN else MotionEvent.ACTION_POINTER_DOWN } else { MotionEvent.ACTION_MOVE } } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) { actionIndex = event.actionIndex val actionPointer = event.getPointerId(actionIndex) action = if (trackedPointerIDs[actionPointer] != -1) { if (trackedPointersIDsCount == 1) MotionEvent.ACTION_UP else MotionEvent.ACTION_POINTER_UP } else { MotionEvent.ACTION_MOVE } } initPointerProps(trackedPointersIDsCount) var count = 0 val oldX = event.x val oldY = event.y event.setLocation(event.rawX, event.rawY) var index = 0 val size = event.pointerCount while (index < size) { val origPointerId = event.getPointerId(index) if (trackedPointerIDs[origPointerId] != -1) { event.getPointerProperties(index, pointerProps[count]) pointerProps[count]!!.id = trackedPointerIDs[origPointerId] event.getPointerCoords(index, pointerCoords[count]) if (index == actionIndex) { action = action or (count shl MotionEvent.ACTION_POINTER_INDEX_SHIFT) } count++ } index++ } // introduced in 1.11.0, remove if crashes are not reported if(pointerProps.isEmpty()|| pointerCoords.isEmpty()){ throw IllegalStateException("pointerCoords.size=${pointerCoords.size}, pointerProps.size=${pointerProps.size}") } val result: MotionEvent try { result = MotionEvent.obtain( event.downTime, event.eventTime, action, count, pointerProps, /* props are copied and hence it is safe to use static array here */ pointerCoords, /* same applies to coords */ event.metaState, event.buttonState, event.xPrecision, event.yPrecision, event.deviceId, event.edgeFlags, event.source, event.flags ) } catch (e: IllegalArgumentException) { throw AdaptEventException(this, event, e) } event.setLocation(oldX, oldY) result.setLocation(oldX, oldY) return result } // exception to help debug https://github.com/software-mansion/react-native-gesture-handler/issues/1188 class AdaptEventException( handler: GestureHandler<*>, event: MotionEvent, e: IllegalArgumentException ) : Exception(""" handler: ${handler::class.simpleName} state: ${handler.state} view: ${handler.view} orchestrator: ${handler.orchestrator} isEnabled: ${handler.isEnabled} isActive: ${handler.isActive} isAwaiting: ${handler.isAwaiting} trackedPointersCount: ${handler.trackedPointersCount} trackedPointers: ${handler.trackedPointerIDs.joinToString(separator = ", ")} while handling event: $event """.trimIndent(), e) {} fun handle(origEvent: MotionEvent) { if (!isEnabled || state == STATE_CANCELLED || state == STATE_FAILED || state == STATE_END || trackedPointersIDsCount < 1) { return } val event = adaptEvent(origEvent) x = event.x y = event.y numberOfPointers = event.pointerCount isWithinBounds = isWithinBounds(view, x, y) if (shouldCancelWhenOutside && !isWithinBounds) { if (state == STATE_ACTIVE) { cancel() } else if (state == STATE_BEGAN) { fail() } return } lastAbsolutePositionX = GestureUtils.getLastPointerX(event, true) lastAbsolutePositionY = GestureUtils.getLastPointerY(event, true) lastEventOffsetX = event.rawX - event.x lastEventOffsetY = event.rawY - event.y onHandle(event) if (event != origEvent) { event.recycle() } } private fun dispatchTouchDownEvent(event: MotionEvent) { changedTouchesPayload = null touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_DOWN val pointerId = event.getPointerId(event.actionIndex) val offsetX = event.rawX - event.x val offsetY = event.rawY - event.y trackedPointers[pointerId] = PointerData( pointerId, event.getX(event.actionIndex), event.getY(event.actionIndex), event.getX(event.actionIndex) + offsetX, event.getY(event.actionIndex) + offsetY, ) trackedPointersCount++ addChangedPointer(trackedPointers[pointerId]!!) extractAllPointersData() dispatchTouchEvent() } private fun dispatchTouchUpEvent(event: MotionEvent) { extractAllPointersData() changedTouchesPayload = null touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_UP val pointerId = event.getPointerId(event.actionIndex) val offsetX = event.rawX - event.x val offsetY = event.rawY - event.y trackedPointers[pointerId] = PointerData( pointerId, event.getX(event.actionIndex), event.getY(event.actionIndex), event.getX(event.actionIndex) + offsetX, event.getY(event.actionIndex) + offsetY, ) addChangedPointer(trackedPointers[pointerId]!!) trackedPointers[pointerId] = null trackedPointersCount-- dispatchTouchEvent() } private fun dispatchTouchMoveEvent(event: MotionEvent) { changedTouchesPayload = null touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_MOVE val offsetX = event.rawX - event.x val offsetY = event.rawY - event.y var pointersAdded = 0 for (i in 0 until event.pointerCount) { val pointerId = event.getPointerId(i) val pointer = trackedPointers[pointerId] ?: continue if (pointer.x != event.getX(i) || pointer.y != event.getY(i)) { pointer.x = event.getX(i) pointer.y = event.getY(i) pointer.absoluteX = event.getX(i) + offsetX pointer.absoluteY = event.getY(i) + offsetY addChangedPointer(pointer) pointersAdded++ } } // only data about pointers that have changed their position is sent, it makes no sense to send // an empty move event (especially when this method is called during down/up event and there is // only info about one pointer) if (pointersAdded > 0) { extractAllPointersData() dispatchTouchEvent() } } fun updatePointerData(event: MotionEvent) { if (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_POINTER_DOWN) { dispatchTouchDownEvent(event) dispatchTouchMoveEvent(event) } else if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_POINTER_UP) { dispatchTouchMoveEvent(event) dispatchTouchUpEvent(event) } else if (event.actionMasked == MotionEvent.ACTION_MOVE) { dispatchTouchMoveEvent(event) } } private fun extractAllPointersData() { allTouchesPayload = null for (pointerData in trackedPointers) { if (pointerData != null) { addPointerToAll(pointerData) } } } private fun cancelPointers() { touchEventType = RNGestureHandlerTouchEvent.EVENT_TOUCH_CANCELLED changedTouchesPayload = null extractAllPointersData() for (pointer in trackedPointers) { pointer?.let { addChangedPointer(it) } } trackedPointersCount = 0 trackedPointers.fill(null) dispatchTouchEvent() } private fun addChangedPointer(pointerData: PointerData) { if (changedTouchesPayload == null) { changedTouchesPayload = Arguments.createArray() } changedTouchesPayload!!.pushMap(createPointerData(pointerData)) } private fun addPointerToAll(pointerData: PointerData) { if (allTouchesPayload == null) { allTouchesPayload = Arguments.createArray() } allTouchesPayload!!.pushMap(createPointerData(pointerData)) } private fun createPointerData(pointerData: PointerData) = Arguments.createMap().apply { putInt("id", pointerData.pointerId) putDouble("x", PixelUtil.toDIPFromPixel(pointerData.x).toDouble()) putDouble("y", PixelUtil.toDIPFromPixel(pointerData.y).toDouble()) putDouble("absoluteX", PixelUtil.toDIPFromPixel(pointerData.absoluteX).toDouble()) putDouble("absoluteY", PixelUtil.toDIPFromPixel(pointerData.absoluteY).toDouble()) } fun consumeChangedTouchesPayload(): WritableArray? { val result = changedTouchesPayload changedTouchesPayload = null return result } fun consumeAllTouchesPayload(): WritableArray? { val result = allTouchesPayload allTouchesPayload = null return result } private fun moveToState(newState: Int) { UiThreadUtil.assertOnUiThread() if (state == newState) { return } // if there are tracked pointers and the gesture is about to end, send event cancelling all pointers if (trackedPointersCount > 0 && (newState == STATE_END || newState == STATE_CANCELLED || newState == STATE_FAILED)) { cancelPointers() } val oldState = state state = newState if (state == STATE_ACTIVE) { // Generate a unique coalescing-key each time the gesture-handler becomes active. All events will have // the same coalescing-key allowing EventDispatcher to coalesce RNGestureHandlerEvents when events are // generated faster than they can be treated by JS thread eventCoalescingKey = nextEventCoalescingKey++ } orchestrator!!.onHandlerStateChange(this, newState, oldState) onStateChange(newState, oldState) } fun wantEvents(): Boolean { return isEnabled && state != STATE_FAILED && state != STATE_CANCELLED && state != STATE_END && trackedPointersIDsCount > 0 } open fun shouldRequireToWaitForFailure(handler: GestureHandler<*>): Boolean { if (handler === this) { return false } return interactionController?.shouldRequireHandlerToWaitForFailure(this, handler) ?: false } fun shouldWaitForHandlerFailure(handler: GestureHandler<*>): Boolean { if (handler === this) { return false } return interactionController?.shouldWaitForHandlerFailure(this, handler) ?: false } open fun shouldRecognizeSimultaneously(handler: GestureHandler<*>): Boolean { if (handler === this) { return true } return interactionController?.shouldRecognizeSimultaneously(this, handler) ?: false } open fun shouldBeCancelledBy(handler: GestureHandler<*>): Boolean { if (handler === this) { return false } return interactionController?.shouldHandlerBeCancelledBy(this, handler) ?: false } fun isWithinBounds(view: View?, posX: Float, posY: Float): Boolean { var left = 0f var top = 0f var right = view!!.width.toFloat() var bottom = view.height.toFloat() if (hitSlop != null) { val padLeft = hitSlop!![HIT_SLOP_LEFT_IDX] val padTop = hitSlop!![HIT_SLOP_TOP_IDX] val padRight = hitSlop!![HIT_SLOP_RIGHT_IDX] val padBottom = hitSlop!![HIT_SLOP_BOTTOM_IDX] if (hitSlopSet(padLeft)) { left -= padLeft } if (hitSlopSet(padTop)) { top -= padTop } if (hitSlopSet(padRight)) { right += padRight } if (hitSlopSet(padBottom)) { bottom += padBottom } val width = hitSlop!![HIT_SLOP_WIDTH_IDX] val height = hitSlop!![HIT_SLOP_HEIGHT_IDX] if (hitSlopSet(width)) { if (!hitSlopSet(padLeft)) { left = right - width } else if (!hitSlopSet(padRight)) { right = left + width } } if (hitSlopSet(height)) { if (!hitSlopSet(padTop)) { top = bottom - height } else if (!hitSlopSet(padBottom)) { bottom = top + height } } } return posX in left..right && posY in top..bottom } fun cancel() { if (state == STATE_ACTIVE || state == STATE_UNDETERMINED || state == STATE_BEGAN) { onCancel() moveToState(STATE_CANCELLED) } } fun fail() { if (state == STATE_ACTIVE || state == STATE_UNDETERMINED || state == STATE_BEGAN) { moveToState(STATE_FAILED) } } fun activate() = activate(force = false) open fun activate(force: Boolean) { if ((!manualActivation || force) && (state == STATE_UNDETERMINED || state == STATE_BEGAN)) { moveToState(STATE_ACTIVE) } } fun begin() { if (state == STATE_UNDETERMINED) { moveToState(STATE_BEGAN) } } fun end() { if (state == STATE_BEGAN || state == STATE_ACTIVE) { moveToState(STATE_END) } } protected open fun onHandle(event: MotionEvent) { moveToState(STATE_FAILED) } protected open fun onStateChange(newState: Int, previousState: Int) {} protected open fun onReset() {} protected open fun onCancel() {} fun reset() { view = null orchestrator = null Arrays.fill(trackedPointerIDs, -1) trackedPointersIDsCount = 0 trackedPointersCount = 0 trackedPointers.fill(null) touchEventType = RNGestureHandlerTouchEvent.EVENT_UNDETERMINED onReset() } fun setOnTouchEventListener(listener: OnTouchEventListener?): GestureHandler<*> { onTouchEventListener = listener return this } override fun toString(): String { val viewString = if (view == null) null else view!!.javaClass.simpleName return this.javaClass.simpleName + "@[" + tag + "]:" + viewString } val lastRelativePositionX: Float get() = lastAbsolutePositionX - lastEventOffsetX val lastRelativePositionY: Float get() = lastAbsolutePositionY - lastEventOffsetY companion object { const val STATE_UNDETERMINED = 0 const val STATE_FAILED = 1 const val STATE_BEGAN = 2 const val STATE_CANCELLED = 3 const val STATE_ACTIVE = 4 const val STATE_END = 5 const val HIT_SLOP_NONE = Float.NaN private const val HIT_SLOP_LEFT_IDX = 0 private const val HIT_SLOP_TOP_IDX = 1 private const val HIT_SLOP_RIGHT_IDX = 2 private const val HIT_SLOP_BOTTOM_IDX = 3 private const val HIT_SLOP_WIDTH_IDX = 4 private const val HIT_SLOP_HEIGHT_IDX = 5 const val DIRECTION_RIGHT = 1 const val DIRECTION_LEFT = 2 const val DIRECTION_UP = 4 const val DIRECTION_DOWN = 8 private const val MAX_POINTERS_COUNT = 12 private lateinit var pointerProps: Array<PointerProperties?> private lateinit var pointerCoords: Array<PointerCoords?> private fun initPointerProps(size: Int) { var size = size if (!::pointerProps.isInitialized) { pointerProps = arrayOfNulls(MAX_POINTERS_COUNT) pointerCoords = arrayOfNulls(MAX_POINTERS_COUNT) } while (size > 0 && pointerProps[size - 1] == null) { pointerProps[size - 1] = PointerProperties() pointerCoords[size - 1] = PointerCoords() size-- } } private var nextEventCoalescingKey: Short = 0 private fun hitSlopSet(value: Float): Boolean { return !java.lang.Float.isNaN(value) } fun stateToString(state: Int): String? { when (state) { STATE_UNDETERMINED -> return "UNDETERMINED" STATE_ACTIVE -> return "ACTIVE" STATE_FAILED -> return "FAILED" STATE_BEGAN -> return "BEGIN" STATE_CANCELLED -> return "CANCELLED" STATE_END -> return "END" } return null } } private data class PointerData( val pointerId: Int, var x: Float, var y: Float, var absoluteX: Float, var absoluteY: Float ) }
mit
d789e22090749619eceb18fe4270071e
31.091164
153
0.679166
4.292871
false
false
false
false
apoi/quickbeer-next
app/src/main/java/quickbeer/android/domain/review/network/ReviewJson.kt
2
1903
/** * This file is part of QuickBeer. * Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.domain.review.network import com.squareup.moshi.Json import org.threeten.bp.ZonedDateTime data class ReviewJson( @field:Json(name = "RatingID") val id: Int, @field:Json(name = "Appearance") val appearance: Int?, @field:Json(name = "Aroma") val aroma: Int?, @field:Json(name = "Flavor") val flavor: Int?, @field:Json(name = "Mouthfeel") val mouthfeel: Int?, @field:Json(name = "Overall") val overall: Int?, @field:Json(name = "TotalScore") val totalScore: Float?, @field:Json(name = "Comments") val comments: String?, @field:Json(name = "TimeEntered") val timeEntered: ZonedDateTime?, @field:Json(name = "TimeUpdated") val timeUpdated: ZonedDateTime?, @field:Json(name = "UserID") val userId: Int?, @field:Json(name = "UserName") val userName: String?, @field:Json(name = "City") val city: String?, @field:Json(name = "StateID") val stateId: Int?, @field:Json(name = "State") val state: String?, @field:Json(name = "CountryID") val countryId: Int?, @field:Json(name = "Country") val country: String?, @field:Json(name = "RateCount") val rateCount: Int? )
gpl-3.0
651269b089bb31187deed6a896a69cce
44.309524
71
0.696795
3.583804
false
false
false
false
google/intellij-community
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/editor/quickDoc/QuickDocNavigationTest.kt
2
3244
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.editor.quickDoc import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.testFramework.UsefulTestCase import org.jetbrains.kotlin.idea.KotlinDocumentationProvider import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase import org.jetbrains.kotlin.idea.test.ProjectDescriptorWithStdlibSources import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.test.TestMetadata import org.jetbrains.kotlin.idea.base.test.TestRoot import org.junit.Assert import org.junit.internal.runners.JUnit38ClassRunner import org.junit.runner.RunWith @TestRoot("idea/tests") @TestMetadata("testData/kdoc/navigate") @RunWith(JUnit38ClassRunner::class) class QuickDocNavigationTest() : KotlinLightCodeInsightFixtureTestCase() { override fun getProjectDescriptor() = ProjectDescriptorWithStdlibSources.INSTANCE fun testSimple() { val target = resolveDocLink("C") UsefulTestCase.assertInstanceOf(target, KtClass::class.java) Assert.assertEquals("C", (target as KtClass).name) } fun testJdkClass() { val target = resolveDocLink("ArrayList") UsefulTestCase.assertInstanceOf(target, PsiClass::class.java) Assert.assertEquals("ArrayList", (target as PsiClass).name) } fun testStdlibFunction() { val target = resolveDocLink("reader") UsefulTestCase.assertInstanceOf(target, KtFunction::class.java) Assert.assertEquals("reader", (target as KtFunction).name) val secondaryTarget = KotlinDocumentationProvider().getDocumentationElementForLink( myFixture.psiManager, "InputStream", target ) UsefulTestCase.assertInstanceOf(secondaryTarget, PsiClass::class.java) Assert.assertEquals("InputStream", (secondaryTarget as PsiClass).name) } fun testQualifiedName() { val target = resolveDocLink("a.b.c.D") UsefulTestCase.assertInstanceOf(target, KtClass::class.java) Assert.assertEquals("D", (target as KtClass).name) } fun testTopLevelFun() { val target = resolveDocLink("doc.topLevelFun") UsefulTestCase.assertInstanceOf(target, KtFunction::class.java) Assert.assertEquals("topLevelFun", (target as KtFunction).name) } fun testTopLevelProperty() { val target = resolveDocLink("doc.topLevelProperty") UsefulTestCase.assertInstanceOf(target, KtProperty::class.java) Assert.assertEquals("topLevelProperty", (target as KtProperty).name) } private fun resolveDocLink(linkText: String): PsiElement? { myFixture.configureByFile(getTestName(true) + ".kt") val source = myFixture.elementAtCaret.getParentOfType<KtDeclaration>(false) return KotlinDocumentationProvider().getDocumentationElementForLink( myFixture.psiManager, linkText, source ) } }
apache-2.0
a15ab6962d4a09aeb7cd6060cdf6e624
41.12987
158
0.748767
4.763583
false
true
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/LayoutBuilder.kt
1
3074
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.layout import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.actionSystem.PlatformDataKeys import com.intellij.openapi.fileChooser.FileChooser import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.components.JBRadioButton import org.jetbrains.annotations.ApiStatus import org.jetbrains.annotations.Nls import javax.swing.AbstractButton import javax.swing.ButtonGroup open class LayoutBuilder @PublishedApi internal constructor(@PublishedApi internal val builder: LayoutBuilderImpl) : RowBuilder by builder.rootRow { @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") override fun withButtonGroup(title: String?, buttonGroup: ButtonGroup, body: () -> Unit) { builder.withButtonGroup(buttonGroup, body) } @Suppress("PropertyName") @PublishedApi @get:Deprecated("", replaceWith = ReplaceWith("builder"), level = DeprecationLevel.ERROR) @get:ApiStatus.ScheduledForRemoval internal val `$`: LayoutBuilderImpl get() = builder } @ApiStatus.ScheduledForRemoval @Deprecated("Use Kotlin UI DSL Version 2") class CellBuilderWithButtonGroupProperty<T : Any> @PublishedApi internal constructor(private val prop: PropertyBinding<T>) @Deprecated("Use Kotlin UI DSL Version 2") class RowBuilderWithButtonGroupProperty<T : Any> @PublishedApi internal constructor(private val builder: RowBuilder, private val prop: PropertyBinding<T>) : RowBuilder by builder { @Deprecated("Use Kotlin UI DSL Version 2") fun Row.radioButton(@NlsContexts.RadioButton text: String, value: T, @Nls comment: String? = null): CellBuilder<JBRadioButton> { val component = JBRadioButton(text, prop.get() == value) attachSubRowsEnabled(component) return component(comment = comment).bindValue(value) } @Deprecated("Use Kotlin UI DSL Version 2") fun CellBuilder<JBRadioButton>.bindValue(value: T): CellBuilder<JBRadioButton> = bindValueToProperty(prop, value) } @Deprecated("Use Kotlin UI DSL Version 2") private fun <T> CellBuilder<JBRadioButton>.bindValueToProperty(prop: PropertyBinding<T>, value: T): CellBuilder<JBRadioButton> = apply { onApply { if (component.isSelected) prop.set(value) } onReset { component.isSelected = prop.get() == value } onIsModified { component.isSelected != (prop.get() == value) } } fun FileChooserDescriptor.chooseFile(event: AnActionEvent, fileChosen: (chosenFile: VirtualFile) -> Unit) { FileChooser.chooseFile(this, event.getData(PlatformDataKeys.PROJECT), event.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT), null, fileChosen) } fun Row.attachSubRowsEnabled(component: AbstractButton) { subRowsEnabled = component.selected() component.selected.addListener { subRowsEnabled = it } }
apache-2.0
8d64c859c9ce800856d80540171b0266
43.550725
148
0.783344
4.51395
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantCompanionReferenceInspection.kt
1
9958
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement import org.jetbrains.kotlin.idea.intentions.isReferenceToBuiltInEnumFunction import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.references.resolveToDescriptors import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.load.java.JvmAbi import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.containingClass import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.kotlin.psi.psiUtil.getReceiverExpression import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.FakeCallableDescriptorForObject import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassNotAny import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperInterfaces import org.jetbrains.kotlin.resolve.descriptorUtil.overriddenTreeAsSequence import org.jetbrains.kotlin.resolve.scopes.utils.findFunction import org.jetbrains.kotlin.resolve.scopes.utils.findVariable import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy import org.jetbrains.kotlin.types.typeUtil.isTypeParameter import org.jetbrains.kotlin.types.typeUtil.makeNotNullable import org.jetbrains.kotlin.types.typeUtil.supertypes import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class RedundantCompanionReferenceInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return referenceExpressionVisitor(fun(expression) { if (isRedundantCompanionReference(expression)) { holder.registerProblem( expression, KotlinBundle.message("redundant.companion.reference"), RemoveRedundantCompanionReferenceFix() ) } }) } private fun isRedundantCompanionReference(reference: KtReferenceExpression): Boolean { val parent = reference.parent as? KtDotQualifiedExpression ?: return false val grandParent = parent.parent as? KtElement val selectorExpression = parent.selectorExpression if (reference == selectorExpression && grandParent !is KtDotQualifiedExpression) return false if (parent.getStrictParentOfType<KtImportDirective>() != null) return false val objectDeclaration = reference.mainReference.resolve() as? KtObjectDeclaration ?: return false if (!objectDeclaration.isCompanion()) return false val referenceText = reference.text if (referenceText != objectDeclaration.name) return false if (reference != selectorExpression && referenceText == (selectorExpression as? KtNameReferenceExpression)?.text) return false val containingClass = objectDeclaration.containingClass() ?: return false if (reference.containingClass() != containingClass && reference == parent.receiverExpression) return false if (parent.isReferenceToBuildInEnumFunctionInEnumClass(containingClass)) return false val context = reference.analyze() if (grandParent.isReferenceToClassOrObject(context)) return false val containingClassDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, containingClass] as? ClassDescriptor ?: return false if (containingClassDescriptor.hasSameNameMemberAs(selectorExpression, context)) return false val implicitReceiverClassDescriptor = reference.getResolutionScope(context)?.getImplicitReceiversHierarchy().orEmpty() .flatMap { val type = it.value.type if (type.isTypeParameter()) type.supertypes() else listOf(type) } .mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor } .filterNot { it.isCompanionObject } if (implicitReceiverClassDescriptor.any { it.hasSameNameMemberAs(selectorExpression, context) }) return false (reference as? KtSimpleNameExpression)?.getReceiverExpression()?.getQualifiedElementSelector() ?.mainReference?.resolveToDescriptors(context)?.firstOrNull() ?.let { if (it != containingClassDescriptor) return false } if (selectorExpression is KtCallExpression && referenceText == selectorExpression.calleeExpression?.text) { val newExpression = KtPsiFactory(reference.project).createExpressionByPattern("$0", selectorExpression) val newContext = newExpression.analyzeAsReplacement(parent, context) val descriptor = newExpression.getResolvedCall(newContext)?.resultingDescriptor as? FunctionDescriptor if (descriptor?.isOperator == true) return false } return true } private fun KtDotQualifiedExpression.isReferenceToBuildInEnumFunctionInEnumClass(containingClass: KtClass): Boolean { return containingClass.isEnum() && (isReferenceToBuiltInEnumFunction() || (parent as? KtElement)?.isReferenceToBuiltInEnumFunction() == true) } private fun KtElement?.isReferenceToClassOrObject(context: BindingContext): Boolean { if (this !is KtQualifiedExpression) return false val descriptor = getResolvedCall(context)?.resultingDescriptor return descriptor == null || descriptor is ConstructorDescriptor || descriptor is FakeCallableDescriptorForObject } private fun ClassDescriptor?.hasSameNameMemberAs(expression: KtExpression?, context: BindingContext): Boolean { if (this == null) return false when (val descriptor = expression?.getResolvedCall(context)?.resultingDescriptor) { is PropertyDescriptor -> { val name = descriptor.name if (findMemberVariable(name) != null) return true val type = descriptor.type val javaGetter = findMemberFunction(Name.identifier(JvmAbi.getterName(name.asString()))) ?.takeIf { f -> f is JavaMethodDescriptor || f.overriddenTreeAsSequence(true).any { it is JavaMethodDescriptor } } if (javaGetter?.valueParameters?.isEmpty() == true && javaGetter.returnType?.makeNotNullable() == type) return true val variable = expression.getResolutionScope().findVariable(name, NoLookupLocation.FROM_IDE) if (variable != null && variable.isLocalOrExtension(this)) return true } is FunctionDescriptor -> { val name = descriptor.name if (findMemberFunction(name) != null) return true val function = expression.getResolutionScope().findFunction(name, NoLookupLocation.FROM_IDE) if (function != null && function.isLocalOrExtension(this)) return true } } return false } private fun <D : MemberDescriptor> ClassDescriptor.findMemberByName(name: Name, find: ClassDescriptor.(Name) -> D?): D? { val member = find(name) if (member != null) return member val memberInSuperClass = getSuperClassNotAny()?.findMemberByName(name, find) if (memberInSuperClass != null) return memberInSuperClass getSuperInterfaces().forEach { val memberInInterface = it.findMemberByName(name, find) if (memberInInterface != null) return memberInInterface } return null } private fun ClassDescriptor.findMemberVariable(name: Name): PropertyDescriptor? = findMemberByName(name) { unsubstitutedMemberScope.getContributedVariables(it, NoLookupLocation.FROM_IDE).firstOrNull() } private fun ClassDescriptor.findMemberFunction(name: Name): FunctionDescriptor? = findMemberByName(name) { unsubstitutedMemberScope.getContributedFunctions(it, NoLookupLocation.FROM_IDE).firstOrNull() } private fun CallableDescriptor.isLocalOrExtension(extensionClassDescriptor: ClassDescriptor): Boolean { return visibility == DescriptorVisibilities.LOCAL || extensionReceiverParameter?.type?.constructor?.declarationDescriptor == extensionClassDescriptor } private class RemoveRedundantCompanionReferenceFix : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.companion.reference.fix.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val expression = descriptor.psiElement as? KtReferenceExpression ?: return removeRedundantCompanionReference(expression) } companion object { fun removeRedundantCompanionReference(expression: KtReferenceExpression) { val parent = expression.parent as? KtDotQualifiedExpression ?: return val selector = parent.selectorExpression ?: return val receiver = parent.receiverExpression if (expression == receiver) parent.replace(selector) else parent.replace(receiver) } } } }
apache-2.0
7c40ec15d1c8a14171903882461b72aa
52.827027
134
0.734585
5.664391
false
false
false
false
square/okhttp
buildSrc/src/main/kotlin/artifacts.kt
2
2478
/* * Copyright (C) 2021 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 * * 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. */ import aQute.bnd.gradle.BundleTaskExtension import org.gradle.api.Project import org.gradle.api.artifacts.VersionCatalogsExtension import org.gradle.api.plugins.ExtensionAware import org.gradle.api.tasks.SourceSetContainer import org.gradle.api.tasks.bundling.Jar import org.gradle.kotlin.dsl.dependencies import org.gradle.kotlin.dsl.findByType import org.gradle.kotlin.dsl.get import org.gradle.kotlin.dsl.getByName fun Project.applyOsgi(vararg bndProperties: String) { // Configure OSGi for the JVM platform on kotlin-multiplatform. plugins.withId("org.jetbrains.kotlin.multiplatform") { applyOsgi("jvmJar", "jvmOsgiApi", bndProperties) } // Configure OSGi for kotlin-jvm. plugins.withId("org.jetbrains.kotlin.jvm") { applyOsgi("jar", "osgiApi", bndProperties) } } private fun Project.applyOsgi( jarTaskName: String, osgiApiConfigurationName: String, bndProperties: Array<out String> ) { val osgi = project.sourceSets.create("osgi") val osgiApi = project.configurations.getByName(osgiApiConfigurationName) val kotlinOsgi = extensions.getByType(VersionCatalogsExtension::class.java).named("libs") .findLibrary("kotlin.stdlib.osgi").get().get() project.dependencies { osgiApi(kotlinOsgi) } val jarTask = tasks.getByName<Jar>(jarTaskName) val bundleExtension = jarTask.extensions.findByType() ?: jarTask.extensions.create( BundleTaskExtension.NAME, BundleTaskExtension::class.java, jarTask ) bundleExtension.run { setClasspath(osgi.compileClasspath + sourceSets["main"].compileClasspath) bnd(*bndProperties) } // Call the convention when the task has finished, to modify the jar to contain OSGi metadata. jarTask.doLast { bundleExtension.buildAction().execute(this) } } val Project.sourceSets: SourceSetContainer get() = (this as ExtensionAware).extensions["sourceSets"] as SourceSetContainer
apache-2.0
2f775daa187407656eab7339e3fcc402
34.913043
96
0.763923
3.871875
false
true
false
false
andrewoma/testczar
core/src/main/kotlin/com/github/andrewoma/testczar/TestBase.kt
1
3090
/* * Copyright (c) 2016 Andrew O'Malley * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.andrewoma.testczar import com.github.andrewoma.testczar.internal.ClassCompletionListener import com.github.andrewoma.testczar.internal.InheritableRuleRunner import com.github.andrewoma.testczar.internal.InheritedRule import com.github.andrewoma.testczar.internal.RunCompletionListener import org.junit.AfterClass import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runner.RunWith import org.junit.runners.model.Statement /** * A base class for all tests that runs the defined rules in the order given prior to each test */ @RunWith(InheritableRuleRunner::class) abstract class TestBase { companion object { internal val classListeners = hashMapOf<Class<*>, List<ClassCompletionListener>>() internal val runListeners = hashSetOf<RunCompletionListener>() @Suppress("unused") @AfterClass @JvmStatic fun afterClass() { val clazz = InheritableRuleRunner.lastFinished.get() if (clazz != null && clazz in classListeners) { // Execute the after class listeners in the reserve order of the before for (listener in classListeners[clazz]!!) { listener.onClassComplete(clazz) } } } } open val rules: List<TestRule> = listOf() @InheritedRule fun rules() = Rules(rules.reversed()) inner class Rules(val rules: List<TestRule>) : TestRule { init { val listeners = rules.filterIsInstance(ClassCompletionListener::class.java) if (listeners.isNotEmpty()) classListeners.put([email protected], listeners) for (listener in rules.filterIsInstance(RunCompletionListener::class.java)) { runListeners.add(listener) } } override fun apply(base: Statement, description: Description) = rules.fold(base) { b, r -> r.apply(b, description) } } }
mit
4bffce9ea135a49c87968fe055dfd7fc
39.12987
98
0.708414
4.591382
false
true
false
false
LWJGL-CI/lwjgl3
modules/lwjgl/core/src/templates/kotlin/core/templates/MemoryAccessJNI.kt
2
3395
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package core.templates import org.lwjgl.generator.* val MemoryAccessJNI = "MemoryAccessJNI".nativeClass(Module.CORE) { nativeImport( "<stdlib.h>", "<stdint.h>" ) access = Access.INTERNAL documentation = "Memory access utilities." Code( nativeCall = "${t}return (jint)sizeof(void *);" )..int( "getPointerSize", "Returns the {@code sizeof(void *)}.", void() ) val primitives = arrayOf( Triple(int8_t, "Byte", "a byte value"), Triple(int16_t, "Short", "a short value"), Triple(int32_t, "Int", "an int value"), Triple(int64_t, "Long", "a long value"), Triple(float, "Float", "a float value"), Triple(double, "Double", "a double value"), Triple(uintptr_t, "Address", "a pointer address") ) nativeDirective( """#ifdef LWJGL_WINDOWS static void* __aligned_alloc(size_t alignment, size_t size) { return _aligned_malloc(size, alignment); } #define __aligned_free _aligned_free #else #if defined(__USE_ISOC11) #define __aligned_alloc aligned_alloc #else static void* __aligned_alloc(size_t alignment, size_t size) { void *p; return posix_memalign(&p, alignment, size) ? NULL : p; } #endif #define __aligned_free free #endif // ----------- ${primitives .asSequence() .map { val (type, name) = it "static inline ${type.name} get$name(void *ptr) { return *(${type.name} *)ptr; }" } .joinToString("\n")} // ----------- ${primitives .asSequence() .map { val (type, name) = it "static inline void put$name(void *ptr, ${type.name} value) { *(${type.name} *)ptr = value; }" } .joinToString("\n")} // -----------""") arrayOf( "malloc" to "void * (*) (size_t)", "calloc" to "void * (*) (size_t, size_t)", "realloc" to "void * (*) (void *, size_t)", "free" to "void (*) (void *)" ).forEach { (name, signature) -> macro..Address..signature.handle( name, "Returns the address of the stdlib {@code $name} function.", void() ) } Code( nativeCall = "${t}return (jlong)(uintptr_t)&__aligned_alloc;" )..macro..Address.."void * (*) (size_t, size_t)".handle( "aligned_alloc", "Returns the address of the stdlib {@code aligned_alloc} function.", void() ) Code( nativeCall = "${t}return (jlong)(uintptr_t)&__aligned_free;" )..macro..Address.."void (*) (void *)".handle( "aligned_free", "Returns the address of the stdlib {@code aligned_free} function.", void() ) for ((type, name, msg) in primitives) type( "get$name", "Reads $msg from the specified memory address.", opaque_p("ptr", "the memory address to read") ) for ((type, name, msg) in primitives) void( "put$name", "Writes $msg to the specified memory address.", opaque_p("ptr", "the memory address to write"), type("value", "the value to write") ) }
bsd-3-clause
9d4204ca891a3919629d53540ab3862a
26.609756
110
0.518409
3.849206
false
false
false
false
ursjoss/sipamato
public/public-entity/src/main/kotlin/ch/difty/scipamato/publ/entity/CodeClass.kt
2
367
package ch.difty.scipamato.publ.entity import ch.difty.scipamato.common.entity.CodeClassLike data class CodeClass( val codeClassId: Int? = null, val langCode: String? = null, val name: String? = null, val description: String? = null, ) : PublicDbEntity, CodeClassLike { companion object { private const val serialVersionUID = 1L } }
gpl-3.0
f996ad30a7b8996d981bc2af32b88013
25.214286
53
0.697548
3.783505
false
false
false
false
zdary/intellij-community
plugins/ide-features-trainer/src/training/dsl/LessonContext.kt
2
2375
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.dsl import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.util.concurrency.annotations.RequiresEdt import org.intellij.lang.annotations.Language import org.jetbrains.annotations.Nls @LearningDsl abstract class LessonContext: LearningDslBase { /** * Start a new task in a lesson context */ @RequiresEdt open fun task(taskContent: TaskContext.() -> Unit) = Unit /** * There will not be any freeze in GUI thread. * The continue of the script will be scheduled with the [delayMillis] */ open fun waitBeforeContinue(delayMillis: Int) = Unit /// SHORTCUTS /// fun prepareRuntimeTask(modalityState: ModalityState? = ModalityState.any(), preparation: TaskRuntimeContext.() -> Unit) { task { addFutureStep { invokeLater(modalityState) { preparation() completeStep() } } } } /** Describe a simple task: just one action required */ fun actionTask(action: String, @Nls getText: TaskContext.(action: String) -> String) { task { text(getText(action)) trigger(action) test { actions(action) } } } fun text(@Language("HTML") @Nls text: String) = task { text(text) } /** * Just shortcut to write action name once * @see task */ fun task(action: String, taskContent: TaskContext.(action: String) -> Unit) = task { taskContent(action) } /** Select text in editor */ fun select(startLine: Int, startColumn: Int, endLine: Int, endColumn: Int) = prepareRuntimeTask { select(startLine, startColumn, endLine, endColumn) } open fun caret(offset: Int) = prepareRuntimeTask { caret(offset) } /** NOTE: [line] and [column] starts from 1 not from zero. So these parameters should be same as in editors. */ open fun caret(line: Int, column: Int) = prepareRuntimeTask { caret(line, column) } open fun caret(text: String, select: Boolean = false) = prepareRuntimeTask { caret(text, select) } open fun caret(position: LessonSamplePosition) = prepareRuntimeTask { caret(position) } open fun prepareSample(sample: LessonSample) = prepareRuntimeTask { setSample(sample) } }
apache-2.0
63b1306e6775736d588cd8db090cfaba
28.320988
140
0.689263
4.263914
false
false
false
false
Raizlabs/DBFlow
processor/src/main/kotlin/com/dbflow5/processor/definition/MigrationDefinition.kt
1
2532
package com.dbflow5.processor.definition import com.dbflow5.annotation.Migration import com.dbflow5.processor.ProcessorManager import com.dbflow5.processor.utils.extractTypeNameFromAnnotation import com.dbflow5.processor.utils.isNullOrEmpty import com.grosner.kpoet.typeName import com.squareup.javapoet.ClassName import com.squareup.javapoet.CodeBlock import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import javax.lang.model.element.ExecutableElement import javax.lang.model.element.TypeElement /** * Description: Used in holding data about migration files. */ class MigrationDefinition(migration: Migration, processorManager: ProcessorManager, typeElement: TypeElement) : BaseDefinition(typeElement, processorManager) { val databaseName: TypeName? val version: Int val priority: Int var constructorName: String? = null private set init { setOutputClassName("") databaseName = migration.extractTypeNameFromAnnotation { it.database } version = migration.version priority = migration.priority val elements = typeElement.enclosedElements elements.forEach { element -> if (element is ExecutableElement && element.simpleName.toString() == "<init>") { if (!constructorName.isNullOrEmpty()) { manager.logError(MigrationDefinition::class, "Migrations cannot have more than one constructor. " + "They can only have an Empty() or single-parameter constructor Empty(Empty.class) that specifies " + "the .class of this migration class.") } if (element.parameters.isEmpty()) { constructorName = "()" } else if (element.parameters.size == 1) { val params = element.parameters val param = params[0] val type = param.asType().typeName if (type is ParameterizedTypeName && type.rawType == ClassName.get(Class::class.java)) { val containedType = type.typeArguments[0] constructorName = CodeBlock.of("(\$T.class)", containedType).toString() } else { manager.logError(MigrationDefinition::class, "Wrong parameter type found for $typeElement. Found $type but required ModelClass.class") } } } } } }
mit
00d0abbfcb9ad76ab57a6a4089f0fefa
39.83871
158
0.636651
5.242236
false
false
false
false
bitsydarel/DBWeather
app/src/main/java/com/dbeginc/dbweather/utils/utility/AppNavigator.kt
1
9651
/* * Copyright (C) 2017 Darel Bitsy * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.dbeginc.dbweather.utils.utility import android.content.Intent import android.support.transition.Fade import android.support.transition.Slide import android.support.v4.app.ActivityCompat import android.support.v4.app.FragmentActivity import android.support.v4.view.GravityCompat import android.view.Gravity import com.dbeginc.dbweather.MainActivity import com.dbeginc.dbweather.articledetail.ArticleDetailActivity import com.dbeginc.dbweather.choosedefaultnewspapers.ChooseNewsPapersFragment import com.dbeginc.dbweather.chooselocations.ChooseLocationsFragment import com.dbeginc.dbweather.findlocationwithgps.GpsLocationFinderFragment import com.dbeginc.dbweather.iptvlivedetail.IpTvLiveActivity import com.dbeginc.dbweather.iptvplaylistdetail.IpTvPlaylistDetailFragment import com.dbeginc.dbweather.iptvplaylists.IptvPlaylistsFragment import com.dbeginc.dbweather.launch.IntroFragment import com.dbeginc.dbweather.launch.SplashFragment import com.dbeginc.dbweather.managelocations.ManageLocationsFragment import com.dbeginc.dbweather.managenewspapers.ManageNewsPapersFragment import com.dbeginc.dbweather.newspaper.NewsPapersFragment import com.dbeginc.dbweather.newspaperdetail.NewsPaperDetailActivity import com.dbeginc.dbweather.weather.WeatherFragment import com.dbeginc.dbweather.youtubefavoritelives.FavoriteYoutubeLivesFragment import com.dbeginc.dbweather.youtubelivedetail.YoutubeLiveDetailActivity import com.dbeginc.dbweather.youtubelives.YoutubeLivesFragment import com.dbeginc.dbweatherlives.viewmodels.IpTvLiveModel import com.dbeginc.dbweatherlives.viewmodels.IpTvPlayListModel import com.dbeginc.dbweatherlives.viewmodels.YoutubeLiveModel import com.dbeginc.dbweathernews.viewmodels.ArticleModel import com.dbeginc.dbweathernews.viewmodels.NewsPaperModel /** * Created by darel on 22.03.18. ** * Navigator Pattern for DBWeather * */ fun goToSplashScreen(container: FragmentActivity, layoutId: Int) { val currentScreen = container.supportFragmentManager.findFragmentById(layoutId) currentScreen?.exitTransition = Slide(Gravity.TOP) val splashFragment = SplashFragment() splashFragment.enterTransition = Slide(Gravity.BOTTOM) container.supportFragmentManager .beginTransaction() .replace( layoutId, splashFragment, SplashFragment::class.java.simpleName ).commit() } fun goToChooseLocationScreen(container: FragmentActivity, layoutId: Int) { val currentScreen = container.supportFragmentManager.findFragmentById(layoutId) currentScreen?.exitTransition = Slide(GravityCompat.END) val chooseLocationsFragment = ChooseLocationsFragment() chooseLocationsFragment.enterTransition = Slide(GravityCompat.START) container.supportFragmentManager .beginTransaction() .replace( layoutId, chooseLocationsFragment, ChooseLocationsFragment::class.java.simpleName ).commit() } fun goToGpsLocationFinder(container: FragmentActivity, layoutId: Int) { val currentScreen = container.supportFragmentManager.findFragmentById(layoutId) currentScreen?.exitTransition = Slide(GravityCompat.START) val gpsLocationFinderScreen = GpsLocationFinderFragment() gpsLocationFinderScreen.enterTransition = Slide(GravityCompat.END) container.supportFragmentManager .beginTransaction() .replace( layoutId, gpsLocationFinderScreen, GpsLocationFinderFragment::class.java.simpleName ).commit() } fun goToChooseDefaultNewsPapers(container: FragmentActivity, layoutId: Int) { val currentScreen = container.supportFragmentManager.findFragmentById(layoutId) currentScreen?.exitTransition = Fade(Fade.OUT) val chooseNewsPapersScreen = ChooseNewsPapersFragment() chooseNewsPapersScreen.enterTransition = Fade(Fade.IN) container.supportFragmentManager .beginTransaction() .replace( layoutId, chooseNewsPapersScreen, ChooseNewsPapersFragment::class.java.simpleName ) .commit() } fun goToMainScreen(currentScreen: FragmentActivity) { val goToMainScreen = Intent(currentScreen, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP) ActivityCompat.startActivity(currentScreen, goToMainScreen, null) currentScreen.supportFinishAfterTransition() } fun goToIntroScreen(container: FragmentActivity, layoutId: Int) { val currentFragment = container.supportFragmentManager.findFragmentById(layoutId) val introFragment = IntroFragment() currentFragment?.exitTransition = Fade(Fade.OUT) introFragment.enterTransition = Fade(Fade.IN) val fragmentTransaction = container.supportFragmentManager.beginTransaction() fragmentTransaction.replace( layoutId, introFragment, IntroFragment::class.java.simpleName ) fragmentTransaction.commit() } fun goToWeatherScreen(container: FragmentActivity, layoutId: Int) { container.supportFragmentManager .beginTransaction() .replace(layoutId, WeatherFragment(), WeatherFragment::class.java.simpleName) .commit() } fun goToNewsPapersScreen(container: FragmentActivity, layoutId: Int) { container.supportFragmentManager .beginTransaction() .replace(layoutId, NewsPapersFragment(), NewsPapersFragment::class.java.simpleName) .commit() } fun goToYoutubeLivesScreen(container: FragmentActivity, layoutId: Int) { container.supportFragmentManager .beginTransaction() .replace(layoutId, YoutubeLivesFragment(), YoutubeLivesFragment::class.java.simpleName) .commit() } fun goToIpTvPlaylistsScreen(container: FragmentActivity, emplacementId: Int) { container.supportFragmentManager .beginTransaction() .replace( emplacementId, IptvPlaylistsFragment(), IptvPlaylistsFragment::class.java.simpleName ) .commit() } fun goToIpTvPlaylistScreen(container: FragmentActivity, emplacementId: Int, playlist: IpTvPlayListModel) { container.supportFragmentManager .beginTransaction() .replace( emplacementId, IpTvPlaylistDetailFragment.newInstance(playlistId = playlist.name), IpTvPlaylistDetailFragment::class.java.simpleName ) .commit() } fun goToFavoriteYoutubeLivesScreen(container: FragmentActivity, emplacementId: Int) { container.supportFragmentManager .beginTransaction() .replace( emplacementId, FavoriteYoutubeLivesFragment(), FavoriteYoutubeLivesFragment::class.java.simpleName ) .commit() } fun goToManageLocationsScreen(container: FragmentActivity, emplacementId: Int) { container.supportFragmentManager .beginTransaction() .replace( emplacementId, ManageLocationsFragment(), ManageLocationsFragment::class.java.simpleName ) .commit() } fun goToManageNewsPapersScreen(container: FragmentActivity, emplacementId: Int) { container.supportFragmentManager .beginTransaction() .replace( emplacementId, ManageNewsPapersFragment(), ManageNewsPapersFragment::class.java.simpleName ) .commit() } fun goToIpTvLiveScreen(container: FragmentActivity, iptvLive: IpTvLiveModel) { val ipTvLiveScreen = Intent(container, IpTvLiveActivity::class.java) ipTvLiveScreen.putExtra(IPTV_LIVE_DATA, iptvLive) ActivityCompat.startActivity(container, ipTvLiveScreen, null) } fun goToYoutubeLiveDetailScreen(container: FragmentActivity, youtubeLive: YoutubeLiveModel) { val youtubeDetailScreenIntent = Intent(container, YoutubeLiveDetailActivity::class.java) youtubeDetailScreenIntent.putExtra(YOUTUBE_LIVE_KEY, youtubeLive) ActivityCompat.startActivity(container, youtubeDetailScreenIntent, null) } fun goToArticleDetailScreen(container: FragmentActivity, article: ArticleModel) { val articleDetailScreenIntent = Intent(container, ArticleDetailActivity::class.java) articleDetailScreenIntent.putExtra(ARTICLE_KEY, article) ActivityCompat.startActivity(container, articleDetailScreenIntent, null) } fun goToNewsPaperDetailScreen(container: FragmentActivity, newsPaper: NewsPaperModel) { val newsPaperDetailScreenIntent = Intent(container, NewsPaperDetailActivity::class.java) newsPaperDetailScreenIntent.putExtra(NEWSPAPER_KEY, newsPaper) ActivityCompat.startActivity(container, newsPaperDetailScreenIntent, null) }
gpl-3.0
adb4979f42a2d78f578c7306cf3d2663
35.285714
106
0.729665
4.901473
false
false
false
false
VREMSoftwareDevelopment/WiFiAnalyzer
app/src/main/kotlin/com/vrem/wifianalyzer/wifi/filter/adapter/EnumFilterAdapter.kt
1
1639
/* * WiFiAnalyzer * Copyright (C) 2015 - 2022 VREM Software Development <[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.vrem.wifianalyzer.wifi.filter.adapter import com.vrem.wifianalyzer.R abstract class EnumFilterAdapter<T : Enum<*>>(selections: Set<T>, val defaults: Array<T>) : BasicFilterAdapter<T>(selections) { override fun isActive(): Boolean = selections.size != defaults.size fun toggle(selection: T): Boolean { val size = selections.size if (selections.contains(selection)) { if (size > 1) { selections = selections.minus(selection) } } else { selections = selections.plus(selection) } return size != selections.size } override fun reset() { selections(defaults) } fun color(selection: T): Int = if (selections.contains(selection)) R.color.selected else R.color.regular fun contains(selection: T): Boolean = selections.contains(selection) }
gpl-3.0
eadb1591579ba7d35491e7fbe4a52c39
35.444444
127
0.691885
4.34748
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/bridges/simpleReturnType.kt
5
298
open class A<T : Number>(val t: T) { open fun foo(): T = t } class Z : A<Int>(17) { override fun foo() = 239 } fun box(): String { val z = Z() val a: A<Int> = z return when { z.foo() != 239 -> "Fail #1" a.foo() != 239 -> "Fail #2" else -> "OK" } }
apache-2.0
6fb55004437d6e6a07f0848a9b4afc7b
16.529412
36
0.432886
2.733945
false
false
false
false
smmribeiro/intellij-community
plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/impl/MnemonicsUsageFactors.kt
12
1821
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.completion.ml.personalization.impl import com.intellij.completion.ml.personalization.* /** * @author Vitaliy.Bibaev */ class MnemonicsUsageReader(factor: DailyAggregatedDoubleFactor) : UserFactorReaderBase(factor) { fun mnemonicsUsageRatio(): Double? { val sums = factor.aggregateSum() val total = sums["total"] val used = sums["withMnemonics"] if (total == null || used == null || total < 1.0) return null return used / total } } class MnemonicsUsageUpdater(factor: MutableDoubleFactor) : UserFactorUpdaterBase(factor) { fun fireCompletionFinished(isMnemonicsUsed: Boolean) { factor.updateOnDate(DateUtil.today()) { compute("total", { _, before -> if (before == null) 1.0 else before + 1 }) val valueBefore = computeIfAbsent("withMnemonics", { 0.0 }) if (isMnemonicsUsed) { set("withMnemonics", valueBefore + 1.0) } } } } class MnemonicsRatio : UserFactorBase<MnemonicsUsageReader>("mnemonicsUsageRatio", UserFactorDescriptions.MNEMONICS_USAGE) { override fun compute(reader: MnemonicsUsageReader): String? = reader.mnemonicsUsageRatio()?.toString() }
apache-2.0
3e1f82736706ed4790e1ccbe3d13486a
36.958333
124
0.695222
4.129252
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/wizard/AbstractNewProjectWizardMultiStepWithAddButton.kt
1
2872
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.wizard import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.PlatformCoreDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.openapi.actionSystem.impl.IdeaActionButtonLook import com.intellij.openapi.application.ModalityState import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.InstallPluginTask import com.intellij.ui.UIBundle import com.intellij.ui.awt.RelativePoint import com.intellij.ui.dsl.builder.Row import com.intellij.ui.dsl.builder.components.SegmentedButtonBorder import java.util.function.Supplier import javax.swing.JComponent abstract class AbstractNewProjectWizardMultiStepWithAddButton<S : NewProjectWizardStep, F: NewProjectWizardMultiStepFactory<S>>( parent: NewProjectWizardStep, epName: ExtensionPointName<F> ) : AbstractNewProjectWizardMultiStep<S, F>(parent, epName) { abstract var additionalStepPlugins: Map<String, String> override fun setupSwitcherUi(builder: Row) { super.setupSwitcherUi(builder) with(builder) { if (additionalStepPlugins.isNotEmpty()) { val plus = AdditionalStepsAction() cell(ActionButton(plus, plus.templatePresentation, ActionPlaces.getPopupPlace("NEW_PROJECT_WIZARD"), ActionToolbar.DEFAULT_MINIMUM_BUTTON_SIZE).apply { setLook(IdeaActionButtonLook()) border = SegmentedButtonBorder() }) } } } private inner class AdditionalStepsAction : AnAction(null, null, AllIcons.General.Add) { override fun actionPerformed(e: AnActionEvent) { val additionalSteps = (additionalStepPlugins.keys - steps.keys).map { OpenMarketPlaceAction(it) } JBPopupFactory.getInstance().createActionGroupPopup( UIBundle.message("new.project.wizard.popup.title.install.plugin"), DefaultActionGroup(additionalSteps), e.dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false ).show(RelativePoint.getSouthOf(e.getData(CONTEXT_COMPONENT) as JComponent)) } } private inner class OpenMarketPlaceAction(private val language: String) : AnAction(Supplier { language }) { override fun actionPerformed(e: AnActionEvent) { val pluginId = PluginId.getId(additionalStepPlugins[language]!!) val component = e.dataContext.getData(CONTEXT_COMPONENT)!! ProgressManager.getInstance().run(InstallPluginTask(setOf(pluginId), ModalityState.stateForComponent(component))) } } }
apache-2.0
a9d7a7f62ee357edd0a1b7b84282b83b
46.098361
128
0.779596
4.632258
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/CreateKotlinSubClassIntention.kt
2
10293
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.intentions import com.intellij.codeInsight.CodeInsightUtil import com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.JavaDirectoryService import com.intellij.psi.PsiFile import com.intellij.refactoring.rename.PsiElementRenameHandler import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.ShortenReferences import org.jetbrains.kotlin.idea.core.overrideImplement.ImplementMembersHandler import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.refactoring.getOrCreateKotlinFile import org.jetbrains.kotlin.idea.refactoring.ui.CreateKotlinClassDialog import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiFactory.ClassHeaderBuilder import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.resolve.ModifiersChecker private const val IMPL_SUFFIX = "Impl" class CreateKotlinSubClassIntention : SelfTargetingRangeIntention<KtClass>( KtClass::class.java, KotlinBundle.lazyMessage("create.kotlin.subclass") ) { override fun applicabilityRange(element: KtClass): TextRange? { if (element.name == null || element.getParentOfType<KtFunction>(true) != null) { // Local / anonymous classes are not supported return null } if (!element.isInterface() && !element.isSealed() && !element.isAbstract() && !element.hasModifier(KtTokens.OPEN_KEYWORD)) { return null } val primaryConstructor = element.primaryConstructor if (!element.isInterface() && primaryConstructor != null) { val constructors = element.secondaryConstructors + primaryConstructor if (constructors.none { !it.isPrivate() && it.valueParameters.all { parameter -> parameter.hasDefaultValue() } }) { // At this moment we require non-private default constructor // TODO: handle non-private constructors with parameters return null } } setTextGetter(getImplementTitle(element)) return TextRange(element.startOffset, element.body?.lBrace?.startOffset ?: element.endOffset) } private fun getImplementTitle(baseClass: KtClass) = when { baseClass.isInterface() -> KotlinBundle.lazyMessage("implement.interface") baseClass.isAbstract() -> KotlinBundle.lazyMessage("implement.abstract.class") baseClass.isSealed() -> KotlinBundle.lazyMessage("implement.sealed.class") else /* open class */ -> KotlinBundle.lazyMessage("create.subclass") } override fun startInWriteAction() = false override fun checkFile(file: PsiFile): Boolean { return true } override fun preparePsiElementForWriteIfNeeded(target: KtClass): Boolean { return true } override fun applyTo(element: KtClass, editor: Editor?) { if (editor == null) throw IllegalArgumentException("This intention requires an editor") val name = element.name ?: throw IllegalStateException("This intention should not be applied to anonymous classes") if (element.isSealed() && !element.languageVersionSettings.supportsFeature(LanguageFeature.SealedInterfaces)) { createNestedSubclass(element, name, editor) } else { createExternalSubclass(element, name, editor) } } private fun defaultTargetName(baseName: String) = "$baseName$IMPL_SUFFIX" private fun KtClassOrObject.hasSameDeclaration(name: String) = declarations.any { it is KtNamedDeclaration && it.name == name } private fun targetNameWithoutConflicts(baseName: String, container: KtClassOrObject?) = KotlinNameSuggester.suggestNameByName(defaultTargetName(baseName)) { container?.hasSameDeclaration(it) != true } private fun createNestedSubclass(sealedClass: KtClass, sealedName: String, editor: Editor) { if (!super.preparePsiElementForWriteIfNeeded(sealedClass)) return val project = sealedClass.project val klass = runWriteAction { val builder = buildClassHeader(targetNameWithoutConflicts(sealedName, sealedClass), sealedClass, sealedName) val classFromText = KtPsiFactory(project).createClass(builder.asString()) val body = sealedClass.getOrCreateBody() body.addBefore(classFromText, body.rBrace) as KtClass } runInteractiveRename(klass, project, sealedClass, editor) chooseAndImplementMethods(project, klass, editor) } private fun createExternalSubclass(baseClass: KtClass, baseName: String, editor: Editor) { var container: KtClassOrObject = baseClass var name = baseName var visibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, DescriptorVisibilities.PUBLIC) while (!container.isPrivate() && !container.isProtected() && !(container is KtClass && container.isInner())) { val parent = container.containingClassOrObject if (parent != null) { val parentName = parent.name if (parentName != null) { container = parent name = "$parentName.$name" val parentVisibility = ModifiersChecker.resolveVisibilityFromModifiers(parent, visibility) if ((DescriptorVisibilities.compare(parentVisibility, visibility) ?: 0) < 0) { visibility = parentVisibility } } } if (container != parent) { break } } val project = baseClass.project val factory = KtPsiFactory(project) if (container.containingClassOrObject == null && !isUnitTestMode()) { val dlg = chooseSubclassToCreate(baseClass, baseName) ?: return val targetName = dlg.className val (file, klass) = runWriteAction { val file = getOrCreateKotlinFile("$targetName.kt", dlg.targetDirectory!!)!! val builder = buildClassHeader(targetName, baseClass, baseClass.fqName!!.asString()) file.add(factory.createClass(builder.asString())) val klass = file.getChildOfType<KtClass>()!! ShortenReferences.DEFAULT.process(klass) file to klass } chooseAndImplementMethods(project, klass, CodeInsightUtil.positionCursor(project, file, klass) ?: editor) } else { if (!super.preparePsiElementForWriteIfNeeded(baseClass)) return val klass = runWriteAction { val builder = buildClassHeader( targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), baseClass, name, visibility ) val classFromText = factory.createClass(builder.asString()) container.parent.addAfter(classFromText, container) as KtClass } runInteractiveRename(klass, project, container, editor) chooseAndImplementMethods(project, klass, editor) } } private fun runInteractiveRename(klass: KtClass, project: Project, container: KtClassOrObject, editor: Editor) { if (isUnitTestMode()) return PsiElementRenameHandler.rename(klass, project, container, editor) } private fun chooseSubclassToCreate(baseClass: KtClass, baseName: String): CreateKotlinClassDialog? { val sourceDir = baseClass.containingFile.containingDirectory val aPackage = JavaDirectoryService.getInstance().getPackage(sourceDir) val dialog = object : CreateKotlinClassDialog( baseClass.project, text, targetNameWithoutConflicts(baseName, baseClass.containingClassOrObject), aPackage?.qualifiedName ?: "", CreateClassKind.CLASS, true, ModuleUtilCore.findModuleForPsiElement(baseClass), baseClass.isSealed() ) { override fun getBaseDir(packageName: String?) = sourceDir override fun reportBaseInTestSelectionInSource() = true } return if (!dialog.showAndGet() || dialog.targetDirectory == null) null else dialog } private fun buildClassHeader( targetName: String, baseClass: KtClass, baseName: String, defaultVisibility: DescriptorVisibility = ModifiersChecker.resolveVisibilityFromModifiers(baseClass, DescriptorVisibilities.PUBLIC) ): ClassHeaderBuilder { return ClassHeaderBuilder().apply { if (!baseClass.isInterface()) { if (defaultVisibility != DescriptorVisibilities.PUBLIC) { modifier(defaultVisibility.name) } if (baseClass.isInner()) { modifier(KtTokens.INNER_KEYWORD.value) } } name(targetName) val typeParameters = baseClass.typeParameterList?.parameters typeParameters(typeParameters?.map { it.text }.orEmpty()) baseClass(baseName, typeParameters?.map { it.name ?: "" }.orEmpty(), baseClass.isInterface()) typeConstraints(baseClass.typeConstraintList?.constraints?.map { it.text }.orEmpty()) } } private fun chooseAndImplementMethods(project: Project, targetClass: KtClass, editor: Editor) { editor.caretModel.moveToOffset(targetClass.textRange.startOffset) ImplementMembersHandler().invoke(project, editor, targetClass.containingFile) } }
apache-2.0
8e51be0ec509c755c53cdaa7492015fa
47.551887
139
0.683766
5.391828
false
false
false
false
Fotoapparat/Fotoapparat
fotoapparat/src/main/java/io/fotoapparat/capability/provide/CapabilitiesProvider.kt
1
1535
@file:Suppress("DEPRECATION") package io.fotoapparat.capability.provide import android.hardware.Camera import io.fotoapparat.capability.Capabilities import io.fotoapparat.parameter.SupportedParameters import io.fotoapparat.parameter.camera.convert.* /** * Returns the [io.fotoapparat.capability.Capabilities] of the given [Camera]. */ internal fun Camera.getCapabilities() = SupportedParameters(parameters).getCapabilities() private fun SupportedParameters.getCapabilities(): Capabilities { return Capabilities( zoom = supportedZoom, flashModes = flashModes.extract { it.toFlash() }, focusModes = focusModes.extract { it.toFocusMode() }, maxFocusAreas = maxNumFocusAreas, canSmoothZoom = supportedSmoothZoom, maxMeteringAreas = maxNumMeteringAreas, jpegQualityRange = jpegQualityRange, exposureCompensationRange = exposureCompensationRange, antiBandingModes = supportedAutoBandingModes.extract(String::toAntiBandingMode), sensorSensitivities = sensorSensitivities.toSet(), previewFpsRanges = supportedPreviewFpsRanges.extract { it.toFpsRange() }, pictureResolutions = pictureResolutions.mapSizes(), previewResolutions = previewResolutions.mapSizes() ) } private fun <Parameter : Any, Code> List<Code>.extract(converter: (Code) -> Parameter?) = mapNotNull { converter(it) }.toSet() private fun Collection<Camera.Size>.mapSizes() = map { it.toResolution() }.toSet()
apache-2.0
dc45b79c2bab74b7ead6f0a0f5095016
42.885714
126
0.722476
4.827044
false
false
false
false
smmribeiro/intellij-community
platform/vcs-log/impl/test/com/intellij/vcs/log/history/TrivialMergesTest.kt
19
3023
// 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.vcs.log.history import com.intellij.vcs.log.graph.TestGraphBuilder import com.intellij.vcs.log.graph.api.LinearGraph import com.intellij.vcs.log.graph.collapsing.DottedFilterEdgesGenerator import com.intellij.vcs.log.graph.graph import com.intellij.vcs.log.graph.impl.assert import org.junit.Test class TrivialMergesTest { fun LinearGraph.assert(vararg toHide: Int, result: TestGraphBuilder.() -> Unit) { assert({ collapsedGraph -> DottedFilterEdgesGenerator.update(collapsedGraph, 0, nodesCount() - 1) hideTrivialMerges(collapsedGraph) { toHide.contains(it) } }, result) } /* 0. |\ | 1 2.| |/ 3. */ @Test fun simpleTrivialDiamond() = graph { 0(1, 2) 1.UNM(3) 2(3) 3() }.assert(0) { 2(3) 3() } /* 0. |\ | 1. 2.| |/ 3. */ @Test fun simpleNonTrivialDiamond() = graph { 0(1, 2) 1(3) 2(3) 3() }.assert(0) { 0(1, 2) 1(3) 2(3) 3() } /* 0. /| 1.| | 2 3 | | 4. |/| 5.| | 6 7 | | 8. |/| 9.| |/ 10 */ @Test fun multipleTrivialMerges() = graph { 0(1, 2) 1(3) 2.UNM(4) 3.UNM(5) 4(5, 6) 5(7) 6.UNM(8) 7.UNM(9) 8(9, 10) 9(10) 10.UNM() }.assert(0, 4, 8) { 1(5.dot) 5(9.dot) 9() } /* 0. /| 1.| | 2. 3 | | 4. |/| 5.| | 6 7 | | 8. |/| 9.| |/ 10 */ @Test fun multipleMergesOneNonTrivial() = graph { 0(1, 2) 1(3) 2(4) 3.UNM(5) 4(5, 6) 5(7) 6.UNM(8) 7.UNM(9) 8(9, 10) 9(10) 10.UNM() }.assert(0, 4, 8) { 0(1, 2) 1(5.dot) 2(5.dot) 5(9.dot) 9() } /* 0. | 1. |\\ 2 |\ | 3.\ 4.|\ \ |/ / | 5./ | |/ / 6. / | 7. |/| 8.| |/ 9. */ @Test fun octopusMerge() = graph { 0(1) 1(2, 3, 7) 2.UNM(4) 3(5, 6) 4(5) 5(6) 6(8) 7(8, 9) 8(9) 9() }.assert(1, 3, 7) { 0(4.dot) 4(5) 5(6) 6(8) 8(9) 9() } /* 0. | 1. |\\ 2 |\ | 3.\ 4.|\ \ |/ / | 5./ | |/ / 6. / | 7. |/| 8.| |/ 9. */ @Test fun nonTrivialOctopusMerge() = graph { 0(1) 1(2, 3, 7) 2.UNM(4) 3(5, 6) 4(5) 5(6) 6(8) 7(8, 9) 8(9) 9() }.assert(1, 7) { 0(1) 1(4.dot, 3.u, 8.dot) 3(5, 6) 4(5) 5(6) 6(8) 8(9) 9() } @Test fun tripleMerge() = graph { 0(1, 3) 1.UNM(2) 2(7) 3.UNM(4, 5) 4.UNM(10) 5.UNM(6) 6(8) 7.UNM(9) 8.UNM(9) 9(11) 10(12) 11.UNM(13) 12.UNM(13) 13(14) 14() }.assert(0, 10) { 0(2.dot, 6.dot, 13.dot) 2(9.dot) 6(9.dot) 9(13.dot) 13(14) 14() } }
apache-2.0
4316718b17a0decf4a3e3146699de4cf
11.495868
140
0.415481
2.467755
false
false
false
false
smmribeiro/intellij-community
plugins/git4idea/tests/git4idea/push/GitPushOperationSingleRepoTest.kt
9
18723
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.push import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.options.advanced.AdvancedSettingsImpl import com.intellij.openapi.ui.TestDialog import com.intellij.openapi.ui.TestDialogManager import com.intellij.openapi.util.Pair import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.Executor.* import com.intellij.openapi.vcs.update.FileGroup import com.intellij.openapi.vcs.update.UpdatedFiles import com.intellij.testFramework.UsefulTestCase import com.intellij.util.containers.ContainerUtil import git4idea.branch.GitBranchUtil import git4idea.config.GitVersionSpecialty import git4idea.config.UpdateMethod import git4idea.push.GitPushRepoResult.Type.* import git4idea.push.GitRejectedPushUpdateDialog.Companion.PushRejectedExitCode import git4idea.repo.GitRepository import git4idea.test.* import git4idea.update.GitUpdateResult import org.junit.After import org.junit.Assume.assumeTrue import org.junit.Before import java.io.File import java.nio.file.Path import java.util.Collections.singletonMap class GitPushOperationSingleRepoTest : GitPushOperationBaseTest() { private lateinit var repository: GitRepository private lateinit var parentRepo: Path private lateinit var broRepo: Path @Throws(Exception::class) override fun setUp() { super.setUp() val trinity = setupRepositories(projectPath, "parent", "bro") parentRepo = trinity.parent broRepo = trinity.bro repository = trinity.projectRepo cd(projectPath) refresh() updateRepositories() } @Before fun beforeEach() { TestDialogManager.setTestDialog(TestDialog.DEFAULT) } @After fun afterEach() { TestDialogManager.setTestDialog(TestDialog.DEFAULT) } fun `test successful push`() { val hash = makeCommit("file.txt") val result = push("master", "origin/master") assertResult(SUCCESS, 1, "master", "origin/master", result) assertPushed(hash, "master") } fun `test push new branch`() { git("checkout -b feature") val result = push("feature", "origin/feature") assertResult(NEW_BRANCH, -1, "feature", "origin/feature", result) assertBranchExists("feature") } fun `test push new branch with commits`() { touch("feature.txt", "content") addCommit("feature commit") val hash = last() git("checkout -b feature") val result = push("feature", "origin/feature") assertResult(NEW_BRANCH, -1, "feature", "origin/feature", result) assertBranchExists("feature") assertPushed(hash, "feature") } fun `test upstream is set for new branch`() { git("checkout -b feature") push("feature", "origin/feature") assertUpstream("feature", "origin", "feature") } fun `test upstream is not modified if already set`() { push("master", "origin/feature") assertUpstream("master", "origin", "master") } fun `test rejected push to tracked branch proposes to update`() { pushCommitFromBro() var dialogShown = false TestDialogManager.setTestDialog { dialogShown = true PushRejectedExitCode.CANCEL.exitCode } val result = push("master", "origin/master") assertTrue("Rejected push dialog wasn't shown", dialogShown) assertResult(REJECTED_NO_FF, -1, "master", "origin/master", result) } fun `test rejected push to other branch doesnt propose to update`() { pushCommitFromBro() cd(repository) git("checkout -b feature") var dialogShown = false TestDialogManager.setTestDialog { dialogShown = true PushRejectedExitCode.CANCEL.exitCode } val result = push("feature", "origin/master") assertFalse("Rejected push dialog shouldn't be shown", dialogShown) assertResult(REJECTED_NO_FF, -1, "feature", "origin/master", result) } fun `test push is rejected too many times`() { pushCommitFromBro() cd(repository) val hash = makeCommit("afile.txt") TestDialogManager.setTestDialog { PushRejectedExitCode.MERGE.exitCode } updateRepositories() val pushSpec = makePushSpec(repository, "master", "origin/master") val result = object : GitPushOperation(project, pushSupport, singletonMap(repository, pushSpec), null, false, false) { override fun update(rootsToUpdate: Collection<GitRepository>, updateMethod: UpdateMethod, checkForRebaseOverMergeProblem: Boolean): GitUpdateResult { val updateResult = super.update(rootsToUpdate, updateMethod, checkForRebaseOverMergeProblem) pushCommitFromBro() return updateResult } }.execute() assertResult(REJECTED_NO_FF, -1, "master", "origin/master", GitUpdateResult.SUCCESS, listOf("bro.txt"), result) cd(parentRepo) val history = git("log --all --pretty=%H ") assertFalse("The commit shouldn't be pushed", history.contains(hash)) } fun `test use selected update method for all consecutive updates`() { pushCommitFromBro() cd(repository) makeCommit("afile.txt") TestDialogManager.setTestDialog { PushRejectedExitCode.REBASE.exitCode } updateRepositories() val pushSpec = makePushSpec(repository, "master", "origin/master") val result = object : GitPushOperation(project, pushSupport, singletonMap(repository, pushSpec), null, false, false) { var updateHappened: Boolean = false override fun update(rootsToUpdate: Collection<GitRepository>, updateMethod: UpdateMethod, checkForRebaseOverMergeProblem: Boolean): GitUpdateResult { val updateResult = super.update(rootsToUpdate, updateMethod, checkForRebaseOverMergeProblem) if (!updateHappened) { updateHappened = true pushCommitFromBro() } return updateResult } }.execute() assertResult(SUCCESS, 1, "master", "origin/master", GitUpdateResult.SUCCESS, result.results[repository]!!) cd(repository) val commitMessages = StringUtil.splitByLines(log("--pretty=%s")) val mergeCommitsInTheLog = commitMessages.any { it.toLowerCase().contains("merge") } assertFalse("Unexpected merge commits when rebase method is selected", mergeCommitsInTheLog) } fun `test force push without lease`() { (AdvancedSettings.getInstance() as AdvancedSettingsImpl).setSetting("git.use.push.force.with.lease", false, testRootDisposable) val broHash = pushCommitFromBro() cd(repository) val myHash = makeCommit("anyfile.txt") val result = push("master", "origin/master", true) assertResult(FORCED, -1, "master", "origin/master", result) cd(parentRepo) val parentHistory = StringUtil.splitByLines(git("log master --pretty=%H")) assertFalse(parentHistory.contains(broHash)) assertEquals(myHash, parentHistory[0]) } fun `test force push with lease succeeds if remote is on expected position`() { assumeForceWithLeaseSupported() val broHash = pushCommitFromBro() cd(repository) val myHash = makeCommit("anyfile.txt") git("fetch") val result = push("master", "origin/master", true) assertResult(FORCED, -1, "master", "origin/master", result) cd(parentRepo) val parentHistory = StringUtil.splitByLines(git("log master --pretty=%H")) assertFalse(parentHistory.contains(broHash)) assertEquals(myHash, parentHistory[0]) } fun `test force push with lease is rejected if remote has changed`() { assumeForceWithLeaseSupported() val broHash = pushCommitFromBro() cd(repository) val myHash = makeCommit("anyfile.txt") val result = push("master", "origin/master", true) assertResult(REJECTED_STALE_INFO, -1, "master", "origin/master", result) cd(parentRepo) val parentHistory = StringUtil.splitByLines(git("log master --pretty=%H")) assertFalse(parentHistory.contains(myHash)) assertEquals(broHash, parentHistory[0]) } fun `test force push with lease succeeds for new branch`() { assumeForceWithLeaseSupported() val broHash = pushCommitFromBro() cd(repository) val myHash = makeCommit("anyfile.txt") val result = push("master", "origin/feature", true) assertResult(NEW_BRANCH, -1, "master", "origin/feature", result) cd(parentRepo) val parentHistory = StringUtil.splitByLines(git("log master --pretty=%H")) assertEquals(broHash, parentHistory[0]) val branchHistory = StringUtil.splitByLines(git("log feature --pretty=%H")) assertEquals(myHash, branchHistory[0]) } fun `test force push with lease is rejected for existing branch`() { assumeForceWithLeaseSupported() val broHash = pushCommitFromBro() cd(broRepo) git("push origin master:feature") cd(repository) makeCommit("anyfile.txt") val result = push("master", "origin/feature", true) assertResult(REJECTED_STALE_INFO, -1, "master", "origin/feature", result) cd(parentRepo) val parentHistory = StringUtil.splitByLines(git("log master --pretty=%H")) assertEquals(broHash, parentHistory[0]) val branchHistory = StringUtil.splitByLines(git("log feature --pretty=%H")) assertEquals(broHash, branchHistory[0]) } fun `test dont propose to update if force push is rejected`() { var dialogShown = false TestDialogManager.setTestDialog { dialogShown = true PushRejectedExitCode.CANCEL.exitCode } val remoteTipAndPushResult = forcePushWithReject(true) assertResult(REJECTED_NO_FF, -1, "master", "origin/master", remoteTipAndPushResult.second) assertFalse("Rejected push dialog should not be shown", dialogShown) cd(parentRepo) assertEquals("The commit pushed from bro should be the last one", remoteTipAndPushResult.first, last()) } fun `test dont silently update if force push is rejected`() { settings.updateMethod = UpdateMethod.REBASE settings.setAutoUpdateIfPushRejected(true) val remoteTipAndPushResult = forcePushWithReject(true) assertResult(REJECTED_NO_FF, -1, "master", "origin/master", remoteTipAndPushResult.second) cd(parentRepo) assertEquals("The commit pushed from bro should be the last one", remoteTipAndPushResult.first, last()) } fun `test dont silently update if force with lease push is rejected`() { assumeForceWithLeaseSupported() settings.updateMethod = UpdateMethod.REBASE settings.setAutoUpdateIfPushRejected(true) val remoteTipAndPushResult = forcePushWithReject(false) assertResult(REJECTED_STALE_INFO, -1, "master", "origin/master", remoteTipAndPushResult.second) cd(parentRepo) assertEquals("The commit pushed from bro should be the last one", remoteTipAndPushResult.first, last()) } private fun forcePushWithReject(fetchFirst: Boolean): Pair<String, GitPushResult> { val pushedHash = pushCommitFromBro() cd(parentRepo) git("config receive.denyNonFastForwards true") cd(repository) makeCommit("anyfile.txt") if (fetchFirst) git("fetch") val map = singletonMap(repository, makePushSpec(repository, "master", "origin/master")) val result = GitPushOperation(project, pushSupport, map, null, true, false).execute() return Pair.create(pushedHash, result) } fun `test merge after rejected push`() { val broHash = pushCommitFromBro() cd(repository) val hash = makeCommit("file.txt") TestDialogManager.setTestDialog { PushRejectedExitCode.MERGE.exitCode } val result = push("master", "origin/master") cd(repository) val log = git("log -3 --pretty=%H#%s") val commits = StringUtil.splitByLines(log) val lastCommitMsg = commits[0].split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1] assertTrue("The last commit doesn't look like a merge commit: $lastCommitMsg", lastCommitMsg.contains("Merge")) assertEquals(hash, commits[1].split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]) assertEquals(broHash, commits[2].split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]) assertResult(SUCCESS, 2, "master", "origin/master", GitUpdateResult.SUCCESS, listOf("bro.txt"), result) } // IDEA-144179 fun `test don't update if rejected by some custom reason`() { cd(repository) val hash = makeCommit("file.txt") val rejectHook = """ cat <<'EOF' remote: Push rejected. remote: refs/heads/master: 53d02a63c9cd5c919091b5d9f21381b98a8341be: commit message doesn't match regex: [A-Z][A-Z_0-9]+-[A-Za-z0-9].* remote: EOF exit 1 """.trimIndent() installHook(parentRepo, "pre-receive", rejectHook) TestDialogManager.setTestDialog { throw AssertionError("Update shouldn't be proposed") } val result = push("master", "origin/master") assertResult(REJECTED_OTHER, -1, "master", "origin/master", result) assertNotPushed(hash) } private fun assertNotPushed(hash: String) { assertEquals("", git("branch -r --contains $hash")) } fun `test update with conflicts cancels push`() { cd(broRepo) append("bro.txt", "bro content") makeCommit("msg") git("push origin master:master") cd(repository) append("bro.txt", "main content") makeCommit("msg") TestDialogManager.setTestDialog { PushRejectedExitCode.REBASE.exitCode } vcsHelper.onMerge {} val result = push("master", "origin/master") assertResult(REJECTED_NO_FF, -1, "master", "origin/master", GitUpdateResult.INCOMPLETE, listOf("bro.txt"), result) } fun `test push tags`() { cd(repository) git("tag v1") updateRepositories() val spec = makePushSpec(repository, "master", "origin/master") val pushResult = GitPushOperation(project, pushSupport, singletonMap(repository, spec), GitPushTagMode.ALL, false, false).execute() val result = pushResult.results[repository]!! val pushedTags = result.pushedTags assertEquals(1, pushedTags.size) assertEquals("refs/tags/v1", pushedTags[0]) } fun `test skip pre push hook`() { assumeTrue("Not testing: pre-push hooks are not supported in ${vcs.version}", GitVersionSpecialty.PRE_PUSH_HOOK.existsIn(vcs.version)) cd(repository) val hash = makeCommit("file.txt") val rejectHook = """ exit 1 """.trimIndent() installHook(repository.root.toNioPath().resolve(".git"), "pre-push", rejectHook) val result = push("master", "origin/master", false, true) assertResult(SUCCESS, 1, "master", "origin/master", result) assertPushed(hash, "master") } fun `test respect branch default setting for silent update when rejected push`() { generateUpdateNeeded() settings.updateMethod = UpdateMethod.BRANCH_DEFAULT git("config branch.master.rebase true") settings.setAutoUpdateIfPushRejected(true) push("master", "origin/master") assertFalse("Unexpected merge commit: rebase should have happened", log("-1 --pretty=%s").toLowerCase().startsWith("merge")) } // there is no "branch default" choice in the rejected push dialog // => simply don't rewrite the setting if the same value is chosen, as was default value initially fun `test dont overwrite branch default setting when agree in rejected push dialog`() { generateUpdateNeeded() settings.updateMethod = UpdateMethod.BRANCH_DEFAULT git("config branch.master.rebase true") TestDialogManager.setTestDialog { PushRejectedExitCode.CANCEL.exitCode } push("master", "origin/master") assertEquals(UpdateMethod.BRANCH_DEFAULT, settings.updateMethod) } private fun generateUpdateNeeded() { pushCommitFromBro() cd(repository) makeCommit("file.txt") } private fun push(from: String, to: String, force: Boolean = false, skipHook: Boolean = false): GitPushResult { updateRepositories() refresh() updateChangeListManager() val spec = makePushSpec(repository, from, to) return GitPushOperation(project, pushSupport, singletonMap(repository, spec), null, force, skipHook).execute() } private fun pushCommitFromBro(): String { cd(broRepo) val hash = makeCommit("bro.txt") git("push") return hash } private fun assertResult(type: GitPushRepoResult.Type, pushedCommits: Int, from: String, to: String, actualResult: GitPushResult) { assertResult(type, pushedCommits, from, to, null, null, actualResult) } private fun assertResult(type: GitPushRepoResult.Type, pushedCommits: Int, from: String, to: String, updateResult: GitUpdateResult?, updatedFiles: List<String>?, actualResult: GitPushResult) { assertResult(type, pushedCommits, from, to, updateResult, actualResult.results[repository]!!) UsefulTestCase.assertSameElements("Updated files set is incorrect", getUpdatedFiles(actualResult.updatedFiles), ContainerUtil.notNullize(updatedFiles)) } private fun getUpdatedFiles(updatedFiles: UpdatedFiles): Collection<String> { val result = mutableListOf<String>() for (group in updatedFiles.topLevelGroups) { result.addAll(getUpdatedFiles(group)) } return result } private fun getUpdatedFiles(group: FileGroup): Collection<String> { val result = mutableListOf<String>() result.addAll(group.files.map { FileUtil.getRelativePath(File(projectPath), File(it))!! }) for (child in group.children) { result.addAll(getUpdatedFiles(child)) } return result } private fun assertPushed(expectedHash: String, branch: String) { cd(parentRepo) val actualHash = git("log -1 --pretty=%H $branch") assertEquals(expectedHash, actualHash) } private fun assertBranchExists(branch: String) { cd(parentRepo) val out = git("branch") assertTrue(out.contains(branch)) } private fun assertUpstream(localBranch: String, expectedUpstreamRemote: String, expectedUpstreamBranch: String) { val upstreamRemote = GitBranchUtil.stripRefsPrefix(git("config branch.$localBranch.remote")) val upstreamBranch = GitBranchUtil.stripRefsPrefix(git("config branch.$localBranch.merge")) assertEquals(expectedUpstreamRemote, upstreamRemote) assertEquals(expectedUpstreamBranch, upstreamBranch) } private fun assumeForceWithLeaseSupported() { val version = vcs.version assumeTrue("Skipping this version of Git since it doesn't support --force-with-lease and calls --force: $version", GitVersionSpecialty.SUPPORTS_FORCE_PUSH_WITH_LEASE.existsIn(version)) } }
apache-2.0
d447838d481c841259f511d312579c3c
34.328302
140
0.706831
4.519189
false
true
false
false
google/intellij-community
platform/build-scripts/src/org/jetbrains/intellij/build/impl/ClassFileChecker.kt
2
8905
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.impl import com.intellij.diagnostic.telemetry.useWithScope import com.intellij.openapi.util.SystemInfoRt import com.intellij.util.lang.JavaVersion import io.opentelemetry.api.trace.Span import org.apache.commons.compress.archivers.zip.ZipFile import org.apache.commons.compress.utils.SeekableInMemoryByteChannel import org.jetbrains.intellij.build.BuildMessages import org.jetbrains.intellij.build.TraceManager.spanBuilder import java.io.BufferedInputStream import java.io.DataInputStream import java.io.InputStream import java.nio.channels.FileChannel import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption import java.util.* import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.ForkJoinTask import java.util.concurrent.atomic.AtomicInteger import java.util.zip.ZipException /** * <p> * Recursively checks .class files in directories and .jar/.zip files to ensure that their versions * do not exceed limits specified in the config map. * </p> * <p> * The config map contains pairs of path prefixes (relative to the check root) to version limits. * The limits are Java version strings (<code>"1.3"</code>, <code>"8"</code> etc.); * empty strings are ignored (making the check always pass). * The map must contain an empty path prefix (<code>""</code>) denoting the default version limit. * </p> * <p>Example: <code>["": "1.8", "lib/idea_rt.jar": "1.3"]</code>.</p> */ internal fun checkClassFiles(versionCheckConfig: Map<String, String>, forbiddenSubPaths: List<String>, root: Path, messages: BuildMessages) { spanBuilder("verify class files") .setAttribute("ruleCount", versionCheckConfig.size.toLong()) .setAttribute("forbiddenSubpathCount", forbiddenSubPaths.size.toLong()) .setAttribute("root", root.toString()) .useWithScope { val rules = ArrayList<Rule>(versionCheckConfig.size) for (entry in versionCheckConfig.entries) { rules.add(Rule(path = entry.key, version = classVersion(entry.value))) } rules.sortWith { o1, o2 -> (-o1.path.length).compareTo(-o2.path.length) } check(rules.isEmpty() || rules.last().path.isEmpty()) { throw ClassFileCheckError("Invalid configuration: missing default version $rules") } val defaultVersion = rules.lastOrNull()?.version check(defaultVersion == null || rules.dropLast(1).none { it.version == defaultVersion }) { throw ClassFileCheckError("Redundant rules with default version: " + rules.dropLast(1).filter { it.version == defaultVersion }) } val checker = ClassFileChecker(rules, forbiddenSubPaths) val errors = ConcurrentLinkedQueue<String>() if (Files.isDirectory(root)) { checker.visitDirectory(root, "", errors) } else { checker.visitFile(root, "", errors) } check(rules.isEmpty() || checker.checkedClassCount.get() != 0) { throw ClassFileCheckError("No classes found under $root - please check the configuration") } val errorCount = errors.size Span.current() .setAttribute("checkedClasses", checker.checkedClassCount.get().toLong()) .setAttribute("checkedJarCount", checker.checkedJarCount.get().toLong()) .setAttribute("errorCount", errorCount.toLong()) for (error in errors) { messages.warning("---\n$error") } check(errorCount == 0) { throw ClassFileCheckError("Failed with $errorCount problems", errors) } val unusedRules = rules.filter { !it.wasUsed } check(unusedRules.isEmpty()) { throw ClassFileCheckError("Class version check rules for the following paths don't match any files, probably entries in " + "ProductProperties::versionCheckerConfig are out of date:\n${unusedRules.joinToString(separator = "\n")}") } } } class ClassFileCheckError(message: String, val errors: Collection<String> = emptyList()) : Exception(message) private val READ = EnumSet.of(StandardOpenOption.READ) private class ClassFileChecker(private val versionRules: List<Rule>, private val forbiddenSubPaths: List<String>) { val checkedJarCount = AtomicInteger() val checkedClassCount = AtomicInteger() fun visitDirectory(directory: Path, relPath: String, errors: MutableCollection<String>) { ForkJoinTask.invokeAll(Files.newDirectoryStream(directory).use { dirStream -> // closure must be used, otherwise variables are not captured by FJT dirStream.map { child -> if (Files.isDirectory(child)) { ForkJoinTask.adapt { visitDirectory(directory = child, relPath = join(relPath, "/", child.fileName.toString()), errors = errors) } } else { ForkJoinTask.adapt { visitFile(file = child, relPath = join(relPath, "/", child.fileName.toString()), errors = errors) } } } }) } fun visitFile(file: Path, relPath: String, errors: MutableCollection<String>) { val fullPath = file.toString() if (fullPath.endsWith(".zip") || fullPath.endsWith(".jar")) { visitZip(fullPath, relPath, ZipFile(FileChannel.open(file, READ)), errors) } else if (fullPath.endsWith(".class")) { checkIfSubPathIsForbidden(relPath, errors) val contentCheckRequired = versionRules.isNotEmpty() && !fullPath.endsWith("module-info.class") && !isMultiVersion(fullPath) if (contentCheckRequired) { BufferedInputStream(Files.newInputStream(file)).use { checkVersion(relPath, it, errors) } } } } // use ZipFile - avoid a lot of small lookups to read entry headers (ZipFile uses central directory) private fun visitZip(zipPath: String, zipRelPath: String, file: ZipFile, errors: MutableCollection<String>) { file.use { checkedJarCount.incrementAndGet() val entries = file.entries while (entries.hasMoreElements()) { val entry = entries.nextElement() if (entry.isDirectory) { continue } val name = entry.name if (name.endsWith(".zip") || name.endsWith(".jar")) { val childZipPath = "$zipPath!/$name" try { visitZip(zipPath = childZipPath, zipRelPath = join(zipRelPath, "!/", name), file = ZipFile(SeekableInMemoryByteChannel(file.getInputStream(entry).readAllBytes())), errors = errors) } catch (e: ZipException) { throw RuntimeException("Cannot read $childZipPath", e) } } else if (name.endsWith(".class")) { val relPath = join(zipRelPath, "!/", name) checkIfSubPathIsForbidden(relPath, errors) val contentCheckRequired = versionRules.isNotEmpty() && !name.endsWith("module-info.class") && !isMultiVersion(name) if (contentCheckRequired) { checkVersion(relPath, file.getInputStream(entry), errors) } } } } } private fun checkIfSubPathIsForbidden(relPath: String, errors: MutableCollection<String>) { for (f in forbiddenSubPaths) { if (relPath.contains(f)) { errors.add("$relPath: .class file has a forbidden subpath: $f") } } } private fun checkVersion(path: String, stream: InputStream, errors: MutableCollection<String>) { checkedClassCount.incrementAndGet() val dataStream = DataInputStream(stream) if (dataStream.readInt() != 0xCAFEBABE.toInt() || dataStream.skipBytes(3) != 3) { errors.add("$path: invalid .class file header") return } val major = dataStream.readUnsignedByte() if (major < 44 || major >= 100) { errors.add("$path: suspicious .class file version: $major") return } val rule = versionRules.first { it.path.isEmpty() || path.startsWith(it.path) } rule.wasUsed = true val expected = rule.version @Suppress("ConvertTwoComparisonsToRangeCheck") if (expected > 0 && major > expected) { errors.add("$path: .class file version $major exceeds expected $expected") } } } private fun isMultiVersion(path: String): Boolean { return path.startsWith("META-INF/versions/") || path.contains("/META-INF/versions/") || (SystemInfoRt.isWindows && path.contains("\\META-INF\\versions\\")) } private fun classVersion(version: String) = if (version.isEmpty()) -1 else JavaVersion.parse(version).feature + 44 // 1.1 = 45 private fun join(prefix: String, separator: String, suffix: String) = if (prefix.isEmpty()) suffix else (prefix + separator + suffix) private data class Rule(@JvmField val path: String, @JvmField val version: Int) { @Volatile @JvmField var wasUsed = false }
apache-2.0
412c7dd24f5ecd2fc0c6ad77641428fd
39.666667
141
0.673442
4.365196
false
false
false
false
MarcinMoskala/ActivityStarter
activitystarter-compiler/src/main/java/activitystarter/compiler/generation/BindingHelpers.kt
1
5489
package activitystarter.compiler.generation import activitystarter.compiler.model.param.ParamType import com.google.auto.common.MoreElements.getPackage import com.squareup.javapoet.ClassName.get fun getBindingClassName(enclosingElement: javax.lang.model.element.TypeElement): com.squareup.javapoet.ClassName { val packageName = getPackage(enclosingElement).qualifiedName.toString() val className = enclosingElement.qualifiedName.toString().substring(packageName.length + 1) return get(packageName, className + "Starter") } fun getBundleSetterFor(type: ParamType) = when (type) { ParamType.String -> "putString" ParamType.Int -> "putInt" ParamType.Long -> "putLong" ParamType.Float -> "putFloat" ParamType.Boolean -> "putBoolean" ParamType.Double -> "putDouble" ParamType.Char -> "putChar" ParamType.Byte -> "putByte" ParamType.Short -> "putShort" ParamType.CharSequence -> "putCharSequence" ParamType.BooleanArray -> "putBooleanArray" ParamType.ByteArray -> "putByteArray" ParamType.ShortArray -> "putShortArray" ParamType.CharArray -> "putCharArray" ParamType.IntArray -> "putIntArray" ParamType.LongArray -> "putLongArray" ParamType.FloatArray -> "putFloatArray" ParamType.DoubleArray -> "putDoubleArray" ParamType.StringArray -> "putStringArray" ParamType.CharSequenceArray -> "putCharSequenceArray" ParamType.IntegerArrayList -> "putIntegerArrayList" ParamType.StringArrayList -> "putStringArrayList" ParamType.CharSequenceArrayList -> "putCharSequenceArrayList" ParamType.ParcelableSubtype -> "putParcelable" ParamType.SerializableSubtype -> "putSerializable" ParamType.ParcelableArrayListSubtype -> "putParcelableArrayList" else -> throw Error("Type not supported") } fun getBundleGetter(bundleName: String, paramType: ParamType, keyName: String): String { val bundleGetterCall = activitystarter.compiler.generation.getBundleGetterCall(paramType) return "$bundleName.$bundleGetterCall($keyName)" } private fun getBundleGetterCall(paramType: ParamType) = when (paramType) { ParamType.String -> "getString" ParamType.Int -> "getInt" ParamType.Long -> "getLong" ParamType.Float -> "getFloat" ParamType.Boolean -> "getBoolean" ParamType.Double -> "getDouble" ParamType.Char -> "getChar" ParamType.Byte -> "getByte" ParamType.Short -> "getShort" ParamType.CharSequence -> "getCharSequence" ParamType.BooleanArray -> "getBooleanArray" ParamType.ByteArray -> "getByteArray" ParamType.ShortArray -> "getShortArray" ParamType.CharArray -> "getCharArray" ParamType.IntArray -> "getIntArray" ParamType.LongArray -> "getLongArray" ParamType.FloatArray -> "getFloatArray" ParamType.DoubleArray -> "getDoubleArray" ParamType.StringArray -> "getStringArray" ParamType.CharSequenceArray -> "getCharSequenceArray" ParamType.IntegerArrayList -> "getIntegerArrayList" ParamType.StringArrayList -> "getStringArrayList" ParamType.CharSequenceArrayList -> "getCharSequenceArrayList" ParamType.ParcelableSubtype -> "getParcelable" ParamType.SerializableSubtype -> "getSerializable" ParamType.ParcelableArrayListSubtype -> "getParcelableArrayList" else -> throw Error("Type not supported") } fun getPutArgumentToIntentMethodName(paramType: ParamType) = when(paramType) { ParamType.IntegerArrayList -> "putIntegerArrayListExtra" ParamType.CharSequenceArrayList -> "putCharSequenceArrayListExtra" ParamType.ParcelableArrayListSubtype -> "putParcelableArrayListExtra" ParamType.StringArrayList -> "putStringArrayListExtra" else -> "putExtra" } fun getIntentGetterFor(paramType: ParamType, key: String): String { val getter = getIntentGetterForParamType(paramType, key) return "intent.$getter" } private fun getIntentGetterForParamType(paramType: ParamType, key: String) = when (paramType) { ParamType.String -> "getStringExtra($key)" ParamType.Int -> "getIntExtra($key, -1)" ParamType.Long -> "getLongExtra($key, -1L)" ParamType.Float -> "getFloatExtra($key, -1F)" ParamType.Boolean -> "getBooleanExtra($key, false)" ParamType.Double -> "getDoubleExtra($key, -1D)" ParamType.Char -> "getCharExtra($key, '\\u0000')" ParamType.Byte -> "getByteExtra($key, (byte) 0)" ParamType.Short -> "getShortExtra($key, (short) -1)" ParamType.CharSequence -> "getCharSequenceExtra($key)" ParamType.BooleanArray -> "getBooleanArrayExtra($key)" ParamType.ByteArray -> "getByteArrayExtra($key)" ParamType.ShortArray -> "getShortArrayExtra($key)" ParamType.CharArray -> "getCharArrayExtra($key)" ParamType.IntArray -> "getIntArrayExtra($key)" ParamType.LongArray -> "getLongArrayExtra($key)" ParamType.FloatArray -> "getFloatArrayExtra($key)" ParamType.DoubleArray -> "getDoubleArrayExtra($key)" ParamType.StringArray -> "getStringArrayExtra($key)" ParamType.CharSequenceArray -> "getCharSequenceArrayExtra($key)" ParamType.IntegerArrayList -> "getIntegerArrayListExtra($key)" ParamType.StringArrayList -> "getStringArrayListExtra($key)" ParamType.CharSequenceArrayList -> "getCharSequenceArrayListExtra($key)" ParamType.ParcelableSubtype -> "getParcelableExtra($key)" ParamType.SerializableSubtype -> "getSerializableExtra($key)" ParamType.ParcelableArrayListSubtype -> "getParcelableArrayListExtra($key)" else -> throw Error("Type not supported") }
apache-2.0
377b6a7dd63fc26a9eede1c2381cb602
45.134454
114
0.743669
4.870453
false
false
false
false
RyanSkraba/beam
examples/kotlin/src/main/java/org/apache/beam/examples/kotlin/snippets/Snippets.kt
2
18385
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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 org.apache.beam.examples.kotlin.snippets import com.google.api.services.bigquery.model.* import com.google.common.collect.ImmutableList import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.apache.beam.sdk.Pipeline import org.apache.beam.sdk.coders.AvroCoder import org.apache.beam.sdk.coders.DefaultCoder import org.apache.beam.sdk.coders.DoubleCoder import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.CreateDisposition import org.apache.beam.sdk.io.gcp.bigquery.BigQueryIO.Write.WriteDisposition import org.apache.beam.sdk.io.gcp.bigquery.DynamicDestinations import org.apache.beam.sdk.io.gcp.bigquery.TableDestination import org.apache.beam.sdk.io.gcp.bigquery.WriteResult import org.apache.beam.sdk.transforms.* import org.apache.beam.sdk.transforms.join.CoGbkResult import org.apache.beam.sdk.transforms.join.CoGroupByKey import org.apache.beam.sdk.transforms.join.KeyedPCollectionTuple import org.apache.beam.sdk.values.* /** Code snippets used in webdocs. */ object Snippets { @DefaultCoder(AvroCoder::class) internal class Quote( val source: String = "", val quote: String = "" ) @DefaultCoder(AvroCoder::class) internal class WeatherData( val year: Long = 0, val month: Long = 0, val day: Long = 0, val maxTemp: Double = 0.0 ) @JvmOverloads @SuppressFBWarnings("SE_BAD_FIELD") //Apparently findbugs doesn't like that a non-serialized object i.e. pipeline is being used inside the run{} block fun modelBigQueryIO( pipeline: Pipeline, writeProject: String = "", writeDataset: String = "", writeTable: String = "") { run { // [START BigQueryTableSpec] val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [END BigQueryTableSpec] } run { // [START BigQueryTableSpecWithoutProject] val tableSpec = "samples.weather_stations" // [END BigQueryTableSpecWithoutProject] } run { // [START BigQueryTableSpecObject] val tableSpec = TableReference() .setProjectId("clouddataflow-readonly") .setDatasetId("samples") .setTableId("weather_stations") // [END BigQueryTableSpecObject] } run { val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [START BigQueryReadTable] val maxTemperatures = pipeline.apply(BigQueryIO.readTableRows().from(tableSpec)) // Each row is of type TableRow .apply<PCollection<Double>>( MapElements.into(TypeDescriptors.doubles()) .via(SerializableFunction<TableRow, Double> { it["max_temperature"] as Double }) ) // [END BigQueryReadTable] } run { val tableSpec = "clouddataflow-readonly:samples.weather_stations" // [START BigQueryReadFunction] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double } .from(tableSpec) .withCoder(DoubleCoder.of())) // [END BigQueryReadFunction] } run { // [START BigQueryReadQuery] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double } .fromQuery( "SELECT max_temperature FROM [clouddataflow-readonly:samples.weather_stations]") .withCoder(DoubleCoder.of())) // [END BigQueryReadQuery] } run { // [START BigQueryReadQueryStdSQL] val maxTemperatures = pipeline.apply( BigQueryIO.read { it.record["max_temperature"] as Double } .fromQuery( "SELECT max_temperature FROM `clouddataflow-readonly.samples.weather_stations`") .usingStandardSql() .withCoder(DoubleCoder.of())) // [END BigQueryReadQueryStdSQL] } // [START BigQuerySchemaJson] val tableSchemaJson = ( "{" + " \"fields\": [" + " {" + " \"name\": \"source\"," + " \"type\": \"STRING\"," + " \"mode\": \"NULLABLE\"" + " }," + " {" + " \"name\": \"quote\"," + " \"type\": \"STRING\"," + " \"mode\": \"REQUIRED\"" + " }" + " ]" + "}") // [END BigQuerySchemaJson] run { var tableSpec = "clouddataflow-readonly:samples.weather_stations" if (writeProject.isNotEmpty() && writeDataset.isNotEmpty() && writeTable.isNotEmpty()) { tableSpec = "$writeProject:$writeDataset.$writeTable" } // [START BigQuerySchemaObject] val tableSchema = TableSchema() .setFields( ImmutableList.of( TableFieldSchema() .setName("source") .setType("STRING") .setMode("NULLABLE"), TableFieldSchema() .setName("quote") .setType("STRING") .setMode("REQUIRED"))) // [END BigQuerySchemaObject] // [START BigQueryWriteInput] /* @DefaultCoder(AvroCoder::class) class Quote( val source: String = "", val quote: String = "" ) */ val quotes = pipeline.apply( Create.of( Quote("Mahatma Gandhi", "My life is my message."), Quote("Yoda", "Do, or do not. There is no 'try'."))) // [END BigQueryWriteInput] // [START BigQueryWriteTable] quotes .apply<PCollection<TableRow>>( MapElements.into(TypeDescriptor.of(TableRow::class.java)) .via(SerializableFunction<Quote, TableRow> { TableRow().set("source", it.source).set("quote", it.quote) })) .apply<WriteResult>( BigQueryIO.writeTableRows() .to(tableSpec) .withSchema(tableSchema) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteTable] // [START BigQueryWriteFunction] quotes.apply<WriteResult>( BigQueryIO.write<Quote>() .to(tableSpec) .withSchema(tableSchema) .withFormatFunction { TableRow().set("source", it.source).set("quote", it.quote) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteFunction] // [START BigQueryWriteJsonSchema] quotes.apply<WriteResult>( BigQueryIO.write<Quote>() .to(tableSpec) .withJsonSchema(tableSchemaJson) .withFormatFunction { TableRow().set("source", it.source).set("quote", it.quote) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteJsonSchema] } run { // [START BigQueryWriteDynamicDestinations] /* @DefaultCoder(AvroCoder::class) class WeatherData( val year: Long = 0, val month: Long = 0, val day: Long = 0, val maxTemp: Double = 0.0 ) */ val weatherData = pipeline.apply( BigQueryIO.read { val record = it.record WeatherData( record.get("year") as Long, record.get("month") as Long, record.get("day") as Long, record.get("max_temperature") as Double) } .fromQuery(""" SELECT year, month, day, max_temperature FROM [clouddataflow-readonly:samples.weather_stations] WHERE year BETWEEN 2007 AND 2009 """.trimIndent()) .withCoder(AvroCoder.of(WeatherData::class.java))) // We will send the weather data into different tables for every year. weatherData.apply<WriteResult>( BigQueryIO.write<WeatherData>() .to( object : DynamicDestinations<WeatherData, Long>() { override fun getDestination(elem: ValueInSingleWindow<WeatherData>): Long? { return elem.value!!.year } override fun getTable(destination: Long?): TableDestination { return TableDestination( TableReference() .setProjectId(writeProject) .setDatasetId(writeDataset) .setTableId("${writeTable}_$destination"), "Table for year $destination") } override fun getSchema(destination: Long?): TableSchema { return TableSchema() .setFields( ImmutableList.of( TableFieldSchema() .setName("year") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("month") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("day") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema() .setName("maxTemp") .setType("FLOAT") .setMode("NULLABLE"))) } }) .withFormatFunction { TableRow() .set("year", it.year) .set("month", it.month) .set("day", it.day) .set("maxTemp", it.maxTemp) } .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryWriteDynamicDestinations] var tableSpec = "clouddataflow-readonly:samples.weather_stations" if (writeProject.isNotEmpty() && writeDataset.isNotEmpty() && writeTable.isNotEmpty()) { tableSpec = "$writeProject:$writeDataset.${writeTable}_partitioning" } val tableSchema = TableSchema() .setFields( ImmutableList.of( TableFieldSchema().setName("year").setType("INTEGER").setMode("REQUIRED"), TableFieldSchema() .setName("month") .setType("INTEGER") .setMode("REQUIRED"), TableFieldSchema().setName("day").setType("INTEGER").setMode("REQUIRED"), TableFieldSchema() .setName("maxTemp") .setType("FLOAT") .setMode("NULLABLE"))) // [START BigQueryTimePartitioning] weatherData.apply<WriteResult>( BigQueryIO.write<WeatherData>() .to("${tableSpec}_partitioning") .withSchema(tableSchema) .withFormatFunction { TableRow() .set("year", it.year) .set("month", it.month) .set("day", it.day) .set("maxTemp", it.maxTemp) } // NOTE: an existing table without time partitioning set up will not work .withTimePartitioning(TimePartitioning().setType("DAY")) .withCreateDisposition(CreateDisposition.CREATE_IF_NEEDED) .withWriteDisposition(WriteDisposition.WRITE_TRUNCATE)) // [END BigQueryTimePartitioning] } } /** Helper function to format results in coGroupByKeyTuple. */ fun formatCoGbkResults( name: String?, emails: Iterable<String>, phones: Iterable<String>): String { val emailsList = ArrayList<String>() for (elem in emails) { emailsList.add("'$elem'") } emailsList.sort() val emailsStr = "[${emailsList.joinToString(", ")}]" val phonesList = ArrayList<String>() for (elem in phones) { phonesList.add("'$elem'") } phonesList.sort() val phonesStr = "[${phonesList.joinToString(", ")}]" return "$name; $emailsStr; $phonesStr" } /** Using a CoGroupByKey transform. */ fun coGroupByKeyTuple( emailsTag: TupleTag<String>, phonesTag: TupleTag<String>, emails: PCollection<KV<String, String>>, phones: PCollection<KV<String, String>>): PCollection<String> { // [START CoGroupByKeyTuple] val results = KeyedPCollectionTuple.of(emailsTag, emails) .and(phonesTag, phones) .apply(CoGroupByKey.create()) // [END CoGroupByKeyTuple] return results.apply( ParDo.of( object : DoFn<KV<String, CoGbkResult>, String>() { @ProcessElement fun processElement(c: ProcessContext) { val e = c.element() val name = e.key val emailsIter = e.value.getAll(emailsTag) val phonesIter = e.value.getAll(phonesTag) val formattedResult = formatCoGbkResults(name, emailsIter, phonesIter) c.output(formattedResult) } })) } } /** Using a Read and Write transform to read/write from/to BigQuery. */
apache-2.0
9a58c757d93f75951d3dfed480b06a50
47.128272
143
0.447212
5.770559
false
false
false
false
Setekh/corvus-android-essentials
app/src/main/java/eu/corvus/essentials/core/Preferences.kt
1
2120
package eu.corvus.essentials.core import android.content.Context import android.preference.PreferenceManager import android.util.Base64 import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.debug import java.net.URLDecoder import kotlin.reflect.KClass /** * Created by Vlad Cazacu on 5/2/2016. */ object Preferences : AnkoLogger { private lateinit var context: Context val defaultPrefs by lazy { PreferenceManager.getDefaultSharedPreferences(context) } internal fun initialize(context: Context) { this.context = context } fun <T : Any> store(obj: T) { val value = gson.toJson(obj) defaultPrefs.edit().putString("obj-${obj.javaClass.simpleName}", Base64.encodeToString(value.toByteArray(Charsets.UTF_8), Base64.NO_WRAP)).apply() } fun <T : Any> fetch(clazz: KClass<T>) : T? { return fetch(clazz.java) } fun clear(clazz: KClass<*>) { clear(clazz.java) } fun clear(clazz: KClass<*>, vararg clazzz: KClass<*>) { clear(clazz.java) for(i in clazzz.indices) clear(clazzz[i].java) } fun contains(clazz: KClass<*>): Boolean { return defaultPrefs.contains("obj-${clazz.java.simpleName}") } fun clear(clazz: Class<*>) { defaultPrefs.edit().remove("obj-${clazz.simpleName}").apply() debug("Cleared object[${clazz.simpleName}] not found.") } fun <T : Any> fetch(clazz: Class<T>) : T? { val value: String? = defaultPrefs.getString("obj-${clazz.simpleName}", null) try { if (value != null) return gson.fromJson(String(Base64.decode(value, Base64.NO_WRAP), Charsets.UTF_8), clazz) } catch (e: Exception) { val obj = gson.fromJson(URLDecoder.decode(value), clazz) store(obj) return obj } debug("Fetched object[${clazz.simpleName}] not found.") return null } /** * Used to wipe everything use #clear if you want to remove a specific thing */ fun clearDefaults() { defaultPrefs.edit().clear().commit() } }
apache-2.0
38d0c5215463c6dc3bbdd09c38968c53
26.907895
154
0.626415
4.030418
false
false
false
false