repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
panoptes-app/panoptes-server | src/main/kotlin/org/panoptes/server/core/MainVerticle.kt | 1 | 6212 | package org.panoptes.server.core
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.handler.codec.mqtt.MqttConnectReturnCode
import io.vertx.core.AbstractVerticle
import io.vertx.core.DeploymentOptions
import io.vertx.core.http.HttpMethod
import io.vertx.core.json.JsonObject
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import io.vertx.kotlin.mqtt.MqttServerOptions
import io.vertx.mqtt.MqttServer
class MainVerticle : AbstractVerticle() {
@Throws(Exception::class)
override fun start() {
startMongoVerticle()
}
private fun startMongoVerticle() {
val options = DeploymentOptions().setConfig(config())
vertx.deployVerticle(MongoVerticle::class.java, options, { verticleDeployment ->
if (verticleDeployment.succeeded()) {
val httpPort = config().getInteger("http.port", 8080)!!
val mqttPort = config().getInteger("mqtt.port", 1883)!!
startHttpServer(httpPort)
startMqttBroker(mqttPort)
} else {
println("could not start mongo verticle because : ${verticleDeployment.cause()}")
}
})
}
private fun startMqttBroker(mqttPort: Int) {
val mqttServerOptions = MqttServerOptions(clientAuthRequired = true, port = mqttPort, autoClientId = true)
val mqttServer = MqttServer.create(vertx, mqttServerOptions)
mqttServer.endpointHandler { endpoint ->
// shows main connect info
println("MQTT client [" + endpoint.clientIdentifier() + "] request to connect, clean session = " + endpoint.isCleanSession)
if (endpoint.auth() != null) {
println("try to authenticate [username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "]")
vertx.eventBus().send<Boolean>(Constants.TOPIC_AUTH_USER, JsonObject().put("login", endpoint.auth().userName()).put("password", endpoint.auth().password()), { response ->
if (!response.succeeded() || !response.result().body()) {
endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED)
} else {
println("authenticate [username = " + endpoint.auth().userName() + ", password = " + endpoint.auth().password() + "] => OK")
if (endpoint.will() != null) {
println("[will topic = " + endpoint.will().willTopic() + " msg = " + endpoint.will().willMessage() +
" QoS = " + endpoint.will().willQos() + " isRetain = " + endpoint.will().isWillRetain + "]")
}
println("[keep alive timeout = " + endpoint.keepAliveTimeSeconds() + "]")
// accept connection from the remote client
endpoint.accept(false)
}
})
} else {
endpoint.reject(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED)
}
endpoint.publishHandler({ message ->
println("msg published on topic ${message.topicName()} : ${String(message.payload().getBytes())}")
})
}.listen { ar ->
if (ar.succeeded()) {
println("MQTT server is listening on port " + ar.result().actualPort())
} else {
println("Error on starting the server")
ar.cause().printStackTrace()
}
}
}
private fun startHttpServer(httpPort: Int) {
val router = Router.router(vertx)
router.route("/auth").handler { routingContext ->
if (routingContext.request().method() == HttpMethod.GET) {
val login = routingContext.request().getParam("login")
val password = routingContext.request().getParam("password")
checkLogin(login, password, routingContext)
} else {
routingContext.fail(HttpResponseStatus.BAD_REQUEST.code())
}
}
router.route("/user").handler { routingContext ->
if (routingContext.request().method() == HttpMethod.POST) {
val login = routingContext.request().getParam("login")
val password = routingContext.request().getParam("password")
createUser(login, password, routingContext)
} else {
routingContext.fail(HttpResponseStatus.BAD_REQUEST.code())
}
}
vertx.createHttpServer().requestHandler(router::accept).listen(httpPort)
println("HTTP server started on port ${httpPort}")
}
private fun createUser(login: String?, password: String?, routingContext: RoutingContext) {
if (login != null && password != null) {
vertx.eventBus().send<String>(Constants.TOPIC_CREATE_USER, JsonObject().put("login",login).put("password", password),{ response ->
if (response.succeeded()) {
routingContext.response().statusCode = HttpResponseStatus.CREATED.code()
routingContext.response().end(response.result().body())
} else {
routingContext.fail(response.cause())
}
} )
} else {
routingContext.fail(HttpResponseStatus.FORBIDDEN.code())
}
}
private fun checkLogin(login: String?, password: String?, routingContext: RoutingContext) {
if (login != null && password != null) {
vertx.eventBus().send<Boolean>(Constants.TOPIC_AUTH_USER, JsonObject().put("login",login).put("password", password),{ response ->
if (response.succeeded() && response.result().body()) {
routingContext.response().statusCode = HttpResponseStatus.OK.code()
} else {
routingContext.fail( HttpResponseStatus.FORBIDDEN.code())
}
} )
} else {
routingContext.response().statusCode = HttpResponseStatus.FORBIDDEN.code()
}
routingContext.response().end()
}
}
| apache-2.0 | 5ccaad5ec023096f6c09186225502dba | 43.371429 | 186 | 0.57888 | 5.066884 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/pointerpanel/PointerPanelView.kt | 1 | 10660 | package com.hewking.pointerpanel
import android.content.Context
import android.content.res.Resources
import android.graphics.*
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import androidx.core.graphics.toColorInt
import androidx.core.math.MathUtils
import com.hewking.custom.R
import kotlin.math.min
/**
* 指针面板视图
*
* 注意:只有[paddingTop]属性有效
*
* 角度按照安卓坐标系的方向从0-360
*
* @author hewking
* @date 2019/12/27
*/
class PointerPanelView(context: Context, attributeSet: AttributeSet? = null) :
View(context, attributeSet) {
val degreesGestureDetector: DegreesGestureDetector
/**轨道背景颜色*/
var trackBgColor: Int = "#E8E8E8".toColorInt()
/**轨道进度*/
var trackProgressStartColor: Int = "#FFC24B".toColorInt()
var trackProgressEndColor: Int = "#FF8E24".toColorInt()
/**轨道大小*/
var trackSize: Int = 10.toDpi()
/**
* 轨道的半径
* 用来推算原点坐标
*
* 只有将轨道绘制成圆,用户体验才好. 椭圆的体验不好.
* */
var trackRadius: Float = -1f
/**轨道绘制开始的角度*/
var trackStartAngle: Int = 200
var trackEndAngle: Int = 340
/**当前的进度*/
var trackProgress: Float = 0f
set(value) {
field = value
postInvalidate()
}
/**浮子*/
var thumbDrawable: Drawable? = null
/**浮子绘制在多少半径上, -1表示在轨道上*/
var thumbRadius: Float = -1f
/**浮子是否跟随进度,旋转*/
var thumbEnableRotate: Boolean = true
/**浮子额外旋转的角度*/
var thumbRotateOffsetDegrees: Int = 90
/**文本指示绘制回调*/
var onPointerTextConfig: (degrees: Int, progress: Float, config: PointerTextConfig) -> Unit =
{ degrees, progress, config ->
if (progress == 0.1f || progress == 0.9f || progress == 0.5f || progress == 0.3f || progress == 0.7f) {
config.text = "$degrees°C"
}
}
/**文本绘制时, 跨度多少*/
var angleTextConfigStep = 1
/**进度改变回调*/
var onProgressChange: (progress: Float, fromUser: Boolean) -> Unit = { _, _ ->
}
val _pointerTextConfig = PointerTextConfig()
val paint: Paint by lazy {
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeCap = Paint.Cap.ROUND
}
}
init {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.PointerPanelView)
trackRadius =
typedArray.getDimensionPixelOffset(R.styleable.PointerPanelView_p_track_radius, -1)
.toFloat()
trackSize =
typedArray.getDimensionPixelOffset(R.styleable.PointerPanelView_p_track_size, trackSize)
trackStartAngle =
typedArray.getInt(R.styleable.PointerPanelView_p_track_start_angle, trackStartAngle)
trackEndAngle =
typedArray.getInt(R.styleable.PointerPanelView_p_track_end_angle, trackEndAngle)
thumbDrawable = typedArray.getDrawable(R.styleable.PointerPanelView_p_thumb_drawable)
angleTextConfigStep = typedArray.getInt(
R.styleable.PointerPanelView_p_track_angle_text_step,
angleTextConfigStep
)
setProgress(
typedArray.getFloat(
R.styleable.PointerPanelView_p_track_progress,
trackProgress
), false
)
thumbRadius = typedArray.getDimensionPixelOffset(
R.styleable.PointerPanelView_p_thumb_radius,
thumbRadius.toInt()
).toFloat()
typedArray.recycle()
degreesGestureDetector = DegreesGestureDetector()
degreesGestureDetector.onHandleEvent = { touchDegrees, rotateDegrees, touchDistance ->
//i("handle:$touchDegrees $rotateDegrees")
if (rotateDegrees <= 3) {
val range = (trackStartAngle - 10)..(trackEndAngle + 10)
touchDegrees in range ||
(touchDegrees + 360) in range
} else {
true
}
}
degreesGestureDetector.onDegreesChange =
{ touchDegrees, touchDegreesQuadrant, rotateDegrees, touchDistance ->
val range = trackStartAngle..trackEndAngle
//i("$touchDegrees $touchDegreesQuadrant")
var degress = if (touchDegreesQuadrant < 0) touchDegrees else touchDegreesQuadrant
if (degreesGestureDetector._downQuadrant == 4 &&
degreesGestureDetector._downQuadrant == degreesGestureDetector._lastQuadrant
) {
//在第4象限按下, 并且未改变过象限
degress = touchDegrees + 360
}
if (degress in range) {
setProgress(
(degress - trackStartAngle.toFloat()) / (trackEndAngle.toFloat() - trackStartAngle.toFloat()),
true
)
}
//i("进度:$touchDegrees $touchDegreesQuadrant $trackProgress")
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (trackRadius < 0) {
trackRadius = min(measuredWidth, measuredHeight) / 2f
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.style = Paint.Style.STROKE
paint.strokeWidth = trackSize.toFloat()
paint.color = trackBgColor
tempRectF.set(trackRectF)
tempRectF.inset(paint.strokeWidth / 2, paint.strokeWidth / 2)
//绘制背景
paint.shader = null
canvas.drawArc(
tempRectF,
trackStartAngle.toFloat(),
trackEndAngle.toFloat() - trackStartAngle.toFloat(),
false, paint
)
//绘制进度
paint.shader = LinearGradient(
tempRectF.left,
0f,
tempRectF.left + tempRectF.width() * trackProgress,
0f,
trackProgressStartColor,
trackProgressEndColor,
Shader.TileMode.CLAMP
)
canvas.drawArc(
tempRectF,
trackStartAngle.toFloat(),
(trackEndAngle - trackStartAngle) * trackProgress,
false,
paint
)
paint.shader = null
paint.style = Paint.Style.FILL
//绘制文本
for (angle in trackStartAngle..trackEndAngle step angleTextConfigStep) {
_pointerTextConfig.reset()
onPointerTextConfig(
angle,
(angle - trackStartAngle).toFloat() / (trackEndAngle - trackStartAngle),
_pointerTextConfig
)
_pointerTextConfig.apply {
if (text?.isNotEmpty() == true) {
paint.color = textColor
paint.textSize = textSize
val textWidth = paint.measureText(text)
val pointF = dotDegrees(
trackRadius - trackSize / 2 - textWidth, angle,
trackRectF.centerX().toInt(),
trackRectF.centerY().toInt()
)
canvas.drawText(
text!!,
pointF.x - textWidth / 2 + textOffsetX,
pointF.y + textOffsetY,
paint
)
}
}
}
val angle = trackStartAngle + (trackEndAngle - trackStartAngle) * trackProgress
//绘制浮子
thumbDrawable?.apply {
val radius = if (thumbRadius >= 0) thumbRadius else trackRadius - trackSize / 2
val pointF = dotDegrees(
radius, angle.toInt(),
trackRectF.centerX().toInt(),
trackRectF.centerY().toInt()
)
val left = (pointF.x - minimumWidth / 2).toInt()
val top = (pointF.y - minimumHeight / 2).toInt()
setBounds(
left,
top,
left + minimumWidth,
top + minimumHeight
)
if (thumbEnableRotate) {
canvas.save()
canvas.rotate(angle + thumbRotateOffsetDegrees, pointF.x, pointF.y)
draw(canvas)
canvas.restore()
} else {
draw(canvas)
}
}
//i("${(trackEndAngle - trackStartAngle) * trackProgress}")
}
val drawRectF = RectF()
get() {
field.set(
paddingLeft.toFloat(),
paddingTop.toFloat(),
(measuredWidth - paddingRight).toFloat(),
(measuredHeight - paddingBottom).toFloat()
)
return field
}
val trackRectF = RectF()
get() {
field.set(
drawRectF.centerX() - trackRadius,
drawRectF.top,
drawRectF.centerX() + trackRadius,
drawRectF.top + trackRadius * 2
)
return field
}
val tempRectF = RectF()
override fun onTouchEvent(event: MotionEvent): Boolean {
super.onTouchEvent(event)
if (!isEnabled) {
return false
}
degreesGestureDetector.onTouchEvent(event, trackRectF.centerX(), trackRectF.centerY())
return true
}
fun setProgress(progress: Float, fromUser: Boolean = false) {
//i("进度:$progress")
trackProgress = MathUtils.clamp(progress, 0f, 1f)
onProgressChange(trackProgress, fromUser)
}
fun i(msg: String) {
Log.i("PointerPanelView", msg)
}
}
data class PointerTextConfig(
var text: String? = null,
var textColor: Int = 0,
var textSize: Float = 0f,
var textOffsetX: Int = 0,
var textOffsetY: Int = 0
)
fun PointerTextConfig.reset() {
text = null
textColor = "#333333".toColorInt()
textSize = 10.toDp()
textOffsetX = 0
textOffsetY = 0
}
internal val dp: Float = Resources.getSystem()?.displayMetrics?.density ?: 0f
internal val dpi: Int = Resources.getSystem()?.displayMetrics?.density?.toInt() ?: 0
internal fun Int.toDp(): Float {
return this * dp
}
internal fun Int.toDpi(): Int {
return this * dpi
} | mit | 70476dae3e43f295ab44c3dbdb5f2784 | 28.238636 | 118 | 0.560198 | 4.879564 | false | false | false | false |
arturbosch/TiNBo | tinbo-plugin-api/src/main/kotlin/io/gitlab/arturbosch/tinbo/api/Junk.kt | 1 | 1836 | package io.gitlab.arturbosch.tinbo.api
import java.util.ArrayList
fun Number.toTimeString(): String {
return toString().apply {
if (length == 1) {
return "0$this"
}
}
}
fun String.spaceIfEmpty(): String =
when (this) {
"" -> " "
else -> this
}
fun String.orThrow(message: () -> String = { "Empty value not allowed!" }): String =
if (this.isEmpty())
throw IllegalArgumentException(message())
else this
inline fun String.toLongOrDefault(long: () -> Long): Long {
return try {
this.toLong()
} catch (e: NumberFormatException) {
long.invoke()
}
}
inline fun String.toIntOrDefault(int: () -> Int): Int {
return try {
this.toInt()
} catch (e: NumberFormatException) {
int.invoke()
}
}
fun <E> List<E>.plusElementAtBeginning(element: E): List<E> {
val result = ArrayList<E>(size + 1)
result.add(element)
result.addAll(this)
return result
}
fun List<String>.withIndexedColumn(): List<String> = this.withIndex().map { "${it.index + 1};${it.value}" }
fun <E> List<E>.applyToString(): List<String> = this.map { it.toString() }
fun <E> List<E>.replaceAt(index: Int, element: E): List<E> {
val list = this.toMutableList()
list[index] = element
return list.toList()
}
fun String.orValue(value: String): String = if (this.isEmpty()) value else this
fun String?.orDefault(value: String): String = if (this.isNullOrEmpty()) value else this!!
fun String.replaceSeparator(): String {
return this.replace(";", ".,")
}
fun String.orDefaultMonth(): Int = this.toIntOrDefault { java.time.LocalDate.now().month.value }
fun String?.toLongOrNull(): Long? = if (this.isNullOrEmpty()) null else this?.toLong()
fun String?.nullIfEmpty(): String? = if (this.isNullOrEmpty()) null else this
fun <E> List<E>.ifNotEmpty(function: List<E>.() -> Unit) {
if (this.isNotEmpty()) {
function.invoke(this)
}
}
| apache-2.0 | 7783394adee4213ebc96b0c21196abb2 | 24.5 | 107 | 0.670479 | 3.149228 | false | false | false | false |
kotlin-graphics/imgui | core/src/main/kotlin/imgui/internal/sections/drawList support.kt | 1 | 3699 | package imgui.internal.sections
import glm_.f
import glm_.glm
import glm_.i
import glm_.min
import glm_.vec2.Vec2
import glm_.vec4.Vec4
import imgui.clamp
import imgui.classes.DrawList
import imgui.font.Font
import kotlin.math.acos
import kotlin.math.cos
import kotlin.math.sin
//-----------------------------------------------------------------------------
// [SECTION] ImDrawList support
//-----------------------------------------------------------------------------
// ImDrawList: Helper function to calculate a circle's segment count given its radius and a "maximum error" value.
// FIXME: the minimum number of auto-segment may be undesirably high for very small radiuses (e.g. 1.0f)
const val DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN = 12
const val DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX = 512
fun DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(_RAD: Float, _MAXERROR: Float) = clamp(((glm.πf * 2f) / acos((_RAD - _MAXERROR) / _RAD)).i, DRAWLIST_CIRCLE_AUTO_SEGMENT_MIN, DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX)
/** ImDrawList: You may set this to higher values (e.g. 2 or 3) to increase tessellation of fast rounded corners path. */
var DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER = 1
/** Data shared between all ImDrawList instances
* You may want to create your own instance of this if you want to use ImDrawList completely without ImGui. In that case, watch out for future changes to this structure.
* Data shared among multiple draw lists (typically owned by parent ImGui context, but you may create one yourself) */
class DrawListSharedData {
/** UV of white pixel in the atlas */
var texUvWhitePixel = Vec2()
/** Current/default font (optional, for simplified AddText overload) */
var font: Font? = null
/** Current/default font size (optional, for simplified AddText overload) */
var fontSize = 0f
var curveTessellationTol = 0f
/** Number of circle segments to use per pixel of radius for AddCircle() etc */
var circleSegmentMaxError = 0f
/** Value for pushClipRectFullscreen() */
var clipRectFullscreen = Vec4()
/** Initial flags at the beginning of the frame (it is possible to alter flags on a per-drawlist basis afterwards) */
var initialFlags = DrawListFlag.None.i
// [Internal] Lookup tables
// Lookup tables
val arcFastVtx = Array(12 * DRAWLIST_ARCFAST_TESSELLATION_MULTIPLIER) {
// FIXME: Bake rounded corners fill/borders in atlas
val a = it * 2 * glm.PIf / 12
Vec2(cos(a), sin(a))
}
/** Precomputed segment count for given radius before we calculate it dynamically (to avoid calculation overhead) */
val circleSegmentCounts = IntArray(64)
/** UV of anti-aliased lines in the atlas */
lateinit var texUvLines: Array<Vec4>
fun setCircleSegmentMaxError_(maxError: Float) {
if (circleSegmentMaxError == maxError)
return
circleSegmentMaxError = maxError
for (i in circleSegmentCounts.indices) {
val radius = i.f
val segmentCount = DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, circleSegmentMaxError)
circleSegmentCounts[i] = segmentCount min 255
}
}
}
/** Helper to build a ImDrawData instance */
class DrawDataBuilder {
/** Global layers for: regular, tooltip */
val layers = Array(2) { ArrayList<DrawList>() }
fun clear() = layers.forEach { it.clear() }
fun flattenIntoSingleLayer() {
val size = layers.map { it.size }.count()
layers[0].ensureCapacity(size)
for (layerN in 1 until layers.size) {
val layer = layers[layerN]
if (layer.isEmpty()) continue
layers[0].addAll(layer)
layer.clear()
}
}
} | mit | dd0f3a873ddb67f7611a0737c4b00f65 | 36.744898 | 197 | 0.659546 | 4.216648 | false | false | false | false |
cashapp/sqldelight | dialects/sqlite-3-24/src/main/kotlin/app/cash/sqldelight/dialects/sqlite_3_24/grammar/mixins/InsertStmtMixin.kt | 1 | 1802 | package app.cash.sqldelight.dialects.sqlite_3_24.grammar.mixins
import app.cash.sqldelight.dialects.sqlite_3_24.grammar.psi.SqliteInsertStmt
import com.alecstrong.sql.psi.core.SqlAnnotationHolder
import com.alecstrong.sql.psi.core.psi.SqlTypes
import com.alecstrong.sql.psi.core.psi.impl.SqlInsertStmtImpl
import com.intellij.lang.ASTNode
internal abstract class InsertStmtMixin(
node: ASTNode,
) : SqlInsertStmtImpl(node),
SqliteInsertStmt {
override fun annotate(annotationHolder: SqlAnnotationHolder) {
super.annotate(annotationHolder)
val insertDefaultValues = insertStmtValues?.node?.findChildByType(
SqlTypes.DEFAULT,
) != null
upsertClause?.let { upsert ->
val upsertDoUpdate = upsert.upsertDoUpdate
if (insertDefaultValues && upsertDoUpdate != null) {
annotationHolder.createErrorAnnotation(upsert, "The upsert clause is not supported after DEFAULT VALUES")
}
val insertOr = node.findChildByType(
SqlTypes.INSERT,
)?.treeNext
val replace = node.findChildByType(
SqlTypes.REPLACE,
)
val conflictResolution = when {
replace != null -> SqlTypes.REPLACE
insertOr != null && insertOr.elementType == SqlTypes.OR -> {
val type = insertOr.treeNext.elementType
check(
type == SqlTypes.ROLLBACK || type == SqlTypes.ABORT ||
type == SqlTypes.FAIL || type == SqlTypes.IGNORE,
)
type
}
else -> null
}
if (conflictResolution != null && upsertDoUpdate != null) {
annotationHolder.createErrorAnnotation(
upsertDoUpdate,
"Cannot use DO UPDATE while " +
"also specifying a conflict resolution algorithm ($conflictResolution)",
)
}
}
}
}
| apache-2.0 | c9e4626d0b4f4c0c0a4b4c73e005d80b | 33 | 113 | 0.668147 | 4.754617 | false | false | false | false |
cashapp/sqldelight | extensions/android-paging3/src/main/java/app/cash/sqldelight/paging3/OffsetQueryPagingSource.kt | 1 | 2433 | /*
* Copyright (C) 2016 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.sqldelight.paging3
import androidx.paging.PagingState
import app.cash.sqldelight.Query
import app.cash.sqldelight.Transacter
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
internal class OffsetQueryPagingSource<RowType : Any>(
private val queryProvider: (limit: Int, offset: Int) -> Query<RowType>,
private val countQuery: Query<Int>,
private val transacter: Transacter,
private val context: CoroutineContext,
) : QueryPagingSource<Int, RowType>() {
override val jumpingSupported get() = true
override suspend fun load(
params: LoadParams<Int>,
): LoadResult<Int, RowType> = withContext(context) {
val key = params.key ?: 0
val limit = when (params) {
is LoadParams.Prepend -> minOf(key, params.loadSize)
else -> params.loadSize
}
val loadResult = transacter.transactionWithResult {
val count = countQuery.executeAsOne()
val offset = when (params) {
is LoadParams.Prepend -> maxOf(0, key - params.loadSize)
is LoadParams.Append -> key
is LoadParams.Refresh -> if (key >= count) maxOf(0, count - params.loadSize) else key
}
val data = queryProvider(limit, offset)
.also { currentQuery = it }
.executeAsList()
val nextPosToLoad = offset + data.size
LoadResult.Page(
data = data,
prevKey = offset.takeIf { it > 0 && data.isNotEmpty() },
nextKey = nextPosToLoad.takeIf { data.isNotEmpty() && data.size >= limit && it < count },
itemsBefore = offset,
itemsAfter = maxOf(0, count - nextPosToLoad),
)
}
if (invalid) LoadResult.Invalid() else loadResult
}
override fun getRefreshKey(state: PagingState<Int, RowType>) =
state.anchorPosition?.let { maxOf(0, it - (state.config.initialLoadSize / 2)) }
}
| apache-2.0 | 1ecc094cb1fa67d5e9c8d67b55c706d6 | 36.430769 | 97 | 0.690917 | 4.238676 | false | false | false | false |
pyamsoft/pasterino | app/src/main/java/com/pyamsoft/pasterino/test/TestImageLoader.kt | 1 | 3249 | /*
* Copyright 2021 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pasterino.test
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.annotation.CheckResult
import androidx.compose.runtime.Composable
import coil.ImageLoader
import coil.annotation.ExperimentalCoilApi
import coil.bitmap.BitmapPool
import coil.decode.DataSource
import coil.memory.MemoryCache
import coil.request.DefaultRequestOptions
import coil.request.Disposable
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.SuccessResult
/** Only use for tests/previews */
private class TestImageLoader(context: Context) : ImageLoader {
private val context = context.applicationContext
private val loadingDrawable by lazy(LazyThreadSafetyMode.NONE) { ColorDrawable(Color.BLACK) }
private val successDrawable by lazy(LazyThreadSafetyMode.NONE) { ColorDrawable(Color.GREEN) }
private val disposable =
object : Disposable {
override val isDisposed: Boolean = true
@ExperimentalCoilApi override suspend fun await() {}
override fun dispose() {}
}
override val bitmapPool: BitmapPool = BitmapPool(0)
override val defaults: DefaultRequestOptions = DefaultRequestOptions()
override val memoryCache: MemoryCache =
object : MemoryCache {
override val maxSize: Int = 1
override val size: Int = 0
override fun clear() {}
override fun get(key: MemoryCache.Key): Bitmap? {
return null
}
override fun remove(key: MemoryCache.Key): Boolean {
return false
}
override fun set(key: MemoryCache.Key, bitmap: Bitmap) {}
}
override fun enqueue(request: ImageRequest): Disposable {
request.apply {
target?.onStart(placeholder = loadingDrawable)
target?.onSuccess(result = successDrawable)
}
return disposable
}
override suspend fun execute(request: ImageRequest): ImageResult {
return SuccessResult(
drawable = successDrawable,
request = request,
metadata =
ImageResult.Metadata(
memoryCacheKey = MemoryCache.Key(""),
isSampled = false,
dataSource = DataSource.MEMORY_CACHE,
isPlaceholderMemoryCacheKeyPresent = false,
))
}
override fun newBuilder(): ImageLoader.Builder {
return ImageLoader.Builder(context)
}
override fun shutdown() {}
}
/** Only use for tests/previews */
@Composable
@CheckResult
fun createNewTestImageLoader(context: Context): ImageLoader {
return TestImageLoader(context)
}
| apache-2.0 | 01044f8813c8a67e778d1a15f85da454 | 29.942857 | 95 | 0.717144 | 4.907855 | false | true | false | false |
smrehan6/WeatherForecast | app/src/main/java/me/smr/weatherforecast/fragments/HomeFragment.kt | 1 | 3076 | package me.smr.weatherforecast.fragments
import android.app.SearchManager
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import dagger.hilt.android.AndroidEntryPoint
import me.smr.weatherforecast.R
import me.smr.weatherforecast.adapters.SearchClickListener
import me.smr.weatherforecast.adapters.SearchResultAdapter
import me.smr.weatherforecast.adapters.WeatherAdapter
import me.smr.weatherforecast.databinding.HomeFragmentBinding
import me.smr.weatherforecast.models.CitySearchResult
import me.smr.weatherforecast.viewmodels.HomeViewModel
@AndroidEntryPoint
class HomeFragment : Fragment() {
private lateinit var binding: HomeFragmentBinding
private lateinit var searchMenu:MenuItem
private val viewModel: HomeViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = HomeFragmentBinding.inflate(inflater, container, false)
binding.lifecycleOwner = this
binding.viewmodel = viewModel
val searchAdapter = SearchResultAdapter(object : SearchClickListener {
override fun onSearchItemClicked(item: CitySearchResult) {
viewModel.onSearchResultClicked(item)
searchMenu.collapseActionView()
}
})
binding.lvSearch.adapter = searchAdapter
val weatherAdapter = WeatherAdapter()
binding.lvCities.adapter = weatherAdapter
viewModel.searchResult.observe(viewLifecycleOwner) {
searchAdapter.submitList(it)
}
viewModel.weatherData.observe(viewLifecycleOwner) {
weatherAdapter.submitList(it)
}
requireActivity().setTitle(R.string.app_name)
setHasOptionsMenu(true)
return binding.root
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.home, menu)
// Associate searchable configuration with the SearchView
val searchManager =
requireActivity().getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchMenu = menu.findItem(R.id.search)
val searchView = searchMenu.actionView as SearchView
searchView.setSearchableInfo(searchManager.getSearchableInfo(requireActivity().componentName))
val listener = object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(p0: MenuItem?): Boolean {
viewModel.showSearch()
return true
}
override fun onMenuItemActionCollapse(p0: MenuItem?): Boolean {
viewModel.hideSearch()
return true
}
}
searchMenu.setOnActionExpandListener(listener)
}
companion object {
const val TAG = "HomeFragment"
}
} | apache-2.0 | 648790ee5b1c76ea7f0afdc1778310c4 | 31.734043 | 102 | 0.709363 | 5.602914 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/ui/adapters/CharacterDetailsActivityAdapter.kt | 1 | 1916 | package tech.salroid.filmy.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import tech.salroid.filmy.data.local.model.CastMovie
import tech.salroid.filmy.databinding.CharCustomRowBinding
class CharacterDetailsActivityAdapter(
private val moviesList: List<CastMovie>,
private val fixedSize: Boolean,
private val clickListener: ((CastMovie, Int) -> Unit)? = null
) : RecyclerView.Adapter<CharacterDetailsActivityAdapter.CharacterDetailsViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterDetailsViewHolder {
val binding =
CharCustomRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return CharacterDetailsViewHolder(binding)
}
override fun onBindViewHolder(holder: CharacterDetailsViewHolder, position: Int) {
holder.bindData(moviesList[position])
}
override fun getItemCount(): Int =
if (fixedSize) if (moviesList.size >= 5) 5 else moviesList.size else moviesList.size
inner class CharacterDetailsViewHolder(private val binding: CharCustomRowBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bindData(movie: CastMovie) {
val movieName = movie.originalTitle
val moviePoster = movie.posterPath
val rolePlayed = movie.character
binding.movieName.text = movieName
binding.movieRolePlayed.text = rolePlayed
Glide.with(binding.root.context)
.load("http://image.tmdb.org/t/p/w342${moviePoster}")
.fitCenter()
.into(binding.moviePoster)
}
init {
binding.root.setOnClickListener {
clickListener?.invoke(moviesList[adapterPosition], adapterPosition)
}
}
}
} | apache-2.0 | 4a31d09d9b0d7913b879df0e59459999 | 35.865385 | 99 | 0.696242 | 4.950904 | false | false | false | false |
Dmedina88/SSB | generator-ssb/generators/templates/template-normal/app/src/main/kotlin/com/grayherring/temp/base/ui/BaseActivity.kt | 1 | 2838 | package <%= appPackage %>.base.ui
import android.arch.lifecycle.LifecycleActivity
import android.arch.lifecycle.ViewModelProviders
import android.support.v4.app.Fragment
import android.view.KeyEvent
import butterknife.ButterKnife
import butterknife.Unbinder
import <%= appPackage %>.base.util.plusAssign
import <%= appPackage %>.viewmodel.ViewModelFactory
import com.grayherring.kotlintest.util.KeyUpListener
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
abstract class BaseActivity<V : BaseState, T : BaseViewModel<V>> : LifecycleActivity(), HasSupportFragmentInjector {
override fun supportFragmentInjector() = dispatchingAndroidInjector
//todo hmmm will always need fragments need to think about it and look more at dagger android
@Inject
protected lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Fragment>
@Inject
protected lateinit var viewModelFactory: ViewModelFactory
@Inject lateinit internal var keyUpListener: KeyUpListener
protected lateinit var viewModel: T
protected val disposable = CompositeDisposable()
lateinit private var unbinder : Unbinder
//not sure if this would be better then the function but the issue is u can override it as var
// abstract val viewLayout: Int
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
setContentView(viewLayout())
unbinder = ButterKnife.bind(this)
initViewModel()
}
//todo this code maybe the same in the fragment and activity maybe abstract it?
/**
* setup for view model and stream
*/
fun initViewModel() {
viewModel = ViewModelProviders.of(this, viewModelFactory).get(viewModelClass())
viewModel.init()
initView(viewModel.lastState)
disposable += viewModel.observeState { bindView(it) }
setUpEventStream()
}
/**
* if initializing view if you have to
*/
open fun initView(state: V) {}
/**
* class needed to get the viewModel
*/
abstract internal fun viewModelClass(): Class<T>
/**
* layout id for view
*/
abstract internal fun viewLayout(): Int
/**
* hook for handling view updates
*/
abstract internal fun bindView(state: V)
/**
* put code that creates events for into the even stream here remember to add to [disposable]
*/
abstract fun setUpEventStream()
override fun onDestroy() {
unbinder.unbind()
disposable.clear()
super.onDestroy()
}
//maybe move this to an other sort of base base class extending this
/**
* used to start debug draw
*/
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
keyUpListener.onKeyUp(this, keyCode, event)
return super.onKeyUp(keyCode, event)
}
}
| apache-2.0 | 47d93132c021871226002dca69eeaaca | 29.516129 | 116 | 0.748062 | 4.876289 | false | false | false | false |
AndroidX/androidx | compose/ui/ui/benchmark/src/androidTest/java/androidx/compose/ui/benchmark/ModifiersBenchmark.kt | 3 | 11695 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("DEPRECATION_ERROR")
package androidx.compose.ui.benchmark
import androidx.compose.foundation.Indication
import androidx.compose.foundation.IndicationInstance
import androidx.compose.foundation.MutatePriority
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.DragScope
import androidx.compose.foundation.gestures.DraggableState
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.ScrollableState
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.hoverable
import androidx.compose.foundation.indication
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.selection.selectable
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusTarget
import androidx.compose.ui.focus.onFocusEvent
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.ContentDrawScope
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.dp
import androidx.test.filters.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
class ModifiersBenchmark(
val name: String,
val count: Int,
val modifierFn: (Boolean) -> Modifier
) {
companion object {
/**
* INSTRUCTIONS FOR ADDING A MODIFIER TO THIS LIST
* ===============================================
*
* To add a modifier, add a `*modifier(...)` line which includes:
* (1) the name of the modifier
* (2) a lambda which accepts a boolean value and returns the modifier. You should use
* the passed in boolean value to toggle between two different sets of parameters
* to the modifier chain. If the modifier takes no parameters, just ignore the
* boolean.
*
* Many modifiers require parameters that are objects that need to be allocated. If this is
* an object which the developer is expected to remember or hold on to somewhere in their
* composition, you should allocate one below on this companion object and then just
* reference it in the modifier lambda so that allocating these isn't included in the
* "recomposition" time.
*/
@JvmStatic
@Parameterized.Parameters(name = "{0}_{1}x")
fun data(): Collection<Array<Any>> = listOf(
*modifier("Modifier") { Modifier },
*modifier("emptyElement", true) { Modifier.emptyElement() },
*modifier("clickable", true) { Modifier.clickable { capture(it) } },
*modifier("semantics", true) { Modifier.semantics { capture(it) } },
*modifier("pointerInput") { Modifier.pointerInput(it) { capture(it) } },
*modifier("focusable") { Modifier.focusable() },
*modifier("drawWithCache") {
Modifier.drawWithCache {
val rectSize = if (it) size / 2f else size
onDrawBehind {
drawRect(Color.Black, size = rectSize)
}
}
},
*modifier("testTag") { Modifier.testTag("$it") },
*modifier("selectableGroup") { Modifier.selectableGroup() },
*modifier("indication") {
Modifier.indication(interactionSource, if (it) indication else null)
},
*modifier("draggable") {
Modifier.draggable(
draggableState,
if (it) Orientation.Vertical else Orientation.Horizontal
)
},
*modifier("hoverable") {
Modifier.hoverable(interactionSource)
},
*modifier("scrollable") {
Modifier.scrollable(
scrollableState,
if (it) Orientation.Vertical else Orientation.Horizontal
)
},
*modifier("toggleable") { Modifier.toggleable(it) { capture(it) } },
*modifier("onFocusEvent") { Modifier.onFocusEvent { capture(it) } },
*modifier("selectable") { Modifier.selectable(it) { capture(it) } },
*modifier("focusTarget", true) { Modifier.focusTarget() },
*modifier("focusRequester") { Modifier.focusRequester(focusRequester) },
*modifier("border") {
Modifier.border(
if (it) 4.dp else 2.dp,
if (it) Color.Black else Color.Blue,
CircleShape
)
},
)
private val focusRequester = FocusRequester()
private val interactionSource = MutableInteractionSource()
private val indication = object : Indication {
@Composable
override fun rememberUpdatedInstance(
interactionSource: InteractionSource
): IndicationInstance {
return object : IndicationInstance {
override fun ContentDrawScope.drawIndication() {
drawContent()
}
}
}
}
private val draggableState = object : DraggableState {
override suspend fun drag(
dragPriority: MutatePriority,
block: suspend DragScope.() -> Unit
) {}
override fun dispatchRawDelta(delta: Float) {}
}
private val scrollableState = ScrollableState { it }
fun modifier(
name: String,
allCounts: Boolean = false,
modifierFn: (Boolean) -> Modifier
): Array<Array<Any>> {
return if (allCounts) {
arrayOf(
arrayOf(name, 1, modifierFn),
arrayOf(name, 10, modifierFn),
arrayOf(name, 100, modifierFn)
)
} else {
arrayOf(arrayOf(name, 10, modifierFn))
}
}
}
@get:Rule
val rule = ComposeBenchmarkRule()
/**
* DEFINITIONS
* ===========
*
* "base" - means that we are only including cost of composition and cost of setting the
* modifier on the layoutnode itself, but excluding Layout/Draw.
*
* "full" - means that we includ all costs from "base", but also including Layout/Draw.
*
* "hoisted" - means that the modifier chain's creation is not included in the benchmark.
* The hoisted measurement is representative of a developer "hoisting" the
* allocation of the benchmark up into a higher scope than the composable it is
* used in so that recomposition doesn't create a new one. The non-hoisted
* variants are more representative of developers making modifier chains inline
* in the composable body (most common).
*
* "reuse" - means that we change up the parameters of the modifier factory, so we are
* effectively measuring how well we are able to "reuse" the state from the
* "same" modifier, but with different parameters
*/
// base cost, including calling the modifier factory
@Test
fun base() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = false,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost. without calling the modifier factory
@Test
fun baseHoisted() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = true,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost. with different parameters (potential for reuse). includes calling the modifier factory.
@Test
fun baseReuse() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = true,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost. with different parameters (potential for reuse). without calling the modifier factory
@Test
fun baseReuseHoisted() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = true,
includeComposition = true,
includeLayout = false,
includeDraw = false,
modifierFn = modifierFn,
)
// base cost + layout/draw, including calling the modifier factory
@Test
fun full() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = false,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
// base cost + layout/draw. without calling the modifier factory
@Test
fun fullHoisted() = rule.measureModifier(
count = count,
reuse = false,
hoistCreation = true,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
// base cost + layout/draw. with different parameters (potential for reuse). includes calling the modifier factory.
@Test
fun fullReuse() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = false,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
// base cost + layout/draw. with different parameters (potential for reuse). without calling the modifier factory
@Test
fun fullReuseHoisted() = rule.measureModifier(
count = count,
reuse = true,
hoistCreation = true,
includeComposition = true,
includeLayout = true,
includeDraw = true,
modifierFn = modifierFn,
)
}
fun Modifier.emptyElement(): Modifier = this then object : Modifier.Element {}
@Suppress("UNUSED_PARAMETER")
fun capture(value: Any?) {} | apache-2.0 | cf728bca5afd58265ab512b607b67383 | 37.857143 | 119 | 0.625139 | 5.131637 | false | true | false | false |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/aclog/api/tweets/TweetsAPI.kt | 1 | 685 | package com.twitter.meil_mitu.twitter4hk.aclog.api.tweets
import com.twitter.meil_mitu.twitter4hk.AbsAPI
import com.twitter.meil_mitu.twitter4hk.AbsOauth
import com.twitter.meil_mitu.twitter4hk.aclog.converter.api.ITweetsConverter
class TweetsAPI<TAclogStatus>(
oauth: AbsOauth,
protected val json: ITweetsConverter<TAclogStatus>) : AbsAPI(oauth) {
fun show(id: Long) = Show(oauth, json, id)
fun lookup(ids: LongArray) = Lookup(oauth, json, ids)
fun userBest() = UserBest(oauth, json)
fun userTimeline() = UserTimeline(oauth, json)
fun userFavorites() = UserFavorites(oauth, json)
fun userFavoritedBy() = UserFavoritedBy(oauth, json)
}
| mit | 69a955621b12c374a44fe8db591b7f2e | 28.782609 | 77 | 0.734307 | 3.477157 | false | false | false | false |
google/dokka | core/src/main/kotlin/Formats/JavaLayoutHtml/JavaLayoutHtmlPackageListService.kt | 2 | 6485 | package org.jetbrains.dokka.Formats
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiParameter
import org.jetbrains.dokka.*
import org.jetbrains.dokka.ExternalDocumentationLinkResolver.Companion.DOKKA_PARAM_PREFIX
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.EnumEntrySyntheticClassDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaPropertyDescriptor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.descriptorUtil.isCompanionObject
import org.jetbrains.kotlin.types.KotlinType
class JavaLayoutHtmlPackageListService: PackageListService {
private fun StringBuilder.appendParam(name: String, value: String) {
append(DOKKA_PARAM_PREFIX)
append(name)
append(":")
appendln(value)
}
override fun formatPackageList(module: DocumentationModule): String {
val packages = module.members(NodeKind.Package).map { it.name }
return buildString {
appendParam("format", "java-layout-html")
appendParam("mode", "kotlin")
for (p in packages) {
appendln(p)
}
}
}
}
class JavaLayoutHtmlInboundLinkResolutionService(private val paramMap: Map<String, List<String>>,
private val resolutionFacade: DokkaResolutionFacade) : InboundExternalLinkResolutionService {
constructor(asJava: Boolean, resolutionFacade: DokkaResolutionFacade) :
this(mapOf("mode" to listOf(if (asJava) "java" else "kotlin")), resolutionFacade)
private val isJavaMode = paramMap["mode"]!!.single() == "java"
private fun getContainerPath(symbol: DeclarationDescriptor): String? {
return when (symbol) {
is PackageFragmentDescriptor -> symbol.fqName.asString().replace('.', '/') + "/"
is ClassifierDescriptor -> getContainerPath(symbol.findPackage()) + symbol.nameWithOuter() + ".html"
else -> null
}
}
private fun DeclarationDescriptor.findPackage(): PackageFragmentDescriptor =
generateSequence(this) { it.containingDeclaration }.filterIsInstance<PackageFragmentDescriptor>().first()
private fun ClassifierDescriptor.nameWithOuter(): String =
generateSequence(this) { it.containingDeclaration as? ClassifierDescriptor }
.toList().asReversed().joinToString(".") { it.name.asString() }
private fun getJavaPagePath(symbol: DeclarationDescriptor): String? {
val sourcePsi = symbol.sourcePsi() ?: return null
val source = (if (sourcePsi is KtDeclaration) {
sourcePsi.toLightElements().firstOrNull()
} else {
sourcePsi
}) as? PsiMember ?: return null
val desc = source.getJavaMemberDescriptor(resolutionFacade) ?: return null
return getPagePath(desc)
}
private fun getPagePath(symbol: DeclarationDescriptor): String? {
return when (symbol) {
is PackageFragmentDescriptor -> getContainerPath(symbol) + "package-summary.html"
is EnumEntrySyntheticClassDescriptor -> getContainerPath(symbol.containingDeclaration) + "#" + symbol.signatureForAnchorUrlEncoded()
is ClassifierDescriptor -> getContainerPath(symbol) + "#"
is FunctionDescriptor, is PropertyDescriptor -> getContainerPath(symbol.containingDeclaration!!) + "#" + symbol.signatureForAnchorUrlEncoded()
else -> null
}
}
private fun DeclarationDescriptor.signatureForAnchor(): String? {
fun ReceiverParameterDescriptor.extractReceiverName(): String {
var receiverClass: DeclarationDescriptor = type.constructor.declarationDescriptor!!
if (receiverClass.isCompanionObject()) {
receiverClass = receiverClass.containingDeclaration!!
} else if (receiverClass is TypeParameterDescriptor) {
val upperBoundClass = receiverClass.upperBounds.singleOrNull()?.constructor?.declarationDescriptor
if (upperBoundClass != null) {
receiverClass = upperBoundClass
}
}
return receiverClass.name.asString()
}
fun KotlinType.qualifiedNameForSignature(): String {
val desc = constructor.declarationDescriptor
return desc?.fqNameUnsafe?.asString() ?: "<ERROR TYPE NAME>"
}
fun StringBuilder.appendReceiverAndCompanion(desc: CallableDescriptor) {
if (desc.containingDeclaration.isCompanionObject()) {
append("Companion.")
}
desc.extensionReceiverParameter?.let {
append("(")
append(it.extractReceiverName())
append(").")
}
}
return when (this) {
is EnumEntrySyntheticClassDescriptor -> buildString {
append("ENUM_VALUE:")
append(name.asString())
}
is JavaMethodDescriptor -> buildString {
append(name.asString())
valueParameters.joinTo(this, prefix = "(", postfix = ")") {
val param = it.sourcePsi() as PsiParameter
param.type.canonicalText
}
}
is JavaPropertyDescriptor -> buildString {
append(name.asString())
}
is FunctionDescriptor -> buildString {
appendReceiverAndCompanion(this@signatureForAnchor)
append(name.asString())
valueParameters.joinTo(this, prefix = "(", postfix = ")") {
it.type.qualifiedNameForSignature()
}
}
is PropertyDescriptor -> buildString {
appendReceiverAndCompanion(this@signatureForAnchor)
append(name.asString())
append(":")
append(returnType?.qualifiedNameForSignature())
}
else -> null
}
}
private fun DeclarationDescriptor.signatureForAnchorUrlEncoded(): String? = signatureForAnchor()?.anchorEncoded()
override fun getPath(symbol: DeclarationDescriptor) = if (isJavaMode) getJavaPagePath(symbol) else getPagePath(symbol)
}
| apache-2.0 | c96ca1da34cb6bcd7a787eda1dcc998b | 41.11039 | 154 | 0.64549 | 5.816143 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/skills/SkillsFragment.kt | 1 | 7531 | package com.habitrpg.android.habitica.ui.fragments.skills
import android.app.Activity
import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentSkillsBinding
import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.Skill
import com.habitrpg.android.habitica.models.responses.SkillResponse
import com.habitrpg.android.habitica.models.user.User
import com.habitrpg.android.habitica.ui.activities.SkillMemberActivity
import com.habitrpg.android.habitica.ui.activities.SkillTasksActivity
import com.habitrpg.android.habitica.ui.adapter.SkillsRecyclerViewAdapter
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.SafeDefaultItemAnimator
import com.habitrpg.android.habitica.ui.viewmodels.MainUserViewModel
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar
import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar.Companion.showSnackbar
import io.reactivex.rxjava3.core.Flowable
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject
class SkillsFragment : BaseMainFragment<FragmentSkillsBinding>() {
internal var adapter: SkillsRecyclerViewAdapter? = null
private var selectedSkill: Skill? = null
override var binding: FragmentSkillsBinding? = null
@Inject
lateinit var userViewModel: MainUserViewModel
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentSkillsBinding {
return FragmentSkillsBinding.inflate(inflater, container, false)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
adapter = SkillsRecyclerViewAdapter()
adapter?.useSkillEvents?.subscribeWithErrorHandler { onSkillSelected(it) }?.let { compositeSubscription.add(it) }
this.tutorialStepIdentifier = "skills"
this.tutorialText = getString(R.string.tutorial_skills)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
userViewModel.user.observe(viewLifecycleOwner) { user ->
user?.let { checkUserLoadSkills(it) }
}
binding?.recyclerView?.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity)
binding?.recyclerView?.adapter = adapter
binding?.recyclerView?.itemAnimator = SafeDefaultItemAnimator()
}
private fun checkUserLoadSkills(user: User) {
if (adapter == null) {
return
}
adapter?.mana = user.stats?.mp ?: 0.0
adapter?.level = user.stats?.lvl ?: 0
adapter?.specialItems = user.items?.special
Flowable.combineLatest(
userRepository.getSkills(user),
userRepository.getSpecialItems(user),
{ skills, items ->
val allEntries = mutableListOf<Skill>()
for (skill in skills) {
allEntries.add(skill)
}
for (item in items) {
allEntries.add(item)
}
return@combineLatest allEntries
}
).subscribe({ skills -> adapter?.setSkillList(skills) }, RxErrorHandler.handleEmptyError())
}
private fun onSkillSelected(skill: Skill) {
when {
"special" == skill.habitClass -> {
selectedSkill = skill
val intent = Intent(activity, SkillMemberActivity::class.java)
memberSelectionResult.launch(intent)
}
skill.target == "task" -> {
selectedSkill = skill
val intent = Intent(activity, SkillTasksActivity::class.java)
taskSelectionResult.launch(intent)
}
else -> useSkill(skill)
}
}
private fun displaySkillResult(usedSkill: Skill?, response: SkillResponse) {
if (!isAdded) return
adapter?.mana = response.user?.stats?.mp ?: 0.0
val activity = activity ?: return
if ("special" == usedSkill?.habitClass) {
showSnackbar(activity.snackbarContainer, context?.getString(R.string.used_skill_without_mana, usedSkill.text), HabiticaSnackbar.SnackbarDisplayType.BLUE)
} else {
context?.let {
showSnackbar(
activity.snackbarContainer, null,
context?.getString(R.string.used_skill_without_mana, usedSkill?.text),
BitmapDrawable(resources, HabiticaIconsHelper.imageOfMagic()),
ContextCompat.getColor(it, R.color.blue_10), "-" + usedSkill?.mana,
HabiticaSnackbar.SnackbarDisplayType.BLUE
)
}
}
if (response.damage > 0) {
lifecycleScope.launch {
delay(2000L)
if (!isAdded) return@launch
showSnackbar(
activity.snackbarContainer, null,
context?.getString(R.string.caused_damage),
BitmapDrawable(resources, HabiticaIconsHelper.imageOfDamage()),
ContextCompat.getColor(activity, R.color.green_10), "+%.01f".format(response.damage),
HabiticaSnackbar.SnackbarDisplayType.SUCCESS
)
}
}
compositeSubscription.add(userRepository.retrieveUser(false).subscribe({ }, RxErrorHandler.handleEmptyError()))
}
private val taskSelectionResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, it.data?.getStringExtra("taskID"))
}
}
private val memberSelectionResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
useSkill(selectedSkill, it.data?.getStringExtra("member_id"))
}
}
private fun useSkill(skill: Skill?, taskId: String? = null) {
if (skill == null) {
return
}
val observable: Flowable<SkillResponse> = if (taskId != null) {
userRepository.useSkill(skill.key, skill.target, taskId)
} else {
userRepository.useSkill(skill.key, skill.target)
}
compositeSubscription.add(
observable.subscribe(
{ skillResponse -> this.displaySkillResult(skill, skillResponse) },
RxErrorHandler.handleEmptyError()
)
)
}
}
| gpl-3.0 | 8bbcea7a48a4df6bd758cefe3a31268f | 42.040936 | 165 | 0.657416 | 5.158219 | false | false | false | false |
androidx/androidx | glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/action/ActionTrampoline.kt | 3 | 4469 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget.action
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.RemoteViews
import androidx.annotation.DoNotInline
import androidx.annotation.RequiresApi
import androidx.glance.appwidget.TranslationContext
internal enum class ActionTrampolineType {
ACTIVITY, BROADCAST, SERVICE, FOREGROUND_SERVICE, CALLBACK
}
private const val ActionTrampolineScheme = "glance-action"
/**
* Wraps the "action intent" into an activity trampoline intent, where it will be invoked based on
* the type, with modifying its content.
*
* @see launchTrampolineAction
*/
internal fun Intent.applyTrampolineIntent(
translationContext: TranslationContext,
viewId: Int,
type: ActionTrampolineType
): Intent {
val target = if (type == ActionTrampolineType.ACTIVITY) {
ActionTrampolineActivity::class.java
} else {
InvisibleActionTrampolineActivity::class.java
}
return Intent(translationContext.context, target).also { intent ->
intent.data = createUniqueUri(translationContext, viewId, type)
intent.putExtra(ActionTypeKey, type.name)
intent.putExtra(ActionIntentKey, this)
}
}
internal fun createUniqueUri(
translationContext: TranslationContext,
viewId: Int,
type: ActionTrampolineType,
extraData: String = "",
): Uri = Uri.Builder().apply {
scheme(ActionTrampolineScheme)
path(type.name)
appendQueryParameter("appWidgetId", translationContext.appWidgetId.toString())
appendQueryParameter("viewId", viewId.toString())
appendQueryParameter("viewSize", translationContext.layoutSize.toString())
appendQueryParameter("extraData", extraData)
if (translationContext.isLazyCollectionDescendant) {
appendQueryParameter(
"lazyCollection",
translationContext.layoutCollectionViewId.toString()
)
appendQueryParameter(
"lazeViewItem",
translationContext.layoutCollectionItemId.toString()
)
}
}.build()
/**
* Unwraps and launches the action intent based on its type.
*
* @see applyTrampolineIntent
*/
@Suppress("DEPRECATION")
internal fun Activity.launchTrampolineAction(intent: Intent) {
val actionIntent = requireNotNull(intent.getParcelableExtra<Intent>(ActionIntentKey)) {
"List adapter activity trampoline invoked without specifying target intent."
}
if (intent.hasExtra(RemoteViews.EXTRA_CHECKED)) {
actionIntent.putExtra(
RemoteViews.EXTRA_CHECKED,
intent.getBooleanExtra(RemoteViews.EXTRA_CHECKED, false)
)
}
val type = requireNotNull(intent.getStringExtra(ActionTypeKey)) {
"List adapter activity trampoline invoked without trampoline type"
}
when (ActionTrampolineType.valueOf(type)) {
ActionTrampolineType.ACTIVITY -> startActivity(actionIntent)
ActionTrampolineType.BROADCAST, ActionTrampolineType.CALLBACK -> sendBroadcast(actionIntent)
ActionTrampolineType.SERVICE -> startService(actionIntent)
ActionTrampolineType.FOREGROUND_SERVICE -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ListAdapterTrampolineApi26Impl.startForegroundService(
context = this,
intent = actionIntent
)
} else {
startService(actionIntent)
}
}
}
finish()
}
private const val ActionTypeKey = "ACTION_TYPE"
private const val ActionIntentKey = "ACTION_INTENT"
@RequiresApi(Build.VERSION_CODES.O)
private object ListAdapterTrampolineApi26Impl {
@DoNotInline
fun startForegroundService(context: Context, intent: Intent) {
context.startForegroundService(intent)
}
}
| apache-2.0 | fff217870afc74dfdf4d1014d002a84d | 33.914063 | 100 | 0.717386 | 4.943584 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/util/lmdb/templates/lmdb.kt | 1 | 55764 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.util.lmdb.templates
import org.lwjgl.generator.*
import org.lwjgl.util.lmdb.*
val lmdb = "LMDB".nativeClass(LMDB_PACKAGE, prefix = "MDB", prefixMethod = "mdb_", library = "lwjgl_lmdb") {
nativeDirective(
"""#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4710 4711))
#endif""", beforeIncludes = true)
nativeDirective(
"""DISABLE_WARNINGS()
#ifdef LWJGL_WINDOWS
__pragma(warning(disable : 4172 4701 4706))
#endif
#define MDB_DEVEL 2
#include "lmdb.h"
ENABLE_WARNINGS()""")
documentation =
"""
Contains bindings to <a href="http://symas.com/mdb/">LMDB</a>, the Symas Lightning Memory-Mapped Database.
<h3>Getting Started</h3>
LMDB is compact, fast, powerful, and robust and implements a simplified variant of the BerkeleyDB (BDB) API.
Everything starts with an environment, created by #env_create(). Once created, this environment must also be opened with #env_open(). #env_open() gets
passed a name which is interpreted as a directory path. Note that this directory must exist already, it is not created for you. Within that directory,
a lock file and a storage file will be generated. If you don't want to use a directory, you can pass the #NOSUBDIR option, in which case the path you
provided is used directly as the data file, and another file with a "-lock" suffix added will be used for the lock file.
Once the environment is open, a transaction can be created within it using #txn_begin(). Transactions may be read-write or read-only, and read-write
transactions may be nested. A transaction must only be used by one thread at a time. Transactions are always required, even for read-only access. The
transaction provides a consistent view of the data.
Once a transaction has been created, a database can be opened within it using #dbi_open(). If only one database will ever be used in the environment, a
$NULL can be passed as the database name. For named databases, the #CREATE flag must be used to create the database if it doesn't already exist. Also,
#env_set_maxdbs() must be called after #env_create() and before #env_open() to set the maximum number of named databases you want to support.
Note: a single transaction can open multiple databases. Generally databases should only be opened once, by the first transaction in the process. After
the first transaction completes, the database handles can freely be used by all subsequent transactions.
Within a transaction, #get() and #put() can store single key/value pairs if that is all you need to do (but see {@code Cursors} below if you want to do
more).
A key/value pair is expressed as two ##MDBVal structures. This struct has two fields, {@code mv_size} and {@code mv_data}. The data is a {@code void}
pointer to an array of {@code mv_size} bytes.
Because LMDB is very efficient (and usually zero-copy), the data returned in an ##MDBVal structure may be memory-mapped straight from disk. In other
words <b>look but do not touch</b> (or {@code free()} for that matter). Once a transaction is closed, the values can no longer be used, so make a copy
if you need to keep them after that.
<h3>Cursors</h3>
To do more powerful things, we must use a cursor.
Within the transaction, a cursor can be created with #cursor_open(). With this cursor we can store/retrieve/delete (multiple) values using
#cursor_get(), #cursor_put(), and #cursor_del().
#cursor_get() positions itself depending on the cursor operation requested, and for some operations, on the supplied key. For example, to list all
key/value pairs in a database, use operation #FIRST for the first call to #cursor_get(), and #NEXT on subsequent calls, until the end is hit.
To retrieve all keys starting from a specified key value, use #SET.
When using #cursor_put(), either the function will position the cursor for you based on the {@code key}, or you can use operation #CURRENT to use the
current position of the cursor. Note that {@code key} must then match the current position's key.
<h4>Summarizing the Opening</h4>
So we have a cursor in a transaction which opened a database in an environment which is opened from a filesystem after it was separately created.
Or, we create an environment, open it from a filesystem, create a transaction within it, open a database within that transaction, and create a cursor
within all of the above.
<h3>Threads and Processes</h3>
LMDB uses POSIX locks on files, and these locks have issues if one process opens a file multiple times. Because of this, do not #env_open() a file
multiple times from a single process. Instead, share the LMDB environment that has opened the file across all threads. Otherwise, if a single process
opens the same environment multiple times, closing it once will remove all the locks held on it, and the other instances will be vulnerable to
corruption from other processes.
Also note that a transaction is tied to one thread by default using Thread Local Storage. If you want to pass read-only transactions across threads,
you can use the #NOTLS option on the environment.
<h3><Transactions, Rollbacks, etc.</h3>
To actually get anything done, a transaction must be committed using #txn_commit(). Alternatively, all of a transaction's operations can be discarded
using #txn_abort(). In a read-only transaction, any cursors will <b>not</b> automatically be freed. In a read-write transaction, all cursors will be
freed and must not be used again.
For read-only transactions, obviously there is nothing to commit to storage. The transaction still must eventually be aborted to close any database
handle(s) opened in it, or committed to keep the database handles around for reuse in new transactions.
In addition, as long as a transaction is open, a consistent view of the database is kept alive, which requires storage. A read-only transaction that no
longer requires this consistent view should be terminated (committed or aborted) when the view is no longer needed (but see below for an optimization).
There can be multiple simultaneously active read-only transactions but only one that can write. Once a single read-write transaction is opened, all
further attempts to begin one will block until the first one is committed or aborted. This has no effect on read-only transactions, however, and they
may continue to be opened at any time.
<h3>Duplicate Keys</h3>
#get() and #put() respectively have no and only some support for multiple key/value pairs with identical keys. If there are multiple values for a key,
#get() will only return the first value.
When multiple values for one key are required, pass the #DUPSORT flag to #dbi_open(). In an #DUPSORT database, by default #put() will not replace the
value for a key if the key existed already. Instead it will add the new value to the key. In addition, #del() will pay attention to the value field
too, allowing for specific values of a key to be deleted.
Finally, additional cursor operations become available for traversing through and retrieving duplicate values.
<h3>Some Optimization</h3>
If you frequently begin and abort read-only transactions, as an optimization, it is possible to only reset and renew a transaction.
#txn_reset() releases any old copies of data kept around for a read-only transaction. To reuse this reset transaction, call #txn_renew() on it. Any
cursors in this transaction must also be renewed using #cursor_renew().
Note that #txn_reset() is similar to #txn_abort() and will close any databases you opened within the transaction.
To permanently free a transaction, reset or not, use #txn_abort().
<h3>Cleaning Up</h3>
For read-only transactions, any cursors created within it must be closed using #cursor_close().
It is very rarely necessary to close a database handle, and in general they should just be left open.
"""
IntConstant(
"mmap at a fixed address (experimental).",
"FIXEDMAP"..0x01
)
IntConstant(
"No environment directory.",
"NOSUBDIR"..0x4000
)
IntConstant(
"Don't fsync after commit.",
"NOSYNC"..0x10000
)
IntConstant(
"Read only.",
"RDONLY"..0x20000
)
IntConstant(
"Don't fsync metapage after commit.",
"NOMETASYNC"..0x40000
)
IntConstant(
"Use writable mmap.",
"WRITEMAP"..0x80000
)
IntConstant(
"Use asynchronous msync when #WRITEMAP is used.",
"MAPASYNC"..0x100000
)
IntConstant(
"Tie reader locktable slots to {@code MDB_txn} objects instead of to threads.",
"NOTLS"..0x200000
)
IntConstant(
"Don't do any locking, caller must manage their own locks.",
"NOLOCK"..0x400000
)
IntConstant(
"Don't do readahead (no effect on Windows).",
"NORDAHEAD"..0x800000
)
IntConstant(
"Don't initialize malloc'd memory before writing to datafile.",
"NOMEMINIT"..0x1000000
)
IntConstant(
"Use reverse string keys.",
"REVERSEKEY"..0x02
)
IntConstant(
"Use sorted duplicates.",
"DUPSORT"..0x04
)
IntConstant(
"Numeric keys in native byte order: either {@code unsigned int} or {@code size_t}. The keys must all be of the same size.",
"INTEGERKEY"..0x08
)
IntConstant(
"With #DUPSORT, sorted dup items have fixed size.",
"DUPFIXED"..0x10
)
IntConstant(
"With #DUPSORT, dups are #INTEGERKEY -style integers.",
"INTEGERDUP"..0x20
)
IntConstant(
"With #DUPSORT, use reverse string dups.",
"REVERSEDUP"..0x40
)
IntConstant(
"Create DB if not already existing.",
"CREATE"..0x40000
)
IntConstant(
"Don't write if the key already exists.",
"NOOVERWRITE"..0x10
)
IntConstant(
"Remove all duplicate data items.",
"NODUPDATA"..0x20
)
IntConstant(
"Overwrite the current key/data pair.",
"CURRENT"..0x40
)
IntConstant(
"Just reserve space for data, don't copy it. Return a pointer to the reserved space.",
"RESERVE"..0x10000
)
IntConstant(
"Data is being appended, don't split full pages.",
"APPEND"..0x20000
)
IntConstant(
"Duplicate data is being appended, don't split full pages.",
"APPENDDUP"..0x40000
)
IntConstant(
"Store multiple data items in one call. Only for #DUPFIXED.",
"MULTIPLE"..0x80000
)
IntConstant(
"Omit free space from copy, and renumber all pages sequentially.",
"CP_COMPACT"..0x01
)
EnumConstant(
"MDB_cursor_op",
"FIRST".enum("Position at first key/data item."),
"FIRST_DUP".enum("Position at first data item of current key. Only for #DUPSORT."),
"GET_BOTH".enum("Position at key/data pair. Only for #DUPSORT."),
"GET_BOTH_RANGE".enum("position at key, nearest data. Only for #DUPSORT."),
"GET_CURRENT".enum("Return key/data at current cursor position."),
"GET_MULTIPLE".enum("Return key and up to a page of duplicate data items from current cursor position. Move cursor to prepare for #NEXT_MULTIPLE. Only for #DUPFIXED."),
"LAST".enum("Position at last key/data item."),
"LAST_DUP".enum("Position at last data item of current key. Only for #DUPSORT."),
"NEXT".enum("Position at next data item."),
"NEXT_DUP".enum("Position at next data item of current key. Only for #DUPSORT."),
"NEXT_MULTIPLE".enum(
"Return key and up to a page of duplicate data items from next cursor position. Move cursor to prepare for #NEXT_MULTIPLE. Only for #DUPFIXED."
),
"NEXT_NODUP".enum("Position at first data item of next key."),
"PREV".enum("Position at previous data item."),
"PREV_DUP".enum("Position at previous data item of current key. Only for #DUPSORT."),
"PREV_NODUP".enum("Position at last data item of previous key."),
"SET".enum("Position at specified key."),
"SET_KEY".enum("Position at specified key, return key + data."),
"SET_RANGE".enum("Position at first key greater than or equal to specified key."),
"PREV_MULTIPLE".enum("Position at previous page and return key and up to a page of duplicate data items. Only for #DUPFIXED.")
)
IntConstant(
"Successful result.",
"SUCCESS".."0"
)
IntConstant(
"Key/data pair already exists.",
"KEYEXIST".."-30799"
)
IntConstant(
"Key/data pair not found (EOF).",
"NOTFOUND".."-30798"
)
IntConstant(
"Requested page not found - this usually indicates corruption.",
"PAGE_NOTFOUND".."-30797"
)
IntConstant(
"Located page was wrong type.",
"CORRUPTED".."-30796"
)
IntConstant(
"Update of meta page failed or environment had fatal error.",
"PANIC".."-30795"
)
IntConstant(
"Environment version mismatch.",
"VERSION_MISMATCH".."-30794"
)
IntConstant(
"File is not a valid LMDB file.",
"INVALID".."-30793"
)
IntConstant(
"Environment mapsize reached.",
"MAP_FULL".."-30792"
)
IntConstant(
"Environment maxdbs reached.",
"DBS_FULL".."-30791"
)
IntConstant(
"Environment maxreaders reached.",
"READERS_FULL".."-30790"
)
IntConstant(
"Too many TLS keys in use - Windows only.",
"TLS_FULL".."-30789"
)
IntConstant(
"Txn has too many dirty pages.",
"TXN_FULL".."-30788"
)
IntConstant(
"Cursor stack too deep - internal error.",
"CURSOR_FULL".."-30787"
)
IntConstant(
"Page has not enough space - internal error.",
"PAGE_FULL".."-30786"
)
IntConstant(
"Database contents grew beyond environment mapsize.",
"MAP_RESIZED".."-30785"
)
IntConstant(
"""
The operation expects an #DUPSORT / #DUPFIXED database. Opening a named DB when the unnamed DB has #DUPSORT / #INTEGERKEY. Accessing a data record as a
database, or vice versa. The database was dropped and recreated with different flags.
""",
"INCOMPATIBLE".."-30784"
)
IntConstant(
"Invalid reuse of reader locktable slot.",
"BAD_RSLOT".."-30783"
)
IntConstant(
"Transaction must abort, has a child, or is invalid.",
"BAD_TXN".."-30782"
)
IntConstant(
"Unsupported size of key/DB name/data, or wrong #DUPFIXED size.",
"BAD_VALSIZE".."-30781"
)
IntConstant(
"The specified DBI was changed unexpectedly.",
"BAD_DBI".."-30780"
)
IntConstant(
"Unexpected problem - txn should abort.",
"PROBLEM".."-30779"
)
IntConstant(
"The last defined error code.",
"LAST_ERRCODE".."MDB_PROBLEM"
)
charASCII_p(
"version",
"Returns the LMDB library version information.",
Check(1)..nullable..int_p.OUT("major", "if non-$NULL, the library major version number is copied here"),
Check(1)..nullable..int_p.OUT("minor", "if non-$NULL, the library minor version number is copied here"),
Check(1)..nullable..int_p.OUT("patch", "if non-$NULL, the library patch version number is copied here"),
returnDoc = "the library version as a string"
)
charASCII_p(
"strerror",
"""
Returns a string describing a given error code.
This function is a superset of the ANSI C X3.159-1989 (ANSI C) strerror(3) function. If the error code is greater than or equal to 0, then the string
returned by the system function strerror(3) is returned. If the error code is less than 0, an error string corresponding to the LMDB library error is
returned.
""",
int.IN("err", "the error code"),
returnDoc = "the description of the error"
)
int(
"env_create",
"""
Creates an LMDB environment handle.
This function allocates memory for a {@code MDB_env} structure. To release the allocated memory and discard the handle, call #env_close(). Before the
handle may be used, it must be opened using #env_open(). Various other options may also need to be set before opening the handle, e.g.
#env_set_mapsize(), #env_set_maxreaders(), #env_set_maxdbs(), depending on usage requirements.
""",
Check(1)..MDB_env_pp.OUT("env", "the address where the new handle will be stored"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
val env_open = int(
"env_open",
"""
Opens an environment handle.
If this function fails, #env_close() must be called to discard the {@code MDB_env} handle.
""",
MDB_env_p.IN("env", "an environment handle returned by #env_create()"),
const..charUTF8_p.IN("path", "the directory in which the database files reside. This directory must already exist and be writable."),
unsigned_int.IN(
"flags",
"""
Special options for this environment. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here. Flags
set by #env_set_flags() are also used.
${ul(
"""#FIXEDMAP
Use a fixed address for the mmap region. This flag must be specified when creating the environment, and is stored persistently in the
environment. If successful, the memory map will always reside at the same virtual address and pointers used to reference data items in the
database will be constant across multiple invocations. This option may not always work, depending on how the operating system has allocated
memory to shared libraries and other uses.
The feature is highly experimental.
""",
"""#NOSUBDIR
By default, LMDB creates its environment in a directory whose pathname is given in {@code path}, and creates its data and lock files under that
directory. With this option, {@code path} is used as-is for the database main data file. The database lock file is the {@code path} with
"-lock" appended.
""",
"""#RDONLY
Open the environment in read-only mode. No write operations will be allowed. LMDB will still modify the lock file - except on read-only
filesystems, where LMDB does not use locks.
""",
"""#WRITEMAP
Use a writeable memory map unless #RDONLY is set. This uses fewer mallocs but loses protection from application bugs like wild pointer writes
and other bad updates into the database. This may be slightly faster for DBs that fit entirely in RAM, but is slower for DBs larger than RAM.
Incompatible with nested transactions.
Do not mix processes with and without #WRITEMAP on the same environment. This can defeat durability (#env_sync() etc).
""",
"""#NOMETASYNC
Flush system buffers to disk only once per transaction, omit the metadata flush. Defer that until the system flushes files to disk, or next
non-#RDONLY commit or #env_sync(). This optimization maintains database integrity, but a system crash may undo the last committed transaction.
I.e. it preserves the ACI (atomicity, consistency, isolation) but not D (durability) database property.
This flag may be changed at any time using #env_set_flags().
""",
"""#NOSYNC
Don't flush system buffers to disk when committing a transaction. This optimization means a system crash can corrupt the database or lose the
last transactions if buffers are not yet flushed to disk. The risk is governed by how often the system flushes dirty buffers to disk and how
often #env_sync() is called. However, if the filesystem preserves write order and the #WRITEMAP flag is not used, transactions exhibit ACI
(atomicity, consistency, isolation) properties and only lose D (durability). I.e. database integrity is maintained, but a system crash may undo
the final transactions. Note that (#NOSYNC | #WRITEMAP) leaves the system with no hint for when to write transactions to disk, unless
#env_sync() is called. (#MAPASYNC | #WRITEMAP) may be preferable.
This flag may be changed at any time using #env_set_flags().
""",
"""#MAPASYNC
When using #WRITEMAP, use asynchronous flushes to disk. As with #NOSYNC, a system crash can then corrupt the database or lose the last
transactions. Calling #env_sync() ensures on-disk database integrity until next commit.
This flag may be changed at any time using #env_set_flags().
""",
"""#NOTLS
Don't use Thread-Local Storage. Tie reader locktable slots to {@code MDB_txn} objects instead of to threads. I.e. #txn_reset() keeps the slot
reseved for the {@code MDB_txn} object. A thread may use parallel read-only transactions. A read-only transaction may span threads if the user
synchronizes its use. Applications that multiplex many user threads over individual OS threads need this option. Such an application must also
serialize the write transactions in an OS thread, since LMDB's write locking is unaware of the user threads.
""",
"""#NOLOCK
Don't do any locking. If concurrent access is anticipated, the caller must manage all concurrency itself. For proper operation the caller must
enforce single-writer semantics, and must ensure that no readers are using old transactions while a writer is active. The simplest approach is
to use an exclusive lock so that no readers may be active at all when a writer begins.
""",
"""#NORDAHEAD
Turn off readahead. Most operating systems perform readahead on read requests by default. This option turns it off if the OS supports it.
Turning it off may help random read performance when the DB is larger than RAM and system RAM is full.
The option is not implemented on Windows.
""",
"""#NOMEMINIT
Don't initialize malloc'd memory before writing to unused spaces in the data file. By default, memory for pages written to the data file is
obtained using malloc. While these pages may be reused in subsequent transactions, freshly malloc'd pages will be initialized to zeroes before
use. This avoids persisting leftover data from other code (that used the heap and subsequently freed the memory) into the data file. Note that
many other system libraries may allocate and free memory from the heap for arbitrary uses. E.g., stdio may use the heap for file I/O buffers.
This initialization step has a modest performance cost so some applications may want to disable it using this flag. This option can be a
problem for applications which handle sensitive data like passwords, and it makes memory checkers like Valgrind noisy. This flag is not needed
with #WRITEMAP, which writes directly to the mmap instead of using malloc for pages. The initialization is also skipped if #RESERVE is used;
the caller is expected to overwrite all of the memory that was reserved in that case.
This flag may be changed at any time using #env_set_flags().
"""
)}
"""
),
mdb_mode_t.IN(
"mode",
"""
The UNIX permissions to set on created files and semaphores.
This parameter is ignored on Windows.
"""
),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"#VERSION_MISMATCH - the version of the LMDB library doesn't match the version that created the database environment.",
"#INVALID - the environment file headers are corrupted.",
"{@code ENOENT} - the directory specified by the path parameter doesn't exist.",
"{@code EACCES} - the user didn't have permission to access the environment files.",
"{@code EAGAIN} - the environment was locked by another process."
)}
"""
)
int(
"env_copy",
"""
Copies an LMDB environment to the specified path.
This function may be used to make a backup of an existing environment. No lockfile is created, since it gets recreated at need.
This call can trigger significant file size growth if run in parallel with write transactions, because it employs a read-only transaction.
""",
MDB_env_p.IN("env", "an environment handle returned by #env_create(). It must have already been opened successfully."),
const..charUTF8_p.IN(
"path",
"the directory in which the copy will reside. This directory must already exist and be writable but must otherwise be empty."
),
returnDoc = "a non-zero error value on failure and 0 on success"
)
/*int(
"env_copyfd",
"",
MDB_env_p.IN("env", ""),
mdb_filehandle_t.IN("fd", "")
)*/
int(
"env_copy2",
"""
Copies an LMDB environment to the specified path, with options.
This function may be used to make a backup of an existing environment. No lockfile is created, since it gets recreated at need.
This call can trigger significant file size growth if run in parallel with write transactions, because it employs a read-only transaction.
""",
MDB_env_p.IN("env", "an environment handle returned by #env_create(). It must have already been opened successfully."),
const..charUTF8_p.IN(
"path",
"the directory in which the copy will reside. This directory must already exist and be writable but must otherwise be empty."
),
unsigned_int.IN(
"flags",
"""
special options for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"""
#CP_COMPACT - Perform compaction while copying: omit free pages and sequentially renumber all pages in output. This option consumes more CPU
and runs more slowly than the default.
"""
)}
"""
)
)
/*int(
"env_copyfd2",
"",
MDB_env_p.IN("env", ""),
mdb_filehandle_t.IN("fd", ""),
unsigned_int.IN("flags", "")
)*/
int(
"env_stat",
"Returns statistics about the LMDB environment.",
env_open["env"],
MDB_stat_p.OUT("stat", "the address of an ##MDBStat structure where the statistics will be copied"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_info",
"Returns information about the LMDB environment.",
env_open["env"],
MDB_envinfo_p.OUT("stat", "the address of an ##MDBEnvInfo structure where the information will be copied"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_sync",
"""
Flushes the data buffers to disk.
Data is always written to disk when #txn_commit() is called, but the operating system may keep it buffered. LMDB always flushes the OS buffers upon
commit as well, unless the environment was opened with #NOSYNC or in part #NOMETASYNC. This call is not valid if the environment was opened with
#RDONLY.
""",
env_open["env"],
intb.IN(
"force",
"""
if non-zero, force a synchronous flush. Otherwise if the environment has the #NOSYNC flag set the flushes will be omitted, and with #MAPASYNC they
will be asynchronous.
"""
),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EACCES} - the environment is read-only.",
"{@code EINVAL} - an invalid parameter was specified.",
"{@code EIO} - an error occurred during synchronization."
)}
"""
)
void(
"env_close",
"""
Closes the environment and releases the memory map.
Only a single thread may call this function. All transactions, databases, and cursors must already be closed before calling this function. Attempts to
use any such handles after calling this function will cause a SIGSEGV. The environment handle will be freed and must not be used again after this call.
""",
env_open["env"]
)
int(
"env_set_flags",
"""
Sets environment flags.
This may be used to set some flags in addition to those from #env_open(), or to unset these flags. If several threads change the flags at the same
time, the result is undefined.
""",
env_open["env"],
unsigned_int.IN("flags", "the flags to change, bitwise OR'ed together"),
intb.IN("onoff", "a non-zero value sets the flags, zero clears them."),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified."
)}
"""
)
int(
"env_get_flags",
"Gets environment flags.",
env_open["env"],
unsigned_int_p.OUT("flags", "the address of an integer to store the flags"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_get_path",
"Returns the path that was used in #env_open().",
env_open["env"],
const..charUTF8_pp.IN(
"path",
"address of a string pointer to contain the path. This is the actual string in the environment, not a copy. It should not be altered in any way."
),
returnDoc = "a non-zero error value on failure and 0 on success"
)
/*int(
"env_get_fd",
"",
MDB_env_p.IN("env", ""),
mdb_filehandle_t_p.OUT("fd", "")
)*/
int(
"env_set_mapsize",
"""
Sets the size of the memory map to use for this environment.
The size should be a multiple of the OS page size. The default is 10485760 bytes. The size of the memory map is also the maximum size of the database.
The value should be chosen as large as possible, to accommodate future growth of the database.
This function should be called after #env_create() and before #env_open(). It may be called at later times if no transactions are active in this
process. Note that the library does not check for this condition, the caller must ensure it explicitly.
The new size takes effect immediately for the current process but will not be persisted to any others until a write transaction has been committed by
the current process. Also, only mapsize increases are persisted into the environment.
If the mapsize is increased by another process, and data has grown beyond the range of the current mapsize, #txn_begin() will return #MAP_RESIZED. This
function may be called with a size of zero to adopt the new size.
Any attempt to set a size smaller than the space already consumed by the environment will be silently changed to the current size of the used space.
""",
env_open["env"],
mdb_size_t.IN("size", "the size in bytes"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified, or the environment has an active write transaction."
)}
"""
)
int(
"env_set_maxreaders",
"""
Sets the maximum number of threads/reader slots for the environment.
This defines the number of slots in the lock table that is used to track readers in the environment. The default is 126.
Starting a read-only transaction normally ties a lock table slot to the current thread until the environment closes or the thread exits. If #NOTLS is
in use, #txn_begin() instead ties the slot to the {@code MDB_txn} object until it or the {@code MDB_env} object is destroyed.
This function may only be called after #env_create() and before #env_open().
""",
env_open["env"],
unsigned_int.IN("readers", "the maximum number of reader lock table slots"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified, or the environment is already open."
)}
"""
)
int(
"env_get_maxreaders",
"Gets the maximum number of threads/reader slots for the environment.",
env_open["env"],
unsigned_int_p.OUT("readers", "address of an integer to store the number of readers"),
returnDoc = "a non-zero error value on failure and 0 on success"
)
int(
"env_set_maxdbs",
"""
Sets the maximum number of named databases for the environment.
This function is only needed if multiple databases will be used in the environment. Simpler applications that use the environment as a single unnamed
database can ignore this option.
This function may only be called after #env_create() and before #env_open().
Currently a moderate number of slots are cheap but a huge number gets expensive: 7-120 words per transaction, and every #dbi_open() does a linear
search of the opened slots.
""",
env_open["env"],
MDB_dbi.IN("dbs", "the maximum number of databases"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified, or the environment is already open."
)}
"""
)
int(
"env_get_maxkeysize",
"""
Gets the maximum size of keys and #DUPSORT data we can write.
Depends on the compile-time constant {@code MAXKEYSIZE}. Default 511.
""",
env_open["env"]
)
int(
"env_set_userctx",
"Set application information associated with the {@code MDB_env}.",
env_open["env"],
voidptr.IN("ctx", "an arbitrary pointer for whatever the application needs")
)
voidptr(
"env_get_userctx",
"Gets the application information associated with the {@code MDB_env}.",
env_open["env"]
)
/*int(
"env_set_assert",
"",
MDB_env_p.IN("env", ""),
MDB_assert_func_p.OUT("func", "")
)*/
int(
"txn_begin",
"""
Creates a transaction for use with the environment.
The transaction handle may be discarded using #txn_abort() or #txn_commit().
A transaction and its cursors must only be used by a single thread, and a thread may only have a single transaction at a time. If #NOTLS is in use,
this does not apply to read-only transactions.
Cursors may not span transactions.
""",
env_open["env"],
nullable..MDB_txn_p.IN(
"parent",
"""
if this parameter is non-$NULL, the new transaction will be a nested transaction, with the transaction indicated by {@code parent} as its parent.
Transactions may be nested to any level. A parent transaction and its cursors may not issue any other operations than #txn_commit() and
#txn_abort() while it has active child transactions.
"""
),
unsigned_int.IN(
"flags",
"""
special options for this transaction. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"#RDONLY - This transaction will not perform any write operations.",
"#NOSYNC - Don't flush system buffers to disk when committing this transaction.",
"#NOMETASYNC - Flush system buffers but omit metadata flush when committing this transaction."
)}
"""
),
MDB_txn_pp.OUT("txn", "address where the new {@code MDB_txn} handle will be stored"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"#PANIC - a fatal error occurred earlier and the environment must be shut down.",
"""
#MAP_RESIZED - another process wrote data beyond this {@code MDB_env}'s mapsize and this environment's map must be resized as well. See
#env_set_mapsize().
""",
"#READERS_FULL - a read-only transaction was requested and the reader lock table is full. See #env_set_maxreaders().",
"{@code ENOMEM} - out of memory."
)}
"""
)
val txn_env = MDB_env_p(
"txn_env",
"Returns the transaction's {@code MDB_env}.",
MDB_txn_p.IN("txn", "a transaction handle returned by #txn_begin().")
)
mdb_size_t(
"txn_id",
"""
Returns the transaction's ID.
This returns the identifier associated with this transaction. For a read-only transaction, this corresponds to the snapshot being read; concurrent
readers will frequently have the same transaction ID.
""",
txn_env["txn"],
returnDoc = "a transaction ID, valid if input is an active transaction"
)
int(
"txn_commit",
"""
Commits all the operations of a transaction into the database.
The transaction handle is freed. It and its cursors must not be used again after this call, except with #cursor_renew().
Earlier documentation incorrectly said all cursors would be freed. Only write-transactions free cursors.
""",
txn_env["txn"],
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"{@code EINVAL} - an invalid parameter was specified.",
"{@code ENOSPC} - no more disk space.",
"{@code EIO} - a low-level I/O error occurred while writing.",
"{@code ENOMEM} - out of memory."
)}
"""
)
void(
"txn_abort",
"""
Abandons all the operations of the transaction instead of saving them.
The transaction handle is freed. It and its cursors must not be used again after this call, except with #cursor_renew().
Earlier documentation incorrectly said all cursors would be freed. Only write-transactions free cursors.
"""",
txn_env["txn"]
)
void(
"txn_reset",
"""
Resets a read-only transaction.
Aborts the transaction like #txn_abort(), but keeps the transaction handle. #txn_renew() may reuse the handle. This saves allocation overhead if the
process will start a new read-only transaction soon, and also locking overhead if #NOTLS is in use. The reader table lock is released, but the table
slot stays tied to its thread or {@code MDB_txn}. Use #txn_abort() to discard a reset handle, and to free its lock table slot if #NOTLS is in use.
Cursors opened within the transaction must not be used again after this call, except with #cursor_renew().
Reader locks generally don't interfere with writers, but they keep old versions of database pages allocated. Thus they prevent the old pages from being
reused when writers commit new data, and so under heavy load the database size may grow much more rapidly than otherwise.
""",
txn_env["txn"]
)
int(
"txn_renew",
"""
Renews a read-only transaction.
This acquires a new reader lock for a transaction handle that had been released by #txn_reset(). It must be called before a reset transaction may be
used again.
""",
txn_env["txn"]
)
int(
"dbi_open",
"""
Opens a database in the environment.
A database handle denotes the name and parameters of a database, independently of whether such a database exists. The database handle may be discarded
by calling #dbi_close(). The old database handle is returned if the database was already open. The handle may only be closed once.
The database handle will be private to the current transaction until the transaction is successfully committed. If the transaction is aborted the
handle will be closed automatically. After a successful commit the handle will reside in the shared environment, and may be used by other transactions.
This function must not be called from multiple concurrent transactions in the same process. A transaction that uses this function must finish (either
commit or abort) before any other transaction in the process may use this function.
To use named databases (with {@code name} != $NULL), #env_set_maxdbs() must be called before opening the environment. Database names are keys in the
unnamed database, and may be read but not written.
""",
txn_env["txn"],
nullable..const..charUTF8_p.IN(
"name",
"the name of the database to open. If only a single database is needed in the environment, this value may be $NULL."
),
unsigned_int.IN(
"flags",
"""
special options for this database. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"""#REVERSEKEY
Keys are strings to be compared in reverse order, from the end of the strings to the beginning. By default, Keys are treated as strings and
compared from beginning to end.
""",
"""#DUPSORT
Duplicate keys may be used in the database. (Or, from another perspective, keys may have multiple data items, stored in sorted order.) By
default keys must be unique and may have only a single data item.
""",
"""#INTEGERKEY
Keys are binary integers in native byte order, either {@code unsigned int} or {@code mdb_size_t}, and will be sorted as such. The keys must all be
of the same size.
""",
"""#DUPFIXED
This flag may only be used in combination with #DUPSORT. This option tells the library that the data items for this database are all the same
size, which allows further optimizations in storage and retrieval. When all data items are the same size, the #GET_MULTIPLE and #NEXT_MULTIPLE
cursor operations may be used to retrieve multiple items at once.
""",
"""#INTEGERDUP
This option specifies that duplicate data items are binary integers, similar to #INTEGERKEY keys.
""",
"""#REVERSEDUP
This option specifies that duplicate data items should be compared as strings in reverse order.
""",
"""#CREATE
Create the named database if it doesn't exist. This option is not allowed in a read-only transaction or a read-only environment.
"""
)}
"""
),
MDB_dbi_p.OUT("dbi", "address where the new {@code MDB_dbi} handle will be stored"),
returnDoc =
"""
a non-zero error value on failure and 0 on success. Some possible errors are:
${ul(
"#NOTFOUND - the specified database doesn't exist in the environment and #CREATE was not specified.",
"#DBS_FULL - too many databases have been opened. See #env_set_maxdbs()."
)}
"""
)
val stat = int(
"stat",
"Retrieves statistics for a database.",
txn_env["txn"],
MDB_dbi.IN("dbi", "a database handle returned by #dbi_open()"),
MDB_stat_p.OUT("stat", "the address of an ##MDBStat structure where the statistics will be copied")
)
int(
"dbi_flags",
"Retrieve the DB flags for a database handle.",
txn_env["txn"],
stat["dbi"],
unsigned_int_p.OUT("flags", "address where the flags will be returned")
)
void(
"dbi_close",
"""
Closes a database handle. Normally unnecessary. Use with care:
This call is not mutex protected. Handles should only be closed by a single thread, and only if no other threads are going to reference the database
handle or one of its cursors any further. Do not close a handle if an existing transaction has modified its database. Doing so can cause misbehavior
from database corruption to errors like #BAD_VALSIZE (since the DB name is gone).
Closing a database handle is not necessary, but lets #dbi_open() reuse the handle value. Usually it's better to set a bigger #env_set_maxdbs(), unless
that value would be large.
""",
env_open["env"],
stat["dbi"]
)
int(
"drop",
"""
Empties or deletes+closes a database.
See #dbi_close() for restrictions about closing the DB handle.
""",
txn_env["txn"],
stat["dbi"],
intb.IN("del", "0 to empty the DB, 1 to delete it from the environment and close the DB handle")
)
int(
"set_compare",
"""
Sets a custom key comparison function for a database.
The comparison function is called whenever it is necessary to compare a key specified by the application with a key currently stored in the database.
If no comparison function is specified, and no special key flags were specified with #dbi_open(), the keys are compared lexically, with shorter keys
collating before longer keys.
This function must be called before any data access functions are used, otherwise data corruption may occur. The same comparison function must be used
by every program accessing the database, every time the database is used.
""",
txn_env["txn"],
stat["dbi"],
MDB_cmp_func.IN("cmp", "an ##MDBCmpFunc function")
)
int(
"set_dupsort",
"""
Sets a custom data comparison function for a #DUPSORT database.
This comparison function is called whenever it is necessary to compare a data item specified by the application with a data item currently stored in
the database.
This function only takes effect if the database was opened with the #DUPSORT flag.
If no comparison function is specified, and no special key flags were specified with #dbi_open(), the data items are compared lexically, with shorter
items collating before longer items.
This function must be called before any data access functions are used, otherwise data corruption may occur. The same comparison function must be used
by every program accessing the database, every time the database is used.
""",
txn_env["txn"],
stat["dbi"],
MDB_cmp_func.IN("cmp", "an ##MDBCmpFunc function")
)
int(
"set_relfunc",
"""
Sets a relocation function for a #FIXEDMAP database.
The relocation function is called whenever it is necessary to move the data of an item to a different position in the database (e.g. through tree
balancing operations, shifts as a result of adds or deletes, etc.). It is intended to allow address/position-dependent data items to be stored in a
database in an environment opened with the #FIXEDMAP option.
Currently the relocation feature is unimplemented and setting this function has no effect.
""",
txn_env["txn"],
stat["dbi"],
MDB_rel_func.IN("rel", "an ##MDBRelFunc function")
)
int(
"set_relctx",
"""
Sets a context pointer for a #FIXEDMAP database's relocation function.
See #set_relfunc() and ##MDBRelFunc for more details.
""",
txn_env["txn"],
stat["dbi"],
voidptr.IN(
"ctx",
"""
an arbitrary pointer for whatever the application needs. It will be passed to the callback function set by ##MDBRelFunc as its {@code relctx}
parameter whenever the callback is invoked.
"""
)
)
int(
"get",
"""
Gets items from a database.
This function retrieves key/data pairs from the database. The address and length of the data associated with the specified {@code key} are returned in
the structure to which {@code data} refers.
If the database supports duplicate keys (#DUPSORT) then the first data item for the key will be returned. Retrieval of other items requires the use of
#cursor_get().
The memory pointed to by the returned values is owned by the database. The caller need not dispose of the memory, and may not modify it in any way. For
values returned in a read-only transaction any modification attempts will cause a SIGSEGV.
Values returned from the database are valid only until a subsequent update operation, or the end of the transaction.
""",
txn_env["txn"],
stat["dbi"],
MDB_val_p.IN("key", "the key to search for in the database"),
MDB_val_p.OUT("data", "the data corresponding to the key")
)
int(
"put",
"""
Stores items into a database.
This function stores key/data pairs in the database. The default behavior is to enter the new key/data pair, replacing any previously existing key if
duplicates are disallowed, or adding a duplicate data item if duplicates are allowed (#DUPSORT).
""",
txn_env["txn"],
stat["dbi"],
MDB_val_p.IN("key", "the key to store in the database"),
MDB_val_p.IN("data", "the data to store"),
unsigned_int.IN(
"flags",
"""
special options for this operation. This parameter must be set to 0 or by bitwise OR'ing together one or more of the values described here.
${ul(
"""
#NODUPDATA - enter the new key/data pair only if it does not already appear in the database. This flag may only be specified if the database
was opened with #DUPSORT. The function will return #KEYEXIST if the key/data pair already appears in the database.
""",
"""
#NOOVERWRITE - enter the new key/data pair only if the key does not already appear in the database. The function will return #KEYEXIST if the
key already appears in the database, even if the database supports duplicates (#DUPSORT). The {@code data} parameter will be set to point to
the existing item.
""",
"""
#RESERVE - reserve space for data of the given size, but don't copy the given data. Instead, return a pointer to the reserved space, which the
caller can fill in later - before the next update operation or the transaction ends. This saves an extra memcpy if the data is being generated
later.
LMDB does nothing else with this memory, the caller is expected to modify all of the space requested. This flag must not be specified if the
database was opened with #DUPSORT.
""",
"""
#APPEND - append the given key/data pair to the end of the database. This option allows fast bulk loading when keys are already known to be in
the correct order. Loading unsorted keys with this flag will cause a #KEYEXIST error.
""",
"#APPENDDUP - as above, but for sorted dup data."
)}
"""
)
)
int(
"del",
"""
Deletes items from a database.
This function removes key/data pairs from the database. If the database does not support sorted duplicate data items (#DUPSORT) the data parameter is
ignored.
If the database supports sorted duplicates and the data parameter is $NULL, all of the duplicate data items for the key will be deleted. Otherwise, if
the data parameter is non-$NULL only the matching data item will be deleted.
This function will return #NOTFOUND if the specified key/data pair is not in the database.
""",
txn_env["txn"],
stat["dbi"],
MDB_val_p.IN("key", "the key to delete from the database"),
nullable..MDB_val_p.IN("data", "the data to delete")
)
int(
"cursor_open",
"""
Creates a cursor handle.
A cursor is associated with a specific transaction and database. A cursor cannot be used when its database handle is closed. Nor when its transaction
has ended, except with #cursor_renew().
It can be discarded with #cursor_close().
A cursor in a write-transaction can be closed before its transaction ends, and will otherwise be closed when its transaction ends.
A cursor in a read-only transaction must be closed explicitly, before or after its transaction ends. It can be reused with #cursor_renew() before
finally closing it.
Earlier documentation said that cursors in every transaction were closed when the transaction committed or aborted.
""",
txn_env["txn"],
stat["dbi"],
MDB_cursor_pp.OUT("cursor", "address where the new {@code MDB_cursor} handle will be stored")
)
val cursor_close = void(
"cursor_close",
"""
Closes a cursor handle.
The cursor handle will be freed and must not be used again after this call. Its transaction must still be live if it is a write-transaction.
""",
MDB_cursor_p.OUT("cursor", "a cursor handle returned by #cursor_open()")
)
int(
"cursor_renew",
"""
Renews a cursor handle.
A cursor is associated with a specific transaction and database. Cursors that are only used in read-only transactions may be re-used, to avoid
unnecessary malloc/free overhead. The cursor may be associated with a new read-only transaction, and referencing the same database handle as it was
created with. This may be done whether the previous transaction is live or dead.
""",
txn_env["txn"],
cursor_close["cursor"]
)
MDB_txn_p(
"cursor_txn",
"Returns the cursor's transaction handle.",
cursor_close["cursor"]
)
MDB_dbi(
"cursor_dbi",
"Return the cursor's database handle.",
cursor_close["cursor"]
)
int(
"cursor_get",
"""
Retrieves by cursor.
This function retrieves key/data pairs from the database. The address and length of the key are returned in the object to which {@code key} refers
(except for the case of the #SET option, in which the {@code key} object is unchanged), and the address and length of the data are returned in the
object to which {@code data} refers.
See #get() for restrictions on using the output values.
""",
cursor_close["cursor"],
MDB_val_p.IN("key", "the key for a retrieved item"),
MDB_val_p.OUT("data", "the data of a retrieved item"),
MDB_cursor_op.IN("op", "a cursor operation {@code MDB_cursor_op}")
)
int(
"cursor_put",
"""
Stores by cursor.
This function stores key/data pairs into the database. The cursor is positioned at the new item, or on failure usually near it.
Earlier documentation incorrectly said errors would leave the state of the cursor unchanged.
""",
cursor_close["cursor"],
MDB_val_p.IN("key", "the key operated on"),
MDB_val_p.IN("data", "the data operated on"),
unsigned_int.IN(
"flags",
"""
options for this operation. This parameter must be set to 0 or one of the values described here.
${ul(
"""
#CURRENT - replace the item at the current cursor position. The {@code key} parameter must still be provided, and must match it. If using
sorted duplicates (#DUPSORT) the data item must still sort into the same place. This is intended to be used when the new data is the same size
as the old. Otherwise it will simply perform a delete of the old record followed by an insert.
""",
"""
#NODUPDATA - enter the new key/data pair only if it does not already appear in the database. This flag may only be specified if the database
was opened with #DUPSORT. The function will return #KEYEXIST if the key/data pair already appears in the database.
""",
"""
#NOOVERWRITE - enter the new key/data pair only if the key does not already appear in the database. The function will return #KEYEXIST if
the key already appears in the database, even if the database supports duplicates (#DUPSORT).
""",
"""
#RESERVE - reserve space for data of the given size, but don't copy the given data. Instead, return a pointer to the reserved space, which
the caller can fill in later - before the next update operation or the transaction ends. This saves an extra memcpy if the data is being
generated later. This flag must not be specified if the database was opened with #DUPSORT.
""",
"""
#APPEND - append the given key/data pair to the end of the database. No key comparisons are performed. This option allows fast bulk loading
when keys are already known to be in the correct order. Loading unsorted keys with this flag will cause a #KEYEXIST error.
""",
"#APPENDDUP - as above, but for sorted dup data.",
"""
#MULTIPLE - store multiple contiguous data elements in a single request. This flag may only be specified if the database was opened with
#DUPFIXED. The {@code data} argument must be an array of two ##MDBVal. The {@code mv_size} of the first {@code MDBVal} must be the size of a
single data element. The {@code mv_data} of the first {@code MDBVal} must point to the beginning of the array of contiguous data elements. The
{@code mv_size} of the second {@code MDBVal} must be the count of the number of data elements to store. On return this field will be set to the
count of the number of elements actually written. The {@code mv_data} of the second {@code MDBVal} is unused.
"""
)}
"""
)
)
int(
"cursor_del",
"""
Deletes current key/data pair.
This function deletes the key/data pair to which the cursor refers.
""",
cursor_close["cursor"],
unsigned_int.IN(
"flags",
"""
options for this operation. This parameter must be set to 0 or one of the values described here.
${ul(
"#NODUPDATA - delete all of the data items for the current key. This flag may only be specified if the database was opened with #DUPSORT."
)}
"""
)
)
int(
"cursor_count",
"""
Returns count of duplicates for current key.
This call is only valid on databases that support sorted duplicate data items #DUPSORT.
""",
cursor_close["cursor"],
mdb_size_t_p.OUT("countp", "address where the count will be stored")
)
int(
"cmp",
"""
Compares two data items according to a particular database.
This returns a comparison as if the two data items were keys in the specified database.
""",
txn_env["txn"],
stat["dbi"],
const..MDB_val_p.IN("a", "the first item to compare"),
const..MDB_val_p.IN("b", "the second item to compare"),
returnDoc = "< 0 if a < b, 0 if a == b, > 0 if a > b"
)
int(
"dcmp",
"""
Compares two data items according to a particular database.
This returns a comparison as if the two items were data items of the specified database. The database must have the #DUPSORT flag.
""",
txn_env["txn"],
stat["dbi"],
const..MDB_val_p.IN("a", "the first item to compare"),
const..MDB_val_p.IN("b", "the second item to compare"),
returnDoc = "< 0 if a < b, 0 if a == b, > 0 if a > b"
)
int(
"reader_list",
"Dumps the entries in the reader lock table.",
env_open["env"],
MDB_msg_func.IN("func", "an ##MDBMsgFunc function"),
voidptr.IN("ctx", "anything the message function needs")
)
int(
"reader_check",
"Checks for stale entries in the reader lock table.",
env_open["env"],
int_p.OUT("dead", "number of stale slots that were cleared")
)
} | bsd-3-clause | 5f0ffa1a957e1aae9d1225643024bed7 | 34.451367 | 170 | 0.71044 | 3.829419 | false | false | false | false |
sxhya/roots | src/primitives/Vector.kt | 1 | 2802 | class Vector constructor (val myCoo: DoubleArray) {
constructor(len: Int): this(DoubleArray(len))
constructor(vec: Vector): this(DoubleArray(vec.myCoo.size) { p: Int -> vec.myCoo[p]})
fun reflectWRT(y: Vector): Vector = add(y, mul(this, -2 * prod(this, y) / len2(this)))
override fun equals(o: Any?): Boolean {
if (o == null) return false
if (o is Vector) return len(add(this, minus(o))) < EPS
throw IllegalArgumentException()
}
override fun hashCode(): Int = myCoo.fold(0) { result: Int, p: Double -> result * 31 + Math.round(p / EPS).toInt()}
override fun toString(): String {
val result = StringBuilder("{")
for (i in myCoo.indices) {
result.append(fmt(myCoo[i]))
if (i < myCoo.size - 1) result.append(", ")
}
return result.toString() + "}"
}
fun getReflection(): Matrix {
val n = myCoo.size
val m = Array(n) { DoubleArray(n) }
var d = len2(this)
if (Math.abs(d) < EPS) throw IllegalArgumentException("Can not reflect w.r.t. zero vector.")
d = -2 / d
for (i in 0 until n) { //column iterator
val c = d * myCoo[i]
for (j in 0 until n) { //row iterator
m[j][i] = c * myCoo[j]
if (i == j) m[j][i] += 1.0
}
}
return Matrix(m)
}
companion object {
val EPS = 0.01
fun fmt(d: Double): String {
return if (Math.abs(d - d.toLong()) <= 0.00001)
String.format("%d", d.toLong())
else
String.format("%e", d)
}
fun add(a: Vector, b: Vector): Vector {
if (a.myCoo.size != b.myCoo.size) throw IllegalArgumentException()
val result = Vector(a.myCoo.size)
for (i in a.myCoo.indices) result.myCoo[i] = a.myCoo[i] + b.myCoo[i]
return result
}
fun mul(a: Vector, c: Double): Vector {
val result = Vector(a.myCoo.size)
for (i in a.myCoo.indices) result.myCoo[i] = c * a.myCoo[i]
return result
}
fun minus(a: Vector): Vector = mul(a, -1.0)
fun minus(a: Vector, b: Vector) = add(a, minus(b))
fun len2(a: Vector): Double = prod(a, a)
fun len(a: Vector): Double = Math.sqrt(len2(a))
fun prod(a: Vector, b: Vector): Double {
if (a.myCoo.size != b.myCoo.size) throw IllegalArgumentException()
return a.myCoo.zip(b.myCoo).fold(0.0, {result: Double, p: Pair<Double, Double> -> result + p.first * p.second })
}
fun angle(a: Vector, b: Vector): Double = prod(a, b) / (len(a) * len(b))
fun orthogonal(a: Vector, b: Vector): Boolean = Math.abs(angle(a, b)) < EPS
}
} | apache-2.0 | 9c1839749bdb6a920a49d0cb8019c2f7 | 31.593023 | 125 | 0.52641 | 3.524528 | false | false | false | false |
bjzhou/Coolapk | app/src/main/kotlin/bjzhou/coolapk/app/ui/base/BaseActivity.kt | 1 | 3403 | package bjzhou.coolapk.app.ui.base
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.ActivityCompat
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import android.view.MenuItem
import bjzhou.coolapk.app.R
import java.util.*
open class BaseActivity : AppCompatActivity() {
private val REQUEST_PERMISSION = Random().nextInt(65535)
private var mPermissionListener: ((permission: String, succeed: Boolean) -> Unit)? = null
val currentFragment: Fragment
get() = supportFragmentManager.findFragmentById(R.id.container)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
fun setFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit()
}
fun addFragment(fragment: Fragment) {
supportFragmentManager.beginTransaction()
.add(R.id.container, fragment)
.commit()
}
fun checkPermissions(listener: (permission: String, succeed: Boolean) -> Unit, vararg permissions: String) {
this.mPermissionListener = listener
val needRequests = ArrayList<String>()
val needShowRationale = ArrayList<String>()
for (permission in permissions) {
val granted = ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
val shouldRational = ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
if (!granted && !shouldRational) {
needRequests.add(permission)
} else if (!granted) {
needShowRationale.add(permission)
} else {
listener(permission, true)
}
}
if (needRequests.isNotEmpty()) {
ActivityCompat.requestPermissions(this, needRequests.toTypedArray(), REQUEST_PERMISSION)
}
if (needShowRationale.isNotEmpty()) {
Snackbar.make(window.decorView.rootView, getRequestPermissionRationaleMessage(), Snackbar.LENGTH_INDEFINITE)
.setAction(android.R.string.ok, {
ActivityCompat.requestPermissions(this, needShowRationale.toTypedArray(), REQUEST_PERMISSION)
})
.show()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_PERMISSION) {
for (i in permissions.indices) {
mPermissionListener?.invoke(permissions[i], grantResults[i] == PackageManager.PERMISSION_GRANTED)
}
}
}
protected fun getRequestPermissionRationaleMessage(): CharSequence {
return "Need permission granted to continue."
}
protected fun setActionBarTitle(resId: Int) {
supportActionBar?.setTitle(resId)
}
protected fun showHome(showHome: Boolean) {
supportActionBar?.setDisplayShowHomeEnabled(showHome)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
}
| gpl-2.0 | d525630a3b65a10af3243387d159aec8 | 36.395604 | 120 | 0.65883 | 5.243451 | false | false | false | false |
angelovstanton/AutomateThePlanet | kotlin/MobileAutomation-Series/src/test/kotlin/appiumandroid/AppiumTests.kt | 1 | 3855 | /*
* Copyright 2021 Automate The Planet Ltd.
* Author: Teodor Nikolov
* 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 appiumandroid
import io.appium.java_client.android.Activity
import io.appium.java_client.android.AndroidDriver
import io.appium.java_client.android.AndroidElement
import io.appium.java_client.remote.AndroidMobileCapabilityType
import io.appium.java_client.remote.MobileCapabilityType
import org.openqa.selenium.remote.DesiredCapabilities
import org.testng.annotations.*
import java.net.URL
import java.nio.file.Paths
class AppiumTests {
private lateinit var driver: AndroidDriver<AndroidElement>
////private lateinit var appiumLocalService: AppiumDriverLocalService
@BeforeClass
fun classInit() {
////appiumLocalService = AppiumServiceBuilder().usingAnyFreePort().build()
////appiumLocalService.start()
val testAppUrl = javaClass.classLoader.getResource("ApiDemos.apk")
val testAppFile = Paths.get((testAppUrl!!).toURI()).toFile()
val testAppPath = testAppFile.absolutePath
val desiredCaps = DesiredCapabilities()
desiredCaps.setCapability(MobileCapabilityType.DEVICE_NAME, "android25-test")
desiredCaps.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.example.android.apis")
desiredCaps.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android")
desiredCaps.setCapability(MobileCapabilityType.PLATFORM_VERSION, "7.1")
desiredCaps.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".view.Controls1")
desiredCaps.setCapability(MobileCapabilityType.APP, testAppPath)
////driver = AndroidDriver<AndroidElement>(appiumLocalService, desiredCaps)
driver = AndroidDriver<AndroidElement>(URL("http://127.0.0.1:4723/wd/hub"), desiredCaps)
driver.closeApp()
}
@BeforeMethod
fun testInit() {
driver.launchApp()
driver.startActivity(Activity("com.example.android.apis", ".view.Controls1"))
}
@AfterMethod
fun testCleanup() {
driver.closeApp()
}
@AfterClass
fun classCleanup() {
////appiumLocalService.stop()
}
@Test
fun locatingElementsTest() {
val button = driver.findElementById("com.example.android.apis:id/button")
button.click()
val checkBox = driver.findElementByClassName("android.widget.CheckBox")
checkBox.click()
val secondButton = driver.findElementByXPath("//*[@resource-id='com.example.android.apis:id/button']")
secondButton.click()
val thirdButton = driver.findElementByAndroidUIAutomator("new UiSelector().textContains(\"BUTTO\");")
thirdButton.click()
}
@Test
fun locatingElementsInsideAnotherElementTest() {
val mainElement = driver.findElementById("android:id/content")
val button = mainElement.findElementById("com.example.android.apis:id/button")
button.click()
val checkBox = mainElement.findElementByClassName("android.widget.CheckBox")
checkBox.click()
val secondButton = mainElement.findElementByXPath("//*[@resource-id='com.example.android.apis:id/button']")
secondButton.click()
val thirdButton = mainElement.findElementByAndroidUIAutomator("new UiSelector().textContains(\"BUTTO\");")
thirdButton.click()
}
} | apache-2.0 | 4ea47a98dcaa7ad765c6d5212727e42e | 38.346939 | 115 | 0.72192 | 4.551358 | false | true | false | false |
PassionateWsj/YH-Android | app/src/main/java/com/intfocus/template/subject/seven/indicatorgroup/IndicatorGroupAdapter.kt | 1 | 5676 | package com.intfocus.template.subject.seven.indicatorgroup
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alibaba.fastjson.JSON
import com.intfocus.template.R
import com.intfocus.template.listener.NoDoubleClickListener
import com.intfocus.template.subject.one.entity.SingleValue
import com.intfocus.template.subject.seven.listener.EventRefreshIndicatorListItemData
import com.intfocus.template.util.LoadAssetsJsonUtil
import com.intfocus.template.util.LogUtil
import com.intfocus.template.util.OKHttpUtils
import com.intfocus.template.util.RxBusUtil
import kotlinx.android.synthetic.main.item_indicator_group.view.*
import okhttp3.Call
import java.io.IOException
import java.text.DecimalFormat
/**
* ****************************************************
* @author jameswong
* created on: 17/12/18 下午5:35
* e-mail: PassionateWsj@outlook.com
* name: 模板七 - 单值组件
* desc:
* ****************************************************
*/
class IndicatorGroupAdapter(val context: Context, private var mData: List<SingleValue>, private val eventCode: Int) : RecyclerView.Adapter<IndicatorGroupAdapter.IndicatorGroupViewHolder>() {
constructor(context: Context, mData: List<SingleValue>) : this(context, mData, -1)
val testApi = "https://api.douban.com/v2/book/search?q=%E7%BC%96%E7%A8%8B%E8%89%BA%E6%9C%AF"
val coCursor = context.resources.getIntArray(R.array.co_cursor)
var count = 0
companion object {
val CODE_EVENT_REFRESH_INDICATOR_LIST_ITEM_DATA = 1
}
override fun getItemCount(): Int = mData.size
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): IndicatorGroupViewHolder =
IndicatorGroupAdapter.IndicatorGroupViewHolder(LayoutInflater.from(context).inflate(R.layout.item_indicator_group, parent, false))
override fun onBindViewHolder(holder: IndicatorGroupViewHolder?, position: Int) {
holder!!.itemView.tv_item_indicator_group_main_data.tag = position
holder.itemView.tv_item_indicator_group_sub_data.tag = position
val data = mData[position]
if (data.isReal_time) {
// data.real_time_api?.let {
testApi.let {
OKHttpUtils.newInstance().getAsyncData(it, object : OKHttpUtils.OnReusltListener {
override fun onFailure(call: Call?, e: IOException?) {
}
override fun onSuccess(call: Call?, response: String?) {
val itemData = JSON.parseObject(LoadAssetsJsonUtil.getAssetsJsonData(data.real_time_api), SingleValue::class.java)
data.main_data = itemData.main_data
data.sub_data = itemData.sub_data
data.state = itemData.state
data.isReal_time = false
notifyItemChanged(position)
}
})
}
}
if (data.main_data == null || data.sub_data == null || data.state == null) {
return
}
val df = DecimalFormat("###,###.##")
val state = data.state.color % coCursor.size
val color = coCursor[state]
holder.itemView.tv_item_indicator_group_title.text = data.main_data.name
val mainValue = data.main_data.data.replace("%", "").toFloat()
holder.itemView.tv_item_indicator_group_main_data.text = df.format(mainValue.toDouble())
val subData = data.sub_data.data.replace("%", "").toFloat()
holder.itemView.tv_item_indicator_group_sub_data.text = df.format(subData.toDouble())
holder.itemView.tv_item_indicator_group_rate.setTextColor(color)
val diffRate = DecimalFormat(".##%").format(((mainValue - subData) / subData).toDouble())
holder.itemView.tv_item_indicator_group_rate.text = diffRate
holder.itemView.img_item_indicator_group_ratiocursor.setCursorState(data.state.color, false)
holder.itemView.img_item_indicator_group_ratiocursor.isDrawingCacheEnabled = true
holder.itemView.rl_item_indicator_group_container.setOnClickListener(object : NoDoubleClickListener() {
override fun onNoDoubleClick(v: View?) {
when (eventCode) {
CODE_EVENT_REFRESH_INDICATOR_LIST_ITEM_DATA -> {
RxBusUtil.getInstance().post(EventRefreshIndicatorListItemData(position))
}
}
LogUtil.d(this, "pos ::: " + position)
LogUtil.d(this, "itemView.id ::: " + holder.itemView.id)
LogUtil.d(this, "state ::: " + state)
LogUtil.d(this, "color ::: " + data.state.color)
LogUtil.d(this, "main_data ::: " + holder.itemView.tv_item_indicator_group_main_data.text)
LogUtil.d(this, "sub_data ::: " + holder.itemView.tv_item_indicator_group_sub_data.text)
LogUtil.d(this, "rate ::: " + holder.itemView.tv_item_indicator_group_rate.text)
LogUtil.d(this, "main_data.width ::: " + holder.itemView.tv_item_indicator_group_main_data.width)
val spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
holder.itemView.tv_item_indicator_group_main_data.measure(spec, spec)
LogUtil.d(this, "main_data.text.width ::: " + holder.itemView.tv_item_indicator_group_main_data.measuredWidth)
}
})
}
fun setData() {
}
class IndicatorGroupViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
} | gpl-3.0 | ea2415c125657bb876471d74752634f1 | 45.385246 | 190 | 0.643867 | 4.14202 | false | false | false | false |
saki4510t/libcommon | app/src/main/java/com/serenegiant/widget/SimpleVideoSourceCameraTextureView.kt | 1 | 12861 | package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki t_saki@serenegiant.com
*
* 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.
*/
import android.content.Context
import android.graphics.PointF
import android.graphics.RectF
import android.graphics.SurfaceTexture
import android.media.FaceDetector
import android.os.Handler
import android.util.AttributeSet
import android.util.Log
import android.view.Surface
import android.view.View
import com.serenegiant.glpipeline.*
import com.serenegiant.gl.GLContext
import com.serenegiant.gl.GLEffect
import com.serenegiant.gl.GLManager
import com.serenegiant.math.Fraction
import com.serenegiant.view.ViewTransformDelegater
/**
* VideoSourceを使ってカメラ映像を受け取りSurfacePipelineで描画処理を行うZoomAspectScaledTextureView/ICameraView実装
*/
class SimpleVideoSourceCameraTextureView @JvmOverloads constructor(
context: Context?, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: ZoomAspectScaledTextureView(context, attrs, defStyleAttr), ICameraView, GLPipelineView {
private val mGLManager: GLManager
private val mGLContext: GLContext
private val mGLHandler: Handler
private val mCameraDelegator: CameraDelegator
private var mVideoSourcePipeline: VideoSourcePipeline? = null
var pipelineMode = GLPipelineView.PREVIEW_ONLY
var enableFaceDetect = false
init {
if (DEBUG) Log.v(TAG, "コンストラクタ:")
mGLManager = GLManager()
mGLContext = mGLManager.glContext
mGLHandler = mGLManager.glHandler
setEnableHandleTouchEvent(ViewTransformDelegater.TOUCH_DISABLED)
mCameraDelegator = CameraDelegator(this@SimpleVideoSourceCameraTextureView,
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT,
object : CameraDelegator.ICameraRenderer {
override fun hasSurface(): Boolean {
if (DEBUG) Log.v(TAG, "hasSurface:")
return mVideoSourcePipeline != null
}
override fun getInputSurface(): SurfaceTexture {
if (DEBUG) Log.v(TAG, "getInputSurfaceTexture:")
checkNotNull(mVideoSourcePipeline)
return mVideoSourcePipeline!!.inputSurfaceTexture
}
override fun onPreviewSizeChanged(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onPreviewSizeChanged:(${width}x${height})")
mVideoSourcePipeline!!.resize(width, height)
setAspectRatio(width, height)
}
}
)
surfaceTextureListener = object : SurfaceTextureListener {
override fun onSurfaceTextureAvailable(
surface: SurfaceTexture, width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureAvailable:(${width}x${height})")
val source = mVideoSourcePipeline
if (source != null) {
addSurface(surface.hashCode(), surface, false)
source.resize(width, height)
mCameraDelegator.startPreview(
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT)
} else {
throw IllegalStateException("already released?")
}
}
override fun onSurfaceTextureSizeChanged(
surface: SurfaceTexture,
width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "onSurfaceTextureSizeChanged:(${width}x${height})")
}
override fun onSurfaceTextureDestroyed(
surface: SurfaceTexture): Boolean {
if (DEBUG) Log.v(TAG, "onSurfaceTextureDestroyed:")
val source = mVideoSourcePipeline
if (source != null) {
val pipeline = GLSurfacePipeline.findById(source, surface.hashCode())
if (pipeline != null) {
pipeline.remove()
pipeline.release()
}
}
return true
}
override fun onSurfaceTextureUpdated(
surface: SurfaceTexture) {
// if (DEBUG) Log.v(TAG, "onSurfaceTextureUpdated:")
}
}
}
override fun onDetachedFromWindow() {
val source = mVideoSourcePipeline
mVideoSourcePipeline = null
source?.release()
mGLManager.release()
super.onDetachedFromWindow()
}
override fun getView() : View {
return this
}
override fun onResume() {
if (DEBUG) Log.v(TAG, "onResume:")
mVideoSourcePipeline = createVideoSource(
CameraDelegator.DEFAULT_PREVIEW_WIDTH, CameraDelegator.DEFAULT_PREVIEW_HEIGHT)
mCameraDelegator.onResume()
}
override fun onPause() {
if (DEBUG) Log.v(TAG, "onPause:")
mCameraDelegator.onPause()
mVideoSourcePipeline?.release()
mVideoSourcePipeline = null
}
override fun setVideoSize(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "setVideoSize:(${width}x${height})")
mCameraDelegator.setVideoSize(width, height)
}
override fun addListener(listener: CameraDelegator.OnFrameAvailableListener) {
if (DEBUG) Log.v(TAG, "addListener:")
mCameraDelegator.addListener(listener)
}
override fun removeListener(listener: CameraDelegator.OnFrameAvailableListener) {
if (DEBUG) Log.v(TAG, "removeListener:")
mCameraDelegator.removeListener(listener)
}
override fun setScaleMode(mode: Int) {
if (DEBUG) Log.v(TAG, "setScaleMode:")
super.setScaleMode(mode)
mCameraDelegator.scaleMode = mode
}
override fun getScaleMode(): Int {
if (DEBUG) Log.v(TAG, "getScaleMode:")
return mCameraDelegator.scaleMode
}
override fun getVideoWidth(): Int {
if (DEBUG) Log.v(TAG, "getVideoWidth:${mCameraDelegator.previewWidth}")
return mCameraDelegator.previewWidth
}
override fun getVideoHeight(): Int {
if (DEBUG) Log.v(TAG, "getVideoHeight:${mCameraDelegator.previewHeight}")
return mCameraDelegator.previewHeight
}
override fun addSurface(
id: Int, surface: Any,
isRecordable: Boolean,
maxFps: Fraction?) {
if (DEBUG) Log.v(TAG, "addSurface:id=${id},${surface}")
val source = mVideoSourcePipeline
if (source != null) {
when (val last = GLPipeline.findLast(source)) {
mVideoSourcePipeline -> {
source.pipeline = createPipeline(surface, maxFps)
if (SUPPORT_RECORDING) {
// 通常の録画(#addSurfaceでエンコーダーへの映像入力用surfaceを受け取る)場合は
// 毎フレームCameraDelegator#callOnFrameAvailableを呼び出さないといけないので
// OnFramePipelineを追加する
if (DEBUG) Log.v(TAG, "addSurface:create OnFramePipeline")
val p = GLPipeline.findLast(source)
p.pipeline = OnFramePipeline(object :
OnFramePipeline.OnFrameAvailableListener {
var cnt: Int = 0
override fun onFrameAvailable() {
if (DEBUG && ((++cnt) % 100 == 0)) {
Log.v(TAG, "onFrameAvailable:${cnt}")
}
mCameraDelegator.callOnFrameAvailable()
}
})
}
if (enableFaceDetect) {
if (DEBUG) Log.v(TAG, "addSurface:create FaceDetectPipeline")
val p = GLPipeline.findLast(source)
p.pipeline = FaceDetectPipeline(mGLManager, Fraction.FIVE, 1
) { /*bitmap,*/ num, faces, width, height ->
if (DEBUG) {
Log.v(TAG, "onDetected:n=${num}")
for (i in 0 until num) {
val face: FaceDetector.Face = faces[i]
val point = PointF()
face.getMidPoint(point)
Log.v(TAG, "onDetected:Confidence=" + face.confidence())
Log.v(TAG, "onDetected:MidPoint.X=" + point.x)
Log.v(TAG, "onDetected:MidPoint.Y=" + point.y)
Log.v(TAG, "onDetected:EyesDistance=" + face.eyesDistance())
}
}
// val context: Context = context
// val outputFile: DocumentFile = if (BuildCheck.isAPI29()) {
// // API29以降は対象範囲別ストレージ
// MediaStoreUtils.getContentDocument(
// context, "image/jpeg",
// Environment.DIRECTORY_DCIM + "/" + Const.APP_DIR,
// FileUtils.getDateTimeString() + ".jpg", null
// )
// } else {
// MediaFileUtils.getRecordingFile(
// context,
// Const.REQUEST_ACCESS_SD,
// Environment.DIRECTORY_DCIM,
// "image/jpeg",
// ".jpg"
// )
// }
// var bos: BufferedOutputStream? = null
// try {
// bos = BufferedOutputStream (context.contentResolver.openOutputStream(outputFile.uri))
// bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos)
// MediaStoreUtils.updateContentUri(context, outputFile.uri)
// } catch (e: FileNotFoundException) {
// Log.w(TAG, e);
// } finally {
// if (bos != null) {
// try {
// bos.close();
// } catch (e: IOException) {
// Log.w(TAG, e);
// }
// }
// }
}
}
}
is GLSurfacePipeline -> {
if (last.hasSurface()) {
last.pipeline = SurfaceRendererPipeline(mGLManager, surface, maxFps)
} else {
last.setSurface(surface, null)
}
}
else -> {
last.pipeline = SurfaceRendererPipeline(mGLManager, surface, maxFps)
}
}
} else {
throw IllegalStateException("already released?")
}
}
override fun removeSurface(id: Int) {
if (DEBUG) Log.v(TAG, "removeSurface:id=${id}")
val found = GLSurfacePipeline.findById(mVideoSourcePipeline!!, id)
if (found != null) {
found.remove()
found.release()
}
}
override fun isRecordingSupported(): Boolean {
// XXX ここでtrueを返すなら録画中にCameraDelegatorのOnFrameAvailableListener#onFrameAvailableが呼び出されるようにしないといけない
return SUPPORT_RECORDING
}
/**
* GLPipelineViewの実装
* @param pipeline
*/
override fun addPipeline(pipeline: GLPipeline) {
val source = mVideoSourcePipeline
if (source != null) {
GLPipeline.append(source, pipeline)
if (DEBUG) Log.v(TAG, "addPipeline:" + GLPipeline.pipelineString(source))
} else {
throw IllegalStateException()
}
}
/**
* GLPipelineViewの実装
*/
override fun getGLManager(): GLManager {
return mGLManager
}
fun isEffectSupported(): Boolean {
return (pipelineMode == GLPipelineView.EFFECT_ONLY)
|| (pipelineMode == GLPipelineView.EFFECT_PLUS_SURFACE)
}
var effect: Int
get() {
val source = mVideoSourcePipeline
return if (source != null) {
val pipeline = GLPipeline.find(source, EffectPipeline::class.java)
if (DEBUG) Log.v(TAG, "getEffect:$pipeline")
pipeline?.currentEffect ?: 0
} else {
0
}
}
set(effect) {
if (DEBUG) Log.v(TAG, "setEffect:$effect")
if ((effect >= 0) && (effect < GLEffect.EFFECT_NUM)) {
post {
val source = mVideoSourcePipeline
if (source != null) {
val pipeline = GLPipeline.find(source, EffectPipeline::class.java)
pipeline?.setEffect(effect)
}
}
}
}
override fun getContentBounds(): RectF {
if (DEBUG) Log.v(TAG, "getContentBounds:")
return RectF(0.0f, 0.0f, getVideoWidth().toFloat(), getVideoHeight().toFloat())
}
/**
* VideoSourceインスタンスを生成
* @param width
* @param height
* @return
*/
private fun createVideoSource(
width: Int, height: Int): VideoSourcePipeline {
return VideoSourcePipeline(mGLManager,
width,
height,
object : GLPipelineSource.PipelineSourceCallback {
override fun onCreate(surface: Surface) {
if (DEBUG) Log.v(TAG, "PipelineSourceCallback#onCreate:$surface")
}
override fun onDestroy() {
if (DEBUG) Log.v(TAG, "PipelineSourceCallback#onDestroy:")
}
},
USE_SHARED_CONTEXT)
}
/**
* GLPipelineインスタンスを生成
* @param surface
*/
private fun createPipeline(surface: Any?, maxFps: Fraction?): GLPipeline {
if (DEBUG) Log.v(TAG, "createPipeline:surface=${surface}")
return when (pipelineMode) {
GLPipelineView.EFFECT_PLUS_SURFACE -> {
if (DEBUG) Log.v(TAG, "createPipeline:create EffectPipeline & SurfaceRendererPipeline")
val effect = EffectPipeline(mGLManager)
effect.pipeline = SurfaceRendererPipeline(mGLManager, surface, maxFps)
effect
}
GLPipelineView.EFFECT_ONLY -> {
if (DEBUG) Log.v(TAG, "createPipeline:create EffectPipeline")
EffectPipeline(mGLManager, surface, maxFps)
}
else -> {
if (DEBUG) Log.v(TAG, "createPipeline:create SurfaceRendererPipeline")
SurfaceRendererPipeline(mGLManager, surface, maxFps)
}
}
}
companion object {
private const val DEBUG = true // set false on production
private val TAG = SimpleVideoSourceCameraTextureView::class.java.simpleName
/**
* 共有GLコンテキストコンテキストを使ったマルチスレッド処理を行うかどうか
*/
private const val USE_SHARED_CONTEXT = false
private const val SUPPORT_RECORDING = true
}
}
| apache-2.0 | 6833d4bb2352878461c9d32423a09f29 | 28.959233 | 100 | 0.689906 | 3.663636 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/quests/roof_shape/AddRoofShape.kt | 1 | 934 | package de.westnordost.streetcomplete.quests.roof_shape
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType
import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao
class AddRoofShape(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) {
override val tagFilters = """
ways, relations with roof:levels
and roof:levels!=0 and !roof:shape and !3dr:type and !3dr:roof
"""
override val commitMessage = "Add roof shapes"
override val icon = R.drawable.ic_quest_roof_shape
override fun getTitle(tags: Map<String, String>) = R.string.quest_roofShape_title
override fun createForm() = AddRoofShapeForm()
override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) {
changes.add("roof:shape", answer)
}
}
| gpl-3.0 | 3877bd12d797e35ad7ece0779ec87f46 | 37.916667 | 85 | 0.761242 | 4.284404 | false | false | false | false |
heinika/MyGankio | app/src/main/java/lijin/heinika/cn/mygankio/entiy/DateBean.kt | 1 | 3148 | package lijin.heinika.cn.mygankio.entiy
import com.google.gson.annotations.SerializedName
/**
* _id : 5732b15067765974f885c05a
* content : <h3><img alt="" src="http://ww2.sinaimg.cn/large/610dc034jw1f3rbikc83dj20dw0kuadt.jpg"></img></h3>
*
* <h3>Android</h3>
*
*
* * [Fragment完全解析三步曲](http://www.jianshu.com/p/d9143a92ad94) (AndWang)
* * [送给小白的设计说明书](http://blog.csdn.net/dd864140130/article/details/51313342) (Dong dong Liu)
* * [Material 风格的干货客户端](http://www.jcodecraeer.com/a/anzhuokaifa/2016/0508/4222.html) (None)
* * [可定制的Indicator,结合ViewPager使用](https://github.com/jiang111/ScalableTabIndicator) (NewTab)
* * [T-MVP:泛型深度解耦下的MVP大瘦身](https://github.com/north2014/T-MVP) (Bai xiaokang)
* * [Simple Android SharedPreferences wrapper](https://github.com/GrenderG/Prefs) (蒋朋)
* * [IntelliJ plugin for supporting PermissionsDispatcher](https://github.com/shiraji/permissions-dispatcher-plugin) (蒋朋)
*
*
* <h3>iOS</h3>
*
*
* * [&&&&别人的 App 不好用?自己改了便是。Moves 篇(上)](http://mp.weixin.qq.com/s?__biz=MzIwMTYzMzcwOQ==&mid=2650948304&idx=1&sn=f76e7b765a7fcabcb71d37052b46e489&scene=0#wechat_redirect) (tripleCC)
* * [网易云信iOS UI组件源码仓库](https://github.com/netease-im/NIM_iOS_UIKit) (__weak_Point)
* * [OpenShop 开源](https://github.com/openshopio/openshop.io-ios) (代码家)
* * [Swift 实现的 OCR 识别库](https://github.com/garnele007/SwiftOCR) (代码家)
* * [让你的微信不再被人撤回消息](http://yulingtianxia.com/blog/2016/05/06/Let-your-WeChat-for-Mac-never-revoke-messages/) (CallMeWhy)
* * [微信双开还是微信定时炸弹?](http://drops.wooyun.org/mobile/15406) (CallMeWhy)
*
*
* <h3>瞎推荐</h3>
*
*
* * [阻碍新手程序员提升的8件小事](http://blog.csdn.net/shenyisyn/article/details/50056319) (LHF)
* * [程序员、黑客与开发者之别](http://36kr.com/p/5046775.html) (LHF)
*
*
* <h3>拓展资源</h3>
*
*
* * [详细介绍了java jvm 垃圾回收相关的知识汇总](http://www.wxtlife.com/2016/04/25/java-jvm-gc/) (Aaron)
* * [使用GPG签名Git提交和标签](http://arondight.me/2016/04/17/%E4%BD%BF%E7%94%A8GPG%E7%AD%BE%E5%90%8DGit%E6%8F%90%E4%BA%A4%E5%92%8C%E6%A0%87%E7%AD%BE/) (蒋朋)
*
*
* <h3>休息视频</h3>
*
*
* * [秒拍牛人大合集,[笑cry]目测膝盖根本不够用啊。](http://weibo.com/p/2304443956b04478364a64185f196f0a89266d) (LHF)
*
*
*
* <iframe frameborder="0" height="498" src="http://v.qq.com/iframe/player.html?vid=w0198nyi5x5&tiny=0&auto=0" width="640">&&</iframe>
*
*
* 感谢所有默默付出的编辑们,愿大家有美好一天.
*
* publishedAt : 2016-05-11T12:11:00.0Z
* title : 秒拍牛人大集合,看到哪个你跪了
*/
data class DateBean(
@SerializedName("_id") val id: String,
val content: String,
val publishedAt: String,
val title: String
)
| apache-2.0 | 5ad8e7fc65a077cb63624759da3ff58c | 40.2 | 225 | 0.689694 | 2.110323 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/metadata/sql/mappers/SearchMetadataTypeMapping.kt | 1 | 2728 | package exh.metadata.sql.mappers
import android.content.ContentValues
import android.database.Cursor
import com.pushtorefresh.storio.sqlite.SQLiteTypeMapping
import com.pushtorefresh.storio.sqlite.operations.delete.DefaultDeleteResolver
import com.pushtorefresh.storio.sqlite.operations.get.DefaultGetResolver
import com.pushtorefresh.storio.sqlite.operations.put.DefaultPutResolver
import com.pushtorefresh.storio.sqlite.queries.DeleteQuery
import com.pushtorefresh.storio.sqlite.queries.InsertQuery
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import exh.metadata.sql.models.SearchMetadata
import exh.metadata.sql.tables.SearchMetadataTable.COL_EXTRA
import exh.metadata.sql.tables.SearchMetadataTable.COL_EXTRA_VERSION
import exh.metadata.sql.tables.SearchMetadataTable.COL_INDEXED_EXTRA
import exh.metadata.sql.tables.SearchMetadataTable.COL_MANGA_ID
import exh.metadata.sql.tables.SearchMetadataTable.COL_UPLOADER
import exh.metadata.sql.tables.SearchMetadataTable.TABLE
class SearchMetadataTypeMapping : SQLiteTypeMapping<SearchMetadata>(
SearchMetadataPutResolver(),
SearchMetadataGetResolver(),
SearchMetadataDeleteResolver()
)
class SearchMetadataPutResolver : DefaultPutResolver<SearchMetadata>() {
override fun mapToInsertQuery(obj: SearchMetadata) = InsertQuery.builder()
.table(TABLE)
.build()
override fun mapToUpdateQuery(obj: SearchMetadata) = UpdateQuery.builder()
.table(TABLE)
.where("$COL_MANGA_ID = ?")
.whereArgs(obj.mangaId)
.build()
override fun mapToContentValues(obj: SearchMetadata) = ContentValues(5).apply {
put(COL_MANGA_ID, obj.mangaId)
put(COL_UPLOADER, obj.uploader)
put(COL_EXTRA, obj.extra)
put(COL_INDEXED_EXTRA, obj.indexedExtra)
put(COL_EXTRA_VERSION, obj.extraVersion)
}
}
class SearchMetadataGetResolver : DefaultGetResolver<SearchMetadata>() {
override fun mapFromCursor(cursor: Cursor): SearchMetadata = SearchMetadata(
mangaId = cursor.getLong(cursor.getColumnIndex(COL_MANGA_ID)),
uploader = cursor.getString(cursor.getColumnIndex(COL_UPLOADER)),
extra = cursor.getString(cursor.getColumnIndex(COL_EXTRA)),
indexedExtra = cursor.getString(cursor.getColumnIndex(COL_INDEXED_EXTRA)),
extraVersion = cursor.getInt(cursor.getColumnIndex(COL_EXTRA_VERSION))
)
}
class SearchMetadataDeleteResolver : DefaultDeleteResolver<SearchMetadata>() {
override fun mapToDeleteQuery(obj: SearchMetadata) = DeleteQuery.builder()
.table(TABLE)
.where("$COL_MANGA_ID = ?")
.whereArgs(obj.mangaId)
.build()
}
| apache-2.0 | edf49cbc1b0bfa2c2c8221946b2a3ad7 | 40.969231 | 86 | 0.745968 | 4.554257 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/ui/library/LibraryPresenter.kt | 1 | 13465 | package eu.kanade.tachiyomi.ui.library
import android.os.Bundle
import com.jakewharton.rxrelay.BehaviorRelay
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaCategory
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.preference.PreferencesHelper
import eu.kanade.tachiyomi.data.preference.getOrDefault
import eu.kanade.tachiyomi.source.LocalSource
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter
import eu.kanade.tachiyomi.util.combineLatest
import eu.kanade.tachiyomi.util.isNullOrUnsubscribed
import exh.favorites.FavoritesSyncHelper
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.io.IOException
import java.io.InputStream
import java.util.ArrayList
import java.util.Collections
import java.util.Comparator
/**
* Class containing library information.
*/
private data class Library(val categories: List<Category>, val mangaMap: LibraryMap)
/**
* Typealias for the library manga, using the category as keys, and list of manga as values.
*/
private typealias LibraryMap = Map<Int, List<LibraryItem>>
/**
* Presenter of [LibraryController].
*/
class LibraryPresenter(
private val db: DatabaseHelper = Injekt.get(),
private val preferences: PreferencesHelper = Injekt.get(),
private val coverCache: CoverCache = Injekt.get(),
private val sourceManager: SourceManager = Injekt.get(),
private val downloadManager: DownloadManager = Injekt.get()
) : BasePresenter<LibraryController>() {
private val context = preferences.context
/**
* Categories of the library.
*/
var categories: List<Category> = emptyList()
private set
/**
* Relay used to apply the UI filters to the last emission of the library.
*/
private val filterTriggerRelay = BehaviorRelay.create(Unit)
/**
* Relay used to apply the UI update to the last emission of the library.
*/
private val downloadTriggerRelay = BehaviorRelay.create(Unit)
/**
* Relay used to apply the selected sorting method to the last emission of the library.
*/
private val sortTriggerRelay = BehaviorRelay.create(Unit)
/**
* Library subscription.
*/
private var librarySubscription: Subscription? = null
// --> EXH
val favoritesSync = FavoritesSyncHelper(context)
// <-- EXH
override fun onCreate(savedState: Bundle?) {
super.onCreate(savedState)
subscribeLibrary()
}
/**
* Subscribes to library if needed.
*/
fun subscribeLibrary() {
if (librarySubscription.isNullOrUnsubscribed()) {
librarySubscription = getLibraryObservable()
.combineLatest(downloadTriggerRelay.observeOn(Schedulers.io()),
{ lib, _ -> lib.apply { setDownloadCount(mangaMap) } })
.combineLatest(filterTriggerRelay.observeOn(Schedulers.io()),
{ lib, _ -> lib.copy(mangaMap = applyFilters(lib.mangaMap)) })
.combineLatest(sortTriggerRelay.observeOn(Schedulers.io()),
{ lib, _ -> lib.copy(mangaMap = applySort(lib.mangaMap)) })
.observeOn(AndroidSchedulers.mainThread())
.subscribeLatestCache({ view, (categories, mangaMap) ->
view.onNextLibraryUpdate(categories, mangaMap)
})
}
}
/**
* Applies library filters to the given map of manga.
*
* @param map the map to filter.
*/
private fun applyFilters(map: LibraryMap): LibraryMap {
val filterDownloaded = preferences.filterDownloaded().getOrDefault()
val filterUnread = preferences.filterUnread().getOrDefault()
val filterCompleted = preferences.filterCompleted().getOrDefault()
val filterFn: (LibraryItem) -> Boolean = f@ { item ->
// Filter when there isn't unread chapters.
if (filterUnread && item.manga.unread == 0) {
return@f false
}
if (filterCompleted && item.manga.status != SManga.COMPLETED) {
return@f false
}
// Filter when there are no downloads.
if (filterDownloaded) {
// Local manga are always downloaded
if (item.manga.source == LocalSource.ID) {
return@f true
}
// Don't bother with directory checking if download count has been set.
if (item.downloadCount != -1) {
return@f item.downloadCount > 0
}
return@f downloadManager.getDownloadCount(item.manga) > 0
}
true
}
return map.mapValues { entry -> entry.value.filter(filterFn) }
}
/**
* Sets downloaded chapter count to each manga.
*
* @param map the map of manga.
*/
private fun setDownloadCount(map: LibraryMap) {
if (!preferences.downloadBadge().getOrDefault()) {
// Unset download count if the preference is not enabled.
for ((_, itemList) in map) {
for (item in itemList) {
item.downloadCount = -1
}
}
return
}
for ((_, itemList) in map) {
for (item in itemList) {
item.downloadCount = downloadManager.getDownloadCount(item.manga)
}
}
}
/**
* Applies library sorting to the given map of manga.
*
* @param map the map to sort.
*/
private fun applySort(map: LibraryMap): LibraryMap {
val sortingMode = preferences.librarySortingMode().getOrDefault()
val lastReadManga by lazy {
var counter = 0
db.getLastReadManga().executeAsBlocking().associate { it.id!! to counter++ }
}
val totalChapterManga by lazy {
var counter = 0
db.getTotalChapterManga().executeAsBlocking().associate { it.id!! to counter++ }
}
val sortFn: (LibraryItem, LibraryItem) -> Int = { i1, i2 ->
when (sortingMode) {
LibrarySort.ALPHA -> i1.manga.title.compareTo(i2.manga.title, true)
LibrarySort.LAST_READ -> {
// Get index of manga, set equal to list if size unknown.
val manga1LastRead = lastReadManga[i1.manga.id!!] ?: lastReadManga.size
val manga2LastRead = lastReadManga[i2.manga.id!!] ?: lastReadManga.size
manga1LastRead.compareTo(manga2LastRead)
}
LibrarySort.LAST_UPDATED -> i2.manga.last_update.compareTo(i1.manga.last_update)
LibrarySort.UNREAD -> i1.manga.unread.compareTo(i2.manga.unread)
LibrarySort.TOTAL -> {
val manga1TotalChapter = totalChapterManga[i1.manga.id!!] ?: 0
val mange2TotalChapter = totalChapterManga[i2.manga.id!!] ?: 0
manga1TotalChapter.compareTo(mange2TotalChapter)
}
LibrarySort.SOURCE -> {
val source1Name = sourceManager.getOrStub(i1.manga.source).name
val source2Name = sourceManager.getOrStub(i2.manga.source).name
source1Name.compareTo(source2Name)
}
else -> throw Exception("Unknown sorting mode")
}
}
val comparator = if (preferences.librarySortingAscending().getOrDefault())
Comparator(sortFn)
else
Collections.reverseOrder(sortFn)
return map.mapValues { entry -> entry.value.sortedWith(comparator) }
}
/**
* Get the categories and all its manga from the database.
*
* @return an observable of the categories and its manga.
*/
private fun getLibraryObservable(): Observable<Library> {
return Observable.combineLatest(getCategoriesObservable(), getLibraryMangasObservable(),
{ dbCategories, libraryManga ->
val categories = if (libraryManga.containsKey(0))
arrayListOf(Category.createDefault()) + dbCategories
else
dbCategories
this.categories = categories
Library(categories, libraryManga)
})
}
/**
* Get the categories from the database.
*
* @return an observable of the categories.
*/
private fun getCategoriesObservable(): Observable<List<Category>> {
return db.getCategories().asRxObservable()
}
/**
* Get the manga grouped by categories.
*
* @return an observable containing a map with the category id as key and a list of manga as the
* value.
*/
private fun getLibraryMangasObservable(): Observable<LibraryMap> {
val libraryAsList = preferences.libraryAsList()
return db.getLibraryMangas().asRxObservable()
.map { list ->
list.map { LibraryItem(it, libraryAsList) }.groupBy { it.manga.category }
}
}
/**
* Requests the library to be filtered.
*/
fun requestFilterUpdate() {
filterTriggerRelay.call(Unit)
}
/**
* Requests the library to have download badges added.
*/
fun requestDownloadBadgesUpdate() {
downloadTriggerRelay.call(Unit)
}
/**
* Requests the library to be sorted.
*/
fun requestSortUpdate() {
sortTriggerRelay.call(Unit)
}
/**
* Called when a manga is opened.
*/
fun onOpenManga() {
// Avoid further db updates for the library when it's not needed
librarySubscription?.let { remove(it) }
}
/**
* Returns the common categories for the given list of manga.
*
* @param mangas the list of manga.
*/
fun getCommonCategories(mangas: List<Manga>): Collection<Category> {
if (mangas.isEmpty()) return emptyList()
return mangas.toSet()
.map { db.getCategoriesForManga(it).executeAsBlocking() }
.reduce { set1: Iterable<Category>, set2 -> set1.intersect(set2) }
}
/**
* Remove the selected manga from the library.
*
* @param mangas the list of manga to delete.
* @param deleteChapters whether to also delete downloaded chapters.
*/
fun removeMangaFromLibrary(mangas: List<Manga>, deleteChapters: Boolean) {
// Create a set of the list
val mangaToDelete = mangas.distinctBy { it.id }
mangaToDelete.forEach { it.favorite = false }
Observable.fromCallable { db.insertMangas(mangaToDelete).executeAsBlocking() }
.onErrorResumeNext { Observable.empty() }
.subscribeOn(Schedulers.io())
.subscribe()
Observable.fromCallable {
mangaToDelete.forEach { manga ->
coverCache.deleteFromCache(manga.thumbnail_url)
if (deleteChapters) {
val source = sourceManager.get(manga.source) as? HttpSource
if (source != null) {
downloadManager.deleteManga(manga, source)
}
}
}
}
.subscribeOn(Schedulers.io())
.subscribe()
}
/**
* Move the given list of manga to categories.
*
* @param categories the selected categories.
* @param mangas the list of manga to move.
*/
fun moveMangasToCategories(categories: List<Category>, mangas: List<Manga>) {
val mc = ArrayList<MangaCategory>()
for (manga in mangas) {
for (cat in categories) {
mc.add(MangaCategory.create(manga, cat))
}
}
db.setMangaCategories(mc, mangas)
}
/**
* Update cover with local file.
*
* @param inputStream the new cover.
* @param manga the manga edited.
* @return true if the cover is updated, false otherwise
*/
@Throws(IOException::class)
fun editCoverWithStream(inputStream: InputStream, manga: Manga): Boolean {
if (manga.source == LocalSource.ID) {
LocalSource.updateCover(context, manga, inputStream)
return true
}
if (manga.thumbnail_url != null && manga.favorite) {
coverCache.copyToCache(manga.thumbnail_url!!, inputStream)
return true
}
return false
}
}
| apache-2.0 | 4a7fd38e555a0473dca4b9d7e1730e87 | 33.81117 | 100 | 0.589157 | 5.060128 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/track/myanimelist/MyAnimeList.kt | 1 | 5379 | package eu.kanade.tachiyomi.data.track.myanimelist
import android.content.Context
import android.graphics.Color
import androidx.annotation.StringRes
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Track
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.data.track.model.TrackSearch
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import uy.kohesive.injekt.injectLazy
class MyAnimeList(private val context: Context, id: Long) : TrackService(id) {
companion object {
const val READING = 1
const val COMPLETED = 2
const val ON_HOLD = 3
const val DROPPED = 4
const val PLAN_TO_READ = 6
const val REREADING = 7
private const val SEARCH_ID_PREFIX = "id:"
private const val SEARCH_LIST_PREFIX = "my:"
}
private val json: Json by injectLazy()
private val interceptor by lazy { MyAnimeListInterceptor(this, getPassword()) }
private val api by lazy { MyAnimeListApi(client, interceptor) }
@StringRes
override fun nameRes() = R.string.tracker_myanimelist
override val supportsReadingDates: Boolean = true
override fun getLogo() = R.drawable.ic_tracker_mal
override fun getLogoColor() = Color.rgb(46, 81, 162)
override fun getStatusList(): List<Int> {
return listOf(READING, COMPLETED, ON_HOLD, DROPPED, PLAN_TO_READ, REREADING)
}
override fun getStatus(status: Int): String = with(context) {
when (status) {
READING -> getString(R.string.reading)
PLAN_TO_READ -> getString(R.string.plan_to_read)
COMPLETED -> getString(R.string.completed)
ON_HOLD -> getString(R.string.on_hold)
DROPPED -> getString(R.string.dropped)
REREADING -> getString(R.string.repeating)
else -> ""
}
}
override fun getReadingStatus(): Int = READING
override fun getRereadingStatus(): Int = REREADING
override fun getCompletionStatus(): Int = COMPLETED
override fun getScoreList(): List<String> {
return IntRange(0, 10).map(Int::toString)
}
override fun displayScore(track: Track): String {
return track.score.toInt().toString()
}
private suspend fun add(track: Track): Track {
return api.updateItem(track)
}
override suspend fun update(track: Track, didReadChapter: Boolean): Track {
if (track.status != COMPLETED) {
if (didReadChapter) {
if (track.last_chapter_read.toInt() == track.total_chapters && track.total_chapters > 0) {
track.status = COMPLETED
track.finished_reading_date = System.currentTimeMillis()
} else if (track.status != REREADING) {
track.status = READING
if (track.last_chapter_read == 1F) {
track.started_reading_date = System.currentTimeMillis()
}
}
}
}
return api.updateItem(track)
}
override suspend fun bind(track: Track, hasReadChapters: Boolean): Track {
val remoteTrack = api.findListItem(track)
return if (remoteTrack != null) {
track.copyPersonalFrom(remoteTrack)
track.media_id = remoteTrack.media_id
if (track.status != COMPLETED) {
val isRereading = track.status == REREADING
track.status = if (isRereading.not() && hasReadChapters) READING else track.status
}
update(track)
} else {
// Set default fields if it's not found in the list
track.status = if (hasReadChapters) READING else PLAN_TO_READ
track.score = 0F
add(track)
}
}
override suspend fun search(query: String): List<TrackSearch> {
if (query.startsWith(SEARCH_ID_PREFIX)) {
query.substringAfter(SEARCH_ID_PREFIX).toIntOrNull()?.let { id ->
return listOf(api.getMangaDetails(id))
}
}
if (query.startsWith(SEARCH_LIST_PREFIX)) {
query.substringAfter(SEARCH_LIST_PREFIX).let { title ->
return api.findListItems(title)
}
}
return api.search(query)
}
override suspend fun refresh(track: Track): Track {
return api.findListItem(track) ?: add(track)
}
override suspend fun login(username: String, password: String) = login(password)
suspend fun login(authCode: String) {
try {
val oauth = api.getAccessToken(authCode)
interceptor.setAuth(oauth)
val username = api.getCurrentUser()
saveCredentials(username, oauth.access_token)
} catch (e: Throwable) {
logout()
}
}
override fun logout() {
super.logout()
trackPreferences.trackToken(this).delete()
interceptor.setAuth(null)
}
fun saveOAuth(oAuth: OAuth?) {
trackPreferences.trackToken(this).set(json.encodeToString(oAuth))
}
fun loadOAuth(): OAuth? {
return try {
json.decodeFromString<OAuth>(trackPreferences.trackToken(this).get())
} catch (e: Exception) {
null
}
}
}
| apache-2.0 | 757a11c86dca707f269c57e7df8bb1a8 | 31.6 | 106 | 0.614055 | 4.554615 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/utils/StringUtils.kt | 1 | 387 | package info.nightscout.androidaps.utils
/**
* class contains useful String functions
*/
object StringUtils {
fun removeSurroundingQuotes(input: String): String {
var string = input
if (string.length >= 2 && string[0] == '"' && string[string.length - 1] == '"') {
string = string.substring(1, string.length - 1)
}
return string
}
} | agpl-3.0 | 5eece7a7d1a72301d917cfe29bcbec5e | 24.866667 | 89 | 0.599483 | 4.206522 | false | false | false | false |
nipapadak/watchtower | Watchtower/app/src/main/java/com/watchtower/networking/ApiClient.kt | 1 | 1610 | package com.watchtower.networking
import android.content.Context
import bolts.CancellationToken
import bolts.Task
import bolts.TaskCompletionSource
import com.watchtower.storage.model.JokeApiModel
import retrofit.*
class ApiClient() {
//region Properties
private val service: APIEndpointInterface
//endregion
//region Init
init {
val retrofit = Retrofit.Builder()
.baseUrl("http://api.icndb.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
service = retrofit.create(APIEndpointInterface::class.java);
}
//endregion
//region Public API Methods
fun getRandomJoke(cancellationToken: CancellationToken) : Task<JokeApiModel> {
val tcs = TaskCompletionSource<JokeApiModel>()
val call = service.getRandomJoke()
// Cancel web call as soon as we request cancellation
cancellationToken.register {
call.cancel()
}
// Enqueue this call so it gets executed asyncronously on a bg thread
call.enqueue( object: Callback<JokeApiModel> {
override fun onFailure(t: Throwable?) {
tcs.setError(Exception(t?.message))
}
override fun onResponse(response: Response<JokeApiModel>?, retrofit: Retrofit?) {
if( response != null ) {
tcs.setResult(response.body())
} else {
tcs.setError(Exception("Null Response"))
}
}
})
return tcs.task
}
//endregion
}
| apache-2.0 | 7bcabcb0831c89216f6459642306618e | 23.393939 | 93 | 0.606211 | 5.111111 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/expression/Serializer.kt | 1 | 9720 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
@file:Suppress("UNCHECKED_CAST")
package arcs.core.data.expression
import arcs.core.data.expression.Expression.BinaryExpression
import arcs.core.data.expression.Expression.BinaryOp
import arcs.core.data.expression.Expression.Scope
import arcs.core.data.expression.Expression.UnaryExpression
import arcs.core.data.expression.Expression.UnaryOp
import arcs.core.util.BigInt
import arcs.core.util.Json
import arcs.core.util.JsonValue
import arcs.core.util.JsonValue.JsonArray
import arcs.core.util.JsonValue.JsonBoolean
import arcs.core.util.JsonValue.JsonNull
import arcs.core.util.JsonValue.JsonNumber
import arcs.core.util.JsonValue.JsonObject
import arcs.core.util.JsonValue.JsonString
import arcs.core.util.JsonVisitor
import arcs.core.util.toBigInt
/** Traverses a tree of [Expression] objects, serializing it into a JSON format. */
class ExpressionSerializer() : Expression.Visitor<JsonValue<*>, Unit> {
override fun <E, T> visit(expr: UnaryExpression<E, T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString(expr.op.token),
"expr" to expr.expr.accept(this, ctx)
)
)
override fun <L, R, T> visit(expr: BinaryExpression<L, R, T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString(expr.op.token),
"left" to expr.left.accept(this, ctx),
"right" to expr.right.accept(this, ctx)
)
)
override fun <T> visit(expr: Expression.FieldExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("."),
"qualifier" to (expr.qualifier?.accept(this, ctx) ?: JsonNull),
"field" to JsonString(expr.field),
"nullSafe" to JsonBoolean(expr.nullSafe)
)
)
override fun <T> visit(expr: Expression.QueryParameterExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("?"),
"identifier" to JsonString(expr.paramIdentifier)
)
)
override fun visit(expr: Expression.NumberLiteralExpression, ctx: Unit) = toNumber(expr.value)
override fun visit(expr: Expression.TextLiteralExpression, ctx: Unit) = JsonString(expr.value)
override fun visit(expr: Expression.BooleanLiteralExpression, ctx: Unit) =
JsonBoolean(expr.value)
override fun visit(expr: Expression.NullLiteralExpression, ctx: Unit) = JsonNull
override fun visit(expr: Expression.FromExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("from"),
"source" to expr.source.accept(this, ctx),
"var" to JsonString(expr.iterationVar),
"qualifier" to (expr.qualifier?.accept(this, ctx) ?: JsonNull)
)
)
override fun visit(expr: Expression.WhereExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("where"),
"expr" to expr.expr.accept(this, ctx),
"qualifier" to expr.qualifier.accept(this, ctx)
)
)
override fun visit(expr: Expression.LetExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("let"),
"expr" to expr.variableExpr.accept(this, ctx),
"var" to JsonString(expr.variableName),
"qualifier" to (expr.qualifier.accept(this, ctx))
)
)
override fun <T> visit(expr: Expression.SelectExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("select"),
"expr" to expr.expr.accept(this, ctx),
"qualifier" to expr.qualifier.accept(this, ctx)
)
)
override fun visit(expr: Expression.NewExpression, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("new"),
"schemaName" to JsonArray(expr.schemaName.map { JsonString(it) }),
"fields" to JsonObject(
expr.fields.associateBy({ it.first }, { it.second.accept(this, ctx) })
)
)
)
override fun <T> visit(expr: Expression.FunctionExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("function"),
"functionName" to JsonString(expr.function.name),
"arguments" to JsonArray(
expr.arguments.map { it.accept(this, ctx) })
)
)
override fun <T> visit(expr: Expression.OrderByExpression<T>, ctx: Unit) =
JsonObject(
mapOf(
"op" to JsonString("orderBy"),
"selectors" to JsonArray(expr.selectors.map { sel ->
JsonArray(listOf(sel.expr.accept(this, ctx), JsonBoolean(sel.descending)))
}
),
"qualifier" to expr.qualifier.accept(this, ctx)
)
)
}
/** Traverses a parsed [JsonValue] representation and returns decoded [Expression] */
class ExpressionDeserializer : JsonVisitor<Expression<*>> {
override fun visit(value: JsonBoolean) = Expression.BooleanLiteralExpression(value.value)
override fun visit(value: JsonString) = Expression.TextLiteralExpression(value.value)
override fun visit(value: JsonNumber) = Expression.NumberLiteralExpression(value.value)
override fun visit(value: JsonNull) = Expression.NullLiteralExpression()
override fun visit(value: JsonArray) =
throw IllegalArgumentException("Arrays should not appear in JSON Serialized Expressions")
override fun visit(value: JsonObject): Expression<*> {
val type = value["op"].string()!!
return when {
type == "." -> Expression.FieldExpression<Any>(
if (value["qualifier"] == JsonNull) {
null
} else {
visit(value["qualifier"]) as Expression<Scope>
},
value["field"].string()!!,
value["nullSafe"].bool()!!
)
BinaryOp.fromToken(type) != null -> {
BinaryExpression(
BinaryOp.fromToken(type) as BinaryOp<Any, Any, Any>,
visit(value["left"]) as Expression<Any>,
visit(value["right"]) as Expression<Any>
)
}
UnaryOp.fromToken(type) != null -> {
UnaryExpression(
UnaryOp.fromToken(type)!! as UnaryOp<Any, Any>,
visit(value["expr"]) as Expression<Any>
)
}
type == "number" -> Expression.NumberLiteralExpression(fromNumber(value))
type == "?" -> Expression.QueryParameterExpression<Any>(value["identifier"].string()!!)
type == "from" ->
Expression.FromExpression(
if (value["qualifier"] == JsonNull) {
null
} else {
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>
},
visit(value["source"].obj()!!) as Expression<Sequence<Any>>,
value["var"].string()!!
)
type == "where" ->
Expression.WhereExpression(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
visit(value["expr"]) as Expression<Boolean>
)
type == "let" ->
Expression.LetExpression(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
visit(value["expr"]) as Expression<Any>,
value["var"].string()!!
)
type == "select" ->
Expression.SelectExpression(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
visit(value["expr"]) as Expression<Sequence<Any>>
)
type == "new" ->
Expression.NewExpression(
value["schemaName"].array()!!.value.map { it.string()!! }.toSet(),
value["fields"].obj()!!.value.map { (name, expr) ->
name to visit(expr)
}.toList()
)
type == "function" ->
Expression.FunctionExpression<Any>(
GlobalFunction.of(value["functionName"].string()!!),
value["arguments"].array()!!.value.map { visit(it) }.toList()
)
type == "orderBy" ->
Expression.OrderByExpression<Any>(
visit(value["qualifier"].obj()!!) as Expression<Sequence<Scope>>,
value["selectors"].array()!!.value.map {
val array = it as JsonArray
Expression.OrderByExpression.Selector(
visit(array[0]) as Expression<Any>,
it[1].bool()!!
)
}.toList()
)
else -> throw IllegalArgumentException("Unknown type $type during deserialization")
}
}
}
/** Given an expression, return a string representation. */
fun <T> Expression<T>.serialize() = this.accept(ExpressionSerializer(), Unit).toString()
/** Given a serialized [Expression], deserialize it. */
fun String.deserializeExpression() = ExpressionDeserializer().visit(Json.parse(this))
private fun toNumberType(value: Number) = when (value) {
is Float -> "F"
is Int -> "I"
is Short -> "S"
is Double -> "D"
is BigInt -> "BI"
is Long -> "L"
is Byte -> "B"
else -> throw IllegalArgumentException("Unknown type of number $value, ${value::class}")
}
private fun toDouble(value: JsonObject) = value["value"].string()!!.toDouble()
private fun toInt(value: JsonObject) = value["value"].string()!!.toInt()
private fun fromNumber(value: JsonObject): Number = when (value["type"].string()!!) {
"F" -> toDouble(value).toFloat()
"D" -> toDouble(value)
"I" -> toInt(value)
"S" -> toInt(value).toShort()
"B" -> toInt(value).toByte()
"L" -> value["value"].string()!!.toLong()
"BI" -> value["value"].string()!!.toBigInt()
else -> throw IllegalArgumentException("Unknown numeric type ${value["type"]}")
}
private fun toNumber(value: Number) = JsonObject(
mutableMapOf(
"op" to JsonString("number"),
"type" to JsonString(toNumberType(value)),
"value" to JsonString(value.toString())
)
)
| bsd-3-clause | 93c0e56c81a579da764b1f2bfe19945d | 33.225352 | 96 | 0.631481 | 4.10473 | false | false | false | false |
JetBrains/ideavim | vim-engine/src/main/kotlin/com/maddyhome/idea/vim/yank/YankGroupBase.kt | 1 | 7163 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.yank
import com.maddyhome.idea.vim.action.motion.updown.MotionDownLess1FirstNonSpaceAction
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.getLineEndForOffset
import com.maddyhome.idea.vim.api.getLineStartForOffset
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.Argument
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.command.SelectionType
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.listener.VimYankListener
import org.jetbrains.annotations.Contract
import kotlin.math.min
open class YankGroupBase : VimYankGroup {
private val yankListeners: MutableList<VimYankListener> = ArrayList()
protected fun yankRange(
editor: VimEditor,
caretToRange: Map<VimCaret, TextRange>,
range: TextRange,
type: SelectionType,
startOffsets: Map<VimCaret, Int>?,
): Boolean {
startOffsets?.forEach { (caret, offset) ->
caret.moveToOffset(offset)
}
notifyListeners(editor, range)
var result = true
for ((caret, myRange) in caretToRange) {
result = caret.registerStorage.storeText(caret, editor, myRange, type, false) && result
}
return result
}
@Contract("_, _ -> new")
protected fun getTextRange(ranges: List<Pair<Int, Int>>, type: SelectionType): TextRange? {
if (ranges.isEmpty()) return null
val size = ranges.size
val starts = IntArray(size)
val ends = IntArray(size)
if (type == SelectionType.LINE_WISE) {
starts[size - 1] = ranges[size - 1].first
ends[size - 1] = ranges[size - 1].second
for (i in 0 until size - 1) {
val range = ranges[i]
starts[i] = range.first
ends[i] = range.second - 1
}
} else {
for (i in 0 until size) {
val range = ranges[i]
starts[i] = range.first
ends[i] = range.second
}
}
return TextRange(starts, ends)
}
/**
* This yanks the text moved over by the motion command argument.
*
* @param editor The editor to yank from
* @param context The data context
* @param count The number of times to yank
* @param rawCount The actual count entered by the user
* @param argument The motion command argument
* @return true if able to yank the text, false if not
*/
override fun yankMotion(
editor: VimEditor,
context: ExecutionContext,
argument: Argument,
operatorArguments: OperatorArguments
): Boolean {
val motion = argument.motion
val type = if (motion.isLinewiseMotion()) SelectionType.LINE_WISE else SelectionType.CHARACTER_WISE
val nativeCaretCount = editor.nativeCarets().size
if (nativeCaretCount <= 0) return false
val carretToRange = HashMap<VimCaret, TextRange>(nativeCaretCount)
val ranges = ArrayList<Pair<Int, Int>>(nativeCaretCount)
// This logic is from original vim
val startOffsets = if (argument.motion.action is MotionDownLess1FirstNonSpaceAction) null else HashMap<VimCaret, Int>(nativeCaretCount)
for (caret in editor.nativeCarets()) {
val motionRange = injector.motion.getMotionRange(editor, caret, context, argument, operatorArguments)
?: continue
assert(motionRange.size() == 1)
ranges.add(motionRange.startOffset to motionRange.endOffset)
startOffsets?.put(caret, motionRange.normalize().startOffset)
carretToRange[caret] = TextRange(motionRange.startOffset, motionRange.endOffset)
}
val range = getTextRange(ranges, type) ?: return false
if (range.size() == 0) return false
return yankRange(
editor,
carretToRange,
range,
type,
startOffsets
)
}
/**
* This yanks count lines of text
*
* @param editor The editor to yank from
* @param count The number of lines to yank
* @return true if able to yank the lines, false if not
*/
override fun yankLine(editor: VimEditor, count: Int): Boolean {
val caretCount = editor.nativeCarets().size
val ranges = ArrayList<Pair<Int, Int>>(caretCount)
val caretToRange = HashMap<VimCaret, TextRange>(caretCount)
for (caret in editor.nativeCarets()) {
val start = injector.motion.moveCaretToCurrentLineStart(editor, caret)
val end = min(injector.motion.moveCaretToRelativeLineEnd(editor, caret, count - 1, true) + 1, editor.fileSize().toInt())
if (end == -1) continue
ranges.add(start to end)
caretToRange[caret] = TextRange(start, end)
}
val range = getTextRange(ranges, SelectionType.LINE_WISE) ?: return false
return yankRange(editor, caretToRange, range, SelectionType.LINE_WISE, null)
}
/**
* This yanks a range of text
*
* @param editor The editor to yank from
* @param range The range of text to yank
* @param type The type of yank
* @return true if able to yank the range, false if not
*/
override fun yankRange(editor: VimEditor, range: TextRange?, type: SelectionType, moveCursor: Boolean): Boolean {
range ?: return false
val caretToRange = HashMap<VimCaret, TextRange>()
val selectionType = if (type == SelectionType.CHARACTER_WISE && range.isMultiple) SelectionType.BLOCK_WISE else type
if (type == SelectionType.LINE_WISE) {
for (i in 0 until range.size()) {
if (editor.offsetToBufferPosition(range.startOffsets[i]).column != 0) {
range.startOffsets[i] = editor.getLineStartForOffset(range.startOffsets[i])
}
if (editor.offsetToBufferPosition(range.endOffsets[i]).column != 0) {
range.endOffsets[i] =
(editor.getLineEndForOffset(range.endOffsets[i]) + 1).coerceAtMost(editor.fileSize().toInt())
}
}
}
val rangeStartOffsets = range.startOffsets
val rangeEndOffsets = range.endOffsets
val startOffsets = HashMap<VimCaret, Int>(editor.nativeCarets().size)
if (type == SelectionType.BLOCK_WISE) {
startOffsets[editor.primaryCaret()] = range.normalize().startOffset
caretToRange[editor.primaryCaret()] = range
} else {
for ((i, caret) in editor.nativeCarets().withIndex()) {
val textRange = TextRange(rangeStartOffsets[i], rangeEndOffsets[i])
startOffsets[caret] = textRange.normalize().startOffset
caretToRange[caret] = textRange
}
}
return if (moveCursor) {
yankRange(editor, caretToRange, range, selectionType, startOffsets)
} else {
yankRange(editor, caretToRange, range, selectionType, null)
}
}
override fun addListener(listener: VimYankListener) = yankListeners.add(listener)
override fun removeListener(listener: VimYankListener) = yankListeners.remove(listener)
override fun notifyListeners(editor: VimEditor, textRange: TextRange) = yankListeners.forEach {
it.yankPerformed(editor, textRange)
}
}
| mit | 23ca1974e414ea3eb74c376bf2284172 | 33.941463 | 139 | 0.695379 | 4.223467 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/formatters/DateTimeFormatter.kt | 1 | 8566 | /*
* Copyright 2019 Poly Forest, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.acornui.formatters
import com.acornui.obj.removeNullValues
import com.acornui.i18n.Locale
import com.acornui.system.userInfo
import com.acornui.time.Date
import kotlin.js.Date as JsDate
/**
* This class formats dates into localized string representations.
*/
class DateTimeFormatter(
/**
* The date formatting style to use when called.
*/
dateStyle: DateTimeStyle? = null,
/**
* The time formatting style to use when called.
*/
timeStyle: DateTimeStyle? = null,
/**
* The number of fractional seconds to apply when calling format(). Valid values are 0-3.
*/
fractionalSecondsDigit: Int? = null,
calendar: Calendar? = null,
dayPeriod: DayPeriod? = null,
numberingSystem: NumberingSystem? = null,
/**
* The locale matching algorithm to use.
*/
localeMatcher: LocaleMatcher = LocaleMatcher.BEST_FIT,
/**
* The time zone for formatting.
* The only values this is guaranteed to work with are "UTC" or null.
* Other values that will likely work based on browser or jvm implementation are the full TZ code
* [https://en.wikipedia.org/wiki/List_of_tz_database_time_zones]
* For example, use "America/New_York" as opposed to "EST"
* If this is null, the user's timezone will be used.
*/
timeZone: String? = null,
/**
* Whether to use 12-hour time (as opposed to 24-hour time). Possible values are true and false; the default is
* locale dependent. This option overrides the hc language tag and/or the hourCycle option in case both are present.
*/
hour12: Boolean? = null,
/**
* The hour cycle to use. This option overrides the hc language tag, if both are present, and the hour12 option
* takes precedence in case both options have been specified.
*/
hourCycle: HourCycle? = null,
/**
* The format matching algorithm to use.
* See the following paragraphs for information about the use of this property.
*/
formatMatcher: FormatMatcher? = null,
weekday: WeekdayFormat? = null,
era: EraFormat? = null,
year: YearFormat? = null,
month: MonthFormat? = null,
day: TimePartFormat? = null,
hour: TimePartFormat? = null,
minute: TimePartFormat? = null,
second: TimePartFormat? = null,
timeZoneName: TimezoneNameFormat? = null,
/**
* The ordered locale chain to use for formatting. If this is left null, the user's current locale will be used.
*
* See [Locale Identification](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation)
*/
locales: List<Locale>? = null
) : StringFormatter<Date> {
private val formatter: dynamic
init {
@Suppress("LocalVariableName")
val JsDateTimeFormat = js("Intl.DateTimeFormat")
val options = js("({})")
options.dateStyle = dateStyle?.name.toJsValue()
options.timeStyle = timeStyle?.name.toJsValue()
options.fractionalSecondsDigit = fractionalSecondsDigit
options.calendar = calendar?.name.toJsValue()
options.dayPeriod = dayPeriod?.name.toJsValue()
options.numberingSystem = numberingSystem?.name.toJsValue()
options.localeMatcher = localeMatcher.name.toJsValue()
options.timeZone = timeZone
options.hour12 = hour12
options.hourCycle = hourCycle?.name.toJsValue()
options.formatMatcher = formatMatcher?.name.toJsValue()
options.weekday = weekday?.name.toJsValue()
options.era = era?.name.toJsValue()
options.year = year?.name.toJsValue()
options.month = month?.name.toJsValue()
options.day = day?.name.toJsValue()
options.hour = hour?.name.toJsValue()
options.minute = minute?.name.toJsValue()
options.second = second?.name.toJsValue()
options.timeZoneName = timeZoneName?.name.toJsValue()
removeNullValues(options)
val loc = (locales ?: userInfo.systemLocale).map { it.value }.toTypedArray()
formatter = JsDateTimeFormat(loc, options)
}
override fun format(value: Date): String =
formatter!!.format(value.jsDate).unsafeCast<String>()
}
enum class DateTimeStyle {
FULL,
LONG,
MEDIUM,
SHORT
}
enum class DayPeriod {
NARROW,
SHORT,
LONG
}
enum class NumberingSystem {
ARAB,
ARABEXT,
BALI,
BENG,
DEVA,
FULLWIDE,
GUJR,
GURU,
HANIDEC,
KHMR,
KNDA,
LAOO,
LATN,
LIMB,
MLYM,
MONG,
MYMR,
ORYA,
TAMLDEC,
TELU,
THAI,
TIBT
}
enum class LocaleMatcher {
LOOKUP,
BEST_FIT
}
enum class FormatMatcher {
BASIC,
BEST_FIT
}
enum class HourCycle {
H11,
H12,
H23,
H24
}
enum class DateTimeFormatStyle {
FULL,
LONG,
MEDIUM,
SHORT,
DEFAULT
}
enum class Calendar {
BUDDHIST,
CHINESE,
COPTIC,
ETHIOPIA,
ETHIOPIC,
GREGORY,
HEBREW,
INDIAN,
ISLAMIC,
ISO8601,
JAPANESE,
PERSIAN,
ROC
}
enum class WeekdayFormat {
/**
* E.g. Thursday
*/
LONG,
/**
* E.g. Thu
*/
SHORT,
/**
* E.g. T
*/
NARROW
}
enum class EraFormat {
/**
* E.g. Anno Domini
*/
LONG,
/**
* E.g. AD
*/
SHORT,
/**
* E.g. A
*/
NARROW
}
enum class YearFormat {
/**
* E.g. 2012
*/
NUMERIC,
/**
* E.g. 12
*/
TWO_DIGIT
}
enum class MonthFormat {
/**
* E.g. 2
*/
NUMERIC,
/**
* E.g. 02
*/
TWO_DIGIT,
/**
* E.g. March
*/
LONG,
/**
* E.g. Mar
*/
SHORT,
/**
* E.g. M
*/
NARROW
}
enum class TimePartFormat {
/**
* E.g. 1
*/
NUMERIC,
/**
* E.g. 01
*/
TWO_DIGIT
}
enum class TimezoneNameFormat {
/**
* E.g. British Summer Time
*/
LONG,
/**
* E.g. GMT+1
*/
SHORT
}
/**
* Converts a two digit year to a four digit year, relative to [currentYear].
* @param year If this is not a two digit year, it will be returned as is. Otherwise, it will be considered relative
* to [currentYear]. That is, the year returned will be in the century of the span of
* `currentYear - 49 to currentYear + 50`.
*/
fun calculateFullYear(year: Int, allowTwoDigitYears: Boolean = true, currentYear: Int = JsDate().getFullYear()): Int? {
return if (year < 100) {
// Two digit year
if (!allowTwoDigitYears) return null
val window = (currentYear + 50) % 100
if (year <= window) {
year + ((currentYear + 50) / 100) * 100
} else {
year + ((currentYear - 49) / 100) * 100
}
} else year
}
private val daysOfWeekCache = HashMap<Pair<Boolean, List<Locale>?>, List<String>>()
/**
* Returns a list of the localized days of the week.
* @param locales The locales to use for lookup. Use null for the user's locale.
*/
fun getDaysOfWeek(longFormat: Boolean, locales: List<Locale>? = null): List<String> {
val cacheKey = longFormat to locales
if (daysOfWeekCache.containsKey(cacheKey)) return daysOfWeekCache[cacheKey]!!
val list = ArrayList<String>(7)
val formatter = DateTimeFormatter(
weekday = if (longFormat) WeekdayFormat.LONG else WeekdayFormat.SHORT,
locales = locales
)
val d = Date(0)
val offset = d.dayOfMonth - d.dayOfWeek
for (i in 0..11) {
list.add(formatter.format(Date(year = 0, month = 1, day = i + offset)))
}
daysOfWeekCache[cacheKey] = list
return list
}
private val monthsOfYearCache = HashMap<Pair<Boolean, List<Locale>?>, List<String>>()
/**
* Returns a list of the localized months of the year.
*
* @param longFormat If true, the whole month names will be returned instead of the abbreviations.
* @param locales The locale chain to use for parsing. If this is null, then [com.acornui.system.UserInfo.currentLocale]
* will be used from [com.acornui.system.userInfo].
*/
fun getMonths(longFormat: Boolean, locales: List<Locale>? = null): List<String> {
val cacheKey = longFormat to locales
if (monthsOfYearCache.containsKey(cacheKey)) return monthsOfYearCache[cacheKey]!!
val list = ArrayList<String>(12)
val formatter = DateTimeFormatter(
month = if (longFormat) MonthFormat.LONG else MonthFormat.SHORT,
locales = locales
)
for (i in 1..12) {
list.add(formatter.format(Date(year = 0, month = i, day = 1)))
}
monthsOfYearCache[cacheKey] = list
return list
}
private fun String?.toJsValue(): String? {
if (this == null) return null
return if (this == "TWO_DIGIT") "2-digit" // Special case.
else toLowerCase().replace('_', ' ')
} | apache-2.0 | d4d1b56fc6a574ad2c6601f28fc3c95c | 20.205446 | 156 | 0.691688 | 3.27697 | false | false | false | false |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/MessageHelper.kt | 1 | 753 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
@NonNls
private const val IDEAVIM_BUNDLE = "messages.IdeaVimBundle"
object MessageHelper : DynamicBundle(IDEAVIM_BUNDLE) {
const val BUNDLE = IDEAVIM_BUNDLE
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any) = getMessage(key, *params)
@JvmStatic
fun message(@PropertyKey(resourceBundle = BUNDLE) key: String) = getMessage(key)
}
| mit | 67df62bd83c38012adda8866191f0a95 | 26.888889 | 111 | 0.766268 | 3.984127 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/component/HBoxBuilder.kt | 1 | 1992 | package org.hexworks.zircon.api.builder.component
import org.hexworks.zircon.api.component.HBox
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.internal.component.impl.DefaultHBox
import org.hexworks.zircon.internal.component.renderer.DefaultHBoxRenderer
import org.hexworks.zircon.internal.dsl.ZirconDsl
import kotlin.math.max
import kotlin.jvm.JvmStatic
@Suppress("UNCHECKED_CAST")
@ZirconDsl
class HBoxBuilder private constructor() : BaseContainerBuilder<HBox, HBoxBuilder>(DefaultHBoxRenderer()) {
var spacing: Int = 0
set(value) {
require(value >= 0) {
"Can't use a negative spacing"
}
field = value
}
fun withSpacing(spacing: Int) = also {
this.spacing = spacing
}
override fun build(): HBox {
return DefaultHBox(
componentMetadata = createMetadata(),
renderingStrategy = createRenderingStrategy(),
initialTitle = title,
spacing = spacing,
).apply {
addComponents(*childrenToAdd.toTypedArray())
}.attachListeners()
}
override fun createCopy() = newBuilder()
.withProps(props.copy())
.withSpacing(spacing)
.withChildren(*childrenToAdd.toTypedArray())
@Suppress("DuplicatedCode")
override fun calculateContentSize(): Size {
if (childrenToAdd.isEmpty()) {
return Size.one()
}
var width = 0
var maxHeight = 0
childrenToAdd
.map { it.size }
.forEach {
width += it.width
maxHeight = max(maxHeight, it.height)
}
if (spacing > 0) {
width += childrenToAdd.size * spacing - 1
}
return Size.create(max(1, width), maxHeight)
}
companion object {
@JvmStatic
fun newBuilder() = HBoxBuilder()
}
}
| apache-2.0 | e6f2b58229f7069680cdd6e7817cf3d2 | 28.294118 | 106 | 0.616968 | 4.742857 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/posts/BasicDialogViewModel.kt | 1 | 1994 | package org.wordpress.android.ui.posts
import android.annotation.SuppressLint
import android.os.Parcelable
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import kotlinx.parcelize.Parcelize
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Dismissed
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Negative
import org.wordpress.android.ui.posts.BasicDialogViewModel.DialogInteraction.Positive
import org.wordpress.android.viewmodel.Event
import javax.inject.Inject
class BasicDialogViewModel
@Inject constructor() : ViewModel() {
private val _onInteraction = MutableLiveData<Event<DialogInteraction>>()
val onInteraction = _onInteraction as LiveData<Event<DialogInteraction>>
fun showDialog(manager: FragmentManager, model: BasicDialogModel) {
val dialog = BasicDialog()
dialog.initialize(model)
dialog.show(manager, model.tag)
}
fun onPositiveClicked(tag: String) {
_onInteraction.postValue(Event(Positive(tag)))
}
fun onNegativeButtonClicked(tag: String) {
_onInteraction.postValue(Event(Negative(tag)))
}
fun onDismissByOutsideTouch(tag: String) {
_onInteraction.postValue(Event(Dismissed(tag)))
}
@Parcelize
@SuppressLint("ParcelCreator")
data class BasicDialogModel(
val tag: String,
val title: String? = null,
val message: String,
val positiveButtonLabel: String,
val negativeButtonLabel: String? = null,
val cancelButtonLabel: String? = null
) : Parcelable
sealed class DialogInteraction(open val tag: String) {
data class Positive(override val tag: String) : DialogInteraction(tag)
data class Negative(override val tag: String) : DialogInteraction(tag)
data class Dismissed(override val tag: String) : DialogInteraction(tag)
}
}
| gpl-2.0 | 65410ad785765b1c373dcd7f61fd193b | 35.925926 | 86 | 0.746239 | 4.781775 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/scopeFunctions/letToRun/qualifyThisWithLambda.kt | 9 | 218 | // WITH_STDLIB
class C {
fun foo() = "c"
val bar = "C"
}
class D {
fun foo() = "d"
val bar = "D"
}
val d = D()
val x = d.apply {
C().<caret>let {
foo() + it.foo() + bar + it.bar
}
}
| apache-2.0 | 9be4c5b4ca2a2959ee0f08da752081a4 | 10.473684 | 39 | 0.412844 | 2.422222 | false | false | false | false |
hermantai/samples | kotlin/Mastering-Kotlin-master/Chapter07/src/Main.kt | 1 | 453 | import authscreen.AuthScreen
fun main() {
val person = Person()
val programmer = Programmer("John", "Smith", "Kotlin")
programmer.preferredLanguage
programmer.firstName
printGreeting("Nate")
"message to log".log()
println(KEY_ID)
screenCount++
val result = AuthScreen.RESULT_AUTHENTICATED
val authScreen = AuthScreen() // wont compile
import authscreen.AuthScreen
val screen = AuthScreen.create()
} | apache-2.0 | 0a82bde16d74ee7889eb8c0b59ebf930 | 19.636364 | 58 | 0.684327 | 4.314286 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/ravkav/RavKavLookup.kt | 1 | 2359 | /*
* RavKavLookup.kt
*
* Copyright 2018 Google
*
* 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 au.id.micolous.metrodroid.transit.ravkav
import au.id.micolous.metrodroid.multi.FormattedString
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.transit.Station
import au.id.micolous.metrodroid.transit.TransitCurrency
import au.id.micolous.metrodroid.transit.Trip
import au.id.micolous.metrodroid.transit.en1545.En1545LookupSTR
import au.id.micolous.metrodroid.util.StationTableReader
private const val RAVKAV_STR = "ravkav"
internal object RavKavLookup : En1545LookupSTR(RAVKAV_STR) {
override val timeZone: MetroTimeZone
get() = MetroTimeZone.JERUSALEM
override fun getRouteName(routeNumber: Int?, routeVariant: Int?, agency: Int?, transport: Int?): FormattedString? {
if (routeNumber == null || routeNumber == 0)
return null
if (agency != null && agency == EGGED)
return FormattedString((routeNumber % 1000).toString())
return FormattedString(routeNumber.toString())
}
override fun parseCurrency(price: Int)= TransitCurrency.ILS(price)
// Irrelevant as RavKAv has EventCode
override fun getMode(agency: Int?, route: Int?): Trip.Mode = Trip.Mode.OTHER
private const val EGGED = 0x3
override val subscriptionMap = mapOf(
641 to R.string.ravkav_generic_trips // generic trips
)
override fun getStation(station: Int, agency: Int?, transport: Int?): Station? {
if (station == 0)
return null
return StationTableReader.getStation(
RAVKAV_STR,
station,
station.toString())
}
}
| gpl-3.0 | 22ee6ff0de13304c093c82cff25c93ce | 35.292308 | 119 | 0.710894 | 4.053265 | false | false | false | false |
bkmioa/NexusRss | app/src/main/java/io/github/bkmioa/nexusrss/download/RemoteDownloader.kt | 1 | 2908 | package io.github.bkmioa.nexusrss.download
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.os.Build
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import io.github.bkmioa.nexusrss.R
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
object RemoteDownloader {
fun download(context: Context, downloadNode: DownloadNode, torrentUrl: String, path: String? = null) {
download(context, DownloadTask(downloadNode, torrentUrl, path))
}
fun download(context: Context, downloadTask: DownloadTask) {
val app = context.applicationContext
Toast.makeText(context, R.string.downloading, Toast.LENGTH_SHORT).show()
val ignore = downloadTask.downloadNode.download(downloadTask.torrentUrl, downloadTask.path)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
Toast.makeText(app, it, Toast.LENGTH_SHORT).show()
}, {
it.printStackTrace()
showFailure(context, downloadTask, it.message)
Toast.makeText(app, it.message, Toast.LENGTH_SHORT).show()
})
}
private fun showFailure(context: Context, task: DownloadTask, message: String?) {
val code = task.torrentUrl.hashCode()
val downloadIntent = DownloadReceiver.createDownloadIntent(context, code, task)
var flag = PendingIntent.FLAG_UPDATE_CURRENT
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
flag = flag or PendingIntent.FLAG_IMMUTABLE
}
val retryIntent= PendingIntent.getBroadcast(context, code, downloadIntent, flag)
val retryAction = NotificationCompat.Action.Builder(R.drawable.ic_refresh, "retry", retryIntent)
.build()
val notification = NotificationCompat.Builder(context, createChannelIfNeeded(context))
.setSmallIcon(R.mipmap.ic_launcher)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setDefaults(0)
.setContentTitle("Download Failure")
.setContentText(message)
.setAutoCancel(true)
.addAction(retryAction)
.build()
NotificationManagerCompat.from(context)
.notify(code, notification)
}
private fun createChannelIfNeeded(context: Context): String {
val channelId = "download_state"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, "Download State", NotificationManager.IMPORTANCE_DEFAULT)
NotificationManagerCompat.from(context).createNotificationChannel(channel)
}
return channelId
}
} | apache-2.0 | 54670158b0169a026716419c713caaf8 | 40.557143 | 114 | 0.68879 | 4.81457 | false | false | false | false |
android/nowinandroid | core/designsystem/src/main/java/com/google/samples/apps/nowinandroid/core/designsystem/component/ViewToggle.kt | 1 | 2203 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.designsystem.component
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
/**
* Now in Android view toggle button with included trailing icon as well as compact and expanded
* text label content slots.
*
* @param expanded Whether the view toggle is currently in expanded mode or compact mode.
* @param onExpandedChange Called when the user clicks the button and toggles the mode.
* @param modifier Modifier to be applied to the button.
* @param enabled Controls the enabled state of the button. When `false`, this button will not be
* clickable and will appear disabled to accessibility services.
* @param compactText The text label content to show in expanded mode.
* @param expandedText The text label content to show in compact mode.
*/
@Composable
fun NiaViewToggleButton(
expanded: Boolean,
onExpandedChange: (Boolean) -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
compactText: @Composable () -> Unit,
expandedText: @Composable () -> Unit
) {
NiaTextButton(
onClick = { onExpandedChange(!expanded) },
modifier = modifier,
enabled = enabled,
text = if (expanded) expandedText else compactText,
trailingIcon = {
Icon(
imageVector = if (expanded) NiaIcons.ViewDay else NiaIcons.ShortText,
contentDescription = null
)
}
)
}
| apache-2.0 | 38701ca02567d9ed85f4694bc42c6bd4 | 37.649123 | 97 | 0.720381 | 4.608787 | false | false | false | false |
iPoli/iPoli-android | app/src/test/java/io/ipoli/android/challenge/usecase/CreateChallengeFromPresetUseCaseSpek.kt | 1 | 7826 | package io.ipoli.android.challenge.usecase
import io.ipoli.android.TestUtil
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.challenge.preset.PresetChallenge
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics.Gender
import io.ipoli.android.challenge.usecase.CreateChallengeFromPresetUseCase.PhysicalCharacteristics.Units
import io.ipoli.android.common.datetime.days
import io.ipoli.android.common.datetime.minutes
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.quest.Color
import io.ipoli.android.quest.Icon
import io.ipoli.android.repeatingquest.usecase.SaveQuestsForRepeatingQuestUseCase
import io.ipoli.android.repeatingquest.usecase.SaveRepeatingQuestUseCase
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should be in range`
import org.amshove.kluent.`should equal`
import org.amshove.kluent.mock
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.threeten.bp.LocalDate
import java.util.*
class CreateChallengeFromPresetUseCaseSpek : Spek({
describe("CreateChallengeFromPresetUseCase") {
fun createPresetChallenge(
quests: List<PresetChallenge.Quest> = emptyList(),
habits: List<PresetChallenge.Habit> = emptyList()
) =
PresetChallenge(
id = UUID.randomUUID().toString(),
name = "c",
color = Color.BLUE,
icon = Icon.ACADEMIC,
shortDescription = "",
description = "",
category = PresetChallenge.Category.ADVENTURE,
imageUrl = "",
duration = 30.days,
busynessPerWeek = 120.minutes,
difficulty = Challenge.Difficulty.EASY,
requirements = emptyList(),
level = 1,
trackedValues = emptyList(),
expectedResults = emptyList(),
gemPrice = 0,
note = "",
config = PresetChallenge.Config(),
schedule = PresetChallenge.Schedule(
quests = quests,
habits = habits
),
status = Post.Status.APPROVED,
author = null,
participantCount = 0
)
fun createNutritionChallenge() =
createPresetChallenge().copy(
config = createPresetChallenge().config.copy(
nutritionMacros = PresetChallenge.NutritionMacros(
female = PresetChallenge.NutritionDetails(
caloriesPerKg = 1f,
proteinPerKg = 1f,
carbohydratesPerKg = 1f,
fatPerKg = 1f
),
male = PresetChallenge.NutritionDetails(
caloriesPerKg = 1f,
proteinPerKg = 1f,
carbohydratesPerKg = 1f,
fatPerKg = 1f
)
)
)
)
fun executeUseCase(params: CreateChallengeFromPresetUseCase.Params): Challenge {
val sc = SaveChallengeUseCase(
TestUtil.challengeRepoMock(),
SaveQuestsForChallengeUseCase(
questRepository = TestUtil.questRepoMock(),
repeatingQuestRepository = TestUtil.repeatingQuestRepoMock(),
saveRepeatingQuestUseCase = SaveRepeatingQuestUseCase(
questRepository = TestUtil.questRepoMock(),
repeatingQuestRepository = TestUtil.repeatingQuestRepoMock(),
saveQuestsForRepeatingQuestUseCase = SaveQuestsForRepeatingQuestUseCase(
TestUtil.questRepoMock(),
mock()
),
reminderScheduler = mock()
)
),
TestUtil.habitRepoMock(null)
)
return CreateChallengeFromPresetUseCase(sc, mock()).execute(params)
}
it("should create Challenge with Quests") {
val pc = createPresetChallenge(
quests = listOf(
PresetChallenge.Quest(
name = "q1",
color = Color.BLUE,
icon = Icon.ACADEMIC,
day = 1,
duration = 30.minutes,
subQuests = emptyList(),
note = ""
)
)
)
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule
)
)
c.quests.size.`should be equal to`(1)
c.quests.first().scheduledDate.`should equal`(LocalDate.now())
}
it("should create Challenge with Habits") {
val pc = createPresetChallenge(
habits = listOf(
PresetChallenge.Habit(
name = "q1",
color = Color.BLUE,
icon = Icon.ACADEMIC,
isGood = true,
timesADay = 3,
isSelected = true
)
)
)
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule
)
)
c.habits.size.`should be equal to`(1)
c.habits.first().timesADay.`should be equal to`(3)
}
it("should create Challenge that tracks weight") {
val pc = createNutritionChallenge()
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule,
playerPhysicalCharacteristics = CreateChallengeFromPresetUseCase.PhysicalCharacteristics(
units = Units.METRIC,
gender = Gender.FEMALE,
weight = 60,
targetWeight = 50
)
)
)
val t =
c.trackedValues
.asSequence()
.filterIsInstance(Challenge.TrackedValue.Target::class.java)
.first()
t.startValue.`should be in range`(59.99, 60.01)
t.targetValue.`should be in range`(49.99, 50.01)
}
it("should create Challenge that tracks macros") {
val pc = createNutritionChallenge()
val c = executeUseCase(
CreateChallengeFromPresetUseCase.Params(
preset = pc,
schedule = pc.schedule,
playerPhysicalCharacteristics = CreateChallengeFromPresetUseCase.PhysicalCharacteristics(
units = Units.METRIC,
gender = Gender.FEMALE,
weight = 60,
targetWeight = 50
)
)
)
val atvs =
c.trackedValues
.filterIsInstance(Challenge.TrackedValue.Average::class.java)
atvs.size.`should be equal to`(4)
atvs.forEach {
it.targetValue.`should be in range`(59.99, 60.01)
}
}
}
})
| gpl-3.0 | 8941f9d430c782bf090697e6aa1a5f88 | 36.806763 | 109 | 0.508433 | 6.085537 | false | false | false | false |
spinnaker/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/OrcaMessageHandler.kt | 1 | 5426 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.fasterxml.jackson.databind.ObjectMapper
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.PipelineExecution
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.api.pipeline.models.TaskExecution
import com.netflix.spinnaker.orca.exceptions.ExceptionHandler
import com.netflix.spinnaker.orca.ext.parent
import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper
import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionNotFoundException
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria
import com.netflix.spinnaker.orca.q.CompleteExecution
import com.netflix.spinnaker.orca.q.ContinueParentStage
import com.netflix.spinnaker.orca.q.ExecutionLevel
import com.netflix.spinnaker.orca.q.InvalidExecutionId
import com.netflix.spinnaker.orca.q.InvalidStageId
import com.netflix.spinnaker.orca.q.InvalidTaskId
import com.netflix.spinnaker.orca.q.StageLevel
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.TaskLevel
import com.netflix.spinnaker.q.Message
import com.netflix.spinnaker.q.MessageHandler
import java.time.Duration
import org.slf4j.Logger
import org.slf4j.LoggerFactory
internal interface OrcaMessageHandler<M : Message> : MessageHandler<M> {
companion object {
val log: Logger = LoggerFactory.getLogger(this::class.java)
val mapper: ObjectMapper = OrcaObjectMapper.getInstance()
val MIN_PAGE_SIZE = 2
}
val repository: ExecutionRepository
fun Collection<ExceptionHandler>.shouldRetry(ex: Exception, taskName: String?): ExceptionHandler.Response? {
val exceptionHandler = find { it.handles(ex) }
return exceptionHandler?.handle(taskName ?: "unspecified", ex)
}
fun TaskLevel.withTask(block: (StageExecution, TaskExecution) -> Unit) =
withStage { stage ->
stage
.taskById(taskId)
.let { task ->
if (task == null) {
log.error("InvalidTaskId: Unable to find task {} in stage '{}' while processing message {}", taskId, mapper.writeValueAsString(stage), this)
queue.push(InvalidTaskId(this))
} else {
block.invoke(stage, task)
}
}
}
fun StageLevel.withStage(block: (StageExecution) -> Unit) =
withExecution { execution ->
try {
execution
.stageById(stageId)
.also {
/**
* Mutates it.context in a required way (such as removing refId and requisiteRefIds from the
* context map) for some non-linear stage features.
*/
StageExecutionImpl(execution, it.type, it.context)
}
.let(block)
} catch (e: IllegalArgumentException) {
log.error("Failed to locate stage with id: {}", stageId, e)
queue.push(InvalidStageId(this))
}
}
fun ExecutionLevel.withExecution(block: (PipelineExecution) -> Unit) =
try {
val execution = repository.retrieve(executionType, executionId)
block.invoke(execution)
} catch (e: ExecutionNotFoundException) {
queue.push(InvalidExecutionId(this))
}
fun StageExecution.startNext() {
execution.let { execution ->
val downstreamStages = downstreamStages()
val phase = syntheticStageOwner
if (downstreamStages.isNotEmpty()) {
downstreamStages.forEach {
queue.push(StartStage(it))
}
} else if (phase != null) {
queue.ensure(ContinueParentStage(parent(), phase), Duration.ZERO)
} else {
queue.push(CompleteExecution(execution))
}
}
}
fun PipelineExecution.shouldQueue(): Boolean {
val configId = pipelineConfigId
return when {
configId == null -> false
!isLimitConcurrent -> {
return when {
maxConcurrentExecutions > 0 -> {
val criteria = ExecutionCriteria().setPageSize(maxConcurrentExecutions+MIN_PAGE_SIZE).setStatuses(RUNNING)
repository
.retrievePipelinesForPipelineConfigId(configId, criteria)
.filter { it.id != id }
.count()
.toBlocking()
.first() >= maxConcurrentExecutions
}
else -> false
}
}
else -> {
val criteria = ExecutionCriteria().setPageSize(MIN_PAGE_SIZE).setStatuses(RUNNING)
repository
.retrievePipelinesForPipelineConfigId(configId, criteria)
.filter { it.id != id }
.count()
.toBlocking()
.first() > 0
}
}
}
}
| apache-2.0 | 709bdaa4f69aaad4b1bf1b2b1ffe1f99 | 36.164384 | 152 | 0.692407 | 4.555835 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/ToggleAmendCommitOption.kt | 1 | 1322 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.ui.components.JBCheckBox
import org.jetbrains.annotations.ApiStatus
import java.awt.event.KeyEvent
@ApiStatus.Internal
class ToggleAmendCommitOption(commitPanel: CheckinProjectPanel, parent: Disposable) : JBCheckBox(VcsBundle.message("commit.amend.commit")) {
private val amendCommitHandler = commitPanel.commitWorkflowHandler.amendCommitHandler
init {
mnemonic = KeyEvent.VK_M
toolTipText = VcsBundle.message("commit.tooltip.merge.this.commit.with.the.previous.one")
addActionListener { amendCommitHandler.isAmendCommitMode = isSelected }
amendCommitHandler.addAmendCommitModeListener(object : AmendCommitModeListener {
override fun amendCommitModeToggled() {
isSelected = amendCommitHandler.isAmendCommitMode
}
}, parent)
}
companion object {
@JvmStatic
fun isAmendCommitOptionSupported(commitPanel: CheckinProjectPanel, amendAware: AmendCommitAware) =
!commitPanel.isNonModalCommit && amendAware.isAmendCommitSupported()
}
} | apache-2.0 | 3e2081bbfffe61bcb155a3b34ebcd964 | 40.34375 | 140 | 0.795008 | 4.755396 | false | false | false | false |
Qase/KotlinLogger | app/src/androidTest/java/quanti/com/kotlinlog3/MainActivity.kt | 1 | 4794 | package quanti.com.kotlinlog3
import android.content.Context
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import org.junit.Assert
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import quanti.com.kotlinlog.file.file.DayLogFile
import quanti.com.kotlinlog.utils.logFilesDir
import java.io.File
@RunWith(AndroidJUnit4::class)
@LargeTest
class HelloWorldEspressoTest {
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
private lateinit var appCtx: Context
private lateinit var file: File
@Before
fun init() {
appCtx = activityRule.activity.applicationContext
onView(withId(R.id.delete)).perform(click())
val dayFile = DayLogFile(appCtx, 7)
file = File(appCtx.filesDir, dayFile.fileName)
}
@Test
fun button_hitme() {
onView(withId(R.id.hitme)).perform(click())
//sleep to force write
Thread.sleep(6000L)
val any = file
.readLines()
.map { it.contains(RANDOM_TEXT) }
.any()
Assert.assertEquals(true, any)
}
@Test
fun button_test1() {
onView(withId(R.id.test1)).perform(click())
//sleep to force write
Thread.sleep(6000L)
val count = file
.readLines()
.count()
Assert.assertEquals(50, count)
}
@Test
fun button_test2() {
onView(withId(R.id.test2)).perform(click())
//sleep to force write
Thread.sleep(6000L)
val count = file
.readLines()
.count()
Assert.assertEquals(5000, count)
}
@Test
fun button_test3() {
onView(withId(R.id.test3)).perform(click())
//wait some time for everything to happen
Thread.sleep(6000L)
val count = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("ArrayIndexOutOf") }
.count()
Assert.assertTrue("At least one handled exception file should be present.", count >= 1)
}
@Test
fun button_test4() {
onView(withId(R.id.throwu)).perform(click())
//wait some time for everything to happen
Thread.sleep(6000L)
val count = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("unhandled") }
.count()
Assert.assertTrue("At least one handled exception file should be present.", count >= 1)
}
@Test
fun button_testStrictCircle() {
onView(withId(R.id.switchButton))
.perform(click())
.perform(click())
onView(withId(R.id.test2))
.perform(click())
.perform(click())
.perform(click())
.perform(click())
.perform(click())
//wait some time for everything to happen
Thread.sleep(12000L)
val filtered = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("strictcircle") }
val countFull = filtered.count { it.length() > 1022 * 1024 }
val countEmpty = filtered.count() - countFull
Assert.assertEquals("There should be two full files.", 2, countFull)
Assert.assertEquals("There should be one opened file.", 1, countEmpty)
}
@Test
fun button_testStrictCircleDeletesOldFiles() {
onView(withId(R.id.switchButton))
.perform(click())
.perform(click())
//write huge amount of data
onView(withId(R.id.test2))
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
.perform(click()).perform(click()).perform(click())
//wait some time for everything to happen
Thread.sleep(12000L)
val count = appCtx
.logFilesDir
.listFiles()
.filter { it.name.contains("strictcircle") }
.count()
Assert.assertEquals("There should be 4 files.", 4, count)
}
}
| mit | 8a9b48246f16020333ceba0fa2ca6b3f | 26.551724 | 95 | 0.580309 | 4.447124 | false | true | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/track/job/DelayedTrackingUpdateJob.kt | 2 | 2757 | package eu.kanade.tachiyomi.data.track.job
import android.content.Context
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.CoroutineWorker
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.WorkerParameters
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.track.TrackManager
import eu.kanade.tachiyomi.util.system.logcat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import logcat.LogPriority
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.TimeUnit
class DelayedTrackingUpdateJob(context: Context, workerParams: WorkerParameters) :
CoroutineWorker(context, workerParams) {
override suspend fun doWork(): Result {
val db = Injekt.get<DatabaseHelper>()
val trackManager = Injekt.get<TrackManager>()
val delayedTrackingStore = Injekt.get<DelayedTrackingStore>()
withContext(Dispatchers.IO) {
val tracks = delayedTrackingStore.getItems().mapNotNull {
val manga = db.getManga(it.mangaId).executeAsBlocking() ?: return@withContext
db.getTracks(manga).executeAsBlocking()
.find { track -> track.id == it.trackId }
?.also { track ->
track.last_chapter_read = it.lastChapterRead
}
}
tracks.forEach { track ->
try {
val service = trackManager.getService(track.sync_id)
if (service != null && service.isLogged) {
service.update(track, true)
db.insertTrack(track).executeAsBlocking()
}
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
}
}
delayedTrackingStore.clear()
}
return Result.success()
}
companion object {
private const val TAG = "DelayedTrackingUpdate"
fun setupTask(context: Context) {
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val request = OneTimeWorkRequestBuilder<DelayedTrackingUpdateJob>()
.setConstraints(constraints)
.setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 20, TimeUnit.SECONDS)
.addTag(TAG)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(TAG, ExistingWorkPolicy.REPLACE, request)
}
}
}
| apache-2.0 | 0b780257c060cfa611aba703c760cb60 | 35.276316 | 93 | 0.635836 | 5.26145 | false | false | false | false |
ihsanbal/LoggingInterceptor | lib/src/main/java/com/ihsanbal/logging/Printer.kt | 1 | 12931 | package com.ihsanbal.logging
import okhttp3.Headers
import okhttp3.RequestBody
import okhttp3.Response
import okhttp3.internal.http.promisesBody
import okio.Buffer
import okio.GzipSource
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.io.EOFException
import java.io.IOException
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
/**
* @author ihsan on 09/02/2017.
*/
class Printer private constructor() {
companion object {
private const val JSON_INDENT = 3
private val LINE_SEPARATOR = System.getProperty("line.separator")
private val DOUBLE_SEPARATOR = LINE_SEPARATOR + LINE_SEPARATOR
private const val N = "\n"
private const val T = "\t"
private const val REQUEST_UP_LINE = "┌────── Request ────────────────────────────────────────────────────────────────────────"
private const val END_LINE = "└───────────────────────────────────────────────────────────────────────────────────────"
private const val RESPONSE_UP_LINE = "┌────── Response ───────────────────────────────────────────────────────────────────────"
private const val BODY_TAG = "Body:"
private const val URL_TAG = "URL: "
private const val METHOD_TAG = "Method: @"
private const val HEADERS_TAG = "Headers:"
private const val STATUS_CODE_TAG = "Status Code: "
private const val RECEIVED_TAG = "Received in: "
private const val DEFAULT_LINE = "│ "
private val OOM_OMITTED = LINE_SEPARATOR + "Output omitted because of Object size."
private fun isEmpty(line: String): Boolean {
return line.isEmpty() || N == line || T == line || line.trim { it <= ' ' }.isEmpty()
}
fun printJsonRequest(builder: LoggingInterceptor.Builder, body: RequestBody?, url: String, header: Headers, method: String) {
val requestBody = body?.let {
LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + bodyToString(body, header)
} ?: ""
val tag = builder.getTag(true)
if (builder.logger == null) I.log(builder.type, tag, REQUEST_UP_LINE, builder.isLogHackEnable)
logLines(builder.type, tag, arrayOf(URL_TAG + url), builder.logger, false, builder.isLogHackEnable)
logLines(builder.type, tag, getRequest(builder.level, header, method), builder.logger, true, builder.isLogHackEnable)
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(builder.type, tag, requestBody.split(LINE_SEPARATOR).toTypedArray(), builder.logger, true, builder.isLogHackEnable)
}
if (builder.logger == null) I.log(builder.type, tag, END_LINE, builder.isLogHackEnable)
}
fun printJsonResponse(builder: LoggingInterceptor.Builder, chainMs: Long, isSuccessful: Boolean,
code: Int, headers: Headers, response: Response, segments: List<String>, message: String, responseUrl: String) {
val responseBody = LINE_SEPARATOR + BODY_TAG + LINE_SEPARATOR + getResponseBody(response)
val tag = builder.getTag(false)
val urlLine = arrayOf(URL_TAG + responseUrl, N)
val responseString = getResponse(headers, chainMs, code, isSuccessful,
builder.level, segments, message)
if (builder.logger == null) {
I.log(builder.type, tag, RESPONSE_UP_LINE, builder.isLogHackEnable)
}
logLines(builder.type, tag, urlLine, builder.logger, true, builder.isLogHackEnable)
logLines(builder.type, tag, responseString, builder.logger, true, builder.isLogHackEnable)
if (builder.level == Level.BASIC || builder.level == Level.BODY) {
logLines(builder.type, tag, responseBody.split(LINE_SEPARATOR).toTypedArray(), builder.logger,
true, builder.isLogHackEnable)
}
if (builder.logger == null) {
I.log(builder.type, tag, END_LINE, builder.isLogHackEnable)
}
}
private fun getResponseBody(response: Response): String {
val responseBody = response.body!!
val headers = response.headers
val contentLength = responseBody.contentLength()
if (!response.promisesBody()) {
return "End request - Promises Body"
} else if (bodyHasUnknownEncoding(response.headers)) {
return "encoded body omitted"
} else {
val source = responseBody.source()
source.request(Long.MAX_VALUE) // Buffer the entire body.
var buffer = source.buffer
var gzippedLength: Long? = null
if ("gzip".equals(headers["Content-Encoding"], ignoreCase = true)) {
gzippedLength = buffer.size
GzipSource(buffer.clone()).use { gzippedResponseBody ->
buffer = Buffer()
buffer.writeAll(gzippedResponseBody)
}
}
val contentType = responseBody.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8)
?: StandardCharsets.UTF_8
if (!buffer.isProbablyUtf8()) {
return "End request - binary ${buffer.size}:byte body omitted"
}
if (contentLength != 0L) {
return getJsonString(buffer.clone().readString(charset))
}
return if (gzippedLength != null) {
"End request - ${buffer.size}:byte, $gzippedLength-gzipped-byte body"
} else {
"End request - ${buffer.size}:byte body"
}
}
}
private fun getRequest(level: Level, headers: Headers, method: String): Array<String> {
val log: String
val loggableHeader = level == Level.HEADERS || level == Level.BASIC
log = METHOD_TAG + method + DOUBLE_SEPARATOR +
if (isEmpty("$headers")) "" else if (loggableHeader) HEADERS_TAG + LINE_SEPARATOR + dotHeaders(headers) else ""
return log.split(LINE_SEPARATOR).toTypedArray()
}
private fun getResponse(headers: Headers, tookMs: Long, code: Int, isSuccessful: Boolean,
level: Level, segments: List<String>, message: String): Array<String> {
val log: String
val loggableHeader = level == Level.HEADERS || level == Level.BASIC
val segmentString = slashSegments(segments)
log = ((if (segmentString.isNotEmpty()) "$segmentString - " else "") + "[is success : "
+ isSuccessful + "] - " + RECEIVED_TAG + tookMs + "ms" + DOUBLE_SEPARATOR + STATUS_CODE_TAG +
code + " / " + message + DOUBLE_SEPARATOR + when {
isEmpty("$headers") -> ""
loggableHeader -> HEADERS_TAG + LINE_SEPARATOR +
dotHeaders(headers)
else -> ""
})
return log.split(LINE_SEPARATOR).toTypedArray()
}
private fun slashSegments(segments: List<String>): String {
val segmentString = StringBuilder()
for (segment in segments) {
segmentString.append("/").append(segment)
}
return segmentString.toString()
}
private fun dotHeaders(headers: Headers): String {
val builder = StringBuilder()
headers.forEach { pair ->
builder.append("${pair.first}: ${pair.second}").append(N)
}
return builder.dropLast(1).toString()
}
private fun logLines(type: Int, tag: String, lines: Array<String>, logger: Logger?,
withLineSize: Boolean, useLogHack: Boolean) {
for (line in lines) {
val lineLength = line.length
val maxLogSize = if (withLineSize) 110 else lineLength
for (i in 0..lineLength / maxLogSize) {
val start = i * maxLogSize
var end = (i + 1) * maxLogSize
end = if (end > line.length) line.length else end
if (logger == null) {
I.log(type, tag, DEFAULT_LINE + line.substring(start, end), useLogHack)
} else {
logger.log(type, tag, line.substring(start, end))
}
}
}
}
private fun bodyToString(requestBody: RequestBody?, headers: Headers): String {
return requestBody?.let {
return try {
when {
bodyHasUnknownEncoding(headers) -> {
return "encoded body omitted)"
}
requestBody.isDuplex() -> {
return "duplex request body omitted"
}
requestBody.isOneShot() -> {
return "one-shot body omitted"
}
else -> {
val buffer = Buffer()
requestBody.writeTo(buffer)
val contentType = requestBody.contentType()
val charset: Charset = contentType?.charset(StandardCharsets.UTF_8)
?: StandardCharsets.UTF_8
return if (buffer.isProbablyUtf8()) {
getJsonString(buffer.readString(charset)) + LINE_SEPARATOR + "${requestBody.contentLength()}-byte body"
} else {
"binary ${requestBody.contentLength()}-byte body omitted"
}
}
}
} catch (e: IOException) {
"{\"err\": \"" + e.message + "\"}"
}
} ?: ""
}
private fun bodyHasUnknownEncoding(headers: Headers): Boolean {
val contentEncoding = headers["Content-Encoding"] ?: return false
return !contentEncoding.equals("identity", ignoreCase = true) &&
!contentEncoding.equals("gzip", ignoreCase = true)
}
private fun getJsonString(msg: String): String {
val message: String
message = try {
when {
msg.startsWith("{") -> {
val jsonObject = JSONObject(msg)
jsonObject.toString(JSON_INDENT)
}
msg.startsWith("[") -> {
val jsonArray = JSONArray(msg)
jsonArray.toString(JSON_INDENT)
}
else -> {
msg
}
}
} catch (e: JSONException) {
msg
} catch (e1: OutOfMemoryError) {
OOM_OMITTED
}
return message
}
fun printFailed(tag: String, builder: LoggingInterceptor.Builder) {
I.log(builder.type, tag, RESPONSE_UP_LINE, builder.isLogHackEnable)
I.log(builder.type, tag, DEFAULT_LINE + "Response failed", builder.isLogHackEnable)
I.log(builder.type, tag, END_LINE, builder.isLogHackEnable)
}
}
init {
throw UnsupportedOperationException()
}
}
/**
* @see 'https://github.com/square/okhttp/blob/master/okhttp-logging-interceptor/src/main/java/okhttp3/logging/utf8.kt'
* */
internal fun Buffer.isProbablyUtf8(): Boolean {
try {
val prefix = Buffer()
val byteCount = size.coerceAtMost(64)
copyTo(prefix, 0, byteCount)
for (i in 0 until 16) {
if (prefix.exhausted()) {
break
}
val codePoint = prefix.readUtf8CodePoint()
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false
}
}
return true
} catch (_: EOFException) {
return false // Truncated UTF-8 sequence.
}
} | mit | dad20f5d615eeeeabe5861b47c2bdada | 44.40146 | 142 | 0.525685 | 5.075071 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/login/LoginActivity.kt | 1 | 3343 | package com.tungnui.dalatlaptop.ux.login
import android.support.design.widget.TabLayout
import android.support.v7.app.AppCompatActivity
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.os.Bundle
import android.view.MenuItem
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.SettingsMy
import com.tungnui.dalatlaptop.interfaces.LoginDialogInterface
import com.tungnui.dalatlaptop.models.Customer
import com.tungnui.dalatlaptop.ux.MainActivity
import com.tungnui.dalatlaptop.ux.MainActivity.Companion.LOGIN_RESULT_CODE
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity : AppCompatActivity() {
/**
* The [android.support.v4.view.PagerAdapter] that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* [android.support.v4.app.FragmentStatePagerAdapter].
*/
private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
private var loginDialogInterface: LoginDialogInterface? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
this.title = "Đăng nhập/ Đăng kí"
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
// Set up the ViewPager with the sections adapter.
container.adapter = mSectionsPagerAdapter
container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs))
tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.itemId){
android.R.id.home ->{
this.finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
inner class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
override fun getItem(position: Int): Fragment {
return when(position){
0 -> LoginFragment()
else -> RegisterFragment()
}
}
override fun getCount(): Int {
// Show 3 total pages.
return 2
}
}
fun handleUserLogin(customer: Customer) {
SettingsMy.setActiveUser(customer)
MainActivity.invalidateDrawerMenuHeader()
if (loginDialogInterface != null) {
loginDialogInterface?.successfulLoginOrRegistration(customer)
}
setResult(LOGIN_RESULT_CODE,intent)
this.finish()
}
companion object {
fun logoutUser() {
SettingsMy.setActiveUser(null)
MainActivity.invalidateDrawerMenuHeader()
}
}
}
| mit | def5ca51ac038f716a48b9da108be25b | 30.771429 | 90 | 0.692146 | 5.031674 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/migration/MigrateExperimentalToRequiresOptInFix.kt | 3 | 4538 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.migration
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.base.fe10.analysis.getEnumValue
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors.DEPRECATION
import org.jetbrains.kotlin.diagnostics.Errors.DEPRECATION_ERROR
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.inspections.RemoveAnnotationFix
import org.jetbrains.kotlin.idea.quickfix.CleanupFix
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.idea.util.addAnnotation
import org.jetbrains.kotlin.idea.util.findAnnotation
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* The quick fix to replace a deprecated `@Experimental` annotation with the new `@RequiresOptIn` annotation.
*/
class MigrateExperimentalToRequiresOptInFix(
annotationEntry: KtAnnotationEntry,
private val requiresOptInInnerText: String?
) : KotlinQuickFixAction<KtAnnotationEntry>(annotationEntry), CleanupFix {
override fun getText(): String = KotlinBundle.message("fix.opt_in.migrate.experimental.annotation.replace")
override fun getFamilyName(): String = KotlinBundle.message("fix.opt_in.migrate.experimental.annotation.replace")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val oldAnnotationEntry = element ?: return
val owner = oldAnnotationEntry.getStrictParentOfType<KtModifierListOwner>() ?: return
val added = owner.addAnnotation(
OptInNames.REQUIRES_OPT_IN_FQ_NAME,
requiresOptInInnerText,
useSiteTarget = null,
searchForExistingEntry = false // We don't want to resolve existing annotations in the write action
)
if (added) oldAnnotationEntry.delete()
}
/**
* Quick fix factory to create remove/replace quick fixes for deprecated `@Experimental` annotations.
*
* If the annotated expression has both `@Experimental` annotation and `@RequiresOptIn` annotation,
* the "Remove annotation" action is proposed to get rid of the obsolete `@Experimental` annotation
* (we don't check if the `level` arguments match in both annotations).
*
* If there is only an `@Experimental` annotation, the factory generates a "Replace annotation" quick fix
* that removes the `@Experimental` annotation and creates a `@RequiresOptIn` annotation
* with the matching value of the `level` argument.
*/
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory !in setOf(DEPRECATION, DEPRECATION_ERROR)) return null
val constructorCallee = diagnostic.psiElement.getStrictParentOfType<KtConstructorCalleeExpression>() ?: return null
val annotationEntry = constructorCallee.parent?.safeAs<KtAnnotationEntry>() ?: return null
val annotationDescriptor = annotationEntry.resolveToDescriptorIfAny() ?: return null
if (annotationDescriptor.fqName == OptInNames.OLD_EXPERIMENTAL_FQ_NAME) {
val annotationOwner = annotationEntry.getStrictParentOfType<KtModifierListOwner>() ?: return null
if (annotationOwner.findAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME) != null)
return RemoveAnnotationFix(KotlinBundle.message("fix.opt_in.migrate.experimental.annotation.remove"), annotationEntry)
val requiresOptInInnerText = when (annotationDescriptor.getEnumValue("level")?.enumEntryName?.asString()) {
"ERROR" -> "level = RequiresOptIn.Level.ERROR"
"WARNING" -> "level = RequiresOptIn.Level.WARNING"
else -> null
}
return MigrateExperimentalToRequiresOptInFix(annotationEntry, requiresOptInInnerText)
}
return null
}
}
}
| apache-2.0 | 5417b1a6d8a729e7794bc197af07353d | 55.725 | 158 | 0.742398 | 5.127684 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/git/src/org/jetbrains/kotlin/idea/git/KotlinExplicitMovementProvider.kt | 2 | 1767 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.git
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Couple
import com.intellij.openapi.vcs.FilePath
import git4idea.checkin.GitCheckinExplicitMovementProvider
import org.jetbrains.kotlin.idea.base.codeInsight.pathBeforeJavaToKotlinConversion
import java.util.*
class KotlinExplicitMovementProvider : GitCheckinExplicitMovementProvider() {
override fun isEnabled(project: Project): Boolean {
return true
}
override fun getDescription(): String {
return KotlinGitBundle.message("j2k.extra.commit.description")
}
override fun getCommitMessage(oldCommitMessage: String): String {
return KotlinGitBundle.message("j2k.extra.commit.commit.message")
}
override fun collectExplicitMovements(
project: Project,
beforePaths: List<FilePath>,
afterPaths: List<FilePath>
): Collection<Movement> {
val movedChanges = ArrayList<Movement>()
for (after in afterPaths) {
val pathBeforeJ2K = after.virtualFile?.pathBeforeJavaToKotlinConversion
if (pathBeforeJ2K != null) {
val before = beforePaths.firstOrNull { it.path == pathBeforeJ2K }
if (before != null) {
movedChanges.add(Movement(before, after))
}
}
}
return movedChanges
}
override fun afterMovementsCommitted(project: Project, movedPaths: MutableList<Couple<FilePath>>) {
movedPaths.forEach { it.second.virtualFile?.pathBeforeJavaToKotlinConversion = null }
}
}
| apache-2.0 | 1566ec52e3bc5bef52d32a28cdd7942f | 36.595745 | 158 | 0.699491 | 4.601563 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/ActColumnList.kt | 1 | 11931 | package jp.juggler.subwaytooter
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.woxthebox.draglistview.DragItem
import com.woxthebox.draglistview.DragItemAdapter
import com.woxthebox.draglistview.DragListView
import com.woxthebox.draglistview.swipe.ListSwipeHelper
import com.woxthebox.draglistview.swipe.ListSwipeItem
import jp.juggler.subwaytooter.api.entity.Acct
import jp.juggler.subwaytooter.column.ColumnEncoder
import jp.juggler.subwaytooter.column.ColumnType
import jp.juggler.util.*
class ActColumnList : AppCompatActivity() {
companion object {
private val log = LogCategory("ActColumnList")
internal const val TMP_FILE_COLUMN_LIST = "tmp_column_list"
const val EXTRA_ORDER = "order"
const val EXTRA_SELECTION = "selection"
fun createIntent(activity: ActMain, currentItem: Int) =
Intent(activity, ActColumnList::class.java).apply {
val array = activity.appState.encodeColumnList()
AppState.saveColumnList(activity, TMP_FILE_COLUMN_LIST, array)
putExtra(EXTRA_SELECTION, currentItem)
}
}
private lateinit var listView: DragListView
private lateinit var listAdapter: MyListAdapter
private var oldSelection: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
backPressed {
makeResult(-1)
finish()
}
App1.setActivityTheme(this)
initUI()
if (savedInstanceState != null) {
restoreData(savedInstanceState.getInt(EXTRA_SELECTION))
} else {
val intent = intent
restoreData(intent.getIntExtra(EXTRA_SELECTION, -1))
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(EXTRA_SELECTION, oldSelection)
val array = listAdapter.itemList.map { it.json }.toJsonArray()
AppState.saveColumnList(this, TMP_FILE_COLUMN_LIST, array)
}
private fun initUI() {
setContentView(R.layout.act_column_list)
App1.initEdgeToEdge(this)
Styler.fixHorizontalPadding0(findViewById(R.id.llContent))
// リストのアダプター
listAdapter = MyListAdapter()
// ハンドル部分をドラッグで並べ替えできるRecyclerView
listView = findViewById(R.id.drag_list_view)
listView.setLayoutManager(androidx.recyclerview.widget.LinearLayoutManager(this))
listView.setAdapter(listAdapter, true)
listView.setCanDragHorizontally(false)
listView.setCustomDragItem(MyDragItem(this, R.layout.lv_column_list))
listView.recyclerView.isVerticalScrollBarEnabled = true
listView.setDragListListener(object : DragListView.DragListListenerAdapter() {
override fun onItemDragStarted(position: Int) {
// 操作中はリフレッシュ禁止
// mRefreshLayout.setEnabled( false );
}
override fun onItemDragEnded(fromPosition: Int, toPosition: Int) {
// 操作完了でリフレッシュ許可
// mRefreshLayout.setEnabled( USE_SWIPE_REFRESH );
// if( fromPosition != toPosition ){
// // 並べ替えが発生した
// }
}
})
// リストを左右スワイプした
listView.setSwipeListener(object : ListSwipeHelper.OnSwipeListenerAdapter() {
override fun onItemSwipeStarted(item: ListSwipeItem) {
// 操作中はリフレッシュ禁止
// mRefreshLayout.setEnabled( false );
}
override fun onItemSwipeEnded(
item: ListSwipeItem,
swipedDirection: ListSwipeItem.SwipeDirection?,
) {
// 操作完了でリフレッシュ許可
// mRefreshLayout.setEnabled( USE_SWIPE_REFRESH );
// 左にスワイプした(右端に青が見えた) なら要素を削除する
if (swipedDirection == ListSwipeItem.SwipeDirection.LEFT) {
val adapterItem = item.tag as MyItem
if (adapterItem.json.optBoolean(ColumnEncoder.KEY_DONT_CLOSE, false)) {
showToast(false, R.string.column_has_dont_close_option)
listView.resetSwipedViews(null)
return
}
listAdapter.removeItem(listAdapter.getPositionForItem(adapterItem))
}
}
})
}
private fun restoreData(ivSelection: Int) {
this.oldSelection = ivSelection
val tmpList = ArrayList<MyItem>()
try {
AppState.loadColumnList(this, TMP_FILE_COLUMN_LIST)
?.objectList()
?.forEachIndexed { index, src ->
try {
val item = MyItem(src, index.toLong(), this)
tmpList.add(item)
if (oldSelection == item.oldIndex) {
item.setOldSelection(true)
}
} catch (ex: Throwable) {
log.trace(ex)
}
}
} catch (ex: Throwable) {
log.trace(ex)
}
listAdapter.itemList = tmpList
}
private fun makeResult(newSelection: Int) {
val intent = Intent()
val itemList = listAdapter.itemList
// どの要素を選択するか
if (newSelection >= 0 && newSelection < listAdapter.itemCount) {
intent.putExtra(EXTRA_SELECTION, newSelection)
} else {
var i = 0
val ie = itemList.size
while (i < ie) {
if (itemList[i].bOldSelection) {
intent.putExtra(EXTRA_SELECTION, i)
break
}
++i
}
}
// 並べ替え用データ
val orderList = ArrayList<Int>()
for (item in itemList) {
orderList.add(item.oldIndex)
}
intent.putExtra(EXTRA_ORDER, orderList)
setResult(Activity.RESULT_OK, intent)
}
private fun performItemSelected(item: MyItem) {
val idx = listAdapter.getPositionForItem(item)
makeResult(idx)
finish()
}
// リスト要素のデータ
internal class MyItem(val json: JsonObject, val id: Long, context: Context) {
val name: String = json.optString(ColumnEncoder.KEY_COLUMN_NAME)
val acct: Acct = Acct.parse(json.optString(ColumnEncoder.KEY_COLUMN_ACCESS_ACCT))
val acctName: String = json.optString(ColumnEncoder.KEY_COLUMN_ACCESS_STR)
val oldIndex = json.optInt(ColumnEncoder.KEY_OLD_INDEX)
val type = ColumnType.parse(json.optInt(ColumnEncoder.KEY_TYPE))
val acctColorBg = json.optInt(ColumnEncoder.KEY_COLUMN_ACCESS_COLOR_BG, 0)
val acctColorFg = json.optInt(ColumnEncoder.KEY_COLUMN_ACCESS_COLOR, 0)
.notZero() ?: context.attrColor(R.attr.colorColumnListItemText)
var bOldSelection: Boolean = false
fun setOldSelection(b: Boolean) {
bOldSelection = b
}
}
// リスト要素のViewHolder
internal inner class MyViewHolder(viewRoot: View) : DragItemAdapter.ViewHolder(
viewRoot,
R.id.ivDragHandle, // View ID。 ここを押すとドラッグ操作をすぐに開始する
true, // 長押しでドラッグ開始するなら真
) {
private val ivBookmark: View = viewRoot.findViewById(R.id.ivBookmark)
private val tvAccess: TextView = viewRoot.findViewById(R.id.tvAccess)
private val tvName: TextView = viewRoot.findViewById(R.id.tvName)
private val ivColumnIcon: ImageView = viewRoot.findViewById(R.id.ivColumnIcon)
private val acctPadLr = (0.5f + 4f * viewRoot.resources.displayMetrics.density).toInt()
init {
// リスト要素のビューが ListSwipeItem だった場合、Swipe操作を制御できる
if (viewRoot is ListSwipeItem) {
viewRoot.setSwipeInStyle(ListSwipeItem.SwipeInStyle.SLIDE)
viewRoot.supportedSwipeDirection = ListSwipeItem.SwipeDirection.LEFT
}
}
fun bind(item: MyItem) {
itemView.tag = item // itemView は親クラスのメンバ変数
ivBookmark.visibility = if (item.bOldSelection) View.VISIBLE else View.INVISIBLE
tvAccess.text = item.acctName
tvAccess.setTextColor(item.acctColorFg)
tvAccess.setBackgroundColor(item.acctColorBg)
tvAccess.setPaddingRelative(acctPadLr, 0, acctPadLr, 0)
tvName.text = item.name
ivColumnIcon.setImageResource(item.type.iconId(item.acct))
// 背景色がテーマ次第なので、カラム設定の色を反映するとアイコンが見えなくなる可能性がある
// よってアイコンやテキストにカラム設定の色を反映しない
}
// @Override
// public boolean onItemLongClicked( View view ){
// return false;
// }
override fun onItemClicked(view: View?) {
val item = itemView.tag as MyItem // itemView は親クラスのメンバ変数
(view.activity as? ActColumnList)?.performItemSelected(item)
}
}
// ドラッグ操作中のデータ
private inner class MyDragItem(context: Context, layoutId: Int) :
DragItem(context, layoutId) {
override fun onBindDragView(clickedView: View, dragView: View) {
val item = clickedView.tag as MyItem
var tv: TextView = dragView.findViewById(R.id.tvAccess)
tv.text = item.acctName
tv.setTextColor(item.acctColorFg)
tv.setBackgroundColor(item.acctColorBg)
tv = dragView.findViewById(R.id.tvName)
tv.text = item.name
val ivColumnIcon: ImageView = dragView.findViewById(R.id.ivColumnIcon)
ivColumnIcon.setImageResource(item.type.iconId(item.acct))
dragView.findViewById<View>(R.id.ivBookmark).visibility =
clickedView.findViewById<View>(R.id.ivBookmark).visibility
dragView.findViewById<View>(R.id.item_layout)
.setBackgroundColor(attrColor(R.attr.list_item_bg_pressed_dragged))
}
}
private inner class MyListAdapter :
DragItemAdapter<MyItem, MyViewHolder>() {
init {
setHasStableIds(true)
itemList = ArrayList()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view = layoutInflater.inflate(R.layout.lv_column_list, parent, false)
return MyViewHolder(view)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
super.onBindViewHolder(holder, position)
holder.bind(itemList[position])
}
override fun getUniqueItemId(position: Int): Long {
val item = mItemList[position] // mItemList は親クラスのメンバ変数
return item.id
}
}
}
| apache-2.0 | eb6000b79534bd3684e98d08e310c583 | 35.075658 | 95 | 0.597019 | 4.59291 | false | false | false | false |
Bugfry/exercism | exercism/kotlin/atbash-cipher/src/main/kotlin/Atbash.kt | 2 | 874 | object Atbash {
fun encode(text: String): String {
return text.filter { it.isLetterOrDigit() }
.map { mirror(it.toLowerCase()) }
.intersperse(' ', 5)
}
fun decode(cipher: String): String =
cipher.filterNot { it.isWhitespace() }
.map { mirror(it) }
.joinToString("")
private fun mirror(c: Char): Char =
if (c in 'a' .. 'z') (219 - c.toInt()).toChar() else c
}
fun Iterable<Char>.intersperse(c: Char, span: Int): String {
val iter = this.iterator()
return object : Iterable<Char> {
override operator fun iterator(): Iterator<Char> =
object : Iterator<Char> {
val source = iter
var count = 0
override fun hasNext(): Boolean = source.hasNext()
override fun next(): Char = if (count++ % (span + 1) == span) c else source.next()
}
}.joinToString("")
}
| mit | 8131d041e811707ab8c4cb3cee45cbb1 | 29.137931 | 90 | 0.573227 | 3.85022 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/feature/S3StorageGridSpec.kt | 1 | 3522 | package no.skatteetaten.aurora.boober.feature
import no.skatteetaten.aurora.boober.model.AuroraDeploymentSpec
data class S3ObjectArea(
val tenant: String,
val bucketName: String,
val specifiedAreaKey: String,
val area: String = specifiedAreaKey
)
val AuroraDeploymentSpec.s3ObjectAreas
get(): List<S3ObjectArea> {
val tenantName = "$affiliation-$cluster"
val defaultBucketName: String = this["$FEATURE_DEFAULTS_FIELD_NAME/bucketName"]
val defaultObjectAreaName =
this.get<String>("$FEATURE_DEFAULTS_FIELD_NAME/objectArea").takeIf { it.isNotBlank() } ?: "default"
return if (this.isSimplifiedAndEnabled(FEATURE_FIELD_NAME)) {
val defaultS3Bucket = S3ObjectArea(
tenant = tenantName,
bucketName = defaultBucketName,
specifiedAreaKey = defaultObjectAreaName
)
listOf(defaultS3Bucket)
} else {
val objectAreaNames = getSubKeyValues(FEATURE_FIELD_NAME)
objectAreaNames
.filter { objectAreaName -> this["$FEATURE_FIELD_NAME/$objectAreaName/enabled"] }
.map { objectAreaName ->
S3ObjectArea(
tenant = tenantName,
bucketName = getOrNull("$FEATURE_FIELD_NAME/$objectAreaName/bucketName") ?: defaultBucketName,
specifiedAreaKey = objectAreaName,
area = this["$FEATURE_FIELD_NAME/$objectAreaName/objectArea"]
)
}
}
}
fun AuroraDeploymentSpec.validateS3(): List<IllegalArgumentException> {
val objectAreas = this.s3ObjectAreas
if (objectAreas.isEmpty()) return emptyList()
val requiredFieldsExceptions = objectAreas.validateRequiredFieldsArePresent()
val duplicateObjectAreaInSameBucketExceptions = objectAreas.verifyObjectAreasAreUnique()
val bucketNameExceptions = objectAreas.validateBucketNames()
return requiredFieldsExceptions + duplicateObjectAreaInSameBucketExceptions + bucketNameExceptions
}
private fun List<S3ObjectArea>.validateBucketNames() = runValidators(
{
if (!Regex("[a-z0-9-.]*").matches(it.bucketName))
"s3 bucketName can only contain lower case characters, numbers, hyphen(-) or period(.), specified value was: \"${it.bucketName}\""
else null
}, { s3ObjectArea ->
"${s3ObjectArea.tenant}-${s3ObjectArea.bucketName}"
.takeIf { it.length < 3 || it.length >= 63 }
?.let { "combination of bucketName and tenantName must be between 3 and 63 chars, specified value was ${it.length} chars long" }
}
)
private fun List<S3ObjectArea>.validateRequiredFieldsArePresent() = runValidators(
{ if (it.bucketName.isEmpty()) "Missing field: bucketName for s3" else null },
{ if (it.area.isEmpty()) "Missing field: objectArea for s3" else null }
)
private fun List<S3ObjectArea>.verifyObjectAreasAreUnique(): List<IllegalArgumentException> {
return groupBy { it.area }
.mapValues { it.value.size }
.filter { it.value > 1 }
.map { (name, count) -> IllegalArgumentException("objectArea name=$name used $count times for same application") }
}
private fun <T> List<T>.runValidators(vararg validators: (T) -> String?) =
validators.flatMap { validator -> this.mapNotNull(validator) }.map { IllegalArgumentException(it) }
private const val FEATURE_FIELD_NAME = "s3"
private const val FEATURE_DEFAULTS_FIELD_NAME = "s3Defaults"
| apache-2.0 | 8d2137ba799ca3f3bad87a64abd01b09 | 41.95122 | 142 | 0.668938 | 4.61599 | false | false | false | false |
square/okio | okio/src/linuxX64Main/kotlin/okio/-LinuxX64PosixVariant.kt | 1 | 1590 | /*
* Copyright (C) 2020 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okio
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import platform.posix.ENOENT
import platform.posix.S_IFDIR
import platform.posix.S_IFMT
import platform.posix.S_IFREG
import platform.posix.errno
import platform.posix.lstat
import platform.posix.stat
internal actual fun PosixFileSystem.variantMetadataOrNull(path: Path): FileMetadata? {
return memScoped {
val stat = alloc<stat>()
if (lstat(path.toString(), stat.ptr) != 0) {
if (errno == ENOENT) return null
throw errnoToIOException(errno)
}
return@memScoped FileMetadata(
isRegularFile = stat.st_mode.toInt() and S_IFMT == S_IFREG,
isDirectory = stat.st_mode.toInt() and S_IFMT == S_IFDIR,
symlinkTarget = symlinkTarget(stat, path),
size = stat.st_size,
createdAtMillis = stat.st_ctim.epochMillis,
lastModifiedAtMillis = stat.st_mtim.epochMillis,
lastAccessedAtMillis = stat.st_atim.epochMillis
)
}
}
| apache-2.0 | e7ead76cd987a80b6cea45b054afeac9 | 33.565217 | 86 | 0.727673 | 3.81295 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/ColorPickerBuilder.kt | 3 | 7124 | /*
* Copyright (C) 2018 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.intellij.ui.colorpicker
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CustomShortcutSet
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.ui.JBColor
import com.intellij.ui.picker.ColorListener
import com.intellij.util.Function
import com.intellij.util.ui.JBUI
import java.awt.Color
import java.awt.Component
import java.awt.Container
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.KeyEvent
import javax.swing.*
val PICKER_BACKGROUND_COLOR = JBColor(Color(252, 252, 252), Color(64, 64, 64))
val PICKER_TEXT_COLOR = Color(186, 186, 186)
const val PICKER_PREFERRED_WIDTH = 300
const val HORIZONTAL_MARGIN_TO_PICKER_BORDER = 14
private val PICKER_BORDER = JBUI.Borders.emptyBottom(10)
private const val SEPARATOR_HEIGHT = 5
/**
* Builder class to help to create customized picker components depends on the requirement.
*/
class ColorPickerBuilder(private val showAlpha: Boolean = false, private val showAlphaAsPercent: Boolean = true) {
private val componentsToBuild = mutableListOf<JComponent>()
val model = ColorPickerModel()
private var originalColor: Color? = null
private var requestFocusWhenDisplay = false
private var focusCycleRoot = false
private var focusedComponentIndex = -1
private val actionMap = mutableMapOf<KeyStroke, Action>()
private val colorListeners = mutableListOf<ColorListenerInfo>()
fun setOriginalColor(originalColor: Color?) = apply { this.originalColor = originalColor }
fun addSaturationBrightnessComponent() = apply { componentsToBuild.add(SaturationBrightnessComponent(model)) }
@JvmOverloads
fun addColorAdjustPanel(colorPipetteProvider: ColorPipetteProvider = GraphicalColorPipetteProvider()) = apply {
componentsToBuild.add(ColorAdjustPanel(model, colorPipetteProvider, showAlpha))
}
fun addColorValuePanel() = apply { componentsToBuild.add(ColorValuePanel(model, showAlpha, showAlphaAsPercent)) }
/**
* If both [okOperation] and [cancelOperation] are null, [IllegalArgumentException] will be raised.
*/
fun addOperationPanel(okOperation: ((Color) -> Unit)?, cancelOperation: ((Color) -> Unit)?) = apply {
componentsToBuild.add(OperationPanel(model, okOperation, cancelOperation))
if (cancelOperation != null) {
addKeyAction(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true), object : AbstractAction() {
override fun actionPerformed(e: ActionEvent?) = cancelOperation.invoke(model.color)
})
}
}
/**
* Add the custom components in to color picker.
*/
fun addCustomComponent(provider: ColorPickerComponentProvider) = apply { componentsToBuild.add(provider.createComponent(model)) }
fun addSeparator() = apply {
val separator = JSeparator(JSeparator.HORIZONTAL)
separator.border = JBUI.Borders.empty()
separator.preferredSize = JBUI.size(PICKER_PREFERRED_WIDTH, SEPARATOR_HEIGHT)
componentsToBuild.add(separator)
}
/**
* Set if Color Picker should request focus when it is displayed.<br>
*
* The default value is **false**
*/
fun focusWhenDisplay(focusWhenDisplay: Boolean) = apply { requestFocusWhenDisplay = focusWhenDisplay }
/**
* Set if Color Picker is the root of focus cycle.<br>
* Set to true to makes the focus traversal inside this Color Picker only. This is useful when the Color Picker is used in an independent
* window, e.g. a popup component or dialog.<br>
*
* The default value is **false**.
*
* @see Component.isFocusCycleRoot
*/
fun setFocusCycleRoot(focusCycleRoot: Boolean) = apply { this.focusCycleRoot = focusCycleRoot }
/**
* When getting the focus, focus to the last added component.<br>
* If this function is called multiple times, only the last time effects.<br>
* By default, nothing is focused in ColorPicker.
*/
fun withFocus() = apply { focusedComponentIndex = componentsToBuild.size - 1 }
fun addKeyAction(keyStroke: KeyStroke, action: Action) = apply { actionMap[keyStroke] = action }
fun addColorListener(colorListener: ColorListener) = addColorListener(colorListener, true)
fun addColorListener(colorListener: ColorListener, invokeOnEveryColorChange: Boolean) = apply {
colorListeners.add(ColorListenerInfo(colorListener, invokeOnEveryColorChange))
}
fun build(): LightCalloutPopup {
if (componentsToBuild.isEmpty()) {
throw IllegalStateException("The Color Picker should have at least one picking component.")
}
val width: Int = componentsToBuild.map { it.preferredSize.width }.max()!!
val height = componentsToBuild.map { it.preferredSize.height }.sum()
var defaultFocusComponent = componentsToBuild.getOrNull(focusedComponentIndex)
if (defaultFocusComponent is ColorValuePanel) {
defaultFocusComponent = defaultFocusComponent.hexField
}
val panel = object : JPanel() {
override fun requestFocusInWindow() = defaultFocusComponent?.requestFocusInWindow() ?: false
override fun addNotify() {
super.addNotify()
if (requestFocusWhenDisplay) {
requestFocusInWindow()
}
}
}
panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
panel.border = PICKER_BORDER
panel.preferredSize = Dimension(width, height)
panel.background = PICKER_BACKGROUND_COLOR
val c = originalColor
if (c != null) {
model.setColor(c, null)
}
for (component in componentsToBuild) {
panel.add(component)
}
panel.isFocusCycleRoot = focusCycleRoot
panel.isFocusTraversalPolicyProvider = true
panel.focusTraversalPolicy = MyFocusTraversalPolicy(defaultFocusComponent)
actionMap.forEach { (keyStroke, action) ->
DumbAwareAction.create {
e: AnActionEvent? -> action.actionPerformed(ActionEvent(e?.inputEvent, 0, ""))
}.registerCustomShortcutSet(CustomShortcutSet(keyStroke), panel)
}
colorListeners.forEach { model.addListener(it.colorListener, it.invokeOnEveryColorChange) }
return LightCalloutPopup(panel,
closedCallback = { model.onClose() },
cancelCallBack = { model.onCancel() })
}
}
private class MyFocusTraversalPolicy(val defaultComponent: Component?) : LayoutFocusTraversalPolicy() {
override fun getDefaultComponent(aContainer: Container?): Component? = defaultComponent
}
private data class ColorListenerInfo(val colorListener: ColorListener, val invokeOnEveryColorChange: Boolean)
| apache-2.0 | 680c8c753094aabf49547096fcd1fe24 | 37.717391 | 139 | 0.739613 | 4.635003 | false | false | false | false |
benoitletondor/EasyBudget | Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/view/report/MonthlyReportFragment.kt | 1 | 5650 | /*
* Copyright 2022 Benoit LETONDOR
*
* 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.benoitletondor.easybudgetapp.view.report
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.benoitletondor.easybudgetapp.R
import com.benoitletondor.easybudgetapp.helper.CurrencyHelper
import com.benoitletondor.easybudgetapp.helper.launchCollect
import com.benoitletondor.easybudgetapp.helper.viewLifecycleScope
import com.benoitletondor.easybudgetapp.parameters.Parameters
import dagger.hilt.android.AndroidEntryPoint
import java.time.LocalDate
import javax.inject.Inject
private const val ARG_FIRST_DAY_OF_MONTH_DATE = "arg_date"
/**
* Fragment that displays monthly report for a given month
*
* @author Benoit LETONDOR
*/
@AndroidEntryPoint
class MonthlyReportFragment : Fragment() {
/**
* The first day of the month
*/
private lateinit var firstDayOfMonth: LocalDate
private val viewModel: MonthlyReportViewModel by viewModels()
@Inject lateinit var parameters: Parameters
// ---------------------------------->
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
firstDayOfMonth = requireArguments().getSerializable(ARG_FIRST_DAY_OF_MONTH_DATE) as LocalDate
// Inflate the layout for this fragment
val v = inflater.inflate(R.layout.fragment_monthly_report, container, false)
val progressBar = v.findViewById<ProgressBar>(R.id.monthly_report_fragment_progress_bar)
val content = v.findViewById<View>(R.id.monthly_report_fragment_content)
val recyclerView = v.findViewById<RecyclerView>(R.id.monthly_report_fragment_recycler_view)
val emptyState = v.findViewById<View>(R.id.monthly_report_fragment_empty_state)
val revenuesAmountTextView = v.findViewById<TextView>(R.id.monthly_report_fragment_revenues_total_tv)
val expensesAmountTextView = v.findViewById<TextView>(R.id.monthly_report_fragment_expenses_total_tv)
val balanceTextView = v.findViewById<TextView>(R.id.monthly_report_fragment_balance_tv)
viewLifecycleScope.launchCollect(viewModel.stateFlow) { state ->
when(state) {
MonthlyReportViewModel.MonthlyReportState.Empty -> {
progressBar.visibility = View.GONE
content.visibility = View.VISIBLE
recyclerView.visibility = View.GONE
emptyState.visibility = View.VISIBLE
revenuesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, 0.0)
expensesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, 0.0)
balanceTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, 0.0)
balanceTextView.setTextColor(ContextCompat.getColor(balanceTextView.context, R.color.budget_green))
}
is MonthlyReportViewModel.MonthlyReportState.Loaded -> {
progressBar.visibility = View.GONE
content.visibility = View.VISIBLE
configureRecyclerView(recyclerView, MonthlyReportRecyclerViewAdapter(state.expenses, state.revenues, parameters))
revenuesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, state.revenuesAmount)
expensesAmountTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, state.expensesAmount)
val balance = state.revenuesAmount - state.expensesAmount
balanceTextView.text = CurrencyHelper.getFormattedCurrencyString(parameters, balance)
balanceTextView.setTextColor(ContextCompat.getColor(balanceTextView.context, if (balance >= 0) R.color.budget_green else R.color.budget_red))
}
MonthlyReportViewModel.MonthlyReportState.Loading -> {
progressBar.visibility = View.VISIBLE
content.visibility = View.GONE
}
}
}
viewModel.loadDataForMonth(firstDayOfMonth)
return v
}
/**
* Configure recycler view LayoutManager & adapter
*/
private fun configureRecyclerView(recyclerView: RecyclerView, adapter: MonthlyReportRecyclerViewAdapter) {
recyclerView.layoutManager = LinearLayoutManager(activity)
recyclerView.adapter = adapter
}
companion object {
fun newInstance(firstDayOfMonth: LocalDate): MonthlyReportFragment = MonthlyReportFragment().apply {
arguments = Bundle().apply {
putSerializable(ARG_FIRST_DAY_OF_MONTH_DATE, firstDayOfMonth)
}
}
}
}
| apache-2.0 | dfffc14b5575ab6799872eb267db30cd | 43.84127 | 161 | 0.707788 | 5.131698 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/GHLoadingPanel.kt | 1 | 3240 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.util.ui.ComponentWithEmptyText
import com.intellij.vcs.log.ui.frame.ProgressStripe
import org.jetbrains.plugins.github.util.getName
import java.awt.BorderLayout
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.KeyStroke
class GHLoadingPanel<T>(private val model: GHLoadingModel,
private val content: T,
parentDisposable: Disposable,
private val textBundle: EmptyTextBundle = EmptyTextBundle.Default)
: JBLoadingPanel(BorderLayout(), parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS)
where T : JComponent, T : ComponentWithEmptyText {
private val updateLoadingPanel =
ProgressStripe(content, parentDisposable, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS).apply {
isOpaque = false
}
var errorHandler: GHLoadingErrorHandler? = null
init {
isOpaque = false
add(updateLoadingPanel, BorderLayout.CENTER)
model.addStateChangeListener(object : GHLoadingModel.StateChangeListener {
override fun onLoadingStarted() = update()
override fun onLoadingCompleted() = update()
override fun onReset() = update()
})
update()
}
private fun update() {
if (model.loading) {
isFocusable = true
content.emptyText.clear()
if (model.resultAvailable) {
updateLoadingPanel.startLoading()
}
else {
startLoading()
}
}
else {
stopLoading()
updateLoadingPanel.stopLoading()
if (model.resultAvailable) {
isFocusable = false
resetKeyboardActions()
content.emptyText.text = textBundle.empty
}
else {
val error = model.error
if (error != null) {
val emptyText = content.emptyText
emptyText.clear()
.appendText(textBundle.errorPrefix, SimpleTextAttributes.ERROR_ATTRIBUTES)
.appendSecondaryText(error.message ?: "Unknown error", SimpleTextAttributes.ERROR_ATTRIBUTES, null)
errorHandler?.getActionForError(error)?.let {
emptyText.appendSecondaryText(" ${it.getName()}", SimpleTextAttributes.LINK_PLAIN_ATTRIBUTES, it)
registerKeyboardAction(it, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED)
}
}
else content.emptyText.text = textBundle.default
}
}
}
interface EmptyTextBundle {
val default: String
val empty: String
val errorPrefix: String
class Simple(override val default: String, override val errorPrefix: String, override val empty: String = "") : EmptyTextBundle
object Default : EmptyTextBundle {
override val default: String = ""
override val empty: String = ""
override val errorPrefix: String = "Can't load data"
}
}
} | apache-2.0 | 23ac79e08b7fbd7fc33f74bc78b9f3e2 | 33.849462 | 140 | 0.695062 | 4.976959 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/progress/impl/CancellationCheck.kt | 1 | 3006 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.progress.impl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Clock
import com.intellij.openapi.util.registry.Registry
import org.jetbrains.annotations.TestOnly
/**
* It is used to check if [ProgressManager.checkCanceled] is invoked often enough - at least once per a threshold ms.
*
* For global usage [CancellationCheck.runWithCancellationCheck] could be used:
* - it has to be enabled with a registry key `ide.cancellation.check.enabled`, it is disabled by default
* - threshold (in ms) is specified with a registry key `ide.cancellation.check.threshold`, default is 500
*/
class CancellationCheck private constructor(val thresholdMs: () -> Long, val checkEnabled: () -> Boolean) {
@TestOnly
internal constructor(thresholdMs: Long): this(thresholdMs = { thresholdMs }, checkEnabled = { true })
private val statusRecord = ThreadLocal.withInitial { CanceledStatusRecord() }
private val hook = CoreProgressManager.CheckCanceledHook { indicator ->
checkCancellationDiff(statusRecord.get())
return@CheckCanceledHook indicator != null
}
private fun checkCancellationDiff(record: CanceledStatusRecord) {
if (record.enabled) {
val now = Clock.getTime()
val diff = now - record.timestamp
if (diff > thresholdMs()) {
LOG.error("${Thread.currentThread().name} last checkCanceled was $diff ms ago")
}
record.timestamp = now
}
}
private fun enableCancellationTimer(record: CanceledStatusRecord, enabled: Boolean) {
val progressManagerImpl = ProgressManager.getInstance() as ProgressManagerImpl
if (enabled) progressManagerImpl.addCheckCanceledHook(hook) else progressManagerImpl.removeCheckCanceledHook(hook)
record.enabled = enabled
record.timestamp = Clock.getTime()
}
fun <T> withCancellationCheck(block: () -> T): T {
if (!checkEnabled()) return block()
val record = statusRecord.get()
if (record.enabled) return block()
enableCancellationTimer(record, true)
try {
return block()
} finally {
try {
checkCancellationDiff(record)
}
finally {
enableCancellationTimer(record,false)
}
}
}
private data class CanceledStatusRecord(var enabled: Boolean = false, var timestamp: Long = Clock.getTime())
companion object {
private val LOG = Logger.getInstance(CancellationCheck::class.java)
@JvmStatic
private val INSTANCE: CancellationCheck =
CancellationCheck(
thresholdMs = { Registry.intValue("ide.cancellation.check.threshold").toLong() },
checkEnabled = { Registry.`is`("ide.cancellation.check.enabled") }
)
@JvmStatic
fun <T> runWithCancellationCheck(block: () -> T): T =
INSTANCE.withCancellationCheck(block)
}
}
| apache-2.0 | c94dcca23feadbb0ca155c09d1cbd230 | 34.785714 | 140 | 0.719561 | 4.513514 | false | false | false | false |
windchopper/password-drop | src/main/kotlin/com/github/windchopper/tools/password/drop/ui/MainController.kt | 1 | 14642 | @file:Suppress("UNUSED_ANONYMOUS_PARAMETER", "unused")
package com.github.windchopper.tools.password.drop.ui
import com.github.windchopper.common.fx.cdi.form.Form
import com.github.windchopper.tools.password.drop.Application
import com.github.windchopper.tools.password.drop.book.*
import com.github.windchopper.tools.password.drop.crypto.CryptoEngine
import com.github.windchopper.tools.password.drop.crypto.Salt
import com.github.windchopper.tools.password.drop.misc.*
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.event.Event
import jakarta.enterprise.event.Observes
import jakarta.inject.Inject
import javafx.application.Platform
import javafx.beans.binding.Bindings.createBooleanBinding
import javafx.beans.binding.Bindings.not
import javafx.beans.binding.BooleanBinding
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.geometry.Dimension2D
import javafx.geometry.Insets
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.effect.DropShadow
import javafx.scene.image.Image
import javafx.scene.image.WritableImage
import javafx.scene.input.ClipboardContent
import javafx.scene.input.DataFormat
import javafx.scene.input.TransferMode
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import javafx.scene.text.Text
import javafx.stage.FileChooser
import javafx.stage.FileChooser.ExtensionFilter
import javafx.stage.Modality
import javafx.stage.Screen
import javafx.stage.StageStyle
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.net.URL
import java.nio.file.Path
import java.nio.file.Paths
import javax.imageio.ImageIO
import kotlin.math.abs
import kotlin.reflect.KClass
@ApplicationScoped @Form(Application.FXML_MAIN) class MainController: Controller() {
@Inject private lateinit var bookCase: BookCase
@Inject private lateinit var treeEditEvent: Event<TreeEdit<BookPart>>
@Inject private lateinit var treeSelectionEvent: Event<TreeSelection<BookPart>>
@Inject private lateinit var mainHideEvent: Event<MainHide>
@FXML private lateinit var bookView: TreeView<BookPart>
@FXML private lateinit var newPageMenuItem: MenuItem
@FXML private lateinit var newParagraphMenuItem: MenuItem
@FXML private lateinit var newPhraseMenuItem: MenuItem
@FXML private lateinit var editMenuItem: MenuItem
@FXML private lateinit var deleteMenuItem: MenuItem
@FXML private lateinit var stayOnTopMenuItem: CheckMenuItem
@FXML private lateinit var reloadBookMenuItem: MenuItem
private var trayIcon: java.awt.TrayIcon? = null
private var openBook: Book? = null
override fun preferredStageSize(): Dimension2D {
return Screen.getPrimary().visualBounds
.let { Dimension2D(it.width / 6, it.height / 3) }
}
override fun afterLoad(form: Parent, parameters: MutableMap<String, *>, formNamespace: MutableMap<String, *>) {
super.afterLoad(form, parameters, formNamespace)
with (stage) {
initStyle(StageStyle.UTILITY)
title = Application.messages["main.head"]
isAlwaysOnTop = Application.stayOnTop.load().value?:false
stayOnTopMenuItem.isSelected = isAlwaysOnTop
setOnCloseRequest {
mainHideEvent.fire(MainHide())
}
with (scene) {
fill = Color.TRANSPARENT
}
}
with (bookView) {
with (selectionModel) {
selectionMode = SelectionMode.SINGLE
selectedItemProperty().addListener { selectedItemProperty, oldSelection, newSelection ->
treeSelectionEvent.fire(TreeSelection(this@MainController, oldSelection, newSelection))
}
}
setOnDragDetected { event ->
selectionModel.selectedItem?.value
?.let { bookPart ->
if (bookPart is Phrase) {
val content = ClipboardContent()
content[DataFormat.PLAIN_TEXT] = bookPart.text?:""
val dragBoard = bookView.startDragAndDrop(TransferMode.COPY)
dragBoard.setContent(content)
fun invertPaint(fill: Paint): Color = if (fill is Color) {
fill.invert()
} else {
Color.WHITE
}
val label = Label(bookPart.name)
.also {
it.background = Background(BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY))
it.effect = DropShadow(3.0, invertPaint(it.textFill))
}
val textBounds = Text(bookPart.name)
.let {
it.font = label.font
it.boundsInLocal
}
dragBoard.dragView = WritableImage(textBounds.width.toInt(), textBounds.height.toInt())
.also { image ->
Scene(label)
.also { it.fill = Color.TRANSPARENT }
.snapshot(image)
}
event.consume()
}
}
}
}
addMenuItemBindings()
addTrayIcon(stage.icons)
GlobalScope.launch {
openBook = Application.openBookPath.load()
?.value
?.let(bookCase::readBook)
?:buildNewBook()
fillBookViewFromBook()
prepareEncryptEngine()
}
}
fun buildNewBook(): Book {
return Book().also { book ->
book.name = Application.messages["book.unnamed"]
book.newPage().also { page ->
page.newParagraph().also { paragraph ->
paragraph.newPhrase()
}
}
}
}
suspend fun fillBookViewFromBook() {
openBook?.let { loadedBook ->
runWithFxThread {
reloadBookMenuItem.isDisable = loadedBook.path == null
val rootItem = TreeItem<BookPart>(openBook)
.also {
bookView.root = it
it.isExpanded = true
}
loadedBook.pages.forEach { page ->
val pageItem = TreeItem<BookPart>(page)
.also {
rootItem.children.add(it)
it.isExpanded = true
}
page.paragraphs.forEach { paragraph ->
val paragraphItem = TreeItem<BookPart>(paragraph)
.also {
pageItem.children.add(it)
it.isExpanded = true
}
paragraph.phrases.forEach { word ->
TreeItem<BookPart>(word)
.also {
paragraphItem.children.add(it)
}
}
}
}
}
}
}
suspend fun prepareEncryptEngine() {
openBook?.let { book ->
if (book.path != null && book.saltRaw == null) {
return
}
val (alertChoice, passwordProperty) = runWithFxThread {
val passwordAlert = prepareAlert(PasswordAlert(book.path == null), Modality.APPLICATION_MODAL)
Pair(passwordAlert.showAndWait(), passwordAlert.passwordProperty)
}
alertChoice
.filter { it == ButtonType.OK }
.ifPresent {
book.cryptoEngine = CryptoEngine(passwordProperty.get(), Salt(book.saltRaw)
.also { book.saltRaw = it.saltRaw })
}
}
}
fun addMenuItemBindings() {
with (bookView.selectionModel) {
fun selectedItemIs(type: KClass<*>): BooleanBinding {
return createBooleanBinding(
{
selectedItem?.value
?.let { type.isInstance(it) }
?:false
},
selectedItemProperty())
}
newPageMenuItem.disableProperty().bind(selectedItemProperty().isNull.or(selectedItemIs(Book::class).not()))
newParagraphMenuItem.disableProperty().bind(selectedItemProperty().isNull.or(selectedItemIs(Page::class).not()))
newPhraseMenuItem.disableProperty().bind(selectedItemProperty().isNull.or(selectedItemIs(Paragraph::class).not()))
editMenuItem.disableProperty().bind(selectedItemProperty().isNull)
deleteMenuItem.disableProperty().bind(selectedItemProperty().isNull.and(not(selectedItemIs(InternalBookPart::class))))
}
}
fun addTrayIcon(images: List<Image>) {
if (java.awt.SystemTray.isSupported()) {
val systemTray = java.awt.SystemTray.getSystemTray()
val trayIconImage = ImageIO.read(URL(
images.map { abs(systemTray.trayIconSize.width - it.width) to it.url }.minByOrNull { it.first }
!!.second))
trayIcon = java.awt.TrayIcon(trayIconImage, Application.messages["tray.head"])
.also { icon ->
systemTray.add(icon)
val openAction = java.awt.event.ActionListener {
Platform.runLater {
with (stage) {
show()
toFront()
}
}
}
icon.addActionListener(openAction)
icon.popupMenu = java.awt.PopupMenu()
.also { menu ->
menu.add(java.awt.MenuItem(Application.messages["tray.show"])
.also { item ->
item.addActionListener(openAction)
item.font = java.awt.Font.decode(null)
.deriveFont(java.awt.Font.BOLD)
})
menu.add(java.awt.MenuItem(Application.messages["tray.exit"])
.also { item ->
item.addActionListener {
Platform.exit()
}
})
}
}
}
}
@FXML fun newPage(event: ActionEvent) {
with (bookView) {
selectionModel.selectedItem.let { item ->
(item.value as Book).newPage().also {
item.children.add(TreeItem(it))
}
}
}
}
@FXML fun newParagraph(event: ActionEvent) {
with (bookView) {
selectionModel.selectedItem.let { item ->
(item.value as Page).newParagraph().also {
item.children.add(TreeItem(it))
}
}
}
}
@FXML fun newPhrase(event: ActionEvent) {
with (bookView) {
selectionModel.selectedItem.let { item ->
(item.value as Paragraph).newPhrase().also {
item.children.add(TreeItem(it))
}
}
}
}
@FXML fun edit(event: ActionEvent) {
treeEditEvent.fire(TreeEdit(this, bookView.selectionModel.selectedItem))
}
@FXML fun delete(event: ActionEvent) {
with (bookView.selectionModel.selectedItem) {
value.let {
if (it is InternalBookPart<*>) {
parent.children.remove(this)
it.removeFromParent()
}
}
}
}
fun prepareFileChooser(): FileChooser {
return FileChooser()
.also {
it.initialDirectory = (Application.openBookPath.load().value?.parent?:Paths.get(System.getProperty("user.home"))).toFile()
it.extensionFilters.add(ExtensionFilter(Application.messages["books"], "*.book.xml"))
}
}
@FXML fun open(event: ActionEvent) {
prepareFileChooser().showOpenDialog(stage)
?.let { file ->
loadBook(file.toPath())
}
}
fun loadBook(path: Path) {
GlobalScope.launch {
exceptionally {
openBook = bookCase.readBook(path)
runBlocking {
fillBookViewFromBook()
prepareEncryptEngine()
}
}
}
}
@FXML fun reload(event: ActionEvent) {
}
@FXML fun save(event: ActionEvent) {
openBook?.let { book ->
if (book.path == null) {
book.path = FileChooser()
.let {
it.initialDirectory = (Application.openBookPath.load().value?:Paths.get(System.getProperty("user.home"))).toFile()
it.extensionFilters.add(ExtensionFilter(Application.messages["books"], "*.book.xml"))
it.showSaveDialog(stage)?.toPath()
}
}
book.path?.let {
bookCase.saveBook(book, it)
Application.openBookPath.save(it)
}
}
}
@FXML fun toggleStayOnTop(event: ActionEvent) {
stage.isAlwaysOnTop = stayOnTopMenuItem.isSelected
Application.stayOnTop.save(stayOnTopMenuItem.isSelected)
}
@FXML fun exit(event: ActionEvent) {
Platform.exit()
}
fun update(@Observes event: TreeUpdateRequest) {
bookView.refresh()
}
fun afterExit(@Observes event: Exit) {
trayIcon?.let { icon ->
java.awt.SystemTray.getSystemTray().remove(icon)
}
}
} | apache-2.0 | 9390e523fc606a0c63225788a115d7e9 | 35.24505 | 138 | 0.533739 | 5.31663 | false | false | false | false |
Unic8/retroauth | retroauth-android/src/main/java/com/andretietz/retroauth/AccountAuthenticator.kt | 1 | 4350 | /*
* Copyright (c) 2015 Andre Tietz
*
* 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.andretietz.retroauth
import android.accounts.AbstractAccountAuthenticator
import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.accounts.NetworkErrorException
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
/**
* This AccountAuthenticator is a very basic implementation of Android's
* [AbstractAccountAuthenticator]. This implementation is intentional as empty as it is. Cause of this is, that
* it's executed in a different process, which makes it difficult to provide login endpoints from
* the app process in here.
*
* NOTE: This class cannot be replaced with a kotlin version yet, since Android cannot load Authenticators
* that are non java once
*/
class AccountAuthenticator(
context: Context,
internal val action: String,
private val cleanupUserData: (account: Account) -> Unit
) : AbstractAccountAuthenticator(context) {
override fun addAccount(
response: AccountAuthenticatorResponse,
accountType: String,
authCredentialType: String?,
requiredFeatures: Array<String>?,
options: Bundle
) = createAuthBundle(response, action, accountType, authCredentialType, null)
override fun getAuthToken(
response: AccountAuthenticatorResponse,
account: Account,
authTokenType: String,
options: Bundle
) = createAuthBundle(response, action, account.type, authTokenType, account.name)
/**
* Creates an Intent to open the Activity to login.
*
* @param response needed parameter
* @param accountType The account Type
* @param credentialType The requested credential-type
* @param accountName The name of the account
* @return a bundle to open the activity
*/
private fun createAuthBundle(
response: AccountAuthenticatorResponse,
action: String,
accountType: String,
credentialType: String?,
accountName: String?
): Bundle? = Bundle().apply {
putParcelable(
AccountManager.KEY_INTENT,
Intent(action).apply {
putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response)
putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType)
putExtra(KEY_CREDENTIAL_TYPE, credentialType)
accountName?.let {
putExtra(AccountManager.KEY_ACCOUNT_NAME, it)
}
})
}
override fun confirmCredentials(
response: AccountAuthenticatorResponse,
account: Account,
options: Bundle?
) = null
override fun editProperties(response: AccountAuthenticatorResponse, accountType: String) = null
override fun getAuthTokenLabel(authCredentialType: String) = null
override fun updateCredentials(
response: AccountAuthenticatorResponse,
account: Account,
authCredentialType: String,
options: Bundle
): Bundle? = null
override fun hasFeatures(
response: AccountAuthenticatorResponse,
account: Account,
features: Array<String>
) = null
@SuppressLint("CheckResult")
@Throws(NetworkErrorException::class)
override fun getAccountRemovalAllowed(response: AccountAuthenticatorResponse, account: Account): Bundle? {
val result = super.getAccountRemovalAllowed(response, account)
if (
result != null && result.containsKey(AccountManager.KEY_BOOLEAN_RESULT) &&
result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT, false)) {
try {
cleanupUserData(account)
} catch (exception: Exception) {
Log.w("AuthenticationService", "Your cleanup method threw an exception:", exception)
}
}
return result
}
companion object {
internal const val KEY_CREDENTIAL_TYPE = "account_credential_type"
}
}
| apache-2.0 | 49b431b2ccc3937cd97040dadf7579b0 | 32.461538 | 111 | 0.741379 | 4.801325 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiplatform/overrideExpect/jvm/jvm.kt | 3 | 623 | actual typealias <!LINE_MARKER("descr='Has declaration in common module'")!>Expect<!> = String
interface Derived : Base {
override fun <!LINE_MARKER("descr='Overrides function in 'Base''")!>expectInReturnType<!>(): Expect
override fun <!LINE_MARKER("descr='Overrides function in 'Base''")!>expectInArgument<!>(e: Expect)
override fun Expect.<!LINE_MARKER("descr='Overrides function in 'Base''")!>expectInReceiver<!>()
override val <!LINE_MARKER("descr='Overrides property in 'Base''")!>expectVal<!>: Expect
override var <!LINE_MARKER("descr='Overrides property in 'Base''")!>expectVar<!>: Expect
}
| apache-2.0 | c35e8b5b29df181b8a4b5558e96e3bcb | 46.923077 | 103 | 0.696629 | 4.580882 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/api/LowLevelFirApiFacadeForCompletion.kt | 2 | 6123 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.api
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.builder.buildPropertyAccessorCopy
import org.jetbrains.kotlin.fir.declarations.builder.buildPropertyCopy
import org.jetbrains.kotlin.fir.declarations.builder.buildSimpleFunctionCopy
import org.jetbrains.kotlin.fir.expressions.FirReturnExpression
import org.jetbrains.kotlin.fir.resolve.FirTowerDataContext
import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol
import org.jetbrains.kotlin.fir.visitors.FirVisitorVoid
import org.jetbrains.kotlin.idea.fir.low.level.api.FirModuleResolveStateForCompletion
import org.jetbrains.kotlin.idea.fir.low.level.api.FirModuleResolveStateImpl
import org.jetbrains.kotlin.idea.fir.low.level.api.element.builder.FirTowerDataContextCollector
import org.jetbrains.kotlin.idea.fir.low.level.api.providers.FirIdeProvider
import org.jetbrains.kotlin.idea.fir.low.level.api.providers.firIdeProvider
import org.jetbrains.kotlin.idea.util.getElementTextInContext
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
object LowLevelFirApiFacadeForCompletion {
fun getResolveStateForCompletion(originalState: FirModuleResolveState): FirModuleResolveState {
check(originalState is FirModuleResolveStateImpl)
return FirModuleResolveStateForCompletion(originalState.project, originalState)
}
fun recordCompletionContextForFunction(
firFile: FirFile,
fakeElement: KtNamedFunction,
originalElement: KtNamedFunction,
state: FirModuleResolveState,
) {
val firIdeProvider = firFile.session.firIdeProvider
val originalFunction = state.getOrBuildFirFor(originalElement) as FirSimpleFunction
val copyFunction = buildFunctionCopyForCompletion(firIdeProvider, fakeElement, originalFunction, state)
state.lazyResolveDeclarationForCompletion(copyFunction, firFile, firIdeProvider, FirResolvePhase.BODY_RESOLVE)
state.recordPsiToFirMappingsForCompletionFrom(copyFunction, firFile, fakeElement.containingKtFile)
}
fun recordCompletionContextForProperty(
firFile: FirFile,
fakeElement: KtProperty,
originalElement: KtProperty,
state: FirModuleResolveState,
) {
val firIdeProvider = firFile.session.firIdeProvider
val originalProperty = state.getOrBuildFirFor(originalElement) as FirProperty
val copyProperty = buildPropertyCopyForCompletion(firIdeProvider, fakeElement, originalProperty, state)
state.lazyResolveDeclarationForCompletion(copyProperty, firFile, firIdeProvider, FirResolvePhase.BODY_RESOLVE)
state.recordPsiToFirMappingsForCompletionFrom(copyProperty, firFile, fakeElement.containingKtFile)
}
private fun buildFunctionCopyForCompletion(
firIdeProvider: FirIdeProvider,
element: KtNamedFunction,
originalFunction: FirSimpleFunction,
state: FirModuleResolveState
): FirSimpleFunction {
val builtFunction = firIdeProvider.buildFunctionWithBody(element, originalFunction)
// right now we can't resolve builtFunction header properly, as it built right in air,
// without file, which is now required for running stages other then body resolve, so we
// take original function header (which is resolved) and copy replacing body with body from builtFunction
return buildSimpleFunctionCopy(originalFunction) {
body = builtFunction.body
symbol = builtFunction.symbol as FirNamedFunctionSymbol
resolvePhase = minOf(originalFunction.resolvePhase, FirResolvePhase.DECLARATIONS)
source = builtFunction.source
session = state.rootModuleSession
}.apply { reassignAllReturnTargets (builtFunction) }
}
private fun buildPropertyCopyForCompletion(
firIdeProvider: FirIdeProvider,
element: KtProperty,
originalProperty: FirProperty,
state: FirModuleResolveState
): FirProperty {
val builtProperty = firIdeProvider.buildPropertyWithBody(element, originalProperty)
val originalSetter = originalProperty.setter
val builtSetter = builtProperty.setter
// setter has a header with `value` parameter, and we want it type to be resolved
val copySetter = if (originalSetter != null && builtSetter != null) {
buildPropertyAccessorCopy(originalSetter) {
body = builtSetter.body
symbol = builtSetter.symbol
resolvePhase = minOf(builtSetter.resolvePhase, FirResolvePhase.DECLARATIONS)
source = builtSetter.source
session = state.rootModuleSession
}.apply { reassignAllReturnTargets(builtSetter) }
} else {
builtSetter
}
return buildPropertyCopy(originalProperty) {
symbol = builtProperty.symbol
initializer = builtProperty.initializer
getter = builtProperty.getter
setter = copySetter
resolvePhase = minOf(originalProperty.resolvePhase, FirResolvePhase.DECLARATIONS)
source = builtProperty.source
session = state.rootModuleSession
}
}
private fun FirFunction<*>.reassignAllReturnTargets(from: FirFunction<*>) {
this.accept(object : FirVisitorVoid() {
override fun visitElement(element: FirElement) {
if (element is FirReturnExpression && element.target.labeledElement == from) {
element.target.bind(this@reassignAllReturnTargets)
}
element.acceptChildren(this)
}
})
}
}
| apache-2.0 | 7d8895dc7035dd8e426e32071804f2de | 45.037594 | 118 | 0.737874 | 5.333624 | false | false | false | false |
AndrewJack/gatekeeper | mobile/src/main/java/technology/mainthread/apps/gatekeeper/data/FCMTopics.kt | 1 | 324 | package technology.mainthread.apps.gatekeeper.data
const val DOOR_OPENED = "door-opened"
const val DOOR_CLOSED = "door-closed"
const val HANDSET_ACTIVATED = "handset-activated"
const val HANDSET_DEACTIVATED = "handset-deactivated"
const val PRIMED = "primed"
const val UNPRIMED = "unprimed"
const val UNLOCKED = "unlocked"
| apache-2.0 | e9036a0fbccc525c8c57894cd985ae8d | 35 | 53 | 0.780864 | 3.306122 | false | false | false | false |
cout970/Modeler | src/main/kotlin/com/cout970/modeler/core/export/project/ProjectLoaderV12.kt | 1 | 13386 | package com.cout970.modeler.core.export.project
import com.cout970.modeler.api.animation.IAnimation
import com.cout970.modeler.api.animation.InterpolationMethod
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.ITransformation
import com.cout970.modeler.api.model.`object`.*
import com.cout970.modeler.api.model.material.IMaterial
import com.cout970.modeler.api.model.material.IMaterialRef
import com.cout970.modeler.api.model.mesh.IMesh
import com.cout970.modeler.api.model.selection.IObjectRef
import com.cout970.modeler.core.animation.Animation
import com.cout970.modeler.core.animation.Channel
import com.cout970.modeler.core.animation.Keyframe
import com.cout970.modeler.core.animation.ref
import com.cout970.modeler.core.export.*
import com.cout970.modeler.core.model.Model
import com.cout970.modeler.core.model.`object`.*
import com.cout970.modeler.core.model.material.ColoredMaterial
import com.cout970.modeler.core.model.material.MaterialNone
import com.cout970.modeler.core.model.material.TexturedMaterial
import com.cout970.modeler.core.model.mesh.FaceIndex
import com.cout970.modeler.core.model.mesh.Mesh
import com.cout970.modeler.core.model.toImmutable
import com.cout970.modeler.core.project.ProjectProperties
import com.cout970.modeler.core.resource.ResourcePath
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.google.gson.*
import kotlinx.collections.immutable.ImmutableMap
import kotlinx.collections.immutable.toImmutableMap
import java.lang.reflect.Type
import java.net.URI
import java.util.*
import java.util.zip.ZipFile
object ProjectLoaderV12 {
const val VERSION = "1.2"
val gson = GsonBuilder()
.setExclusionStrategies(ProjectExclusionStrategy())
.setPrettyPrinting()
.enableComplexMapKeySerialization()
.registerTypeAdapter(UUID::class.java, UUIDSerializer())
.registerTypeAdapter(IVector3::class.java, Vector3Serializer())
.registerTypeAdapter(IVector2::class.java, Vector2Serializer())
.registerTypeAdapter(IQuaternion::class.java, QuaternionSerializer())
.registerTypeAdapter(IGroupRef::class.java, GroupRefSerializer())
.registerTypeAdapter(IMaterialRef::class.java, MaterialRefSerializer())
.registerTypeAdapter(IObjectRef::class.java, ObjectRefSerializer())
.registerTypeAdapter(ITransformation::class.java, TransformationSerializer())
.registerTypeAdapter(BiMultimap::class.java, BiMultimapSerializer())
.registerTypeAdapter(ImmutableMap::class.java, ImmutableMapSerializer())
.registerTypeAdapter(IModel::class.java, ModelSerializer())
.registerTypeAdapter(IMaterial::class.java, MaterialSerializer())
.registerTypeAdapter(IObject::class.java, ObjectSerializer())
.registerTypeAdapter(IGroupTree::class.java, GroupTreeSerializer())
.registerTypeAdapter(IGroup::class.java, serializerOf<Group>())
.registerTypeAdapter(IMesh::class.java, MeshSerializer())
.registerTypeAdapter(IAnimation::class.java, AnimationSerializer())
.create()!!
fun loadProject(zip: ZipFile, path: String): ProgramSave {
val properties = zip.load<ProjectProperties>("project.json", gson)
?: throw IllegalStateException("Missing file 'project.json' inside '$path'")
val model = zip.load<IModel>("model.json", gson)
?: throw IllegalStateException("Missing file 'model.json' inside '$path'")
val animation = zip.load<IAnimation>("animation.json", gson)
?: throw IllegalStateException("Missing file 'animation.json' inside '$path'")
checkIntegrity(listOf(model.objectMap, model.materialMap, model.groupMap, model.tree))
checkIntegrity(listOf(animation))
return ProgramSave(VERSION, properties, model.addAnimation(animation), emptyList())
}
class ModelSerializer : JsonDeserializer<IModel> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IModel {
val obj = json.asJsonObject
val objects: Map<IObjectRef, IObject> = context.deserializeT(obj["objectMap"])
return Model.of(
objectMap = objects,
materialMap = context.deserializeT(obj["materialMap"]),
groupMap = context.deserializeT(obj["groupMap"]),
groupTree = MutableGroupTree(RootGroupRef, objects.keys.toMutableList()).toImmutable()
)
}
}
class MaterialSerializer : JsonDeserializer<IMaterial> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IMaterial {
val obj = json.asJsonObject
if (obj.has("type")) {
return when (obj["type"].asString) {
"texture" -> {
val id = context.deserialize<UUID>(obj["id"], UUID::class.java)
TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id)
}
"color" -> {
val id = context.deserialize<UUID>(obj["id"], UUID::class.java)
ColoredMaterial(obj["name"].asString, context.deserializeT(obj["color"]), id)
}
else -> MaterialNone
}
}
return when {
obj["name"].asString == "noTexture" -> MaterialNone
else -> {
val id = context.deserialize<UUID>(obj["id"], UUID::class.java)
TexturedMaterial(obj["name"].asString, ResourcePath(URI(obj["path"].asString)), id)
}
}
}
}
class ObjectSerializer : JsonDeserializer<IObject> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IObject {
val obj = json.asJsonObject
return when (obj["class"].asString) {
"ObjectCube" -> {
ObjectCube(
name = context.deserialize(obj["name"], String::class.java),
transformation = context.deserialize(obj["transformation"], ITransformation::class.java),
material = context.deserialize(obj["material"], IMaterialRef::class.java),
textureOffset = context.deserialize(obj["textureOffset"], IVector2::class.java),
textureSize = context.deserialize(obj["textureSize"], IVector2::class.java),
mirrored = context.deserialize(obj["mirrored"], Boolean::class.java),
visible = context.deserialize(obj["visible"], Boolean::class.java),
id = context.deserialize(obj["id"], UUID::class.java)
)
}
"Object" -> Object(
name = context.deserialize(obj["name"], String::class.java),
mesh = context.deserialize(obj["mesh"], IMesh::class.java),
material = context.deserialize(obj["material"], IMaterialRef::class.java),
visible = context.deserialize(obj["visible"], Boolean::class.java),
id = context.deserialize(obj["id"], UUID::class.java)
)
else -> throw IllegalStateException("Unknown Class: ${obj["class"]}")
}
}
}
class GroupTreeSerializer : JsonSerializer<IGroupTree>, JsonDeserializer<IGroupTree> {
data class Aux(val key: IGroupRef, val value: Set<IGroupRef>)
data class Aux2(val key: IGroupRef, val value: IGroupRef)
override fun serialize(src: IGroupTree, typeOfSrc: Type, context: JsonSerializationContext): JsonElement {
val tree = src as GroupTree
return JsonObject().apply {
add("childMap", JsonArray().also { array ->
tree.childMap.map { Aux(it.key, it.value) }.map { context.serializeT(it) }.forEach { it -> array.add(it) }
})
add("parentMap", JsonArray().also { array ->
tree.parentMap.map { Aux2(it.key, it.value) }.map { context.serializeT(it) }.forEach { it -> array.add(it) }
})
}
}
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IGroupTree {
if (json.isJsonNull) return GroupTree.emptyTree()
val obj = json.asJsonObject
val childMapArray = obj["childMap"].asJsonArray
val parentMapArray = obj["parentMap"].asJsonArray
val childMap = childMapArray
.map { context.deserialize(it, Aux::class.java) as Aux }
.map { it.key to it.value }
.toMap()
.toImmutableMap()
val parentMap = parentMapArray
.map { context.deserialize(it, Aux2::class.java) as Aux2 }
.map { it.key to it.value }
.toMap()
.toImmutableMap()
return GroupTree(parentMap, childMap)
}
}
class MeshSerializer : JsonSerializer<IMesh>, JsonDeserializer<IMesh> {
override fun serialize(src: IMesh, typeOfSrc: Type?, context: JsonSerializationContext): JsonElement {
val pos = context.serializeT(src.pos)
val tex = context.serializeT(src.tex)
val faces = JsonArray().apply {
src.faces.forEach { face ->
add(JsonArray().apply {
repeat(face.vertexCount) {
add(JsonArray().apply {
add(face.pos[it]); add(face.tex[it])
})
}
})
}
}
return JsonObject().apply {
add("pos", pos)
add("tex", tex)
add("faces", faces)
}
}
override fun deserialize(json: JsonElement, typeOfT: Type?, context: JsonDeserializationContext): IMesh {
val obj = json.asJsonObject
val pos = context.deserializeT<List<IVector3>>(obj["pos"])
val tex = context.deserializeT<List<IVector2>>(obj["tex"])
val faces = obj["faces"].asJsonArray.map { face ->
val vertex = face.asJsonArray
val posIndices = ArrayList<Int>(vertex.size())
val texIndices = ArrayList<Int>(vertex.size())
repeat(vertex.size()) {
val pair = vertex[it].asJsonArray
posIndices.add(pair[0].asInt)
texIndices.add(pair[1].asInt)
}
FaceIndex.from(posIndices, texIndices)
}
return Mesh(pos, tex, faces)
}
}
class AnimationSerializer : JsonDeserializer<IAnimation> {
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): IAnimation {
if (json.isJsonNull) return Animation.of()
val obj = json.asJsonObject
val channelsObj = obj["channels"]
val channels = if (!channelsObj.isJsonArray) emptyList() else channelsObj.asJsonArray.map { it ->
val channel = it.asJsonObject
val interName = channel["interpolation"].asString
val keyframesJson = channel["keyframes"].asJsonArray
val keyframes = keyframesJson.map { it.asJsonObject }.map {
Keyframe(
time = it["time"].asFloat,
value = context.deserializeT(it["value"])
)
}
Channel(
name = channel["name"].asString,
interpolation = InterpolationMethod.valueOf(interName),
enabled = channel["enabled"].asBoolean,
keyframes = keyframes,
id = context.deserializeT(channel["id"])
)
}
return Animation(
channels = channels.associateBy { it.ref },
timeLength = obj["timeLength"].asFloat,
channelMapping = emptyMap(),
name = "animation"
)
}
}
class BiMultimapSerializer : JsonDeserializer<BiMultimap<IGroupRef, IObjectRef>> {
data class Aux(val key: IGroupRef, val value: List<IObjectRef>)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): BiMultimap<IGroupRef, IObjectRef> {
if (json.isJsonNull || (json.isJsonArray && json.asJsonArray.size() == 0))
return emptyBiMultimap()
val array = json.asJsonArray
val list = array.map { context.deserialize(it, Aux::class.java) as Aux }
return biMultimapOf(*list.map { it.key to it.value }.toTypedArray())
}
}
} | gpl-3.0 | b7d40971f11c0343e82618825fe41c0e | 43.623333 | 140 | 0.594203 | 4.987332 | false | false | false | false |
ex3ndr/telegram-tl | Builder/src/org/telegram/tl/builder/JavaBuilder.kt | 1 | 24495 | package org.telegram.tl.builder
import java.util.ArrayList
import java.io.File
import java.nio.charset.Charset
import java.util.HashMap
/**
* Created with IntelliJ IDEA.
* User: ex3ndr
* Date: 23.10.13
* Time: 13:09
*/
fun convertToJavaModel(model: TLModel): JavaModel
{
var javaTypes = HashMap<String, JavaTypeObject>()
for (t in model.types)
{
if (t is TLCombinedTypeDef)
{
var combinedType = t as TLCombinedTypeDef
javaTypes.put(combinedType.name, JavaTypeObject(combinedType))
}
}
var javaMethods = ArrayList<JavaRpcMethod>()
for (t in model.methods) {
javaMethods.add(JavaRpcMethod(t))
}
for (t in javaTypes.values())
{
for (p in t.commonParameters)
{
p.reference = mapReference(javaTypes, p.tlParameterDef.typeDef)
}
for (c in t.constructors)
{
for (p in c.parameters)
{
p.reference = mapReference(javaTypes, p.tlParameterDef.typeDef)
}
}
}
for (m in javaMethods)
{
m.returnReference = mapReference(javaTypes, m.tlMethod.returnType)
for (p in m.parameters)
{
p.reference = mapReference(javaTypes, p.tlParameterDef.typeDef)
}
}
return JavaModel(javaTypes, javaMethods)
}
fun mapReference(javaTypes: HashMap<String, JavaTypeObject>, tlType: TLTypeDef): JavaTypeReference
{
return if (tlType is TLCombinedTypeDef) {
JavaTypeTlReference(tlType, javaTypes.get((tlType as TLCombinedTypeDef).name)!!);
} else if (tlType is TLBuiltInTypeDef)
{
JavaTypeBuiltInReference(tlType);
} else if (tlType is TLBuiltInGenericTypeDef)
{
var generic = tlType as TLBuiltInGenericTypeDef
if (generic.name != "Vector")
{
throw RuntimeException("Only Vector built-in generics are supported")
}
JavaTypeVectorReference(tlType, mapReference(javaTypes, (tlType as TLBuiltInGenericTypeDef).basic));
}
else if (tlType is TLBuiltInTypeDef)
{
JavaTypeBuiltInReference(tlType)
}
else if (tlType is TLAnyTypeDef) {
JavaTypeAnyReference(tlType)
}
else if (tlType is TLFunctionalTypeDef) {
JavaTypeFunctionalReference(tlType)
}
else {
JavaTypeUnknownReference(tlType)
}
}
fun buildSerializer(parameters: List<JavaParameter>): String
{
if (parameters.size() == 0)
{
return ""
}
var serializer = "";
for (p in parameters)
{
if (p.reference is JavaTypeTlReference)
{
serializer += JavaSerializeObject.replace("{int}", p.internalName);
}
else if (p.reference is JavaTypeVectorReference)
{
serializer += JavaSerializeVector.replace("{int}", p.internalName);
} else if (p.reference is JavaTypeBuiltInReference)
{
if (p.tlParameterDef.typeDef.name == "int")
{
serializer += JavaSerializeInt.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "Bool")
{
serializer += JavaSerializeBoolean.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "long")
{
serializer += JavaSerializeLong.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "double")
{
serializer += JavaSerializeDouble.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "string")
{
serializer += JavaSerializeString.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "bytes")
{
serializer += JavaSerializeBytes.replace("{int}", p.internalName);
} else throw RuntimeException("Unknown internal type: " + p.tlParameterDef.typeDef.name)
} else if (p.reference is JavaTypeFunctionalReference) {
serializer += JavaSerializeFunctional.replace("{int}", p.internalName);
} else if (p.reference is JavaTypeAnyReference) {
serializer += JavaSerializeObject.replace("{int}", p.internalName);
}
else
{
throw RuntimeException("Unknown type: " + p.tlParameterDef.typeDef.name)
}
}
return JavaSerializeTemplate.replace("{body}", serializer)
}
fun buildDeserializer(parameters: List<JavaParameter>): String
{
if (parameters.size() == 0)
{
return ""
}
var serializer = "";
for (p in parameters)
{
if (p.reference is JavaTypeTlReference)
{
serializer += JavaDeserializeObject.replace("{int}", p.internalName)
.replace("{type}", (p.reference as JavaTypeTlReference).javaName);
}
else if (p.reference is JavaTypeVectorReference)
{
if ((p.reference as JavaTypeVectorReference).internalReference is JavaTypeBuiltInReference)
{
var intReference = (p.reference as JavaTypeVectorReference).internalReference as JavaTypeBuiltInReference;
if (intReference.javaName == "int")
{
serializer += JavaDeserializeIntVector.replace("{int}", p.internalName);
} else if (intReference.javaName == "long")
{
serializer += JavaDeserializeLongVector.replace("{int}", p.internalName);
}
else if (intReference.javaName == "String")
{
serializer += JavaDeserializeStringVector.replace("{int}", p.internalName);
}
else {
serializer += JavaDeserializeVector.replace("{int}", p.internalName);
}
}
else {
serializer += JavaDeserializeVector.replace("{int}", p.internalName);
}
} else if (p.reference is JavaTypeBuiltInReference)
{
if (p.tlParameterDef.typeDef.name == "int")
{
serializer += JavaDeserializeInt.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "Bool")
{
serializer += JavaDeserializeBoolean.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "long")
{
serializer += JavaDeserializeLong.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "double")
{
serializer += JavaDeserializeDouble.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "string")
{
serializer += JavaDeserializeString.replace("{int}", p.internalName);
} else if (p.tlParameterDef.typeDef.name == "bytes")
{
serializer += JavaDeserializeBytes.replace("{int}", p.internalName);
} else throw RuntimeException("Unknown internal type: " + p.tlParameterDef.typeDef.name)
}
else if (p.reference is JavaTypeFunctionalReference) {
serializer += JavaDeserializeFunctional.replace("{int}", p.internalName);
} else if (p.reference is JavaTypeAnyReference) {
serializer += JavaDeserializeObject.replace("{int}", p.internalName)
.replace("{type}", "TLObject");
}
else
{
throw RuntimeException("Unknown type: " + p.tlParameterDef.typeDef.name)
}
}
return JavaDeserializeTemplate.replace("{body}", serializer)
}
fun writeJavaClasses(model: JavaModel, path: String)
{
for (t in model.types.values()) {
if (t.constructors.size == 1 && !IgnoreUniting.any {(x) -> x == t.tlType.name })
{
var generatedFile = JavaClassTemplate;
generatedFile = generatedFile
.replace("{name}", t.javaTypeName)
.replace("{package}", t.javaPackage)
.replace("{class_id}", "0x" + Integer.toHexString(t.constructors.first!!.tlConstructor.id))
.replace("{to_string}",
JavaToStringTemplate.replace("{value}", t.constructors.first!!.tlConstructor.name + "#" + Integer.toHexString(t.constructors.first!!.tlConstructor.id)));
var fields = "";
for (p in t.constructors.get(0).parameters)
{
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in t.constructors.get(0).parameters)
{
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
if (t.constructors.get(0).parameters.size > 0)
{
var constructorArgs = "";
var constructorBody = "";
for (p in t.constructors.get(0).parameters)
{
if (constructorArgs != "") {
constructorArgs += ", ";
}
constructorArgs += JavaConstructorArgTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
constructorBody += JavaConstructorBodyTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName) + "\n";
}
generatedFile = generatedFile.replace("{constructor}",
JavaConstructorTemplate
.replace("{name}", t.javaTypeName)
.replace("{args}", constructorArgs)
.replace("{body}", constructorBody))
}
else {
generatedFile = generatedFile.replace("{constructor}", "")
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
generatedFile = generatedFile.replace("{serialize}", buildSerializer(t.constructors.get(0).parameters))
generatedFile = generatedFile.replace("{deserialize}", buildDeserializer(t.constructors.get(0).parameters))
var directory = t.javaPackage.split('.').fold(path, {(x, t) -> x + "/" + t });
val destFile = File(directory + "/" + t.javaTypeName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
} else {
var directory = t.javaPackage.split('.').fold(path, {(x, t) -> x + "/" + t });
run {
var generatedFile = JavaAbsClassTemplate;
generatedFile = generatedFile
.replace("{name}", t.javaTypeName)
.replace("{package}", t.javaPackage);
var fields = "";
for (p in t.commonParameters)
{
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in t.commonParameters)
{
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
val destFile = File(directory + "/" + t.javaTypeName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
}
for (constr in t.constructors)
{
var generatedFile = JavaChildClassTemplate;
generatedFile = generatedFile
.replace("{name}", constr.javaClassName)
.replace("{base-name}", t.javaTypeName)
.replace("{package}", t.javaPackage)
.replace("{class_id}", "0x" + Integer.toHexString(constr.tlConstructor.id))
.replace("{to_string}",
JavaToStringTemplate.replace("{value}", constr.tlConstructor.name + "#" + Integer.toHexString(constr.tlConstructor.id)));
var fields = "";
for (p in constr.parameters)
{
if (t.commonParameters.any {(x) -> x.internalName == p.internalName })
{
continue
}
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in constr.parameters)
{
if (t.commonParameters.any {(x) -> x.internalName == p.internalName })
{
continue
}
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
if (constr.parameters.size > 0)
{
var constructorArgs = "";
var constructorBody = "";
for (p in constr.parameters)
{
if (constructorArgs != "") {
constructorArgs += ", ";
}
constructorArgs += JavaConstructorArgTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
constructorBody += JavaConstructorBodyTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName) + "\n";
}
var constructor = JavaConstructorTemplate
.replace("{name}", constr.javaClassName)
.replace("{args}", constructorArgs)
.replace("{body}", constructorBody);
generatedFile = generatedFile.replace("{constructor}", constructor)
} else {
generatedFile = generatedFile.replace("{constructor}", "")
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
generatedFile = generatedFile.replace("{serialize}", buildSerializer(constr.parameters))
generatedFile = generatedFile.replace("{deserialize}", buildDeserializer(constr.parameters))
val destFile = File(directory + "/" + constr.javaClassName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
}
}
}
for (m in model.methods)
{
var generatedFile = JavaMethodTemplate;
var returnTypeName = m.returnReference!!.javaName;
if (returnTypeName == "boolean") {
returnTypeName = "org.telegram.tl.TLBool"
}
generatedFile = generatedFile
.replace("{name}", m.requestClassName)
.replace("{package}", JavaPackage + "." + JavaMethodPackage)
.replace("{class_id}", "0x" + Integer.toHexString(m.tlMethod.id))
.replace("{return_type}", returnTypeName)
.replace("{to_string}",
JavaToStringTemplate.replace("{value}", m.tlMethod.name + "#" + Integer.toHexString(m.tlMethod.id)));
var fields = "";
for (p in m.parameters)
{
fields += JavaFieldTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
}
generatedFile = generatedFile.replace("{fields}", fields)
var getterSetter = "";
for (p in m.parameters)
{
getterSetter += JavaGetterSetterTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
.replace("{getter}", p.getterName)
.replace("{setter}", p.setterName)
}
if (m.parameters.size > 0)
{
var constructorArgs = "";
var constructorBody = "";
for (p in m.parameters)
{
if (constructorArgs != "") {
constructorArgs += ", ";
}
constructorArgs += JavaConstructorArgTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName)
constructorBody += JavaConstructorBodyTemplate
.replace("{type}", p.reference!!.javaName)
.replace("{int}", p.internalName) + "\n";
}
var constructor = JavaConstructorTemplate
.replace("{name}", m.requestClassName)
.replace("{args}", constructorArgs)
.replace("{body}", constructorBody);
generatedFile = generatedFile.replace("{constructor}", constructor)
} else {
var constructor = JavaConstructorTemplate
.replace("{name}", m.requestClassName)
.replace("{args}", "")
.replace("{body}", "");
generatedFile = generatedFile.replace("{constructor}", constructor)
}
generatedFile = generatedFile.replace("{getter-setters}", getterSetter)
generatedFile = generatedFile.replace("{serialize}", buildSerializer(m.parameters))
generatedFile = generatedFile.replace("{deserialize}", buildDeserializer(m.parameters))
var responseParser = JavaMethodParserTemplate.replace("{return_type}",
returnTypeName);
if (m.returnReference is JavaTypeVectorReference) {
var vectorReference = m.returnReference as JavaTypeVectorReference;
if (vectorReference.internalReference is JavaTypeBuiltInReference) {
var intReference = vectorReference.internalReference as JavaTypeBuiltInReference;
if (intReference.javaName == "int") {
responseParser = responseParser.replace("{body}", JavaMethodParserBodyIntVector)
} else if (intReference.javaName == "long") {
responseParser = responseParser.replace("{body}", JavaMethodParserBodyLongVector)
}
else {
throw RuntimeException("Unsupported vector internal reference")
}
}
else if (vectorReference.internalReference is JavaTypeTlReference) {
var tlReference = vectorReference.internalReference as JavaTypeTlReference;
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyVector.replace("{vector_type}", tlReference.javaName))
} else {
throw RuntimeException("Unsupported built-in reference")
}
}
else if (m.returnReference is JavaTypeTlReference) {
var returnReference = m.returnReference as JavaTypeTlReference;
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyGeneral.replace("{return_type}", returnReference.javaName))
} else if (m.returnReference is JavaTypeBuiltInReference) {
var returnReference = m.returnReference as JavaTypeBuiltInReference;
if (returnReference.javaName != "boolean") {
throw RuntimeException("Only boolean built-in reference allowed as return")
}
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyGeneral.replace("{return_type}", "org.telegram.tl.TLBool"))
}
else {
var functionalParameter: JavaParameter? = null
for (p in m.parameters)
{
if (p.reference is JavaTypeFunctionalReference) {
functionalParameter = p;
break
}
}
if (functionalParameter == null) {
throw RuntimeException("Any reference without functional reference: " + m.methodName)
}
// throw RuntimeException("Unsupported return reference")
responseParser = responseParser.replace("{body}",
JavaMethodParserBodyReference.replace("{return_type}", "TLObject")
.replace("{int}", functionalParameter!!.internalName))
}
generatedFile = generatedFile.replace("{responseParser}", responseParser)
var directory = (JavaPackage + "." + JavaMethodPackage).split('.').fold(path, {(x, t) -> x + "/" + t });
val destFile = File(directory + "/" + m.requestClassName + ".java");
File(directory).mkdirs()
destFile.writeText(generatedFile, "utf-8")
}
var requests = ""
for (m in model.methods) {
var args = "";
var methodArgs = "";
for (p in m.parameters) {
if (args != "") {
args += ", ";
}
if (methodArgs != "") {
methodArgs += ", ";
}
methodArgs += p.internalName;
args += p.reference!!.javaName + " " + p.internalName;
}
var returnTypeName = m.returnReference!!.javaName;
if (returnTypeName == "boolean")
{
returnTypeName = "TLBool";
}
requests += JavaRequesterMethod.replace("{return_type}", returnTypeName)
.replace("{method_name}", m.methodName)
.replace("{method_class}", m.requestClassName)
.replace("{args}", args)
.replace("{method_args}", methodArgs)
}
var directory = JavaPackage.split('.').fold(path, {(x, t) -> x + "/" + t });
val destRequesterFile = File(directory + "/TLApiRequester.java");
File(directory).mkdirs()
destRequesterFile.writeText(JavaRequesterTemplate
.replace("{methods}", requests)
.replace("{package}", JavaPackage), "utf-8")
var contextInit = ""
for (t in model.types.values()) {
if (t.constructors.size == 1 && !IgnoreUniting.any {(x) -> x == t.tlType.name })
{
contextInit += JavaContextIntRecord
.replace("{type}", t.javaPackage + "." + t.javaTypeName)
.replace("{id}", "0x" + Integer.toHexString(t.constructors.first!!.tlConstructor.id));
}
else {
for (c in t.constructors)
{
contextInit += JavaContextIntRecord
.replace("{type}", t.javaPackage + "." + c.javaClassName)
.replace("{id}", "0x" + Integer.toHexString(c.tlConstructor.id));
}
}
}
val destFile = File(directory + "/TLApiContext.java");
File(directory).mkdirs()
destFile.writeText(JavaContextTemplate
.replace("{init}", contextInit)
.replace("{package}", JavaPackage), "utf-8")
} | mit | 889973472e181ff97ab76e88e5e7705c | 40.378378 | 173 | 0.531986 | 5.521867 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/base/analysis-api/analysis-api-utils/src/org/jetbrains/kotlin/idea/base/analysis/api/utils/KtSymbolFromIndexProvider.kt | 1 | 5131 | // 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.base.analysis.api.utils
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMember
import com.intellij.psi.search.PsiShortNamesCache
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtNamedClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.getSymbolOfTypeSafe
import org.jetbrains.kotlin.idea.stubindex.KotlinClassShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFullClassNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinFunctionShortNameIndex
import org.jetbrains.kotlin.idea.stubindex.KotlinPropertyShortNameIndex
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClassOrObject
class KtSymbolFromIndexProvider(private val project: Project) {
context(KtAnalysisSession)
fun getKotlinClassesByName(
name: Name,
psiFilter: (KtClassOrObject) -> Boolean = { true },
): Sequence<KtNamedClassOrObjectSymbol> {
val scope = analysisScope
return KotlinClassShortNameIndex[name.asString(), project, scope]
.asSequence()
.filter(psiFilter)
.mapNotNull { it.getNamedClassOrObjectSymbol() }
}
context(KtAnalysisSession)
fun getKotlinClassesByNameFilter(
nameFilter: (Name) -> Boolean,
psiFilter: (KtClassOrObject) -> Boolean = { true },
): Sequence<KtNamedClassOrObjectSymbol> {
val scope = analysisScope
val index = KotlinFullClassNameIndex
return index.getAllKeys(project).asSequence()
.filter { fqName -> nameFilter(getShortName(fqName)) }
.flatMap { fqName -> index[fqName, project, scope] }
.filter(psiFilter)
.mapNotNull { it.getNamedClassOrObjectSymbol() }
}
context(KtAnalysisSession)
fun getJavaClassesByNameFilter(
nameFilter: (Name) -> Boolean,
psiFilter: (PsiClass) -> Boolean = { true }
): Sequence<KtNamedClassOrObjectSymbol> {
val names = buildSet<Name> {
forEachNonKotlinCache { cache ->
cache.allClassNames.forEach { nameString ->
if (Name.isValidIdentifier(nameString)) return@forEach
val name = Name.identifier(nameString)
if (nameFilter(name)) {
add(name)
}
}
}
}
return sequence {
names.forEach { name ->
yieldAll(getJavaClassesByName(name, psiFilter))
}
}
}
context(KtAnalysisSession)
fun getJavaClassesByName(
name: Name,
psiFilter: (PsiClass) -> Boolean = { true }
): Sequence<KtNamedClassOrObjectSymbol> {
val scope = analysisScope
val nameString = name.asString()
return sequence {
forEachNonKotlinCache { cache ->
yieldAll(cache.getClassesByName(nameString, scope).iterator())
}
}
.filter(psiFilter)
.mapNotNull { it.getNamedClassSymbol() }
}
context(KtAnalysisSession)
fun getKotlinCallableSymbolsByName(
name: Name,
psiFilter: (KtCallableDeclaration) -> Boolean = { true },
): Sequence<KtCallableSymbol> {
val scope = analysisScope
val nameString = name.asString()
return sequence {
yieldAll(KotlinFunctionShortNameIndex[nameString, project, scope])
yieldAll(KotlinPropertyShortNameIndex[nameString, project, scope])
}
.onEach { ProgressManager.checkCanceled() }
.filter { it is KtCallableDeclaration && psiFilter(it) }
.mapNotNull { it.getSymbolOfTypeSafe<KtCallableSymbol>() }
}
context(KtAnalysisSession)
fun getJavaCallableSymbolsByName(
name: Name,
psiFilter: (PsiMember) -> Boolean = { true }
): Sequence<KtCallableSymbol> {
val scope = analysisScope
val nameString = name.asString()
return sequence {
forEachNonKotlinCache { cache -> yieldAll(cache.getMethodsByName(nameString, scope).iterator()) }
forEachNonKotlinCache { cache -> yieldAll(cache.getFieldsByName(nameString, scope).iterator()) }
}
.filter(psiFilter)
.mapNotNull { it.getCallableSymbol() }
}
private inline fun forEachNonKotlinCache(action: (cache: PsiShortNamesCache) -> Unit) {
for (cache in PsiShortNamesCache.EP_NAME.getExtensions(project)) {
if (cache::class.java.name == "org.jetbrains.kotlin.idea.caches.KotlinShortNamesCache") continue
action(cache)
}
}
private fun getShortName(fqName: String) = Name.identifier(fqName.substringAfterLast('.'))
} | apache-2.0 | 9c5c0d06cfea6622d596c8de29bf405e | 37.878788 | 120 | 0.663613 | 5.311594 | false | false | false | false |
kivensolo/UiUsingListView | database/src/main/java/com/kingz/database/entity/SongEntity.kt | 1 | 349 | package com.kingz.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
//@Entity(tableName = "songs")
@Entity
class SongEntity(
@PrimaryKey
@ColumnInfo(name = "singer")
var singer: String = "",
@ColumnInfo(name = "release_year")
var releaseYear: Int = 0
) : BaseEntity() | gpl-2.0 | 51ee6578a100f6808aca14ac93839ea8 | 19.588235 | 38 | 0.710602 | 3.793478 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMlSessionService.kt | 1 | 2637 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml
import com.intellij.ide.actions.searcheverywhere.SearchEverywhereFoundElementInfo
import com.intellij.ide.actions.searcheverywhere.SearchRestartReason
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicReference
internal class SearchEverywhereMlSessionService {
companion object {
internal const val RECORDER_CODE = "MLSE"
@JvmStatic
fun getInstance(): SearchEverywhereMlSessionService =
ApplicationManager.getApplication().getService(SearchEverywhereMlSessionService::class.java)
}
private val sessionIdCounter = AtomicInteger()
private var activeSession: AtomicReference<SearchEverywhereMLSearchSession?> = AtomicReference()
private val experiment: SearchEverywhereMlExperiment = SearchEverywhereMlExperiment()
fun shouldOrderByML(): Boolean = experiment.shouldOrderByMl()
fun getCurrentSession(): SearchEverywhereMLSearchSession? {
if (experiment.isAllowed) {
return activeSession.get()
}
return null
}
fun onSessionStarted(project: Project?) {
if (experiment.isAllowed) {
activeSession.updateAndGet { SearchEverywhereMLSearchSession(project, sessionIdCounter.incrementAndGet()) }
}
}
fun onSearchRestart(project: Project?,
tabId: String,
reason: SearchRestartReason,
keysTyped: Int,
backspacesTyped: Int,
textLength: Int,
previousElementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
if (experiment.isAllowed) {
getCurrentSession()?.onSearchRestart(project, previousElementsProvider, reason, tabId, keysTyped, backspacesTyped, textLength)
}
}
fun onItemSelected(project: Project?, indexes: IntArray, closePopup: Boolean, elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
if (experiment.isAllowed) {
getCurrentSession()?.onItemSelected(project, experiment, indexes, closePopup, elementsProvider)
}
}
fun onSearchFinished(project: Project?, elementsProvider: () -> List<SearchEverywhereFoundElementInfo>) {
if (experiment.isAllowed) {
getCurrentSession()?.onSearchFinished(project, experiment, elementsProvider)
}
}
fun onDialogClose() {
activeSession.updateAndGet { null }
}
} | apache-2.0 | d601b67b548e2fe1d19a32a7af437a93 | 38.373134 | 158 | 0.739477 | 5.459627 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/klib/KotlinNativeLibraryDataService.kt | 5 | 3194 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleJava.configuration.klib
import com.intellij.openapi.externalSystem.model.DataNode
import com.intellij.openapi.externalSystem.model.ProjectKeys
import com.intellij.openapi.externalSystem.model.project.LibraryData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.IdeUIModifiableModelsProvider
import com.intellij.openapi.externalSystem.service.project.manage.AbstractProjectDataService
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants
import com.intellij.openapi.externalSystem.util.Order
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.libraries.Library
import org.jetbrains.kotlin.idea.gradle.configuration.klib.KotlinNativeLibraryNameUtil.KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE
// KT-30490. This `ProjectDaaStervice` must be executed immediately after
// `com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService` to clean-up KLIBs before any other actions taken on them.
@Order(ExternalSystemConstants.BUILTIN_LIBRARY_DATA_SERVICE_ORDER + 1) // force order
class KotlinNativeLibraryDataService : AbstractProjectDataService<LibraryData, Library>() {
override fun getTargetDataKey() = ProjectKeys.LIBRARY
// See also `com.intellij.openapi.externalSystem.service.project.manage.LibraryDataService.postProcess()`
override fun postProcess(
toImport: MutableCollection<out DataNode<LibraryData>>,
projectData: ProjectData?,
project: Project,
modelsProvider: IdeModifiableModelsProvider
) {
if (projectData == null || modelsProvider is IdeUIModifiableModelsProvider) return
val librariesModel = modelsProvider.modifiableProjectLibrariesModel
val potentialOrphans = HashMap<String, Library>()
librariesModel.libraries.forEach { library ->
val libraryName = library.name?.takeIf { it.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) } ?: return@forEach
potentialOrphans[libraryName] = library
}
if (potentialOrphans.isEmpty()) return
modelsProvider.modules.forEach { module ->
modelsProvider.getOrderEntries(module).forEach inner@{ orderEntry ->
val libraryOrderEntry = orderEntry as? LibraryOrderEntry ?: return@inner
if (libraryOrderEntry.isModuleLevel) return@inner
val libraryName = (libraryOrderEntry.library?.name ?: libraryOrderEntry.libraryName)
?.takeIf { it.startsWith(KOTLIN_NATIVE_LIBRARY_PREFIX_PLUS_SPACE) } ?: return@inner
potentialOrphans.remove(libraryName)
}
}
potentialOrphans.keys.forEach { libraryName ->
librariesModel.getLibraryByName(libraryName)?.let { librariesModel.removeLibrary(it) }
}
}
}
| apache-2.0 | ad6ca4d1942d2d6874840de5c71e26ac | 52.233333 | 158 | 0.762993 | 5.069841 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/stepping/smartStepInto/OpcodeReportingMethodVisitor.kt | 4 | 2365 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.stepping.smartStepInto
import org.jetbrains.org.objectweb.asm.Handle
import org.jetbrains.org.objectweb.asm.Label
import org.jetbrains.org.objectweb.asm.MethodVisitor
import org.jetbrains.org.objectweb.asm.Opcodes
/**
* This class pipes all visit*Insn calls to the [reportOpcode] function. The derived class can process all visited opcodes
* by overriding only [reportOpcode] function.
*/
open class OpcodeReportingMethodVisitor(
private val delegate: OpcodeReportingMethodVisitor? = null
) : MethodVisitor(Opcodes.API_VERSION, delegate) {
protected open fun reportOpcode(opcode: Int) {
delegate?.reportOpcode(opcode)
}
override fun visitInsn(opcode: Int) =
reportOpcode(opcode)
override fun visitLdcInsn(value: Any?) =
reportOpcode(Opcodes.LDC)
override fun visitLookupSwitchInsn(dflt: Label?, keys: IntArray?, labels: Array<out Label>?) =
reportOpcode(Opcodes.LOOKUPSWITCH)
override fun visitMultiANewArrayInsn(descriptor: String?, numDimensions: Int) =
reportOpcode(Opcodes.MULTIANEWARRAY)
override fun visitIincInsn(variable: Int, increment: Int) =
reportOpcode(Opcodes.IINC)
override fun visitIntInsn(opcode: Int, operand: Int) =
reportOpcode(opcode)
override fun visitVarInsn(opcode: Int, variable: Int) =
reportOpcode(opcode)
override fun visitTypeInsn(opcode: Int, type: String?) =
reportOpcode(opcode)
override fun visitFieldInsn(opcode: Int, owner: String?, name: String?, descriptor: String?) =
reportOpcode(opcode)
override fun visitJumpInsn(opcode: Int, label: Label?) =
reportOpcode(opcode)
override fun visitTableSwitchInsn(min: Int, max: Int, dflt: Label?, vararg labels: Label?) =
reportOpcode(Opcodes.TABLESWITCH)
override fun visitMethodInsn(opcode: Int, owner: String, name: String, descriptor: String, isInterface: Boolean) =
reportOpcode(opcode)
override fun visitInvokeDynamicInsn(
name: String?,
descriptor: String?,
bootstrapMethodHandle: Handle?,
vararg bootstrapMethodArguments: Any?
) = reportOpcode(Opcodes.INVOKEDYNAMIC)
}
| apache-2.0 | 1ffd9969f9e74abceca1ac989d07ad83 | 46.3 | 158 | 0.730655 | 4.323583 | false | false | false | false |
K0zka/kerub | src/test/kotlin/com/github/kerubistan/kerub/host/servicemanager/rc/RcServiceManagerTest.kt | 2 | 1383 | package com.github.kerubistan.kerub.host.servicemanager.rc
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RcServiceManagerTest {
@Test
fun disable() {
assertFalse(RcServiceManager.disable("ctld","""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
ctld_enable="YES"
""").contains("ctld"))
}
@Test
fun testIsEnabled() {
assertTrue(RcServiceManager.isEnabled("ctld",
"""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
ctld_enable="YES"
"""))
assertFalse(RcServiceManager.isEnabled("ctld",
"""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
ctld_enable="NO"
"""))
assertFalse(RcServiceManager.isEnabled("ctld",
"""
hostname="freebsd10"
ifconfig_re0="DHCP"
ifconfig_re0_ipv6="inet6 accept_rtadv"
sshd_enable="YES"
ntpd_enable="YES"
# Set dumpdev to "AUTO" to enable crash dumps, "NO" to disable
dumpdev="AUTO"
"""))
}
@Test
fun testDisable() {
}
} | apache-2.0 | 590dbc833aadae950a0ad67799546dc5 | 20.968254 | 62 | 0.718727 | 2.967811 | false | true | false | false |
lytefast/flex-input | flexinput/src/main/java/com/lytefast/flexinput/adapters/AttachmentPreviewAdapter.kt | 1 | 3383 | package com.lytefast.flexinput.adapters
import android.content.ContentResolver
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.recyclerview.widget.RecyclerView
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.drawee.view.SimpleDraweeView
import com.facebook.imagepipeline.common.ResizeOptions
import com.facebook.imagepipeline.common.RotationOptions
import com.facebook.imagepipeline.request.ImageRequestBuilder
import com.lytefast.flexinput.R
import com.lytefast.flexinput.model.Attachment
import com.lytefast.flexinput.model.Photo
import com.lytefast.flexinput.utils.SelectionAggregator
typealias SelectionAggregatorProvider<T> = (AttachmentPreviewAdapter<T>) -> SelectionAggregator<T>
/**
* [RecyclerView.Adapter] which, given a list of attachments understands how to display them.
* This can be extended to implement custom previews.
*
* @author Sam Shih
*/
class AttachmentPreviewAdapter<T : Attachment<Any>>
@JvmOverloads constructor(private val contentResolver: ContentResolver,
selectionAggregatorProvider: SelectionAggregatorProvider<T>? = null)
: RecyclerView.Adapter<AttachmentPreviewAdapter<T>.ViewHolder>() {
val selectionAggregator: SelectionAggregator<T> =
selectionAggregatorProvider?.invoke(this) ?: SelectionAggregator(this)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.view_attachment_preview_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = selectionAggregator[position]
holder.bind(item)
}
override fun getItemCount(): Int = selectionAggregator.size
fun clear() {
val oldItemCount = itemCount
selectionAggregator.clear()
notifyItemRangeRemoved(0, oldItemCount)
}
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val draweeView: SimpleDraweeView = itemView as SimpleDraweeView
init {
val tintDrawable = AppCompatResources.getDrawable(itemView.context, R.drawable.ic_file_24dp)
draweeView.hierarchy.setPlaceholderImage(tintDrawable)
}
fun bind(item: T) {
when (item) {
is Photo -> draweeView.setImageURI(item.getThumbnailUri(contentResolver))
else -> {
// Make sure large images don't crash drawee
// http://stackoverflow.com/questions/33676807/fresco-bitmap-too-large-to-be-uploaded-into-a-texture
val height = draweeView.layoutParams.height
val imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(item.uri)
.setRotationOptions(RotationOptions.autoRotate())
.setResizeOptions(ResizeOptions(height, height))
val controller = Fresco.newDraweeControllerBuilder()
.setOldController(draweeView.controller)
.setAutoPlayAnimations(true)
.setImageRequest(imageRequestBuilder.build())
.build()
draweeView.controller = controller
}
}
itemView.setOnClickListener {
// Let the child delete the item, and notify us
selectionAggregator.unselectItem(item)
}
}
}
}
| mit | f89a7969ffe5edd7fb91e79b951297da | 35.376344 | 110 | 0.741945 | 4.805398 | false | false | false | false |
stoyicker/dinger | event-tracker/src/main/kotlin/tracker/EventTrackerImpl.kt | 1 | 460 | package tracker
import android.content.Context
import android.os.Bundle
internal sealed class EventTrackerImpl : EventTracker {
object Void : EventTrackerImpl() {
override fun init(context: Context) = Unit
override fun trackRecommendationResponse(data: Bundle) = Unit
override fun trackLikeResponse(data: Bundle) = Unit
override fun trackUserProvidedAccount() = Unit
override fun setUserProvidedAccount(value: String?) = Unit
}
}
| mit | 92d42d7f5603e59cd896e9d0a89e63d2 | 24.555556 | 65 | 0.758696 | 4.6 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/mediapreview/MediaPreviewV2State.kt | 1 | 554 | package org.thoughtcrime.securesms.mediapreview
import org.thoughtcrime.securesms.database.MediaDatabase
import org.thoughtcrime.securesms.mediasend.Media
data class MediaPreviewV2State(
val mediaRecords: List<MediaDatabase.MediaRecord> = emptyList(),
val loadState: LoadState = LoadState.INIT,
val position: Int = 0,
val showThread: Boolean = false,
val allMediaInAlbumRail: Boolean = false,
val leftIsRecent: Boolean = false,
val albums: Map<Long, List<Media>> = mapOf(),
) {
enum class LoadState { INIT, DATA_LOADED, MEDIA_READY }
}
| gpl-3.0 | 9993bc31005b66e68fb31029abe3b599 | 33.625 | 66 | 0.767148 | 3.929078 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/solver/shortcut/binderprovider/GuavaListenableFutureInsertMethodBinderProvider.kt | 3 | 2428 | /*
* Copyright 2018 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.room.solver.shortcut.binderprovider
import androidx.room.compiler.processing.XType
import androidx.room.ext.GuavaUtilConcurrentTypeNames
import androidx.room.ext.L
import androidx.room.ext.N
import androidx.room.ext.RoomGuavaTypeNames
import androidx.room.ext.T
import androidx.room.processor.Context
import androidx.room.processor.ProcessorErrors
import androidx.room.solver.shortcut.binder.CallableInsertMethodBinder.Companion.createInsertBinder
import androidx.room.solver.shortcut.binder.InsertOrUpsertMethodBinder
import androidx.room.vo.ShortcutQueryParameter
/**
* Provider for Guava ListenableFuture binders.
*/
class GuavaListenableFutureInsertMethodBinderProvider(
private val context: Context
) : InsertOrUpsertMethodBinderProvider {
private val hasGuavaRoom by lazy {
context.processingEnv.findTypeElement(RoomGuavaTypeNames.GUAVA_ROOM) != null
}
override fun matches(declared: XType): Boolean =
declared.typeArguments.size == 1 &&
declared.rawType.typeName == GuavaUtilConcurrentTypeNames.LISTENABLE_FUTURE
override fun provide(
declared: XType,
params: List<ShortcutQueryParameter>
): InsertOrUpsertMethodBinder {
if (!hasGuavaRoom) {
context.logger.e(ProcessorErrors.MISSING_ROOM_GUAVA_ARTIFACT)
}
val typeArg = declared.typeArguments.first()
val adapter = context.typeAdapterStore.findInsertAdapter(typeArg, params)
return createInsertBinder(typeArg, adapter) { callableImpl, dbField ->
addStatement(
"return $T.createListenableFuture($N, $L, $L)",
RoomGuavaTypeNames.GUAVA_ROOM,
dbField,
"true", // inTransaction
callableImpl
)
}
}
} | apache-2.0 | c2aaaf69a584aff658dd0adeba5a9023 | 35.80303 | 99 | 0.726524 | 4.642447 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/checker/infos/WrapIntoRef.kt | 10 | 647 | // FIR_IDENTICAL
fun refs() {
var <warning>a</warning> = 1
val <warning>v</warning> = {
<info>a</info> = 2
}
var <warning>x</warning> = 1
val <warning>b</warning> = object {
fun foo() {
<info>x</info> = 2
}
}
var <warning>y</warning> = 1
fun foo() {
<info>y</info> = 1
}
}
fun refsPlusAssign() {
var a = 1
val <warning>v</warning> = {
<info>a</info> += 2
}
var x = 1
val <warning>b</warning> = object {
fun foo() {
<info>x</info> += 2
}
}
var y = 1
fun foo() {
<info>y</info> += 1
}
}
| apache-2.0 | 26cf92e3645db7715e703aed55306fb4 | 15.589744 | 39 | 0.426584 | 3.037559 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/IdeaKpmProjectDeserializerImpl.kt | 6 | 2750 | // 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.gradleJava.configuration.kpm
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.gradle.kpm.idea.IdeaKpmProject
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmExtrasSerializationExtension
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmExtrasSerializer
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationContext
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationLogger
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationLogger.Severity.ERROR
import org.jetbrains.kotlin.gradle.kpm.idea.serialize.IdeaKpmSerializationLogger.Severity.WARNING
import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ExtrasSerializationService
import org.jetbrains.kotlin.idea.gradleTooling.serialization.IdeaKpmProjectDeserializer
import org.jetbrains.kotlin.kpm.idea.proto.IdeaKpmProject
import org.jetbrains.kotlin.tooling.core.Extras
class IdeaKpmProjectDeserializerImpl : IdeaKpmProjectDeserializer {
override fun read(data: ByteArray): IdeaKpmProject? {
return IdeaKpmSerializationContextImpl().IdeaKpmProject(data)
}
}
private class IdeaKpmSerializationContextImpl : IdeaKpmSerializationContext {
override val logger: IdeaKpmSerializationLogger = IntellijIdeaKpmSerializationLogger
override val extrasSerializationExtension: IdeaKpmExtrasSerializationExtension = IdeaKpmCompositeExtrasSerializationExtension(
ExtrasSerializationService.EP_NAME.extensionList.map { it.extension }
)
}
private object IntellijIdeaKpmSerializationLogger : IdeaKpmSerializationLogger {
val logger = Logger.getInstance(IntellijIdeaKpmSerializationLogger::class.java)
override fun report(severity: IdeaKpmSerializationLogger.Severity, message: String, cause: Throwable?) {
when (severity) {
WARNING -> logger.warn(message, cause)
ERROR -> logger.error(message, cause)
else -> logger.warn(message, cause)
}
}
}
private class IdeaKpmCompositeExtrasSerializationExtension(
private val extensions: List<IdeaKpmExtrasSerializationExtension>
) : IdeaKpmExtrasSerializationExtension {
override fun <T : Any> serializer(key: Extras.Key<T>): IdeaKpmExtrasSerializer<T>? {
val serializers = extensions.mapNotNull { it.serializer(key) }
if (serializers.isEmpty()) return null
if (serializers.size == 1) return serializers.single()
IntellijIdeaKpmSerializationLogger.error(
"Conflicting serializers for $key: $serializers"
)
return null
}
}
| apache-2.0 | 1a8685f9f368cfc068e6f036bd35041f | 45.610169 | 130 | 0.792 | 5.064457 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/ui/validation/requestors.kt | 2 | 2351 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.ui.validation
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.observable.properties.GraphProperty
import com.intellij.openapi.observable.properties.ObservableProperty
import com.intellij.openapi.observable.properties.PropertyGraph
import com.intellij.openapi.observable.util.whenDisposed
import com.intellij.openapi.observable.util.whenStateChanged
import com.intellij.openapi.observable.util.whenTextChanged
import com.intellij.ui.EditorTextField
import java.awt.ItemSelectable
import javax.swing.text.JTextComponent
val WHEN_TEXT_CHANGED = DialogValidationRequestor.WithParameter<JTextComponent> { textComponent ->
DialogValidationRequestor { parentDisposable, validate ->
textComponent.whenTextChanged(parentDisposable) { validate() }
}
}
val WHEN_TEXT_FIELD_TEXT_CHANGED = DialogValidationRequestor.WithParameter<EditorTextField> { textComponent ->
DialogValidationRequestor { parentDisposable, validate ->
val listener = object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
validate()
}
}
textComponent.addDocumentListener(listener)
parentDisposable?.whenDisposed { textComponent.removeDocumentListener(listener) }
}
}
val WHEN_STATE_CHANGED = DialogValidationRequestor.WithParameter<ItemSelectable> { component ->
DialogValidationRequestor { parentDisposable, validate ->
component.whenStateChanged(parentDisposable) { validate() }
}
}
val AFTER_GRAPH_PROPAGATION = DialogValidationRequestor.WithParameter<PropertyGraph> { graph ->
DialogValidationRequestor { parentDisposable, validate ->
graph.afterPropagation(parentDisposable, validate)
}
}
val AFTER_PROPERTY_PROPAGATION = DialogValidationRequestor.WithParameter<GraphProperty<*>> { property ->
DialogValidationRequestor { parentDisposable, validate ->
property.afterPropagation(parentDisposable, validate)
}
}
val AFTER_PROPERTY_CHANGE = DialogValidationRequestor.WithParameter<ObservableProperty<*>> { property ->
DialogValidationRequestor { parentDisposable, validate ->
property.afterChange(parentDisposable) { validate() }
}
} | apache-2.0 | 6680c1d92adc8a1e7dda26649edf0bef | 40.263158 | 120 | 0.804764 | 5.2713 | false | false | false | false |
GunoH/intellij-community | platform/configuration-store-impl/src/SaveResult.kt | 5 | 1465 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.configurationStore
import com.intellij.openapi.components.impl.stores.SaveSessionAndFile
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class SaveResult {
companion object {
@JvmField
internal val EMPTY = SaveResult()
}
private var error: Throwable? = null
@JvmField
internal val readonlyFiles: MutableList<SaveSessionAndFile> = mutableListOf()
@JvmField
internal var isChanged = false
@Synchronized
internal fun addError(error: Throwable) {
val existingError = this.error
if (existingError == null) {
this.error = error
}
else {
existingError.addSuppressed(error)
}
}
@Synchronized
internal fun addReadOnlyFile(info: SaveSessionAndFile) {
readonlyFiles.add(info)
}
@Synchronized
internal fun appendTo(saveResult: SaveResult) {
if (this === EMPTY) {
return
}
synchronized(saveResult) {
if (error != null) {
if (saveResult.error == null) {
saveResult.error = error
}
else {
saveResult.error!!.addSuppressed(error)
}
}
saveResult.readonlyFiles.addAll(readonlyFiles)
if (isChanged) {
saveResult.isChanged = true
}
}
}
@Synchronized
internal fun throwIfErrored() {
error?.let {
throw it
}
}
} | apache-2.0 | 6b1889d996d403b6f1a03351d3e7b6e6 | 20.880597 | 120 | 0.662116 | 4.493865 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/ui/branch/GitBranchActionsUtil.kt | 4 | 6406 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ui.branch
import com.intellij.dvcs.branch.GroupingKey
import com.intellij.dvcs.branch.isGroupingEnabled
import com.intellij.dvcs.branch.setGrouping
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pair
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.VcsNotifier
import com.intellij.util.containers.ContainerUtil
import git4idea.GitLocalBranch
import git4idea.GitNotificationIdsHolder.Companion.BRANCHES_UPDATE_SUCCESSFUL
import git4idea.GitNotificationIdsHolder.Companion.BRANCH_CHECKOUT_FAILED
import git4idea.GitNotificationIdsHolder.Companion.BRANCH_CREATION_FAILED
import git4idea.GitReference
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.branch.*
import git4idea.config.GitVcsSettings
import git4idea.fetch.GitFetchSupport
import git4idea.history.GitHistoryUtils
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.update.GitUpdateExecutionProcess
import org.jetbrains.annotations.Nls
import javax.swing.Icon
@JvmOverloads
internal fun createOrCheckoutNewBranch(project: Project,
repositories: List<GitRepository>,
startPoint: String,
@Nls(capitalization = Nls.Capitalization.Title)
title: String = GitBundle.message("branches.create.new.branch.dialog.title"),
initialName: String? = null) {
val options = GitNewBranchDialog(project, repositories, title, initialName, true, true, false, true).showAndGetOptions() ?: return
GitBranchCheckoutOperation(project, repositories).perform(startPoint, options)
}
internal fun updateBranches(project: Project, repositories: List<GitRepository>, localBranchNames: List<String>) {
val repoToTrackingInfos =
repositories.associateWith { it.branchTrackInfos.filter { info -> localBranchNames.contains(info.localBranch.name) } }
if (repoToTrackingInfos.isEmpty()) return
GitVcs.runInBackground(object : Task.Backgroundable(project, GitBundle.message("branches.updating.process"), true) {
private val successfullyUpdated = arrayListOf<String>()
override fun run(indicator: ProgressIndicator) {
val fetchSupport = GitFetchSupport.fetchSupport(project)
val currentBranchesMap: MutableMap<GitRepository, GitBranchPair> = HashMap()
for ((repo, trackingInfos) in repoToTrackingInfos) {
val currentBranch = repo.currentBranch
for (trackingInfo in trackingInfos) {
val localBranch = trackingInfo.localBranch
val remoteBranch = trackingInfo.remoteBranch
if (localBranch == currentBranch) {
currentBranchesMap[repo] = GitBranchPair(currentBranch, remoteBranch)
}
else {
// Fast-forward all non-current branches in the selection
val localBranchName = localBranch.name
val remoteBranchName = remoteBranch.nameForRemoteOperations
val fetchResult = fetchSupport.fetch(repo, trackingInfo.remote, "$remoteBranchName:$localBranchName")
try {
fetchResult.throwExceptionIfFailed()
successfullyUpdated.add(localBranchName)
}
catch (ignored: VcsException) {
fetchResult.showNotificationIfFailed(GitBundle.message("branches.update.failed"))
}
}
}
}
// Update all current branches in the selection
if (currentBranchesMap.isNotEmpty()) {
GitUpdateExecutionProcess(project,
repositories,
currentBranchesMap,
GitVcsSettings.getInstance(project).updateMethod,
false).execute()
}
}
override fun onSuccess() {
if (successfullyUpdated.isNotEmpty()) {
VcsNotifier.getInstance(project).notifySuccess(BRANCHES_UPDATE_SUCCESSFUL, "",
GitBundle.message("branches.selected.branches.updated.title",
successfullyUpdated.size,
successfullyUpdated.joinToString("\n")))
}
}
})
}
internal fun isTrackingInfosExist(branchNames: List<String>, repositories: List<GitRepository>) =
repositories
.flatMap(GitRepository::getBranchTrackInfos)
.any { trackingBranchInfo -> branchNames.any { branchName -> branchName == trackingBranchInfo.localBranch.name } }
internal fun hasRemotes(project: Project): Boolean {
return GitUtil.getRepositories(project).any { repository -> !repository.remotes.isEmpty() }
}
internal fun hasTrackingConflicts(conflictingLocalBranches: Map<GitRepository, GitLocalBranch>,
remoteBranchName: String): Boolean =
conflictingLocalBranches.any { (repo, branch) ->
val trackInfo = GitBranchUtil.getTrackInfoForBranch(repo, branch)
trackInfo != null && !GitReference.BRANCH_NAME_HASHING_STRATEGY.equals(remoteBranchName, trackInfo.remoteBranch.name)
}
internal abstract class BranchGroupingAction(private val key: GroupingKey,
icon: Icon? = null) : ToggleAction(key.text, key.description, icon), DumbAware {
abstract fun setSelected(e: AnActionEvent, key: GroupingKey, state: Boolean)
override fun isSelected(e: AnActionEvent) =
e.project?.let { GitVcsSettings.getInstance(it).branchSettings.isGroupingEnabled(key) } ?: false
override fun setSelected(e: AnActionEvent, state: Boolean) {
val project = e.project ?: return
val branchSettings = GitVcsSettings.getInstance(project).branchSettings
branchSettings.setGrouping(key, state)
setSelected(e, key, state)
}
}
| apache-2.0 | 3a41fe24774b5ede439f71567902bf9e | 47.165414 | 140 | 0.69591 | 5.120703 | false | false | false | false |
Cognifide/gradle-aem-plugin | launcher/src/main/kotlin/com/cognifide/gradle/aem/launcher/BuildScaffolder.kt | 1 | 11273 | package com.cognifide.gradle.aem.launcher
import java.util.*
class BuildScaffolder(private val launcher: Launcher) {
fun scaffold() {
saveBuildSrc()
saveProperties()
saveSettings()
saveRootBuildScript()
saveEnvBuildScript()
saveEnvSrcFiles()
}
private fun saveBuildSrc() = launcher.workFileOnce("buildSrc/build.gradle.kts") {
println("Saving Gradle build source script file '$this'")
writeText("""
repositories {
mavenLocal()
mavenCentral()
gradlePluginPortal()
}
dependencies {
implementation("com.cognifide.gradle:aem-plugin:${launcher.pluginVersion}")
implementation("com.cognifide.gradle:environment-plugin:2.0.3")
implementation("com.neva.gradle:fork-plugin:7.0.0")
}
""".trimIndent())
}
private fun saveProperties() = launcher.workFileOnce("gradle.properties") {
println("Saving Gradle properties file '$this'")
outputStream().use { output ->
Properties().apply {
putAll(defaultProps)
if (savePropsFlag) {
putAll(saveProps)
}
store(output, null)
}
}
}
private val savePropsFlag get() = launcher.args.contains(Launcher.ARG_SAVE_PROPS)
private val saveProps get() = launcher.args.filter { it.startsWith(Launcher.ARG_SAVE_PREFIX) }
.map { it.removePrefix(Launcher.ARG_SAVE_PREFIX) }
.map { it.substringBefore("=") to it.substringAfter("=") }
.toMap()
private val defaultProps get() = mapOf(
"org.gradle.logging.level" to "info",
"org.gradle.daemon" to "true",
"org.gradle.parallel" to "true",
"org.gradle.caching" to "true",
"org.gradle.jvmargs" to "-Xmx2048m -XX:MaxPermSize=512m -Dfile.encoding=UTF-8"
)
private fun saveRootBuildScript() = launcher.workFileOnce("build.gradle.kts") {
println("Saving root Gradle build script file '$this'")
writeText("""
plugins {
id("com.cognifide.aem.common")
id("com.neva.fork")
}
apply(from = "gradle/fork/props.gradle.kts")
if (file("gradle.user.properties").exists()) {
if (aem.mvnBuild.available) defaultTasks(":env:setup")
else defaultTasks(":env:instanceSetup")
}
allprojects {
repositories {
mavenCentral()
}
}
aem {
mvnBuild {
depGraph {
// softRedundantModule("ui.content" to "ui.apps")
}
discover()
}
}
""".trimIndent())
}
private fun saveEnvBuildScript() = launcher.workFileOnce("env/build.gradle.kts") {
println("Saving environment Gradle build script file '$this'")
writeText("""
plugins {
id("com.cognifide.aem.instance.local")
id("com.cognifide.environment")
}
val instancePassword = common.prop.string("instance.default.password")
val publishHttpUrl = common.prop.string("publish.httpUrl") ?: aem.findInstance("local-publish")?.httpUrl ?: "http://127.0.0.1:4503"
val dispatcherHttpUrl = common.prop.string("dispatcher.httpUrl") ?: "http://127.0.0.1:80"
val dispatcherTarUrl = common.prop.string("dispatcher.tarUrl") ?: "http://download.macromedia.com/dispatcher/download/dispatcher-apache2.4-linux-x86_64-4.3.3.tar.gz"
aem {
instance { // https://github.com/Cognifide/gradle-aem-plugin/blob/master/docs/instance-plugin.md
provisioner {
enableCrxDe()
configureReplicationAgentAuthor("publish") {
agent { configure(transportUri = "${'$'}publishHttpUrl/bin/receive?sling:authRequestLogin=1", transportUser = "admin", transportPassword = instancePassword, userId = "admin") }
version.set(publishHttpUrl)
}
configureReplicationAgentPublish("flush") {
agent { configure(transportUri = "${'$'}dispatcherHttpUrl/dispatcher/invalidate.cache") }
version.set(dispatcherHttpUrl)
}
}
}
}
environment { // https://github.com/Cognifide/gradle-environment-plugin
docker {
containers {
"httpd" {
resolve {
resolveFiles {
download(dispatcherTarUrl).use {
copyArchiveFile(it, "**/dispatcher-apache*.so", file("modules/mod_dispatcher.so"))
}
}
ensureDir("htdocs", "cache", "logs")
}
up {
symlink(
"/etc/httpd.extra/conf.modules.d/02-dispatcher.conf" to "/etc/httpd/conf.modules.d/02-dispatcher.conf",
"/etc/httpd.extra/conf.d/variables/default.vars" to "/etc/httpd/conf.d/variables/default.vars"
)
ensureDir("/usr/local/apache2/logs", "/var/www/localhost/htdocs", "/var/www/localhost/cache")
execShell("Starting HTTPD server", "/usr/sbin/httpd -k start")
}
reload {
cleanDir("/var/www/localhost/cache")
execShell("Restarting HTTPD server", "/usr/sbin/httpd -k restart")
}
dev {
watchRootDir(
"dispatcher/src/conf.d",
"dispatcher/src/conf.dispatcher.d",
"env/src/environment/httpd")
}
}
}
}
hosts {
"http://publish" { tag("publish") }
"http://dispatcher" { tag("dispatcher") }
}
healthChecks {
aem.findInstance("local-author")?.let { instance ->
http("Author Sites Editor", "${'$'}{instance.httpUrl}/sites.html") {
containsText("Sites")
options { basicCredentials = instance.credentials }
}
http("Author Replication Agent - Publish", "${'$'}{instance.httpUrl}/etc/replication/agents.author/publish.test.html") {
containsText("succeeded")
options { basicCredentials = instance.credentials }
}
}
aem.findInstance("local-publish")?.let { instance ->
http("Publish Replication Agent - Flush", "${'$'}{instance.httpUrl}/etc/replication/agents.publish/flush.test.html") {
containsText("succeeded")
options { basicCredentials = instance.credentials }
}
/*
http("Site Home", "http://publish/us/en.html") {
containsText("My Site")
}
*/
}
}
}
tasks {
instanceSetup { if (rootProject.aem.mvnBuild.available) dependsOn(":all:deploy") }
instanceResolve { dependsOn(":requireProps") }
instanceCreate { dependsOn(":requireProps") }
environmentUp { mustRunAfter(instanceAwait, instanceUp, instanceProvision, instanceSetup) }
environmentAwait { mustRunAfter(instanceAwait, instanceUp, instanceProvision, instanceSetup) }
}
""".trimIndent())
}
private fun saveEnvSrcFiles() {
launcher.workFileOnce("env/src/environment/docker-compose.yml.peb") {
println("Saving environment Docker compose file '$this'")
writeText("""
version: "3"
services:
httpd:
image: centos/httpd:latest
command: ["tail", "-f", "--retry", "/usr/local/apache2/logs/error.log"]
deploy:
replicas: 1
ports:
- "80:80"
networks:
- docker-net
volumes:
- "{{ rootPath }}/dispatcher/src/conf.d:/etc/httpd/conf.d"
- "{{ rootPath }}/dispatcher/src/conf.dispatcher.d:/etc/httpd/conf.dispatcher.d"
- "{{ sourcePath }}/httpd:/etc/httpd.extra"
- "{{ workPath }}/httpd/modules/mod_dispatcher.so:/etc/httpd/modules/mod_dispatcher.so"
- "{{ workPath }}/httpd/logs:/etc/httpd/logs"
{% if docker.runtime.safeVolumes %}
- "{{ workPath }}/httpd/cache:/var/www/localhost/cache"
- "{{ workPath }}/httpd/htdocs:/var/www/localhost/htdocs"
{% endif %}
{% if docker.runtime.hostInternalIpMissing %}
extra_hosts:
- "host.docker.internal:{{ docker.runtime.hostInternalIp }}"
{% endif %}
networks:
docker-net:
""".trimIndent())
}
launcher.workFileOnce("env/src/environment/httpd/conf.d/variables/default.vars") {
println("Saving environment variables file '$this'")
writeText("""
Define DOCROOT /var/www/localhost/cache
Define AEM_HOST host.docker.internal
Define AEM_IP 10.0.*.*
Define AEM_PORT 4503
Define DISP_LOG_LEVEL Warn
Define REWRITE_LOG_LEVEL Warn
Define EXPIRATION_TIME A2592000
""".trimIndent())
}
launcher.workFileOnce("env/src/environment/httpd/conf.modules.d/02-dispatcher.conf") {
println("Saving environment HTTPD dispatcher config file '$this'")
writeText("""
LoadModule dispatcher_module modules/mod_dispatcher.so
""".trimIndent())
}
}
private fun saveSettings() = launcher.workFileOnce("settings.gradle.kts") {
println("Saving Gradle settings file '$this'")
writeText("""
include(":env")
""".trimIndent())
}
} | apache-2.0 | 53c78d971f8e055e69f517b094aad478 | 43.039063 | 204 | 0.478577 | 5.292488 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/ActivityProvider.kt | 1 | 1008 | package ch.rmy.android.http_shortcuts.utils
import androidx.annotation.UiThread
import androidx.fragment.app.FragmentActivity
import ch.rmy.android.framework.extensions.safeRemoveIf
import ch.rmy.android.http_shortcuts.exceptions.NoActivityAvailableException
import java.lang.ref.WeakReference
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ActivityProvider
@Inject
constructor() {
fun getActivity(): FragmentActivity =
activeActivities.lastOrNull()?.get() ?: throw NoActivityAvailableException()
companion object {
private val activeActivities = mutableListOf<WeakReference<FragmentActivity>>()
@UiThread
fun registerActivity(activity: FragmentActivity) {
activeActivities.add(WeakReference(activity))
}
@UiThread
fun deregisterActivity(activity: FragmentActivity) {
activeActivities.safeRemoveIf { reference -> reference.get().let { it == null || it == activity } }
}
}
}
| mit | 6a9ea8ae90595c22585923f020bc8ed6 | 29.545455 | 111 | 0.735119 | 4.893204 | false | false | false | false |
minecrafter/Shortify | common/src/main/kotlin/com/redrield/shortify/common/TinyUrlShortener.kt | 1 | 563 | package com.redrield.shortify.common
import com.redrield.shortify.util.ShortifyUtil
import org.apache.commons.io.IOUtils
import org.apache.http.client.methods.HttpGet
import java.net.URLEncoder
class TinyUrlShortener : Shortener {
override fun getShortenedUrl(toShorten: String): String {
val url = "http://tinyurl.com/api-create.php?url=${URLEncoder.encode(toShorten, "UTF-8")}"
val client = ShortifyUtil.CLIENT
val req = HttpGet(url)
val res = client.execute(req)
return IOUtils.toString(res.entity.content)
}
} | mit | 581f1b53682c76927e0476e40818d58f | 34.25 | 98 | 0.726465 | 3.563291 | false | false | false | false |
siosio/nablarch-helper | src/main/java/siosio/repository/converter/PsiFileConverter.kt | 1 | 2606 | package siosio.repository.converter
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.module.*
import com.intellij.openapi.roots.impl.*
import com.intellij.openapi.vfs.*
import com.intellij.psi.*
import com.intellij.psi.search.*
import com.intellij.util.xml.*
import siosio.*
import siosio.repository.extension.*
import siosio.repository.xml.*
/**
*/
class PsiFileConverter : Converter<PsiFile>(), CustomReferenceConverter<PsiFile> {
override fun createReferences(value: GenericDomValue<PsiFile>?,
element: PsiElement?,
context: ConvertContext?): Array<PsiReference> {
return arrayOf(MyReference(element!!, value, context))
}
override fun fromString(s: String?, context: ConvertContext?): PsiFile? {
val project = context?.project ?: return null
val module = context.module ?: return null
val scope = GlobalSearchScope.moduleRuntimeScope(module, context.file.inTestScope(module))
return ResourceFileUtil.findResourceFileInScope(s, project, scope)?.let {
return PsiManager.getInstance(project).findFile(it)
}
}
override fun toString(t: PsiFile?, context: ConvertContext?): String? {
val project = context?.project ?: return null
val directoryIndex = DirectoryIndex.getInstance(project)
return directoryIndex.toResourceFile(t?.virtualFile ?: return null)
}
class MyReference(psiElement: PsiElement,
val file: GenericDomValue<PsiFile>?,
private val context: ConvertContext?) : PsiReferenceBase<PsiElement>(psiElement) {
override fun getVariants(): Array<out Any> {
context ?: return emptyArray()
val directoryIndex = DirectoryIndex.getInstance(myElement.project)
return XmlHelper.findNablarchXml(myElement) {
map {
LookupElementBuilder.create(directoryIndex.toResourceFile(it.virtualFile))
.withIcon(nablarchIcon)
.withAutoCompletionPolicy(AutoCompletionPolicy.ALWAYS_AUTOCOMPLETE)
}.toList().toTypedArray()
} ?: emptyArray()
}
override fun resolve(): PsiElement? {
return file?.value
}
}
}
private fun DirectoryIndex.toResourceFile(file: VirtualFile): String {
val packageName = getPackageName(file.parent)
return if (packageName.isNullOrEmpty()) {
file.name
} else {
packageName!!.replace('.', '/') + '/' + file.name
}
}
| apache-2.0 | b32a126f43031e15aec7cb228c5f1270 | 34.69863 | 104 | 0.646969 | 5.099804 | false | false | false | false |
wuan/bo-android | app/src/main/java/org/blitzortung/android/app/view/AlertView.kt | 1 | 12239 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.app.view
import android.content.Context
import android.graphics.*
import android.graphics.Paint.Align
import android.graphics.Paint.Style
import android.location.Location
import android.preference.PreferenceManager
import android.util.AttributeSet
import android.util.Log
import org.blitzortung.android.alert.AlertResult
import org.blitzortung.android.alert.data.AlertSector
import org.blitzortung.android.alert.event.AlertEvent
import org.blitzortung.android.alert.event.AlertResultEvent
import org.blitzortung.android.alert.handler.AlertHandler
import org.blitzortung.android.app.Main
import org.blitzortung.android.app.R
import org.blitzortung.android.data.MainDataHandler
import org.blitzortung.android.dialogs.AlertDialog
import org.blitzortung.android.dialogs.AlertDialogColorHandler
import org.blitzortung.android.location.LocationEvent
import org.blitzortung.android.map.overlay.color.ColorHandler
import org.blitzortung.android.util.TabletAwareView
import kotlin.math.cos
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sin
class AlertView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : TabletAwareView(context, attrs, defStyle) {
private val arcArea = RectF()
private val background = Paint()
private val sectorPaint = Paint()
private val lines = Paint(Paint.ANTI_ALIAS_FLAG)
private val textStyle = Paint(Paint.ANTI_ALIAS_FLAG)
private val warnText = Paint(Paint.ANTI_ALIAS_FLAG)
private val transfer = Paint()
private val alarmNotAvailableTextLines: Array<String> = context.getString(R.string.alarms_not_available)
.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
private lateinit var colorHandler: ColorHandler
private var intervalDuration: Int = 0
private var temporaryBitmap: Bitmap? = null
private var temporaryCanvas: Canvas? = null
private var alertResult: AlertResult? = null
private var location: Location? = null
private var enableDescriptionText = false
val alertEventConsumer: (AlertEvent?) -> Unit = { event ->
Log.v(Main.LOG_TAG, "AlertView alertEventConsumer received $event")
alertResult = if (event is AlertResultEvent) {
event.alertResult
} else {
null
}
invalidate()
}
val locationEventConsumer: (LocationEvent) -> Unit = { locationEvent ->
Log.v(Main.LOG_TAG, "AlertView received location ${locationEvent.location}")
location = locationEvent.location
val visibility = if (location != null) VISIBLE else INVISIBLE
setVisibility(visibility)
invalidate()
}
init {
with(lines) {
color = 0xff404040.toInt()
style = Style.STROKE
}
with(textStyle) {
color = 0xff404040.toInt()
textSize = 0.8f * this@AlertView.textSize * textSizeFactor(context)
}
background.color = 0xffb0b0b0.toInt()
}
fun enableLongClickListener(dataHandler: MainDataHandler, alertHandler: AlertHandler) {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
setOnLongClickListener {
AlertDialog(context, AlertDialogColorHandler(sharedPreferences), dataHandler, alertHandler)
.show()
true
}
}
fun enableDescriptionText() {
enableDescriptionText = true
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val getSize = fun(spec: Int) = MeasureSpec.getSize(spec)
val parentWidth = getSize(widthMeasureSpec) * sizeFactor
val parentHeight = getSize(heightMeasureSpec) * sizeFactor
val size = min(parentWidth.toInt(), parentHeight.toInt())
super.onMeasure(MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(size, MeasureSpec.EXACTLY))
}
override fun onDraw(canvas: Canvas) {
val size = max(width, height)
val pad = 4
val center = size / 2.0f
val radius = center - pad
prepareTemporaryBitmap(size)
val alertResult = alertResult
val temporaryCanvas = temporaryCanvas
val temporaryBitmap = temporaryBitmap
if (temporaryBitmap != null && temporaryCanvas != null) {
if (alertResult != null && intervalDuration != 0) {
val alertParameters = alertResult.parameters
val rangeSteps = alertParameters.rangeSteps
val rangeStepCount = rangeSteps.size
val radiusIncrement = radius / rangeStepCount
val sectorWidth = (360 / alertParameters.sectorLabels.size).toFloat()
with(lines) {
color = colorHandler.lineColor
strokeWidth = (size / 150).toFloat()
}
with(textStyle) {
textAlign = Align.CENTER
color = colorHandler.textColor
}
val actualTime = System.currentTimeMillis()
for (alertSector in alertResult.sectors) {
val startAngle = alertSector.minimumSectorBearing + 90f + 180f
val ranges = alertSector.ranges
for (rangeIndex in ranges.indices.reversed()) {
val alertSectorRange = ranges[rangeIndex]
val sectorRadius = (rangeIndex + 1) * radiusIncrement
val leftTop = center - sectorRadius
val bottomRight = center + sectorRadius
val drawColor = alertSectorRange.strikeCount > 0
if (drawColor) {
val color = colorHandler.getColor(actualTime, alertSectorRange.latestStrikeTimestamp, intervalDuration)
sectorPaint.color = color
}
arcArea.set(leftTop, leftTop, bottomRight, bottomRight)
temporaryCanvas.drawArc(arcArea, startAngle, sectorWidth, true, if (drawColor) sectorPaint else background)
}
}
for (alertSector in alertResult.sectors) {
val bearing = alertSector.minimumSectorBearing.toDouble()
temporaryCanvas.drawLine(center, center, center + (radius * sin(bearing / 180.0f * Math.PI)).toFloat(), center + (radius * -cos(bearing / 180.0f * Math.PI)).toFloat(), lines)
if (enableDescriptionText && size > TEXT_MINIMUM_SIZE) {
drawSectorLabel(center, radiusIncrement, alertSector, bearing + sectorWidth / 2.0)
}
}
textStyle.textAlign = Align.RIGHT
val textHeight = textStyle.getFontMetrics(null)
for (radiusIndex in 0 until rangeStepCount) {
val leftTop = center - (radiusIndex + 1) * radiusIncrement
val bottomRight = center + (radiusIndex + 1) * radiusIncrement
arcArea.set(leftTop, leftTop, bottomRight, bottomRight)
temporaryCanvas.drawArc(arcArea, 0f, 360f, false, lines)
if (enableDescriptionText && size > TEXT_MINIMUM_SIZE) {
val text = "%.0f".format(rangeSteps[radiusIndex])
temporaryCanvas.drawText(text, center + (radiusIndex + 0.85f) * radiusIncrement, center + textHeight / 3f, textStyle)
if (radiusIndex == rangeStepCount - 1) {
val distanceUnit = resources.getString(alertParameters.measurementSystem.unitNameString)
temporaryCanvas.drawText(distanceUnit, center + (radiusIndex + 0.85f) * radiusIncrement, center + textHeight * 1.33f, textStyle)
}
}
}
} else {
if (enableDescriptionText && size > TEXT_MINIMUM_SIZE) {
drawAlertOrLocationMissingMessage(center, temporaryCanvas)
} else {
if (location != null) {
drawOwnLocationSymbol(center, radius, size, temporaryCanvas)
}
}
}
canvas.drawBitmap(temporaryBitmap, 0f, 0f, transfer)
}
}
private fun drawAlertOrLocationMissingMessage(center: Float, canvas: Canvas) {
with(warnText) {
color = resources.getColor(R.color.RedWarn)
textAlign = Align.CENTER
textSize = DEFAULT_FONT_SIZE.toFloat()
val maxWidth = alarmNotAvailableTextLines.map { warnText.measureText(it) }.maxOrNull()
?: width.toFloat() - 20
val scale = (width - 20).toFloat() / maxWidth
//Now scale the text so we can use the whole width of the canvas
textSize = scale * DEFAULT_FONT_SIZE
}
for (line in alarmNotAvailableTextLines.indices) {
canvas.drawText(alarmNotAvailableTextLines[line], center, center + (line - 1) * warnText.getFontMetrics(null), warnText)
}
}
private fun drawOwnLocationSymbol(center: Float, radius: Float, size: Int, temporaryCanvas: Canvas) {
with(lines) {
color = colorHandler.lineColor
strokeWidth = (size / 80).toFloat()
}
val largeRadius = radius * 0.8f
val leftTop = center - largeRadius
val bottomRight = center + largeRadius
arcArea.set(leftTop, leftTop, bottomRight, bottomRight)
temporaryCanvas.drawArc(arcArea, 0f, 360f, false, lines)
val smallRadius = radius * 0.6f
temporaryCanvas.drawLine(center - smallRadius, center, center + smallRadius, center, lines)
temporaryCanvas.drawLine(center, center - smallRadius, center, center + smallRadius, lines)
}
private fun drawSectorLabel(center: Float, radiusIncrement: Float, sector: AlertSector, bearing: Double) {
if (bearing != 90.0) {
val text = sector.label
val textRadius = (sector.ranges.size - 0.5f) * radiusIncrement
temporaryCanvas!!.drawText(text, center + (textRadius * sin(bearing / 180.0 * Math.PI)).toFloat(), center + (textRadius * -cos(bearing / 180.0 * Math.PI)).toFloat() + textStyle.getFontMetrics(null) / 3f, textStyle)
}
}
private fun prepareTemporaryBitmap(size: Int) {
if (temporaryBitmap == null) {
val temporaryBitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
this.temporaryBitmap = temporaryBitmap
temporaryCanvas = Canvas(temporaryBitmap)
}
background.color = colorHandler.backgroundColor
background.xfermode = XFERMODE_CLEAR
temporaryCanvas!!.drawPaint(background)
background.xfermode = XFERMODE_SRC
}
fun setColorHandler(colorHandler: ColorHandler, intervalDuration: Int) {
this.colorHandler = colorHandler
this.intervalDuration = intervalDuration
}
override fun setBackgroundColor(backgroundColor: Int) {
background.color = backgroundColor
}
fun setAlpha(alpha: Int) {
transfer.alpha = alpha
}
companion object {
private const val TEXT_MINIMUM_SIZE = 300
private const val DEFAULT_FONT_SIZE = 20
private val XFERMODE_CLEAR = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
private val XFERMODE_SRC = PorterDuffXfermode(PorterDuff.Mode.SRC)
}
}
| apache-2.0 | 87f157c09a1b9bf8c0aa543f35a3dd49 | 39.793333 | 226 | 0.634336 | 4.982899 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/util/ParamUtil.kt | 1 | 12665 | package org.evomaster.core.problem.util
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestPath
import org.evomaster.core.problem.rest.param.*
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.collection.ArrayGene
import org.evomaster.core.search.gene.collection.FixedMapGene
import org.evomaster.core.search.gene.collection.PairGene
import org.evomaster.core.search.gene.datetime.DateTimeGene
import org.evomaster.core.search.gene.numeric.DoubleGene
import org.evomaster.core.search.gene.numeric.FloatGene
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.gene.numeric.LongGene
import org.evomaster.core.search.gene.optional.CustomMutationRateGene
import org.evomaster.core.search.gene.optional.FlexibleGene
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.sql.SqlAutoIncrementGene
import org.evomaster.core.search.gene.optional.NullableGene
import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene
import org.evomaster.core.search.gene.string.StringGene
/**
* this class used to handle binding values among params
*/
class ParamUtil {
companion object {
private const val DISRUPTIVE_NAME = "d_"
private const val BODYGENE_NAME = "body"
private const val separator = "@"
/**
* when identifying relationship based on the "tokens", if the token belongs to [GENERAL_NAMES],
* we may further use up-level token.
*/
private val GENERAL_NAMES = mutableListOf("id", "name", "value")
/**
* @return the actions which have the longest path in [actions]
*/
fun selectLongestPathAction(actions: List<RestCallAction>): List<RestCallAction> {
val max =
actions.asSequence().map { a -> a.path.levels() }
.maxOrNull()!!
return actions.filter { a -> a.path.levels() == max }
}
/**
* append param i.e., [paramToAppend] with additional info [paramsText]
*/
fun appendParam(paramsText: String, paramToAppend: String): String =
if (paramsText.isBlank()) paramToAppend else "$paramsText$separator$paramToAppend"
/**
* @return extracted params
*/
fun parseParams(params: String): List<String> = params.split(separator)
/**
* @return a field name with info of its object
*/
fun modifyFieldName(obj: ObjectGene, field: Gene): String {
return if (isGeneralName(field.name)) (obj.refType ?: "") + field.name else field.name
}
/**
* @return whether [name] is possibly matched with a field [fieldName] of [refType]
*/
fun compareField(fieldName: String, refType: String?, name: String): Boolean {
if (!isGeneralName(fieldName) || refType == null) return fieldName.equals(name, ignoreCase = true)
val prefix = "$refType$fieldName".equals(name, ignoreCase = true)
if (prefix) return true
return "$fieldName$refType".equals(name, ignoreCase = true)
}
/**
* @return are all [params] BodyParam?
*/
fun isAllBodyParam(params: List<Param>): Boolean {
return numOfBodyParam(params) == params.size
}
/**
* @return a number of BodyParam in [params]
*/
fun numOfBodyParam(params: List<Param>): Int {
return params.count { it is BodyParam }
}
/**
* @return do [params] contain any BodyParam?
*/
fun existBodyParam(params: List<Param>): Boolean {
return numOfBodyParam(params) > 0
}
/**
* @return whether [geneA] and [geneB] have same value.
*/
fun compareGenesWithValue(geneA: Gene, geneB: Gene): Boolean {
val geneAWithGeneBType = geneB.copy()
geneAWithGeneBType.bindValueBasedOn(geneA)
return when (geneB) {
is StringGene -> geneB.value == (geneAWithGeneBType as StringGene).value
is IntegerGene -> geneB.value == (geneAWithGeneBType as IntegerGene).value
is DoubleGene -> geneB.value == (geneAWithGeneBType as DoubleGene).value
is FloatGene -> geneB.value == (geneAWithGeneBType as FloatGene).value
is LongGene -> geneB.value == (geneAWithGeneBType as LongGene).value
else -> {
throw IllegalArgumentException("the type of $geneB is not supported")
}
}
}
/**
* @return the score of match between [target] and [source] which represents two genes respectively. Note that 0 means matched.
* @param doContain indicates whether 'contains' can be considered as match. i.e., target contains every token of sources.
*/
fun scoreOfMatch(target: String, source: String, doContain: Boolean): Int {
val targets = target.split(separator).filter { it != DISRUPTIVE_NAME }.toMutableList()
val sources = source.split(separator).filter { it != DISRUPTIVE_NAME }.toMutableList()
if (doContain) {
if (sources.toHashSet().map { s -> if (target.lowercase().contains(s.lowercase())) 1 else 0 }
.sum() == sources.toHashSet().size)
return 0
}
if (targets.toHashSet().size == sources.toHashSet().size) {
if (targets.containsAll(sources)) return 0
}
if (sources.contains(BODYGENE_NAME)) {
val sources_rbody = sources.filter { it != BODYGENE_NAME }.toMutableList()
if (sources_rbody.toHashSet().map { s -> if (target.lowercase().contains(s.lowercase())) 1 else 0 }
.sum() == sources_rbody.toHashSet().size)
return 0
}
if (targets.first() != sources.first())
return -1
else
return targets.plus(sources).filter { targets.contains(it).xor(sources.contains(it)) }.size
}
/**
* @return a map of a path of gene to gene
* @param parameters specifies the params which contains genes to be extracted
* @param tokensInPath specified the tokens of the path which refers to [parameters]
*/
fun geneNameMaps(parameters: List<Param>, tokensInPath: List<String>?): MutableMap<String, Gene> {
val maps = mutableMapOf<String, Gene>()
val pred = { gene: Gene -> (gene is DateTimeGene) }
parameters.forEach { p ->
p.gene.flatView(pred).filter {
!(it is ObjectGene ||
it is CustomMutationRateGene<*> ||
it is OptionalGene ||
it is ArrayGene<*> ||
it is FixedMapGene<*, *>)
}
.forEach { g ->
val names = getGeneNamesInPath(parameters, g)
if (names != null)
maps.put(genGeneNameInPath(names, tokensInPath), g)
}
}
return maps
}
/**
* @return whether [text] is a general name, e.g., 'id' or 'name'
*/
fun isGeneralName(text: String): Boolean {
return GENERAL_NAMES.any { it.equals(text, ignoreCase = true) }
}
private fun genGeneNameInPath(names: MutableList<String>, tokensInPath: List<String>?): String {
tokensInPath?.let {
return names.plus(tokensInPath).joinToString(separator)
}
return names.joinToString(separator)
}
private fun getGeneNamesInPath(parameters: List<Param>, gene: Gene): MutableList<String>? {
parameters.forEach { p ->
val names = mutableListOf<String>()
if (extractPathFromRoot(p.gene, gene, names)) {
return names
}
}
return null
}
/**
* extract a path from [comGene] to [gene]
* @param names contains the name of genes in the path
*
* @return can find [gene] in [comGene]?
*/
private fun extractPathFromRoot(comGene: Gene, gene: Gene, names: MutableList<String>): Boolean {
when (comGene) {
is ObjectGene -> return extractPathFromRoot(comGene, gene, names)
is PairGene<*, *> -> return extractPathFromRoot(comGene, gene, names)
is CustomMutationRateGene<*> -> return extractPathFromRoot(comGene, gene, names)
is OptionalGene -> return extractPathFromRoot(comGene, gene, names)
is ArrayGene<*> -> return extractPathFromRoot(comGene, gene, names)
is FixedMapGene<*, *> -> return extractPathFromRoot(comGene, gene, names)
else -> if (comGene == gene) {
names.add(comGene.name)
return true
} else return false
}
}
private fun extractPathFromRoot(comGene: ObjectGene, gene: Gene, names: MutableList<String>): Boolean {
comGene.fields.forEach {
if (extractPathFromRoot(it, gene, names)) {
names.add(it.name)
return true
}
}
return false
}
private fun extractPathFromRoot(comGene: CustomMutationRateGene<*>, gene: Gene, names: MutableList<String>): Boolean {
if (extractPathFromRoot(comGene.gene, gene, names)) {
names.add(comGene.name)
return true
}
return false
}
private fun extractPathFromRoot(comGene: OptionalGene, gene: Gene, names: MutableList<String>): Boolean {
if (extractPathFromRoot(comGene.gene, gene, names)) {
names.add(comGene.name)
return true
}
return false
}
private fun extractPathFromRoot(comGene: ArrayGene<*>, gene: Gene, names: MutableList<String>): Boolean {
comGene.getViewOfElements().forEach {
if (extractPathFromRoot(it, gene, names)) {
return true
}
}
return false
}
private fun extractPathFromRoot(comGene: PairGene<*, *>, gene: Gene, names: MutableList<String>): Boolean {
listOf(comGene.first, comGene.second).forEach {
if (extractPathFromRoot(it, gene, names)) {
names.add(it.name)
return true
}
}
return false
}
private fun extractPathFromRoot(comGene: FixedMapGene<*, *>, gene: Gene, names: MutableList<String>): Boolean {
comGene.getAllElements().forEach {
if (extractPathFromRoot(it, gene, names)) {
names.add(it.name)
return true
}
}
return false
}
fun getParamId(param: Param, path: RestPath): String {
return listOf(param.name).plus(path.getNonParameterTokens().reversed()).joinToString(separator)
}
fun generateParamId(list: Array<String>): String = list.joinToString(separator)
fun getValueGene(gene: Gene): Gene {
if (gene is OptionalGene) {
return getValueGene(gene.gene)
} else if (gene is CustomMutationRateGene<*>)
return getValueGene(gene.gene)
else if (gene is SqlPrimaryKeyGene) {
if (gene.gene is SqlAutoIncrementGene)
return gene
else return getValueGene(gene.gene)
} else if (gene is NullableGene) {
return getValueGene(gene.gene)
} else if (gene is FlexibleGene){
return getValueGene(gene.gene)
}
return gene
}
fun getObjectGene(gene: Gene): ObjectGene? {
if (gene is ObjectGene) {
return gene
} else if (gene is OptionalGene) {
return getObjectGene(gene.gene)
} else if (gene is CustomMutationRateGene<*>)
return getObjectGene(gene.gene)
else return null
}
}
} | lgpl-3.0 | 11bba3af64a556f64b3ae9141e818b7c | 40.123377 | 135 | 0.570707 | 4.937622 | false | false | false | false |
ilya-g/kotlinx.collections.immutable | benchmarks/commonMain/src/benchmarks/immutableList/builder/Remove.kt | 1 | 1942 | /*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package benchmarks.immutableList.builder
import benchmarks.*
import kotlinx.collections.immutable.PersistentList
import kotlinx.benchmark.*
@State(Scope.Benchmark)
open class Remove {
@Param(BM_1, BM_10, BM_100, BM_1000, BM_10000, BM_100000, BM_1000000, BM_10000000)
var size: Int = 0
@Param(IP_100, IP_99_09, IP_95, IP_70, IP_50, IP_30, IP_0)
var immutablePercentage: Double = 0.0
@Benchmark
fun addAndRemoveLast(): PersistentList.Builder<String> {
val builder = persistentListBuilderAdd(size, immutablePercentage)
for (i in 0 until size) {
builder.removeAt(builder.size - 1)
}
return builder
}
/**
* Adds [size] elements to an empty persistent list builder
* and then removes one element from the beginning.
*
* Measures (mean time and memory spent per `add` operation) + (time and memory spent on `removeAt` operation) / size.
*
* Expected time: [Add.addLast] + nearly constant.
* Expected memory: [Add.addLast] + nearly constant.
*/
@Benchmark
fun addAndRemoveFirst(): String {
val builder = persistentListBuilderAdd(size, immutablePercentage)
return builder.removeAt(0)
}
/**
* Adds [size] elements to an empty persistent list builder
* and then removes one element from the middle.
*
* Measures (mean time and memory spent per `add` operation) + (time and memory spent on `removeAt` operation) / size.
*
* Expected time: [Add.addLast] + nearly constant.
* Expected memory: [Add.addLast] + nearly constant.
*/
@Benchmark
fun addAndRemoveMiddle(): String {
val builder = persistentListBuilderAdd(size, immutablePercentage)
return builder.removeAt(size / 2)
}
} | apache-2.0 | 58809a214b5bf890d33ea6f520ebfcce | 32.5 | 122 | 0.664264 | 4.029046 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/api/user/UserApi.kt | 2 | 1886 | package me.proxer.library.api.user
import retrofit2.Retrofit
/**
* API for the User class.
*
* @author Ruben Gees
*/
class UserApi internal constructor(retrofit: Retrofit) {
private val internalApi = retrofit.create(InternalApi::class.java)
/**
* Returns the respective endpoint.
*/
fun login(username: String, password: String): LoginEndpoint {
return LoginEndpoint(internalApi, username, password)
}
/**
* Returns the respective endpoint.
*/
fun logout(): LogoutEndpoint {
return LogoutEndpoint(internalApi)
}
/**
* Returns the respective endpoint.
*/
fun topTen(userId: String? = null, username: String? = null): UserTopTenEndpoint {
return UserTopTenEndpoint(internalApi, userId, username)
}
/**
* Returns the respective endpoint.
*/
fun info(userId: String? = null, username: String? = null): UserInfoEndpoint {
return UserInfoEndpoint(internalApi, userId, username)
}
/**
* Returns the respective endpoint.
*/
fun about(userId: String? = null, username: String? = null): UserAboutEndpoint {
return UserAboutEndpoint(internalApi, userId, username)
}
/**
* Returns the respective endpoint.
*/
fun mediaList(userId: String? = null, username: String? = null): UserMediaListEndpoint {
return UserMediaListEndpoint(internalApi, userId, username)
}
/**
* Returns the respective endpoint.
*/
fun comments(userId: String? = null, username: String? = null): UserCommentsEndpoint {
return UserCommentsEndpoint(internalApi, userId, username)
}
/**
* Returns the respective endpoint.
*/
fun history(userId: String? = null, username: String? = null): UserHistoryEndpoint {
return UserHistoryEndpoint(internalApi, userId, username)
}
}
| gpl-3.0 | 23340944080ffb2c86591883279c7898 | 26.333333 | 92 | 0.651644 | 4.566586 | false | false | false | false |
Jire/Acelta | src/main/kotlin/com/acelta/util/Indexer.kt | 1 | 1220 | package com.acelta.util
class Indexer<T>(val capacity: Int) : MutableIterable<T> {
private val array = arrayOfNulls<Any?>(capacity)
private val reusableIterator = Iterator()
var size = 0
var highest = 0
operator fun get(index: Int) = array[index] as? T
operator fun set(index: Int, element: T?): T? {
val last = array[index]
array[index] = element
if (null === last && null !== element) {
size++
if (highest < index) highest = index
} else if (null !== last && null === element) {
size--
if (highest == index) highest--
}
return last as? T
}
fun nextIndex(): Int {
if (size == capacity)
throw IllegalStateException("There is no next index because the indexer is filled to capacity!")
for (i in 0..array.size - 1) if (null === array[i]) return i
throw IllegalStateException("Could not find an open index!")
}
private inner class Iterator : MutableIterator<T> {
internal var cursor = 0
override fun hasNext() = size > 0 && cursor <= highest
override tailrec fun next(): T = get(cursor++) ?: next()
override fun remove() {
set(cursor, null)
}
}
override fun iterator(): MutableIterator<T> {
reusableIterator.cursor = 0
return reusableIterator
}
} | gpl-3.0 | 54b406aa432dfea1511e2d174fe910cb | 22.480769 | 99 | 0.657377 | 3.475783 | false | false | false | false |
MaTriXy/Fuse-Game | Belote/app/src/main/java/com/elkriefy/games/belote/fragments/MainActivityFragment.kt | 1 | 5690 | package com.elkriefy.games.belote.fragments
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import com.elkriefy.games.belote.R
import com.elkriefy.games.belote.data.types.Player
import com.google.android.gms.auth.api.Auth
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
class MainActivityFragment : Fragment(), GoogleApiClient.OnConnectionFailedListener {
private val RC_SIGN_IN: Int = 78
private lateinit var loginWithGoogleButton: Button
private lateinit var joinToQue: Button
private var mGoogleApiClient: GoogleApiClient? = null
private var currentUserInQue = false
private lateinit var rootView: ViewGroup
private lateinit var playesQueReference: DatabaseReference
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
mGoogleApiClient = GoogleApiClient.Builder(context)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_main, container, false) as ViewGroup
return rootView
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
loginWithGoogleButton = view!!.findViewById<Button>(R.id.login_with_google)
joinToQue = view.findViewById<Button>(R.id.join_to_que)
var currentUser = FirebaseAuth.getInstance().currentUser
joinToQue.setOnClickListener {
when (currentUserInQue) {
true -> {
val database = FirebaseDatabase.getInstance()
database.getReference(Player.TABLE + "/" + FirebaseAuth.getInstance().currentUser!!.uid).removeValue()
currentUserInQue = false
joinToQue.text = getString(R.string.join)
}
else -> {
val database = FirebaseDatabase.getInstance()
var player = Player()
var currentUser1 = FirebaseAuth.getInstance().currentUser
player.id = currentUser1!!.uid
player.email = currentUser1!!.email
database.getReference(Player.TABLE + "/" + currentUser1.uid).setValue(player)
currentUserInQue = true
joinToQue.text = getString(R.string.leave)
}
}
}
when (currentUser) {
null -> {
loginWithGoogleButton.setOnClickListener {
signIn()
}
}
else -> {
loginWithGoogleButton.visibility = View.GONE
joinToQue.visibility = View.VISIBLE
Toast.makeText(context, "hello" + currentUser.displayName, Toast.LENGTH_SHORT).show()
}
}
}
private fun signIn() {
val signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient)
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val result = Auth.GoogleSignInApi.getSignInResultFromIntent(data)
if (result.isSuccess) {
// Google Sign In was successful, authenticate with Firebase
val account = result.signInAccount
firebaseAuthWithGoogle(account!!)
} else {
// Google Sign In failed, update UI appropriately
// ...
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
FirebaseAuth.getInstance().signInWithCredential(credential)
.addOnCompleteListener(activity, { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
val user = FirebaseAuth.getInstance().currentUser
Toast.makeText(context, "success", Toast.LENGTH_SHORT).show()
loginWithGoogleButton.visibility = View.GONE
joinToQue.visibility = View.VISIBLE
// activity.onBackPressed()
} else {
Toast.makeText(context, "falied", Toast.LENGTH_SHORT).show()
}
// ...
})
}
override fun onConnectionFailed(p0: ConnectionResult) {
}
}
| apache-2.0 | 93a3264a2f3ffebfd785595c347d9a65 | 40.838235 | 122 | 0.627768 | 5.332709 | false | false | false | false |
mikkokar/styx | system-tests/ft-suite/src/test/kotlin/com/hotels/styx/routing/ConditionRoutingSpec.kt | 1 | 3411 | /*
Copyright (C) 2013-2019 Expedia Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.hotels.styx.routing
import com.hotels.styx.api.HttpHeaderNames.HOST
import com.hotels.styx.api.HttpRequest.get
import com.hotels.styx.api.HttpResponseStatus.OK
import com.hotels.styx.client.StyxHttpClient
import com.hotels.styx.support.StyxServerProvider
import com.hotels.styx.support.proxyHttpHostHeader
import com.hotels.styx.support.proxyHttpsHostHeader
import io.kotlintest.Spec
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
import reactor.core.publisher.toMono
import java.nio.charset.StandardCharsets.UTF_8
class ConditionRoutingSpec : StringSpec() {
init {
"Routes HTTP protocol" {
val request = get("/11")
.header(HOST, styxServer().proxyHttpHostHeader())
.build();
client.send(request)
.toMono()
.block()
.let {
it!!.status() shouldBe (OK)
it.bodyAs(UTF_8) shouldBe ("Hello, from http server!")
}
}
"Routes HTTPS protocol" {
val request = get("/2")
.header(HOST, styxServer().proxyHttpsHostHeader())
.build();
client.secure()
.send(request)
.toMono()
.block()
.let {
it!!.status() shouldBe (OK)
it.bodyAs(UTF_8) shouldBe ("Hello, from secure server!")
}
}
}
val client: StyxHttpClient = StyxHttpClient.Builder().build()
val styxServer = StyxServerProvider("""
proxy:
connectors:
http:
port: 0
https:
port: 0
sslProvider: JDK
sessionTimeoutMillis: 300000
sessionCacheSize: 20000
admin:
connectors:
http:
port: 0
httpPipeline:
type: InterceptorPipeline
config:
handler:
type: ConditionRouter
config:
routes:
- condition: protocol() == "https"
destination:
name: proxy-to-https
type: StaticResponseHandler
config:
status: 200
content: "Hello, from secure server!"
fallback:
type: StaticResponseHandler
config:
status: 200
content: "Hello, from http server!"
""".trimIndent())
override fun beforeSpec(spec: Spec) {
styxServer.restart()
}
override fun afterSpec(spec: Spec) {
styxServer.stop()
}
}
| apache-2.0 | 6beef28114c187cd4a728c80ef566342 | 29.185841 | 80 | 0.545881 | 5.129323 | false | false | false | false |
faruktoptas/FancyShowCaseView | app/src/main/java/me/toptas/fancyshowcasesample/RecyclerViewActivity.kt | 1 | 2601 | /*
* Copyright (c) 2018. Faruk Toptaş
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.toptas.fancyshowcasesample
import android.os.Bundle
import android.view.View
import java.util.ArrayList
import kotlinx.android.synthetic.main.activity_recycler_view.*
import me.toptas.fancyshowcase.FancyShowCaseView
import android.os.Build
import android.view.ViewTreeObserver
import androidx.recyclerview.widget.LinearLayoutManager
class RecyclerViewActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
val modelList = ArrayList<MyModel>()
for (i in 0..24) {
modelList.add(MyModel("Item $i"))
}
val layoutManager = LinearLayoutManager(this)
val adapter = MyRecyclerViewAdapter(modelList)
adapter.setClickListener(View.OnClickListener { v ->
focus(v)
})
recyclerView.adapter = adapter
recyclerView.layoutManager = layoutManager
recyclerView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val width = recyclerView.width
val height = recyclerView.height
if (width > 0 && height > 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
recyclerView.viewTreeObserver.removeOnGlobalLayoutListener(this)
} else {
recyclerView.viewTreeObserver.removeGlobalOnLayoutListener(this)
}
}
focus(layoutManager.findViewByPosition(2)!!.findViewById(R.id.ivIcon))
}
})
}
private fun focus(v: View) {
FancyShowCaseView.Builder(this@RecyclerViewActivity)
.focusOn(v)
.title("Focus RecyclerView Items")
.enableAutoTextPosition()
.build()
.show()
}
}
| apache-2.0 | 8e49e85319e8f78be172afc3866bcd30 | 33.666667 | 114 | 0.652692 | 4.924242 | false | false | false | false |
VerifAPS/verifaps-lib | symbex/src/main/kotlin/edu/kit/iti/formal/automation/smt/DefaultS2STranslator.kt | 1 | 3957 | package edu.kit.iti.formal.automation.smt
/*-
* #%L
* iec-symbex
* %%
* Copyright (C) 2017 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.smt.*
import edu.kit.iti.formal.smv.EnumType
import edu.kit.iti.formal.smv.SMVType
import edu.kit.iti.formal.smv.SMVTypes
import edu.kit.iti.formal.smv.SMVWordType
import edu.kit.iti.formal.smv.ast.SLiteral
import java.math.BigInteger
/**
* Default translator for types from smv to smt. Uses bit vectors!
*
* @author Alexander Weigl
* @version 1 (15.10.17)
*/
class DefaultS2STranslator : S2SDataTypeTranslator {
override fun translate(datatype: SMVType): SExpr {
if (SMVTypes.BOOLEAN == datatype)
return SSymbol(SMTProgram.SMT_BOOLEAN)
if (datatype is SMVWordType) {
val width = datatype.width
val bv = SList()
bv.add(SSymbol("_"))
bv.add(SSymbol("BitVec"))
bv.add(SSymbol(width.toString()))
return bv
}
if (datatype is EnumType) {
return SExprFacade.parseExpr("(_ BitVec 16)")
}
throw IllegalArgumentException()
}
override fun translate(l: SLiteral): SExpr {
val dataType = l.dataType
when (dataType) {
SMVTypes.BOOLEAN ->
return SSymbol(if (l.value.toString().equals("TRUE", ignoreCase = true)) "true" else "false")
is SMVWordType -> {
val prefix = "#b"
val b = l.value as BigInteger
return SSymbol("#b" + twoComplement(b, dataType.width))
}
is EnumType -> {
val et = l.dataType as EnumType?
val value = l.value as String
val i = et!!.values.indexOf(value)
return SSymbol("#b" + twoComplement(BigInteger.valueOf(i.toLong()), 16))
}
SMVTypes.INT -> {
return SInteger(l.value as BigInteger)
}
else ->
throw IllegalArgumentException("Unsupported data type: ${l.dataType}")
}
}
companion object {
fun paddedString(length: Int, fill: Char, s: String): CharArray {
val sb = CharArray(Math.max(length, s.length))
var i = 0
while (i < length - s.length) {
sb[i] = fill
i++
}
var j = 0
while (j < s.length) {
sb[i] = s[j]
j++
i++
}
return sb
}
fun twoComplement(integer: BigInteger, bitLength: Int): String {
val pos = if (integer.signum() < 0) integer.negate() else integer
val binary = pos.toString(2)
val b = paddedString(bitLength, '0', binary)
if (integer.signum() < 0) {
//complement
for (i in b.indices) {
b[i] = if (b[i] == '1') '0' else '1'
}
//+1
for (i in b.indices.reversed()) {
b[i] = (if (b[i] == '1') '0' else '1').toChar()
if (b[i] == '1') {
break
}
}
}
return String(b)
}
}
}
| gpl-3.0 | 449690b13e6f838b4853df49ae1f921a | 30.656 | 109 | 0.535759 | 4.083591 | false | false | false | false |
duftler/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/MessageCompatibilityTest.kt | 1 | 2595 | /*
* Copyright 2018 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.fasterxml.jackson.module.kotlin.convertValue
import com.netflix.spinnaker.orca.jackson.OrcaObjectMapper
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.q.Message
import org.assertj.core.api.Assertions.assertThat
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import java.util.UUID
internal object MessageCompatibilityTest : Spek({
describe("deserializing ContinueParentStage") {
val mapper = OrcaObjectMapper.newInstance().apply {
registerSubtypes(ContinueParentStage::class.java)
}
val json = mapOf(
"kind" to "continueParentStage",
"executionType" to "PIPELINE",
"executionId" to UUID.randomUUID().toString(),
"application" to "covfefe",
"stageId" to UUID.randomUUID().toString()
)
given("an older message with no syntheticStageOwner") {
on("deserializing the JSON") {
val message = mapper.convertValue<Message>(json)
it("doesn't blow up") {
assertThat(message).isInstanceOf(ContinueParentStage::class.java)
}
it("defaults the missing field") {
assertThat((message as ContinueParentStage).phase).isEqualTo(STAGE_BEFORE)
}
}
}
given("a newer message with a syntheticStageOwner") {
val newJson = json + mapOf("phase" to "STAGE_AFTER")
on("deserializing the JSON") {
val message = mapper.convertValue<Message>(newJson)
it("doesn't blow up") {
assertThat(message).isInstanceOf(ContinueParentStage::class.java)
}
it("deserializes the new field") {
assertThat((message as ContinueParentStage).phase).isEqualTo(STAGE_AFTER)
}
}
}
}
})
| apache-2.0 | 0e3a4a378ac051cc80f665d4e866751f | 32.701299 | 84 | 0.710212 | 4.317804 | false | false | false | false |
NLPIE/BioMedICUS | biomedicus-core/src/main/kotlin/edu/umn/biomedicus/sh/Nicotine.kt | 1 | 14526 | /*
* Copyright (c) 2018 Regents of the University of Minnesota.
*
* 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 edu.umn.biomedicus.sh
import edu.umn.biomedicus.annotations.Setting
import edu.umn.biomedicus.common.SequenceDetector
import edu.umn.biomedicus.dependencies
import edu.umn.biomedicus.framework.TagEx
import edu.umn.biomedicus.framework.TagExFactory
import edu.umn.biomedicus.parsing.findHead
import edu.umn.biomedicus.sentences.Sentence
import edu.umn.biomedicus.time.TemporalPhrase
import edu.umn.biomedicus.tokenization.ParseToken
import edu.umn.biomedicus.tokenization.Token
import edu.umn.nlpengine.*
import java.io.File
import java.nio.file.Path
import javax.inject.Inject
import javax.inject.Singleton
/**
* The verb that is a head for nicotine social history information.
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineRelevant(
override val startIndex: Int,
override val endIndex: Int
) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* The unit of a nicotine usage measurement, used in [NicotineAmount] detection.
* E.g. cigarettes, packs, tins.
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineUnit(override val startIndex: Int, override val endIndex: Int) : Label()
/**
* The quantity and unit of a nicotine usage measurement. E.g. 1 - 5 packs
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineAmount(override val startIndex: Int, override val endIndex: Int) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* How often nicotine is used. E.g. daily, infrequently
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineFrequency(override val startIndex: Int, override val endIndex: Int) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* The time period nicotine usage occurs/occurred in or over. Includes phrases like
* "for thirty years" or "at night" or "weekend nights"
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineTemporal(override val startIndex: Int, override val endIndex: Int) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* The type of nicotine, cigarettes, chewing tobacco, etc.
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineType(override val startIndex: Int, override val endIndex: Int) : Label()
/**
* A word that indicates whether usage is ongoing or has ceased.
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineStatus(override val startIndex: Int, override val endIndex: Int) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* The method how nicotine usage occurred. E.g. smoked, chewed, etc.
*/
@LabelMetadata(classpath = "biomedicus.v2", distinct = true)
data class NicotineMethod(override val startIndex: Int, override val endIndex: Int) : Label() {
constructor(textRange: TextRange) : this(textRange.startIndex, textRange.endIndex)
}
/**
* Detects [NicotineRelevant] labels from [NicotineCue] labels in text.
*/
class NicotineRelevantLabeler : DocumentTask {
override fun run(document: Document) {
val relevants = document.findRelevantAncestors(document.labelIndex<NicotineCue>())
.map { NicotineRelevant(it) }
document.labelAll(relevants)
}
}
/**
* Detects if a phrase is a nicotine dependant phrase by seeing if it is, or has a
* [NicotineRelevant] ancestor
*/
internal fun Document.isNicotineDep(textRange: TextRange): Boolean {
val insideSpan = dependencies().inside(textRange)
val nicotineRelevants = labelIndex<NicotineRelevant>()
val alcoholRelevants = labelIndex<AlcoholRelevant>()
val drugRelevants = labelIndex<DrugRelevant>()
val phraseRoot = findHead(insideSpan)
phraseRoot.selfAndParentIterator().forEach {
if (nicotineRelevants.containsSpan(it)) return true
if (alcoholRelevants.containsSpan(it) || drugRelevants.containsSpan(it)) return false
}
return false
}
/**
* The model for nicotine amount units.
*/
@Singleton
class NicotineAmountUnits(
val detector: SequenceDetector<String, Token>
) {
@Inject internal constructor(
@Setting("sh.nicotine.amountUnits.asDataPath") path: Path
) : this(SequenceDetector.loadFromFile(path) { a, b: Token ->
b.text.startsWith(a, true)
})
}
/**
* Detects and labels [NicotineUnit] instances.
*/
class NicotineUnitDetector(
private val detector: SequenceDetector<String, Token>
) : DocumentTask {
@Inject internal constructor(amountUnits: NicotineAmountUnits) : this(amountUnits.detector)
override fun run(document: Document) {
val sentences = document.labelIndex<Sentence>()
val tokens = document.labelIndex<ParseToken>()
val candidates = document.labelIndex<NicotineCandidate>()
val labeler = document.labeler<NicotineUnit>()
candidates
.map { sentences.inside(it) }
.forEach {
it.map { tokens.inside(it).asList() }
.forEach { sentenceTokens ->
detector.detectAll(sentenceTokens).forEach {
val unit = NicotineUnit(
sentenceTokens[it.first].startIndex,
sentenceTokens[it.last].endIndex
)
if (document.isNicotineDep(unit)) labeler.add(unit)
}
}
}
}
}
/**
* The TagEx search expression for nicotine amounts.
*
* @property expr the nicotine amount TagEx search expression
*/
@Singleton
class NicotineAmountSearchExpr(val expr: TagEx) {
@Inject internal constructor(
searchExprFactory: TagExFactory,
@Setting("sh.nicotine.amountExpr.asDataPath") path: Path
) : this(searchExprFactory.parse(path.toFile().readText()))
}
/**
* Detects and labels instances of [NicotineAmount] in text using the nicotine amount TagEx pattern.
*
* @property expr the nicotine amount TagEx search expression
*/
class NicotineAmountDetector(private val expr: TagEx) : DocumentTask {
@Inject internal constructor(
nicotineAmountSearchExpr: NicotineAmountSearchExpr
) : this(nicotineAmountSearchExpr.expr)
override fun run(document: Document) {
val labeler = document.labeler<NicotineAmount>()
document.labelIndex<NicotineCandidate>()
.asSequence()
.flatMap { expr.findAll(document, it) }
.filter(document::isNicotineDep)
.map(::NicotineAmount)
.forEach(labeler::add)
}
}
/**
* Detects and labels [NicotineFrequency] instances in text using the general [UsageFrequency]
* label.
*/
class NicotineFrequencyDetector : DocumentTask {
override fun run(document: Document) {
val nicotineCandidates = document.labelIndex<NicotineCandidate>()
val amounts = document.labelIndex<NicotineAmount>()
val usageFrequencies = document.labelIndex<UsageFrequency>()
val labeler = document.labeler<NicotineFrequency>()
for (nicotineCandidate in nicotineCandidates) {
usageFrequencies
.inside(nicotineCandidate)
.asSequence()
.filter { amounts.containing(it).isEmpty() }
.filter { document.isNicotineDep(it) }
.map { NicotineFrequency(it) }
.forEach { labeler.add(it) }
}
}
}
/**
* Detects and labels [NicotineTemporal] instances in text using the general [TemporalPhrase].
*/
class NicotineTemporalDetector : DocumentTask {
override fun run(document: Document) {
val nicotineCandidates = document.labelIndex<NicotineCandidate>()
val frequencies = document.labelIndex<NicotineFrequency>()
val amounts = document.labelIndex<NicotineAmount>()
val temporalPhrases = document.labelIndex<TemporalPhrase>()
val temporalLabeler = document.labeler<NicotineTemporal>()
for (nicotineCandidate in nicotineCandidates) {
temporalPhrases.inside(nicotineCandidate)
.asSequence()
.filter { amounts.containing(it).isEmpty() }
.filter { frequencies.containing(it).isEmpty() }
.filter { document.isNicotineDep(it) }
.forEach { temporalLabeler.add(NicotineTemporal(it)) }
}
}
}
/**
* The model for nicotine types.
*/
@Singleton
class NicotineTypes(val detector: SequenceDetector<String, Token>) {
@Inject internal constructor(
@Setting("sh.nicotine.types.asDataPath") path: Path
) : this(SequenceDetector.loadFromFile(path, tokenTextEquals))
}
/**
* Detects and labels [NicotineType] instances in text using the nicotine types model.
*/
class NicotineTypeDetector(
private val detector: SequenceDetector<String, Token>
) : DocumentTask {
@Inject internal constructor(nicotineTypes: NicotineTypes) : this(nicotineTypes.detector)
override fun run(document: Document) {
val candidates = document.labelIndex<NicotineCandidate>()
val tokens = document.labelIndex<ParseToken>()
val labeler = document.labeler<NicotineType>()
candidates
.map { tokens.inside(it).asList() }
.forEach { candidateTokens ->
detector.detectAll(candidateTokens)
.forEach {
val type = NicotineType(
candidateTokens[it.first].startIndex,
candidateTokens[it.last].endIndex
)
if (document.isNicotineDep(type)) labeler.add(type)
}
}
}
}
/**
* Model for nicotine status phrases.
*/
@Singleton
class NicotineStatusPhrases(val detector: SequenceDetector<String, ParseToken>) {
@Inject internal constructor(
@Setting("sh.nicotine.statusPhrases.asDataPath") path: Path
) : this(SequenceDetector.loadFromFile(path) { string, token: ParseToken ->
token.text.compareTo(string, true) == 0
})
}
/**
* Detects nicotine status phrases in text using the nicotine status model and the general
* [UsageStatusPhrases]
*/
class NicotineStatusDetector(
private val detector: SequenceDetector<String, ParseToken>
) : DocumentTask {
@Inject internal constructor(
statusPhrases: NicotineStatusPhrases
) : this(statusPhrases.detector)
override fun run(document: Document) {
val tokens = document.labelIndex<ParseToken>()
val usageStatuses = document.labelIndex<UsageStatus>()
val labeler = document.labeler<NicotineStatus>()
document.labelIndex<NicotineCandidate>()
.onEach {
usageStatuses.inside(it)
.filter { document.isNicotineDep(it) }
.forEach {
labeler.add(NicotineStatus(it))
}
}
.map { tokens.inside(it).asList() }
.forEach { sentenceTokens ->
detector.detectAll(sentenceTokens).forEach {
val status = NicotineStatus(sentenceTokens[it.first].startIndex,
sentenceTokens[it.last].endIndex)
if (document.isNicotineDep(status)) labeler.add(status)
}
}
}
}
/**
* Nicotine methods model.
*/
@Singleton
class NicotineMethodPhrases(val detector: SequenceDetector<String, ParseToken>) {
@Inject internal constructor(
@Setting("sh.nicotine.methodPhrases.asDataPath") path: Path
) : this(SequenceDetector.loadFromFile(path) { string, token: ParseToken ->
token.text.compareTo(string, true) == 0
})
}
/**
* Detects and labels instances of [NicotineMethod] in text using the [GenericMethodPhrase]
* instances and the nicotine methods model.
*/
class NicotineMethodDetector(
private val detector: SequenceDetector<String, ParseToken>
) : DocumentTask {
@Inject internal constructor(phrases: NicotineMethodPhrases) : this(phrases.detector)
override fun run(document: Document) {
val candidates = document.labelIndex<NicotineCandidate>()
val tokens = document.labelIndex<ParseToken>()
val genericMethods = document.labelIndex<GenericMethodPhrase>()
val labeler = document.labeler<NicotineMethod>()
candidates
.onEach {
genericMethods
.inside(it)
.filter { document.isNicotineDep(it) }
.forEach {
labeler.add(NicotineMethod(it))
}
}
.map { tokens.inside(it).asList() }
.forEach { sentenceTokens ->
detector.detectAll(sentenceTokens)
.map {
NicotineMethod(sentenceTokens[it.first].startIndex,
sentenceTokens[it.last].endIndex)
}
.filter { document.isNicotineDep(it) }
.forEach {
labeler.add(it)
}
}
}
}
| apache-2.0 | 43e47c4341168cb891b90abb243e48f3 | 35.497487 | 100 | 0.636376 | 4.858194 | false | false | false | false |
funfunStudy/algorithm | kotlin/src/main/kotlin/DigitalRoot.kt | 1 | 828 | import java.util.Scanner
/**
* Created by Lazysoul on 2017. 7. 18..
*/
object DigitalRoot {
@JvmStatic
fun main(args: Array<String>) {
val sc = Scanner(System.`in`)
val result = getResult(sc, listOf())
require(result == listOf(6, 3))
}
tailrec fun getResult(sc: Scanner, acc: List<Int>): List<Int> {
val value = sc.nextLine()
return when (value) {
"0" -> acc
else -> getResult(sc, acc.plus(getDigitalRoot(value)))
}
}
tailrec fun getDigitalRoot(value: String): Int {
return if (value.length == 1) {
value.toInt()
} else {
getDigitalRoot(value
.map { it.toInt() - 48 }
.reduce { x, y -> x + y }
.toString())
}
}
} | mit | 2b791741353c28f15b449ebc41c8bbca | 22.685714 | 67 | 0.490338 | 3.942857 | false | false | false | false |
AsynkronIT/protoactor-kotlin | proto-mailbox/src/main/kotlin/actor/proto/mailbox/DefaultMailbox.kt | 1 | 3124 | package actor.proto.mailbox
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
private val emptyStats = arrayOf<MailboxStatistics>()
typealias MailboxQueue = Queue<Any>
class DefaultMailbox(private val systemMessages: MailboxQueue,
private val userMailbox: MailboxQueue,
private val stats: Array<MailboxStatistics> = emptyStats) : Mailbox {
private val status = AtomicInteger(MailboxStatus.IDLE)
private val sysCount = AtomicInteger(0)
private val userCount = AtomicInteger(0)
private lateinit var dispatcher: Dispatcher
private lateinit var invoker: MessageInvoker
private var suspended: Boolean = false
fun status(): Int = status.get()
override fun postUserMessage(msg: Any) {
if (userMailbox.offer(msg)) {
userCount.incrementAndGet()
schedule()
for (stats in stats) stats.messagePosted(msg)
} else {
for (stats in stats) stats.messageDropped(msg)
}
}
override fun postSystemMessage(msg: Any) {
sysCount.incrementAndGet()
systemMessages.add(msg)
for (stats in stats) stats.messagePosted(msg)
schedule()
}
override fun registerHandlers(invoker: MessageInvoker, dispatcher: Dispatcher) {
this.invoker = invoker
this.dispatcher = dispatcher
}
override fun start() {
for (stats in stats) stats.mailboxStarted()
}
override suspend fun run() {
var msg: Any? = null
try {
for (i in 0 until dispatcher.throughput) {
if (sysCount.get() > 0) {
msg = systemMessages.poll()
sysCount.decrementAndGet()
if (msg != null) {
when (msg) {
is SuspendMailbox -> suspended = true
is ResumeMailbox -> suspended = false
}
invoker.invokeSystemMessage(msg as SystemMessage)
for (stat in stats) stat.messageReceived(msg)
}
}
if (!suspended && userCount.get() > 0) {
msg = userMailbox.poll()
userCount.decrementAndGet()
if (msg == null) break
else {
invoker.invokeUserMessage(msg)
for (stat in stats) stat.messageReceived(msg)
}
} else {
break
}
}
} catch (e: Exception) {
if (msg != null) invoker.escalateFailure(e, msg)
}
status.set(MailboxStatus.IDLE)
if (sysCount.get() > 0 || (!suspended && userCount.get() > 0)) {
schedule()
} else {
for (stat in stats) stat.mailboxEmpty()
}
}
private fun schedule() {
val wasIdle = status.compareAndSet(MailboxStatus.IDLE, MailboxStatus.BUSY)
if (wasIdle) {
dispatcher.schedule(this)
}
}
}
| apache-2.0 | daf3286172b15325008255981c13c106 | 31.206186 | 90 | 0.538412 | 5.063209 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/bean/reshttp/ResQuickTestCount.kt | 1 | 408 | package com.fuyoul.sanwenseller.bean.reshttp
/**
* @author: chen
* @CreatDate: 2017\11\4 0004
* @Desc:
*/
class ResQuickTestCount {
// {
//
// "date":0,
// "maxOrdersCount":0,
// "masterId":0,
// "allowableOrdersCount":0
// }
var isChanged: Int = 0
var date: String = ""
var maxOrdersCount = 0
var masterId: Long = 0
var restOrdersCount = 0
} | apache-2.0 | 16ec267778764309e78bb8e0195db6bf | 15.36 | 44 | 0.556373 | 3.138462 | false | false | false | false |
Kotlin/anko | anko/library/generated/sdk28/src/main/java/Views.kt | 2 | 113433 | @file:JvmName("Sdk28ViewsKt")
package org.jetbrains.anko
import org.jetbrains.anko.custom.*
import org.jetbrains.anko.AnkoViewDslMarker
import android.view.ViewManager
import android.view.ViewGroup.LayoutParams
import android.app.Activity
import android.app.Fragment
import android.content.Context
import android.os.Build
import android.widget.*
@PublishedApi
internal object `$$Anko$Factories$Sdk28View` {
val MEDIA_ROUTE_BUTTON = { ctx: Context -> android.app.MediaRouteButton(ctx) }
val GESTURE_OVERLAY_VIEW = { ctx: Context -> android.gesture.GestureOverlayView(ctx) }
val EXTRACT_EDIT_TEXT = { ctx: Context -> android.inputmethodservice.ExtractEditText(ctx) }
val TV_VIEW = { ctx: Context -> android.media.tv.TvView(ctx) }
val G_L_SURFACE_VIEW = { ctx: Context -> android.opengl.GLSurfaceView(ctx) }
val SURFACE_VIEW = { ctx: Context -> android.view.SurfaceView(ctx) }
val TEXTURE_VIEW = { ctx: Context -> android.view.TextureView(ctx) }
val VIEW = { ctx: Context -> android.view.View(ctx) }
val VIEW_STUB = { ctx: Context -> android.view.ViewStub(ctx) }
val WEB_VIEW = { ctx: Context -> android.webkit.WebView(ctx) }
val ADAPTER_VIEW_FLIPPER = { ctx: Context -> android.widget.AdapterViewFlipper(ctx) }
val ANALOG_CLOCK = { ctx: Context -> android.widget.AnalogClock(ctx) }
val AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.AutoCompleteTextView(ctx) }
val BUTTON = { ctx: Context -> android.widget.Button(ctx) }
val CALENDAR_VIEW = { ctx: Context -> android.widget.CalendarView(ctx) }
val CHECK_BOX = { ctx: Context -> android.widget.CheckBox(ctx) }
val CHECKED_TEXT_VIEW = { ctx: Context -> android.widget.CheckedTextView(ctx) }
val CHRONOMETER = { ctx: Context -> android.widget.Chronometer(ctx) }
val DATE_PICKER = { ctx: Context -> android.widget.DatePicker(ctx) }
val DIALER_FILTER = { ctx: Context -> android.widget.DialerFilter(ctx) }
val DIGITAL_CLOCK = { ctx: Context -> android.widget.DigitalClock(ctx) }
val EDIT_TEXT = { ctx: Context -> android.widget.EditText(ctx) }
val EXPANDABLE_LIST_VIEW = { ctx: Context -> android.widget.ExpandableListView(ctx) }
val IMAGE_BUTTON = { ctx: Context -> android.widget.ImageButton(ctx) }
val IMAGE_VIEW = { ctx: Context -> android.widget.ImageView(ctx) }
val LIST_VIEW = { ctx: Context -> android.widget.ListView(ctx) }
val MULTI_AUTO_COMPLETE_TEXT_VIEW = { ctx: Context -> android.widget.MultiAutoCompleteTextView(ctx) }
val NUMBER_PICKER = { ctx: Context -> android.widget.NumberPicker(ctx) }
val PROGRESS_BAR = { ctx: Context -> android.widget.ProgressBar(ctx) }
val QUICK_CONTACT_BADGE = { ctx: Context -> android.widget.QuickContactBadge(ctx) }
val RADIO_BUTTON = { ctx: Context -> android.widget.RadioButton(ctx) }
val RATING_BAR = { ctx: Context -> android.widget.RatingBar(ctx) }
val SEARCH_VIEW = { ctx: Context -> android.widget.SearchView(ctx) }
val SEEK_BAR = { ctx: Context -> android.widget.SeekBar(ctx) }
val SLIDING_DRAWER = { ctx: Context -> android.widget.SlidingDrawer(ctx, null) }
val SPACE = { ctx: Context -> android.widget.Space(ctx) }
val SPINNER = { ctx: Context -> android.widget.Spinner(ctx) }
val STACK_VIEW = { ctx: Context -> android.widget.StackView(ctx) }
val SWITCH = { ctx: Context -> android.widget.Switch(ctx) }
val TAB_HOST = { ctx: Context -> android.widget.TabHost(ctx) }
val TAB_WIDGET = { ctx: Context -> android.widget.TabWidget(ctx) }
val TEXT_CLOCK = { ctx: Context -> android.widget.TextClock(ctx) }
val TEXT_VIEW = { ctx: Context -> android.widget.TextView(ctx) }
val TIME_PICKER = { ctx: Context -> android.widget.TimePicker(ctx) }
val TOGGLE_BUTTON = { ctx: Context -> android.widget.ToggleButton(ctx) }
val TWO_LINE_LIST_ITEM = { ctx: Context -> android.widget.TwoLineListItem(ctx) }
val VIDEO_VIEW = { ctx: Context -> android.widget.VideoView(ctx) }
val VIEW_FLIPPER = { ctx: Context -> android.widget.ViewFlipper(ctx) }
val ZOOM_BUTTON = { ctx: Context -> android.widget.ZoomButton(ctx) }
val ZOOM_CONTROLS = { ctx: Context -> android.widget.ZoomControls(ctx) }
}
inline fun ViewManager.mediaRouteButton(): android.app.MediaRouteButton = mediaRouteButton() {}
inline fun ViewManager.mediaRouteButton(init: (@AnkoViewDslMarker android.app.MediaRouteButton).() -> Unit): android.app.MediaRouteButton {
return ankoView(`$$Anko$Factories$Sdk28View`.MEDIA_ROUTE_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedMediaRouteButton(theme: Int = 0): android.app.MediaRouteButton = themedMediaRouteButton(theme) {}
inline fun ViewManager.themedMediaRouteButton(theme: Int = 0, init: (@AnkoViewDslMarker android.app.MediaRouteButton).() -> Unit): android.app.MediaRouteButton {
return ankoView(`$$Anko$Factories$Sdk28View`.MEDIA_ROUTE_BUTTON, theme) { init() }
}
inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView() {}
inline fun ViewManager.gestureOverlayView(init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk28View`.GESTURE_OVERLAY_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedGestureOverlayView(theme: Int = 0): android.gesture.GestureOverlayView = themedGestureOverlayView(theme) {}
inline fun ViewManager.themedGestureOverlayView(theme: Int = 0, init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk28View`.GESTURE_OVERLAY_VIEW, theme) { init() }
}
inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView() {}
inline fun Context.gestureOverlayView(init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk28View`.GESTURE_OVERLAY_VIEW, theme = 0) { init() }
}
inline fun Context.themedGestureOverlayView(theme: Int = 0): android.gesture.GestureOverlayView = themedGestureOverlayView(theme) {}
inline fun Context.themedGestureOverlayView(theme: Int = 0, init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk28View`.GESTURE_OVERLAY_VIEW, theme) { init() }
}
inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView() {}
inline fun Activity.gestureOverlayView(init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk28View`.GESTURE_OVERLAY_VIEW, theme = 0) { init() }
}
inline fun Activity.themedGestureOverlayView(theme: Int = 0): android.gesture.GestureOverlayView = themedGestureOverlayView(theme) {}
inline fun Activity.themedGestureOverlayView(theme: Int = 0, init: (@AnkoViewDslMarker android.gesture.GestureOverlayView).() -> Unit): android.gesture.GestureOverlayView {
return ankoView(`$$Anko$Factories$Sdk28View`.GESTURE_OVERLAY_VIEW, theme) { init() }
}
inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText() {}
inline fun ViewManager.extractEditText(init: (@AnkoViewDslMarker android.inputmethodservice.ExtractEditText).() -> Unit): android.inputmethodservice.ExtractEditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EXTRACT_EDIT_TEXT, theme = 0) { init() }
}
inline fun ViewManager.themedExtractEditText(theme: Int = 0): android.inputmethodservice.ExtractEditText = themedExtractEditText(theme) {}
inline fun ViewManager.themedExtractEditText(theme: Int = 0, init: (@AnkoViewDslMarker android.inputmethodservice.ExtractEditText).() -> Unit): android.inputmethodservice.ExtractEditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EXTRACT_EDIT_TEXT, theme) { init() }
}
inline fun ViewManager.tvView(): android.media.tv.TvView = tvView() {}
inline fun ViewManager.tvView(init: (@AnkoViewDslMarker android.media.tv.TvView).() -> Unit): android.media.tv.TvView {
return ankoView(`$$Anko$Factories$Sdk28View`.TV_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedTvView(theme: Int = 0): android.media.tv.TvView = themedTvView(theme) {}
inline fun ViewManager.themedTvView(theme: Int = 0, init: (@AnkoViewDslMarker android.media.tv.TvView).() -> Unit): android.media.tv.TvView {
return ankoView(`$$Anko$Factories$Sdk28View`.TV_VIEW, theme) { init() }
}
inline fun Context.tvView(): android.media.tv.TvView = tvView() {}
inline fun Context.tvView(init: (@AnkoViewDslMarker android.media.tv.TvView).() -> Unit): android.media.tv.TvView {
return ankoView(`$$Anko$Factories$Sdk28View`.TV_VIEW, theme = 0) { init() }
}
inline fun Context.themedTvView(theme: Int = 0): android.media.tv.TvView = themedTvView(theme) {}
inline fun Context.themedTvView(theme: Int = 0, init: (@AnkoViewDslMarker android.media.tv.TvView).() -> Unit): android.media.tv.TvView {
return ankoView(`$$Anko$Factories$Sdk28View`.TV_VIEW, theme) { init() }
}
inline fun Activity.tvView(): android.media.tv.TvView = tvView() {}
inline fun Activity.tvView(init: (@AnkoViewDslMarker android.media.tv.TvView).() -> Unit): android.media.tv.TvView {
return ankoView(`$$Anko$Factories$Sdk28View`.TV_VIEW, theme = 0) { init() }
}
inline fun Activity.themedTvView(theme: Int = 0): android.media.tv.TvView = themedTvView(theme) {}
inline fun Activity.themedTvView(theme: Int = 0, init: (@AnkoViewDslMarker android.media.tv.TvView).() -> Unit): android.media.tv.TvView {
return ankoView(`$$Anko$Factories$Sdk28View`.TV_VIEW, theme) { init() }
}
inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView() {}
inline fun ViewManager.gLSurfaceView(init: (@AnkoViewDslMarker android.opengl.GLSurfaceView).() -> Unit): android.opengl.GLSurfaceView {
return ankoView(`$$Anko$Factories$Sdk28View`.G_L_SURFACE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedGLSurfaceView(theme: Int = 0): android.opengl.GLSurfaceView = themedGLSurfaceView(theme) {}
inline fun ViewManager.themedGLSurfaceView(theme: Int = 0, init: (@AnkoViewDslMarker android.opengl.GLSurfaceView).() -> Unit): android.opengl.GLSurfaceView {
return ankoView(`$$Anko$Factories$Sdk28View`.G_L_SURFACE_VIEW, theme) { init() }
}
inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView() {}
inline fun ViewManager.surfaceView(init: (@AnkoViewDslMarker android.view.SurfaceView).() -> Unit): android.view.SurfaceView {
return ankoView(`$$Anko$Factories$Sdk28View`.SURFACE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedSurfaceView(theme: Int = 0): android.view.SurfaceView = themedSurfaceView(theme) {}
inline fun ViewManager.themedSurfaceView(theme: Int = 0, init: (@AnkoViewDslMarker android.view.SurfaceView).() -> Unit): android.view.SurfaceView {
return ankoView(`$$Anko$Factories$Sdk28View`.SURFACE_VIEW, theme) { init() }
}
inline fun ViewManager.textureView(): android.view.TextureView = textureView() {}
inline fun ViewManager.textureView(init: (@AnkoViewDslMarker android.view.TextureView).() -> Unit): android.view.TextureView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXTURE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedTextureView(theme: Int = 0): android.view.TextureView = themedTextureView(theme) {}
inline fun ViewManager.themedTextureView(theme: Int = 0, init: (@AnkoViewDslMarker android.view.TextureView).() -> Unit): android.view.TextureView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXTURE_VIEW, theme) { init() }
}
inline fun ViewManager.view(): android.view.View = view() {}
inline fun ViewManager.view(init: (@AnkoViewDslMarker android.view.View).() -> Unit): android.view.View {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedView(theme: Int = 0): android.view.View = themedView(theme) {}
inline fun ViewManager.themedView(theme: Int = 0, init: (@AnkoViewDslMarker android.view.View).() -> Unit): android.view.View {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW, theme) { init() }
}
inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub() {}
inline fun ViewManager.viewStub(init: (@AnkoViewDslMarker android.view.ViewStub).() -> Unit): android.view.ViewStub {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_STUB, theme = 0) { init() }
}
inline fun ViewManager.themedViewStub(theme: Int = 0): android.view.ViewStub = themedViewStub(theme) {}
inline fun ViewManager.themedViewStub(theme: Int = 0, init: (@AnkoViewDslMarker android.view.ViewStub).() -> Unit): android.view.ViewStub {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_STUB, theme) { init() }
}
inline fun ViewManager.webView(): android.webkit.WebView = webView() {}
inline fun ViewManager.webView(init: (@AnkoViewDslMarker android.webkit.WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk28View`.WEB_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedWebView(theme: Int = 0): android.webkit.WebView = themedWebView(theme) {}
inline fun ViewManager.themedWebView(theme: Int = 0, init: (@AnkoViewDslMarker android.webkit.WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk28View`.WEB_VIEW, theme) { init() }
}
inline fun Context.webView(): android.webkit.WebView = webView() {}
inline fun Context.webView(init: (@AnkoViewDslMarker android.webkit.WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk28View`.WEB_VIEW, theme = 0) { init() }
}
inline fun Context.themedWebView(theme: Int = 0): android.webkit.WebView = themedWebView(theme) {}
inline fun Context.themedWebView(theme: Int = 0, init: (@AnkoViewDslMarker android.webkit.WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk28View`.WEB_VIEW, theme) { init() }
}
inline fun Activity.webView(): android.webkit.WebView = webView() {}
inline fun Activity.webView(init: (@AnkoViewDslMarker android.webkit.WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk28View`.WEB_VIEW, theme = 0) { init() }
}
inline fun Activity.themedWebView(theme: Int = 0): android.webkit.WebView = themedWebView(theme) {}
inline fun Activity.themedWebView(theme: Int = 0, init: (@AnkoViewDslMarker android.webkit.WebView).() -> Unit): android.webkit.WebView {
return ankoView(`$$Anko$Factories$Sdk28View`.WEB_VIEW, theme) { init() }
}
inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper() {}
inline fun ViewManager.adapterViewFlipper(init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.ADAPTER_VIEW_FLIPPER, theme = 0) { init() }
}
inline fun ViewManager.themedAdapterViewFlipper(theme: Int = 0): android.widget.AdapterViewFlipper = themedAdapterViewFlipper(theme) {}
inline fun ViewManager.themedAdapterViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.ADAPTER_VIEW_FLIPPER, theme) { init() }
}
inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper() {}
inline fun Context.adapterViewFlipper(init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.ADAPTER_VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Context.themedAdapterViewFlipper(theme: Int = 0): android.widget.AdapterViewFlipper = themedAdapterViewFlipper(theme) {}
inline fun Context.themedAdapterViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.ADAPTER_VIEW_FLIPPER, theme) { init() }
}
inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper() {}
inline fun Activity.adapterViewFlipper(init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.ADAPTER_VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Activity.themedAdapterViewFlipper(theme: Int = 0): android.widget.AdapterViewFlipper = themedAdapterViewFlipper(theme) {}
inline fun Activity.themedAdapterViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AdapterViewFlipper).() -> Unit): android.widget.AdapterViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.ADAPTER_VIEW_FLIPPER, theme) { init() }
}
inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock() {}
inline fun ViewManager.analogClock(init: (@AnkoViewDslMarker android.widget.AnalogClock).() -> Unit): android.widget.AnalogClock {
return ankoView(`$$Anko$Factories$Sdk28View`.ANALOG_CLOCK, theme = 0) { init() }
}
inline fun ViewManager.themedAnalogClock(theme: Int = 0): android.widget.AnalogClock = themedAnalogClock(theme) {}
inline fun ViewManager.themedAnalogClock(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AnalogClock).() -> Unit): android.widget.AnalogClock {
return ankoView(`$$Anko$Factories$Sdk28View`.ANALOG_CLOCK, theme) { init() }
}
inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView() {}
inline fun ViewManager.autoCompleteTextView(init: (@AnkoViewDslMarker android.widget.AutoCompleteTextView).() -> Unit): android.widget.AutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk28View`.AUTO_COMPLETE_TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedAutoCompleteTextView(theme: Int = 0): android.widget.AutoCompleteTextView = themedAutoCompleteTextView(theme) {}
inline fun ViewManager.themedAutoCompleteTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.AutoCompleteTextView).() -> Unit): android.widget.AutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk28View`.AUTO_COMPLETE_TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.button(): android.widget.Button = button() {}
inline fun ViewManager.button(init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedButton(theme: Int = 0): android.widget.Button = themedButton(theme) {}
inline fun ViewManager.themedButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme) { init() }
}
inline fun ViewManager.button(text: CharSequence?): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme = 0) {
setText(text)
}
}
inline fun ViewManager.button(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedButton(text: CharSequence?, theme: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme) {
setText(text)
}
}
inline fun ViewManager.themedButton(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme) {
init()
setText(text)
}
}
inline fun ViewManager.button(text: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme = 0) {
setText(text)
}
}
inline fun ViewManager.button(text: Int, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedButton(text: Int, theme: Int): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme) {
setText(text)
}
}
inline fun ViewManager.themedButton(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.Button).() -> Unit): android.widget.Button {
return ankoView(`$$Anko$Factories$Sdk28View`.BUTTON, theme) {
init()
setText(text)
}
}
inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView() {}
inline fun ViewManager.calendarView(init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk28View`.CALENDAR_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedCalendarView(theme: Int = 0): android.widget.CalendarView = themedCalendarView(theme) {}
inline fun ViewManager.themedCalendarView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk28View`.CALENDAR_VIEW, theme) { init() }
}
inline fun Context.calendarView(): android.widget.CalendarView = calendarView() {}
inline fun Context.calendarView(init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk28View`.CALENDAR_VIEW, theme = 0) { init() }
}
inline fun Context.themedCalendarView(theme: Int = 0): android.widget.CalendarView = themedCalendarView(theme) {}
inline fun Context.themedCalendarView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk28View`.CALENDAR_VIEW, theme) { init() }
}
inline fun Activity.calendarView(): android.widget.CalendarView = calendarView() {}
inline fun Activity.calendarView(init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk28View`.CALENDAR_VIEW, theme = 0) { init() }
}
inline fun Activity.themedCalendarView(theme: Int = 0): android.widget.CalendarView = themedCalendarView(theme) {}
inline fun Activity.themedCalendarView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CalendarView).() -> Unit): android.widget.CalendarView {
return ankoView(`$$Anko$Factories$Sdk28View`.CALENDAR_VIEW, theme) { init() }
}
inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox() {}
inline fun ViewManager.checkBox(init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) { init() }
}
inline fun ViewManager.themedCheckBox(theme: Int = 0): android.widget.CheckBox = themedCheckBox(theme) {}
inline fun ViewManager.themedCheckBox(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) { init() }
}
inline fun ViewManager.checkBox(text: CharSequence?): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
setText(text)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
init()
setText(text)
}
}
inline fun ViewManager.checkBox(text: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
setText(text)
}
}
inline fun ViewManager.checkBox(text: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: Int, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
setText(text)
}
}
inline fun ViewManager.themedCheckBox(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
init()
setText(text)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: CharSequence?, checked: Boolean, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, checked: Boolean, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: CharSequence?, checked: Boolean, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: Int, checked: Boolean): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkBox(text: Int, checked: Boolean, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme = 0) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: Int, checked: Boolean, theme: Int): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.themedCheckBox(text: Int, checked: Boolean, theme: Int, init: (@AnkoViewDslMarker android.widget.CheckBox).() -> Unit): android.widget.CheckBox {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECK_BOX, theme) {
init()
setText(text)
setChecked(checked)
}
}
inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView() {}
inline fun ViewManager.checkedTextView(init: (@AnkoViewDslMarker android.widget.CheckedTextView).() -> Unit): android.widget.CheckedTextView {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECKED_TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedCheckedTextView(theme: Int = 0): android.widget.CheckedTextView = themedCheckedTextView(theme) {}
inline fun ViewManager.themedCheckedTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.CheckedTextView).() -> Unit): android.widget.CheckedTextView {
return ankoView(`$$Anko$Factories$Sdk28View`.CHECKED_TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer() {}
inline fun ViewManager.chronometer(init: (@AnkoViewDslMarker android.widget.Chronometer).() -> Unit): android.widget.Chronometer {
return ankoView(`$$Anko$Factories$Sdk28View`.CHRONOMETER, theme = 0) { init() }
}
inline fun ViewManager.themedChronometer(theme: Int = 0): android.widget.Chronometer = themedChronometer(theme) {}
inline fun ViewManager.themedChronometer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Chronometer).() -> Unit): android.widget.Chronometer {
return ankoView(`$$Anko$Factories$Sdk28View`.CHRONOMETER, theme) { init() }
}
inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker() {}
inline fun ViewManager.datePicker(init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.DATE_PICKER, theme = 0) { init() }
}
inline fun ViewManager.themedDatePicker(theme: Int = 0): android.widget.DatePicker = themedDatePicker(theme) {}
inline fun ViewManager.themedDatePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.DATE_PICKER, theme) { init() }
}
inline fun Context.datePicker(): android.widget.DatePicker = datePicker() {}
inline fun Context.datePicker(init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.DATE_PICKER, theme = 0) { init() }
}
inline fun Context.themedDatePicker(theme: Int = 0): android.widget.DatePicker = themedDatePicker(theme) {}
inline fun Context.themedDatePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.DATE_PICKER, theme) { init() }
}
inline fun Activity.datePicker(): android.widget.DatePicker = datePicker() {}
inline fun Activity.datePicker(init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.DATE_PICKER, theme = 0) { init() }
}
inline fun Activity.themedDatePicker(theme: Int = 0): android.widget.DatePicker = themedDatePicker(theme) {}
inline fun Activity.themedDatePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DatePicker).() -> Unit): android.widget.DatePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.DATE_PICKER, theme) { init() }
}
inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter() {}
inline fun ViewManager.dialerFilter(init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk28View`.DIALER_FILTER, theme = 0) { init() }
}
inline fun ViewManager.themedDialerFilter(theme: Int = 0): android.widget.DialerFilter = themedDialerFilter(theme) {}
inline fun ViewManager.themedDialerFilter(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk28View`.DIALER_FILTER, theme) { init() }
}
inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter() {}
inline fun Context.dialerFilter(init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk28View`.DIALER_FILTER, theme = 0) { init() }
}
inline fun Context.themedDialerFilter(theme: Int = 0): android.widget.DialerFilter = themedDialerFilter(theme) {}
inline fun Context.themedDialerFilter(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk28View`.DIALER_FILTER, theme) { init() }
}
inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter() {}
inline fun Activity.dialerFilter(init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk28View`.DIALER_FILTER, theme = 0) { init() }
}
inline fun Activity.themedDialerFilter(theme: Int = 0): android.widget.DialerFilter = themedDialerFilter(theme) {}
inline fun Activity.themedDialerFilter(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DialerFilter).() -> Unit): android.widget.DialerFilter {
return ankoView(`$$Anko$Factories$Sdk28View`.DIALER_FILTER, theme) { init() }
}
inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock() {}
inline fun ViewManager.digitalClock(init: (@AnkoViewDslMarker android.widget.DigitalClock).() -> Unit): android.widget.DigitalClock {
return ankoView(`$$Anko$Factories$Sdk28View`.DIGITAL_CLOCK, theme = 0) { init() }
}
inline fun ViewManager.themedDigitalClock(theme: Int = 0): android.widget.DigitalClock = themedDigitalClock(theme) {}
inline fun ViewManager.themedDigitalClock(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.DigitalClock).() -> Unit): android.widget.DigitalClock {
return ankoView(`$$Anko$Factories$Sdk28View`.DIGITAL_CLOCK, theme) { init() }
}
inline fun ViewManager.editText(): android.widget.EditText = editText() {}
inline fun ViewManager.editText(init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme = 0) { init() }
}
inline fun ViewManager.themedEditText(theme: Int = 0): android.widget.EditText = themedEditText(theme) {}
inline fun ViewManager.themedEditText(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme) { init() }
}
inline fun ViewManager.editText(text: CharSequence?): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme = 0) {
setText(text)
}
}
inline fun ViewManager.editText(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedEditText(text: CharSequence?, theme: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme) {
setText(text)
}
}
inline fun ViewManager.themedEditText(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme) {
init()
setText(text)
}
}
inline fun ViewManager.editText(text: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme = 0) {
setText(text)
}
}
inline fun ViewManager.editText(text: Int, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedEditText(text: Int, theme: Int): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme) {
setText(text)
}
}
inline fun ViewManager.themedEditText(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.EditText).() -> Unit): android.widget.EditText {
return ankoView(`$$Anko$Factories$Sdk28View`.EDIT_TEXT, theme) {
init()
setText(text)
}
}
inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView() {}
inline fun ViewManager.expandableListView(init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk28View`.EXPANDABLE_LIST_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedExpandableListView(theme: Int = 0): android.widget.ExpandableListView = themedExpandableListView(theme) {}
inline fun ViewManager.themedExpandableListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk28View`.EXPANDABLE_LIST_VIEW, theme) { init() }
}
inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView() {}
inline fun Context.expandableListView(init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk28View`.EXPANDABLE_LIST_VIEW, theme = 0) { init() }
}
inline fun Context.themedExpandableListView(theme: Int = 0): android.widget.ExpandableListView = themedExpandableListView(theme) {}
inline fun Context.themedExpandableListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk28View`.EXPANDABLE_LIST_VIEW, theme) { init() }
}
inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView() {}
inline fun Activity.expandableListView(init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk28View`.EXPANDABLE_LIST_VIEW, theme = 0) { init() }
}
inline fun Activity.themedExpandableListView(theme: Int = 0): android.widget.ExpandableListView = themedExpandableListView(theme) {}
inline fun Activity.themedExpandableListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ExpandableListView).() -> Unit): android.widget.ExpandableListView {
return ankoView(`$$Anko$Factories$Sdk28View`.EXPANDABLE_LIST_VIEW, theme) { init() }
}
inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton() {}
inline fun ViewManager.imageButton(init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedImageButton(theme: Int = 0): android.widget.ImageButton = themedImageButton(theme) {}
inline fun ViewManager.themedImageButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme) { init() }
}
inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme = 0) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageButton(imageDrawable: android.graphics.drawable.Drawable?, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme = 0) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageButton(imageDrawable: android.graphics.drawable.Drawable?, theme: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageButton(imageDrawable: android.graphics.drawable.Drawable?, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageButton(imageResource: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme = 0) {
setImageResource(imageResource)
}
}
inline fun ViewManager.imageButton(imageResource: Int, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme = 0) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageButton(imageResource: Int, theme: Int): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme) {
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageButton(imageResource: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageButton).() -> Unit): android.widget.ImageButton {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_BUTTON, theme) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.imageView(): android.widget.ImageView = imageView() {}
inline fun ViewManager.imageView(init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedImageView(theme: Int = 0): android.widget.ImageView = themedImageView(theme) {}
inline fun ViewManager.themedImageView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme) { init() }
}
inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme = 0) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageView(imageDrawable: android.graphics.drawable.Drawable?, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme = 0) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageView(imageDrawable: android.graphics.drawable.Drawable?, theme: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme) {
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.themedImageView(imageDrawable: android.graphics.drawable.Drawable?, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme) {
init()
setImageDrawable(imageDrawable)
}
}
inline fun ViewManager.imageView(imageResource: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme = 0) {
setImageResource(imageResource)
}
}
inline fun ViewManager.imageView(imageResource: Int, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme = 0) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageView(imageResource: Int, theme: Int): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme) {
setImageResource(imageResource)
}
}
inline fun ViewManager.themedImageView(imageResource: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.ImageView).() -> Unit): android.widget.ImageView {
return ankoView(`$$Anko$Factories$Sdk28View`.IMAGE_VIEW, theme) {
init()
setImageResource(imageResource)
}
}
inline fun ViewManager.listView(): android.widget.ListView = listView() {}
inline fun ViewManager.listView(init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk28View`.LIST_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedListView(theme: Int = 0): android.widget.ListView = themedListView(theme) {}
inline fun ViewManager.themedListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk28View`.LIST_VIEW, theme) { init() }
}
inline fun Context.listView(): android.widget.ListView = listView() {}
inline fun Context.listView(init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk28View`.LIST_VIEW, theme = 0) { init() }
}
inline fun Context.themedListView(theme: Int = 0): android.widget.ListView = themedListView(theme) {}
inline fun Context.themedListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk28View`.LIST_VIEW, theme) { init() }
}
inline fun Activity.listView(): android.widget.ListView = listView() {}
inline fun Activity.listView(init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk28View`.LIST_VIEW, theme = 0) { init() }
}
inline fun Activity.themedListView(theme: Int = 0): android.widget.ListView = themedListView(theme) {}
inline fun Activity.themedListView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ListView).() -> Unit): android.widget.ListView {
return ankoView(`$$Anko$Factories$Sdk28View`.LIST_VIEW, theme) { init() }
}
inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView() {}
inline fun ViewManager.multiAutoCompleteTextView(init: (@AnkoViewDslMarker android.widget.MultiAutoCompleteTextView).() -> Unit): android.widget.MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk28View`.MULTI_AUTO_COMPLETE_TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedMultiAutoCompleteTextView(theme: Int = 0): android.widget.MultiAutoCompleteTextView = themedMultiAutoCompleteTextView(theme) {}
inline fun ViewManager.themedMultiAutoCompleteTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.MultiAutoCompleteTextView).() -> Unit): android.widget.MultiAutoCompleteTextView {
return ankoView(`$$Anko$Factories$Sdk28View`.MULTI_AUTO_COMPLETE_TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker() {}
inline fun ViewManager.numberPicker(init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk28View`.NUMBER_PICKER, theme = 0) { init() }
}
inline fun ViewManager.themedNumberPicker(theme: Int = 0): android.widget.NumberPicker = themedNumberPicker(theme) {}
inline fun ViewManager.themedNumberPicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk28View`.NUMBER_PICKER, theme) { init() }
}
inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker() {}
inline fun Context.numberPicker(init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk28View`.NUMBER_PICKER, theme = 0) { init() }
}
inline fun Context.themedNumberPicker(theme: Int = 0): android.widget.NumberPicker = themedNumberPicker(theme) {}
inline fun Context.themedNumberPicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk28View`.NUMBER_PICKER, theme) { init() }
}
inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker() {}
inline fun Activity.numberPicker(init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk28View`.NUMBER_PICKER, theme = 0) { init() }
}
inline fun Activity.themedNumberPicker(theme: Int = 0): android.widget.NumberPicker = themedNumberPicker(theme) {}
inline fun Activity.themedNumberPicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.NumberPicker).() -> Unit): android.widget.NumberPicker {
return ankoView(`$$Anko$Factories$Sdk28View`.NUMBER_PICKER, theme) { init() }
}
inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar() {}
inline fun ViewManager.progressBar(init: (@AnkoViewDslMarker android.widget.ProgressBar).() -> Unit): android.widget.ProgressBar {
return ankoView(`$$Anko$Factories$Sdk28View`.PROGRESS_BAR, theme = 0) { init() }
}
inline fun ViewManager.themedProgressBar(theme: Int = 0): android.widget.ProgressBar = themedProgressBar(theme) {}
inline fun ViewManager.themedProgressBar(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ProgressBar).() -> Unit): android.widget.ProgressBar {
return ankoView(`$$Anko$Factories$Sdk28View`.PROGRESS_BAR, theme) { init() }
}
inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge() {}
inline fun ViewManager.quickContactBadge(init: (@AnkoViewDslMarker android.widget.QuickContactBadge).() -> Unit): android.widget.QuickContactBadge {
return ankoView(`$$Anko$Factories$Sdk28View`.QUICK_CONTACT_BADGE, theme = 0) { init() }
}
inline fun ViewManager.themedQuickContactBadge(theme: Int = 0): android.widget.QuickContactBadge = themedQuickContactBadge(theme) {}
inline fun ViewManager.themedQuickContactBadge(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.QuickContactBadge).() -> Unit): android.widget.QuickContactBadge {
return ankoView(`$$Anko$Factories$Sdk28View`.QUICK_CONTACT_BADGE, theme) { init() }
}
inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton() {}
inline fun ViewManager.radioButton(init: (@AnkoViewDslMarker android.widget.RadioButton).() -> Unit): android.widget.RadioButton {
return ankoView(`$$Anko$Factories$Sdk28View`.RADIO_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedRadioButton(theme: Int = 0): android.widget.RadioButton = themedRadioButton(theme) {}
inline fun ViewManager.themedRadioButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.RadioButton).() -> Unit): android.widget.RadioButton {
return ankoView(`$$Anko$Factories$Sdk28View`.RADIO_BUTTON, theme) { init() }
}
inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar() {}
inline fun ViewManager.ratingBar(init: (@AnkoViewDslMarker android.widget.RatingBar).() -> Unit): android.widget.RatingBar {
return ankoView(`$$Anko$Factories$Sdk28View`.RATING_BAR, theme = 0) { init() }
}
inline fun ViewManager.themedRatingBar(theme: Int = 0): android.widget.RatingBar = themedRatingBar(theme) {}
inline fun ViewManager.themedRatingBar(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.RatingBar).() -> Unit): android.widget.RatingBar {
return ankoView(`$$Anko$Factories$Sdk28View`.RATING_BAR, theme) { init() }
}
inline fun ViewManager.searchView(): android.widget.SearchView = searchView() {}
inline fun ViewManager.searchView(init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk28View`.SEARCH_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedSearchView(theme: Int = 0): android.widget.SearchView = themedSearchView(theme) {}
inline fun ViewManager.themedSearchView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk28View`.SEARCH_VIEW, theme) { init() }
}
inline fun Context.searchView(): android.widget.SearchView = searchView() {}
inline fun Context.searchView(init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk28View`.SEARCH_VIEW, theme = 0) { init() }
}
inline fun Context.themedSearchView(theme: Int = 0): android.widget.SearchView = themedSearchView(theme) {}
inline fun Context.themedSearchView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk28View`.SEARCH_VIEW, theme) { init() }
}
inline fun Activity.searchView(): android.widget.SearchView = searchView() {}
inline fun Activity.searchView(init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk28View`.SEARCH_VIEW, theme = 0) { init() }
}
inline fun Activity.themedSearchView(theme: Int = 0): android.widget.SearchView = themedSearchView(theme) {}
inline fun Activity.themedSearchView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SearchView).() -> Unit): android.widget.SearchView {
return ankoView(`$$Anko$Factories$Sdk28View`.SEARCH_VIEW, theme) { init() }
}
inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar() {}
inline fun ViewManager.seekBar(init: (@AnkoViewDslMarker android.widget.SeekBar).() -> Unit): android.widget.SeekBar {
return ankoView(`$$Anko$Factories$Sdk28View`.SEEK_BAR, theme = 0) { init() }
}
inline fun ViewManager.themedSeekBar(theme: Int = 0): android.widget.SeekBar = themedSeekBar(theme) {}
inline fun ViewManager.themedSeekBar(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SeekBar).() -> Unit): android.widget.SeekBar {
return ankoView(`$$Anko$Factories$Sdk28View`.SEEK_BAR, theme) { init() }
}
inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer() {}
inline fun ViewManager.slidingDrawer(init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk28View`.SLIDING_DRAWER, theme = 0) { init() }
}
inline fun ViewManager.themedSlidingDrawer(theme: Int = 0): android.widget.SlidingDrawer = themedSlidingDrawer(theme) {}
inline fun ViewManager.themedSlidingDrawer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk28View`.SLIDING_DRAWER, theme) { init() }
}
inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer() {}
inline fun Context.slidingDrawer(init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk28View`.SLIDING_DRAWER, theme = 0) { init() }
}
inline fun Context.themedSlidingDrawer(theme: Int = 0): android.widget.SlidingDrawer = themedSlidingDrawer(theme) {}
inline fun Context.themedSlidingDrawer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk28View`.SLIDING_DRAWER, theme) { init() }
}
inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer() {}
inline fun Activity.slidingDrawer(init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk28View`.SLIDING_DRAWER, theme = 0) { init() }
}
inline fun Activity.themedSlidingDrawer(theme: Int = 0): android.widget.SlidingDrawer = themedSlidingDrawer(theme) {}
inline fun Activity.themedSlidingDrawer(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.SlidingDrawer).() -> Unit): android.widget.SlidingDrawer {
return ankoView(`$$Anko$Factories$Sdk28View`.SLIDING_DRAWER, theme) { init() }
}
inline fun ViewManager.space(): android.widget.Space = space() {}
inline fun ViewManager.space(init: (@AnkoViewDslMarker android.widget.Space).() -> Unit): android.widget.Space {
return ankoView(`$$Anko$Factories$Sdk28View`.SPACE, theme = 0) { init() }
}
inline fun ViewManager.themedSpace(theme: Int = 0): android.widget.Space = themedSpace(theme) {}
inline fun ViewManager.themedSpace(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Space).() -> Unit): android.widget.Space {
return ankoView(`$$Anko$Factories$Sdk28View`.SPACE, theme) { init() }
}
inline fun ViewManager.spinner(): android.widget.Spinner = spinner() {}
inline fun ViewManager.spinner(init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk28View`.SPINNER, theme = 0) { init() }
}
inline fun ViewManager.themedSpinner(theme: Int = 0): android.widget.Spinner = themedSpinner(theme) {}
inline fun ViewManager.themedSpinner(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk28View`.SPINNER, theme) { init() }
}
inline fun Context.spinner(): android.widget.Spinner = spinner() {}
inline fun Context.spinner(init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk28View`.SPINNER, theme = 0) { init() }
}
inline fun Context.themedSpinner(theme: Int = 0): android.widget.Spinner = themedSpinner(theme) {}
inline fun Context.themedSpinner(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk28View`.SPINNER, theme) { init() }
}
inline fun Activity.spinner(): android.widget.Spinner = spinner() {}
inline fun Activity.spinner(init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk28View`.SPINNER, theme = 0) { init() }
}
inline fun Activity.themedSpinner(theme: Int = 0): android.widget.Spinner = themedSpinner(theme) {}
inline fun Activity.themedSpinner(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Spinner).() -> Unit): android.widget.Spinner {
return ankoView(`$$Anko$Factories$Sdk28View`.SPINNER, theme) { init() }
}
inline fun ViewManager.stackView(): android.widget.StackView = stackView() {}
inline fun ViewManager.stackView(init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk28View`.STACK_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedStackView(theme: Int = 0): android.widget.StackView = themedStackView(theme) {}
inline fun ViewManager.themedStackView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk28View`.STACK_VIEW, theme) { init() }
}
inline fun Context.stackView(): android.widget.StackView = stackView() {}
inline fun Context.stackView(init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk28View`.STACK_VIEW, theme = 0) { init() }
}
inline fun Context.themedStackView(theme: Int = 0): android.widget.StackView = themedStackView(theme) {}
inline fun Context.themedStackView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk28View`.STACK_VIEW, theme) { init() }
}
inline fun Activity.stackView(): android.widget.StackView = stackView() {}
inline fun Activity.stackView(init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk28View`.STACK_VIEW, theme = 0) { init() }
}
inline fun Activity.themedStackView(theme: Int = 0): android.widget.StackView = themedStackView(theme) {}
inline fun Activity.themedStackView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.StackView).() -> Unit): android.widget.StackView {
return ankoView(`$$Anko$Factories$Sdk28View`.STACK_VIEW, theme) { init() }
}
inline fun ViewManager.switch(): android.widget.Switch = switch() {}
inline fun ViewManager.switch(init: (@AnkoViewDslMarker android.widget.Switch).() -> Unit): android.widget.Switch {
return ankoView(`$$Anko$Factories$Sdk28View`.SWITCH, theme = 0) { init() }
}
inline fun ViewManager.themedSwitch(theme: Int = 0): android.widget.Switch = themedSwitch(theme) {}
inline fun ViewManager.themedSwitch(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.Switch).() -> Unit): android.widget.Switch {
return ankoView(`$$Anko$Factories$Sdk28View`.SWITCH, theme) { init() }
}
inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost() {}
inline fun ViewManager.tabHost(init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_HOST, theme = 0) { init() }
}
inline fun ViewManager.themedTabHost(theme: Int = 0): android.widget.TabHost = themedTabHost(theme) {}
inline fun ViewManager.themedTabHost(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_HOST, theme) { init() }
}
inline fun Context.tabHost(): android.widget.TabHost = tabHost() {}
inline fun Context.tabHost(init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_HOST, theme = 0) { init() }
}
inline fun Context.themedTabHost(theme: Int = 0): android.widget.TabHost = themedTabHost(theme) {}
inline fun Context.themedTabHost(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_HOST, theme) { init() }
}
inline fun Activity.tabHost(): android.widget.TabHost = tabHost() {}
inline fun Activity.tabHost(init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_HOST, theme = 0) { init() }
}
inline fun Activity.themedTabHost(theme: Int = 0): android.widget.TabHost = themedTabHost(theme) {}
inline fun Activity.themedTabHost(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabHost).() -> Unit): android.widget.TabHost {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_HOST, theme) { init() }
}
inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget() {}
inline fun ViewManager.tabWidget(init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_WIDGET, theme = 0) { init() }
}
inline fun ViewManager.themedTabWidget(theme: Int = 0): android.widget.TabWidget = themedTabWidget(theme) {}
inline fun ViewManager.themedTabWidget(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_WIDGET, theme) { init() }
}
inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget() {}
inline fun Context.tabWidget(init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_WIDGET, theme = 0) { init() }
}
inline fun Context.themedTabWidget(theme: Int = 0): android.widget.TabWidget = themedTabWidget(theme) {}
inline fun Context.themedTabWidget(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_WIDGET, theme) { init() }
}
inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget() {}
inline fun Activity.tabWidget(init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_WIDGET, theme = 0) { init() }
}
inline fun Activity.themedTabWidget(theme: Int = 0): android.widget.TabWidget = themedTabWidget(theme) {}
inline fun Activity.themedTabWidget(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TabWidget).() -> Unit): android.widget.TabWidget {
return ankoView(`$$Anko$Factories$Sdk28View`.TAB_WIDGET, theme) { init() }
}
inline fun ViewManager.textClock(): android.widget.TextClock = textClock() {}
inline fun ViewManager.textClock(init: (@AnkoViewDslMarker android.widget.TextClock).() -> Unit): android.widget.TextClock {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_CLOCK, theme = 0) { init() }
}
inline fun ViewManager.themedTextClock(theme: Int = 0): android.widget.TextClock = themedTextClock(theme) {}
inline fun ViewManager.themedTextClock(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TextClock).() -> Unit): android.widget.TextClock {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_CLOCK, theme) { init() }
}
inline fun ViewManager.textView(): android.widget.TextView = textView() {}
inline fun ViewManager.textView(init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedTextView(theme: Int = 0): android.widget.TextView = themedTextView(theme) {}
inline fun ViewManager.themedTextView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme) { init() }
}
inline fun ViewManager.textView(text: CharSequence?): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme = 0) {
setText(text)
}
}
inline fun ViewManager.textView(text: CharSequence?, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedTextView(text: CharSequence?, theme: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme) {
setText(text)
}
}
inline fun ViewManager.themedTextView(text: CharSequence?, theme: Int, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme) {
init()
setText(text)
}
}
inline fun ViewManager.textView(text: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme = 0) {
setText(text)
}
}
inline fun ViewManager.textView(text: Int, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme = 0) {
init()
setText(text)
}
}
inline fun ViewManager.themedTextView(text: Int, theme: Int): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme) {
setText(text)
}
}
inline fun ViewManager.themedTextView(text: Int, theme: Int, init: (@AnkoViewDslMarker android.widget.TextView).() -> Unit): android.widget.TextView {
return ankoView(`$$Anko$Factories$Sdk28View`.TEXT_VIEW, theme) {
init()
setText(text)
}
}
inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker() {}
inline fun ViewManager.timePicker(init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.TIME_PICKER, theme = 0) { init() }
}
inline fun ViewManager.themedTimePicker(theme: Int = 0): android.widget.TimePicker = themedTimePicker(theme) {}
inline fun ViewManager.themedTimePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.TIME_PICKER, theme) { init() }
}
inline fun Context.timePicker(): android.widget.TimePicker = timePicker() {}
inline fun Context.timePicker(init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.TIME_PICKER, theme = 0) { init() }
}
inline fun Context.themedTimePicker(theme: Int = 0): android.widget.TimePicker = themedTimePicker(theme) {}
inline fun Context.themedTimePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.TIME_PICKER, theme) { init() }
}
inline fun Activity.timePicker(): android.widget.TimePicker = timePicker() {}
inline fun Activity.timePicker(init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.TIME_PICKER, theme = 0) { init() }
}
inline fun Activity.themedTimePicker(theme: Int = 0): android.widget.TimePicker = themedTimePicker(theme) {}
inline fun Activity.themedTimePicker(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TimePicker).() -> Unit): android.widget.TimePicker {
return ankoView(`$$Anko$Factories$Sdk28View`.TIME_PICKER, theme) { init() }
}
inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton() {}
inline fun ViewManager.toggleButton(init: (@AnkoViewDslMarker android.widget.ToggleButton).() -> Unit): android.widget.ToggleButton {
return ankoView(`$$Anko$Factories$Sdk28View`.TOGGLE_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedToggleButton(theme: Int = 0): android.widget.ToggleButton = themedToggleButton(theme) {}
inline fun ViewManager.themedToggleButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ToggleButton).() -> Unit): android.widget.ToggleButton {
return ankoView(`$$Anko$Factories$Sdk28View`.TOGGLE_BUTTON, theme) { init() }
}
inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem() {}
inline fun ViewManager.twoLineListItem(init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk28View`.TWO_LINE_LIST_ITEM, theme = 0) { init() }
}
inline fun ViewManager.themedTwoLineListItem(theme: Int = 0): android.widget.TwoLineListItem = themedTwoLineListItem(theme) {}
inline fun ViewManager.themedTwoLineListItem(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk28View`.TWO_LINE_LIST_ITEM, theme) { init() }
}
inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem() {}
inline fun Context.twoLineListItem(init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk28View`.TWO_LINE_LIST_ITEM, theme = 0) { init() }
}
inline fun Context.themedTwoLineListItem(theme: Int = 0): android.widget.TwoLineListItem = themedTwoLineListItem(theme) {}
inline fun Context.themedTwoLineListItem(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk28View`.TWO_LINE_LIST_ITEM, theme) { init() }
}
inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem() {}
inline fun Activity.twoLineListItem(init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk28View`.TWO_LINE_LIST_ITEM, theme = 0) { init() }
}
inline fun Activity.themedTwoLineListItem(theme: Int = 0): android.widget.TwoLineListItem = themedTwoLineListItem(theme) {}
inline fun Activity.themedTwoLineListItem(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.TwoLineListItem).() -> Unit): android.widget.TwoLineListItem {
return ankoView(`$$Anko$Factories$Sdk28View`.TWO_LINE_LIST_ITEM, theme) { init() }
}
inline fun ViewManager.videoView(): android.widget.VideoView = videoView() {}
inline fun ViewManager.videoView(init: (@AnkoViewDslMarker android.widget.VideoView).() -> Unit): android.widget.VideoView {
return ankoView(`$$Anko$Factories$Sdk28View`.VIDEO_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedVideoView(theme: Int = 0): android.widget.VideoView = themedVideoView(theme) {}
inline fun ViewManager.themedVideoView(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.VideoView).() -> Unit): android.widget.VideoView {
return ankoView(`$$Anko$Factories$Sdk28View`.VIDEO_VIEW, theme) { init() }
}
inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper() {}
inline fun ViewManager.viewFlipper(init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_FLIPPER, theme = 0) { init() }
}
inline fun ViewManager.themedViewFlipper(theme: Int = 0): android.widget.ViewFlipper = themedViewFlipper(theme) {}
inline fun ViewManager.themedViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_FLIPPER, theme) { init() }
}
inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper() {}
inline fun Context.viewFlipper(init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Context.themedViewFlipper(theme: Int = 0): android.widget.ViewFlipper = themedViewFlipper(theme) {}
inline fun Context.themedViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_FLIPPER, theme) { init() }
}
inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper() {}
inline fun Activity.viewFlipper(init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_FLIPPER, theme = 0) { init() }
}
inline fun Activity.themedViewFlipper(theme: Int = 0): android.widget.ViewFlipper = themedViewFlipper(theme) {}
inline fun Activity.themedViewFlipper(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ViewFlipper).() -> Unit): android.widget.ViewFlipper {
return ankoView(`$$Anko$Factories$Sdk28View`.VIEW_FLIPPER, theme) { init() }
}
inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton() {}
inline fun ViewManager.zoomButton(init: (@AnkoViewDslMarker android.widget.ZoomButton).() -> Unit): android.widget.ZoomButton {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_BUTTON, theme = 0) { init() }
}
inline fun ViewManager.themedZoomButton(theme: Int = 0): android.widget.ZoomButton = themedZoomButton(theme) {}
inline fun ViewManager.themedZoomButton(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomButton).() -> Unit): android.widget.ZoomButton {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_BUTTON, theme) { init() }
}
inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls() {}
inline fun ViewManager.zoomControls(init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_CONTROLS, theme = 0) { init() }
}
inline fun ViewManager.themedZoomControls(theme: Int = 0): android.widget.ZoomControls = themedZoomControls(theme) {}
inline fun ViewManager.themedZoomControls(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_CONTROLS, theme) { init() }
}
inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls() {}
inline fun Context.zoomControls(init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_CONTROLS, theme = 0) { init() }
}
inline fun Context.themedZoomControls(theme: Int = 0): android.widget.ZoomControls = themedZoomControls(theme) {}
inline fun Context.themedZoomControls(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_CONTROLS, theme) { init() }
}
inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls() {}
inline fun Activity.zoomControls(init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_CONTROLS, theme = 0) { init() }
}
inline fun Activity.themedZoomControls(theme: Int = 0): android.widget.ZoomControls = themedZoomControls(theme) {}
inline fun Activity.themedZoomControls(theme: Int = 0, init: (@AnkoViewDslMarker android.widget.ZoomControls).() -> Unit): android.widget.ZoomControls {
return ankoView(`$$Anko$Factories$Sdk28View`.ZOOM_CONTROLS, theme) { init() }
}
@PublishedApi
internal object `$$Anko$Factories$Sdk28ViewGroup` {
val APP_WIDGET_HOST_VIEW = { ctx: Context -> _AppWidgetHostView(ctx) }
val ABSOLUTE_LAYOUT = { ctx: Context -> _AbsoluteLayout(ctx) }
val ACTION_MENU_VIEW = { ctx: Context -> _ActionMenuView(ctx) }
val FRAME_LAYOUT = { ctx: Context -> _FrameLayout(ctx) }
val GALLERY = { ctx: Context -> _Gallery(ctx) }
val GRID_LAYOUT = { ctx: Context -> _GridLayout(ctx) }
val GRID_VIEW = { ctx: Context -> _GridView(ctx) }
val HORIZONTAL_SCROLL_VIEW = { ctx: Context -> _HorizontalScrollView(ctx) }
val IMAGE_SWITCHER = { ctx: Context -> _ImageSwitcher(ctx) }
val LINEAR_LAYOUT = { ctx: Context -> _LinearLayout(ctx) }
val RADIO_GROUP = { ctx: Context -> _RadioGroup(ctx) }
val RELATIVE_LAYOUT = { ctx: Context -> _RelativeLayout(ctx) }
val SCROLL_VIEW = { ctx: Context -> _ScrollView(ctx) }
val TABLE_LAYOUT = { ctx: Context -> _TableLayout(ctx) }
val TABLE_ROW = { ctx: Context -> _TableRow(ctx) }
val TEXT_SWITCHER = { ctx: Context -> _TextSwitcher(ctx) }
val TOOLBAR = { ctx: Context -> _Toolbar(ctx) }
val VIEW_ANIMATOR = { ctx: Context -> _ViewAnimator(ctx) }
val VIEW_SWITCHER = { ctx: Context -> _ViewSwitcher(ctx) }
}
inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView() {}
inline fun ViewManager.appWidgetHostView(init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.APP_WIDGET_HOST_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedAppWidgetHostView(theme: Int = 0): android.appwidget.AppWidgetHostView = themedAppWidgetHostView(theme) {}
inline fun ViewManager.themedAppWidgetHostView(theme: Int = 0, init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.APP_WIDGET_HOST_VIEW, theme) { init() }
}
inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView() {}
inline fun Context.appWidgetHostView(init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.APP_WIDGET_HOST_VIEW, theme = 0) { init() }
}
inline fun Context.themedAppWidgetHostView(theme: Int = 0): android.appwidget.AppWidgetHostView = themedAppWidgetHostView(theme) {}
inline fun Context.themedAppWidgetHostView(theme: Int = 0, init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.APP_WIDGET_HOST_VIEW, theme) { init() }
}
inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView() {}
inline fun Activity.appWidgetHostView(init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.APP_WIDGET_HOST_VIEW, theme = 0) { init() }
}
inline fun Activity.themedAppWidgetHostView(theme: Int = 0): android.appwidget.AppWidgetHostView = themedAppWidgetHostView(theme) {}
inline fun Activity.themedAppWidgetHostView(theme: Int = 0, init: (@AnkoViewDslMarker _AppWidgetHostView).() -> Unit): android.appwidget.AppWidgetHostView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.APP_WIDGET_HOST_VIEW, theme) { init() }
}
inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout() {}
inline fun ViewManager.absoluteLayout(init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ABSOLUTE_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedAbsoluteLayout(theme: Int = 0): android.widget.AbsoluteLayout = themedAbsoluteLayout(theme) {}
inline fun ViewManager.themedAbsoluteLayout(theme: Int = 0, init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ABSOLUTE_LAYOUT, theme) { init() }
}
inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout() {}
inline fun Context.absoluteLayout(init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ABSOLUTE_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedAbsoluteLayout(theme: Int = 0): android.widget.AbsoluteLayout = themedAbsoluteLayout(theme) {}
inline fun Context.themedAbsoluteLayout(theme: Int = 0, init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ABSOLUTE_LAYOUT, theme) { init() }
}
inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout() {}
inline fun Activity.absoluteLayout(init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ABSOLUTE_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedAbsoluteLayout(theme: Int = 0): android.widget.AbsoluteLayout = themedAbsoluteLayout(theme) {}
inline fun Activity.themedAbsoluteLayout(theme: Int = 0, init: (@AnkoViewDslMarker _AbsoluteLayout).() -> Unit): android.widget.AbsoluteLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ABSOLUTE_LAYOUT, theme) { init() }
}
inline fun ViewManager.actionMenuView(): android.widget.ActionMenuView = actionMenuView() {}
inline fun ViewManager.actionMenuView(init: (@AnkoViewDslMarker _ActionMenuView).() -> Unit): android.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ACTION_MENU_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedActionMenuView(theme: Int = 0): android.widget.ActionMenuView = themedActionMenuView(theme) {}
inline fun ViewManager.themedActionMenuView(theme: Int = 0, init: (@AnkoViewDslMarker _ActionMenuView).() -> Unit): android.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ACTION_MENU_VIEW, theme) { init() }
}
inline fun Context.actionMenuView(): android.widget.ActionMenuView = actionMenuView() {}
inline fun Context.actionMenuView(init: (@AnkoViewDslMarker _ActionMenuView).() -> Unit): android.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ACTION_MENU_VIEW, theme = 0) { init() }
}
inline fun Context.themedActionMenuView(theme: Int = 0): android.widget.ActionMenuView = themedActionMenuView(theme) {}
inline fun Context.themedActionMenuView(theme: Int = 0, init: (@AnkoViewDslMarker _ActionMenuView).() -> Unit): android.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ACTION_MENU_VIEW, theme) { init() }
}
inline fun Activity.actionMenuView(): android.widget.ActionMenuView = actionMenuView() {}
inline fun Activity.actionMenuView(init: (@AnkoViewDslMarker _ActionMenuView).() -> Unit): android.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ACTION_MENU_VIEW, theme = 0) { init() }
}
inline fun Activity.themedActionMenuView(theme: Int = 0): android.widget.ActionMenuView = themedActionMenuView(theme) {}
inline fun Activity.themedActionMenuView(theme: Int = 0, init: (@AnkoViewDslMarker _ActionMenuView).() -> Unit): android.widget.ActionMenuView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.ACTION_MENU_VIEW, theme) { init() }
}
inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout() {}
inline fun ViewManager.frameLayout(init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.FRAME_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedFrameLayout(theme: Int = 0): android.widget.FrameLayout = themedFrameLayout(theme) {}
inline fun ViewManager.themedFrameLayout(theme: Int = 0, init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.FRAME_LAYOUT, theme) { init() }
}
inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout() {}
inline fun Context.frameLayout(init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.FRAME_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedFrameLayout(theme: Int = 0): android.widget.FrameLayout = themedFrameLayout(theme) {}
inline fun Context.themedFrameLayout(theme: Int = 0, init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.FRAME_LAYOUT, theme) { init() }
}
inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout() {}
inline fun Activity.frameLayout(init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.FRAME_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedFrameLayout(theme: Int = 0): android.widget.FrameLayout = themedFrameLayout(theme) {}
inline fun Activity.themedFrameLayout(theme: Int = 0, init: (@AnkoViewDslMarker _FrameLayout).() -> Unit): android.widget.FrameLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.FRAME_LAYOUT, theme) { init() }
}
inline fun ViewManager.gallery(): android.widget.Gallery = gallery() {}
inline fun ViewManager.gallery(init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GALLERY, theme = 0) { init() }
}
inline fun ViewManager.themedGallery(theme: Int = 0): android.widget.Gallery = themedGallery(theme) {}
inline fun ViewManager.themedGallery(theme: Int = 0, init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GALLERY, theme) { init() }
}
inline fun Context.gallery(): android.widget.Gallery = gallery() {}
inline fun Context.gallery(init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GALLERY, theme = 0) { init() }
}
inline fun Context.themedGallery(theme: Int = 0): android.widget.Gallery = themedGallery(theme) {}
inline fun Context.themedGallery(theme: Int = 0, init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GALLERY, theme) { init() }
}
inline fun Activity.gallery(): android.widget.Gallery = gallery() {}
inline fun Activity.gallery(init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GALLERY, theme = 0) { init() }
}
inline fun Activity.themedGallery(theme: Int = 0): android.widget.Gallery = themedGallery(theme) {}
inline fun Activity.themedGallery(theme: Int = 0, init: (@AnkoViewDslMarker _Gallery).() -> Unit): android.widget.Gallery {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GALLERY, theme) { init() }
}
inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout() {}
inline fun ViewManager.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedGridLayout(theme: Int = 0): android.widget.GridLayout = themedGridLayout(theme) {}
inline fun ViewManager.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout() {}
inline fun Context.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedGridLayout(theme: Int = 0): android.widget.GridLayout = themedGridLayout(theme) {}
inline fun Context.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout() {}
inline fun Activity.gridLayout(init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedGridLayout(theme: Int = 0): android.widget.GridLayout = themedGridLayout(theme) {}
inline fun Activity.themedGridLayout(theme: Int = 0, init: (@AnkoViewDslMarker _GridLayout).() -> Unit): android.widget.GridLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_LAYOUT, theme) { init() }
}
inline fun ViewManager.gridView(): android.widget.GridView = gridView() {}
inline fun ViewManager.gridView(init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedGridView(theme: Int = 0): android.widget.GridView = themedGridView(theme) {}
inline fun ViewManager.themedGridView(theme: Int = 0, init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_VIEW, theme) { init() }
}
inline fun Context.gridView(): android.widget.GridView = gridView() {}
inline fun Context.gridView(init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_VIEW, theme = 0) { init() }
}
inline fun Context.themedGridView(theme: Int = 0): android.widget.GridView = themedGridView(theme) {}
inline fun Context.themedGridView(theme: Int = 0, init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_VIEW, theme) { init() }
}
inline fun Activity.gridView(): android.widget.GridView = gridView() {}
inline fun Activity.gridView(init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_VIEW, theme = 0) { init() }
}
inline fun Activity.themedGridView(theme: Int = 0): android.widget.GridView = themedGridView(theme) {}
inline fun Activity.themedGridView(theme: Int = 0, init: (@AnkoViewDslMarker _GridView).() -> Unit): android.widget.GridView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.GRID_VIEW, theme) { init() }
}
inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView() {}
inline fun ViewManager.horizontalScrollView(init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedHorizontalScrollView(theme: Int = 0): android.widget.HorizontalScrollView = themedHorizontalScrollView(theme) {}
inline fun ViewManager.themedHorizontalScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme) { init() }
}
inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView() {}
inline fun Context.horizontalScrollView(init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme = 0) { init() }
}
inline fun Context.themedHorizontalScrollView(theme: Int = 0): android.widget.HorizontalScrollView = themedHorizontalScrollView(theme) {}
inline fun Context.themedHorizontalScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme) { init() }
}
inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView() {}
inline fun Activity.horizontalScrollView(init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme = 0) { init() }
}
inline fun Activity.themedHorizontalScrollView(theme: Int = 0): android.widget.HorizontalScrollView = themedHorizontalScrollView(theme) {}
inline fun Activity.themedHorizontalScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _HorizontalScrollView).() -> Unit): android.widget.HorizontalScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.HORIZONTAL_SCROLL_VIEW, theme) { init() }
}
inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher() {}
inline fun ViewManager.imageSwitcher(init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.IMAGE_SWITCHER, theme = 0) { init() }
}
inline fun ViewManager.themedImageSwitcher(theme: Int = 0): android.widget.ImageSwitcher = themedImageSwitcher(theme) {}
inline fun ViewManager.themedImageSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.IMAGE_SWITCHER, theme) { init() }
}
inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher() {}
inline fun Context.imageSwitcher(init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.IMAGE_SWITCHER, theme = 0) { init() }
}
inline fun Context.themedImageSwitcher(theme: Int = 0): android.widget.ImageSwitcher = themedImageSwitcher(theme) {}
inline fun Context.themedImageSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.IMAGE_SWITCHER, theme) { init() }
}
inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher() {}
inline fun Activity.imageSwitcher(init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.IMAGE_SWITCHER, theme = 0) { init() }
}
inline fun Activity.themedImageSwitcher(theme: Int = 0): android.widget.ImageSwitcher = themedImageSwitcher(theme) {}
inline fun Activity.themedImageSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ImageSwitcher).() -> Unit): android.widget.ImageSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.IMAGE_SWITCHER, theme) { init() }
}
inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout() {}
inline fun ViewManager.linearLayout(init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.LINEAR_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedLinearLayout(theme: Int = 0): android.widget.LinearLayout = themedLinearLayout(theme) {}
inline fun ViewManager.themedLinearLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.LINEAR_LAYOUT, theme) { init() }
}
inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout() {}
inline fun Context.linearLayout(init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.LINEAR_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedLinearLayout(theme: Int = 0): android.widget.LinearLayout = themedLinearLayout(theme) {}
inline fun Context.themedLinearLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.LINEAR_LAYOUT, theme) { init() }
}
inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout() {}
inline fun Activity.linearLayout(init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.LINEAR_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedLinearLayout(theme: Int = 0): android.widget.LinearLayout = themedLinearLayout(theme) {}
inline fun Activity.themedLinearLayout(theme: Int = 0, init: (@AnkoViewDslMarker _LinearLayout).() -> Unit): android.widget.LinearLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.LINEAR_LAYOUT, theme) { init() }
}
inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup() {}
inline fun ViewManager.radioGroup(init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RADIO_GROUP, theme = 0) { init() }
}
inline fun ViewManager.themedRadioGroup(theme: Int = 0): android.widget.RadioGroup = themedRadioGroup(theme) {}
inline fun ViewManager.themedRadioGroup(theme: Int = 0, init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RADIO_GROUP, theme) { init() }
}
inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup() {}
inline fun Context.radioGroup(init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RADIO_GROUP, theme = 0) { init() }
}
inline fun Context.themedRadioGroup(theme: Int = 0): android.widget.RadioGroup = themedRadioGroup(theme) {}
inline fun Context.themedRadioGroup(theme: Int = 0, init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RADIO_GROUP, theme) { init() }
}
inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup() {}
inline fun Activity.radioGroup(init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RADIO_GROUP, theme = 0) { init() }
}
inline fun Activity.themedRadioGroup(theme: Int = 0): android.widget.RadioGroup = themedRadioGroup(theme) {}
inline fun Activity.themedRadioGroup(theme: Int = 0, init: (@AnkoViewDslMarker _RadioGroup).() -> Unit): android.widget.RadioGroup {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RADIO_GROUP, theme) { init() }
}
inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout() {}
inline fun ViewManager.relativeLayout(init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RELATIVE_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedRelativeLayout(theme: Int = 0): android.widget.RelativeLayout = themedRelativeLayout(theme) {}
inline fun ViewManager.themedRelativeLayout(theme: Int = 0, init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RELATIVE_LAYOUT, theme) { init() }
}
inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout() {}
inline fun Context.relativeLayout(init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RELATIVE_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedRelativeLayout(theme: Int = 0): android.widget.RelativeLayout = themedRelativeLayout(theme) {}
inline fun Context.themedRelativeLayout(theme: Int = 0, init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RELATIVE_LAYOUT, theme) { init() }
}
inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout() {}
inline fun Activity.relativeLayout(init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RELATIVE_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedRelativeLayout(theme: Int = 0): android.widget.RelativeLayout = themedRelativeLayout(theme) {}
inline fun Activity.themedRelativeLayout(theme: Int = 0, init: (@AnkoViewDslMarker _RelativeLayout).() -> Unit): android.widget.RelativeLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.RELATIVE_LAYOUT, theme) { init() }
}
inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView() {}
inline fun ViewManager.scrollView(init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.SCROLL_VIEW, theme = 0) { init() }
}
inline fun ViewManager.themedScrollView(theme: Int = 0): android.widget.ScrollView = themedScrollView(theme) {}
inline fun ViewManager.themedScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.SCROLL_VIEW, theme) { init() }
}
inline fun Context.scrollView(): android.widget.ScrollView = scrollView() {}
inline fun Context.scrollView(init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.SCROLL_VIEW, theme = 0) { init() }
}
inline fun Context.themedScrollView(theme: Int = 0): android.widget.ScrollView = themedScrollView(theme) {}
inline fun Context.themedScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.SCROLL_VIEW, theme) { init() }
}
inline fun Activity.scrollView(): android.widget.ScrollView = scrollView() {}
inline fun Activity.scrollView(init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.SCROLL_VIEW, theme = 0) { init() }
}
inline fun Activity.themedScrollView(theme: Int = 0): android.widget.ScrollView = themedScrollView(theme) {}
inline fun Activity.themedScrollView(theme: Int = 0, init: (@AnkoViewDslMarker _ScrollView).() -> Unit): android.widget.ScrollView {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.SCROLL_VIEW, theme) { init() }
}
inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout() {}
inline fun ViewManager.tableLayout(init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_LAYOUT, theme = 0) { init() }
}
inline fun ViewManager.themedTableLayout(theme: Int = 0): android.widget.TableLayout = themedTableLayout(theme) {}
inline fun ViewManager.themedTableLayout(theme: Int = 0, init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_LAYOUT, theme) { init() }
}
inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout() {}
inline fun Context.tableLayout(init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_LAYOUT, theme = 0) { init() }
}
inline fun Context.themedTableLayout(theme: Int = 0): android.widget.TableLayout = themedTableLayout(theme) {}
inline fun Context.themedTableLayout(theme: Int = 0, init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_LAYOUT, theme) { init() }
}
inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout() {}
inline fun Activity.tableLayout(init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_LAYOUT, theme = 0) { init() }
}
inline fun Activity.themedTableLayout(theme: Int = 0): android.widget.TableLayout = themedTableLayout(theme) {}
inline fun Activity.themedTableLayout(theme: Int = 0, init: (@AnkoViewDslMarker _TableLayout).() -> Unit): android.widget.TableLayout {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_LAYOUT, theme) { init() }
}
inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow() {}
inline fun ViewManager.tableRow(init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_ROW, theme = 0) { init() }
}
inline fun ViewManager.themedTableRow(theme: Int = 0): android.widget.TableRow = themedTableRow(theme) {}
inline fun ViewManager.themedTableRow(theme: Int = 0, init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_ROW, theme) { init() }
}
inline fun Context.tableRow(): android.widget.TableRow = tableRow() {}
inline fun Context.tableRow(init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_ROW, theme = 0) { init() }
}
inline fun Context.themedTableRow(theme: Int = 0): android.widget.TableRow = themedTableRow(theme) {}
inline fun Context.themedTableRow(theme: Int = 0, init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_ROW, theme) { init() }
}
inline fun Activity.tableRow(): android.widget.TableRow = tableRow() {}
inline fun Activity.tableRow(init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_ROW, theme = 0) { init() }
}
inline fun Activity.themedTableRow(theme: Int = 0): android.widget.TableRow = themedTableRow(theme) {}
inline fun Activity.themedTableRow(theme: Int = 0, init: (@AnkoViewDslMarker _TableRow).() -> Unit): android.widget.TableRow {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TABLE_ROW, theme) { init() }
}
inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher() {}
inline fun ViewManager.textSwitcher(init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TEXT_SWITCHER, theme = 0) { init() }
}
inline fun ViewManager.themedTextSwitcher(theme: Int = 0): android.widget.TextSwitcher = themedTextSwitcher(theme) {}
inline fun ViewManager.themedTextSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TEXT_SWITCHER, theme) { init() }
}
inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher() {}
inline fun Context.textSwitcher(init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TEXT_SWITCHER, theme = 0) { init() }
}
inline fun Context.themedTextSwitcher(theme: Int = 0): android.widget.TextSwitcher = themedTextSwitcher(theme) {}
inline fun Context.themedTextSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TEXT_SWITCHER, theme) { init() }
}
inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher() {}
inline fun Activity.textSwitcher(init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TEXT_SWITCHER, theme = 0) { init() }
}
inline fun Activity.themedTextSwitcher(theme: Int = 0): android.widget.TextSwitcher = themedTextSwitcher(theme) {}
inline fun Activity.themedTextSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _TextSwitcher).() -> Unit): android.widget.TextSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TEXT_SWITCHER, theme) { init() }
}
inline fun ViewManager.toolbar(): android.widget.Toolbar = toolbar() {}
inline fun ViewManager.toolbar(init: (@AnkoViewDslMarker _Toolbar).() -> Unit): android.widget.Toolbar {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TOOLBAR, theme = 0) { init() }
}
inline fun ViewManager.themedToolbar(theme: Int = 0): android.widget.Toolbar = themedToolbar(theme) {}
inline fun ViewManager.themedToolbar(theme: Int = 0, init: (@AnkoViewDslMarker _Toolbar).() -> Unit): android.widget.Toolbar {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TOOLBAR, theme) { init() }
}
inline fun Context.toolbar(): android.widget.Toolbar = toolbar() {}
inline fun Context.toolbar(init: (@AnkoViewDslMarker _Toolbar).() -> Unit): android.widget.Toolbar {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TOOLBAR, theme = 0) { init() }
}
inline fun Context.themedToolbar(theme: Int = 0): android.widget.Toolbar = themedToolbar(theme) {}
inline fun Context.themedToolbar(theme: Int = 0, init: (@AnkoViewDslMarker _Toolbar).() -> Unit): android.widget.Toolbar {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TOOLBAR, theme) { init() }
}
inline fun Activity.toolbar(): android.widget.Toolbar = toolbar() {}
inline fun Activity.toolbar(init: (@AnkoViewDslMarker _Toolbar).() -> Unit): android.widget.Toolbar {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TOOLBAR, theme = 0) { init() }
}
inline fun Activity.themedToolbar(theme: Int = 0): android.widget.Toolbar = themedToolbar(theme) {}
inline fun Activity.themedToolbar(theme: Int = 0, init: (@AnkoViewDslMarker _Toolbar).() -> Unit): android.widget.Toolbar {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.TOOLBAR, theme) { init() }
}
inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator() {}
inline fun ViewManager.viewAnimator(init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_ANIMATOR, theme = 0) { init() }
}
inline fun ViewManager.themedViewAnimator(theme: Int = 0): android.widget.ViewAnimator = themedViewAnimator(theme) {}
inline fun ViewManager.themedViewAnimator(theme: Int = 0, init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_ANIMATOR, theme) { init() }
}
inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator() {}
inline fun Context.viewAnimator(init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_ANIMATOR, theme = 0) { init() }
}
inline fun Context.themedViewAnimator(theme: Int = 0): android.widget.ViewAnimator = themedViewAnimator(theme) {}
inline fun Context.themedViewAnimator(theme: Int = 0, init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_ANIMATOR, theme) { init() }
}
inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator() {}
inline fun Activity.viewAnimator(init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_ANIMATOR, theme = 0) { init() }
}
inline fun Activity.themedViewAnimator(theme: Int = 0): android.widget.ViewAnimator = themedViewAnimator(theme) {}
inline fun Activity.themedViewAnimator(theme: Int = 0, init: (@AnkoViewDslMarker _ViewAnimator).() -> Unit): android.widget.ViewAnimator {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_ANIMATOR, theme) { init() }
}
inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher() {}
inline fun ViewManager.viewSwitcher(init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_SWITCHER, theme = 0) { init() }
}
inline fun ViewManager.themedViewSwitcher(theme: Int = 0): android.widget.ViewSwitcher = themedViewSwitcher(theme) {}
inline fun ViewManager.themedViewSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_SWITCHER, theme) { init() }
}
inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher() {}
inline fun Context.viewSwitcher(init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_SWITCHER, theme = 0) { init() }
}
inline fun Context.themedViewSwitcher(theme: Int = 0): android.widget.ViewSwitcher = themedViewSwitcher(theme) {}
inline fun Context.themedViewSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_SWITCHER, theme) { init() }
}
inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher() {}
inline fun Activity.viewSwitcher(init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_SWITCHER, theme = 0) { init() }
}
inline fun Activity.themedViewSwitcher(theme: Int = 0): android.widget.ViewSwitcher = themedViewSwitcher(theme) {}
inline fun Activity.themedViewSwitcher(theme: Int = 0, init: (@AnkoViewDslMarker _ViewSwitcher).() -> Unit): android.widget.ViewSwitcher {
return ankoView(`$$Anko$Factories$Sdk28ViewGroup`.VIEW_SWITCHER, theme) { init() }
}
| apache-2.0 | 4385d0f29468ba3db3323ecaed2e8df8 | 59.01746 | 200 | 0.745259 | 4.253684 | false | false | false | false |
weisterjie/FamilyLedger | app/src/main/java/ycj/com/familyledger/view/EdxDialog.kt | 1 | 6300 | package ycj.com.familyledger.view
import android.app.Dialog
import android.content.Context
import android.graphics.drawable.BitmapDrawable
import android.text.Editable
import android.text.InputFilter
import android.text.InputType
import android.text.TextWatcher
import android.view.Gravity
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import org.jetbrains.anko.*
import ycj.com.familyledger.R
import ycj.com.familyledger.utils.RegexUtils
import java.text.SimpleDateFormat
import java.util.*
/**
* @author: ycj
* @date: 2017-06-15 15:06
* @version V1.0 <>
*/
class EdxDialog {
companion object {
fun create(): EdxDialog = EdxDialog()
}
fun showEdxDialog(msg: String, context: Context, callBack: DataCallBack) {
val dialog = Dialog(context)
dialog.show()
val wind = dialog.window
wind.setBackgroundDrawable(BitmapDrawable())
val windowMa = context.windowManager
val attri = wind.attributes
attri.width = (windowMa.defaultDisplay.width * 0.75).toInt()
attri.height = (windowMa.defaultDisplay.height * 0.45).toInt()
wind.attributes = attri
var edxDate: EditText? = null
var edxCash: EditText? = null
var tvOk: TextView? = null
val dialogView = context.relativeLayout {
background = context.resources.getDrawable(R.drawable.bg_edx_dialog)
lparams(width = matchParent, height = matchParent) {
topPadding = dip(10)
}
textView(msg) {
gravity = Gravity.CENTER
textSize = sp(5).toFloat()
textColor = context.resources.getColor(R.color.black_text)
}.lparams(width = matchParent, height = dip(40))
linearLayout {
orientation = LinearLayout.VERTICAL
gravity = Gravity.CENTER
edxDate = editText {
id = R.id.edx_date_add
maxLines = 1
textSize = sp(5).toFloat()
inputType = InputType.TYPE_DATETIME_VARIATION_DATE or InputType.TYPE_CLASS_DATETIME
filters = arrayOf<InputFilter>(InputFilter.LengthFilter(10))
background = context.resources.getDrawable(R.drawable.edx_input_bg)
hintTextColor = context.resources.getColor(R.color.gray_text)
hint = "日期模板 2017-06-20"
}.lparams(width = matchParent, height = dip(40)) {
rightMargin = dip(20)
leftMargin = dip(20)
}
edxCash = editText {
id = R.id.edx_cash_add
maxLines = 1
textSize = sp(5).toFloat()
inputType = InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_CLASS_NUMBER
filters = arrayOf<InputFilter>(InputFilter.LengthFilter(8))
background = context.resources.getDrawable(R.drawable.edx_input_bg)
hint = "请输入金额"
hintTextColor = context.resources.getColor(R.color.gray_text)
}.lparams(width = matchParent, height = dip(40)) {
topMargin = dip(20)
rightMargin = dip(20)
leftMargin = dip(20)
}
}.lparams(width = matchParent, height = wrapContent) {
centerInParent()
}
tvOk = textView("确定") {
gravity = Gravity.CENTER
textSize = sp(6).toFloat()
textColor = context.resources.getColor(R.color.btn_text_color_selector)
background = context.resources.getDrawable(R.drawable.bg_btn_bottom_dialog)
}.lparams(width = matchParent, height = dip(40)) {
topMargin = dip(20)
alignParentBottom()
}
}
val date = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(Date())
edxDate?.setText(date)
edxDate?.setSelection(date.length)
tvOk?.setOnClickListener {
val dates = edxDate?.editableText.toString()
val cashs = edxCash?.editableText.toString()
if (dates.length < 6 || cashs == "") {
context.toast("数据有误")
} else if (RegexUtils.create().isDate(dates)) {
callBack.callBack(dates, cashs)
dialog.dismiss()
} else {
context.toast("日期格式不正确")
}
}
edxCash?.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
val res = s.toString()
if (s !is Number && s != ".") return
if (res.length == 1 && res == ".") {
edxCash?.setText("")
return
}
if (res.length == 2 && res.startsWith("0")) {
if (res != "0.") {
edxCash?.setText("0")
edxCash?.setSelection(res.length - 1)
return
}
}
if (res.length == 4 && res.endsWith(".")) {
if (!res.substring(1, res.length - 1).contains(".")) {
} else {
edxCash?.setText(res.substring(0, res.length - 1))
edxCash?.setSelection(res.length - 1)
}
return
}
if (res.length == 4 && res.contains("0.0")) {
if (res.endsWith(".") || res.endsWith("0")) {
edxCash?.setText("0.0")
edxCash?.setSelection(res.length - 1)
}
}
}
override fun afterTextChanged(s: Editable) {
}
})
wind.setContentView(dialogView)
}
interface DataCallBack {
fun callBack(dates: String, cashs: String)
}
}
| apache-2.0 | ffcd01bc25d9e3d8664d361bb36126c8 | 36.461078 | 103 | 0.525575 | 4.834621 | false | false | false | false |
jitsi/jibri | src/main/kotlin/org/jitsi/jibri/util/Tee.kt | 1 | 3324 | /*
* Copyright @ 2018 Atlassian Pty Ltd
*
* 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.jitsi.jibri.util
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
import java.io.OutputStream
import java.io.PipedInputStream
import java.io.PipedOutputStream
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.Future
class EndOfStreamException : Exception()
private const val EOF = -1
/**
* Reads from the given [InputStream] and mirrors the read
* data to all of the created 'branches' off of it.
* All branches will 'receive' all data from the original
* [InputStream] starting at the the point of
* the branch's creation.
* NOTE: This class will not read from the given [InputStream]
* automatically, its [read] must be invoked
* to read the data from the original stream and write it to
* the branches
*/
class TeeLogic(inputStream: InputStream) {
private val reader = BufferedReader(InputStreamReader(inputStream))
private var branches = CopyOnWriteArrayList<OutputStream>()
/**
* Reads a byte from the original [InputStream] and
* writes it to all of the branches. If EOF is detected,
* all branches will be closed and [EndOfStreamException]
* will be thrown, so that any callers can know not
* to bother calling again.
*/
fun read() {
val c = reader.read()
if (c == EOF) {
branches.forEach(OutputStream::close)
throw EndOfStreamException()
} else {
branches.forEach { it.write(c) }
}
}
/**
* If you want to close the Tee before the underlying
* [InputStream] closes, you'll need to call [close] to
* properly close all downstream branches. Note that
* calling [read] after [close] when there are branches
* will result in [java.io.IOException].
*/
fun close() {
branches.forEach(OutputStream::close)
}
/**
* Returns an [InputStream] that will receive
* all data from the original [InputStream]
* starting from the time of its creation
*/
fun addBranch(): InputStream {
with(PipedOutputStream()) {
branches.add(this)
return PipedInputStream(this)
}
}
}
/**
* A wrapper around [TeeLogic] which spins up its own thread
* to do the reading automatically
*/
class Tee(inputStream: InputStream) {
private val teeLogic = TeeLogic(inputStream)
private val task: Future<*>
init {
task = TaskPools.ioPool.submit {
while (true) {
teeLogic.read()
}
}
}
fun addBranch(): InputStream {
return teeLogic.addBranch()
}
fun stop() {
task.cancel(true)
teeLogic.close()
}
}
| apache-2.0 | 7386664cb111ed5701b111f67ab99c9b | 28.415929 | 75 | 0.665764 | 4.333768 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/internal/ThanksActivity.kt | 1 | 874 | package com.androidvip.hebf.ui.internal
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.androidvip.hebf.R
class ThanksActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_thanks)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
val link1 = findViewById<TextView>(R.id.special_sub)
val link2 = findViewById<TextView>(R.id.special_sub_1)
link1.movementMethod = LinkMovementMethod.getInstance()
link2?.movementMethod = LinkMovementMethod.getInstance()
}
}
| apache-2.0 | 841dd68e025c314c7a82d6c71ef57c57 | 32.615385 | 64 | 0.755149 | 4.724324 | false | false | false | false |