repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Edward608/RxBinding | rxbinding-appcompat-v7-kotlin/src/main/kotlin/com/jakewharton/rxbinding2/support/v7/widget/RxToolbar.kt | 2 | 2304 | @file:Suppress(
names = "NOTHING_TO_INLINE"
)
package com.jakewharton.rxbinding2.support.v7.widget
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import com.jakewharton.rxbinding2.internal.VoidToUnit
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import kotlin.Int
import kotlin.Suppress
import kotlin.Unit
/**
* Create an observable which emits the clicked item in `view`'s menu.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.itemClicks(): Observable<MenuItem> = RxToolbar.itemClicks(this)
/**
* Create an observable which emits on `view` navigation click events. The emitted value is
* unspecified and should only be used as notification.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [Toolbar.setNavigationOnClickListener]
* to observe clicks. Only one observable can be used for a view at a time.
*/
inline fun Toolbar.navigationClicks(): Observable<Unit> = RxToolbar.navigationClicks(this).map(VoidToUnit)
/**
* An action which sets the title property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.title(): Consumer<in CharSequence?> = RxToolbar.title(this)
/**
* An action which sets the title property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.titleRes(): Consumer<in Int> = RxToolbar.titleRes(this)
/**
* An action which sets the subtitle property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.subtitle(): Consumer<in CharSequence?> = RxToolbar.subtitle(this)
/**
* An action which sets the subtitle property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
inline fun Toolbar.subtitleRes(): Consumer<in Int> = RxToolbar.subtitleRes(this)
| apache-2.0 | 96100eb8128d9a92e781275c55cb78e3 | 33.909091 | 106 | 0.75434 | 4.151351 | false | false | false | false |
lts123124/comic-read | app/src/main/kotlin/me/tianshengli/comicread/util/DrawView.kt | 1 | 5243 | package me.tianshengli.comicread.util
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ScaleGestureDetector
import android.view.View
import com.bumptech.glide.request.target.ViewTarget
import com.bumptech.glide.request.transition.Transition
@Suppress("unused")
/**
* Created by lts on 16-4-11.
* Image Draw
*/
class DrawView : View {
constructor(
context: Context
) : super(context) {
initView()
}
constructor(
context: Context,
attributeSet: AttributeSet
) : super(context, attributeSet) {
initView()
}
constructor(
context: Context,
attributeSet: AttributeSet,
defStyleAttr: Int
) : super(context, attributeSet, defStyleAttr) {
initView()
}
private var bitmap: Bitmap? = null
private var bmpW: Int = 0
private var bmpH: Int = 0
private var bmpP: Paint = Paint()
private var mScaleFactor = 1.0f
private var mPosX = 0f
private var mPosY = 0f
private var widthScale = 1.0f
private var heightScale = 1.0f
private lateinit var mScaleDetector: ScaleGestureDetector
private lateinit var mGestureDetector: GestureDetector
private var handlerDoubleTap: (() -> Any)? = null
private fun initView() {
mGestureDetector = GestureDetector(context, gestureListener)
mScaleDetector = ScaleGestureDetector(context, scaleListener)
}
fun getLoadTarget(): ViewTarget<DrawView, Bitmap> {
return object : ViewTarget<DrawView, Bitmap>(this) {
override fun onResourceReady(resource: Bitmap?, transition: Transition<in Bitmap>?) {
if(resource != null) {
[email protected](resource)
}
}
}
}
fun setImage(bmp: Bitmap) {
bitmap = bmp
bmpH = bmp.height
bmpW = bmp.width
mScaleFactor = 1.0f
initSize()
invalidate()
}
private var viewW: Int = 0
private var viewH: Int = 0
fun setTargetSize(targetHeight: Int,
targetWidth: Int) {
viewW = targetHeight
viewH = targetWidth
}
private fun initSize() {
if (viewH > 0 && viewW > 0) {
widthScale = 1.0f * viewW / bmpW
heightScale = 1.0f * viewH / bmpH
mScaleFactor = Math.min(widthScale, heightScale)
mPosX = ((viewW / 2) - (bmpW / 2)).toFloat()
mPosY = ((viewH / 2) - (bmpH / 2)).toFloat()
}
}
private fun checkBounds() {
if (mScaleFactor > widthScale) {
mPosX = Math.min(mPosX, (mScaleFactor - 1) * (bmpW / 2))
mPosX = Math.max(mPosX, viewW - bmpW - (mScaleFactor - 1) * (bmpW / 2))
} else {
mPosX = Math.max(mPosX, (mScaleFactor - 1) * (bmpW / 2))
mPosX = Math.min(mPosX, viewW - bmpW - (mScaleFactor - 1) * (bmpW / 2))
}
if (mScaleFactor > heightScale) {
mPosY = Math.min(mPosY, (mScaleFactor - 1) * (bmpH / 2))
mPosY = Math.max(mPosY, viewH - bmpH - (mScaleFactor - 1) * (bmpH / 2))
} else {
mPosY = Math.max(mPosY, (mScaleFactor - 1) * (bmpH / 2))
mPosY = Math.min(mPosY, viewH - bmpH - (mScaleFactor - 1) * (bmpH / 2))
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (bitmap == null) {
canvas.drawColor(Color.BLACK)
return
}
canvas.save()
checkBounds()
canvas.scale(mScaleFactor, mScaleFactor, mPosX + (bmpW / 2), mPosY + (bmpH / 2))
canvas.drawBitmap(bitmap, mPosX, mPosY, bmpP)
canvas.restore()
}
@SuppressLint("ClickableViewAccessibility")
override fun onTouchEvent(event: MotionEvent): Boolean {
mScaleDetector.onTouchEvent(event)
mGestureDetector.onTouchEvent(event)
return true
}
fun setOnDoubleTap(handler: () -> Any) {
handlerDoubleTap = handler
}
private val scaleListener = object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
override fun onScale(detector: ScaleGestureDetector): Boolean {
mScaleFactor *= detector.scaleFactor
mScaleFactor = Math.max(0.3f, Math.min(mScaleFactor, 4.0f))
invalidate()
return true
}
}
private val gestureListener = object : GestureDetector.SimpleOnGestureListener() {
override fun onScroll(
e1: MotionEvent?,
e2: MotionEvent?,
distanceX: Float,
distanceY: Float
): Boolean {
mPosX -= distanceX
mPosY -= distanceY
invalidate()
return true
}
override fun onDoubleTap(e: MotionEvent?): Boolean {
if (handlerDoubleTap != null) {
handlerDoubleTap!!()
}
return true
}
}
} | mit | fdd76934641efa66d17f8d69ad3c9e9b | 27.042781 | 97 | 0.585352 | 4.34743 | false | false | false | false |
arcao/Geocaching4Locus | geocaching-api/src/main/java/com/arcao/geocaching4locus/data/api/model/GeocacheLogType.kt | 1 | 2098 | package com.arcao.geocaching4locus.data.api.model
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
class GeocacheLogType(
id: Int,
name: String,
imageUrl: String
) : Type(id, name, imageUrl) {
companion object {
/** found the geocache */
const val FOUND_IT = 2
/** Did Not Find (DNF) the geocache */
const val DNF_IT = 3
/** Adding a comment to the geocache */
const val WRITE_NOTE = 4
/** changing the status of the geocache to archived */
const val ARCHIVE = 5
/** flagging the geocache as needing to be archived */
const val NEEDS_ARCHIVING = 7
/** RSVPing for an event */
const val WILL_ATTEND = 9
/** Attended an event (counts as a find) */
const val ATTENDED = 10
/** Successfully captured a webcam geocache (counts as a find) */
const val WEBCAM_PHOTO_TAKEN = 11
/** changing the status of the geocache from archived to active */
const val UNARCHIVE = 12
/** changing the status of the geocache to disabled */
const val TEMPORARILY_DISABLE_LISTING = 22
/** changing the status of the geocache from disabled to active */
const val ENABLE_LISTING = 23
/** changing the status of the geocache from unpublished to active */
const val PUBLISH_LISTING = 24
/** retracting the geocache (admin only) */
const val RETRACT_LISTING = 25
/** flagging a geocache owner that the geocache needs some attention */
const val NEEDS_MAINTENANCE = 45
/** announcing that owner maintenance was done */
const val OWNER_MAINTENANCE = 46
/** updating the coordinates of the geocache */
const val UPDATE_COORDINATES = 47
/** a note left by the reviewer */
const val POST_REVIEWER_NOTE = 68
/** event host announcement to attendees */
const val EVENT_ANNOUNCEMENT = 74
/** submitting a geocache to be published */
const val SUBMIT_FOR_REVIEW = 76
}
}
| gpl-3.0 | 37dc31e11133c311553af968160b6ba5 | 29.405797 | 79 | 0.615825 | 4.444915 | false | false | false | false |
FantAsylum/Floor--13 | core/src/com/floor13/game/core/creatures/Cyborg.kt | 1 | 2619 | package com.floor13.game.core.creatures
import com.floor13.game.core.Position
import com.floor13.game.core.map.Map
class Cyborg(kindId: String, position: Position): Creature(kindId, position) {
override val perception: Int
get() = basePerception // TODO: perception classes, item bonuses
override val connectivity: Int
get() = baseConnectivity // TODO: connectivity classes, item bonuses
override val intelligence: Int
get() = baseIntelligence // TODO: item bonuses, hunger penalty (possibly)
override val canSeeThroughWalls = false // TODO: possible - with sonar sight system
override fun hit(damagePoints: Int) {
// TODO: implement
}
// TODO: add function for hitting specified part
override fun levelUp(level: Int) {
attributePoints++
}
override val sightRange = 4 // FIXME: stub
override fun calculateFieldOfView(map: Map): List<Position> {
fun dist(x1: Int, y1: Int, x2: Int, y2: Int): Float {
val x = x2 - x1
val y = y2 - y1
return x.toFloat() * x.toFloat() + y.toFloat() * y.toFloat()
}
// TODO: pick FOV calculation method basing on Sight System item
// of the cyborg and optimize
return map.getTilesWithIndices()
.filter { (x, y, tile) -> dist(x, y, position.x, position.y) < sightRange * sightRange }
.map { Position(it.x, it.y) }
}
var basePerception: Int = 0
private set
var baseConnectivity: Int = 0
private set
var baseIntelligence: Int = 0
private set
var attributePoints: Int = 0
private set
/**
* Increase intelligence using one attribute point
* @return true - if succeded, false - if cyborg has no attribute points
*/
fun increasePerception(): Boolean {
if (attributePoints > 0) {
attributePoints--
basePerception++
return true
}
return false
}
/**
* Increase intelligence using one attribute point
* @return true - if succeded, false - if cyborg has no attribute points
*/
fun increaseConnectivity(): Boolean {
if (attributePoints > 0) {
attributePoints--
baseConnectivity++
return true
}
return false
}
/**
* Increase intelligence using one attribute point
* @return true - if succeded, false - if cyborg has no attribute points
*/
fun increaseIntelligence(): Boolean {
if (attributePoints > 0) {
attributePoints--
baseIntelligence++
return true
}
return false
}
}
| mit | a7837b43d3fe6854a67707ac5992f695 | 28.761364 | 92 | 0.621229 | 4.092188 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/Pose.kt | 1 | 3824 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle
import org.joml.Matrix4f
import org.joml.Vector2d
import uk.co.nickthecoder.tickle.graphics.Color
import uk.co.nickthecoder.tickle.graphics.Renderer
import uk.co.nickthecoder.tickle.graphics.Texture
import uk.co.nickthecoder.tickle.resources.Resources
import uk.co.nickthecoder.tickle.util.*
class Pose(
val texture: Texture,
rect: YDownRect = YDownRect(0, 0, texture.width, texture.height))
: Copyable<Pose>, Deletable, Renamable, Dependable {
var rect: YDownRect = rect
set(v) {
field = v
updateRectd()
}
var offsetX: Double = 0.0
var offsetY: Double = 0.0
/**
* Points other than the offsetX,Y, which can be snapped to.
*/
var snapPoints = mutableListOf<Vector2d>()
/**
* The natural direction. i.e. if the Actor moved "forward", which mathematical angle would that be?
* For the default value of 0, the image is pointing to the right.
*/
val direction = Angle()
/**
* If the pose is tiled, then the actor will use a TiledAppearance, and it can be resized without scaling.
*/
var tiled = false
internal val rectd = Rectd(0.0, 0.0, 1.0, 1.0)
init {
updateRectd()
}
fun updateRectd() {
rectd.left = rect.left.toDouble() / texture.width
rectd.bottom = rect.bottom.toDouble() / texture.height
rectd.right = rect.right.toDouble() / texture.width
rectd.top = rect.top.toDouble() / texture.height
}
private val WHITE = Color.white()
fun draw(renderer: Renderer, x: Double, y: Double, color: Color = WHITE, modelMatrix: Matrix4f? = null) {
val left = x - offsetX
val bottom = y - offsetY
renderer.drawTexture(
texture,
left, bottom, left + rect.width, bottom + rect.height,
rectd,
color,
modelMatrix)
}
// Dependency
// Deletable
override fun dependables(): List<Costume> {
return Resources.instance.costumes.items().values.filter { it.dependsOn(this) }
}
override fun delete() {
Resources.instance.poses.remove(this)
}
// Renamable
override fun rename(newName: String) {
Resources.instance.poses.rename(this, newName)
}
// Copyable
override fun copy(): Pose {
val copy = Pose(texture, YDownRect(rect.left, rect.top, rect.right, rect.bottom))
copy.offsetX = offsetX
copy.offsetY = offsetY
copy.direction.radians = direction.radians
return copy
}
/*
// Causes a problem - Copy a Pose, and double clicking the copy won't open the copy (as the original is equal to it).
override fun equals(other: Any?): Boolean {
if (other !is Pose) {
return false
}
return rect == other.rect && rectd == other.rectd && texture == other.texture && direction.radians == other.direction.radians && tiled == other.tiled
}
*/
override fun toString(): String {
return "Pose rect=$rect offset=($offsetX , $offsetY) direction=$direction rectd=$rectd"
}
}
| gpl-3.0 | 2e60fb02862db0ead161ca3c06ea394d | 29.110236 | 157 | 0.64932 | 4.055143 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/bean/others/AppointMentItemBean.kt | 1 | 616 | package com.fuyoul.sanwenseller.bean.others
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.configs.Code
/**
* @author: chen
* @CreatDate: 2017\10\30 0030
* @Desc:
*/
class AppointMentItemBean : MultBaseBean {
override fun itemType(): Int = Code.VIEWTYPE_APPOINTMENT
var isSelect = false//是否已预约
var time: String = ""//时间
var avatar: String = ""//预约用户的头像
var userInfoId: Long = 0//预约人的id
var orderId: Long = 0
var isBusy = false//是否全天不可约
var canOrder = true// 某个时间点是否可接单
} | apache-2.0 | 275753fd6f017ab56c2eb81f1bfc2ec5 | 23.863636 | 60 | 0.692308 | 3.230769 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/WebPages.kt | 1 | 1655 | package cn.yiiguxing.plugin.translate
import java.util.*
object WebPages {
private const val BASE_URL_GITHUB = "https://yiiguxing.github.io/TranslationPlugin"
private const val BASE_URL_GITEE = "https://yiiguxing.gitee.io/translation-plugin"
fun get(vararg path: String, locale: Locale = Locale.getDefault()): String {
val baseUrl =
if (locale.language == Locale.CHINESE.language && (locale.country == "" || locale.country == "CN")) {
BASE_URL_GITEE
} else {
BASE_URL_GITHUB
}
val langPath = when (locale.language) {
Locale.CHINESE.language -> ""
Locale.JAPANESE.language -> "/ja"
Locale.KOREAN.language -> "/ko"
else -> "/en"
}
return "$baseUrl$langPath/${path.joinToString("/")}"
}
fun getStarted(locale: Locale = Locale.getDefault()): String = get("start.html", locale = locale)
fun updates(version: String = "", locale: Locale = Locale.getDefault()): String {
val query = if (version.isEmpty()) "" else "?v=$version"
return get("updates.html${query}", locale = locale)
}
fun releaseNote(version: String, dark: Boolean = false, locale: Locale = Locale.getDefault()): String {
return get(
"updates",
"v${version.replace('.', '_')}.html?editor=true&dark=$dark",
locale = locale
)
}
fun support(locale: Locale = Locale.getDefault()): String = get("support.html", locale = locale)
fun donors(locale: Locale = Locale.getDefault()): String = get("support.html#patrons", locale = locale)
} | mit | d3049552fcccabdff938d48d01fb735f | 35.8 | 113 | 0.592749 | 4.168766 | false | false | false | false |
alexnuts/kiwi | kiwi/src/main/java/com/kiwi/ui/BaseView.kt | 1 | 1629 | package com.kiwi.ui
import android.content.Context
import android.os.Bundle
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import com.kiwi.ScreenHolder
import com.kiwi.adapter.Typed
import kotlin.properties.Delegates
/**
* Created by alexflipren on 18.04.16.
*/
abstract class KBaseView(context: Context, attributeSet: AttributeSet? = null, style: Int = -1) : LinearLayout(context, attributeSet, style), ScreenHolder {
val inflaterView: View
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, -1)
init {
inflaterView = LayoutInflater.from(context).inflate(layoutId(), this, true)
}
override fun onAttachedToWindow() {
onInit(null, null)
super.onAttachedToWindow()
}
override fun onInit(arguments: Bundle?, savedInstance: Bundle?) {
onInitView()
}
abstract fun onInitView()
}
abstract class KBaseTypedView<T : Typed>(context: Context, attributeSet: AttributeSet? = null, style: Int = -1) : KBaseView(context, attributeSet, style) {
var obj: T? by Delegates.observable(null) {
prop, old: T?, new: T? ->
setObject(new)
}
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, -1)
private fun setObject(obj: T?) {
if (obj != null)
onUpdate(obj)
else
onUpdateEmpty()
}
abstract fun onUpdate(obj: T)
open fun onUpdateEmpty() = Unit
open fun setOnKeyListener(key: String, listener: OnClickListener) {
}
} | apache-2.0 | cabb30b9e9bfc35bf1cc2a53f1de88fa | 24.873016 | 156 | 0.686311 | 4.155612 | false | false | false | false |
konrad-jamrozik/droidmate | dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/ApkViewsFile.kt | 1 | 1979 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2016 Konrad Jamrozik
//
// 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/>.
//
// email: [email protected]
// web: www.droidmate.org
package org.droidmate.report
import com.konradjamrozik.isDirectory
import org.droidmate.exploration.data_aggregators.IApkExplorationOutput2
import java.nio.file.Files
import java.nio.file.Path
class ApkViewsFile(val data: IApkExplorationOutput2, dir: Path) : DataFile(buildFilePath(data, dir)) {
init {
require(dir.isDirectory)
}
override fun writeOut() {
Files.write(file, apkViewsString.toByteArray())
}
val apkViewsString: String by lazy { data.apkViewsString }
private val IApkExplorationOutput2.apkViewsString: String
get() {
return "Unique actionable widget\n" +
this.uniqueActionableWidgets.map { it.uniqueString }.joinToString(separator = "\n") +
"\n====================\n" +
"Unique clicked widgets\n" +
this.uniqueClickedWidgets.map { it.uniqueString }.joinToString(separator = "\n")
}
companion object {
val fileNameSuffix = "_views.txt"
private fun buildFilePath(data: IApkExplorationOutput2, dir: Path): Path {
require(dir.isDirectory)
return dir.resolve("${data.apkFileNameWithUnderscoresForDots}$fileNameSuffix")
}
}
}
| gpl-3.0 | 0db1b7c389679a2bdc01a8b2e46cf27b | 32.542373 | 102 | 0.718039 | 4.131524 | false | false | false | false |
HelloHuDi/usb-with-serial-port | usb-serial-port-measure/src/main/java/com/aio/usbserialport/cache/UsbSerialPortCache.kt | 1 | 4477 | package com.aio.usbserialport.cache
import android.content.Context
import android.hardware.usb.UsbDevice
import android.util.Base64
import com.aio.usbserialport.utils.ParcelableUtil
import com.aio.usbserialport.utils.PreferenceUtil
import com.hd.serialport.usb_driver.*
import com.hd.serialport.utils.L
/**
* Created by hd on 2017/8/31 .
* usb port [android.hardware.usb.UsbDevice]and
* serial port[android.serialport.SerialPort] path
* [com.hd.serialport.param.SerialPortMeasureParameter.devicePath]cache
*/
class UsbSerialPortCache constructor(val context: Context, val deviceType: Int) {
companion object {
fun newInstance(context: Context, deviceType: Int = 0) = UsbSerialPortCache(context, deviceType)
}
private val usbDevice_Name = "_usbDevice"
private val usbPort_Name = "_usbPort"
private val serialPort_Name = "_serialPort"
fun getSerialPortCache() = PreferenceUtil.get(context, deviceType.toString()+serialPort_Name, "") as String
fun getUsbDeviceCache(): UsbDevice? {
if (!PreferenceUtil.contains(context, deviceType.toString() + usbDevice_Name)) return null
val usbDeviceStr = PreferenceUtil.get(context, deviceType.toString() + usbDevice_Name, "") as String
if (usbDeviceStr.isNotEmpty())
return UsbDevice.CREATOR.createFromParcel(ParcelableUtil.read(Base64.decode(usbDeviceStr, 0)))
return null
}
fun getUsbPortCache(): UsbSerialPort? {
if (!PreferenceUtil.contains(context, deviceType.toString()+usbPort_Name)) return null
val usbDevice = getUsbDeviceCache() ?: return null
val usb_type = PreferenceUtil.get(context, deviceType.toString()+usbPort_Name, 0) as Int
var driver: UsbSerialDriver? = null
when (usb_type) {
/*UsbPortDeviceType.USB_CDC_ACM */1 -> driver = CdcAcmSerialDriver(usbDevice)
/*UsbPortDeviceType.USB_CP21xx*/ 2 -> driver = Cp21xxSerialDriver(usbDevice)
/*UsbPortDeviceType.USB_FTD*/ 3 -> driver = FtdiSerialDriver(usbDevice)
/*UsbPortDeviceType.USB_PL2303*/4 -> driver = ProlificSerialDriver(usbDevice)
/*UsbPortDeviceType.USB_CH34xx*/5 -> driver = Ch34xSerialDriver(usbDevice)
}
if (driver != null) {
val port = driver.ports[0]
L.d("get cache port success:"+driver+"="+driver.deviceType)
return port
}
L.d("get cache port UnSuccess")
return null
}
fun removeCachePort() {
PreferenceUtil.remove(context, deviceType.toString()+usbPort_Name)
PreferenceUtil.remove(context, deviceType.toString()+serialPort_Name)
PreferenceUtil.remove(context, deviceType.toString() + usbDevice_Name)
}
fun removeAllCachePort() {
PreferenceUtil.clear(context)
}
fun setUsbSerialPortCache(usbPort: UsbSerialPort?=null,usbDevice: UsbDevice?=null,serialPortPath: String?=null){
if(usbPort!=null){
setUsbPortCache(usbPort)
}else if(usbDevice!=null){
setUsbDeviceCache(usbDevice)
}else if(!serialPortPath.isNullOrEmpty()){
setSerialPortCache(serialPortPath)
}
}
fun setSerialPortCache(serialPortPath: String) {
if (!PreferenceUtil.contains(context, deviceType.toString()+serialPort_Name))
PreferenceUtil.put(context, deviceType.toString()+serialPort_Name, serialPortPath)
}
fun setUsbDeviceCache(usbDevice: UsbDevice) {
if (!PreferenceUtil.contains(context, deviceType.toString() + usbDevice_Name))
PreferenceUtil.put(context, deviceType.toString() + usbDevice_Name, Base64.encodeToString(ParcelableUtil.write(usbDevice), 0))
}
fun setUsbPortCache(usbPort: UsbSerialPort) {
val usbDevice = usbPort.driver.device
var usb_type = 0//UsbPortDeviceType.USB_OTHERS
when (usbPort) {
is CdcAcmSerialDriver.CdcAcmSerialPort -> usb_type = 1//UsbPortDeviceType.USB_CDC_ACM
is Cp21xxSerialDriver.Cp21xxSerialPort -> usb_type = 2//UsbPortDeviceType.USB_CP21xx
is FtdiSerialDriver.FtdiSerialPort -> usb_type = 3//UsbPortDeviceType.USB_FTD
is ProlificSerialDriver.ProlificSerialPort -> usb_type = 4//UsbPortDeviceType.USB_PL2303
is Ch34xSerialDriver.Ch340SerialPort -> usb_type = 5//UsbPortDeviceType.USB_CH34xx
}
PreferenceUtil.put(context, deviceType.toString()+usbPort_Name, usb_type)
setUsbDeviceCache(usbDevice)
}
} | apache-2.0 | 3482d66a39be337f73e0b71f0f46f986 | 42.901961 | 138 | 0.695555 | 3.958444 | false | false | false | false |
luoyuan800/NeverEnd | dataModel/src/cn/luo/yuan/maze/model/task/Scene.kt | 1 | 518 | package cn.luo.yuan.maze.model.task
import cn.luo.yuan.maze.utils.Field
import cn.luo.yuan.maze.utils.StringUtils
import java.io.Serializable
/**
* Copyright @Luo
* Created by Gavin Luo on 8/1/2017.
*/
class Scene : Serializable {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
var taskId :String = StringUtils.EMPTY_STRING;
var order = 0
var leftPic:Array<Byte>? = null
var rightPic:Array<Byte>? = null
val msg = mutableListOf<String>()
} | bsd-3-clause | 46a5c02e0ca42c28b50a56e83758a82c | 24.95 | 71 | 0.698842 | 3.572414 | false | false | false | false |
TheFallOfRapture/First-Game-Engine | src/main/kotlin/com/morph/engine/graphics/LoadedFont.kt | 2 | 5052 | package com.morph.engine.graphics
import com.morph.engine.math.Vector2f
import com.morph.engine.util.IOUtils
import org.lwjgl.BufferUtils
import org.lwjgl.stb.*
import org.lwjgl.system.MemoryStack
import java.io.IOException
import java.nio.CharBuffer
/**
* Created on 7/30/2017.
*/
class LoadedFont(val fontName: String) {
lateinit var textureAtlas: Texture
private set
private val charIndices: Array<IntArray> = Array(CHARSET_RANGE) { intArrayOf() }
private var characters: Array<LoadedCharacter?> = arrayOfNulls(CHARSET_RANGE)
var scale: Float = 0f
private set
var ascent: Float = 0f
private set
private var yAdvance: Int = 0
private val size: Int = 0
private var kerningTable: Array<FloatArray> = Array(CHARSET_RANGE) { FloatArray(CHARSET_RANGE) }
init {
try {
STBTTPackContext.malloc().use { context ->
STBTTPackedchar.malloc(CHARSET_RANGE).use { packedChars ->
val pixels = BufferUtils.createByteBuffer(LoadedFont.BITMAP_WIDTH * LoadedFont.BITMAP_HEIGHT)
val fontBuffer = IOUtils.getFileAsByteBuffer(fontName, 160 * 1024)
STBTruetype.stbtt_PackSetOversampling(context, 2, 2)
STBTruetype.stbtt_PackBegin(context, pixels, LoadedFont.BITMAP_WIDTH, LoadedFont.BITMAP_HEIGHT, 0, 1)
STBTruetype.stbtt_PackFontRange(context, fontBuffer, 0, LoadedFont.SIZE.toFloat(), 32, packedChars)
STBTruetype.stbtt_PackEnd(context)
this.textureAtlas = Texture(fontName, LoadedFont.BITMAP_WIDTH, LoadedFont.BITMAP_HEIGHT, pixels)
preloadPackedChars(packedChars)
}
}
} catch (e: IOException) {
throw RuntimeException(e)
}
}
private fun preloadPackedChars(packedChars: STBTTPackedchar.Buffer) {
try {
MemoryStack.stackPush().use { stack ->
val x = stack.floats(0.0f)
val y = stack.floats(0.0f)
val q = STBTTAlignedQuad.mallocStack(stack)
val fontInfo = STBTTFontinfo.mallocStack(stack)
val fontBuffer = IOUtils.getFileAsByteBuffer(fontName, 160 * 1024)
val ascent = IntArray(1)
val descent = IntArray(1)
val lineGap = IntArray(1)
STBTruetype.stbtt_InitFont(fontInfo, fontBuffer)
scale = STBTruetype.stbtt_ScaleForPixelHeight(fontInfo, LoadedFont.SIZE.toFloat())
STBTruetype.stbtt_GetFontVMetrics(fontInfo, ascent, descent, lineGap)
yAdvance = ascent[0] - descent[0] + lineGap[0]
this.ascent = ascent[0] * scale
for (i in 0 until CHARSET_RANGE) {
val c = CHARSET[i]
val xAdvance = IntArray(1)
val leftSideBearing = IntArray(1)
STBTruetype.stbtt_GetPackedQuad(packedChars, LoadedFont.BITMAP_WIDTH, LoadedFont.BITMAP_HEIGHT, i, x, y, q, false)
STBTruetype.stbtt_GetCodepointHMetrics(fontInfo, c.toInt(), xAdvance, leftSideBearing)
val texCoords = arrayOf(Vector2f(q.s0(), q.t0()), Vector2f(q.s1(), q.t0()), Vector2f(q.s1(), q.t1()), Vector2f(q.s0(), q.t1()))
val indices = sequenceOf(0, 1, 3, 1, 2, 3).map { it * 4 }
val pc = packedChars.get(i)
val offsetData = floatArrayOf(pc.xoff(), pc.yoff(), pc.xoff2(), pc.yoff2())
characters[c.toInt() - CHAR_FIRST] = LoadedCharacter(c, texCoords, indices.toList().toTypedArray().toIntArray(), xAdvance[0].toFloat(), offsetData)
CharBuffer.wrap(CHARSET.toCharArray()).chars().forEach { c2 -> kerningTable[c.toInt() - CHAR_FIRST][c2 - CHAR_FIRST] = STBTruetype.stbtt_GetCodepointKernAdvance(fontInfo, c.toInt(), c2) * scale }
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
fun kerningLookup(c1: Char, c2: Char): Float {
return if (c1 == '\n' || c2 == '\n') 0f else kerningTable[c1.toInt() - CHAR_FIRST][c2.toInt() - CHAR_FIRST]
}
fun getCharData(c: Char) = charIndices[c.toInt() - CHAR_FIRST]
fun getCharacter(c: Char) = characters[c.toInt() - CHAR_FIRST]
fun getYAdvance() = yAdvance.toFloat()
fun destroy() {
textureAtlas.destroy()
}
companion object {
private const val BITMAP_WIDTH = 1024
private const val BITMAP_HEIGHT = 1024
const val SIZE = 64
const val CHAR_FIRST = 32
private const val CHAR_LAST = 128
const val CHARSET_RANGE = CHAR_LAST - CHAR_FIRST
@JvmStatic val CHARSET: String = buildString {
for (i in CHAR_FIRST until CHAR_LAST) {
append(i.toChar())
}
}
fun isValidChar(c: Char): Boolean {
return CHARSET.contains(Character.toString(c))
}
}
}
| mit | 83215f26a38f102cdfbfb52b43dbbb04 | 35.875912 | 215 | 0.594814 | 3.901158 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/symphony/SymphonyAuthInterceptor.kt | 1 | 6120 | package com.baulsupp.okurl.services.symphony
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.AuthInterceptor
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.kotlin.JSON
import com.baulsupp.okurl.kotlin.query
import com.baulsupp.okurl.kotlin.request
import com.baulsupp.okurl.secrets.Secrets
import com.baulsupp.okurl.services.AbstractServiceDefinition
import com.baulsupp.okurl.services.symphony.model.SessionInfo
import com.baulsupp.okurl.services.symphony.model.TokenResponse
import kotlinx.coroutines.runBlocking
import okhttp3.HttpUrl
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.Buffer
import java.io.File
import java.security.KeyStore
import java.security.SecureRandom
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager
class SymphonyAuthInterceptor : AuthInterceptor<SymphonyCredentials>() {
override val serviceDefinition = object : AbstractServiceDefinition<SymphonyCredentials>(
"symphony.com", "Symphony", "symphony",
"https://rest-api.symphony.com/"
) {
override fun parseCredentialsString(s: String): SymphonyCredentials {
return SymphonyCredentials.parse(s)
}
override fun formatCredentialsString(credentials: SymphonyCredentials): String = credentials.format()
}
override suspend fun intercept(chain: Interceptor.Chain, credentials: SymphonyCredentials): Response {
var request = chain.request()
if (credentials.sessionToken != null) {
val builder = request.newBuilder().header("sessionToken", credentials.sessionToken)
.header("keyManagerToken", credentials.keyToken.orEmpty())
repairJsonRequests(request, builder)
request = builder.build()
}
return chain.proceed(request)
}
private fun repairJsonRequests(request: Request, builder: Request.Builder) {
if (request.header("Content-Type") == "application/x-www-form-urlencoded") {
val buffer = Buffer()
request.body!!.writeTo(buffer)
// repair missing header
if (buffer.size > 0 && (buffer[0] == '['.toByte() || buffer[0] == '{'.toByte())) {
builder.header("Content-Type", "application/json")
}
}
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): SymphonyCredentials {
val pod = Secrets.prompt("Symphony POD", "symphony.pod", "foundation-dev", false)
val keystoreFile = Secrets.prompt(
"Symphony Client ID",
"symphony.keystore",
System.getenv("HOME") + "/.symphony/keystore.p12",
false
)
val password = Secrets.prompt("Symphony Password", "symphony.password", "", true)
return auth(keystoreFile, password, client, pod)
}
private suspend fun auth(
keystoreFile: String,
password: String,
client: OkHttpClient,
pod: String
): SymphonyCredentials {
val keystore = KeyStore.getInstance("PKCS12").apply {
load(File(keystoreFile).inputStream(), password.toCharArray())
}
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
kmf.init(keystore, password.toCharArray())
val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
tmf.init(null as KeyStore?)
val context = SSLContext.getInstance("TLS")
context.init(kmf.keyManagers, tmf.trustManagers, SecureRandom())
val ssf = context.socketFactory
val tm = tmf.trustManagers[0] as X509TrustManager
// TODO avoid leaking connections
val authClient = client.newBuilder().sslSocketFactory(ssf, tm).build()
val authResponse = authClient.query<TokenResponse>(request {
url("https://$pod-api.symphony.com/sessionauth/v1/authenticate")
post("{}".toRequestBody(JSON))
})
val keyResponse = authClient.query<TokenResponse>(request {
url("https://$pod-api.symphony.com/keyauth/v1/authenticate")
post("{}".toRequestBody(JSON))
})
return SymphonyCredentials(pod, keystoreFile, password, authResponse.token, keyResponse.token)
}
override suspend fun validate(
client: OkHttpClient,
credentials: SymphonyCredentials
): ValidatedCredentials {
if (credentials.sessionToken == null) {
return ValidatedCredentials()
}
val result = client.query<SessionInfo>(request {
url("https://${credentials.pod}.symphony.com/pod/v2/sessioninfo")
header("sessionToken", credentials.sessionToken)
})
return ValidatedCredentials(result.displayName, result.company)
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
return SymphonyUrlCompleter(pods(credentialsStore), completionVariableCache, client)
}
override fun canRenew(credentials: SymphonyCredentials): Boolean {
return true
}
override suspend fun renew(client: OkHttpClient, credentials: SymphonyCredentials): SymphonyCredentials? {
return auth(credentials.keystore, credentials.password, client, credentials.pod)
}
suspend fun pods(credentialsStore: CredentialsStore): List<String> {
val pods = credentialsStore.findAllNamed(serviceDefinition).keys.toList()
return listOf("foundation-dev") + pods
}
override suspend fun supportsUrl(url: HttpUrl, credentialsStore: CredentialsStore): Boolean =
url.host.endsWith("symphony.com")
override fun hosts(credentialsStore: CredentialsStore): Set<String> {
// TODO make suspend function
return runBlocking { SymphonyUrlCompleter.podsToHosts(pods(credentialsStore)) }
}
}
| apache-2.0 | 1540b161eed1baec2e5211b4c8e629dd | 34.172414 | 108 | 0.746895 | 4.25 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/gui/components/buttons/SwitchButton.kt | 2 | 2046 | package com.cout970.magneticraft.systems.gui.components.buttons
import com.cout970.magneticraft.IVector2
import com.cout970.magneticraft.misc.guiTexture
import com.cout970.magneticraft.misc.vector.Vec2d
import com.cout970.magneticraft.misc.vector.contains
import com.cout970.magneticraft.misc.vector.vec2Of
import com.cout970.magneticraft.systems.gui.render.IComponent
import com.cout970.magneticraft.systems.gui.render.IGui
class SwitchButton(
override val pos: IVector2,
val enableIcon: IVector2,
val disableIcon: IVector2,
val tooltipEnable: String? = null,
val tooltipDisable: String? = null,
val id: String = "no-id",
var onClick: () -> Unit = {},
var isEnable: () -> Boolean = { false }
) : IComponent {
override lateinit var gui: IGui
override val size: IVector2 = vec2Of(18, 18)
val backgroundEnable = vec2Of(36, 100)
val backgroundDisable = vec2Of(55, 100)
val hoverUV = vec2Of(183, 10)
override fun drawFirstLayer(mouse: Vec2d, partialTicks: Float) {
val enable = isEnable()
gui.bindTexture(guiTexture("misc"))
gui.drawTexture(
gui.pos + pos,
size,
if (enable) backgroundEnable else backgroundDisable
)
gui.drawTexture(
gui.pos + pos + vec2Of(1, 1),
vec2Of(16, 16),
if (enable) enableIcon else disableIcon
)
}
override fun drawSecondLayer(mouse: Vec2d) {
if (mouse in (gui.pos + pos to size)) {
gui.bindTexture(guiTexture("misc"))
gui.drawTexture(
pos,
size,
hoverUV
)
val txt = if (isEnable()) tooltipEnable else tooltipDisable
if (txt != null) {
gui.drawHoveringText(listOf(txt), mouse)
}
}
}
override fun onMouseClick(mouse: Vec2d, mouseButton: Int): Boolean {
val inBounds = mouse in (gui.pos + pos to size)
if (inBounds) onClick()
return inBounds
}
} | gpl-2.0 | 58bf2cc43263cbdf26c581ce6cea75b7 | 30.015152 | 72 | 0.62219 | 4.027559 | false | false | false | false |
wireapp/wire-android | storage/src/main/kotlin/com/waz/zclient/storage/db/users/migration/UserDatabase127To128Migration.kt | 1 | 28840 | @file:Suppress("MagicNumber", "TooManyFunctions", "LargeClass")
package com.waz.zclient.storage.db.users.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.waz.zclient.storage.db.MigrationUtils.recreateAndTryMigrate
val USER_DATABASE_MIGRATION_127_TO_128 = object : Migration(127, 128) {
override fun migrate(database: SupportSQLiteDatabase) {
migrateUserTable(database)
migrateAssetsTable(database)
migrateConversationsTable(database)
migrateConversationMembersTable(database)
migrateMessagesTable(database)
migrateKeyValuesTable(database)
migrateSyncJobsTable(database)
migrateErrorsTable(database)
migrateNotificationData(database)
migrateContactHashesTable(database)
migrateContactsOnWire(database)
migrateClientsTable(database)
migrateLikingTable(database)
migrateContactsTable(database)
migrateEmailAddressTable(database)
migratePhoneNumbersTable(database)
migrateMessageDeletionTable(database)
migrateEditHistoryTable(database)
migratePushNotificationEvents(database)
migrateReadReceiptsTable(database)
migratePropertiesTable(database)
migrateUploadAssetTable(database)
migrateDownloadAssetTable(database)
migrateAssets2Table(database)
migrateFcmNotificationsTable(database)
migrateFcmNotificationStatsTable(database)
migrateFoldersTable(database)
migrateConversationFoldersTable(database)
migrateConversationRoleActionTable(database)
migrateMessageContentIndexTable(database)
createButtonsTable(database)
}
private fun migrateUserTable(database: SupportSQLiteDatabase) {
val tempTableName = "UsersTemp"
val originalTableName = "Users"
val primaryKey = "_id"
val searchKey = "skey"
val createTempTable = """
CREATE TABLE $tempTableName (
$primaryKey TEXT PRIMARY KEY NOT NULL,
teamId TEXT,
name TEXT NOT NULL DEFAULT '',
email TEXT,
phone TEXT,
tracking_id TEXT,
picture TEXT,
accent INTEGER NOT NULL DEFAULT 0,
$searchKey TEXT NOT NULL DEFAULT '',
connection TEXT NOT NULL DEFAULT '',
conn_timestamp INTEGER NOT NULL DEFAULT 0,
conn_msg TEXT,
conversation TEXT,
relation TEXT NOT NULL DEFAULT '',
timestamp INTEGER,
verified TEXT,
deleted INTEGER NOT NULL DEFAULT 0,
availability INTEGER NOT NULL DEFAULT 0,
handle TEXT,
provider_id TEXT,
integration_id TEXT,
expires_at INTEGER,
managed_by TEXT,
self_permissions INTEGER NOT NULL DEFAULT 0,
copy_permissions INTEGER NOT NULL DEFAULT 0,
created_by TEXT
)""".trimIndent()
val conversationIdIndex = "CREATE INDEX IF NOT EXISTS Conversation_id on $originalTableName ($primaryKey)"
val searchKeyIndex = "CREATE INDEX IF NOT EXISTS UserData_search_key on $originalTableName ($searchKey)"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
conversationIdIndex,
searchKeyIndex
)
}
private fun migrateAssetsTable(database: SupportSQLiteDatabase) {
val tempTableName = "AssetsTemp"
val originalTableName = "Assets"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
asset_type TEXT NOT NULL DEFAULT '',
data TEXT NOT NULL DEFAULT ''
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateConversationsTable(database: SupportSQLiteDatabase) {
val tempTableName = "ConversationsTemp"
val originalTableName = "Conversations"
val searchKey = "search_key"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
remote_id TEXT NOT NULL DEFAULT '',
name TEXT,
creator TEXT NOT NULL DEFAULT '',
conv_type INTEGER NOT NULL DEFAULT 0,
team TEXT,
is_managed INTEGER,
last_event_time INTEGER NOT NULL DEFAULT 0,
is_active INTEGER NOT NULL DEFAULT 0,
last_read INTEGER NOT NULL DEFAULT 0,
muted_status INTEGER NOT NULL DEFAULT 0,
mute_time INTEGER NOT NULL DEFAULT 0,
archived INTEGER NOT NULL DEFAULT 0,
archive_time INTEGER NOT NULL DEFAULT 0,
cleared INTEGER,
generated_name TEXT NOT NULL DEFAULT '',
$searchKey TEXT,
unread_count INTEGER NOT NULL DEFAULT 0,
unsent_count INTEGER NOT NULL DEFAULT 0,
hidden INTEGER NOT NULL DEFAULT 0,
missed_call TEXT,
incoming_knock TEXT,
verified TEXT,
ephemeral INTEGER,
global_ephemeral INTEGER,
unread_call_count INTEGER NOT NULL DEFAULT 0,
unread_ping_count INTEGER NOT NULL DEFAULT 0,
access TEXT,
access_role TEXT,
link TEXT,
unread_mentions_count INTEGER NOT NULL DEFAULT 0,
unread_quote_count INTEGER NOT NULL DEFAULT 0,
receipt_mode INTEGER
)""".trimIndent()
val conversationSearchKeyIndex = """
CREATE INDEX IF NOT EXISTS Conversation_search_key on $originalTableName ($searchKey)
""".trimIndent()
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
conversationSearchKeyIndex
)
}
private fun migrateConversationMembersTable(database: SupportSQLiteDatabase) {
val tempTableName = "ConversationMembersTemp"
val originalTableName = "ConversationMembers"
val convid = "conv_id"
val userId = "user_id"
val createTempTable = """
CREATE TABLE $tempTableName (
$userId TEXT NOT NULL DEFAULT '',
$convid TEXT NOT NULL DEFAULT '',
role TEXT NOT NULL DEFAULT '',
PRIMARY KEY ($userId, $convid));
)""".trimIndent()
val conversationIdIndex = "CREATE INDEX IF NOT EXISTS ConversationMembers_conv on $originalTableName ($convid)"
val userIdIndex = "CREATE INDEX IF NOT EXISTS ConversationMembers_userid on $originalTableName ($userId)"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
conversationIdIndex,
userIdIndex
)
}
private fun migrateMessagesTable(database: SupportSQLiteDatabase) {
val tempTableName = "MessagesTemp"
val originalTableName = "Messages"
val convId = "conv_id"
val time = "time"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
$convId TEXT NOT NULL DEFAULT '',
msg_type TEXT NOT NULL DEFAULT '',
user_id TEXT NOT NULL DEFAULT '',
content TEXT,
protos BLOB,
$time INTEGER NOT NULL DEFAULT 0,
local_time INTEGER NOT NULL DEFAULT 0,
first_msg INTEGER NOT NULL DEFAULT 0,
members TEXT,
recipient TEXT,
email TEXT,
name TEXT,
msg_state TEXT NOT NULL DEFAULT '',
content_size INTEGER NOT NULL DEFAULT 0,
edit_time INTEGER NOT NULL DEFAULT 0,
ephemeral INTEGER,
expiry_time INTEGER,
expired INTEGER NOT NULL DEFAULT 0,
duration INTEGER,
quote TEXT,
quote_validity INTEGER NOT NULL DEFAULT 0,
force_read_receipts INTEGER,
asset_id TEXT
)""".trimIndent()
val convAndTimeIndex = "CREATE INDEX IF NOT EXISTS Messages_conv_time on $originalTableName ($convId, $time)"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
convAndTimeIndex
)
}
private fun migrateKeyValuesTable(database: SupportSQLiteDatabase) {
val tempTableName = "KeyValuesTemp"
val originalTableName = "KeyValues"
val createTempTable = """
CREATE TABLE $tempTableName (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL DEFAULT ''
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateSyncJobsTable(database: SupportSQLiteDatabase) {
val tempTableName = "SyncJobsTemp"
val originalTableName = "SyncJobs"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
data TEXT NOT NULL DEFAULT ''
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateErrorsTable(database: SupportSQLiteDatabase) {
val tempTableName = "ErrorsTemp"
val originalTableName = "Errors"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
err_type TEXT NOT NULL DEFAULT '',
users TEXT NOT NULL DEFAULT '',
messages TEXT NOT NULL DEFAULT '',
conv_id TEXT,
res_code INTEGER NOT NULL DEFAULT 0,
res_msg TEXT NOT NULL DEFAULT '',
res_label TEXT NOT NULL DEFAULT '',
time INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateNotificationData(database: SupportSQLiteDatabase) {
val tempTableName = "NotificationDataTemp"
val originalTableName = "NotificationData"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
data TEXT NOT NULL DEFAULT ''
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateContactHashesTable(database: SupportSQLiteDatabase) {
val tempTableName = "ContactHashesTemp"
val originalTableName = "ContactHashes"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
hashes TEXT
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateContactsOnWire(database: SupportSQLiteDatabase) {
val tempTableName = "ContactsOnWireTemp"
val originalTableName = "ContactsOnWire"
val contact = "contact"
val createTempTable = """
CREATE TABLE $tempTableName (
user TEXT NOT NULL DEFAULT '',
$contact TEXT NOT NULL DEFAULT '',
PRIMARY KEY (user, contact)
)""".trimIndent()
val contactIndex = "CREATE INDEX IF NOT EXISTS ContactsOnWire_contact on $originalTableName ( $contact )"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
contactIndex
)
}
private fun migrateClientsTable(database: SupportSQLiteDatabase) {
val tempTableName = "ClientsTemp"
val originalTableName = "Clients"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
data TEXT NOT NULL DEFAULT ''
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateLikingTable(database: SupportSQLiteDatabase) {
val tempTableName = "LikingsTemp"
val originalTableName = "Likings"
val createTempTable = """
CREATE TABLE $tempTableName (
message_id TEXT NOT NULL DEFAULT '',
user_id TEXT NOT NULL DEFAULT '',
timestamp INTEGER NOT NULL DEFAULT 0,
action INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (message_id, user_id)
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateContactsTable(database: SupportSQLiteDatabase) {
val tempTableName = "ContactsTemp"
val originalTableName = "Contacts"
val sorting = "sort_key"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL DEFAULT '',
name_source INTEGER NOT NULL DEFAULT 0,
$sorting TEXT NOT NULL DEFAULT '',
search_key TEXT NOT NULL DEFAULT ''
)""".trimIndent()
val contactSortingIndex = "CREATE INDEX IF NOT EXISTS Contacts_sorting on $originalTableName ( $sorting )"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
contactSortingIndex
)
}
private fun migrateEmailAddressTable(database: SupportSQLiteDatabase) {
val tempTableName = "EmailAddressesTemp"
val originalTableName = "EmailAddresses"
val contact = "contact"
val emailAddress = "email_address"
val createTempTable = """
CREATE TABLE $tempTableName (
$contact TEXT NOT NULL DEFAULT '',
$emailAddress TEXT NOT NULL DEFAULT '',
PRIMARY KEY (contact, email_address)
)""".trimIndent()
val contactIndex = "CREATE INDEX IF NOT EXISTS EmailAddresses_contact on EmailAddresses ($contact)"
val emailIndex = "CREATE INDEX IF NOT EXISTS EmailAddresses_email on EmailAddresses ($emailAddress)"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
contactIndex,
emailIndex
)
}
private fun migratePhoneNumbersTable(database: SupportSQLiteDatabase) {
val tempTableName = "PhoneNumbersTemp"
val originalTableName = "PhoneNumbers"
val contact = "contact"
val phoneNumber = "phone_number"
val createTempTable = """
CREATE TABLE $tempTableName (
$contact TEXT NOT NULL DEFAULT '',
$phoneNumber TEXT NOT NULL DEFAULT '',
PRIMARY KEY (contact, phone_number)
)""".trimIndent()
val contactIndex = "CREATE INDEX IF NOT EXISTS PhoneNumbers_contact on $originalTableName ($contact)"
val phoneIndex = "CREATE INDEX IF NOT EXISTS PhoneNumbers_phone on $originalTableName ($phoneNumber)"
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
contactIndex,
phoneIndex
)
}
private fun migrateMessageDeletionTable(database: SupportSQLiteDatabase) {
val tempTableName = "MsgDeletionTemp"
val originalTableName = "MsgDeletion"
val createTempTable = """
CREATE TABLE $tempTableName (
message_id TEXT PRIMARY KEY NOT NULL,
timestamp INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateEditHistoryTable(database: SupportSQLiteDatabase) {
val tempTableName = "EditHistoryTemp"
val originalTableName = "EditHistory"
val createTempTable = """
CREATE TABLE $tempTableName (
original_id TEXT PRIMARY KEY NOT NULL,
updated_id TEXT NOT NULL DEFAULT '',
timestamp INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migratePushNotificationEvents(database: SupportSQLiteDatabase) {
val tempTableName = "PushNotificationEventsTemp"
val originalTableName = "PushNotificationEvents"
val createTempTable = """
CREATE TABLE $tempTableName (
pushId TEXT PRIMARY KEY NOT NULL,
event_index INTEGER NOT NULL DEFAULT 0,
decrypted INTEGER NOT NULL DEFAULT 0,
event TEXT NOT NULL DEFAULT '',
plain BLOB,
transient INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateReadReceiptsTable(database: SupportSQLiteDatabase) {
val tempTableName = "ReadReceiptsTemp"
val originalTableName = "ReadReceipts"
val createTempTable = """
CREATE TABLE $tempTableName (
message_id TEXT NOT NULL DEFAULT '',
user_id TEXT NOT NULL DEFAULT '',
timestamp INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (message_id, user_id)
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migratePropertiesTable(database: SupportSQLiteDatabase) {
val tempTableName = "PropertiesTemp"
val originalTableName = "Properties"
val createTempTable = """
CREATE TABLE $tempTableName (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL DEFAULT ''
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateUploadAssetTable(database: SupportSQLiteDatabase) {
val tempTableName = "UploadAssetsTemp"
val originalTableName = "UploadAssets"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
source TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL DEFAULT '',
sha BLOB,
md5 BLOB,
mime TEXT NOT NULL DEFAULT '',
preview TEXT NOT NULL DEFAULT '',
uploaded INTEGER NOT NULL DEFAULT 0,
size INTEGER NOT NULL DEFAULT 0,
retention INTEGER NOT NULL DEFAULT 0,
public INTEGER NOT NULL DEFAULT 0,
encryption TEXT NOT NULL DEFAULT '',
encryption_salt TEXT,
details TEXT NOT NULL DEFAULT '',
status INTEGER NOT NULL DEFAULT 0,
asset_id TEXT
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateDownloadAssetTable(database: SupportSQLiteDatabase) {
val tempTableName = "DownloadAssetsTemp"
val originalTableName = "DownloadAssets"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
mime TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL DEFAULT '',
preview TEXT NOT NULL DEFAULT '',
details TEXT NOT NULL DEFAULT '',
downloaded INTEGER NOT NULL DEFAULT 0,
size INTEGER NOT NULL DEFAULT 0,
status INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateAssets2Table(database: SupportSQLiteDatabase) {
val tempTableName = "Assets2Temp"
val originalTableName = "Assets2"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
token TEXT,
name TEXT NOT NULL DEFAULT '',
encryption TEXT NOT NULL DEFAULT '',
mime TEXT NOT NULL DEFAULT '',
sha BLOB,
size INTEGER NOT NULL DEFAULT 0,
source TEXT,
preview TEXT,
details TEXT NOT NULL DEFAULT '',
conversation_id TEXT
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateFcmNotificationsTable(database: SupportSQLiteDatabase) {
val tempTableName = "FCMNotificationsTemp"
val originalTableName = "FCMNotifications"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT NOT NULL DEFAULT '',
stage TEXT NOT NULL DEFAULT '',
stage_start_time INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (_id, stage)
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateFcmNotificationStatsTable(database: SupportSQLiteDatabase) {
val tempTableName = "FCMNotificationStatsTemp"
val originalTableName = "FCMNotificationStats"
val createTempTable = """
CREATE TABLE $tempTableName (
stage TEXT PRIMARY KEY NOT NULL,
bucket1 INTEGER NOT NULL DEFAULT 0,
bucket2 INTEGER NOT NULL DEFAULT 0,
bucket3 INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateFoldersTable(database: SupportSQLiteDatabase) {
val tempTableName = "FoldersTemp"
val originalTableName = "Folders"
val createTempTable = """
CREATE TABLE $tempTableName (
_id TEXT PRIMARY KEY NOT NULL,
name TEXT NOT NULL DEFAULT '',
type INTEGER NOT NULL DEFAULT 0
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateConversationFoldersTable(database: SupportSQLiteDatabase) {
val tempTableName = "ConversationFoldersTemp"
val originalTableName = "ConversationFolders"
val createTempTable = """
CREATE TABLE $tempTableName (
conv_id TEXT NOT NULL DEFAULT '',
folder_id TEXT NOT NULL DEFAULT '',
PRIMARY KEY (conv_id, folder_id)
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun migrateConversationRoleActionTable(database: SupportSQLiteDatabase) {
val tempTableName = "ConversationRoleActionTemp"
val originalTableName = "ConversationRoleAction"
val convId = "conv_id"
val createTempTable = """
CREATE TABLE $tempTableName (
label TEXT NOT NULL DEFAULT '',
action TEXT NOT NULL DEFAULT '',
$convId TEXT NOT NULL DEFAULT '',
PRIMARY KEY (label, action, $convId)
)""".trimIndent()
val conversationIdIndex = """
CREATE INDEX IF NOT EXISTS ConversationRoleAction_convid on $originalTableName ($convId)
""".trimIndent()
recreateAndTryMigrate(
database,
originalTableName,
tempTableName,
createTempTable,
conversationIdIndex
)
}
private fun migrateMessageContentIndexTable(database: SupportSQLiteDatabase) {
val tempTableName = "MessageContentIndexTemp"
val originalTableName = "MessageContentIndex"
val messageId = "message_id"
val convId = "conv_id"
val content = "content"
val time = "time"
val createTempTable = """
CREATE VIRTUAL TABLE $tempTableName using fts4(
$messageId TEXT NOT NULL DEFAULT '',
$convId TEXT NOT NULL DEFAULT '',
$content TEXT NOT NULL DEFAULT '',
$time INTEGER NOT NULL DEFAULT 0,
)""".trimIndent()
recreateAndTryMigrate(
database = database,
originalTableName = originalTableName,
tempTableName = tempTableName,
createTempTable = createTempTable
)
}
private fun createButtonsTable(database: SupportSQLiteDatabase) {
database.execSQL("DROP TABLE IF EXISTS Buttons")
database.execSQL("""
CREATE TABLE IF NOT EXISTS Buttons (
message_id TEXT NOT NULL DEFAULT '',
button_id TEXT NOT NULL DEFAULT '',
title TEXT NOT NULL DEFAULT '',
ordinal INTEGER NOT NULL DEFAULT 0,
state INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY(message_id, button_id)
)""".trimIndent()
)
}
}
| gpl-3.0 | 1963de0f886d19df70b10a0d88134993 | 36.847769 | 119 | 0.577774 | 5.812173 | false | false | false | false |
7hens/KDroid | core/src/main/java/cn/thens/kdroid/core/app/Extensions.kt | 1 | 1626 | @file:Suppress("unused")
package cn.thens.kdroid.core.app
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.ContextWrapper
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import java.io.File
fun Activity.hideSoftInput() {
if (currentFocus != null) {
inputMethodManager?.hideSoftInputFromWindow(currentFocus.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
fun Context.toast(text: CharSequence) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show()
}
fun Context.longToast(text: CharSequence) {
Toast.makeText(this, text, Toast.LENGTH_LONG).show()
}
val hasExternalStorage: Boolean get() = Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()
val Context.suitableCacheDir: File get () = if (hasExternalStorage) externalCacheDir else cacheDir
inline fun runOnUiThread(crossinline fn: () -> Unit) {
val mainLooper = Looper.getMainLooper()
if (mainLooper.thread == Thread.currentThread()) {
fn()
} else {
Handler(mainLooper).post { fn() }
}
}
fun extractActivity(context: Context): Activity? {
var ctx = context
while (true) {
when (ctx) {
is Activity -> return ctx
is Application -> return null
is ContextWrapper -> {
val baseContext = ctx.baseContext
if (baseContext == ctx) return null
ctx = baseContext
}
else -> return null
}
}
} | apache-2.0 | 02a0b8e9d4be9d292ae2fc7418a070d2 | 27.54386 | 113 | 0.683272 | 4.418478 | false | false | false | false |
ModerateFish/component | app/src/main/java/com/thornbirds/repodemo/TestFragment.kt | 1 | 3023 | package com.thornbirds.repodemo
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.thornbirds.framework.fragment.ComponentFragment
/**
* Created by yangli on 2017/9/7.
*/
class TestFragment : ComponentFragment() {
override val TAG: String = "TestFragment"
private var mId = 0
override fun onAttach(context: Context) {
super.onAttach(context)
if (arguments != null) {
mId = requireArguments().getInt(EXTRA_FRAGMENT_ID, hashCode())
} else {
Log.w(TAG, "onAttach arguments not found, fragment " + mId + ", hashCode=" + hashCode())
}
Log.d(TAG, "onAttach fragment " + mId + ", hashCode=" + hashCode())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (arguments != null) {
mId = requireArguments().getInt(EXTRA_FRAGMENT_ID, hashCode())
} else {
Log.w(TAG, "onCreate arguments not found, fragment " + mId + ", hashCode=" + hashCode())
}
Log.d(TAG, "onCreate fragment " + mId + ", hashCode=" + hashCode())
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
Log.d(TAG, "onCreateView fragment " + mId + ", hashCode=" + hashCode())
return inflater.inflate(R.layout.fragment_test, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d(TAG, "onViewCreated fragment " + mId + ", hashCode=" + hashCode())
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Log.d(TAG, "onActivityCreated fragment " + mId + ", hashCode=" + hashCode())
}
override fun onStart() {
super.onStart()
Log.d(TAG, "onStart fragment " + mId + ", hashCode=" + hashCode())
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume fragment " + mId + ", hashCode=" + hashCode())
}
override fun onPause() {
super.onPause()
Log.d(TAG, "onPause fragment " + mId + ", hashCode=" + hashCode())
}
override fun onStop() {
super.onStop()
Log.d(TAG, "onStop fragment " + mId + ", hashCode=" + hashCode())
}
override fun onDestroyView() {
super.onDestroyView()
Log.d(TAG, "onDestroyView fragment " + mId + ", hashCode=" + hashCode())
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy fragment " + mId + ", hashCode=" + hashCode())
}
override fun onDetach() {
super.onDetach()
Log.d(TAG, "onDetach fragment " + mId + ", hashCode=" + hashCode())
}
companion object {
const val EXTRA_FRAGMENT_ID = "extra_fragment_id"
}
} | apache-2.0 | de3a3c2faa5b1d67f759191e16ea9a40 | 30.5 | 100 | 0.610982 | 4.368497 | false | false | false | false |
josesamuel/remoter | sampleclient-remoter/src/main/java/util/remoter/remoterclient/TestMemoryLeakActivity.kt | 1 | 4133 | package util.remoter.remoterclient
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.PersistableBundle
import android.util.Log
import android.view.View
import android.widget.TextView
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import remoter.RemoterProxy
import remoter.builder.ServiceConnector
//import remoter.builder.ServiceConnector
import util.remoter.service.*
import java.lang.Exception
/**
* A sample client to validate there are no memory leaks while sending the stub across remote process.
*
* Perform register/unregister multiple times and run the profiler.
*
* Once GC is done on both client and server, the profiler should show only active listeners. Any unregistered
* listeners should have been collected
*/
class TestMemoryLeakActivity : Activity() {
lateinit var service: ISampleKotlinService
private val listener = object: ISampleKotlinServiceListener {
override suspend fun onEcho(echo: String?) {
Log.v(TAG, "Callback on onEcho $echo")
}
}
private val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.v(TAG, "Service connected 1")
sampleService = ISampleService_Proxy(service)
Log.v(TAG, "Service connected $sampleService")
}
override fun onServiceDisconnected(name: ComponentName) {}
}
private var sampleService: ISampleService? = null
private var sampleServiceListener: ISampleServiceListener? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
service = ISampleKotlinService_Proxy(ServiceConnector.of(this.applicationContext, "util.remoter.remoterclient.SampleKotlinService"))
setContentView(R.layout.layout)
findViewById<View>(R.id.register).setOnClickListener {
Log.v(TAG, "Register $sampleService")
if (sampleService != null) {
sampleServiceListener = SampleListener()
Log.v(TAG, "Registering " + sampleServiceListener.hashCode())
val result = sampleService!!.registerListener(sampleServiceListener)
Log.v(TAG, "Register result $result")
}
GlobalScope.launch {
Log.v(TAG, "Echo result $service ${service.testEcho(System.currentTimeMillis().toString(), null)}")
Log.v(TAG, " ${service.registerListener(listener)}")
}
}
findViewById<View>(R.id.unregister).setOnClickListener {
Log.v(TAG, "Un Register $sampleService")
if (sampleService != null) {
val result = sampleService!!.unRegisterListener(sampleServiceListener)
//clear the stub
(sampleService as RemoterProxy).destroyStub(sampleServiceListener)
Log.v(TAG, "UnRegister result $result")
}
GlobalScope.launch {
Log.v(TAG, " unregister result of suspend ${service.unRegisterListener(listener)}")
ServiceConnector.of(applicationContext, "util.remoter.remoterclient.SampleKotlinService").disconnect()
}
}
val remoterServiceIntent = Intent(ServiceIntents.INTENT_REMOTER_SERVICE)
remoterServiceIntent.setClassName("util.remoter.remoterservice", ServiceIntents.INTENT_REMOTER_SERVICE)
Log.v(TAG, "Connecting with service")
val result = bindService(remoterServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
//startService(remoterServiceIntent);
Log.v(TAG, "Connecting with service result $result")
}
internal class SampleListener : ISampleServiceListener {
override fun onEcho(echo: String) {
Log.v(TAG, "Listener call $echo")
}
}
companion object {
private const val TAG = "Test"
}
} | apache-2.0 | 6fcb4528acde0bad5addff9eba7b854f | 38 | 140 | 0.688362 | 4.822637 | false | false | false | false |
edvin/tornadofx-idea-plugin | src/main/kotlin/no/tornado/tornadofx/idea/annotator/CSSBoxAnnotator.kt | 1 | 5144 | package no.tornado.tornadofx.idea.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.lang.annotation.HighlightSeverity
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import no.tornado.tornadofx.idea.FXTools.isStylesheet
import no.tornado.tornadofx.idea.quickfixes.css.BoxQuickFix
import org.jetbrains.kotlin.idea.core.quickfix.QuickFixUtil
import org.jetbrains.kotlin.idea.references.KtInvokeFunctionReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.search.allScope
import org.jetbrains.kotlin.js.descriptorUtils.getJetTypeFqName
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtProperty
/**
* Creates an annotation for CssBox statements, if they can be simplified.
*
* Created by amish on 6/14/17.
*/
class CSSBoxAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element.isInStylesheetClass()) {
if (element is KtBinaryExpression) {
val left = element.left
if (left is KtNameReferenceExpression) {
val prop = left.mainReference.resolve()
if (prop is KtProperty) {
val returnType = QuickFixUtil.getDeclarationReturnType(prop)
if (returnType?.getJetTypeFqName(false) == "tornadofx.CssBox") {
doAnnotation(element, holder)
}
}
}
}
}
}
private fun doAnnotation(element: KtBinaryExpression, holder: AnnotationHolder) {
val right = element.right?.mainReference
if (right is KtInvokeFunctionReference) {
val args = right.expression.valueArguments
val values = mutableListOf<Pair<Double, String>?>()
args.forEach { values.add(it.text.convertOrNull()) }
if (values.isAllSimplifiable()) {
holder.newAnnotation(HighlightSeverity.WEAK_WARNING, "Can be simplified to box(${values[0]!!.first}${values[0]!!.second}).")
.range(element.right!!.textRange)
.withFix(BoxQuickFix(element, values[0]!!))
.create()
} else if (values.isVHSimplifiable()) {
holder.newAnnotation(HighlightSeverity.WEAK_WARNING, "Can be simplified to box(${values[0]!!.first}${values[0]!!.second}, ${values[1]!!.first}${values[1]!!.second}).")
.range(element.right!!.textRange)
.withFix(BoxQuickFix(element, values[0]!!, values[1]!!))
.create()
}
}
}
private fun String.convertOrNull(): Pair<Double, String>? {
with(this) {
if (endsWith(".px")) return substringBefore(".px").toDouble() to "px"
if (endsWith(".mm")) return substringBefore(".mm").toDouble() to "mm"
if (endsWith(".cm")) return substringBefore(".cm").toDouble() to "cm"
if (endsWith(".in")) return substringBefore(".in").toDouble() to "in"
if (endsWith(".pt")) return substringBefore(".pt").toDouble() to "pt"
if (endsWith(".pc")) return substringBefore(".pc").toDouble() to "pc"
if (endsWith(".em")) return substringBefore(".em").toDouble() to "em"
if (endsWith(".ex")) return substringBefore(".ex").toDouble() to "ex"
if (endsWith(".percent")) return substringBefore(".percent").toDouble() to "percent"
}
return null
}
private fun MutableList<Pair<Double, String>?>.isAllSimplifiable(): Boolean {
return this.size == 4 && this[0]?.first == this[1]?.first && this[0]?.first == this[2]?.first && this[0]?.first == this[3]?.first
&& this[0]?.second == this[1]?.second && this[0]?.second == this[2]?.second && this[0]?.second == this[3]?.second
|| size == 2 && this[0]?.first == this[1]?.first && this[0]?.second == this[1]?.second
}
private fun MutableList<Pair<Double, String>?>.isVHSimplifiable(): Boolean {
//top == bottom && right == left
return this.size == 4 && this[0]?.first == this[2]?.first && this[1]?.first == this[3]?.first
&& this[0]?.second == this[2]?.second && this[1]?.second == this[3]?.second
}
private fun PsiElement.isInStylesheetClass(): Boolean {
val psiClass = this.toKtClassOrNull().toPsiClassOrNull()
return psiClass != null && isStylesheet(psiClass)
}
private fun PsiElement.toKtClassOrNull(): KtClass? = PsiTreeUtil.getParentOfType(this, KtClass::class.java)
private fun KtClass?.toPsiClassOrNull(): PsiClass? = if (this != null) {
val psiFacade = JavaPsiFacade.getInstance(this.project)
psiFacade.findClass(this.fqName.toString(), this.project.allScope())
} else null
}
| apache-2.0 | de8a6da59cb4772320c89a6c0c423d8d | 46.192661 | 184 | 0.628499 | 4.42685 | false | false | false | false |
vase4kin/TeamCityApp | app/src/main/java/com/github/vase4kin/teamcityapp/app_navigation/BottomNavigationView.kt | 1 | 4598 | /*
* Copyright 2020 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.app_navigation
import android.os.Bundle
import android.os.Handler
import com.github.vase4kin.teamcityapp.R
import com.github.vase4kin.teamcityapp.home.view.HomeActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton
import teamcityapp.libraries.utils.getThemeColor
private const val DELAY = 40L
interface BottomNavigationView {
/**
* Init bottom navigation
*/
fun initViews(listener: ViewListener, savedInstanceState: Bundle?)
fun showFavoritesFab()
fun showFilterFab()
fun hideFab()
fun updateNotifications(tabPosition: Int, count: Int)
fun selectTab(tabPosition: Int)
interface ViewListener {
fun onTabSelected(navItem: AppNavigationItem, wasSelected: Boolean)
fun onFavoritesFabClicked()
fun onFilterTabsClicked(navItem: AppNavigationItem)
}
}
class BottomNavigationViewImpl(
private val interactor: AppNavigationInteractor,
private val activity: HomeActivity
) : BottomNavigationView {
private lateinit var fab: FloatingActionButton
private lateinit var navigation: com.google.android.material.bottomnavigation.BottomNavigationView
private lateinit var listener: BottomNavigationView.ViewListener
override fun initViews(
listener: BottomNavigationView.ViewListener,
savedInstanceState: Bundle?
) {
this.listener = listener
initViews()
initBottomNavView()
initFab()
interactor.initNavigation(savedInstanceState)
}
private fun initViews() {
navigation = activity.findViewById(R.id.navigation)
fab = activity.findViewById(R.id.home_floating_action_button)
}
private fun initFab() {
fab.setOnClickListener {
when (val currentItem = navigation.selectedItemId) {
R.id.favorites -> listener.onFavoritesFabClicked()
R.id.build_queue, R.id.running_builds, R.id.agents -> {
AppNavigationItem.values().find { it.id == currentItem }?.let {
listener.onFilterTabsClicked(it)
}
}
}
}
}
private fun initBottomNavView() {
navigation.setOnNavigationItemSelectedListener { item ->
AppNavigationItem.values().find { it.id == item.itemId }?.let {
selectTabInternal(it, item.isChecked)
}
true
}
}
private fun selectTabInternal(navItem: AppNavigationItem, isSelected: Boolean) {
Handler(activity.mainLooper).postDelayed(
{
interactor.switchTab(navItem.ordinal)
listener.onTabSelected(navItem, isSelected)
},
DELAY
)
}
override fun showFavoritesFab() = fab.run {
setImageResource(R.drawable.ic_add_black_24dp)
show()
}
override fun showFilterFab() = fab.run {
setImageResource(R.drawable.ic_filter_list_white_24px)
show()
}
override fun hideFab() = fab.hide()
override fun updateNotifications(tabPosition: Int, count: Int) {
getAppNavItemByPosition(tabPosition)?.let {
val menuItemId = it.id
val badgeDrawable = navigation.getOrCreateBadge(menuItemId)
badgeDrawable.backgroundColor = activity.getThemeColor(R.attr.colorSecondary)
badgeDrawable.badgeTextColor = activity.getThemeColor(R.attr.colorOnPrimarySurface)
badgeDrawable.isVisible = true
badgeDrawable.number = count
badgeDrawable.verticalOffset = activity.resources.getDimensionPixelOffset(R.dimen.dp_4)
}
}
override fun selectTab(tabPosition: Int) {
getAppNavItemByPosition(tabPosition)?.let {
navigation.selectedItemId = it.id
}
}
private fun getAppNavItemByPosition(position: Int): AppNavigationItem? =
AppNavigationItem.values().getOrNull(position)
}
| apache-2.0 | b58cfc04f6b6668a97a8be0afe16030f | 32.562044 | 102 | 0.675076 | 4.779626 | false | false | false | false |
y2k/ProjectCaerus | app/src/main/kotlin/android/content/res/ThemeAttributeResolver.kt | 1 | 6007 | package android.content.res
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.TypedValue
import android.widget.LinearLayout
import com.projectcaerus.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.parser.Parser
import java.io.File
import java.util.*
/**
* Created by y2k on 6/5/16.
*/
open class ThemeAttributeResolver(
private val resDirectory: File,
private val resources: Resources) {
private val public = Jsoup.parse(File("../res/values/public.xml").readText(), "", Parser.xmlParser())
private val styles = Jsoup.parse(File("../res/values/styles.xml").readText(), "", Parser.xmlParser())
private val stringPool = HashMap<Int, String>()
private val drawableParser = DrawableParser(public)
private val dimensionParser = DimensionParser(styles, public, resDirectory)
private val textParser = TextParser(public, stringPool)
fun getPooledString(id: Int): CharSequence? {
return stringPool[id]
}
fun getAnimation(id: Int): XmlResourceParser {
return getXmlResourceById(id, "anim")
}
fun getLayout(id: Int): XmlResourceParser {
return getXmlResourceById(id, "layout")
}
private fun getXmlResourceById(id: Int, type: String): ResourceParser {
val pathToResource = getPathToResource(id, type)
val parser = ResourceParser(this)
parser.setInput(pathToResource.bufferedReader())
return parser
}
protected open fun getPathToResource(id: Int, type: String): File {
val resName = public.select("public[type=$type][id=${id.toHex()}]").first().attr("name")
return File(File("../res/$type"), "$resName.xml")
}
fun loadDrawable(value: TypedValue, id: Int): Drawable {
if (value.type in TypedValue.TYPE_FIRST_COLOR_INT..TypedValue.TYPE_LAST_COLOR_INT) {
return ColorDrawable(value.data)
}
val bgName = public.select("public[type=drawable][id=${id.toHex()}]").first().attr("name")
println("bgName = $bgName")
val pathToResource = getPathToResource(bgName)
return when {
pathToResource.extension == "xml" -> {
pathToResource.bufferedReader().use {
val parser = ResourceParser(this)
parser.setInput(it)
createStateListDrawable(resources, parser)
}
}
pathToResource.name.endsWith(".9.png") -> {
return NinePatchDrawable(pathToResource)
}
else -> throw UnsupportedOperationException("Path = $pathToResource")
}
}
private fun getPathToResource(resName: String): File {
return File("../res")
.listFiles { s -> s.isDirectory }
.flatMap { it.listFiles().toList() }
.first { it.nameWithoutExtension.replace(".9", "") == resName }
}
fun obtainStyledAttributes(set: AttributeSet?, attrs: IntArray, defStyleAttr: Int, defStyleRes: Int): TypedArray {
val data = IntArray(attrs.size * 6)
val style = getStyle(defStyleAttr)
val indexes = ArrayList<Int>()
dimensionParser.parse2(attrs, indexes, set, data, "layout_margin")
dimensionParser.parse2(attrs, indexes, set, data, "layout_width")
dimensionParser.parse2(attrs, indexes, set, data, "layout_height")
dimensionParser.parse2(attrs, indexes, set, data, "padding")
dimensionParser.parse2(attrs, indexes, set, data, "paddingLeft")
dimensionParser.parse2(attrs, indexes, set, data, "paddingRight")
dimensionParser.parse2(attrs, indexes, set, data, "paddingTop")
dimensionParser.parse2(attrs, indexes, set, data, "paddingBottom")
textParser.parse(attrs, data, indexes, set, "text")
textParser.parse(attrs, data, indexes, set, "hint")
drawableParser.parser(attrs, data, indexes, style, set)
getAttrIndex(attrs, "orientation")?.let {
val textOrientation = set?.getAttributeValue(null, "android:orientation") ?: return@let
val orientation = when (textOrientation) {
"horizontal" -> LinearLayout.HORIZONTAL
"vertical" -> LinearLayout.VERTICAL
else -> throw IllegalStateException("Orientation: $textOrientation")
}
data[6 * it] = TypedValue.TYPE_FIRST_INT
data[6 * it + 1] = orientation
indexes.add(it)
}
indexes.add(0, indexes.size)
return TypedArray(resources, data, indexes.toIntArray(), attrs.size);
}
private fun getStyle(defStyleAttr: Int): Element {
if (defStyleAttr == 0) return Document("")
val styleAttrName = public.select("public[id=${defStyleAttr.toHex()}]").first()
if (styleAttrName.attr("type") != "attr") throw IllegalStateException()
val styleName = getThemeAttribute(styleAttrName.attr("name"))
return styles.select("style[name=${styleName.split('/')[1]}]").first()
}
private fun getThemeAttribute(attributeName: String): String {
return styles.select("style[name=Theme] > item[name=$attributeName]").first().text()
}
fun getAttributeIndex(name: String): Int {
return getResource("attr", name)
}
fun getDrawableIndex(name: String): Int {
return getResource("drawable", name)
}
private fun getAttrIndex(attrs: IntArray, name: String): Int? {
val index = getResource("attr", name)
return attrs.indexOf(index).let { if (it >= 0) it else null }
}
private fun getResource(type: String, name: String): Int {
return public.select("public[type='$type'][name=$name]").first().attrId()
}
}
fun Element.attrId(): Int {
return attr("id").let { Integer.parseInt(it.substring(2), 16) }
}
fun Int.toHex(): String {
return String.format("0x%08X", this)
}
| gpl-3.0 | ae827943fc2b8b8044ba4f517b04a473 | 36.310559 | 118 | 0.642917 | 4.266335 | false | false | false | false |
google/ksp | test-utils/src/main/kotlin/com/google/devtools/ksp/processor/ConstructorDeclarationsProcessor.kt | 1 | 3680 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.processor
import com.google.devtools.ksp.getClassDeclarationByName
import com.google.devtools.ksp.getConstructors
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
class ConstructorDeclarationsProcessor : AbstractTestProcessor() {
val visitor = ConstructorsVisitor()
override fun toResult(): List<String> {
return visitor.toResult()
}
override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getAllFiles().forEach { it.accept(visitor, Unit) }
val classNames = visitor.classNames().toList() // copy
// each class has a cousin in the lib package, visit them as well, make sure
// we report the same structure when they are compiled code as well
classNames.forEach {
resolver
.getClassDeclarationByName("lib.${it.simpleName.asString()}")
?.accept(visitor, Unit)
}
return emptyList()
}
class ConstructorsVisitor : KSVisitorVoid() {
private val declarationsByClass = LinkedHashMap<KSClassDeclaration, MutableList<String>>()
fun classNames() = declarationsByClass.keys
fun toResult(): List<String> {
return declarationsByClass.entries
.sortedBy {
// sort by simple name to get cousin classes next to each-other
// since we traverse the lib after main, lib will be the second one
// because sortedBy is stable sort
it.key.simpleName.asString()
}.flatMap {
listOf("class: " + it.key.qualifiedName!!.asString()) + it.value
}
}
fun KSFunctionDeclaration.toSignature(): String {
return this.simpleName.asString() +
"(${this.parameters.map {
buildString {
append(it.type.resolve().declaration.qualifiedName?.asString())
if (it.hasDefault) {
append("(hasDefault)")
}
}
}.joinToString(",")})" +
": ${this.returnType?.resolve()?.declaration?.qualifiedName?.asString()
?: "<no-return>"}"
}
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
val declarations = mutableListOf<String>()
declarations.addAll(
classDeclaration.getConstructors().map {
it.toSignature()
}.sorted()
)
// TODO add some assertions that if we go through he path of getDeclarations
// we still find the same constructors
declarationsByClass[classDeclaration] = declarations
}
override fun visitFile(file: KSFile, data: Unit) {
file.declarations.forEach { it.accept(this, Unit) }
}
}
}
| apache-2.0 | 8ca495781717e9666bb35b6b73f5e0a9 | 40.348315 | 98 | 0.6125 | 5.219858 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/psi/element/MdTableImpl.kt | 1 | 2853 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.vladsch.md.nav.psi.util.MdPsiBundle
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTypes
import icons.MdIcons
import javax.swing.Icon
open class MdTableImpl(node: ASTNode) : MdCompositeImpl(node), MdTable, MdStructureViewPresentableElement, MdStructureViewPresentableItem, MdBreadcrumbElement {
override fun getIcon(flags: Int): Icon? {
return MdIcons.Element.TABLE
}
override fun getStructureViewPresentation(): ItemPresentation {
return MdElementItemPresentation(this)
}
override fun getLocationString(): String? {
val captionElement = captionElement
if (captionElement != null) {
val captionText = MdPsiImplUtil.getNodeText(captionElement, true, false)
if (captionText.isNotEmpty()) return captionText
}
val header = MdPsiImplUtil.findChildByType(this, MdTypes.TABLE_HEADER)
if (header != null) {
val headerText = header.firstChild
if (headerText != null && headerText.text.isNotEmpty()) return getTableRowText(headerText).replace("\\s+".toRegex(), " ")
}
val body = MdPsiImplUtil.findChildByType(this, MdTypes.TABLE_HEADER)
if (body != null) {
val bodyText = body.firstChild
if (bodyText != null && bodyText.text.isNotEmpty()) return getTableRowText(bodyText).replace("\\s+".toRegex(), " ")
}
return null
}
private fun getTableRowText(tableRow: PsiElement): String {
val sb = StringBuilder()
sb.append("| ")
for (cell in tableRow.children) {
sb.append(MdPsiImplUtil.getNodeText(cell, true, false))
sb.append(cell.node.treeNext.text)
}
return sb.toString()
}
val captionElement: PsiElement?
get() {
return MdPsiImplUtil.findChildByType(this, MdTypes.TABLE_CAPTION)
}
val captionText: String?
get() {
val captionElement = captionElement ?: return null
val captionText = captionElement.text.removeSurrounding("[", "]")
return captionText
}
override fun getPresentableText(): String? {
return MdPsiBundle.message("table")
}
override fun getBreadcrumbInfo(): String {
return MdPsiBundle.message("table")
}
override fun getBreadcrumbTooltip(): String? {
return node.text
}
override fun getBreadcrumbTextElement(): PsiElement? {
return null
}
}
| apache-2.0 | 8acbb59a13d715810c985473b6af5591 | 35.113924 | 177 | 0.666667 | 4.677049 | false | false | false | false |
roylanceMichael/yaorm | yaorm/src/main/java/org/roylance/yaorm/services/jdbc/JDBCGranularDatabaseService.kt | 1 | 9731 | package org.roylance.yaorm.services.jdbc
import org.roylance.yaorm.YaormModel
import org.roylance.yaorm.models.TypeModel
import org.roylance.yaorm.models.entity.EntityResultModel
import org.roylance.yaorm.services.IConnectionSourceFactory
import org.roylance.yaorm.services.ICursor
import org.roylance.yaorm.services.IGranularDatabaseService
import org.roylance.yaorm.services.IStreamer
import java.sql.ResultSet
import java.util.*
class JDBCGranularDatabaseService(override val connectionSourceFactory: IConnectionSourceFactory,
private val shouldManuallyCommitAfterUpdate: Boolean,
private val keepLogOfSQLExecutions: Boolean = false): IGranularDatabaseService {
private val report = YaormModel.DatabaseExecutionReport.newBuilder().setCallsToDatabase(0)
override fun getReport(): YaormModel.DatabaseExecutionReport {
return this.report.build()
}
override fun buildTableDefinitionFromQuery(query: String, rowCount: Int): YaormModel.TableDefinition {
val statement = this.connectionSourceFactory.generateReadStatement()
val resultSet = statement.executeQuery(query)
var successful = true
try {
val types = HashMap<String, TypeModel>()
var rowNumber = 0
while (resultSet.next() && rowNumber < rowCount) {
if (types.size == 0) {
// this starts at index 1 for some reason... tests for sqlite, mysql, and postgres
var i = 1
while (i <= resultSet.metaData.columnCount) {
val columnName = resultSet.metaData.getColumnLabel(i)
types[columnName] = TypeModel(columnName, i)
i++
}
}
types.keys.forEach {
val item = resultSet.getString(it)
if (item == null) {
types[it]!!.addTest(EmptyString)
}
else {
types[it]!!.addTest(item)
}
}
rowNumber += 1
}
val returnTable = YaormModel.TableDefinition.newBuilder()
types.keys.forEach {
returnTable.addColumnDefinitions(types[it]!!.buildColumnDefinition())
}
return returnTable.build()
}
catch(e: Exception) {
successful = false
e.printStackTrace()
throw e
}
finally {
resultSet.close()
this.report.callsToDatabase = this.report.callsToDatabase + 1
if (keepLogOfSQLExecutions) {
val newExecution = YaormModel.DatabaseExecution.newBuilder()
.setRawSql(query)
.setTimeCalled(Date().time)
.setOrderCalled(report.callsToDatabase)
.setResult(successful)
report.addExecutions(newExecution)
}
}
}
override fun isAvailable(): Boolean {
try {
return this.connectionSourceFactory.writeConnection.isValid(TenSeconds)
}
catch(e: UnsupportedOperationException) {
e.printStackTrace()
return true
}
catch(e: Exception) {
e.printStackTrace()
// todo: log better
return false
}
}
override fun executeUpdateQuery(query: String): EntityResultModel {
if (query.isBlank()) {
return EntityResultModel()
}
val statement = this.connectionSourceFactory.generateUpdateStatement()
val returnObject = EntityResultModel()
try {
val result = statement.executeUpdate(query)
val returnedKeys = ArrayList<String>()
returnObject.generatedKeys = returnedKeys
returnObject.successful = result > 0
return returnObject
}
catch(e: Exception) {
returnObject.successful = false
throw e
}
finally {
if (this.shouldManuallyCommitAfterUpdate) {
this.connectionSourceFactory.writeConnection.commit()
}
this.report.callsToDatabase = this.report.callsToDatabase + 1
if (keepLogOfSQLExecutions) {
val newExecution = YaormModel.DatabaseExecution.newBuilder()
.setRawSql(query)
.setTimeCalled(Date().time)
.setOrderCalled(report.callsToDatabase)
.setResult(returnObject.successful)
report.addExecutions(newExecution)
}
}
}
override fun executeSelectQuery(definition: YaormModel.TableDefinition, query: String): ICursor {
val statement = this.connectionSourceFactory.generateReadStatement()
var successful = true
try {
val resultSet = statement.executeQuery(query)
return JDBCCursor(definition, resultSet)
}
catch(e:Exception) {
successful = false
throw e
}
finally {
// normally close, but wait for service to do it
this.report.callsToDatabase = this.report.callsToDatabase + 1
if (keepLogOfSQLExecutions) {
val newExecution = YaormModel.DatabaseExecution.newBuilder()
.setRawSql(query)
.setTimeCalled(Date().time)
.setOrderCalled(report.callsToDatabase)
.setResult(successful)
report.addExecutions(newExecution)
}
}
}
override fun executeSelectQueryStream(definition: YaormModel.TableDefinition, query: String, streamer: IStreamer) {
val statement = this.connectionSourceFactory.generateReadStatement()
var successful = true
try {
val resultSet = statement.executeQuery(query)
JDBCCursor(definition, resultSet).getRecordsStream(streamer)
}
catch (e: Exception) {
successful = false
throw e
}
finally {
// normally close, but wait for service to do it
this.report.callsToDatabase = this.report.callsToDatabase + 1
if (keepLogOfSQLExecutions) {
val newExecution = YaormModel.DatabaseExecution.newBuilder()
.setRawSql(query)
.setTimeCalled(Date().time)
.setOrderCalled(report.callsToDatabase)
.setResult(successful)
report.addExecutions(newExecution)
}
}
}
override fun executeSelectQuery(query: String): YaormModel.Records {
val returnRecord = YaormModel.Records.newBuilder()
val streamer = object: IStreamer {
override fun stream(record: YaormModel.Record) {
returnRecord.addRecords(record)
}
}
executeSelectQueryStream(query, streamer)
return returnRecord.build()
}
override fun executeSelectQueryStream(query: String, stream: IStreamer) {
val statement = connectionSourceFactory.generateReadStatement()
var successful = true
try {
val resultSet = statement.executeQuery(query)
buildRecords(resultSet, stream)
}
catch (e: Exception) {
successful = false
throw e
}
finally {
report.callsToDatabase = report.callsToDatabase + 1
if (keepLogOfSQLExecutions) {
val newExecution = YaormModel.DatabaseExecution.newBuilder()
.setRawSql(query)
.setTimeCalled(Date().time)
.setOrderCalled(report.callsToDatabase)
.setResult(successful)
report.addExecutions(newExecution)
}
}
}
override fun commit() {
this.connectionSourceFactory.writeConnection.commit()
}
override fun close() {
this.connectionSourceFactory.close()
}
private fun buildRecords(resultSet: ResultSet, protoStreamer: IStreamer) {
val foundColumns = HashMap<String, YaormModel.ColumnDefinition>()
while (resultSet.next()) {
val newRecord = YaormModel.Record.newBuilder()
if (foundColumns.size == 0) {
// this starts at index 1 for some reason... tests for sqlite, mysql, and postgres
var i = 1
while (i <= resultSet.metaData.columnCount) {
val columnName = resultSet.metaData.getColumnLabel(i)
foundColumns[columnName] = YaormModel.ColumnDefinition.newBuilder()
.setName(columnName)
.setType(YaormModel.ProtobufType.STRING)
.build()
i++
}
}
foundColumns.keys.forEach {
val item = resultSet.getString(it)
if (item != null) {
val newColumn = YaormModel.Column.newBuilder()
.setDefinition(foundColumns[it]!!)
.setStringHolder(item)
newRecord.addColumns(newColumn)
}
}
protoStreamer.stream(newRecord.build())
}
}
companion object {
const private val TenSeconds = 10
const private val EmptyString = ""
}
}
| mit | 5262ab591b8f9b1b13b62560ffbbc7bf | 35.445693 | 119 | 0.561916 | 5.541572 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/data/storage/PostgresQueries.kt | 1 | 11840 | /*
* Copyright (C) 2018. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.data.storage
import com.openlattice.analysis.requests.Filter
import com.openlattice.postgres.DataTables.*
import com.openlattice.postgres.PostgresColumn.*
import com.openlattice.postgres.PostgresTable
import com.openlattice.postgres.ResultSetAdapters
import org.slf4j.LoggerFactory
import java.util.*
const val FETCH_SIZE = 100000
/**
* Handles reading data from linked entity sets.
*/
private val logger = LoggerFactory.getLogger(PostgresQueries::class.java)
const val ENTITIES_TABLE_ALIAS = "entity_key_ids"
const val LEFT_JOIN = "LEFT JOIN"
const val INNER_JOIN = "INNER JOIN"
const val FILTERED_ENTITY_KEY_IDS = "filtered_entity_key_ids"
val entityKeyIdColumns = listOf(ENTITY_SET_ID.name, ID_VALUE.name).joinToString(",")
private val ALLOWED_LINKING_METADATA_OPTIONS = EnumSet.of(
MetadataOption.LAST_WRITE,
MetadataOption.ENTITY_KEY_IDS,
MetadataOption.ENTITY_SET_IDS
)
private val ALLOWED_NON_LINKING_METADATA_OPTIONS = EnumSet.allOf(MetadataOption::class.java).minus(
listOf(
MetadataOption.ENTITY_SET_IDS
)
)
@Deprecated("old class")
internal class PostgresQueries
/**
*
*/
@Deprecated("old query")
fun selectEntitySetWithCurrentVersionOfPropertyTypes(
entityKeyIds: Map<UUID, Optional<Set<UUID>>>,
propertyTypes: Map<UUID, String>,
returnedPropertyTypes: Collection<UUID>,
authorizedPropertyTypes: Map<UUID, Set<UUID>>,
propertyTypeFilters: Map<UUID, Set<Filter>>,
metadataOptions: Set<MetadataOption>,
binaryPropertyTypes: Map<UUID, Boolean>,
linking: Boolean,
omitEntitySetId: Boolean,
metadataFilters: String = ""
): String {
val entitiesClause = buildEntitiesClause(entityKeyIds, linking)
val withClause = buildWithClauseOld(linking, entitiesClause)
val joinColumns = getJoinColumns(linking, omitEntitySetId)
val entitiesSubquerySql = selectEntityKeyIdsWithCurrentVersionSubquerySql(
entitiesClause,
metadataOptions,
linking,
omitEntitySetId,
joinColumns
)
val dataColumns = joinColumns
.union(getMetadataOptions(metadataOptions, linking))
.union(returnedPropertyTypes.map { propertyTypes.getValue(it) })
.joinToString(",")
// for performance, we place inner joins of filtered property tables at the end
val orderedPropertyTypesByJoin = propertyTypes.toList()
.sortedBy { propertyTypeFilters.containsKey(it.first) }.toMap()
val propertyTableJoins =
orderedPropertyTypesByJoin
//Exclude any property from the join where no property is authorized.
.filter { pt -> authorizedPropertyTypes.any { it.value.contains(pt.key) } }
.map {
val joinType = if (propertyTypeFilters.containsKey(it.key)) INNER_JOIN else LEFT_JOIN
val propertyTypeEntitiesClause = buildPropertyTypeEntitiesClause(
entityKeyIds,
it.key,
authorizedPropertyTypes
)
val subQuerySql = selectCurrentVersionOfPropertyTypeSql(
propertyTypeEntitiesClause,
it.key,
propertyTypeFilters[it.key] ?: setOf(),
it.value,
joinColumns,
metadataFilters
)
"$joinType $subQuerySql USING (${joinColumns.joinToString(",")})"
}
.joinToString("\n")
val fullQuery = "$withClause SELECT $dataColumns FROM $entitiesSubquerySql $propertyTableJoins"
return fullQuery
}
@Deprecated("old query")
private fun buildWithClauseOld(linking: Boolean, entitiesClause: String): String {
val joinColumns = if (linking) {
listOf(ENTITY_SET_ID.name, ID_VALUE.name, LINKING_ID.name)
} else {
listOf(ENTITY_SET_ID.name, ID_VALUE.name)
}
val selectColumns = joinColumns.joinToString(",") { "${PostgresTable.IDS.name}.$it AS $it" }
val queriesSql = "SELECT $selectColumns FROM ${PostgresTable.IDS.name} WHERE ${VERSION.name} > 0 $entitiesClause"
return "WITH $FILTERED_ENTITY_KEY_IDS AS ( $queriesSql ) "
}
@Deprecated("old query")
internal fun selectCurrentVersionOfPropertyTypeSql(
entitiesClause: String,
propertyTypeId: UUID,
filters: Set<Filter>,
fqn: String,
joinColumns: List<String>,
metadataFilters: String = ""
): String {
val propertyTable = quote(propertyTableName(propertyTypeId))
val groupByColumns = joinColumns.joinToString(",")
val arrayAgg = " array_agg($fqn) as $fqn "
val filtersClause = buildFilterClause(fqn, filters)
return "(SELECT $groupByColumns, $arrayAgg " +
"FROM $propertyTable INNER JOIN $FILTERED_ENTITY_KEY_IDS USING (${ENTITY_SET_ID.name},${ID_VALUE.name}) " +
"WHERE ${VERSION.name} > 0 $entitiesClause $filtersClause $metadataFilters" +
"GROUP BY ($groupByColumns)) as $propertyTable "
}
/**
* This routine generates SQL that selects all entity key ids that are not tombstoned for the given entities clause. If
* metadata is requested on a linked read, behavior is undefined as it will end up
*
* @param entitiesClause The clause that controls which entities will be evaluated by this query.
* @param metadataOptions The metadata to return for the entity.
*
* @return A named SQL subquery fragment consisting of all entity key satisfying the provided clauses from the
* ids table.
*/
@Deprecated("old query")
internal fun selectEntityKeyIdsWithCurrentVersionSubquerySql(
entitiesClause: String,
metadataOptions: Set<MetadataOption>,
linking: Boolean,
omitEntitySetId: Boolean,
joinColumns: List<String>
): String {
val metadataColumns = getMetadataOptions(metadataOptions.minus(MetadataOption.ENTITY_KEY_IDS), linking)
.joinToString(",")
val joinColumnsSql = joinColumns.joinToString(",")
val selectColumns = joinColumnsSql +
// used in materialized entitysets for both linking and non-linking entity sets to join on edges
if (metadataOptions.contains(MetadataOption.ENTITY_KEY_IDS)) {
", array_agg(${PostgresTable.IDS.name}.${ID.name}) AS " +
ResultSetAdapters.mapMetadataOptionToPostgresColumn(MetadataOption.ENTITY_KEY_IDS)
} else {
""
} +
if (metadataColumns.isNotEmpty()) {
if (linking) {
if (metadataOptions.contains(MetadataOption.LAST_WRITE)) {
", max(${LAST_WRITE.name}) AS " +
ResultSetAdapters.mapMetadataOptionToPostgresColumn(MetadataOption.LAST_WRITE)
} else {
""
} + if (metadataOptions.contains(MetadataOption.ENTITY_SET_IDS)) {
", array_agg(${PostgresTable.IDS.name}.${ENTITY_SET_ID.name}) AS " +
ResultSetAdapters.mapMetadataOptionToPostgresColumn(MetadataOption.ENTITY_SET_IDS)
} else {
""
}
} else {
", $metadataColumns"
}
} else {
""
}
val groupBy = if (linking) {
if (omitEntitySetId) {
"GROUP BY ${LINKING_ID.name}"
} else {
"GROUP BY (${ENTITY_SET_ID.name},${LINKING_ID.name})"
}
} else {
if (metadataOptions.contains(MetadataOption.ENTITY_KEY_IDS)) {
"GROUP BY (${ENTITY_SET_ID.name}, ${ID.name})"
} else {
""
}
}
return "( SELECT $selectColumns FROM ${PostgresTable.IDS.name} INNER JOIN $FILTERED_ENTITY_KEY_IDS USING($joinColumnsSql) WHERE true $entitiesClause $groupBy ) as $ENTITIES_TABLE_ALIAS"
}
@Deprecated("old query")
internal fun buildEntitiesClause(entityKeyIds: Map<UUID, Optional<Set<UUID>>>, linking: Boolean): String {
if (entityKeyIds.isEmpty()) return ""
val filterLinkingIds = if (linking) " AND ${LINKING_ID.name} IS NOT NULL " else ""
val idsColumn = if (linking) LINKING_ID.name else ID_VALUE.name
return "$filterLinkingIds AND (" + entityKeyIds.entries.joinToString(" OR ") {
val idsClause = it.value
.filter { ids -> ids.isNotEmpty() }
.map { ids -> " $idsColumn IN (" + ids.joinToString(",") { id -> "'$id'" } + ") AND" }
.orElse("")
" ($idsClause ${PostgresTable.IDS.name}.${ENTITY_SET_ID.name} = '${it.key}' )"
} + ")"
}
@Deprecated("old query")
internal fun buildPropertyTypeEntitiesClause(
entityKeyIds: Map<UUID, Optional<Set<UUID>>>,
propertyTypeId: UUID,
authorizedPropertyTypes: Map<UUID, Set<UUID>>
): String {
/*
* Filter out any entity sets for which you aren't authorized to read this property.
* There should always be at least one entity set as this isn't invoked for any properties
* with not readable entity sets.
*/
val authorizedEntitySetIds = entityKeyIds.asSequence().filter {
authorizedPropertyTypes[it.key]?.contains(propertyTypeId) ?: false
}.joinToString(",") { "'${it.key}'" }
return if (authorizedEntitySetIds.isNotEmpty()) "AND ${ENTITY_SET_ID.name} IN ($authorizedEntitySetIds)" else ""
}
@Deprecated("old query")
internal fun buildFilterClause(fqn: String, filter: Set<Filter>): String {
if (filter.isEmpty()) return ""
return filter.joinToString(" AND ", prefix = " AND ") { it.asSql(fqn) }
}
@Deprecated("old query")
private fun getJoinColumns(linking: Boolean, omitEntitySetId: Boolean): List<String> {
return if (linking) {
if (omitEntitySetId) {
listOf(LINKING_ID.name)
} else {
listOf(ENTITY_SET_ID.name, LINKING_ID.name)
}
} else {
listOf(ENTITY_SET_ID.name, ID_VALUE.name)
}
}
@Deprecated("old query")
private fun getMetadataOptions(metadataOptions: Set<MetadataOption>, linking: Boolean): List<String> {
val allowedMetadataOptions = if (linking)
metadataOptions.intersect(ALLOWED_LINKING_METADATA_OPTIONS)
else
metadataOptions.intersect(ALLOWED_NON_LINKING_METADATA_OPTIONS)
//TODO: Make this an error and fix cases by providing static method for getting all allowed metadata options
//as opposed to just EnumSet.allOf(...)
val invalidMetadataOptions = metadataOptions - allowedMetadataOptions
if (invalidMetadataOptions.isNotEmpty()) {
logger.warn("Invalid metadata options requested: {}", invalidMetadataOptions)
}
return allowedMetadataOptions.map { ResultSetAdapters.mapMetadataOptionToPostgresColumn(it) }
} | gpl-3.0 | d1526826ff85e4e658c2946bba96698e | 39.138983 | 189 | 0.640541 | 4.50019 | false | false | false | false |
geckour/Egret | app/src/main/java/com/geckour/egret/view/fragment/LicenseFragment.kt | 1 | 2499 | package com.geckour.egret.view.fragment
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.geckour.egret.R
import com.geckour.egret.databinding.FragmentLicenseBinding
import com.geckour.egret.view.activity.SettingActivity
class LicenseFragment : BaseFragment() {
enum class License {
Stetho,
RxJava,
RxAndroid,
RxKotlin,
RxLifecycle,
Orma,
Retrofit,
Glide,
Timber,
MaterialDrawer,
CircularImageView,
Calligraphy,
Emoji,
CommonsIO
}
companion object {
val TAG: String = this::class.java.simpleName
fun newInstance(): LicenseFragment = LicenseFragment()
}
lateinit private var binding: FragmentLicenseBinding
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_license, container, false)
return binding.root
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
injectLicense()
}
override fun onPause() {
super.onPause()
}
override fun onResume() {
super.onResume()
(activity as? SettingActivity)?.binding?.appBarMain?.toolbar?.title = getString(R.string.title_fragment_license)
}
private fun injectLicense() {
listOf(
binding.licenseStetho,
binding.licenseReactiveXJava,
binding.licenseReactiveXAndroid,
binding.licenseReactiveXKotlin,
binding.licenseReactiveXLifecycle,
binding.licenseOrma,
binding.licenseRetrofit,
binding.licenseGlide,
binding.licenseTimber,
binding.licenseMaterialDrawer,
binding.licenseCircularImageView,
binding.licenseCalligraphy,
binding.licenseEmoji,
binding.licenseCommonsIo
)
.forEach {
it.apply {
name.setOnClickListener {
body.visibility = if (body.visibility == View.VISIBLE) View.GONE else View.VISIBLE
}
}
}
}
} | gpl-3.0 | 18baf49bffe2290857399adc4c1882b2 | 28.411765 | 120 | 0.607443 | 5.351178 | false | false | false | false |
http4k/http4k | http4k-security/digest/src/main/kotlin/org/http4k/security/digest/DigestEncoder.kt | 1 | 1728 | package org.http4k.security.digest
import org.http4k.core.Method
import org.http4k.security.Nonce
import org.http4k.security.digest.Qop.Auth
import org.http4k.security.digest.Qop.AuthInt
import org.http4k.util.Hex
import java.nio.charset.Charset
import java.security.MessageDigest
import kotlin.text.Charsets.ISO_8859_1
class DigestEncoder(private val digester: MessageDigest, private val charset: Charset = ISO_8859_1) {
private fun hexDigest(value: String) = Hex.hex(digest(value))
private fun digest(value: String) = digester.digest(value.toByteArray(charset))
operator fun invoke(
realm: String,
qop: Qop?,
method: Method,
username: String,
password: String,
nonce: Nonce,
cnonce: Nonce?,
nonceCount: Long?,
digestUri: String
): ByteArray {
val nc = nonceCount?.toString(16)?.padStart(8, '0')
/*
* TODO: If the algorithm directive's value is "MD5-sess", then HA1 is
* HA1 = MD5(MD5(username:realm:password):nonce:cnonce)
* Note: this feature doesn't have wide browser compatibility, so may be ok to ignore
*/
val ha1 = hexDigest("${username}:$realm:$password")
/*
* TODO auth-int QoP should be of format MD5(method:digestURI:MD5(entityBody))
* This might be problematic if BodyMode is Stream
* Note: this feature doesn't have wide browser compatibility, so may be ok to ignore
*/
val ha2 = hexDigest("$method:$digestUri")
val response = when (qop) {
null -> "$ha1:$nonce:$ha2"
Auth, AuthInt -> "$ha1:$nonce:$nc:$cnonce:${qop.value}:$ha2"
}
return digest(response)
}
}
| apache-2.0 | fde12e1e7e5e94fccfcdacfd9dd6f022 | 33.56 | 101 | 0.643519 | 3.74026 | false | false | false | false |
vitoling/HiWeather | src/main/kotlin/com/vito/work/weather/service/HistoryWeatherService.kt | 1 | 7752 | package com.vito.work.weather.service
import com.vito.work.weather.config.Constant
import com.vito.work.weather.dto.City
import com.vito.work.weather.dto.HistoryWeather
import com.vito.work.weather.repo.DistrictDao
import com.vito.work.weather.repo.HistoryWeatherDao
import com.vito.work.weather.service.spider.AbstractSpiderTask
import com.vito.work.weather.service.spider.MonthViewPageProcessor
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import us.codecraft.webmagic.ResultItems
import us.codecraft.webmagic.Spider
import us.codecraft.webmagic.scheduler.QueueScheduler
import java.sql.Date
import java.sql.Timestamp
import java.time.LocalDate
import java.time.LocalDateTime
import javax.annotation.PreDestroy
import javax.annotation.Resource
/**
* Created by lingzhiyuan.
* Date : 16/4/5.
* Time : 下午7:55.
* Description:
*
*/
@Service
@Transactional
class HistoryWeatherService : AbstractSpiderTask() {
@Resource
lateinit var historyWeatherDao: HistoryWeatherDao
@Resource
lateinit var districtDao: DistrictDao
@PreDestroy
fun destroy() {
spider.close()
logger.info("History Spider Stopped")
}
companion object {
// 只使用一个 spider, 一个线程池
var spider: Spider = Spider.create(MonthViewPageProcessor())
.thread(Constant.SPIDER_THREAD_COUNT)
private val logger = LoggerFactory.getLogger(HistoryWeatherService::class.java)
}
fun execute() {
task {
HistoryWeatherService.spider.scheduler = QueueScheduler()
val cities = districtDao.findAll(City::class.java)
cities.forEach { city ->
var tempDate = Constant.SPIDER_HISTORY_START_DATE
while (tempDate <= LocalDate.now().minusMonths(1)) {
try {
tempDate = tempDate.plusMonths(1)
updateFromWeb(city, tempDate)
} catch(ex: Exception) {
// 忽略更新时的异常
continue
}
}
}
}
}
/**
* 根据日期找到一个历史项, 找不到则抛出资源未找到的异常
* */
fun findHistoryWeather(city: City, date: LocalDate): HistoryWeather? {
val weather = historyWeatherDao.findByCityDate(city.id, Date.valueOf(date))
return weather
}
/**
* 更新历史天气的入口
*
* 执行更新和和保存操作
* */
fun updateFromWeb(city: City, date: LocalDate) {
try {
task {
val targetUrl = monthViewUrlBuilder(Constant.HISTORY_WEATHER_BASE_URL, city.pinyin, date)
val hws = fetchDataViaSpider(targetUrl, city)
saveHistoryWeather(hws, city)
}
} finally {
spider.scheduler = QueueScheduler()
}
}
/**
* 执行保存历史天气的操作
* */
fun saveHistoryWeather(weathers: List<HistoryWeather>, city: City) {
val savedWeathers = weathers
.map { it.date }
.let { historyWeatherDao.findByCityDates(city.id, it) }
.toMutableList()
weathers.forEach {
iw ->
savedWeathers.singleOrNull { it.city == iw.city && it.date == iw.date }?.apply {
max = iw.max
min = iw.min
wind_direction = iw.wind_direction
wind_force = iw.wind_force
weather = iw.weather
update_time = iw.update_time
} ?: savedWeathers.add(iw)
}
savedWeathers.forEach { historyWeatherDao save it }
}
fun findHistoryWeathersOfToday(cityId: Long): List<HistoryWeather> {
val now = LocalDate.now()
val dates = (Constant.SPIDER_HISTORY_START_DATE.year .. now.year).map { Date.valueOf(LocalDate.of(it, now.monthValue, now.dayOfMonth)) }
return historyWeatherDao.findByCityDates(cityId, dates)
}
fun findHistoryTops(cityId: Long): List<HistoryWeather> {
val result = mutableListOf<HistoryWeather>()
val maxTempWeather = historyWeatherDao.findHighestTemperature(cityId) ?: HistoryWeather()
val minTempWeather = historyWeatherDao.findLowestTemperature(cityId) ?: HistoryWeather()
result.add(maxTempWeather)
result.add(minTempWeather)
return result
}
/**
* 根据城市的 id查找某一天的历史天气
* */
fun findByDate(cityId: Long, date: LocalDate): HistoryWeather? {
return historyWeatherDao.findByCityDate(cityId, Date.valueOf(date))
}
/**
* 根据城市的 id 查出某一个月所有的历史天气
* */
fun findByMonth(cityId: Long, date: LocalDate): List<HistoryWeather>? {
val dates = mutableListOf<Date>()
// 这个月的起始日期
val startDate = date.minusDays(date.dayOfMonth.toLong() - 1)
(0 .. date.lengthOfMonth() - 1).forEach { offset -> dates.add(Date.valueOf(startDate.plusDays(offset.toLong()))) }
return historyWeatherDao.findByCityDates(cityId, dates)
}
}
/**
* URL Builder
* */
private val monthViewUrlBuilder: (String, String, LocalDate) -> String = {
baseUrl, cityPinyin, date ->
val urlSeparator = "/"
val urlSuffix = ".html"
StringBuffer().apply {
if (! baseUrl.startsWith("http://") && ! baseUrl.startsWith("https://")) {
append("http://")
}
append(baseUrl)
append(urlSeparator)
append(cityPinyin)
append(urlSeparator)
append(date.year)
val month = date.monthValue
append(if (month >= 10) month else "0$month")
append(urlSuffix)
}.toString()
}
/**
* 解析获取到的结果集
* 一个 url 代表一个城市一个月的历史天气
*
* */
private val fetchDataViaSpider = fun(targetUrl: String, city: City): List<HistoryWeather> {
val resultItems: ResultItems?
try {
resultItems = HistoryWeatherService.spider.get(targetUrl)
} catch(ex: Exception) {
throw ex
}
if (resultItems == null || resultItems.request == null) {
throw Exception("Request Can't Be Null")
}
var hws: List<HistoryWeather> = listOf()
resultItems.apply {
val dateStrs: List<String> = get("date")
val maxes: List<String> = get("max")
val mines: List<String> = get("min")
val weathers: List<String> = get("weather")
val directions: List<String> = get("wind_direction")
val forces: List<String> = get("wind_force")
hws = dateStrs
.map { Date.valueOf(it) }
.mapIndexed {
index, date ->
HistoryWeather().apply {
this.city = city.id
this.date = date
this.max = Integer.parseInt(maxes[index])
this.min = Integer.parseInt(mines[index])
// 调换温度的顺序, 数字大的为 max, 小的为 min
if (this.max < this.min) {
val temp = this.min
this.min = this.max
this.max = temp
}
this.weather = weathers[index]
this.wind_direction = directions[index]
this.wind_force = forces[index]
this.update_time = Timestamp.valueOf(LocalDateTime.now())
}
}
}
return hws
} | gpl-3.0 | 84f4ca949eb8af2a4911f601dafe0d17 | 30.66383 | 144 | 0.5875 | 4.184477 | false | false | false | false |
tipsy/javalin | javalin/src/main/java/io/javalin/http/sse/Emitter.kt | 1 | 1309 | package io.javalin.http.sse
import java.io.IOException
import java.io.InputStream
import javax.servlet.AsyncContext
import javax.servlet.ServletOutputStream
const val COMMENT_PREFIX = ":"
class Emitter(private var asyncContext: AsyncContext) {
private lateinit var output: ServletOutputStream
private var closed = false
private val newline = "\n"
init {
try {
this.output = asyncContext.response.outputStream
} catch (e: IOException) {
closed = true
}
}
fun emit(event: String, data: InputStream, id: String?) = synchronized(this) {
try {
if (id != null) {
output.print("id: $id$newline")
}
output.print("event: $event$newline")
output.print("data: ")
data.copyTo(output)
output.print(newline)
output.print(newline)
asyncContext.response.flushBuffer()
} catch (e: IOException) {
closed = true
}
}
fun emit(comment: String) = try {
comment.split(newline).forEach {
output.print("$COMMENT_PREFIX $it$newline")
}
asyncContext.response.flushBuffer()
} catch (e: IOException) {
closed = true
}
fun isClosed() = closed
}
| apache-2.0 | 429ddf794bdafcec612568a62fa52885 | 24.173077 | 82 | 0.58136 | 4.407407 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/map/IntersectionUtil.kt | 2 | 3282 | package de.westnordost.streetcomplete.map
import android.graphics.PointF
import android.view.ViewGroup
import androidx.core.view.children
import androidx.core.view.isVisible
fun findClosestIntersection(v: ViewGroup, target: PointF): PointF? {
val w = v.width.toFloat()
val h = v.height.toFloat()
val ox = w / 2
val oy = h / 2
val tx = target.x
val ty = target.y
var minA = Float.MAX_VALUE
var a: Float
// left side
a = intersectionWithVerticalSegment(ox, oy, tx, ty, 0f, 0f, h)
if (a < minA) minA = a
// right side
a = intersectionWithVerticalSegment(ox, oy, tx, ty, w, 0f, h)
if (a < minA) minA = a
// top side
a = intersectionWithHorizontalSegment(ox, oy, tx, ty, 0f, 0f, w)
if (a < minA) minA = a
// bottom side
a = intersectionWithHorizontalSegment(ox, oy, tx, ty, 0f, h, w)
if (a < minA) minA = a
for (child in v.children) {
if (!child.isVisible) continue
val t = child.top.toFloat()
val b = child.bottom.toFloat()
val r = child.right.toFloat()
val l = child.left.toFloat()
// left side
if (l > ox && l < w) {
a = intersectionWithVerticalSegment(ox, oy, tx, ty, l, t, b - t)
if (a < minA) minA = a
}
// right side
if (r > 0 && r < ox) {
a = intersectionWithVerticalSegment(ox, oy, tx, ty, r, t, b - t)
if (a < minA) minA = a
}
// top side
if (t > oy && t < h) {
a = intersectionWithHorizontalSegment(ox, oy, tx, ty, l, t, r - l)
if (a < minA) minA = a
}
// bottom side
if (b > 0 && b < oy) {
a = intersectionWithHorizontalSegment(ox, oy, tx, ty, l, b, r - l)
if (a < minA) minA = a
}
}
return if (minA <= 1f) PointF(ox + (tx - ox) * minA, oy + (ty - oy) * minA) else null
}
/** Intersection of line segment going from P to Q with vertical line starting at V and given
* length. Returns the f for P+f*(Q-P) or MAX_VALUE if no intersection found. */
private fun intersectionWithVerticalSegment(
px: Float, py: Float,
qx: Float, qy: Float,
vx: Float, vy: Float,
length: Float
): Float {
val dx = qx - px
if (dx == 0f) return Float.MAX_VALUE
val a = (vx - px) / dx
// not in range of line segment A
if (a < 0f || a > 1f) return Float.MAX_VALUE
val dy = qy - py
val posY = py + dy * a
// not in range of horizontal line segment
if (posY < vy || posY > vy + length) return Float.MAX_VALUE
return a
}
/** Intersection of line segment going from P to Q with horizontal line starting at H and given
* length. Returns the f for P+f*(Q-P) or MAX_VALUE if no intersection found. */
private fun intersectionWithHorizontalSegment(
px: Float, py: Float,
qx: Float, qy: Float,
hx: Float, hy: Float,
length: Float
): Float {
val dy = qy - py
if (dy == 0f) return Float.MAX_VALUE
val a = (hy - py) / dy
// not in range of line segment P-Q
if (a < 0f || a > 1f) return Float.MAX_VALUE
val dx = qx - px
val posX = px + dx * a
// not in range of horizontal line segment
if (posX < hx || posX > hx + length) return Float.MAX_VALUE
return a
}
| gpl-3.0 | 36ef2eba1193cda0ace6a0be269a65cc | 28.836364 | 95 | 0.573736 | 3.19883 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-domain/src/main/kotlin/com/octaldata/domain/structure/docs.kt | 1 | 1544 | package com.octaldata.domain.structure
/**
* Models the base level record/document/message/object/etc coming from a streaming system.
*
* Kafka: Record
* Pulsar: Message
* Kinesis: Message
* Redpanda: Record
*
* @param urn uniquely identifies this record in the underlying system.
* @param meta information such as topic, offset
* @param headers extra headers included with some records
* @param keyBytes the underlying bytes of the key in the record or null if no key was present
* @param valueBytes the underlying bytes of the value in the record or null if no value was present
*/
@Suppress("ArrayInDataClass")
data class DataRecord(
val urn: DataRecordUrn,
val meta: Map<String, String?>,
val headers: Map<String, String?>,
val keySize: Int,
val keyBytes: ByteArray?,
val valueSize: Int,
val valueBytes: ByteArray?,
) {
companion object Meta {
const val Partition = "partition"
const val Topic = "topic"
const val Offset = "offset"
const val LeaderEpoch = "leader_epoch"
const val Timestamp = "timestamp"
const val TimestampType = "timestamp_type"
}
fun meta(key: String): String? = meta[key]
fun metaAsInt(key: String): Int? = meta[key]?.toIntOrNull()
fun metaAsLong(key: String): Long? = meta[key]?.toLongOrNull()
fun header(key: String): String? = headers[key]
fun headerAsInt(key: String): Int? = headers[key]?.toIntOrNull()
fun headerAsLong(key: String): Long? = headers[key]?.toLongOrNull()
}
data class DataRecordUrn(val value: String) | apache-2.0 | 6299c595452dc1ad1c950add502ebfd1 | 33.333333 | 100 | 0.704663 | 3.969152 | false | false | false | false |
brianmadden/krawler | src/main/kotlin/io/thelandscape/krawler/robots/RobotsTxt.kt | 1 | 2599 | /**
* Created by [email protected] on 1/14/17.
*
* Copyright (c) <2017> <H, llc>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package io.thelandscape.krawler.robots
import io.thelandscape.krawler.http.KrawlUrl
import io.thelandscape.krawler.http.RequestResponse
import org.apache.http.HttpResponse
import org.apache.http.client.protocol.HttpClientContext
import org.apache.http.util.EntityUtils
class RobotsTxt(url: KrawlUrl, response: HttpResponse, context: HttpClientContext) : RequestResponse {
// TODO: Improve handling: https://en.wikipedia.org/wiki/Robots_exclusion_standard#About_the_standard
var disallowRules: Map<String, MutableSet<String>> = mapOf()
private set
// Do all the parsing in a single pass in here
init {
val rules: MutableMap<String, MutableSet<String>> = mutableMapOf()
val responseList: List<String> = EntityUtils.toString(response.entity).lines()
var userAgent: String = ""
for (line in responseList) {
val splitVal = line.split(":").map(String::trim)
val key: String = splitVal[0].toLowerCase()
val value: String = splitVal[1].trim()
if (key == "user-agent") {
userAgent = value
continue
}
if (key == "disallow") {
if (userAgent in rules)
rules[userAgent]!!.add(value)
else
rules[userAgent] = mutableSetOf(value)
continue
}
}
disallowRules = rules
}
}
| mit | dbcdf9003f1bbaa2e387e65d2364a868 | 38.984615 | 120 | 0.680646 | 4.435154 | false | false | false | false |
sabi0/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GithubApiRequestExecutor.kt | 1 | 9436 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
import com.google.gson.JsonParseException
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.util.ThrowableConvertor
import com.intellij.util.io.HttpRequests
import com.intellij.util.io.HttpSecurityUtil
import com.intellij.util.io.RequestBuilder
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.annotations.TestOnly
import org.jetbrains.plugins.github.api.data.GithubErrorMessage
import org.jetbrains.plugins.github.exceptions.*
import org.jetbrains.plugins.github.util.GithubSettings
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.io.Reader
import java.net.HttpURLConnection
import java.util.function.Supplier
/**
* Executes API requests taking care of authentication, headers, proxies, timeouts, etc.
*/
sealed class GithubApiRequestExecutor {
@Throws(IOException::class, ProcessCanceledException::class)
abstract fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T
@TestOnly
@Throws(IOException::class, ProcessCanceledException::class)
fun <T> execute(request: GithubApiRequest<T>): T = execute(EmptyProgressIndicator(), request)
class WithTokenAuth internal constructor(githubSettings: GithubSettings,
private val token: String,
private val useProxy: Boolean) : Base(githubSettings) {
@Throws(IOException::class, ProcessCanceledException::class)
override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T {
indicator.checkCanceled()
return createRequestBuilder(request)
.tuner { connection -> connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Token $token") }
.useProxy(useProxy)
.execute(request, indicator)
}
}
class WithBasicAuth internal constructor(githubSettings: GithubSettings,
private val login: String,
private val password: CharArray,
private val twoFactorCodeSupplier: Supplier<String?>) : Base(githubSettings) {
private var twoFactorCode: String? = null
@Throws(IOException::class, ProcessCanceledException::class)
override fun <T> execute(indicator: ProgressIndicator, request: GithubApiRequest<T>): T {
indicator.checkCanceled()
val basicHeaderValue = HttpSecurityUtil.createBasicAuthHeaderValue(login, password)
return executeWithBasicHeader(indicator, request, basicHeaderValue)
}
private fun <T> executeWithBasicHeader(indicator: ProgressIndicator, request: GithubApiRequest<T>, header: String): T {
indicator.checkCanceled()
return try {
createRequestBuilder(request)
.tuner { connection ->
connection.addRequestProperty(HttpSecurityUtil.AUTHORIZATION_HEADER_NAME, "Basic $header")
twoFactorCode?.let { connection.addRequestProperty(OTP_HEADER_NAME, it) }
}
.execute(request, indicator)
}
catch (e: GithubTwoFactorAuthenticationException) {
twoFactorCode = twoFactorCodeSupplier.get() ?: throw e
executeWithBasicHeader(indicator, request, header)
}
}
}
abstract class Base(private val githubSettings: GithubSettings) : GithubApiRequestExecutor() {
protected fun <T> RequestBuilder.execute(request: GithubApiRequest<T>, indicator: ProgressIndicator): T {
indicator.checkCanceled()
try {
return connect {
val connection = it.connection as HttpURLConnection
if (request is GithubApiRequest.WithBody) {
LOG.debug("Request: ${connection.requestMethod} ${connection.url} with body:\n${request.body}")
it.write(request.body)
}
else {
LOG.debug("Request: ${connection.requestMethod} ${connection.url}")
}
checkResponseCode(connection)
indicator.checkCanceled()
val result = request.extractResult(createResponse(it, indicator))
LOG.debug("Request: ${connection.requestMethod} ${connection.url}: Success")
result
}
}
catch (e: GithubStatusCodeException) {
@Suppress("UNCHECKED_CAST")
if (request is GithubApiRequest.Get.Optional<*> && e.statusCode == HttpURLConnection.HTTP_NOT_FOUND) return null as T else throw e
}
catch (e: GithubConfusingException) {
if (request.operationName != null) {
val errorText = "Can't ${request.operationName}"
e.setDetails(errorText)
LOG.debug(errorText, e)
}
throw e
}
}
protected fun createRequestBuilder(request: GithubApiRequest<*>): RequestBuilder {
return when (request) {
is GithubApiRequest.Get -> HttpRequests.request(request.url)
is GithubApiRequest.Post -> HttpRequests.post(request.url, request.bodyMimeType)
is GithubApiRequest.Patch -> HttpRequests.patch(request.url, request.bodyMimeType)
is GithubApiRequest.Head -> HttpRequests.head(request.url)
is GithubApiRequest.Delete -> HttpRequests.delete(request.url)
else -> throw UnsupportedOperationException("${request.javaClass} is not supported")
}
.connectTimeout(githubSettings.connectionTimeout)
.userAgent("Intellij IDEA Github Plugin")
.throwStatusCodeException(false)
.forceHttps(true)
.accept(request.acceptMimeType)
}
@Throws(IOException::class)
private fun checkResponseCode(connection: HttpURLConnection) {
if (connection.responseCode < 400) return
val statusLine = "${connection.responseCode} ${connection.responseMessage}"
val errorText = getErrorText(connection)
val jsonError = getJsonError(connection, errorText)
LOG.debug("Request: ${connection.requestMethod} ${connection.url}: Error ${statusLine} body:\n${errorText}")
throw when (connection.responseCode) {
HttpURLConnection.HTTP_UNAUTHORIZED,
HttpURLConnection.HTTP_PAYMENT_REQUIRED,
HttpURLConnection.HTTP_FORBIDDEN -> {
val otpHeader = connection.getHeaderField(OTP_HEADER_NAME)
if (otpHeader != null && otpHeader.contains("required", true)) {
GithubTwoFactorAuthenticationException(jsonError?.message ?: errorText)
}
else if (jsonError?.containsReasonMessage("API rate limit exceeded") == true) {
GithubRateLimitExceededException(jsonError.message)
}
else GithubAuthenticationException("Request response: " + (jsonError?.message ?: errorText))
}
else -> {
if (jsonError != null) {
GithubStatusCodeException("$statusLine - ${jsonError.message}", jsonError, connection.responseCode)
}
else {
GithubStatusCodeException("$statusLine - ${errorText}", connection.responseCode)
}
}
}
}
private fun getErrorText(connection: HttpURLConnection): String {
return connection.errorStream?.let { InputStreamReader(it).use { it.readText() } } ?: ""
}
private fun getJsonError(connection: HttpURLConnection, errorText: String): GithubErrorMessage? {
if (!connection.contentType.startsWith(GithubApiContentHelper.JSON_MIME_TYPE)) return null
return try {
return GithubApiContentHelper.fromJson(errorText)
}
catch (jse: JsonParseException) {
LOG.debug(jse)
null
}
}
private fun createResponse(request: HttpRequests.Request, indicator: ProgressIndicator): GithubApiResponse {
return object : GithubApiResponse {
override fun findHeader(headerName: String): String? = request.connection.getHeaderField(headerName)
override fun <T> readBody(converter: ThrowableConvertor<Reader, T, IOException>): T = request.getReader(indicator).use {
converter.convert(it)
}
override fun <T> handleBody(converter: ThrowableConvertor<InputStream, T, IOException>): T = request.inputStream.use {
converter.convert(it)
}
}
}
}
class Factory internal constructor(private val githubSettings: GithubSettings) {
@CalledInAny
fun create(token: String): WithTokenAuth {
return create(token, true)
}
@CalledInAny
fun create(token: String, useProxy: Boolean = true): WithTokenAuth {
return GithubApiRequestExecutor.WithTokenAuth(githubSettings, token, useProxy)
}
@CalledInAny
internal fun create(login: String, password: CharArray, twoFactorCodeSupplier: Supplier<String?>): WithBasicAuth {
return GithubApiRequestExecutor.WithBasicAuth(githubSettings, login, password, twoFactorCodeSupplier)
}
companion object {
@JvmStatic
fun getInstance(): Factory = service()
}
}
companion object {
private val LOG = logger<GithubApiRequestExecutor>()
private const val OTP_HEADER_NAME = "X-GitHub-OTP"
}
} | apache-2.0 | 0ac9895ea63f4ee1ac5e96c0fa053131 | 41.895455 | 140 | 0.691925 | 4.987315 | false | false | false | false |
ageery/kwicket | kwicket-wicket-core/src/main/kotlin/org/kwicket/wicket/core/markup/html/basic/KLabel.kt | 1 | 5673 | package org.kwicket.wicket.core.markup.html.basic
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.markup.html.WebMarkupContainer
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.component.q
@Deprecated(
message = "Use the method in the lambda package",
replaceWith = ReplaceWith(expression = "org.kwicket.wicket.core.lambda.label")
)
fun label(
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
): (String) -> Label = {
KLabel(
id = it,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
}
@Deprecated(
message = "Use the method in the queued package",
replaceWith = ReplaceWith(expression = "org.kwicket.wicket.core.queued.label")
)
fun WebMarkupContainer.label(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
) = q(
KLabel(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
)
@Deprecated(
message = "Use the method in the queued package",
replaceWith = ReplaceWith(expression = "org.kwicket.wicket.core.queued.label")
)
fun WebMarkupContainer.label(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behavior: Behavior
) = q(
KLabel(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behavior = behavior
)
)
/**
* [Label] with named and default constructor arguments.
*
* @param id Wicket markup id
* @param model model for the component
* @param outputMarkupId whether to include an HTML id for the component in the markup
* @param outputMarkupPlaceholderTag whether to include a placeholder tag for the component in the markup when the
* component is not visible
* @param visible whether the component is visible
* @param enabled whether the component is enabled
* @param escapeModelStrings whether model strings should be escaped
* @param renderBodyOnly whether the tag associated with the component should be included in the markup
* @param behaviors list of [Behavior] to add to the component
*/
open class KLabel(
id: String,
model: IModel<*>? = null, // FIXME: make the model required!
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behaviors: List<Behavior>? = null
) : Label(id, model) {
/**
* Creates a [KLabel] instance with a single [Behavior].
*
* @param id Wicket markup id
* @param model model for the component
* @param outputMarkupId whether to include an HTML id for the component in the markup
* @param outputMarkupPlaceholderTag whether to include a placeholder tag for the component in the markup when the
* component is not visible
* @param visible whether the component is visible
* @param enabled whether the component is enabled
* @param escapeModelStrings whether model strings should be escaped
* @param renderBodyOnly whether the tag associated with the component should be included in the markup
* @param behavior [Behavior] to add to the component
*/
constructor(
id: String,
model: IModel<*>? = null,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
behavior: Behavior
) : this(
id = id,
model = model,
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = listOf(behavior)
)
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
}
} | apache-2.0 | 2a5a1fa947997c1be0239f34962edfde | 32.976048 | 118 | 0.673894 | 4.971954 | false | false | false | false |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/asyncs/BackgroundWorker.kt | 1 | 3308 | /*
* Copyright (c) 2016. Sunghyouk Bae <[email protected]>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.core.asyncs
import debop4k.core.loggerOf
import debop4k.core.utils.joinThread
import java.lang.*
import java.util.concurrent.atomic.*
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
/**
* 백그라운에서 수행되는 Worker 를 표현합니다.
*
* @author debop [email protected]
*/
interface BackgroundWorker {
/** Worker name */
val name: String
/** Worker 가 작업 중인가? */
val isRunning: Boolean
/** Worker를 시작합니다. */
@PostConstruct
fun start(): Unit
/** Worker 를 종료합니다. */
@PreDestroy
fun stop(): Unit
}
/**
* 백그라운드에서 수행되는 Worker 의 추상 클래스입니다.
* 이 클래스를 상속 받고, 백그라운드에서 수행할 작업을 [newWorkerThread] 메소드를 재정의하면 됩니다.
*
* @author debop [email protected]
*/
abstract class AbstractBackgroundWorker(override val name: String) : BackgroundWorker {
private val log = loggerOf(javaClass)
protected val running = AtomicBoolean(false)
@Volatile protected var workerThread: Thread? = null
/** 실제 Background 작업을 수행할 Thread를 생성합니다 */
abstract fun newWorkerThread(): Thread
/** 백그라운드 작업용 스레드가 실행 중인가? */
override val isRunning: Boolean
get() = running.get()
/**
* 백그라운드 작업을 시작합니다.
* Spring Bean으로 등록하면 [PostConstruct] annotation 지정에 따라 자동으로 시작합니다.
*/
@PostConstruct
@Synchronized
override fun start(): Unit {
if (isRunning)
return
log.debug("{} 작업을 위한 백그라운드 스레드를 생성하고 시작합니다.", name)
try {
workerThread = newWorkerThread()
workerThread?.let {
it.run()
running.compareAndSet(false, true)
}
} catch(e: Exception) {
log.error("{} 작업 스레드를 시작하는데 실패했습니다.", name, e)
throw RuntimeException(e)
}
}
/**
* 백그라운드 작업을 종료합니다.
* Spring Bean으로 등록하면 [PreDestroy] annotation 지정에 따라 자동으로 종료합니다.
*/
@PreDestroy
@Synchronized
override fun stop(): Unit {
if (!isRunning)
return
log.debug("{} 작업을 종료합니다...", name)
try {
workerThread?.let {
if (it.isAlive) {
it.interrupt()
joinThread(it, 500)
}
}
} catch(e: Exception) {
log.warn("{} 작업용 스레드를 종료하는데 실패했습니다.", name, e)
} finally {
workerThread = null
running.set(false)
}
}
}
| apache-2.0 | aadf5f5e08ea7f4096a4d71fd88175a0 | 22.779661 | 87 | 0.659301 | 3.128205 | false | false | false | false |
cfig/Android_boot_image_editor | bbootimg/src/main/kotlin/packable/IPackable.kt | 1 | 3226 | // Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.packable
import avb.AVBInfo
import cfig.Avb
import cfig.helper.Helper
import cfig.helper.Dumpling
import cfig.helper.Helper.Companion.check_call
import cfig.helper.Helper.Companion.check_output
import cfig.helper.Helper.Companion.deleteIfExists
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
interface IPackable {
val loopNo: Int
val outDir: String
get() = Helper.prop("workDir")
fun capabilities(): List<String> {
return listOf("^dtbo\\.img$")
}
fun unpack(fileName: String = "dtbo.img")
fun pack(fileName: String = "dtbo.img")
fun flash(fileName: String = "dtbo.img", deviceName: String = "dtbo") {
"adb root".check_call()
val abUpdateProp = "adb shell getprop ro.build.ab_update".check_output()
log.info("ro.build.ab_update=$abUpdateProp")
val slotSuffix = if (abUpdateProp == "true" && !fileName.startsWith("misc.img")) {
"adb shell getprop ro.boot.slot_suffix".check_output()
} else {
""
}
log.info("slot suffix = $slotSuffix")
"adb push $fileName /mnt/file.to.burn".check_call()
"adb shell dd if=/mnt/file.to.burn of=/dev/block/by-name/$deviceName$slotSuffix".check_call()
"adb shell rm /mnt/file.to.burn".check_call()
}
fun pull(fileName: String = "dtbo.img", deviceName: String = "dtbo") {
"adb root".check_call()
val abUpdateProp = "adb shell getprop ro.build.ab_update".check_output()
log.info("ro.build.ab_update=$abUpdateProp")
val slotSuffix = if (abUpdateProp == "true" && !fileName.startsWith("misc.img")) {
"adb shell getprop ro.boot.slot_suffix".check_output()
} else {
""
}
log.info("slot suffix = $slotSuffix")
"adb shell dd if=/dev/block/by-name/$deviceName$slotSuffix of=/mnt/file.to.pull".check_call()
"adb pull /mnt/file.to.pull $fileName".check_call()
"adb shell rm /mnt/file.to.pull".check_call()
}
// invoked solely by reflection
fun `@verify`(fileName: String) {
val ai = AVBInfo.parseFrom(Dumpling(fileName)).dumpDefault(fileName)
Avb.verify(ai, Dumpling(fileName, fileName))
}
fun clear() {
val workDir = Helper.prop("workDir")
if (File(workDir).exists()) {
log.info("deleting $workDir ...")
File(workDir).deleteRecursively()
}
File(workDir).mkdirs()
"uiderrors".deleteIfExists()
}
companion object {
val log: Logger = LoggerFactory.getLogger(IPackable::class.java)
}
}
| apache-2.0 | f1e43e4128587d7209f5ca6e56b683f9 | 35.659091 | 101 | 0.648481 | 3.72948 | false | false | false | false |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/machines/compoundmaker/CompoundMakerCategory.kt | 1 | 3767 | package net.ndrei.teslapoweredthingies.machines.compoundmaker
import mezz.jei.api.IModRegistry
import mezz.jei.api.gui.IDrawable
import mezz.jei.api.gui.IRecipeLayout
import mezz.jei.api.ingredients.IIngredients
import mezz.jei.api.recipe.IRecipeCategoryRegistration
import mezz.jei.api.recipe.IRecipeWrapper
import net.minecraft.client.Minecraft
import net.minecraft.item.ItemStack
import net.minecraftforge.fluids.FluidStack
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import net.ndrei.teslacorelib.utils.isEmpty
import net.ndrei.teslapoweredthingies.client.ThingiesTexture
import net.ndrei.teslapoweredthingies.integrations.jei.BaseCategory
import net.ndrei.teslapoweredthingies.integrations.jei.TeslaThingyJeiCategory
/**
* Created by CF on 2017-07-06.
*/
@TeslaThingyJeiCategory
object CompoundMakerCategory
: BaseCategory<CompoundMakerCategory.RecipeWrapper>(CompoundMakerBlock) {
private lateinit var fluidOverlay: IDrawable
override fun setRecipe(recipeLayout: IRecipeLayout, recipeWrapper: RecipeWrapper, ingredients: IIngredients) {
val recipe = recipeWrapper.recipe
val fluids = recipeLayout.fluidStacks
var fluidIndex = 0
if (!recipe.left.isEmpty) {
fluids.init(0, true, 5, 15, 8, 27, 1000, true, fluidOverlay)
fluids.set(0, recipe.left)
fluidIndex = 1
}
if (!recipe.right.isEmpty) {
fluids.init(fluidIndex, true, 71, 15, 8, 27, 1000, true, fluidOverlay)
fluids.set(fluidIndex, recipe.right)
}
val stacks = recipeLayout.itemStacks
var stackIndex = 0
recipe.top.forEachIndexed { i, it ->
stacks.init(stackIndex, true, 15 + i * 18, 6)
stacks.set(stackIndex, it)
stackIndex++
}
recipe.bottom.forEachIndexed { i, it ->
stacks.init(stackIndex, true, 15 + i * 18, 33)
stacks.set(stackIndex, it)
stackIndex++
}
stacks.init(stackIndex, false, 92, 20)
stacks.set(stackIndex, recipe.output)
}
class RecipeWrapper(val recipe: CompoundMakerRecipe)
: IRecipeWrapper {
override fun getIngredients(ingredients: IIngredients) {
val fluids = mutableListOf<FluidStack>()
listOf(this.recipe.left, this.recipe.right).mapNotNullTo(fluids) { it?.copy() }
if (fluids.isNotEmpty()) {
ingredients.setInputs(FluidStack::class.java, fluids)
}
val items = mutableListOf<ItemStack>()
items.addAll(this.recipe.top)
items.addAll(this.recipe.bottom)
if (items.isNotEmpty()) {
ingredients.setInputs(ItemStack::class.java, items.map { it.copy() })
}
ingredients.setOutput(ItemStack::class.java, this.recipe.output.copy())
}
@SideOnly(Side.CLIENT)
override fun drawInfo(minecraft: Minecraft, recipeWidth: Int, recipeHeight: Int, mouseX: Int, mouseY: Int) {
super.drawInfo(minecraft, recipeWidth, recipeHeight, mouseX, mouseY)
}
}
override fun register(registry: IRecipeCategoryRegistration) {
super.register(registry)
this.recipeBackground = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES_2.resource, 124, 66, 124, 57)
fluidOverlay = this.guiHelper.createDrawable(ThingiesTexture.JEI_TEXTURES.resource, 132, 147, 8, 27)
}
override fun register(registry: IModRegistry) {
super.register(registry)
registry.handleRecipes(CompoundMakerRecipe::class.java, { RecipeWrapper(it) }, this.uid)
registry.addRecipes(CompoundMakerRegistry.getAllRecipes(), this.uid)
}
}
| mit | 5e123a54185e6caad48ff73a8048aeca | 37.438776 | 120 | 0.680648 | 4.256497 | false | false | false | false |
hea3ven/DulceDeLeche | src/main/kotlin/com/hea3ven/dulcedeleche/modules/redstone/block/entity/CraftingMachineBlockEntity.kt | 1 | 7365 | package com.hea3ven.dulcedeleche.modules.redstone.block.entity
import com.hea3ven.dulcedeleche.modules.redstone.inventory.CraftingMachineInventory
import com.hea3ven.tools.commonutils.block.entity.MachineBlockEntity
import com.hea3ven.tools.commonutils.util.InventoryExtraUtil
import com.hea3ven.tools.commonutils.util.ItemStackUtil
import net.minecraft.block.entity.BlockEntityType
import net.minecraft.container.Container
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.inventory.BasicInventory
import net.minecraft.inventory.CraftingInventory
import net.minecraft.inventory.Inventories
import net.minecraft.inventory.Inventory
import net.minecraft.item.ItemStack
import net.minecraft.nbt.CompoundTag
import net.minecraft.recipe.RecipeType
import net.minecraft.recipe.crafting.CraftingRecipe
import net.minecraft.util.DefaultedList
abstract class CraftingMachineBlockEntity(additionalSlots: Int, blockEntityType: BlockEntityType<*>) :
MachineBlockEntity(blockEntityType), CraftingMachineInventory {
private val inventory = DefaultedList.create(28 + additionalSlots, ItemStack.EMPTY)!!
// private val recipe = DefaultedList.create(9, ItemStack.EMPTY)!!
override fun getInvStack(index: Int) = inventory[index]
override fun canPlayerUseInv(player: PlayerEntity) = true
override fun removeInvStack(index: Int) = Inventories.removeStack(inventory, index)!!
override fun clear() = inventory.clear()
override fun isInvEmpty() = inventory.all(ItemStack::isEmpty)
override fun takeInvStack(index: Int, amount: Int): ItemStack {
if (index == recipeResultIndex) {
return inventory[index].copy()
} else {
return Inventories.splitStack(inventory, index, amount)!!
}
}
override fun setInvStack(index: Int, stack: ItemStack) {
if (index in recipeInventoryRange) {
val recipeStack = stack.copy()
if (!recipeStack.isEmpty) {
recipeStack.amount = 1
}
inventory[index] = recipeStack
inventory[9] = getRecipe()?.output ?: ItemStack.EMPTY
markDirty()
} else {
if (stack.amount > invMaxStackAmount) {
stack.amount = invMaxStackAmount
}
inventory[index] = stack
}
}
override fun getInvSize() = inventory.size
// fun getRecipeStacks() = recipe
override fun toTag(tag: CompoundTag): CompoundTag {
super.toTag(tag)
Inventories.toTag(tag, inventory)
// InventoryExtraUtil.serialize(tag, recipe, "Recipe")
return tag
}
override fun fromTag(tag: CompoundTag) {
super.fromTag(tag)
if (tag.containsKey("Recipe")) {
// Convert from pre 1.2.0 format
val recipe = DefaultedList.create(9, ItemStack.EMPTY)
InventoryExtraUtil.deserialize(tag, recipe, "Recipe")
val oldInventory = DefaultedList.create(inventory.size - 10, ItemStack.EMPTY)
Inventories.fromTag(tag, oldInventory)
recipe.forEachIndexed { index, stack -> inventory[index] = stack }
oldInventory.forEachIndexed { index, stack -> inventory[index + 10] = stack }
} else {
inventory.clear()
Inventories.fromTag(tag, inventory)
}
}
fun canCraft(player: PlayerEntity?): Boolean {
val invCopy = BasicInventory(*inventory.map(ItemStack::copy).toTypedArray())
return !tryCraftItem(player, invCopy).isEmpty
}
override fun craftItem(player: PlayerEntity?): ItemStack {
if (!world.isClient) {
markDirty()
return tryCraftItem(player, this)
}
return inventory[recipeResultIndex]
}
private fun tryCraftItem(player: PlayerEntity?, inventory: Inventory): ItemStack {
val recipe = getRecipe() ?: return ItemStack.EMPTY
if (!onCraftItem(recipe, player, inventory)) {
return ItemStack.EMPTY
}
return recipe.output.copy()
}
protected open fun onCraftItem(recipe: CraftingRecipe, player: PlayerEntity?, inventory: Inventory): Boolean {
if (!consumeItems(inventory)) {
return false
}
val remainingStacks = recipe.getRemainingStacks(getCraftingInventory())
if (!storeRemainders(remainingStacks, inventory, player)) {
return false
}
return true
}
private fun consumeItems(inventory: Inventory): Boolean {
for (index in recipeInventoryRange) {
val recipeStack = inventory.getInvStack(index)
if (!recipeStack.isEmpty && !consumeItem(recipeStack, inventory)) {
// TODO: Test if this works
// not enough ingredients to craft
return false
}
}
return true
}
private fun consumeItem(stack: ItemStack, inventory: Inventory): Boolean {
for (invIndex in inputInventoryRange) {
val invStack = inventory.getInvStack(invIndex)
if (ItemStackUtil.areStacksCombinable(stack, invStack)) {
invStack.amount -= 1
return true
}
}
// TODO: consume from player inventory
return false
}
private fun storeRemainders(remainingStacks: DefaultedList<ItemStack>, inventory: Inventory,
player: PlayerEntity?): Boolean {
for (remainingStack in remainingStacks) {
if (!remainingStack.isEmpty) {
if (!storeRemainder(remainingStack, inventory, player)) {
return false
}
}
}
return true
}
private fun storeRemainder(remainingStack: ItemStack, inventory: Inventory, player: PlayerEntity?): Boolean {
for (invIndex in inputInventoryRange) {
val originalStack = inventory.getInvStack(invIndex)
if (originalStack.isEmpty) {
inventory.setInvStack(invIndex, remainingStack)
} else if (ItemStackUtil.areStacksCombinable(originalStack, remainingStack)) {
remainingStack.addAmount(originalStack.amount)
inventory.setInvStack(invIndex, remainingStack)
} else if (player != null) {
if (!player.inventory.insertStack(remainingStack)) {
player.dropItem(remainingStack, false)
}
} else {
return false
}
}
return true
}
private fun getCraftingInventory(): CraftingInventory {
val craftInv = CraftingInventory(object : Container(null, 0) {
override fun canUse(var1: PlayerEntity?) = false
override fun getType() = null
}, 3, 3)
recipeInventoryRange.forEachIndexed { index, i -> craftInv.setInvStack(index, getInvStack(i).copy()) }
return craftInv
}
private fun getRecipe(): CraftingRecipe? {
val craftInv = getCraftingInventory()
return world.recipeManager.get(RecipeType.CRAFTING, craftInv, world).orElse(null)
}
companion object {
val recipeInventoryRange = 0 until 9
val recipeResultIndex = recipeInventoryRange.endInclusive + 1
val inputInventoryRange = (recipeResultIndex + 1) until 28
}
}
| mit | 42501bccb2aa2e8dd6b9d9e23a59581c | 36.576531 | 114 | 0.643992 | 4.626256 | false | false | false | false |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/productsearch/PreviewCardAdapter.kt | 1 | 3307 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.mlkit.md.productsearch
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.google.mlkit.md.R
/** Powers the bottom card carousel for displaying the preview of product search result. */
class PreviewCardAdapter(
private val searchedObjectList: List<SearchedObject>,
private val previewCordClickedListener: (searchedObject: SearchedObject) -> Any
) : RecyclerView.Adapter<PreviewCardAdapter.CardViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
return CardViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.products_preview_card, parent, false)
)
}
override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
val searchedObject = searchedObjectList[position]
holder.bindProducts(searchedObject.productList)
holder.itemView.setOnClickListener { previewCordClickedListener.invoke(searchedObject) }
}
override fun getItemCount(): Int = searchedObjectList.size
class CardViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val imageView: ImageView = itemView.findViewById(R.id.card_image)
private val titleView: TextView = itemView.findViewById(R.id.card_title)
private val subtitleView: TextView = itemView.findViewById(R.id.card_subtitle)
private val imageSize: Int = itemView.resources.getDimensionPixelOffset(R.dimen.preview_card_image_size)
internal fun bindProducts(products: List<Product>) {
if (products.isEmpty()) {
imageView.visibility = View.GONE
titleView.setText(R.string.static_image_card_no_result_title)
subtitleView.setText(R.string.static_image_card_no_result_subtitle)
} else {
val topProduct = products[0]
imageView.visibility = View.VISIBLE
imageView.setImageDrawable(null)
if (!TextUtils.isEmpty(topProduct.imageUrl)) {
ImageDownloadTask(imageView, imageSize).execute(topProduct.imageUrl)
} else {
imageView.setImageResource(R.drawable.logo_google_cloud)
}
titleView.text = topProduct.title
subtitleView.text = itemView
.resources
.getString(R.string.static_image_preview_card_subtitle, products.size - 1)
}
}
}
}
| apache-2.0 | 1affe1e9614904d1763df1c6cce2691d | 41.948052 | 112 | 0.693378 | 4.737822 | false | false | false | false |
toadzky/dropwizard-horizon-bundle | src/main/kotlin/com/skytag/dropwizard/horizon/messages/HzStructuredRead.kt | 1 | 443 | package com.skytag.dropwizard.horizon.messages
data class HzStructuredRead(override val collection: String,
val limit: Int? = null,
val order: HzOrderingClause? = null,
val above: HzMatchingClause? = null,
val below: HzMatchingClause? = null,
val findAll: List<Map<String,Any>>? = null) : HzReadOptions | mit | 515100eaa7e38f0012c5e40f75b05193 | 54.5 | 87 | 0.530474 | 5.151163 | false | false | false | false |
QuickBlox/quickblox-android-sdk | sample-chat-kotlin/app/src/main/java/com/quickblox/sample/chat/kotlin/ui/activity/DialogsActivity.kt | 1 | 27702 | package com.quickblox.sample.chat.kotlin.ui.activity
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.os.Vibrator
import android.text.TextUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import androidx.appcompat.view.ActionMode
import androidx.core.view.get
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GoogleApiAvailability
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout
import com.quickblox.chat.QBChatService
import com.quickblox.chat.QBIncomingMessagesManager
import com.quickblox.chat.QBSystemMessagesManager
import com.quickblox.chat.exception.QBChatException
import com.quickblox.chat.listeners.QBChatDialogMessageListener
import com.quickblox.chat.listeners.QBSystemMessageListener
import com.quickblox.chat.model.QBChatDialog
import com.quickblox.chat.model.QBChatMessage
import com.quickblox.chat.model.QBDialogType
import com.quickblox.core.QBEntityCallback
import com.quickblox.core.exception.QBResponseException
import com.quickblox.core.request.QBRequestGetBuilder
import com.quickblox.messages.services.QBPushManager
import com.quickblox.messages.services.SubscribeService
import com.quickblox.sample.chat.kotlin.R
import com.quickblox.sample.chat.kotlin.async.BaseAsyncTask
import com.quickblox.sample.chat.kotlin.managers.DialogsManager
import com.quickblox.sample.chat.kotlin.ui.adapter.DialogsAdapter
import com.quickblox.sample.chat.kotlin.utils.*
import com.quickblox.sample.chat.kotlin.utils.chat.ChatHelper
import com.quickblox.sample.chat.kotlin.utils.qb.QbChatDialogMessageListenerImpl
import com.quickblox.sample.chat.kotlin.utils.qb.QbDialogHolder
import com.quickblox.sample.chat.kotlin.utils.qb.VerboseQbChatConnectionListener
import com.quickblox.sample.chat.kotlin.utils.qb.callback.QBPushSubscribeListenerImpl
import com.quickblox.sample.chat.kotlin.utils.qb.callback.QbEntityCallbackImpl
import com.quickblox.users.QBUsers
import com.quickblox.users.model.QBUser
import org.jivesoftware.smack.ConnectionListener
import java.lang.ref.WeakReference
const val DIALOGS_PER_PAGE = 100
class DialogsActivity : BaseActivity(), DialogsManager.ManagingDialogsCallbacks {
private val TAG = DialogsActivity::class.java.simpleName
private lateinit var refreshLayout: SwipyRefreshLayout
private lateinit var progress: ProgressBar
private var isProcessingResultInProgress: Boolean = false
private lateinit var pushBroadcastReceiver: BroadcastReceiver
private lateinit var chatConnectionListener: ConnectionListener
private lateinit var dialogsAdapter: DialogsAdapter
private var allDialogsMessagesListener: QBChatDialogMessageListener = AllDialogsMessageListener()
private var systemMessagesListener: SystemMessagesListener = SystemMessagesListener()
private lateinit var systemMessagesManager: QBSystemMessagesManager
private lateinit var incomingMessagesManager: QBIncomingMessagesManager
private var dialogsManager: DialogsManager = DialogsManager()
private lateinit var currentUser: QBUser
private var currentActionMode: ActionMode? = null
private var hasMoreDialogs = true
private val joinerTasksSet = HashSet<DialogJoinerAsyncTask>()
companion object {
private const val REQUEST_SELECT_PEOPLE = 174
private const val REQUEST_DIALOG_ID_FOR_UPDATE = 165
private const val PLAY_SERVICES_REQUEST_CODE = 9000
fun start(context: Context) {
val intent = Intent(context, DialogsActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dialogs)
if (!ChatHelper.isLogged()) {
reloginToChat()
}
if (ChatHelper.getCurrentUser() != null) {
currentUser = ChatHelper.getCurrentUser()!!
} else {
Log.e(TAG, "Finishing " + TAG + ". Current user is null")
finish()
}
supportActionBar?.title = getString(R.string.dialogs_logged_in_as, currentUser.fullName)
initUi()
initConnectionListener()
}
override fun onResumeFinished() {
if (ChatHelper.isLogged()) {
checkPlayServicesAvailable()
registerQbChatListeners()
if (QbDialogHolder.dialogsMap.isNotEmpty()) {
loadDialogsFromQb(true, true)
} else {
loadDialogsFromQb(false, true)
}
} else {
reloginToChat()
}
}
private fun reloginToChat() {
showProgressDialog(R.string.dlg_relogin)
if (SharedPrefsHelper.hasQbUser()) {
ChatHelper.loginToChat(SharedPrefsHelper.getQbUser()!!, object : QBEntityCallback<Void> {
override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
Log.d(TAG, "Relogin Successful")
checkPlayServicesAvailable()
registerQbChatListeners()
loadDialogsFromQb(false, false)
}
override fun onError(e: QBResponseException) {
Log.d(TAG, "Relogin Failed " + e.message)
hideProgressDialog()
showErrorSnackbar(R.string.reconnect_failed, e, View.OnClickListener { reloginToChat() })
}
})
}
}
private fun checkPlayServicesAvailable() {
val apiAvailability = GoogleApiAvailability.getInstance()
val resultCode = apiAvailability.isGooglePlayServicesAvailable(this)
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_REQUEST_CODE).show()
} else {
Log.e(TAG, "This device is not supported.")
shortToast("This device is not supported")
finish()
}
}
}
override fun onPause() {
super.onPause()
ChatHelper.removeConnectionListener(chatConnectionListener)
LocalBroadcastManager.getInstance(this).unregisterReceiver(pushBroadcastReceiver)
}
override fun onStop() {
super.onStop()
cancelTasks()
unregisterQbChatListeners()
}
override fun onDestroy() {
super.onDestroy()
unregisterQbChatListeners()
}
private fun registerQbChatListeners() {
ChatHelper.addConnectionListener(chatConnectionListener)
try {
systemMessagesManager = QBChatService.getInstance().systemMessagesManager
incomingMessagesManager = QBChatService.getInstance().incomingMessagesManager
} catch (e: Exception) {
Log.d(TAG, "Can not get SystemMessagesManager. Need relogin. " + e.message)
reloginToChat()
return
}
if (incomingMessagesManager == null) {
reloginToChat()
return
}
systemMessagesManager.addSystemMessageListener(systemMessagesListener)
incomingMessagesManager.addDialogMessageListener(allDialogsMessagesListener)
dialogsManager.addManagingDialogsCallbackListener(this)
pushBroadcastReceiver = PushBroadcastReceiver()
LocalBroadcastManager.getInstance(this).registerReceiver(pushBroadcastReceiver,
IntentFilter(ACTION_NEW_FCM_EVENT))
}
private fun unregisterQbChatListeners() {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener)
systemMessagesManager.removeSystemMessageListener(systemMessagesListener)
dialogsManager.removeManagingDialogsCallbackListener(this)
}
private fun cancelTasks() {
joinerTasksSet.iterator().forEach {
it.cancel(true)
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_activity_dialogs, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (isProcessingResultInProgress) {
return super.onOptionsItemSelected(item)
}
when (item.itemId) {
R.id.menu_dialogs_action_logout -> {
isProcessingResultInProgress = true
item.isEnabled = false
invalidateOptionsMenu()
unsubscribeFromPushes()
return true
}
R.id.menu_appinfo -> {
AppInfoActivity.start(this)
return true
}
R.id.menu_add_chat -> {
showProgressDialog(R.string.dlg_loading)
SelectUsersActivity.startForResult(this, REQUEST_SELECT_PEOPLE, null)
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
@Suppress("UNCHECKED_CAST")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Log.d(TAG, "onActivityResult with ResultCode: $resultCode RequestCode: $requestCode")
if (resultCode == Activity.RESULT_OK) {
when (requestCode) {
REQUEST_SELECT_PEOPLE -> {
val selectedUsers = data?.getSerializableExtra(EXTRA_QB_USERS) as ArrayList<QBUser>
var chatName = data.getStringExtra(EXTRA_CHAT_NAME)
if (isPrivateDialogExist(selectedUsers)) {
selectedUsers.remove(ChatHelper.getCurrentUser())
val existingPrivateDialog = QbDialogHolder.getPrivateDialogWithUser(selectedUsers[0])
isProcessingResultInProgress = false
existingPrivateDialog?.let {
ChatActivity.startForResult(this, REQUEST_DIALOG_ID_FOR_UPDATE, it)
}
} else {
showProgressDialog(R.string.create_chat)
if (TextUtils.isEmpty(chatName)) {
chatName = ""
}
createDialog(selectedUsers, chatName!!)
}
}
REQUEST_DIALOG_ID_FOR_UPDATE -> {
if (data?.getStringExtra(EXTRA_DIALOG_ID) != null) {
val dialogId = data.getStringExtra(EXTRA_DIALOG_ID)
loadUpdatedDialog(dialogId!!)
} else {
isProcessingResultInProgress = false
loadDialogsFromQb(true, false)
}
}
}
} else {
updateDialogsAdapter()
}
}
private fun isPrivateDialogExist(allSelectedUsers: ArrayList<QBUser>): Boolean {
val selectedUsers = ArrayList<QBUser>()
selectedUsers.addAll(allSelectedUsers)
selectedUsers.remove(ChatHelper.getCurrentUser())
return selectedUsers.size == 1 && QbDialogHolder.hasPrivateDialogWithUser(selectedUsers[0])
}
private fun loadUpdatedDialog(dialogId: String) {
ChatHelper.getDialogById(dialogId, object : QbEntityCallbackImpl<QBChatDialog>() {
override fun onSuccess(result: QBChatDialog, bundle: Bundle?) {
QbDialogHolder.addDialog(result)
updateDialogsAdapter()
isProcessingResultInProgress = false
}
override fun onError(e: QBResponseException) {
isProcessingResultInProgress = false
}
})
}
override fun startSupportActionMode(callback: ActionMode.Callback): ActionMode? {
currentActionMode = super.startSupportActionMode(callback)
return currentActionMode
}
private fun userLogout() {
Log.d(TAG, "SignOut")
QBUsers.signOut().performAsync(object : QBEntityCallback<Void> {
override fun onSuccess(aVoid: Void?, bundle: Bundle?) {
ChatHelper.destroy()
SharedPrefsHelper.removeQbUser()
QbDialogHolder.clear()
LoginActivity.start(this@DialogsActivity)
hideProgressDialog()
finish()
}
override fun onError(e: QBResponseException?) {
Log.d(TAG, "Unable to SignOut: " + e?.message)
hideProgressDialog()
showErrorSnackbar(R.string.error_logout, e, View.OnClickListener { userLogout() })
}
})
}
private fun unsubscribeFromPushes() {
showProgressDialog(R.string.dlg_logout)
if (QBPushManager.getInstance().isSubscribedToPushes) {
QBPushManager.getInstance().addListener(object : QBPushSubscribeListenerImpl() {
override fun onSubscriptionDeleted(success: Boolean) {
Log.d(TAG, "Subscription Deleted")
QBPushManager.getInstance().removeListener(this)
userLogout()
}
})
SubscribeService.unSubscribeFromPushes(this@DialogsActivity)
} else {
userLogout()
}
}
private fun initUi() {
val emptyHintLayout = findViewById<LinearLayout>(R.id.ll_chat_empty)
val dialogsListView: ListView = findViewById(R.id.list_dialogs_chats)
refreshLayout = findViewById(R.id.swipy_refresh_layout)
progress = findViewById(R.id.pb_dialogs)
val dialogs = ArrayList(QbDialogHolder.dialogsMap.values)
dialogsAdapter = DialogsAdapter(this, dialogs)
dialogsListView.emptyView = emptyHintLayout
dialogsListView.adapter = dialogsAdapter
dialogsListView.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
val selectedDialog = parent.getItemAtPosition(position) as QBChatDialog
if (currentActionMode != null) {
dialogsAdapter.toggleSelection(selectedDialog)
var subtitle = ""
if (dialogsAdapter.selectedItems.size != 1) {
subtitle = getString(R.string.dialogs_actionmode_subtitle, dialogsAdapter.selectedItems.size.toString())
} else {
subtitle = getString(R.string.dialogs_actionmode_subtitle_single, dialogsAdapter.selectedItems.size.toString())
}
currentActionMode!!.subtitle = subtitle
currentActionMode!!.menu.get(0).isVisible = (dialogsAdapter.selectedItems.size >= 1)
} else if (ChatHelper.isLogged()) {
showProgressDialog(R.string.dlg_loading)
ChatActivity.startForResult(this, REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog)
} else {
showProgressDialog(R.string.dlg_login)
ChatHelper.loginToChat(currentUser,
object : QBEntityCallback<Void> {
override fun onSuccess(p0: Void?, p1: Bundle?) {
hideProgressDialog()
ChatActivity.startForResult(this@DialogsActivity, REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog)
}
override fun onError(e: QBResponseException?) {
hideProgressDialog()
shortToast(R.string.login_chat_login_error)
}
})
}
}
dialogsListView.setOnItemLongClickListener { parent, view, position, id ->
val selectedDialog = parent.getItemAtPosition(position) as QBChatDialog
startSupportActionMode(DeleteActionModeCallback())
dialogsAdapter.selectItem(selectedDialog)
return@setOnItemLongClickListener true
}
refreshLayout.setOnRefreshListener {
cancelTasks()
loadDialogsFromQb(silentUpdate = true, clearDialogHolder = true)
}
refreshLayout.setColorSchemeResources(R.color.color_new_blue, R.color.random_color_2, R.color.random_color_3, R.color.random_color_7)
}
private fun createDialog(selectedUsers: ArrayList<QBUser>, chatName: String) {
ChatHelper.createDialogWithSelectedUsers(selectedUsers, chatName,
object : QBEntityCallback<QBChatDialog> {
override fun onSuccess(dialog: QBChatDialog, args: Bundle?) {
Log.d(TAG, "Creating Dialog Successful")
isProcessingResultInProgress = false
dialogsManager.sendSystemMessageAboutCreatingDialog(systemMessagesManager, dialog)
val dialogs = ArrayList<QBChatDialog>()
dialogs.add(dialog)
QbDialogHolder.addDialogs(dialogs)
DialogJoinerAsyncTask(this@DialogsActivity, dialogs).execute()
ChatActivity.startForResult(this@DialogsActivity, REQUEST_DIALOG_ID_FOR_UPDATE, dialog, true)
hideProgressDialog()
}
override fun onError(error: QBResponseException) {
Log.d(TAG, "Creating Dialog Error: " + error.message)
isProcessingResultInProgress = false
hideProgressDialog()
showErrorSnackbar(R.string.dialogs_creation_error, error, null)
}
}
)
}
private fun loadDialogsFromQb(silentUpdate: Boolean, clearDialogHolder: Boolean) {
isProcessingResultInProgress = true
if (silentUpdate) {
progress.visibility = View.VISIBLE
} else {
showProgressDialog(R.string.dlg_loading)
}
val requestBuilder = QBRequestGetBuilder()
requestBuilder.limit = DIALOGS_PER_PAGE
requestBuilder.skip = if (clearDialogHolder) {
0
} else {
QbDialogHolder.dialogsMap.size
}
ChatHelper.getDialogs(requestBuilder, object : QBEntityCallback<ArrayList<QBChatDialog>> {
override fun onSuccess(dialogs: ArrayList<QBChatDialog>, bundle: Bundle?) {
if (dialogs.size < DIALOGS_PER_PAGE) {
hasMoreDialogs = false
}
if (clearDialogHolder) {
QbDialogHolder.clear()
hasMoreDialogs = true
}
QbDialogHolder.addDialogs(dialogs)
updateDialogsAdapter()
val joinerTask = DialogJoinerAsyncTask(this@DialogsActivity, dialogs)
joinerTasksSet.add(joinerTask)
joinerTask.execute()
disableProgress()
if (hasMoreDialogs) {
loadDialogsFromQb(true, false)
}
}
override fun onError(e: QBResponseException) {
disableProgress()
shortToast(e.message)
}
})
}
private fun disableProgress() {
isProcessingResultInProgress = false
hideProgressDialog()
refreshLayout.isRefreshing = false
progress.visibility = View.GONE
}
private fun initConnectionListener() {
val rootView: View = findViewById(R.id.layout_root)
chatConnectionListener = object : VerboseQbChatConnectionListener(rootView) {
override fun reconnectionSuccessful() {
super.reconnectionSuccessful()
loadDialogsFromQb(false, true)
}
}
}
private fun updateDialogsAdapter() {
val listDialogs = ArrayList(QbDialogHolder.dialogsMap.values)
dialogsAdapter.updateList(listDialogs)
}
override fun onDialogCreated(chatDialog: QBChatDialog) {
loadDialogsFromQb(true, true)
}
override fun onDialogUpdated(chatDialog: String) {
updateDialogsAdapter()
}
override fun onNewDialogLoaded(chatDialog: QBChatDialog) {
updateDialogsAdapter()
}
private inner class DeleteActionModeCallback internal constructor() : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
val vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
vibrator.vibrate(80)
mode.title = getString(R.string.dialogs_actionmode_title)
mode.subtitle = getString(R.string.dialogs_actionmode_subtitle_single, "1")
mode.menuInflater.inflate(R.menu.menu_activity_dialogs_action_mode, menu)
val menuItem = menu.findItem(R.id.menu_dialogs_action_delete)
if (menuItem != null && menuItem is TextView) {
}
dialogsAdapter.prepareToSelect()
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
return false
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_dialogs_action_delete -> {
deleteSelected()
currentActionMode?.finish()
return true
}
}
return false
}
override fun onDestroyActionMode(mode: ActionMode) {
currentActionMode = null
dialogsAdapter.clearSelection()
}
private fun deleteSelected() {
showProgressDialog(R.string.dlg_deleting_chats)
val selectedDialogs = dialogsAdapter.selectedItems
val groupDialogsToDelete = ArrayList<QBChatDialog>()
val privateDialogsToDelete = ArrayList<QBChatDialog>()
for (dialog in selectedDialogs) {
if (dialog.type == QBDialogType.PUBLIC_GROUP) {
shortToast(getString(R.string.dialogs_cannot_delete_chat, dialog.name))
} else if (dialog.type == QBDialogType.GROUP) {
groupDialogsToDelete.add(dialog)
} else if (dialog.type == QBDialogType.PRIVATE) {
privateDialogsToDelete.add(dialog)
}
}
if (privateDialogsToDelete.size > 0) {
deletePrivateDialogs(privateDialogsToDelete)
}
if (groupDialogsToDelete.size > 0) {
notifyDialogsLeave(groupDialogsToDelete)
leaveGroupDialogs(groupDialogsToDelete)
} else {
hideProgressDialog()
}
}
private fun deletePrivateDialogs(privateDialogsToDelete: List<QBChatDialog>) {
ChatHelper.deletePrivateDialogs(privateDialogsToDelete, object : QBEntityCallback<ArrayList<String>> {
override fun onSuccess(dialogsIds: ArrayList<String>, bundle: Bundle?) {
Log.d(TAG, "PRIVATE Dialogs Deleting Successful")
QbDialogHolder.deleteDialogs(dialogsIds)
updateDialogsAdapter()
}
override fun onError(e: QBResponseException) {
Log.d(TAG, "Deleting PRIVATE Dialogs Error: " + e.message)
showErrorSnackbar(R.string.dialogs_deletion_error, e,
View.OnClickListener { deletePrivateDialogs(privateDialogsToDelete) })
}
})
}
private fun leaveGroupDialogs(groupDialogsToDelete: List<QBChatDialog>) {
ChatHelper.leaveGroupDialogs(groupDialogsToDelete, object : QBEntityCallback<List<QBChatDialog>> {
override fun onSuccess(qbChatDialogs: List<QBChatDialog>, bundle: Bundle?) {
Log.d(TAG, "GROUP Dialogs Deleting Successful")
QbDialogHolder.deleteDialogs(qbChatDialogs)
updateDialogsAdapter()
hideProgressDialog()
}
override fun onError(e: QBResponseException) {
hideProgressDialog()
Log.d(TAG, "Deleting GROUP Dialogs Error: " + e.message)
longToast(R.string.dialogs_deletion_error)
}
})
}
private fun notifyDialogsLeave(dialogsToNotify: List<QBChatDialog>) {
for (dialog in dialogsToNotify) {
dialogsManager.sendMessageLeftUser(dialog)
dialogsManager.sendSystemMessageLeftUser(systemMessagesManager, dialog)
try {
// Its a hack to give the Chat Server more time to process the message and deliver them
Thread.sleep(300)
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}
}
private inner class PushBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// Get extra data included in the Intent
val message = intent.getStringExtra(EXTRA_FCM_MESSAGE)
Log.v(TAG, "Received broadcast " + intent.action + " with data: " + message)
loadDialogsFromQb(false, false)
}
}
private inner class SystemMessagesListener : QBSystemMessageListener {
override fun processMessage(qbChatMessage: QBChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage)
}
override fun processError(e: QBChatException, qbChatMessage: QBChatMessage) {
}
}
private inner class AllDialogsMessageListener : QbChatDialogMessageListenerImpl() {
override fun processMessage(dialogID: String, qbChatMessage: QBChatMessage, senderID: Int?) {
Log.d(TAG, "Processing received Message: " + qbChatMessage.body)
if (senderID != currentUser.id) {
dialogsManager.onGlobalMessageReceived(dialogID, qbChatMessage)
}
}
}
private class DialogJoinerAsyncTask internal constructor(dialogsActivity: DialogsActivity,
private val dialogs: ArrayList<QBChatDialog>) : BaseAsyncTask<Void, Void, Void>() {
private val activityRef: WeakReference<DialogsActivity> = WeakReference(dialogsActivity)
@Throws(Exception::class)
override fun performInBackground(vararg params: Void): Void? {
if (!isCancelled) {
ChatHelper.join(dialogs)
}
return null
}
override fun onResult(result: Void?) {
if (!isCancelled && !activityRef.get()?.hasMoreDialogs!!) {
activityRef.get()?.disableProgress()
} else {
}
}
override fun onException(e: Exception) {
super.onException(e)
if (!isCancelled) {
Log.d("Dialog Joiner Task", "Error: $e")
shortToast("Error: " + e.message)
}
}
override fun onCancelled() {
super.onCancelled()
cancel(true)
}
}
} | bsd-3-clause | 5757ca8cafeff13d19f06662c7685e7b | 40.163447 | 144 | 0.620388 | 5.350975 | false | false | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/constant/DoKitModule.kt | 1 | 394 | package com.didichuxing.doraemonkit.constant
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2021/6/17-16:05
* 描 述:
* 修订历史:
* ================================================
*/
enum class DoKitModule {
MODULE_FT,
MODULE_MC,
MODULE_RPC_MC,
MODULE_DMAP,
MODULE_GPS_MOCK
}
| apache-2.0 | 785d673ce0fa52a9da8b23a70b989cd4 | 18.333333 | 51 | 0.41092 | 3.515152 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/data/Geofence.kt | 1 | 3891 | package org.tasks.data
import android.os.Parcel
import android.os.Parcelable
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Ignore
import androidx.room.PrimaryKey
import com.todoroo.andlib.data.Table
import com.todoroo.astrid.data.Task
import org.tasks.R
import org.tasks.preferences.Preferences
import java.io.Serializable
@Entity(
tableName = Geofence.TABLE_NAME,
foreignKeys = [
ForeignKey(
entity = Task::class,
parentColumns = ["_id"],
childColumns = ["task"],
onDelete = ForeignKey.CASCADE,
),
]
)
class Geofence : Serializable, Parcelable {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "geofence_id")
@Transient
var id: Long = 0
@ColumnInfo(name = "task", index = true)
@Transient
var task: Long = 0
@ColumnInfo(name = "place")
var place: String? = null
@ColumnInfo(name = "arrival")
var isArrival = false
@ColumnInfo(name = "departure")
var isDeparture = false
constructor()
@Ignore
constructor(task: Long, place: String?, arrival: Boolean, departure: Boolean) : this(place, arrival, departure) {
this.task = task
}
@Ignore
constructor(place: String?, preferences: Preferences) {
this.place = place
val defaultReminders = preferences.getIntegerFromString(R.string.p_default_location_reminder_key, 1)
isArrival = defaultReminders == 1 || defaultReminders == 3
isDeparture = defaultReminders == 2 || defaultReminders == 3
}
@Ignore
constructor(place: String?, arrival: Boolean, departure: Boolean) {
this.place = place
isArrival = arrival
isDeparture = departure
}
@Ignore
constructor(o: Geofence) {
id = o.id
task = o.task
place = o.place
isArrival = o.isArrival
isDeparture = o.isDeparture
}
@Ignore
constructor(parcel: Parcel) {
id = parcel.readLong()
task = parcel.readLong()
place = parcel.readString()
isArrival = parcel.readInt() == 1
isDeparture = parcel.readInt() == 1
}
override fun describeContents() = 0
override fun writeToParcel(out: Parcel, flags: Int) {
with(out) {
writeLong(id)
writeLong(task)
writeString(place)
writeInt(if (isArrival) 1 else 0)
writeInt(if (isDeparture) 1 else 0)
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Geofence) return false
if (id != other.id) return false
if (task != other.task) return false
if (place != other.place) return false
if (isArrival != other.isArrival) return false
if (isDeparture != other.isDeparture) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + task.hashCode()
result = 31 * result + (place?.hashCode() ?: 0)
result = 31 * result + isArrival.hashCode()
result = 31 * result + isDeparture.hashCode()
return result
}
override fun toString(): String =
"Geofence(id=$id, task=$task, place=$place, isArrival=$isArrival, isDeparture=$isDeparture)"
companion object {
const val TABLE_NAME = "geofences"
@JvmField val TABLE = Table(TABLE_NAME)
@JvmField val TASK = TABLE.column("task")
@JvmField val PLACE = TABLE.column("place")
@JvmField val CREATOR: Parcelable.Creator<Geofence> = object : Parcelable.Creator<Geofence> {
override fun createFromParcel(source: Parcel): Geofence = Geofence(source)
override fun newArray(size: Int): Array<Geofence?> = arrayOfNulls(size)
}
}
} | gpl-3.0 | 56b761ae8e436ea3c998d09c3322d9d0 | 28.044776 | 117 | 0.619378 | 4.332962 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/main/kotlin/org/jitsi/videobridge/stats/StatsCollector.kt | 1 | 5913 | /*
* Copyright @ 2015 - Present, 8x8 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 org.jitsi.videobridge.stats
import org.jitsi.utils.concurrent.PeriodicRunnableWithObject
import org.jitsi.utils.concurrent.RecurringRunnableExecutor
import org.jitsi.videobridge.stats.config.StatsManagerConfig
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicBoolean
/**
* [StatsCollector] periodically collects statistics by calling [Statistics.generate] on [statistics], and periodically
* pushes the latest collected statistics to the [StatsTransport]s that have been added to it.
*
* @author Hristo Terezov
* @author Lyubomir Marinov
*/
class StatsCollector(
/**
* The instance which can collect statistics via [Statistics.generate]. The [StatsCollector] invokes this
* periodically.
*/
val statistics: Statistics
) {
/**
* The [RecurringRunnableExecutor] which periodically invokes [statisticsRunnable].
*/
private val statisticsExecutor = RecurringRunnableExecutor(
StatsCollector::class.java.simpleName + "-statisticsExecutor"
)
/**
* The [RecurringRunnableExecutor] which periodically invokes [transportRunnables].
*/
private val transportExecutor = RecurringRunnableExecutor(
StatsCollector::class.java.simpleName + "-transportExecutor"
)
/**
* The periodic runnable which collects statistics by invoking `statistics.generate()`.
*/
private val statisticsRunnable: StatisticsPeriodicRunnable
/**
* The runnables which periodically push statistics to the [StatsTransport]s that have been added.
*/
private val transportRunnables: MutableList<TransportPeriodicRunnable> = CopyOnWriteArrayList()
private val running = AtomicBoolean()
init {
val period = config.interval.toMillis()
require(period >= 1) { "period $period" }
statisticsRunnable = StatisticsPeriodicRunnable(statistics, period)
}
/**
* Adds a specific <tt>StatsTransport</tt> through which this [StatsCollector] is to periodically send statistics.
*
* @param transport the [StatsTransport] to add
* @param updatePeriodMs the period in milliseconds at which this [StatsCollector] is to repeatedly send statistics
* to the specified [transport].
*/
fun addTransport(transport: StatsTransport, updatePeriodMs: Long) {
require(updatePeriodMs >= 1) { "period $updatePeriodMs" }
TransportPeriodicRunnable(transport, updatePeriodMs).also {
transportRunnables.add(it)
if (running.get()) {
transportExecutor.registerRecurringRunnable(it)
}
}
}
fun removeTransport(transport: StatsTransport) {
val runnable = transportRunnables.find { it.o == transport }
runnable?.let {
transportExecutor.deRegisterRecurringRunnable(it)
transportRunnables.remove(it)
}
}
/**
* {@inheritDoc}
*
* Starts the [StatsTransport]s added to this [StatsCollector]. Commences the collection of statistics.
*/
fun start() {
if (running.compareAndSet(false, true)) {
// Register statistics and transports with their respective RecurringRunnableExecutor in order to have them
// periodically executed.
statisticsExecutor.registerRecurringRunnable(statisticsRunnable)
transportRunnables.forEach { transportExecutor.registerRecurringRunnable(it) }
}
}
/**
* {@inheritDoc}
*
* Stops the [StatsTransport]s added to this [StatsCollector] and the [StatisticsPeriodicRunnable].
*/
fun stop() {
if (running.compareAndSet(true, false)) {
// De-register statistics and transports from their respective
// RecurringRunnableExecutor in order to have them no longer
// periodically executed.
statisticsExecutor.deRegisterRecurringRunnable(statisticsRunnable)
// Stop the StatTransports added to this StatsManager
transportRunnables.forEach { transportExecutor.deRegisterRecurringRunnable(it) }
transportRunnables.clear()
}
}
/**
* Implements a [RecurringRunnable] which periodically collects statistics from a specific [Statistics].
*/
private class StatisticsPeriodicRunnable(statistics: Statistics, period: Long) :
PeriodicRunnableWithObject<Statistics>(statistics, period) {
override fun doRun() {
o.generate()
}
}
/**
* Implements a [RecurringRunnable] which periodically publishes statistics through a specific [StatsTransport].
*/
private inner class TransportPeriodicRunnable(transport: StatsTransport, period: Long) :
PeriodicRunnableWithObject<StatsTransport>(transport, period) {
override fun doRun() {
// FIXME measurementInterval was meant to be the actual interval of time that the information of the
// Statistics covers. However, it became difficult after a refactoring to calculate measurementInterval.
val measurementInterval = period
o.publishStatistics(statisticsRunnable.o, measurementInterval)
}
}
companion object {
@JvmField
val config = StatsManagerConfig()
}
}
| apache-2.0 | 128b12baedf9679585e30bda5fee0cd8 | 36.903846 | 119 | 0.693726 | 5.028061 | false | false | false | false |
arturbosch/detekt | detekt-metrics/src/main/kotlin/io/github/detekt/metrics/processors/ProjectSLOCProcessor.kt | 1 | 920 | package io.github.detekt.metrics.processors
import io.gitlab.arturbosch.detekt.api.DetektVisitor
import org.jetbrains.kotlin.com.intellij.openapi.util.Key
import org.jetbrains.kotlin.psi.KtFile
class ProjectSLOCProcessor : AbstractProcessor() {
override val visitor: DetektVisitor = SLOCVisitor()
override val key: Key<Int> = sourceLinesKey
}
class SLOCVisitor : DetektVisitor() {
override fun visitKtFile(file: KtFile) {
val lines = file.text.split('\n')
val sloc = SLOC().count(lines)
file.putUserData(sourceLinesKey, sloc)
}
private class SLOC {
private val comments = arrayOf("//", "/*", "*/", "*")
fun count(lines: List<String>): Int {
return lines
.map { it.trim() }
.count { trim -> trim.isNotEmpty() && !comments.any { trim.startsWith(it) } }
}
}
}
val sourceLinesKey = Key<Int>("sloc")
| apache-2.0 | 365b8f515d8fee78c7838b97744a0675 | 26.878788 | 93 | 0.63587 | 3.948498 | false | false | false | false |
aglne/mycollab | mycollab-dao/src/main/java/org/mybatis/scripting/velocity/Ifnotnull.kt | 3 | 1602 | package org.mybatis.scripting.velocity
import org.apache.velocity.context.InternalContextAdapter
import org.apache.velocity.exception.MethodInvocationException
import org.apache.velocity.exception.ParseErrorException
import org.apache.velocity.exception.ResourceNotFoundException
import org.apache.velocity.runtime.directive.Directive
import org.apache.velocity.runtime.directive.DirectiveConstants
import org.apache.velocity.runtime.parser.node.Node
import java.io.IOException
import java.io.Writer
/**
* @author MyCollab Ltd.
* @since 4.0
*/
class Ifnotnull : Directive() {
/*
* (non-Javadoc)
*
* @see org.apache.velocity.runtime.directive.Directive#getName()
*/
override fun getName(): String = "ifnotnull"
/*
* (non-Javadoc)
*
* @see org.apache.velocity.runtime.directive.Directive#getType()
*/
override fun getType(): Int = DirectiveConstants.BLOCK
/*
* (non-Javadoc)
*
* @see
* org.apache.velocity.runtime.directive.Directive#render(org.apache.velocity
* .context.InternalContextAdapter, java.io.Writer,
* org.apache.velocity.runtime.parser.node.Node)
*/
@Throws(IOException::class, ResourceNotFoundException::class, ParseErrorException::class, MethodInvocationException::class)
override fun render(context: InternalContextAdapter, writer: Writer, node: Node): Boolean {
val value = node.jjtGetChild(0).value(context)
if (value != null) {
val content = node.jjtGetChild(1)
content.render(context, writer)
}
return true
}
}
| agpl-3.0 | 2af67f7ba7834261bfe246946d403399 | 29.807692 | 127 | 0.707865 | 4.055696 | false | false | false | false |
equeim/tremotesf-android | common/src/main/kotlin/org/equeim/tremotesf/common/AlphanumericComparator.kt | 1 | 3794 | /*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tremotesf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.equeim.tremotesf.common
import java.text.Collator
import kotlin.math.sign
class AlphanumericComparator : Comparator<String> {
private val collator = Collator.getInstance()
override fun compare(s1: String?, s2: String?): Int {
if (s1 == null) {
return if (s2 == null) {
0
} else {
-1
}
}
if (s2 == null) {
return 1
}
if (s1.isEmpty()) {
return if (s2.isEmpty()) {
0
} else {
-1
}
}
if (s2.isEmpty()) {
return 1
}
var s1Index = 0
val s1Length = s1.length
var s1Slice = ""
var s2Index = 0
val s2Length = s2.length
var s2Slice = ""
var result = 0
while (s1Index < s1Length && s2Index < s2Length) {
val s1IsDigit = isDigit(s1[s1Index])
val s2IsDigit = isDigit(s2[s2Index])
if (s1IsDigit) {
if (s2IsDigit) {
s1Slice = slice(s1, s1Length, s1Index, true)
s2Slice = slice(s2, s2Length, s2Index, true)
val s1Number: Long
try {
s1Number = s1Slice.toLong()
} catch (e: NumberFormatException) {
result = 1
break
}
val s2Number: Long
try {
s2Number = s2Slice.toLong()
} catch (e: NumberFormatException) {
result = -1
break
}
result = (s1Number - s2Number).sign
} else {
result = -1
}
} else if (s2IsDigit) {
result = 1
} else {
s1Slice = slice(s1, s1Length, s1Index, false)
s2Slice = slice(s2, s2Length, s2Index, false)
result = collator.compare(s1Slice, s2Slice)
}
if (result != 0) {
break
}
s1Index += s1Slice.length
s2Index += s2Slice.length
}
if (result == 0) {
return s1Length - s2Length
}
return result
}
// This method supports only ASCII digits
// Character.isDigit() is too slow on Android due to native
// method call.
// You can replace it with Character.isDigit() if you
// want to use this class with OpenJDK
private fun isDigit(ch: Char) = ch in '0'..'9'
private fun slice(s: String, length: Int, index: Int, digit: Boolean): String {
var i = index + 1
while (i < length) {
if (isDigit(s[i]) != digit) {
break
}
++i
}
if (index == 0 && i == length) {
return s
}
return s.substring(index, i)
}
}
| gpl-3.0 | 1fbf5fff50f0ae3d8c9bfbd67796cce1 | 27.526316 | 83 | 0.48893 | 4.234375 | false | false | false | false |
cashapp/sqldelight | dialects/sqlite-3-24/src/main/kotlin/app/cash/sqldelight/dialects/sqlite_3_24/grammar/mixins/UpsertClauseMixin.kt | 1 | 1516 | package app.cash.sqldelight.dialects.sqlite_3_24.grammar.mixins
import app.cash.sqldelight.dialects.sqlite_3_24.grammar.psi.SqliteUpsertClause
import app.cash.sqldelight.dialects.sqlite_3_24.grammar.psi.SqliteUpsertConflictTarget
import app.cash.sqldelight.dialects.sqlite_3_24.grammar.psi.SqliteUpsertDoUpdate
import com.alecstrong.sql.psi.core.psi.QueryElement
import com.alecstrong.sql.psi.core.psi.SqlCompositeElementImpl
import com.alecstrong.sql.psi.core.psi.SqlInsertStmt
import com.alecstrong.sql.psi.core.psi.mixins.SingleRow
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
internal abstract class UpsertClauseMixin(
node: ASTNode,
) : SqlCompositeElementImpl(node),
SqliteUpsertClause {
override fun queryAvailable(child: PsiElement): Collection<QueryElement.QueryResult> {
val insertStmt = (this.parent as SqlInsertStmt)
val tableName = insertStmt.tableName
val table = tablesAvailable(this).first { it.tableName.name == tableName.name }.query
if (child is SqliteUpsertConflictTarget) {
return super.queryAvailable(child)
}
if (child is SqliteUpsertDoUpdate) {
val excludedTable = QueryElement.QueryResult(
SingleRow(
tableName,
"excluded",
),
table.columns,
synthesizedColumns = table.synthesizedColumns,
)
val available = arrayListOf(excludedTable)
available += super.queryAvailable(child)
return available
}
return super.queryAvailable(child)
}
}
| apache-2.0 | 647eae0b4fb3bccb5d76c3e8f389658b | 33.454545 | 89 | 0.754617 | 4.086253 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/test/kotlin/co/nums/intellij/aem/htl/documentation/HtlListPropertiesInBracketAccessDocumentationProviderTest.kt | 1 | 2117 | package co.nums.intellij.aem.htl.documentation
import co.nums.intellij.aem.htl.DOLLAR
class HtlListPropertiesInBracketAccessDocumentationProviderTest : HtlDocumentationProviderTestBase() {
fun testIndexPredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['index']}
^
""",
"<code>Number</code><p>zero-based counter (<code>0..length-1</code>)</p>"
)
fun testCountPredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['count']}
^
""",
"<code>Number</code><p>one-based counter (<code>1..length</code>)</p>"
)
fun testFirstPredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['first']}
^
""",
"<code>Boolean</code><p><code>true</code> for the first element being iterated</p>"
)
fun testMiddlePredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['middle']}
^
""",
"<code>Boolean</code><p><code>true</code> if element being iterated is neither the first nor the last</p>"
)
fun testLastPredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['last']}
^
""",
"<code>Boolean</code><p><code>true</code> for the last element being iterated</p>"
)
fun testOddPredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['odd']}
^
""",
"<code>Boolean</code><p><code>true</code> if index is odd</p>"
)
fun testEvenPredefinedPropertyDoc() = doTestWithDollarConstant(
"""
$DOLLAR{properties['even']}
^
""",
"<code>Boolean</code><p><code>true</code> if index is even</p>"
)
}
| gpl-3.0 | d140fc08c94571924606fd1391cdd45c | 32.603175 | 118 | 0.510156 | 4.911833 | false | true | false | false |
panpf/sketch | sketch-extensions/src/main/java/com/github/panpf/sketch/request/PauseLoadWhenScrollingDrawableDecodeInterceptor.kt | 1 | 2521 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.request
import com.github.panpf.sketch.decode.DrawableDecodeInterceptor
import com.github.panpf.sketch.decode.DrawableDecodeInterceptor.Chain
import com.github.panpf.sketch.decode.DrawableDecodeResult
import com.github.panpf.sketch.util.PauseLoadWhenScrollingMixedScrollListener
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.first
/**
* Pause loading new images while the list is scrolling
*
* @see DisplayRequest.Builder.pauseLoadWhenScrolling
* @see PauseLoadWhenScrollingMixedScrollListener
*/
class PauseLoadWhenScrollingDrawableDecodeInterceptor(override val sortWeight: Int = 0) : DrawableDecodeInterceptor {
companion object {
private val scrollingFlow = MutableStateFlow(false)
var scrolling: Boolean
get() = scrollingFlow.value
set(value) {
scrollingFlow.value = value
}
}
var enabled = true
override val key: String? = null
override suspend fun intercept(chain: Chain): DrawableDecodeResult {
val request = chain.request
if (enabled
&& request is DisplayRequest
&& request.isPauseLoadWhenScrolling
&& !request.isIgnoredPauseLoadWhenScrolling
&& scrollingFlow.value
) {
scrollingFlow.filter { !it }.first()
}
return chain.proceed()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PauseLoadWhenScrollingDrawableDecodeInterceptor) return false
if (sortWeight != other.sortWeight) return false
return true
}
override fun hashCode(): Int {
return sortWeight
}
override fun toString(): String = "PauseLoadWhenScrollingDrawableDecodeInterceptor(sortWeight=$sortWeight,enabled=$enabled)"
} | apache-2.0 | 8a2d233e737984cd5f1b4bf5e162dc91 | 33.547945 | 128 | 0.712812 | 4.71215 | false | false | false | false |
icapps/niddler-ui | client-lib/src/main/kotlin/com/icapps/niddler/lib/model/classifier/BodyParser.kt | 1 | 6035 | package com.icapps.niddler.lib.model.classifier
import com.google.gson.JsonParser
import com.icapps.niddler.lib.model.BodyFormat
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.File
import java.io.InputStreamReader
import java.net.URLDecoder
import java.nio.charset.Charset
import javax.imageio.ImageIO
import javax.xml.parsers.DocumentBuilderFactory
/**
* @author nicolaverbeeck
*/
class BodyParser(private val initialBodyFormat: BodyFormat, private val bodyBytes: ByteArray?) {
private companion object {
private const val SPACE = 32.toByte()
private const val LF = 10.toByte()
private const val CR = 13.toByte()
private const val TAB = 9.toByte()
}
fun determineBodyType(): ConcreteBody? {
if (bodyBytes == null || bodyBytes.isEmpty())
return ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype, data = null)
if (initialBodyFormat.type == BodyFormatType.FORMAT_BINARY || initialBodyFormat.type == BodyFormatType.FORMAT_EMPTY)
return determineBodyFromContent(bodyBytes) ?: ConcreteBody(initialBodyFormat.type,
initialBodyFormat.subtype,
data = bodyBytes)
return when (initialBodyFormat.type) {
BodyFormatType.FORMAT_JSON -> ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype, examineJson(bodyBytes))
BodyFormatType.FORMAT_XML -> ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype, examineXML(bodyBytes))
BodyFormatType.FORMAT_PLAIN, BodyFormatType.FORMAT_HTML ->
ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype,
String(bodyBytes, Charset.forName(initialBodyFormat.encoding ?: Charsets.UTF_8.name())))
BodyFormatType.FORMAT_IMAGE ->
createImage(bodyBytes)
BodyFormatType.FORMAT_EMPTY ->
ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype, null)
BodyFormatType.FORMAT_FORM_ENCODED ->
ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype, examineFormEncoded(bodyBytes))
else -> null
}
}
private fun determineBodyFromContent(content: ByteArray): ConcreteBody? {
val firstReasonableTextByte = findFirstNonBlankByte(content)
when (firstReasonableTextByte) {
'{'.toByte(), '['.toByte() ->
return ConcreteBody(BodyFormatType.FORMAT_JSON, "application/json", examineJson(content))
'<'.toByte() ->
examineXML(content)?.let { xmlData ->
return if (firstBytesContainHtml(content, "html"))
ConcreteBody(BodyFormatType.FORMAT_HTML, "text/html", xmlData)
else
ConcreteBody(BodyFormatType.FORMAT_XML, "application/xml", xmlData) //TODO image svg
}
}
return null
}
private fun findFirstNonBlankByte(bytes: ByteArray): Byte? {
val index = bytes.indexOfFirst { it != SPACE || it != CR || it != LF || it != TAB }
return bytes.getOrNull(index)
}
private fun examineJson(bodyAsBytes: ByteArray?): Any? {
if (bodyAsBytes == null || bodyAsBytes.isEmpty()) return null
try {
return JsonParser().parse(InputStreamReader(ByteArrayInputStream(bodyAsBytes), Charsets.UTF_8))
} catch (e: Exception) {
return null
}
}
private fun examineXML(bodyAsBytes: ByteArray?): Any? {
if (bodyAsBytes == null || bodyAsBytes.isEmpty()) return null
try {
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(ByteArrayInputStream(bodyAsBytes))
} catch (e: Exception) {
return null
}
}
private fun examineFormEncoded(bodyAsBytes: ByteArray?): Any? {
if (bodyAsBytes == null || bodyAsBytes.isEmpty()) return null
val map: MutableMap<String, String> = mutableMapOf()
String(bodyAsBytes).split('&').forEach {
val parts = it.split('=')
val key = URLDecoder.decode(parts[0], "UTF-8")
val value = URLDecoder.decode(parts[1], "UTF-8")
map[key] = value
}
return map
}
private fun firstBytesContainHtml(bytes: ByteArray, string: String): Boolean {
return String(bytes, 0, Math.min(bytes.size, 32)).contains(string, true)
}
private fun createImage(bytes: ByteArray): ConcreteBody? {
val body = when (initialBodyFormat.subtype!!) {
"image/webp" -> readWebPImage(bytes)
"application/svg+xml" -> return ConcreteBody(BodyFormatType.FORMAT_XML, initialBodyFormat.subtype, examineXML(bodyBytes))
else -> ImageIO.read(ByteArrayInputStream(bytes))
}
return ConcreteBody(initialBodyFormat.type, initialBodyFormat.subtype, body)
}
private fun readWebPImage(bytes: ByteArray): BufferedImage? {
if (!File("/usr/local/bin/dwebp").exists())
return null
val source = File.createTempFile("tmp_img", "dat")
source.writeBytes(bytes)
val converted = File.createTempFile("tmp_img", "png")
val proc = ProcessBuilder()
.command("/usr/local/bin/dwebp", source.absolutePath, "-o", converted.absolutePath) //TODO fix
.start()
proc.waitFor()
try {
return ImageIO.read(converted)
} finally {
source.delete()
converted.delete()
}
}
}
data class ConcreteBody(
val type: BodyFormatType,
val rawType: String?,
val data: Any?
)
enum class BodyFormatType(val verbose: String) {
FORMAT_JSON("application/json"),
FORMAT_XML("application/xml"),
FORMAT_PLAIN("text/plain"),
FORMAT_IMAGE("image"),
FORMAT_BINARY("binary"),
FORMAT_HTML("text/html"),
FORMAT_EMPTY(""),
FORMAT_FORM_ENCODED("x-www-form-urlencoded")
} | apache-2.0 | 3d0a61cc570b2e2dac118f36faa7285d | 38.710526 | 133 | 0.637945 | 4.463757 | false | false | false | false |
lare96/luna | plugins/world/player/skill/runecrafting/craftRune/Rune.kt | 1 | 1930 | package world.player.skill.runecrafting.craftRune
/**
* An enum representing a rune that can be crafted at an [Altar].
*/
enum class Rune(val id: Int,
val altar: Int,
val multiplier: Int,
val level: Int,
val exp: Double) {
AIR(id = 556,
altar = 2478,
multiplier = 11,
level = 1,
exp = 5.0),
MIND(id = 558,
altar = 2479,
multiplier = 14,
level = 2,
exp = 5.5),
WATER(id = 555,
altar = 2480,
multiplier = 19,
level = 5,
exp = 6.0),
EARTH(id = 557,
altar = 2481,
multiplier = 26,
level = 9,
exp = 6.5),
FIRE(id = 554,
altar = 2482,
multiplier = 35,
level = 14,
exp = 7.0),
BODY(id = 559,
altar = 2483,
multiplier = 46,
level = 20,
exp = 7.5),
COSMIC(id = 564,
altar = 2484,
multiplier = 59,
level = 27,
exp = 8.0),
CHAOS(id = 562,
altar = 2487,
multiplier = 74,
level = 35,
exp = 8.5),
NATURE(id = 561,
altar = 2486,
multiplier = 91,
level = 44,
exp = 9.0),
LAW(id = 563,
altar = 2485,
multiplier = 99,
level = 54,
exp = 9.5),
DEATH(id = 560,
altar = 2488,
multiplier = 99,
level = 65,
exp = 10.0),
BLOOD(id = 565,
altar = 2490,
multiplier = 99,
level = 80,
exp = 10.5),
SOUL(id = 566,
altar = 2489,
multiplier = 99,
level = 95,
exp = 11.0);
companion object {
/**
* Mappings of [Rune.altar] to [Rune] instances.
*/
val ALTAR_TO_RUNE = values().associateBy { it.altar }
}
} | mit | b7fb9784af57550df591a135d03f0285 | 21.717647 | 65 | 0.415544 | 3.587361 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/ui/PrimaryButtonAnimator.kt | 1 | 3594 | package com.stripe.android.paymentsheet.ui
import android.animation.ObjectAnimator
import android.content.Context
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.core.animation.doOnEnd
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import com.stripe.android.paymentsheet.R
internal class PrimaryButtonAnimator(
private val context: Context
) {
private val slideAnimationDuration = context.resources
.getInteger(android.R.integer.config_shortAnimTime)
.toLong()
internal fun fadeIn(
view: View,
parentWidth: Int,
onAnimationEnd: () -> Unit
) {
view.startAnimation(
AnimationUtils.loadAnimation(
context,
R.anim.stripe_paymentsheet_transition_fade_in
).also { animation ->
animation.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
view.isVisible = true
}
override fun onAnimationEnd(p0: Animation?) {
view.isVisible = true
slideToCenter(view, parentWidth, onAnimationEnd)
}
override fun onAnimationRepeat(p0: Animation?) {
}
}
)
}
)
}
// slide the view to the horizontal center of the parent view
private fun slideToCenter(
view: View,
parentWidth: Int,
onAnimationEnd: () -> Unit
) {
val iconCenter = view.left + (view.right - view.left) / 2f
val targetX = iconCenter - parentWidth / 2f
ObjectAnimator.ofFloat(
view,
"translationX",
0f,
-targetX
).also { animator ->
animator.duration = slideAnimationDuration
animator.doOnEnd {
delay(view, onAnimationEnd)
}
}.start()
}
private fun delay(
view: View,
onAnimationEnd: () -> Unit
) {
// This is effectively a no-op for ANIMATE_OUT_MILLIS
ObjectAnimator.ofFloat(
view,
"rotation",
0f,
0f
).also { animator ->
animator.duration = HOLD_ANIMATION_ON_SLIDE_IN_COMPLETION
animator.doOnEnd {
onAnimationEnd()
}
}.start()
}
internal fun fadeOut(view: View) {
view.startAnimation(
AnimationUtils.loadAnimation(
context,
R.anim.stripe_paymentsheet_transition_fade_out
).also { animation ->
animation.setAnimationListener(
object : Animation.AnimationListener {
override fun onAnimationStart(p0: Animation?) {
view.isVisible = true
}
override fun onAnimationEnd(p0: Animation?) {
view.isInvisible = true
}
override fun onAnimationRepeat(p0: Animation?) {
}
}
)
}
)
}
internal companion object {
// the delay before the payment sheet is dismissed
const val HOLD_ANIMATION_ON_SLIDE_IN_COMPLETION = 1500L
}
}
| mit | 0c2f3c5e151e557ef33ee0175f853ca8 | 29.457627 | 76 | 0.523372 | 5.606864 | false | false | false | false |
stripe/stripe-android | payments-ui-core/src/main/java/com/stripe/android/ui/core/elements/AddressElementUI.kt | 1 | 1830 | package com.stripe.android.ui.core.elements
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Divider
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.stripe.android.ui.core.paymentsColors
import com.stripe.android.ui.core.paymentsShapes
@Composable
internal fun AddressElementUI(
enabled: Boolean,
controller: AddressController,
hiddenIdentifiers: Set<IdentifierSpec>,
lastTextFieldIdentifier: IdentifierSpec?
) {
val fields by controller.fieldsFlowable.collectAsState(null)
// The last rendered field is not always the last field in the list.
// So we need to pre filter so we know when to stop drawing dividers.
fields?.filterNot { hiddenIdentifiers.contains(it.identifier) }?.let { fieldList ->
Column {
fieldList.forEachIndexed { index, field ->
SectionFieldElementUI(
enabled,
field,
hiddenIdentifiers = hiddenIdentifiers,
lastTextFieldIdentifier = lastTextFieldIdentifier
)
if (index != fieldList.lastIndex) {
Divider(
color = MaterialTheme.paymentsColors.componentDivider,
thickness = MaterialTheme.paymentsShapes.borderStrokeWidth.dp,
modifier = Modifier.padding(
horizontal = MaterialTheme.paymentsShapes.borderStrokeWidth.dp
)
)
}
}
}
}
}
| mit | 7b3a8717c6ab42d23753502858dc91c2 | 37.93617 | 90 | 0.654645 | 5.289017 | false | false | false | false |
AndroidX/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/TempListUtils.kt | 3 | 10908 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text
import androidx.compose.ui.util.fastForEach
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
// TODO: remove these when we can add new APIs to ui-util outside of beta cycle
/**
* Returns a list containing only elements matching the given [predicate].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T> List<T>.fastFilter(predicate: (T) -> Boolean): List<T> {
contract { callsInPlace(predicate) }
val target = ArrayList<T>(size)
fastForEach {
if (predicate(it)) target += (it)
}
return target
}
/**
* Returns a list containing only elements from the given collection
* having distinct keys returned by the given [selector] function.
*
* The elements in the resulting list are in the same order as they were in the source collection.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T, K> List<T>.fastDistinctBy(selector: (T) -> K): List<T> {
contract { callsInPlace(selector) }
val set = HashSet<K>(size)
val target = ArrayList<T>(size)
fastForEach { e ->
val key = selector(e)
if (set.add(key)) target += e
}
return target
}
/**
* Returns the first element yielding the largest value of the given function or `null` if there
* are no elements.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T, R : Comparable<R>> List<T>.fastMinByOrNull(selector: (T) -> R): T? {
contract { callsInPlace(selector) }
if (isEmpty()) return null
var minElem = get(0)
var minValue = selector(minElem)
for (i in 1..lastIndex) {
val e = get(i)
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right
* to current accumulator value and each element.
*
* Returns the specified [initial] value if the collection is empty.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*
* @param [operation] function that takes current accumulator value and an element, and calculates
* the next accumulator value.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T, R> List<T>.fastFold(initial: R, operation: (acc: R, T) -> R): R {
contract { callsInPlace(operation) }
var accumulator = initial
fastForEach { e ->
accumulator = operation(accumulator, e)
}
return accumulator
}
/**
* Returns a single list of all elements yielded from results of [transform] function being invoked
* on each element of original collection.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T, R> List<T>.fastFlatMap(transform: (T) -> Iterable<R>): List<R> {
contract { callsInPlace(transform) }
val target = ArrayList<R>(size)
fastForEach { e ->
val list = transform(e)
target.addAll(list)
}
return target
}
/**
* Returns a list containing all elements not matching the given [predicate].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T> List<T>.fastFilterNot(predicate: (T) -> Boolean): List<T> {
contract { callsInPlace(predicate) }
val target = ArrayList<T>(size)
fastForEach {
if (!predicate(it)) target += (it)
}
return target
}
/**
* Returns a list containing all elements that are not null
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@OptIn(ExperimentalContracts::class)
internal fun <T : Any> List<T?>.fastFilterNotNull(): List<T> {
val target = ArrayList<T>(size)
fastForEach {
if ((it) != null) target += (it)
}
return target
}
/**
* Returns a list containing the first elements satisfying the given [predicate].
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
@Suppress("BanInlineOptIn") // Treat Kotlin Contracts as non-experimental.
@OptIn(ExperimentalContracts::class)
internal inline fun <T> List<T>.fastTakeWhile(predicate: (T) -> Boolean): List<T> {
contract { callsInPlace(predicate) }
val target = ArrayList<T>(size)
for (i in indices) {
val item = get(i)
if (!predicate(item))
break
target += item
}
return target
}
/**
* Returns a list containing all elements except first [n] elements.
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*
* @throws IllegalArgumentException if [n] is negative.
*/
internal fun <T> List<T>.fastDrop(n: Int): List<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
if (n == 0) {
return this
}
val resultSize = size - n
if (resultSize <= 0) {
return emptyList()
}
if (resultSize == 1) {
return listOf(last())
}
val target = ArrayList<T>(resultSize)
for (index in n until size) {
target += get(index)
}
return target
}
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix]
* and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case
* only the first [limit] elements will be appended, followed by the [truncated] string (which
* defaults to "...").
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
internal fun <T> List<T>.fastJoinToString(
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((T) -> CharSequence)? = null
): String {
return fastJoinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform)
.toString()
}
/**
* Appends the string from all the elements separated using [separator] and using the given
* [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which
* case only the first [limit] elements will be appended, followed by the [truncated] string
* (which defaults to "...").
*
* **Do not use for collections that come from public APIs**, since they may not support random
* access in an efficient way, and this method may actually be a lot slower. Only use for
* collections that are created by code we control and are known to support random access.
*/
private fun <T, A : Appendable> List<T>.fastJoinTo(
buffer: A,
separator: CharSequence = ", ",
prefix: CharSequence = "",
postfix: CharSequence = "",
limit: Int = -1,
truncated: CharSequence = "...",
transform: ((T) -> CharSequence)? = null
): A {
buffer.append(prefix)
var count = 0
for (index in indices) {
val element = get(index)
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
buffer.appendElement(element, transform)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
return buffer
}
/**
* Copied from Appendable.kt
*/
private fun <T> Appendable.appendElement(element: T, transform: ((T) -> CharSequence)?) {
when {
transform != null -> append(transform(element))
element is CharSequence? -> append(element)
element is Char -> append(element)
else -> append(element.toString())
}
}
| apache-2.0 | effd6448fa8a0488aac5bebf74bd9ad3 | 36.875 | 99 | 0.690594 | 4.122449 | false | false | false | false |
AndroidX/androidx | buildSrc/private/src/main/kotlin/androidx/build/ReportLibraryMetricsTask.kt | 3 | 3693 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build
import com.google.gson.Gson
import com.jakewharton.dex.DexParser.Companion.toDexParser
import java.io.File
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Classpath
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
import org.gradle.api.tasks.TaskProvider
private const val BYTECODE_SIZE = "bytecode_size"
private const val METHOD_COUNT = "method_count"
private const val JSON_FILE_EXTENSION = ".json"
private const val JAR_FILE_EXTENSION = ".jar"
private const val LINT_JAR = "lint$JAR_FILE_EXTENSION"
@CacheableTask
abstract class ReportLibraryMetricsTask : DefaultTask() {
init {
group = "LibraryMetrics"
description = "Task for reporting build time library metrics. Currently gathers .aar sizes."
}
/**
* The variants we are interested in gathering metrics for.
*/
@get:[InputFiles Classpath]
abstract val jarFiles: ConfigurableFileCollection
@get:OutputFile
abstract val outputFile: Property<File>
@TaskAction
fun reportLibraryMetrics() {
val file = outputFile.get()
file.parentFile.mkdirs()
val jarFiles = getJarFiles()
val map = mutableMapOf<String, Any>()
val bytecodeSize = getBytecodeSize(jarFiles)
if (bytecodeSize > 0L) {
map[BYTECODE_SIZE] = bytecodeSize
}
val methodCount = getMethodCount(jarFiles)
if (methodCount > 0) {
map[METHOD_COUNT] = methodCount
}
file.writeText(Gson().toJson(map))
}
private fun getJarFiles(): List<File> {
return jarFiles.files.filter { file ->
file.name.endsWith(JAR_FILE_EXTENSION) &&
// AARs bundle a `lint.jar` that contains lint checks published by the library -
// this isn't runtime code and is not part of the actual library, so ignore it.
file.name != LINT_JAR
}
}
private fun getBytecodeSize(jarFiles: List<File>): Long {
return jarFiles.sumOf { it.length() }
}
private fun getMethodCount(jarFiles: List<File>): Int {
return when {
jarFiles.isEmpty() -> 0
jarFiles.all { it.isFile } -> jarFiles.toDexParser().listMethods().size
else ->
throw IllegalStateException("One or more of the items in $jarFiles is not a file.")
}
}
}
fun Project.configureReportLibraryMetricsTask(): TaskProvider<ReportLibraryMetricsTask> {
val task = tasks.register("reportLibraryMetrics", ReportLibraryMetricsTask::class.java)
task.configure {
val outputDir = project.rootProject.getLibraryMetricsDirectory()
it.outputFile.set(
task.map {
File(outputDir, "${project.group}_${project.name}$JSON_FILE_EXTENSION")
}
)
}
return task
}
| apache-2.0 | 387520136e385f2493532f9e8116b8e9 | 32.880734 | 100 | 0.679393 | 4.244828 | false | false | false | false |
vimeo/vimeo-networking-java | auth/src/main/java/com/vimeo/networking2/internal/MutableAuthenticatorDelegate.kt | 1 | 5970 | /*
* Copyright (c) 2020 Vimeo (https://vimeo.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.vimeo.networking2.internal
import com.vimeo.networking2.Authenticator
import com.vimeo.networking2.PinCodeInfo
import com.vimeo.networking2.SsoConnection
import com.vimeo.networking2.SsoDomain
import com.vimeo.networking2.TeamToken
import com.vimeo.networking2.VimeoAccount
import com.vimeo.networking2.VimeoCallback
import com.vimeo.networking2.VimeoRequest
/**
* An [Authenticator] that delegates its implementation to an internal mutable instance [actual]. The purpose of this
* class is to allow the [Authenticator] instance to be re-initialized on the fly. It delegates to an underlying actual
* implementation that can be changed dynamically. This allows the [Authenticator.initialize] function to change the
* implementation used without changing the reference returned by [Authenticator.instance].
*
* @param actual The actual implementation of [Authenticator], defaults to null.
*/
class MutableAuthenticatorDelegate(var actual: Authenticator? = null) : Authenticator {
private val authenticator: Authenticator
get() = actual ?: error("Must call Authenticator.initialize() before calling Authenticator.instance()")
override val currentAccount: VimeoAccount?
get() = authenticator.currentAccount
override fun authenticateWithClientCredentials(callback: VimeoCallback<VimeoAccount>): VimeoRequest =
authenticator.authenticateWithClientCredentials(callback)
override fun authenticateWithGoogle(
token: String,
username: String,
marketingOptIn: Boolean,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.authenticateWithGoogle(token, username, marketingOptIn, callback)
override fun authenticateWithFacebook(
token: String,
username: String,
marketingOptIn: Boolean,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.authenticateWithFacebook(token, username, marketingOptIn, callback)
override fun authenticateWithEmailJoin(
displayName: String,
email: String,
password: String,
marketingOptIn: Boolean,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.authenticateWithEmailJoin(displayName, email, password, marketingOptIn, callback)
override fun authenticateWithEmailLogin(
username: String,
password: String,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.authenticateWithEmailLogin(username, password, callback)
override fun exchangeAccessToken(accessToken: String, callback: VimeoCallback<VimeoAccount>): VimeoRequest =
authenticator.exchangeAccessToken(accessToken, callback)
override fun exchangeOAuth1Token(
token: String,
tokenSecret: String,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.exchangeOAuth1Token(token, tokenSecret, callback)
override fun createCodeGrantAuthorizationUri(responseCode: String): String =
authenticator.createCodeGrantAuthorizationUri(responseCode)
override fun authenticateWithCodeGrant(uri: String, callback: VimeoCallback<VimeoAccount>): VimeoRequest =
authenticator.authenticateWithCodeGrant(uri, callback)
override fun checkSsoConnection(email: String, callback: VimeoCallback<SsoConnection>): VimeoRequest =
authenticator.checkSsoConnection(email, callback)
override fun createSsoAuthorizationUri(ssoConnection: SsoConnection, responseCode: String): String? =
authenticator.createSsoAuthorizationUri(ssoConnection, responseCode)
override fun fetchSsoDomain(domain: String, callback: VimeoCallback<SsoDomain>): VimeoRequest =
authenticator.fetchSsoDomain(domain, callback)
override fun createSsoAuthorizationUri(ssoDomain: SsoDomain, responseCode: String): String? =
authenticator.createSsoAuthorizationUri(ssoDomain, responseCode)
override fun authenticateWithSso(
uri: String,
marketingOptIn: Boolean,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.authenticateWithSso(uri, marketingOptIn, callback)
override fun fetchPinCodeInfo(callback: VimeoCallback<PinCodeInfo>): VimeoRequest =
authenticator.fetchPinCodeInfo(callback)
override fun authenticateWithPinCode(
pinCodeInfo: PinCodeInfo,
callback: VimeoCallback<VimeoAccount>
): VimeoRequest = authenticator.authenticateWithPinCode(pinCodeInfo, callback)
override fun logOut(callback: VimeoCallback<Unit>): VimeoRequest = authenticator.logOut(callback)
override fun logOutLocally() = authenticator.logOutLocally()
override fun getMagistoTeamToken(
teamId: String,
callback: VimeoCallback<TeamToken>
) = authenticator.getMagistoTeamToken(teamId, callback)
}
| mit | 66dbd6f1881d7c2406c429b24aa98a21 | 45.640625 | 119 | 0.765662 | 4.810637 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/RsImportOptimizer.kt | 2 | 8032 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring
import com.intellij.lang.ImportOptimizer
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import org.rust.ide.inspections.lints.PathUsageMap
import org.rust.ide.inspections.lints.RsUnusedImportInspection
import org.rust.ide.inspections.lints.isUsed
import org.rust.ide.inspections.lints.pathUsage
import org.rust.ide.utils.import.COMPARATOR_FOR_SPECKS_IN_USE_GROUP
import org.rust.ide.utils.import.UseItemWrapper
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.doc.psi.RsDocComment
import org.rust.stdext.withNext
class RsImportOptimizer : ImportOptimizer {
override fun supports(file: PsiFile): Boolean = file is RsFile
override fun processFile(file: PsiFile) = Runnable {
val documentManager = PsiDocumentManager.getInstance(file.project)
val document = documentManager.getDocument(file)
if (document != null) {
documentManager.commitDocument(document)
}
optimizeAndReorderUseItems(file as RsFile)
reorderExternCrates(file)
}
private fun reorderExternCrates(file: RsFile) {
val first = file.firstItem ?: return
val externCrateItems = file.childrenOfType<RsExternCrateItem>()
externCrateItems
.sortedBy { it.referenceName }
.mapNotNull { it.copy() as? RsExternCrateItem }
.forEach { file.addBefore(it, first) }
externCrateItems.forEach { it.delete() }
}
private fun optimizeAndReorderUseItems(file: RsFile) {
file.forEachMod { mod, pathUsage ->
val uses = mod
.childrenOfType<RsUseItem>()
.filterNot { it.isReexportOfLegacyMacro() }
replaceOrderOfUseItems(mod, uses, pathUsage)
}
}
companion object {
fun optimizeUseItems(file: RsFile) {
val factory = RsPsiFactory(file.project)
file.forEachMod { mod, pathUsage ->
val uses = mod.childrenOfType<RsUseItem>()
uses.forEach { optimizeUseItem(it, factory, pathUsage) }
}
}
private fun optimizeUseItem(useItem: RsUseItem, factory: RsPsiFactory, pathUsage: PathUsageMap?) {
val useSpeck = useItem.useSpeck ?: return
val used = optimizeUseSpeck(useSpeck, factory, pathUsage)
if (!used) {
(useItem.nextSibling as? PsiWhiteSpace)?.delete()
useItem.delete()
}
}
/** Returns false if [useSpeck] is empty and should be removed */
private fun optimizeUseSpeck(
useSpeck: RsUseSpeck,
factory: RsPsiFactory,
// PSI changes during optimizing increments modification tracker
// So we pass [pathUsage] so it will not be recalculated
pathUsage: PathUsageMap?,
): Boolean {
val useGroup = useSpeck.useGroup
if (useGroup == null) {
return if (pathUsage != null && !useSpeck.isUsed(pathUsage)) {
useSpeck.deleteWithSurroundingComma()
false
} else {
true
}
} else {
useGroup.useSpeckList.forEach { optimizeUseSpeck(it, factory, pathUsage) }
if (removeUseSpeckIfEmpty(useSpeck)) return false
if (removeCurlyBracesIfPossible(factory, useSpeck)) return true
useGroup.sortUseSpecks()
return true
}
}
fun RsUseGroup.sortUseSpecks() {
val sortedList = useSpeckList
.sortedWith(COMPARATOR_FOR_SPECKS_IN_USE_GROUP)
.map { it.copy() }
useSpeckList.zip(sortedList).forEach { it.first.replace(it.second) }
}
/** Returns true if successfully removed, e.g. `use aaa::{bbb};` -> `use aaa::bbb;` */
private fun removeCurlyBracesIfPossible(psiFactory: RsPsiFactory, useSpeck: RsUseSpeck): Boolean {
val name = useSpeck.useGroup?.asTrivial?.text ?: return false
val path = useSpeck.path?.text
val tempPath = "${if (path != null) "$path::" else ""}$name"
val newUseSpeck = psiFactory.createUseSpeck(tempPath)
useSpeck.replace(newUseSpeck)
return true
}
/**
* Returns true if [useSpeck] is empty and was successfully removed,
* e.g. `use aaa::{bbb::{}, ccc, ddd};` -> `use aaa::{ccc, ddd};`
*/
private fun removeUseSpeckIfEmpty(useSpeck: RsUseSpeck): Boolean {
val useGroup = useSpeck.useGroup ?: return false
if (useGroup.useSpeckList.isNotEmpty()) return false
if (useSpeck.parent is RsUseGroup) {
useSpeck.deleteWithSurroundingComma()
}
// else can't delete useSpeck.parent if it is RsUseItem, because it will cause invalidation exception
return true
}
private fun replaceOrderOfUseItems(mod: RsMod, uses: Collection<RsUseItem>, pathUsage: PathUsageMap?) {
// We should ignore all items before `{` in inline modules
val offset = if (mod is RsModItem) mod.lbrace.textOffset + 1 else 0
val first = mod.childrenOfType<RsElement>()
.firstOrNull { it.textOffset >= offset && it !is RsExternCrateItem && it !is RsAttr && it !is RsDocComment } ?: return
val psiFactory = RsPsiFactory(mod.project)
val sortedUses = uses
.asSequence()
.map { UseItemWrapper(it) }
.filter {
val useSpeck = it.useItem.useSpeck ?: return@filter false
optimizeUseSpeck(useSpeck, psiFactory, pathUsage)
}
.sorted()
for ((useWrapper, nextUseWrapper) in sortedUses.withNext()) {
val addedUseItem = mod.addBefore(useWrapper.useItem, first)
mod.addAfter(psiFactory.createNewline(), addedUseItem)
if (useWrapper.packageGroupLevel != nextUseWrapper?.packageGroupLevel) {
mod.addAfter(psiFactory.createNewline(), addedUseItem)
}
}
uses.forEach {
(it.nextSibling as? PsiWhiteSpace)?.delete()
it.delete()
}
}
}
}
private fun RsFile.forEachMod(callback: (RsMod, PathUsageMap?) -> Unit) {
getAllModulesInFile()
.filter { it.childOfType<RsUseItem>() != null }
.map { it to getPathUsage(it) }
.forEach { (mod, pathUsage) -> callback(mod, pathUsage) }
}
private fun RsFile.getAllModulesInFile(): List<RsMod> {
val result = mutableListOf<RsMod>()
fun go(mod: RsMod) {
result += mod
mod.childrenOfType<RsModItem>().forEach(::go)
}
go(this)
return result
}
private fun getPathUsage(mod: RsMod): PathUsageMap? {
if (!RsUnusedImportInspection.isEnabled(mod.project)) return null
return mod.pathUsage
}
// `macro_rules! foo { () => {} }`
// `pub(crate) use foo_ as foo;`
// `pub(crate) use foo;`
private fun RsUseItem.isReexportOfLegacyMacro(): Boolean {
val useSpeck = useSpeck ?: return false
val useGroup = useSpeck.useGroup
return if (useGroup == null) {
useSpeck.isReexportOfLegacyMacro()
} else {
useSpeck.coloncolon == null && useGroup.useSpeckList.any { it.isReexportOfLegacyMacro() }
}
}
private fun RsUseSpeck.isReexportOfLegacyMacro(): Boolean {
val path = path ?: return false
return path.coloncolon == null
// TODO: Check not null when we will support resolving legacy macro in `use foo as bar;`
&& path.reference?.resolve().let { it is RsMacro || it == null && alias != null }
&& !isStarImport
&& useGroup == null
}
| mit | 42114fdba59f0fa7679bf9feb3677f19 | 38.566502 | 134 | 0.611305 | 4.658933 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/AddRemainingArmsFix.kt | 2 | 2431 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.utils.checkMatch.Pattern
import org.rust.ide.utils.import.RsImportHelper.importTypeReferencesFromTy
import org.rust.lang.core.psi.*
import org.rust.lang.core.types.type
open class AddRemainingArmsFix(
match: RsMatchExpr,
@SafeFieldForPreview
private val patterns: List<Pattern>,
) : LocalQuickFixOnPsiElement(match) {
override fun getFamilyName(): String = NAME
override fun getText(): String = familyName
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
if (startElement !is RsMatchExpr) return
val expr = startElement.expr ?: return
val rsPsiFactory = RsPsiFactory(project)
val oldMatchBody = startElement.matchBody
?: rsPsiFactory.createMatchBody(emptyList()).let { startElement.addAfter(it, expr) as RsMatchBody }
val lastMatchArm = oldMatchBody.matchArmList.lastOrNull()
if (lastMatchArm != null && lastMatchArm.expr !is RsBlockExpr && lastMatchArm.comma == null)
lastMatchArm.add(rsPsiFactory.createComma())
val newArms = createNewArms(rsPsiFactory, oldMatchBody)
for (arm in newArms) {
oldMatchBody.addBefore(arm, oldMatchBody.rbrace)
}
importTypeReferencesFromTy(startElement, expr.type)
}
open fun createNewArms(psiFactory: RsPsiFactory, oldMatchBody: RsMatchBody): List<RsMatchArm> =
psiFactory.createMatchBody(patterns, oldMatchBody).matchArmList
companion object {
const val NAME = "Add remaining patterns"
}
}
class AddWildcardArmFix(match: RsMatchExpr) : AddRemainingArmsFix(match, emptyList()) {
override fun getFamilyName(): String = NAME
override fun getText(): String = familyName
override fun createNewArms(psiFactory: RsPsiFactory, oldMatchBody: RsMatchBody): List<RsMatchArm> = listOf(
psiFactory.createMatchBody(listOf(Pattern.wild())).matchArmList.first()
)
companion object {
const val NAME = "Add _ pattern"
}
}
| mit | d30f9ea57faab09bd94a5ef0850c8b17 | 36.4 | 111 | 0.73262 | 4.38018 | false | false | false | false |
jk1/youtrack-idea-plugin | src/main/kotlin/com/github/jk1/ytplugin/timeTracker/CustomAttributesHandler.kt | 1 | 717 | package com.github.jk1.ytplugin.timeTracker
import com.google.gson.JsonArray
class CustomAttributesHandler {
fun parseCustomAttributes(json: JsonArray): Map<String, List<String>> {
return if (json.isJsonNull || json.size() == 0){
mapOf()
} else {
val valuesMap = mutableMapOf<String, List<String>>()
// allow selecting empty attribute
json.forEach { it ->
val valuesNames = listOf("") +
(it.asJsonObject.get("values").asJsonArray.map { it.asJsonObject.get("name").asString})
valuesMap[it.asJsonObject.get("name").asString] = valuesNames
}
valuesMap
}
}
} | apache-2.0 | aa8b59181ac8353735e4d77e4e1af699 | 33.190476 | 111 | 0.578801 | 4.596154 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/types/ty/TyPointer.kt | 3 | 1153 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.types.ty
import org.rust.lang.core.psi.RsTypeAlias
import org.rust.lang.core.types.BoundElement
import org.rust.lang.core.types.infer.TypeFolder
import org.rust.lang.core.types.infer.TypeVisitor
data class TyPointer(
val referenced: Ty,
val mutability: Mutability,
override val aliasedBy: BoundElement<RsTypeAlias>? = null
) : Ty(referenced.flags) {
override fun superFoldWith(folder: TypeFolder): Ty =
TyPointer(referenced.foldWith(folder), mutability, aliasedBy?.foldWith(folder))
override fun superVisitWith(visitor: TypeVisitor): Boolean =
referenced.visitWith(visitor)
override fun withAlias(aliasedBy: BoundElement<RsTypeAlias>): Ty = copy(aliasedBy = aliasedBy)
override fun isEquivalentToInner(other: Ty): Boolean {
if (this === other) return true
if (other !is TyPointer) return false
if (!referenced.isEquivalentTo(other.referenced)) return false
if (mutability != other.mutability) return false
return true
}
}
| mit | 1e73daa3d0efbbf8893b4e1db46affd3 | 31.027778 | 98 | 0.722463 | 4.208029 | false | false | false | false |
scenerygraphics/SciView | src/main/kotlin/sc/iview/commands/view/DisplayVertices.kt | 1 | 3490 | /*-
* #%L
* Scenery-backed 3D visualization package for ImageJ.
* %%
* Copyright (C) 2016 - 2021 SciView developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package sc.iview.commands.view
import graphics.scenery.Mesh
import org.scijava.ItemIO
import org.scijava.command.Command
import org.scijava.log.LogService
import org.scijava.plugin.Menu
import org.scijava.plugin.Parameter
import org.scijava.plugin.Plugin
import org.scijava.table.DefaultGenericTable
import org.scijava.table.DoubleColumn
import org.scijava.table.GenericColumn
import org.scijava.table.Table
import sc.iview.SciView
import sc.iview.commands.MenuWeights.VIEW
import sc.iview.commands.MenuWeights.VIEW_SET_TRANSFER_FUNCTION
import sc.iview.process.MeshConverter
/**
* Command to display the vertices of the currently active Node as a table.
*
* @author Kyle Harrington
*/
@Plugin(type = Command::class, menuRoot = "SciView", menu = [Menu(label = "View", weight = VIEW), Menu(label = "Display Vertices", weight = VIEW_SET_TRANSFER_FUNCTION)])
class DisplayVertices : Command {
@Parameter
private lateinit var sciView: SciView
// TODO: this should be the way to do this instead of using sciView.activeNode()
// @Parameter
// private Mesh mesh;
@Parameter(type = ItemIO.OUTPUT)
private lateinit var table: Table<*, *>
override fun run() {
if (sciView.activeNode is Mesh) {
val scMesh = sciView.activeNode as Mesh
val mesh = MeshConverter.toImageJ(scMesh)
table = DefaultGenericTable()
// we create two columns
val idColumn = GenericColumn("ID")
val xColumn = DoubleColumn("X")
val yColumn = DoubleColumn("Y")
val zColumn = DoubleColumn("Z")
for (v in mesh.vertices()) {
idColumn.add(v.index())
xColumn.add(v.x())
yColumn.add(v.y())
zColumn.add(v.z())
}
(table as DefaultGenericTable).add(idColumn)
(table as DefaultGenericTable).add(xColumn)
(table as DefaultGenericTable).add(yColumn)
(table as DefaultGenericTable).add(zColumn)
}
}
}
| bsd-2-clause | 5fde6e2a426518bb9bec2f706862752c | 39.114943 | 169 | 0.701433 | 4.235437 | false | false | false | false |
SimpleMobileTools/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/views/PatternTab.kt | 1 | 3553 | package com.simplemobiletools.commons.views
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.RelativeLayout
import androidx.biometric.auth.AuthPromptHost
import com.andrognito.patternlockview.PatternLockView
import com.andrognito.patternlockview.listener.PatternLockViewListener
import com.andrognito.patternlockview.utils.PatternLockUtils
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.PROTECTION_PATTERN
import com.simplemobiletools.commons.interfaces.HashListener
import com.simplemobiletools.commons.interfaces.SecurityTab
import kotlinx.android.synthetic.main.tab_pattern.view.*
class PatternTab(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs), SecurityTab {
private var hash = ""
private var requiredHash = ""
private var scrollView: MyScrollView? = null
lateinit var hashListener: HashListener
override fun onFinishInflate() {
super.onFinishInflate()
val textColor = context.getProperTextColor()
context.updateTextColors(pattern_lock_holder)
pattern_lock_view.setOnTouchListener { v, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> scrollView?.isScrollable = false
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> scrollView?.isScrollable = true
}
false
}
pattern_lock_view.correctStateColor = context.getProperPrimaryColor()
pattern_lock_view.normalStateColor = textColor
pattern_lock_view.addPatternLockListener(object : PatternLockViewListener {
override fun onComplete(pattern: MutableList<PatternLockView.Dot>?) {
receivedHash(PatternLockUtils.patternToSha1(pattern_lock_view, pattern))
}
override fun onCleared() {}
override fun onStarted() {}
override fun onProgress(progressPattern: MutableList<PatternLockView.Dot>?) {}
})
}
override fun initTab(
requiredHash: String,
listener: HashListener,
scrollView: MyScrollView,
biometricPromptHost: AuthPromptHost,
showBiometricAuthentication: Boolean
) {
this.requiredHash = requiredHash
this.scrollView = scrollView
hash = requiredHash
hashListener = listener
}
private fun receivedHash(newHash: String) {
when {
hash.isEmpty() -> {
hash = newHash
pattern_lock_view.clearPattern()
pattern_lock_title.setText(R.string.repeat_pattern)
}
hash == newHash -> {
pattern_lock_view.setViewMode(PatternLockView.PatternViewMode.CORRECT)
Handler().postDelayed({
hashListener.receivedHash(hash, PROTECTION_PATTERN)
}, 300)
}
else -> {
pattern_lock_view.setViewMode(PatternLockView.PatternViewMode.WRONG)
context.toast(R.string.wrong_pattern)
Handler().postDelayed({
pattern_lock_view.clearPattern()
if (requiredHash.isEmpty()) {
hash = ""
pattern_lock_title.setText(R.string.insert_pattern)
}
}, 1000)
}
}
}
override fun visibilityChanged(isVisible: Boolean) {}
}
| gpl-3.0 | 30725054a3b857520c87631ef6f3c8a7 | 36.797872 | 103 | 0.652406 | 4.948468 | false | false | false | false |
rabbitmq/rabbitmq-tutorials | kotlin/src/main/kotlin/RPCServer.kt | 1 | 1689 | import com.rabbitmq.client.AMQP
import com.rabbitmq.client.ConnectionFactory
import com.rabbitmq.client.DefaultConsumer
import com.rabbitmq.client.Envelope
class RPCServer {
companion object {
const val RPC_QUEUE_NAME = "rpc_queue"
fun fib(n: Int): Int {
if (n == 0) return 0
return if (n == 1) 1 else fib(n - 1) + fib(n - 2)
}
}
}
fun main(args: Array<String>) {
val factory = ConnectionFactory()
factory.host = "localhost"
val connection = factory.newConnection()
val channel = connection.createChannel()
channel.queueDeclare(RPCServer.RPC_QUEUE_NAME, false, false, false, null)
channel.basicQos(1)
System.out.println(" [x] Awaiting RPC requests")
val consumer = object : DefaultConsumer(channel) {
override fun handleDelivery(consumerTag: String, envelope: Envelope, properties: AMQP.BasicProperties, body: ByteArray) {
val replyProps = AMQP.BasicProperties.Builder()
.correlationId(properties.correlationId)
.build()
val message = String(body, charset("UTF-8"))
val n = Integer.parseInt(message)
println(" [.] fib($message)")
val response = RPCServer.fib(n).toString()
channel.basicPublish("", properties.replyTo, replyProps, response.toByteArray())
channel.basicAck(envelope.deliveryTag, false)
}
}
channel.basicConsume(RPCServer.RPC_QUEUE_NAME, false, consumer)
// Wait and be prepared to consume the message from RPC client.
while (true) {
synchronized(consumer) {
(consumer as Object).wait()
}
}
} | apache-2.0 | a29fe02810e90a802802a0b77872a842 | 32.8 | 129 | 0.632327 | 4.191067 | false | false | false | false |
lytefast/flex-input | flexinput/src/main/java/com/lytefast/flexinput/model/Attachment.kt | 1 | 2787 | package com.lytefast.flexinput.model
import android.content.ContentResolver
import android.net.Uri
import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.CallSuper
import androidx.core.view.inputmethod.InputContentInfoCompat
import com.facebook.common.util.HashCodeUtil
import com.lytefast.flexinput.utils.FileUtils.getFileName
import java.io.File
/**
* Represents an attachable resource in the form of [Uri].
*
* @author Sam Shih
*/
open class Attachment<out T>(
val id: Long,
val uri: Uri,
val displayName: String,
val data: T? = null
) : Parcelable {
constructor(parcelIn: Parcel) : this(
id = parcelIn.readLong(),
uri = parcelIn.readParcelable(Uri::class.java.classLoader) ?: Uri.EMPTY,
displayName = parcelIn.readString() ?: "",
data = null // this shouldn't be required anyways.
)
override fun equals(other: Any?): Boolean {
if (other != null && other is Attachment<*>) {
return this.id == other.id && this.uri == other.uri
}
return false
}
override fun hashCode(): Int = HashCodeUtil.hashCode(id, uri)
override fun describeContents(): Int = 0
@CallSuper
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id)
dest.writeParcelable(uri, flags)
dest.writeString(displayName)
// dest.writeParcelable(data, flags);
}
companion object {
@Suppress("unused") // Used as part of Parcellable
@JvmField
val CREATOR = object : Parcelable.Creator<Attachment<*>> {
override fun createFromParcel(parcelIn: Parcel): Attachment<*> = Attachment<Any>(parcelIn)
override fun newArray(size: Int): Array<Attachment<*>?> = arrayOfNulls(size)
}
@JvmStatic
fun Uri.toAttachment(resolver: ContentResolver): Attachment<Uri> {
val fileName = getFileName(resolver) ?: hashCode().toString()
return Attachment(hashCode().toLong(), this, fileName, null)
}
@JvmStatic
fun InputContentInfoCompat.toAttachment(
resolver: ContentResolver,
appendExtension: Boolean = false,
defaultName: String = "unknown"): Attachment<InputContentInfoCompat> {
val rawFileName = contentUri.getQueryParameter("fileName") ?: defaultName
val fileName = rawFileName.substringAfterLast(File.separatorChar)
val attachmentName = if (appendExtension) {
val type = description.getMimeType(0)
?: contentUri.getQueryParameter("mimeType")
?: resolver.getType(contentUri)
type?.let {
"$fileName.${it.substringAfterLast('/')}"
} ?: fileName
} else {
fileName
}
return Attachment(
contentUri.hashCode().toLong(),
contentUri,
attachmentName,
this)
}
}
}
| mit | 3f189a0524daa0b3e2646bc4a8ca315b | 28.648936 | 96 | 0.670255 | 4.480707 | false | false | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/chatroom/ChatRoomFragment.kt | 1 | 8212 | /*
* Copyright 2020 Google 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.app.playhvz.screens.chatroom
import android.app.Activity
import android.os.Bundle
import android.view.*
import android.view.inputmethod.InputMethodManager
import android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT
import android.widget.ProgressBar
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doOnTextChanged
import androidx.emoji.widget.EmojiEditText
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.playhvz.R
import com.app.playhvz.app.EspressoIdlingResource
import com.app.playhvz.common.globals.SharedPreferencesConstants
import com.app.playhvz.common.globals.SharedPreferencesConstants.Companion.CURRENT_GAME_ID
import com.app.playhvz.common.globals.SharedPreferencesConstants.Companion.CURRENT_PLAYER_ID
import com.app.playhvz.firebase.classmodels.ChatRoom
import com.app.playhvz.firebase.classmodels.Message
import com.app.playhvz.firebase.classmodels.Player
import com.app.playhvz.firebase.operations.ChatDatabaseOperations
import com.app.playhvz.firebase.viewmodels.ChatRoomViewModel
import com.app.playhvz.navigation.NavigationUtil
import com.app.playhvz.utils.PlayerUtils
import com.google.android.material.button.MaterialButton
import kotlinx.coroutines.runBlocking
/** Fragment for showing a list of Chatrooms the user is a member of.*/
class ChatRoomFragment : Fragment() {
companion object {
private val TAG = ChatRoomFragment::class.qualifiedName
}
lateinit var chatViewModel: ChatRoomViewModel
lateinit var messageAdapter: MessageAdapter
private lateinit var chatRoomId: String
private lateinit var playerId: String
private lateinit var progressBar: ProgressBar
private lateinit var messageInputView: EmojiEditText
private lateinit var sendButton: MaterialButton
private val args: ChatRoomFragmentArgs by navArgs()
private var gameId: String? = null
private var toolbar: ActionBar? = null
private var isChatWithAdmin: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
chatRoomId = args.chatRoomId
playerId = args.playerId
chatViewModel = ChatRoomViewModel()
messageAdapter = MessageAdapter(listOf(), requireContext(), this)
val sharedPrefs = activity?.getSharedPreferences(
SharedPreferencesConstants.PREFS_FILENAME,
0
)!!
gameId = sharedPrefs.getString(CURRENT_GAME_ID, null)
toolbar = (activity as AppCompatActivity).supportActionBar
setupObservers()
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = inflater.inflate(R.layout.fragment_chat_room, container, false)
progressBar = view.findViewById(R.id.progress_bar)
sendButton = view.findViewById(R.id.send_button)
messageInputView = view.findViewById(R.id.message_input)
messageInputView.requestFocus()
messageInputView.doOnTextChanged { text, _, _, _ ->
when {
text.isNullOrEmpty() || text.isBlank() -> {
sendButton.isEnabled = false
}
else -> {
sendButton.isEnabled = true
}
}
}
sendButton.setOnClickListener {
sendMessage()
}
val messageRecyclerView = view.findViewById<RecyclerView>(R.id.message_list)
val layoutManager = LinearLayoutManager(context)
layoutManager.stackFromEnd = true
messageRecyclerView.layoutManager = layoutManager
messageRecyclerView.adapter = messageAdapter
progressBar.visibility = View.GONE
setupToolbar()
return view
}
override fun onStart() {
super.onStart()
// Must wait to show keyboard until the Fragment is started
showKeyboard()
}
override fun onPause() {
super.onPause()
hideKeyboard()
}
override fun onResume() {
super.onResume()
val name = chatViewModel.getChatName()
if (name != null && name != toolbar?.title) {
toolbar?.title = name
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_chat, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.chat_info) {
NavigationUtil.navigateToChatInfo(findNavController(), chatRoomId, playerId, isChatWithAdmin)
}
return super.onOptionsItemSelected(item)
}
fun setupToolbar() {
toolbar?.title = ""
setHasOptionsMenu(true)
}
private fun setupObservers() {
if (gameId.isNullOrEmpty() || playerId.isNullOrEmpty()) {
return
}
chatViewModel.getChatRoomObserver(gameId!!, chatRoomId)
.observe(this, androidx.lifecycle.Observer { serverChatRoom ->
onChatRoomUpdated(serverChatRoom)
})
chatViewModel.getMessagesObserver(gameId!!, chatRoomId)
.observe(this, androidx.lifecycle.Observer { serverMessageList ->
onMessagesUpdated(serverMessageList)
})
}
/** Update data and notify view and adapter of change. */
private fun onChatRoomUpdated(updatedChatRoom: ChatRoom) {
if (updatedChatRoom.name != toolbar?.title) {
toolbar?.title = updatedChatRoom.name
messageInputView.hint = getString(R.string.chat_input_hint, updatedChatRoom.name)
}
isChatWithAdmin = updatedChatRoom.withAdmins
}
private fun onMessagesUpdated(updatedMessageList: List<Message>) {
val players = mutableMapOf<String, LiveData<Player>>()
for (message in updatedMessageList) {
if (!players.containsKey(message.senderId)) {
players[message.senderId] = PlayerUtils.getPlayer(gameId!!, message.senderId)
}
}
messageAdapter.setData(updatedMessageList, players)
messageAdapter.notifyDataSetChanged()
}
private fun updateView() {
if (this.view == null) {
return
}
progressBar.visibility = View.GONE
}
private fun sendMessage() {
val message = messageInputView.text.toString()
if (message.isEmpty() || message.isBlank()) {
return
}
messageInputView.text.clear()
runBlocking {
EspressoIdlingResource.increment()
ChatDatabaseOperations.sendChatMessage(
gameId!!,
chatRoomId,
playerId,
message,
{
EspressoIdlingResource.decrement()
},
{
EspressoIdlingResource.decrement()
})
}
}
private fun showKeyboard() {
val imm = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.showSoftInput(messageInputView, SHOW_IMPLICIT)
}
private fun hideKeyboard() {
val imm = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager?
imm?.hideSoftInputFromWindow(messageInputView.windowToken, 0)
}
} | apache-2.0 | 708d04ccee3ec01101868764cde0a935 | 34.864629 | 105 | 0.677667 | 5.1325 | false | false | false | false |
InsanusMokrassar/IObjectK | src/main/kotlin/com/github/insanusmokrassar/IObjectK/extensions/CommonIObject.kt | 1 | 9236 | package com.github.insanusmokrassar.IObjectK.extensions
import com.github.insanusmokrassar.IObjectK.exceptions.ReadException
import com.github.insanusmokrassar.IObjectK.interfaces.*
import com.github.insanusmokrassar.IObjectK.realisations.SimpleIObject
import java.util.logging.Logger
/**
* Creating mutable map to CommonIObject
*/
fun <K, V> CommonIObject<K, V>.asMutableMap(): Map<K, V> {
return IInputObjectMap(this)
}
internal class CommonIObjectMap<K, V>(
private val source: CommonIObject<K, V>
) : MutableMap<K, V>, IInputObjectMap<K, V>(source) {
override val entries: MutableSet<MutableMap.MutableEntry<K, V>>
get() {
val set = HashSet<MutableMap.MutableEntry<K, V>>()
source.keys().forEach {
set.add(
CommonIObjectEntry(it, source)
)
}
return set
}
override val keys: MutableSet<K>
get() = source.keys().toMutableSet()
override val values: MutableCollection<V>
get() = entries.map { it.value }.toMutableList()
override fun clear() {
keys.forEach {
source.remove(it)
}
}
override fun put(key: K, value: V): V? {
val old =try {
source.get<V>(key)
} catch (e: ReadException) {
null
}
source[key] = value
return old
}
override fun putAll(from: Map<out K, V>) {
from.forEach {
source[it.key] = it.value
}
}
override fun remove(key: K): V? {
val old =try {
source.get<V>(key)
} catch (e: ReadException) {
null
}
source.remove(key)
return old
}
}
private class CommonIObjectEntry<K, V>(
override val key: K,
private val source: CommonIObject<K, V>
) : MutableMap.MutableEntry<K, V> {
override val value: V
get() = source[key] ?: throw IllegalStateException("Value is absent")
override fun setValue(newValue: V): V {
val old = source.get<V>(key)
source[key] = newValue
return old
}
}
@Throws(ReadException::class)
private fun CommonIObject<String, in Any>.remap(
key: String,
sourceIObject: CommonIObject<String, Any>,
destObject: CommonIObject<String, Any>
): Boolean {
return try {
val rule = get<String>(key)// "keyToPut": "path/to/get/field"
remapByValue(key, rule, sourceIObject, destObject)
} catch (e: ReadException) {
throw e
} catch (e: Exception) {
false
}
}
private fun remapByValue(
key: String,
rule: String,
sourceIObject: CommonIObject<String, Any>,
destObject: CommonIObject<String, Any>
): Boolean {
return try {
rule.toPath().let {
destObject[key] = sourceIObject.get(it)
}
true
} catch (e: ReadException) {
throw e
} catch (e: Exception) {
false
}
}
/**
* [this] - remap rules in next format:
* <pre>
* {
* "key": "target/source/key/to/get/value",
* "key1": ["target","source","key","to","get","value"],
* "key2": rules map which keys will be used as "key2/ruleKey"
* }
* </pre>
*/
fun CommonIObject<String, in Any>.remap(
sourceObject: CommonIObject<String, Any>,
destObject: CommonIObject<String, Any>
) {
keys().forEach {
key ->
try {
if (!remap(key, sourceObject, destObject)) {
try {
val childRules = get<IObject<Any>>(key)
try {
destObject.get<IObject<Any>>(key)
} catch (e: Exception) {
SimpleIObject().also {
destObject[key] = it
}
}.let { childDest ->
childRules.remap(sourceObject, childDest)
}
} catch (e: Exception) {
val rules = get<List<String>>(key)// think that it is array of keys in source object
val iterator = rules.iterator()
while (iterator.hasNext()) {
val rule = iterator.next()
try {
val remapResult: Boolean = remapByValue(
key,
rule,
sourceObject,
destObject
)
if (remapResult) {
break
}
} catch (e: ReadException) {
continue
}
}
}
}
} catch (e: ReadException) {
Logger.getGlobal().throwing(
"IObject#Extensions",
"remap",
e
)
}
}
}
private fun Iterable<*>.toJsonString(): String {
return joinToString(",", "[", "]") {
it ?.let {
when (it) {
is IInputObject<*, *> -> (it as? IInputObject<String, in Any>) ?. toJsonString() ?: it.toString()
is Iterable<*> -> it.toJsonString()
is Number -> it.toString()
is Boolean -> it.toString()
else -> "\"${it.toString().replace("\"", "\\\"")}\""
}
} ?: "null"
}
}
/**
* Convert [IInputObject] to JSON formatted [String]
*/
fun <K, V> IInputObject<K, V>.toJsonString(): String {
return keys().joinToString(",", "{", "}") {
val value = get<V>(it)
val valueString = when(value) {
is IInputObject<*, *> -> value.toJsonString()
is Iterable<*> -> value.toJsonString()
else -> "\"${value.toString().replace("\"", "\\\"")}\""
}
"\"${it.toString().replace("\"", "\\\"")}\":$valueString"
}
}
private const val delimiter = "/"
private const val lastIdentifier = "last"
/**
* Convert receiver to path which can be used in operations with iterable keys
*/
fun String.toPath(): List<String> {
return this.split(delimiter).filter { it.isNotEmpty() }
}
/**
* Put [value] by [path] into object. In path identifiers as "0" can be used to choose object/array in array or to put in specified position
*/
fun <T> CommonIObject<T, in Any>.put(path: List<T>, value: Any) {
var currentParent: Any = this
path.forEach {
if (path.last() == it) {
when (currentParent) {
is List<*> -> {
(currentParent as? MutableList<Any>)?.let {
currentParent ->
if (it == lastIdentifier) {
currentParent.add(value)
} else {
currentParent.add(it.toString().toInt(), value)
}
}
}
is IInputObject<*, *> -> (currentParent as IOutputObject<T, Any>)[it] = value
else -> throw IllegalStateException("Can't get value by key: $it; It is not list or IOutputObject")
}
} else {
currentParent = when (currentParent) {
is List<*> -> (currentParent as List<*>)[it.toString().toInt()]!!
is IInputObject<*, *> -> (currentParent as CommonIObject<T, Any>)[it]
else -> throw IllegalStateException("Can't get value by key: $it; It is not list or CommonIObject")
}
}
}
}
/**
* Get value by [path] in object. In path identifiers as "0" can be used to choose object/array in array
*/
fun <T, R: Any> IInputObject<T, in Any>.get(path: List<T>): R {
var current: Any = this
path.forEach {
current = when (current) {
is List<*> -> (current as List<*>)[it.toString().toInt()]!!
is IInputObject<*, *> -> (current as IInputObject<T, Any>)[it]
else -> throw IllegalStateException("Can't get value by key: $it; It is not list or CommonIObject")
}
}
return current as R
}
/**
* Cut value by [path] in object. In path identifiers as "0" can be used to choose object/array in array
*/
fun <T, R: Any> CommonIObject<T, in Any>.cut(path: List<T>): R {
var current: Any = this
path.forEach {
val parent = current
current = when (current) {
is List<*> -> (current as List<*>)[it.toString().toInt()]!!
is CommonIObject<*, *> -> (current as CommonIObject<T, Any>)[it]
else -> throw IllegalStateException("Can't get value by key: $it; It is not list or CommonIObject")
}
if (path.last() == it) {
when (parent) {
is MutableList<*> -> (parent as MutableList<Any>).remove(it.toString().toInt())
is CommonIObject<*, *> -> (parent as CommonIObject<T, Any>).remove(it)
else -> throw IllegalStateException("Can't get value by key: $it; It is not list or CommonIObject")
}
}
}
return current as R
} | mit | 700e81699a3e97f0837eabcc3f04eb56 | 31.524648 | 140 | 0.506713 | 4.391821 | false | false | false | false |
smichel17/simpletask-android | app/src/main/java/nl/mpcjanssen/simpletask/MultiComparator.kt | 1 | 3576 | package nl.mpcjanssen.simpletask
import android.util.Log
import nl.mpcjanssen.simpletask.task.Task
import nl.mpcjanssen.simpletask.util.alfaSort
import java.util.*
class MultiComparator(sorts: ArrayList<String>, today: String, caseSensitve: Boolean, createAsBackup: Boolean, moduleName: String? = null) {
var comparator : Comparator<Task>? = null
var fileOrder = true
val luaCache: MutableMap<Task, String> = HashMap<Task, String>();
init {
label@ for (sort in sorts) {
val parts = sort.split(Query.SORT_SEPARATOR.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
var reverse = false
val sortType: String
if (parts.size == 1) {
// support older shortcuts and widgets
reverse = false
sortType = parts[0]
} else {
sortType = parts[1]
if (parts[0] == Query.REVERSED_SORT) {
reverse = true
}
}
var comp: (Task) -> Comparable<*>
val lastDate = "9999-99-99"
when (sortType) {
"file_order" -> {
fileOrder = !reverse
break@label
}
"by_context" -> comp = { t ->
val txt = t.lists?.let { alfaSort(it).firstOrNull() } ?: ""
if (caseSensitve) {
txt
} else {
txt.toLowerCase(Locale.getDefault())
}
}
"by_project" -> comp = { t ->
val txt = t.tags?.let { alfaSort(it).firstOrNull() } ?: ""
if (caseSensitve) {
txt
} else {
txt.toLowerCase(Locale.getDefault())
}
}
"alphabetical" -> comp = if (caseSensitve) {
{ it.showParts { p -> p.isAlpha() } }
} else {
{ it.showParts { p -> p.isAlpha() }.toLowerCase(Locale.getDefault()) }
}
"by_prio" -> comp = { it.priority }
"completed" -> comp = { it.isCompleted() }
"by_creation_date" -> comp = { it.createDate ?: lastDate }
"in_future" -> comp = { it.inFuture(today) }
"by_due_date" -> comp = { it.dueDate ?: lastDate }
"by_threshold_date" -> comp = {
val fallback = if (createAsBackup) it.createDate ?: lastDate else lastDate
it.thresholdDate ?: fallback
}
"by_completion_date" -> comp = { it.completionDate ?: lastDate }
"by_lua" -> {
if (moduleName == null || !Interpreter.hasOnSortCallback(moduleName)) {
continue@label
}
comp = {
luaCache[it] ?: Interpreter.onSortCallback(moduleName, it).also { str ->
luaCache[it] = str
}
}
}
else -> {
Log.w("MultiComparator", "Unknown sort: $sort")
continue@label
}
}
comparator = if (reverse) {
comparator?.thenByDescending(comp) ?: compareByDescending(comp)
} else {
comparator?.thenBy(comp) ?: compareBy(comp)
}
}
}
}
| gpl-3.0 | 13c3d803f9ebb9b5eb29ad166921620e | 38.296703 | 140 | 0.440996 | 4.845528 | false | false | false | false |
veyndan/reddit-client | app/src/main/java/com/veyndan/paper/reddit/ui/widget/PostFlairView.kt | 2 | 1544 | package com.veyndan.paper.reddit.ui.widget
import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.support.v7.widget.AppCompatTextView
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.util.AttributeSet
import android.view.View
import com.binaryfork.spanny.Spanny
import com.veyndan.paper.reddit.MainActivity
import com.veyndan.paper.reddit.api.reddit.Reddit
import com.veyndan.paper.reddit.post.Flair
class PostFlairView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {
init {
movementMethod = LinkMovementMethod.getInstance()
}
fun setFlair(flair: Flair, subreddit: String) {
(background as GradientDrawable).setColor(flair.backgroundColor)
setCompoundDrawablesWithIntrinsicBounds(flair.icon, null, null, null)
if (flair.searchable()) {
text = Spanny.spanText(flair.text.orEmpty(), object : ClickableSpan() {
override fun onClick(widget: View?) {
val intent: Intent = Intent(context, MainActivity::class.java)
intent.putExtra(Reddit.FILTER, Reddit.Filter(
nodeDepth = 0,
subredditName = subreddit,
searchQuery = flair.searchQuery!!))
context.startActivity(intent)
}
})
} else {
text = flair.text.orEmpty()
}
}
}
| mit | 9f9d2615d73fdea84b1a8bc6820db27c | 36.658537 | 96 | 0.663212 | 4.780186 | false | false | false | false |
java-opengl-labs/learn-OpenGL | src/main/kotlin/learnOpenGL/common/Mesh.kt | 1 | 5733 | package learnOpenGL.common
import assimp.AiMaterial
import assimp.AiMesh
import assimp.AiScene
import assimp.AiTexture
import glm_.set
import gln.draw.glDrawElements
import gln.get
import gln.glf.glf
import gln.glf.semantic
import gln.texture.glBindTexture
import gln.texture.initTexture2d
import gln.vertexArray.glBindVertexArray
import gln.vertexArray.glVertexAttribPointer
import gln.vertexArray.withVertexArray
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL13.GL_TEXTURE0
import org.lwjgl.opengl.GL13.glActiveTexture
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.glEnableVertexAttribArray
import org.lwjgl.opengl.GL30.*
import uno.buffer.destroy
import uno.buffer.floatBufferBig
import uno.buffer.intBufferBig
import uno.buffer.intBufferOf
import java.nio.IntBuffer
/**
* Created by GBarbieri on 02.05.2017.
*/
class Mesh(assimpMesh: AiMesh, scene: AiScene) {
val vao = intBufferBig(1)
enum class Buffer { Vertex, Element }
val buffers = intBufferBig<Buffer>()
val indexCount: Int
var diffuseMap: IntBuffer? = null
var specularMap: IntBuffer? = null
init { // Now that we have all the required data, set the vertex buffers and its attribute pointers.
// Create buffers/arrays
glGenVertexArrays(vao)
glGenBuffers(buffers)
glBindVertexArray(vao)
// Load data into vertex buffers
glBindBuffer(GL_ARRAY_BUFFER, buffers[Buffer.Vertex])
val vertexSize = 3 + 3 + 2
val vertices = floatBufferBig(vertexSize * assimpMesh.numVertices)
assimpMesh.vertices.forEachIndexed { i, v ->
val n = assimpMesh.normals[i]
v.to(vertices, i * vertexSize)
n.to(vertices, i * vertexSize + 3)
if (assimpMesh.textureCoords[0].isNotEmpty()) {
val tc = assimpMesh.textureCoords[0][i]
vertices[i * vertexSize + 3 + 3] = tc[0]
vertices[i * vertexSize + 3 + 3 + 1] = tc[1]
}
}
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[Buffer.Element])
indexCount = assimpMesh.numFaces * 3
val indices = intBufferBig(indexCount)
repeat(indexCount) { indices[it] = assimpMesh.faces[it / 3][it % 3] }
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW)
// Set the vertex attribute pointers
// Vertex Positions
glEnableVertexAttribArray(semantic.attr.POSITION)
glVertexAttribPointer(glf.pos3_nor3_tc2)
// Vertex Normals
glEnableVertexAttribArray(semantic.attr.NORMAL)
glVertexAttribPointer(glf.pos3_nor3_tc2[1])
// Vertex Texture Coords
glEnableVertexAttribArray(semantic.attr.TEX_COORD)
glVertexAttribPointer(glf.pos3_nor3_tc2[2])
// Vertex Tangent
// glEnableVertexAttribArray(3)
// glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *) offsetof (Vertex, Tangent))
// // Vertex Bitangent
// glEnableVertexAttribArray(4)
// glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *) offsetof (Vertex, Bitangent))
glBindVertexArray()
// Process materials
with(scene.materials[assimpMesh.materialIndex]) {
textures.firstOrNull { it.type == AiTexture.Type.diffuse }?.let {
diffuseMap = intBufferOf(loadMaterialTexture(it, scene))
}
textures.firstOrNull { it.type == AiTexture.Type.specular }?.let {
specularMap = intBufferOf(loadMaterialTexture(it, scene))
}
}
}
/**
* Checks all material textures of a given type and loads the textures if they're not loaded yet.
* The required info is returned as a Texture struct.
*/
fun loadMaterialTexture(assimpTex: AiMaterial.Texture, scene: AiScene) = initTexture2d {
val gliTexture = scene.textures[assimpTex.file]!!
// val format = gli.gl.translate(gliTexture.format, gliTexture.swizzles)
// image(format.internal, gliTexture.)
// glTexImage2D(format, gliTexture)
image(gliTexture)
glGenerateMipmap(GL_TEXTURE_2D)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
}
fun draw(diffuse: Boolean = false, specular: Boolean = false) {
if (diffuse) diffuseMap?.let {
glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE)
glBindTexture(GL_TEXTURE_2D, it)
}
if (specular) specularMap?.let {
glActiveTexture(GL_TEXTURE0 + semantic.sampler.SPECULAR)
glBindTexture(GL_TEXTURE_2D, it)
}
// Draw mesh
withVertexArray(vao) {
glDrawElements(indexCount)
}
// Always good practice to set everything back to defaults once configured.
if (diffuse) diffuseMap?.let {
glActiveTexture(GL_TEXTURE0 + semantic.sampler.DIFFUSE)
glBindTexture(GL_TEXTURE_2D)
}
if (specular) specularMap?.let {
glActiveTexture(GL_TEXTURE0 + semantic.sampler.SPECULAR)
glBindTexture(GL_TEXTURE_2D)
}
}
fun dispose() {
glDeleteVertexArrays(vao)
glDeleteBuffers(buffers)
diffuseMap?.let {
glDeleteTextures(it)
it.destroy()
}
specularMap?.let {
glDeleteTextures(it)
it.destroy()
}
}
}
| mit | 138ebb9dff4b84ebfb747d98e1395b9a | 33.329341 | 114 | 0.653236 | 4.175528 | false | false | false | false |
inorichi/tachiyomi-extensions | src/ru/selfmanga/src/eu/kanade/tachiyomi/extension/ru/selfmanga/Selfmanga.kt | 1 | 10169 | package eu.kanade.tachiyomi.extension.ru.selfmanga
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.source.model.Filter
import eu.kanade.tachiyomi.source.model.FilterList
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.model.SChapter
import eu.kanade.tachiyomi.source.model.SManga
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.Request
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.regex.Pattern
class Selfmanga : ParsedHttpSource() {
override val name = "Selfmanga"
override val baseUrl = "https://selfmanga.live"
override val lang = "ru"
override val supportsLatest = true
override fun popularMangaSelector() = "div.tile"
override fun latestUpdatesSelector() = popularMangaSelector()
override fun popularMangaRequest(page: Int): Request =
GET("$baseUrl/list?sortType=rate&offset=${70 * (page - 1)}", headers)
override fun latestUpdatesRequest(page: Int): Request =
GET("$baseUrl/list?sortType=updated&offset=${70 * (page - 1)}", headers)
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.thumbnail_url = element.select("img.lazy").first().attr("data-original")
element.select("h3 > a").first().let {
manga.setUrlWithoutDomain(it.attr("href"))
manga.title = it.attr("title")
}
return manga
}
override fun latestUpdatesFromElement(element: Element): SManga =
popularMangaFromElement(element)
override fun popularMangaNextPageSelector() = "a.nextLink"
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
val url = "$baseUrl/search/advanced".toHttpUrlOrNull()!!.newBuilder()
(if (filters.isEmpty()) getFilterList() else filters).forEach { filter ->
when (filter) {
is GenreList -> filter.state.forEach { genre ->
if (genre.state != Filter.TriState.STATE_IGNORE) {
url.addQueryParameter(genre.id, arrayOf("=", "=in", "=ex")[genre.state])
}
}
is Category -> filter.state.forEach { category ->
if (category.state != Filter.TriState.STATE_IGNORE) {
url.addQueryParameter(category.id, arrayOf("=", "=in", "=ex")[category.state])
}
}
}
}
if (query.isNotEmpty()) {
url.addQueryParameter("q", query)
}
return GET(url.toString().replace("=%3D", "="), headers)
}
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaFromElement(element: Element): SManga = popularMangaFromElement(element)
// max 200 results
override fun searchMangaNextPageSelector(): Nothing? = null
override fun mangaDetailsParse(document: Document): SManga {
val infoElement = document.select(".expandable").first()
val manga = SManga.create()
manga.title = document.select("h1.names .name").text()
manga.author = infoElement.select("span.elem_author").first()?.text()
manga.genre = infoElement.select("span.elem_genre").text().replace(" ,", ",")
manga.description = infoElement.select("div.manga-description").text()
manga.status = parseStatus(infoElement.html())
manga.thumbnail_url = infoElement.select("img").attr("data-full")
return manga
}
private fun parseStatus(element: String): Int = when {
element.contains("Запрещена публикация произведения по копирайту") || element.contains("ЗАПРЕЩЕНА К ПУБЛИКАЦИИ НА ТЕРРИТОРИИ РФ!") -> SManga.LICENSED
element.contains("<b>Сингл</b>") || element.contains("выпуск завершен") -> SManga.COMPLETED
element.contains("выпуск продолжается") -> SManga.ONGOING
else -> SManga.UNKNOWN
}
override fun chapterListSelector() = "div.chapters-link tbody tr"
override fun chapterFromElement(element: Element): SChapter {
val urlElement = element.select("a").first()
val urlText = urlElement.text()
val chapter = SChapter.create()
chapter.setUrlWithoutDomain(urlElement.attr("href") + "?mtr=1")
if (urlText.endsWith(" новое")) {
chapter.name = urlText.dropLast(6)
} else {
chapter.name = urlText
}
chapter.date_upload = element.select("td.hidden-xxs").last()?.text()?.let {
try {
SimpleDateFormat("dd/MM/yy", Locale.US).parse(it)?.time ?: 0L
} catch (e: ParseException) {
SimpleDateFormat("dd.MM.yy", Locale.US).parse(it)?.time ?: 0L
}
} ?: 0
return chapter
}
override fun prepareNewChapter(chapter: SChapter, manga: SManga) {
val basic = Regex("""\s*([0-9]+)(\s-\s)([0-9]+)\s*""")
val extra = Regex("""\s*([0-9]+\sЭкстра)\s*""")
val single = Regex("""\s*Сингл\s*""")
when {
basic.containsMatchIn(chapter.name) -> {
basic.find(chapter.name)?.let {
val number = it.groups[3]?.value!!
chapter.chapter_number = number.toFloat()
}
}
extra.containsMatchIn(chapter.name) -> // Extra chapters doesn't contain chapter number
chapter.chapter_number = -2f
single.containsMatchIn(chapter.name) -> // Oneshoots, doujinshi and other mangas with one chapter
chapter.chapter_number = 1f
}
}
override fun pageListParse(response: Response): List<Page> {
val html = response.body!!.string()
val beginIndex = html.indexOf("rm_h.init( [")
val endIndex = html.indexOf(");", beginIndex)
val trimmedHtml = html.substring(beginIndex, endIndex)
val p = Pattern.compile("'.*?','.*?',\".*?\"")
val m = p.matcher(trimmedHtml)
val pages = mutableListOf<Page>()
var i = 0
while (m.find()) {
val urlParts = m.group().replace("[\"\']+".toRegex(), "").split(',')
val url = if (urlParts[1].isEmpty() && urlParts[2].startsWith("/static/")) {
baseUrl + urlParts[2]
} else {
if (urlParts[1].endsWith("/manga/")) {
urlParts[0] + urlParts[2]
} else {
urlParts[1] + urlParts[0] + urlParts[2]
}
}
pages.add(Page(i++, "", url))
}
return pages
}
override fun pageListParse(document: Document): List<Page> {
throw Exception("Not used")
}
override fun imageUrlParse(document: Document) = ""
override fun imageRequest(page: Page): Request {
val imgHeader = Headers.Builder().apply {
add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64)")
add("Referer", baseUrl)
}.build()
return GET(page.imageUrl!!, imgHeader)
}
private class Genre(name: String, val id: String) : Filter.TriState(name)
private class GenreList(genres: List<Genre>) : Filter.Group<Genre>("Genres", genres)
private class Category(categories: List<Genre>) : Filter.Group<Genre>("Category", categories)
/* [...document.querySelectorAll("tr.advanced_option:nth-child(1) > td:nth-child(3) span.js-link")]
* .map(el => `Genre("${el.textContent.trim()}", $"{el.getAttribute('onclick')
* .substr(31,el.getAttribute('onclick').length-33)"})`).join(',\n')
* on https://selfmanga.ru/search/advanced
*/
override fun getFilterList() = FilterList(
Category(getCategoryList()),
GenreList(getGenreList())
)
private fun getCategoryList() = listOf(
Genre("Артбук", "el_5894"),
Genre("Веб", "el_2160"),
Genre("Журнал", "el_4983"),
Genre("Ранобэ", "el_5215"),
Genre("Сборник", "el_2157")
)
private fun getGenreList() = listOf(
Genre("боевик", "el_2155"),
Genre("боевые искусства", "el_2143"),
Genre("вампиры", "el_2148"),
Genre("гарем", "el_2142"),
Genre("гендерная интрига", "el_2156"),
Genre("героическое фэнтези", "el_2146"),
Genre("детектив", "el_2152"),
Genre("дзёсэй", "el_2158"),
Genre("додзинси", "el_2141"),
Genre("драма", "el_2118"),
Genre("ёнкома", "el_2161"),
Genre("история", "el_2119"),
Genre("комедия", "el_2136"),
Genre("махо-сёдзё", "el_2147"),
Genre("мистика", "el_2132"),
Genre("научная фантастика", "el_2133"),
Genre("повседневность", "el_2135"),
Genre("постапокалиптика", "el_2151"),
Genre("приключения", "el_2130"),
Genre("психология", "el_2144"),
Genre("романтика", "el_2121"),
Genre("сверхъестественное", "el_2159"),
Genre("сёдзё", "el_2122"),
Genre("сёдзё-ай", "el_2128"),
Genre("сёнэн", "el_2134"),
Genre("сёнэн-ай", "el_2139"),
Genre("спорт", "el_2129"),
Genre("сэйнэн", "el_5838"),
Genre("трагедия", "el_2153"),
Genre("триллер", "el_2150"),
Genre("ужасы", "el_2125"),
Genre("фантастика", "el_2140"),
Genre("фэнтези", "el_2131"),
Genre("школа", "el_2127"),
Genre("этти", "el_4982")
)
}
| apache-2.0 | 0f671b766e48e821adf247858f5de18e | 37.97992 | 157 | 0.594066 | 3.935929 | false | false | false | false |
Mindera/skeletoid | kt-extensions/src/main/java/com/mindera/skeletoid/kt/extensions/views/View.kt | 1 | 1490 | @file:Suppress("NOTHING_TO_INLINE")
package com.mindera.skeletoid.kt.extensions.views
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewGroup
import android.view.ViewTreeObserver
fun View.visible() {
visibility = VISIBLE
}
fun View.invisible() {
visibility = INVISIBLE
}
fun View.gone() {
visibility = GONE
}
fun View.isVisible(): Boolean {
return visibility == VISIBLE
}
fun View.isInvisible(): Boolean {
return visibility == INVISIBLE
}
fun View.isGone(): Boolean {
return visibility == GONE
}
fun View.disableChildren(enabled: Boolean) {
this.isEnabled = enabled
if (this is ViewGroup) {
for (i in 0 until this.childCount) {
this.getChildAt(i).disableChildren(enabled)
}
}
}
fun View.setPaddingTop(paddingTop: Int) {
setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
}
fun View.setPaddingBottom(paddingBottom: Int) {
setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom)
}
inline fun <T: View> T.afterDrawn(crossinline nextFunction: T.() -> Unit) {
viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
if (measuredWidth > 0 && measuredHeight > 0) {
viewTreeObserver.removeOnGlobalLayoutListener(this)
nextFunction()
}
}
})
}
| mit | 722b0d961413aba81b417b6352845a40 | 22.28125 | 97 | 0.69396 | 4.306358 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/presentation/library/components/LibraryGridCover.kt | 1 | 2467 | package eu.kanade.presentation.library.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import eu.kanade.presentation.components.BadgeGroup
import eu.kanade.presentation.components.MangaCover
import eu.kanade.tachiyomi.ui.library.LibraryItem
@Composable
fun MangaGridCover(
modifier: Modifier = Modifier,
cover: @Composable BoxScope.() -> Unit = {},
badgesStart: (@Composable RowScope.() -> Unit)? = null,
badgesEnd: (@Composable RowScope.() -> Unit)? = null,
content: @Composable BoxScope.() -> Unit = {},
) {
Box(
modifier = modifier
.fillMaxWidth()
.aspectRatio(MangaCover.Book.ratio),
) {
cover()
content()
if (badgesStart != null) {
BadgeGroup(
modifier = Modifier
.padding(4.dp)
.align(Alignment.TopStart),
content = badgesStart,
)
}
if (badgesEnd != null) {
BadgeGroup(
modifier = Modifier
.padding(4.dp)
.align(Alignment.TopEnd),
content = badgesEnd,
)
}
}
}
@Composable
fun LibraryGridCover(
modifier: Modifier = Modifier,
mangaCover: eu.kanade.domain.manga.model.MangaCover,
item: LibraryItem,
showDownloadBadge: Boolean,
showUnreadBadge: Boolean,
showLocalBadge: Boolean,
showLanguageBadge: Boolean,
content: @Composable BoxScope.() -> Unit = {},
) {
MangaGridCover(
modifier = modifier,
cover = {
MangaCover.Book(
modifier = Modifier.fillMaxWidth(),
data = mangaCover,
)
},
badgesStart = {
DownloadsBadge(enabled = showDownloadBadge, item = item)
UnreadBadge(enabled = showUnreadBadge, item = item)
},
badgesEnd = {
LanguageBadge(showLanguage = showLanguageBadge, showLocal = showLocalBadge, item = item)
},
content = content,
)
}
| apache-2.0 | 50ff8ba88cc0be79f43324b60a330063 | 29.8375 | 100 | 0.619781 | 4.681214 | false | false | false | false |
wesamhaboush/kotlin-algorithms | src/main/kotlin/algorithms/circular-primes.kt | 1 | 3294 | package algorithms
/*
Circular primes
Problem 35
The number, 197, is called a circular prime because all rotations of the digits:
197, 971, and 719, are themselves prime.
There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97.
How many circular primes are there below one million?
The idea of the solution is to find the numbers in a much smaller search space. For example:
- No even digits are allowed, so 0, 2, 4, 6, 8 are not allowed to be in the numbers except the prime 2)
- The digit five is not allowed in the number (except the prime 5 itself
- Any set of digits with a sum that divides by 3 (except the prime 4 itself)
- Then we can test for primeness
*/
fun circularPrimes(upperBound: Long): Set<Long> {
require(isPowerOf(upperBound, 10)) { "upperBound must be a power of 10" }
// find how many digits can our number be:
// for example, if input is 10000, then a max of 4 digits are required,
// so we need to generate all 1 digit numbers (x), and two digits (xx), three digits(xxx)
// and finally four digit numbers (xxxx)
val maxNumberOfDigits = countDigitsInNumber(upperBound) - 1
val circularPrimesSet =
// we need to add the single digit numbers that are circular always
// and the general rules do not apply to them
sequenceOf(2L, 3L, 5L).filter { it < upperBound } + generateSequence(1) { it + 1 }
// we need to generate a sequence of digit couts, for example
// for 10000 upperBound, we need to generate (1, 2, 3, 4) sequence
// in order to generate their combinations
.take(maxNumberOfDigits)
//each number of digits value will generate a list of values
// so we need to flat map (from 1 digits -> List() + 2 digits -> List()) etc.
.flatMap {
// from each number of digits, generate the possible combinations
// for example, for 2 digits, we find all combinations from
// (1, 3, 7, 9) of 2 digits, ie. 13, 31, 79, 97, 37, 73, 19, 91, etc.
generateListOfPossibleCircularPrimesSequence(0, it)
.filter { !divides3(it) } // anything that divides by 3 is not prime
.filter { isPrime(it) } // anything that's not prime is toast
.filter {
// now we find all cicle combinations from the number in question
// and make sure they are all prime
allCircularNumbersFrom(it).all { isPrime(it) }
}
}
return circularPrimesSet.toSortedSet() // sorting it for beauty :)
}
private val allowedDigits = listOf(1, 3, 7, 9)
fun generateListOfPossibleCircularPrimesSequence(current: Long, numDigits: Int): Sequence<Long> {
return if (numDigits == 0)
sequenceOf(current)
else
allowedDigits
.asSequence()
.flatMap {
generateListOfPossibleCircularPrimesSequence(current * 10 + it, numDigits - 1)
}
}
| gpl-3.0 | 64a205875b0d2fc42967fd8c036fc0b2 | 46.73913 | 103 | 0.58895 | 4.487738 | false | false | false | false |
exponentjs/exponent | android/expoview/src/main/java/host/exp/exponent/notifications/helpers/ExpoCronParser.kt | 2 | 2021 | package host.exp.exponent.notifications.helpers
import com.cronutils.builder.CronBuilder
import com.cronutils.model.Cron
import com.cronutils.model.field.expression.FieldExpressionFactory
import java.util.*
object ExpoCronParser {
@JvmStatic fun createCronInstance(options: HashMap<String?, Any?>): Cron {
val cronBuilder = CronBuilder.cron(ExpoCronDefinitionBuilder.cronDefinition)
val year = options["year"]
if (year is Number) {
cronBuilder.withYear(FieldExpressionFactory.on(year.toInt()))
} else {
cronBuilder.withYear(FieldExpressionFactory.always())
}
val hour = options["hour"]
if (hour is Number) {
cronBuilder.withHour(FieldExpressionFactory.on(hour.toInt()))
} else {
cronBuilder.withHour(FieldExpressionFactory.always())
}
val minute = options["minute"]
if (minute is Number) {
cronBuilder.withMinute(FieldExpressionFactory.on(minute.toInt()))
} else {
cronBuilder.withMinute(FieldExpressionFactory.always())
}
val second = options["second"]
if (second is Number) {
cronBuilder.withSecond(FieldExpressionFactory.on(second.toInt()))
} else {
cronBuilder.withSecond(FieldExpressionFactory.always())
}
val month = options["month"]
if (month is Number) {
cronBuilder.withMonth(FieldExpressionFactory.on(month.toInt()))
} else {
cronBuilder.withMonth(FieldExpressionFactory.always())
}
val day = options["day"]
if (day is Number) {
cronBuilder.withDoM(FieldExpressionFactory.on(day.toInt()))
} else if (options.containsKey("weekDay")) {
cronBuilder.withDoM(FieldExpressionFactory.questionMark())
} else {
cronBuilder.withDoM(FieldExpressionFactory.always())
}
val weekDay = options["weekDay"]
if (weekDay is Number) {
cronBuilder.withDoW(FieldExpressionFactory.on(weekDay.toInt()))
} else {
cronBuilder.withDoW(FieldExpressionFactory.questionMark())
}
return cronBuilder.instance()
}
}
| bsd-3-clause | ea1c6c5ece72b22eaca150afff8cef6b | 30.092308 | 80 | 0.701138 | 3.909091 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt | 1 | 13012 | package info.nightscout.androidaps.plugins.general.tidepool.comm
import android.content.Context
import android.os.PowerManager
import android.os.SystemClock
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus
import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthReplyMessage
import info.nightscout.androidaps.plugins.general.tidepool.messages.AuthRequestMessage
import info.nightscout.androidaps.plugins.general.tidepool.messages.DatasetReplyMessage
import info.nightscout.androidaps.plugins.general.tidepool.messages.OpenDatasetRequestMessage
import info.nightscout.androidaps.plugins.general.tidepool.messages.UploadReplyMessage
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TidepoolUploader @Inject constructor(
private val aapsLogger: AAPSLogger,
private val rxBus: RxBus,
private val ctx: Context,
private val rh: ResourceHelper,
private val sp: SP,
private val uploadChunk: UploadChunk,
private val activePlugin: ActivePlugin,
private val dateUtil: DateUtil
) {
private var wl: PowerManager.WakeLock? = null
companion object {
private const val INTEGRATION_BASE_URL = "https://int-api.tidepool.org"
private const val PRODUCTION_BASE_URL = "https://api.tidepool.org"
internal const val VERSION = "0.0.1"
const val PUMP_TYPE = "Tandem"
}
private var retrofit: Retrofit? = null
private var session: Session? = null
enum class ConnectionStatus {
DISCONNECTED, CONNECTING, CONNECTED, FAILED
}
var connectionStatus: ConnectionStatus = ConnectionStatus.DISCONNECTED
private fun getRetrofitInstance(): Retrofit? {
if (retrofit == null) {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
val client = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(InfoInterceptor(TidepoolUploader::class.java.name, aapsLogger))
.build()
retrofit = Retrofit.Builder()
.baseUrl(if (sp.getBoolean(R.string.key_tidepool_dev_servers, false)) INTEGRATION_BASE_URL else PRODUCTION_BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit
}
private fun createSession(): Session {
val service = getRetrofitInstance()?.create(TidepoolApiService::class.java)
return Session(AuthRequestMessage.getAuthRequestHeader(sp), SESSION_TOKEN_HEADER, service)
}
// TODO: call on preference change
fun resetInstance() {
retrofit = null
aapsLogger.debug(LTag.TIDEPOOL, "Instance reset")
connectionStatus = ConnectionStatus.DISCONNECTED
}
@Synchronized
fun doLogin(doUpload: Boolean = false) {
if (connectionStatus == ConnectionStatus.CONNECTED || connectionStatus == ConnectionStatus.CONNECTING) {
aapsLogger.debug(LTag.TIDEPOOL, "Already connected")
return
}
// TODO failure backoff
extendWakeLock(30000)
session = createSession()
val authHeader = session?.authHeader
if (authHeader != null) {
connectionStatus = ConnectionStatus.CONNECTING
rxBus.send(EventTidepoolStatus(("Connecting")))
val call = session?.service?.getLogin(authHeader)
call?.enqueue(TidepoolCallback<AuthReplyMessage>(aapsLogger, rxBus, session!!, "Login", {
startSession(session!!, doUpload)
}, {
connectionStatus = ConnectionStatus.FAILED
releaseWakeLock()
}))
return
} else {
aapsLogger.debug(LTag.TIDEPOOL, "Cannot do login as user credentials have not been set correctly")
connectionStatus = ConnectionStatus.FAILED
rxBus.send(EventTidepoolStatus(("Invalid credentials")))
releaseWakeLock()
return
}
}
fun testLogin(rootContext: Context) {
val session = createSession()
session.authHeader?.let {
val call = session.service?.getLogin(it)
call?.enqueue(TidepoolCallback<AuthReplyMessage>(aapsLogger, rxBus, session, "Login", {
OKDialog.show(rootContext, rh.gs(R.string.tidepool), "Successfully logged into Tidepool.")
}, {
OKDialog.show(rootContext, rh.gs(R.string.tidepool), "Failed to log into Tidepool.\nCheck that your user name and password are correct.")
}))
}
?: OKDialog.show(rootContext, rh.gs(R.string.tidepool), "Cannot do login as user credentials have not been set correctly")
}
private fun startSession(session: Session, doUpload: Boolean = false) {
extendWakeLock(30000)
if (session.authReply?.userid != null) {
// See if we already have an open data set to write to
val datasetCall = session.service!!.getOpenDataSets(session.token!!,
session.authReply!!.userid!!, BuildConfig.APPLICATION_ID, 1)
datasetCall.enqueue(TidepoolCallback<List<DatasetReplyMessage>>(aapsLogger, rxBus, session, "Get Open Datasets", {
if (session.datasetReply == null) {
rxBus.send(EventTidepoolStatus(("Creating new dataset")))
val call = session.service.openDataSet(session.token!!, session.authReply!!.userid!!,
OpenDatasetRequestMessage(activePlugin.activePump.serialNumber(), dateUtil).getBody())
call.enqueue(TidepoolCallback<DatasetReplyMessage>(aapsLogger, rxBus, session, "Open New Dataset", {
connectionStatus = ConnectionStatus.CONNECTED
rxBus.send(EventTidepoolStatus(("New dataset OK")))
if (doUpload) doUpload()
else
releaseWakeLock()
}, {
rxBus.send(EventTidepoolStatus(("New dataset FAILED")))
connectionStatus = ConnectionStatus.FAILED
releaseWakeLock()
}))
} else {
aapsLogger.debug(LTag.TIDEPOOL, "Existing Dataset: " + session.datasetReply!!.getUploadId())
// TODO: Wouldn't need to do this if we could block on the above `call.enqueue`.
// ie, do the openDataSet conditionally, and then do `doUpload` either way.
connectionStatus = ConnectionStatus.CONNECTED
rxBus.send(EventTidepoolStatus(("Appending to existing dataset")))
if (doUpload) doUpload()
else
releaseWakeLock()
}
}, {
connectionStatus = ConnectionStatus.FAILED
rxBus.send(EventTidepoolStatus(("Open dataset FAILED")))
releaseWakeLock()
}))
} else {
aapsLogger.error("Got login response but cannot determine userId - cannot proceed")
connectionStatus = ConnectionStatus.FAILED
rxBus.send(EventTidepoolStatus(("Error userId")))
releaseWakeLock()
}
}
@Synchronized
fun doUpload() {
session.let { session ->
if (session == null) {
aapsLogger.error("Session is null, cannot proceed")
releaseWakeLock()
return
}
extendWakeLock(60000)
session.iterations++
val chunk = uploadChunk.getNext(session)
when {
chunk == null -> {
aapsLogger.error("Upload chunk is null, cannot proceed")
releaseWakeLock()
}
chunk.length == 2 -> {
aapsLogger.debug(LTag.TIDEPOOL, "Empty dataset - marking as succeeded")
rxBus.send(EventTidepoolStatus(("No data to upload")))
releaseWakeLock()
uploadNext()
}
else -> {
val body = chunk.toRequestBody("application/json".toMediaTypeOrNull())
rxBus.send(EventTidepoolStatus(("Uploading")))
if (session.service != null && session.token != null && session.datasetReply != null) {
val call = session.service.doUpload(session.token!!, session.datasetReply!!.getUploadId()!!, body)
call.enqueue(TidepoolCallback<UploadReplyMessage>(aapsLogger, rxBus, session, "Data Upload", {
uploadChunk.setLastEnd(session.end)
rxBus.send(EventTidepoolStatus(("Upload completed OK")))
releaseWakeLock()
uploadNext()
}, {
rxBus.send(EventTidepoolStatus(("Upload FAILED")))
releaseWakeLock()
}))
}
}
}
}
}
private fun uploadNext() {
if (uploadChunk.getLastEnd() < dateUtil.now() - T.mins(1).msecs()) {
SystemClock.sleep(3000)
aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + dateUtil.dateAndTimeString(uploadChunk.getLastEnd()))
doUpload()
}
}
fun deleteDataSet() {
if (session?.datasetReply?.id != null) {
extendWakeLock(60000)
val call = session!!.service?.deleteDataSet(session!!.token!!, session!!.datasetReply!!.id!!)
call?.enqueue(TidepoolCallback(aapsLogger, rxBus, session!!, "Delete Dataset", {
connectionStatus = ConnectionStatus.DISCONNECTED
rxBus.send(EventTidepoolStatus(("Dataset removed OK")))
releaseWakeLock()
}, {
connectionStatus = ConnectionStatus.DISCONNECTED
rxBus.send(EventTidepoolStatus(("Dataset remove FAILED")))
releaseWakeLock()
}))
} else {
aapsLogger.error("Got login response but cannot determine datasetId - cannot proceed")
}
}
@Suppress("unused")
fun deleteAllData() {
val session = this.session
val token = session?.token
val userId = session?.authReply?.userid
try {
requireNotNull(session)
requireNotNull(token)
requireNotNull(userId)
extendWakeLock(60000)
val call = session.service?.deleteAllData(token, userId)
call?.enqueue(TidepoolCallback(aapsLogger, rxBus, session, "Delete all data", {
connectionStatus = ConnectionStatus.DISCONNECTED
rxBus.send(EventTidepoolStatus(("All data removed OK")))
releaseWakeLock()
}, {
connectionStatus = ConnectionStatus.DISCONNECTED
rxBus.send(EventTidepoolStatus(("All data remove FAILED")))
releaseWakeLock()
}))
} catch (e: IllegalArgumentException) {
aapsLogger.error("Got login response but cannot determine userId - cannot proceed")
}
}
@Synchronized
private fun extendWakeLock(ms: Long) {
if (wl == null) {
val pm = ctx.getSystemService(Context.POWER_SERVICE) as PowerManager
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:TidepoolUploader")
wl?.acquire(ms)
} else {
releaseWakeLock() // lets not get too messy
wl?.acquire(ms)
}
}
@Synchronized
private fun releaseWakeLock() {
wl?.let {
if (it.isHeld) {
try {
it.release()
} catch (e: Exception) {
aapsLogger.error("Error releasing wakelock: $e")
}
}
}
}
} | agpl-3.0 | 77b89eb3980b65b00abbdae44f56e0bd | 40.977419 | 153 | 0.606901 | 5.274422 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/data/Capability.kt | 1 | 11175 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.data
import arcs.core.util.Time
/** A base class for all the store capabilities. */
sealed class Capability(val tag: String) {
enum class Comparison { LessStrict, Equivalent, Stricter }
open fun isEquivalent(other: Capability): Boolean {
return when (other) {
is Range -> toRange().isEquivalent(other)
else -> compare(other) == Comparison.Equivalent
}
}
open fun contains(other: Capability): Boolean {
return when (other) {
is Range -> toRange().contains(other)
else -> isEquivalent(other)
}
}
fun isLessStrict(other: Capability) = compare(other) == Comparison.LessStrict
fun isSameOrLessStrict(other: Capability) = compare(other) != Comparison.Stricter
fun isStricter(other: Capability) = compare(other) == Comparison.Stricter
fun isSameOrStricter(other: Capability) = compare(other) != Comparison.LessStrict
fun compare(other: Capability): Comparison {
if (tag != other.tag) throw IllegalArgumentException("Cannot compare different Capabilities")
return when (this) {
is Persistence -> compare(other as Persistence)
is Encryption -> compare(other as Encryption)
is Ttl -> compare(other as Ttl)
is Queryable -> compare(other as Queryable)
is Shareable -> compare(other as Shareable)
is Range -> throw UnsupportedOperationException(
"Capability.Range comparison not supported yet."
)
}
}
/**
* Returns its own tag if this is an individual capability, or the tag of the inner capability,
* if this is a range.
*/
fun getRealTag(): String {
return when (tag) {
Capability.Range.TAG -> (this as Capability.Range).min.tag
else -> tag
}
}
fun isCompatible(other: Capability): Boolean {
return getRealTag() == other.getRealTag()
}
open fun toRange() = Range(this, this)
/** Capability describing persistence requirement for the store. */
data class Persistence(val kind: Kind) : Capability(TAG) {
enum class Kind { None, InMemory, OnDisk, Unrestricted }
fun compare(other: Persistence): Comparison {
return when {
kind.ordinal < other.kind.ordinal -> Comparison.Stricter
kind.ordinal > other.kind.ordinal -> Comparison.LessStrict
else -> Comparison.Equivalent
}
}
companion object {
const val TAG = "persistence"
val UNRESTRICTED = Persistence(Kind.Unrestricted)
val ON_DISK = Persistence(Kind.OnDisk)
val IN_MEMORY = Persistence(Kind.InMemory)
val NONE = Persistence(Kind.None)
val ANY = Range(Persistence.UNRESTRICTED, Persistence.NONE)
fun fromAnnotations(annotations: List<Annotation>): Persistence? {
val kinds = mutableSetOf<Kind>()
for (annotation in annotations) {
when (annotation.name) {
"onDisk", "persistent" -> {
if (annotation.params.size > 0) {
throw IllegalArgumentException(
"Unexpected parameter for $annotation.name capability annotation"
)
}
kinds.add(Kind.OnDisk)
}
"inMemory", "tiedToArc", "tiedToRuntime" -> {
if (annotation.params.size > 0) {
throw IllegalArgumentException(
"Unexpected parameter for $annotation.name capability annotation"
)
}
kinds.add(Kind.InMemory)
}
}
}
return when (kinds.size) {
0 -> null
1 -> Persistence(kinds.elementAt(0))
else -> throw IllegalArgumentException(
"Containing multiple persistence capabilities: $annotations"
)
}
}
}
}
/** Capability describing retention policy of the store. */
sealed class Ttl(count: Int, val isInfinite: Boolean = false) : Capability(TAG) {
/** Number of minutes for retention, or -1 for infinite. */
val minutes: Int = count * when (this) {
is Minutes -> 1
is Hours -> 60
is Days -> 60 * 24
is Infinite -> 1 // returns -1 because Infinite `count` is -1.
}
/** Number of milliseconds for retention, or -1 for infinite. */
val millis: Long = if (this is Infinite) -1 else minutes * MILLIS_IN_MIN
init {
require(count > 0 || isInfinite) {
"must be either positive count or infinite, " +
"but got count=$count and isInfinite=$isInfinite"
}
}
fun compare(other: Ttl): Comparison {
return when {
(isInfinite && other.isInfinite) || millis == other.millis -> Comparison.Equivalent
isInfinite -> Comparison.LessStrict
other.isInfinite -> Comparison.Stricter
millis < other.millis -> Comparison.Stricter
else -> Comparison.LessStrict
}
}
fun calculateExpiration(time: Time): Long {
return if (isInfinite) RawEntity.UNINITIALIZED_TIMESTAMP
else time.currentTimeMillis + millis
}
data class Minutes(val count: Int) : Ttl(count)
data class Hours(val count: Int) : Ttl(count)
data class Days(val count: Int) : Ttl(count)
data class Infinite(val count: Int = TTL_INFINITE) : Ttl(count, true)
companion object {
const val TAG = "ttl"
const val TTL_INFINITE = -1
const val MILLIS_IN_MIN = 60 * 1000L
val ANY = Range(Ttl.Infinite(), Ttl.Minutes(1))
private val TTL_PATTERN =
"^([0-9]+)[ ]*(day[s]?|hour[s]?|minute[s]?|[d|h|m])$".toRegex()
fun fromString(ttlStr: String): Ttl {
val ttlMatch = requireNotNull(TTL_PATTERN.matchEntire(ttlStr.trim())) {
"Invalid TTL $ttlStr."
}
val (_, count, units) = ttlMatch.groupValues
// Note: consider using idiomatic KT types:
// https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.time/-duration-unit/
return when (units.trim()) {
"m", "minute", "minutes" -> Ttl.Minutes(count.toInt())
"h", "hour", "hours" -> Ttl.Hours(count.toInt())
"d", "day", "days" -> Ttl.Days(count.toInt())
else -> throw IllegalStateException("Invalid TTL units: $units")
}
}
fun fromAnnotations(annotations: List<Annotation>): Ttl? {
val ttls = annotations.filter { it.name == "ttl" }
return when (ttls.size) {
0 -> null
1 -> {
if (ttls.elementAt(0).params.size > 1) {
throw IllegalArgumentException("Unexpected parameter for Ttl Capability annotation")
}
Capability.Ttl.fromString(ttls.elementAt(0).getStringParam("value"))
}
else -> throw IllegalArgumentException(
"Containing multiple ttl capabilities: $annotations"
)
}
}
}
}
/** Capability describing whether the store needs to be encrypted. */
data class Encryption(val value: Boolean) : Capability(TAG) {
fun compare(other: Encryption): Comparison {
return when {
value == other.value -> Comparison.Equivalent
value -> Comparison.Stricter
else -> Comparison.LessStrict
}
}
companion object {
const val TAG = "encryption"
val ANY = Range(Encryption(false), Encryption(true))
fun fromAnnotations(annotations: List<Annotation>): Encryption? {
val filtered = annotations.filter { it.name == "encrypted" }
return when (filtered.size) {
0 -> null
1 -> {
if (filtered.elementAt(0).params.size > 0) {
throw IllegalArgumentException("Unexpected parameter for Encryption annotation")
}
Capability.Encryption(true)
}
else -> throw IllegalArgumentException(
"Containing multiple encryption capabilities: $annotations"
)
}
}
}
}
/** Capability describing whether the store needs to be queryable. */
data class Queryable(val value: Boolean) : Capability(TAG) {
fun compare(other: Queryable): Comparison {
return when {
value == other.value -> Comparison.Equivalent
value -> Comparison.Stricter
else -> Comparison.LessStrict
}
}
companion object {
const val TAG = "queryable"
val ANY = Range(Queryable(false), Queryable(true))
fun fromAnnotations(annotations: List<Annotation>): Queryable? {
val filtered = annotations.filter { it.name == "queryable" }
return when (filtered.size) {
0 -> null
1 -> {
if (filtered.elementAt(0).params.size > 0) {
throw IllegalArgumentException("Unexpected parameter for Queryable annotation")
}
Capability.Queryable(true)
}
else -> throw IllegalArgumentException(
"Containing multiple queryable capabilities: $annotations"
)
}
}
}
}
/** Capability describing whether the store needs to be shareable across arcs. */
data class Shareable(val value: Boolean) : Capability(TAG) {
fun compare(other: Shareable): Comparison {
return when {
value == other.value -> Comparison.Equivalent
value -> Comparison.Stricter
else -> Comparison.LessStrict
}
}
companion object {
const val TAG = "shareable"
val ANY = Range(Shareable(false), Shareable(true))
fun fromAnnotations(annotations: List<Annotation>): Shareable? {
val filtered = annotations.filter {
arrayOf("shareable", "tiedToRuntime").contains(it.name)
}
return when (filtered.size) {
0 -> null
1 -> {
if (filtered.elementAt(0).params.size > 0) {
throw IllegalArgumentException("Unexpected parameter for Shareable annotation")
}
Capability.Shareable(true)
}
else -> throw IllegalArgumentException(
"Containing multiple shareable capabilities: $annotations"
)
}
}
}
}
data class Range(val min: Capability, val max: Capability) : Capability(TAG) {
init {
require(min.isSameOrLessStrict(max)) {
"Minimum capability in a range must be equivalent or less strict than maximum."
}
}
override fun isEquivalent(other: Capability): Boolean {
return when (other) {
is Range -> min.isEquivalent(other.min) && max.isEquivalent(other.max)
else -> min.isEquivalent(other) && max.isEquivalent(other)
}
}
override fun contains(other: Capability): Boolean {
return when (other) {
is Range ->
min.isSameOrLessStrict(other.min) && max.isSameOrStricter(other.max)
else -> min.isSameOrLessStrict(other) && max.isSameOrStricter(other)
}
}
override fun toRange() = this
companion object {
const val TAG = "range"
}
}
}
| bsd-3-clause | 89d7669818de21a421ba77250fdd367e | 32.659639 | 98 | 0.612081 | 4.47 | false | false | false | false |
Hexworks/zircon | zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/modifiers/DelayedTileStringExample.kt | 1 | 1562 | package org.hexworks.zircon.examples.modifiers
import org.hexworks.zircon.api.CP437TilesetResources
import org.hexworks.zircon.api.ColorThemes
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.SwingApplications
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.builder.screen.ScreenBuilder
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.ComponentDecorations.box
object DelayedTileStringExample {
private val SIZE = Size.create(50, 30)
private val TILESET = CP437TilesetResources.taffer20x20()
private val THEME = ColorThemes.cyberpunk()
@JvmStatic
fun main(args: Array<String>) {
val tileGrid = SwingApplications.startTileGrid(
AppConfig.newBuilder()
.withDefaultTileset(TILESET)
.withSize(SIZE)
.withDebugMode(true)
.build()
)
val screen = ScreenBuilder.createScreenFor(tileGrid)
val panel = Components.panel()
.withDecorations(box())
.withPreferredSize(Size.create(48, 20))
.build()
screen.addComponent(panel)
val myText = "This is a very long string I'd like to add with a typewriter effect"
panel.addComponent(
Components.textBox(panel.contentSize.width)
.addParagraph(
text = myText,
withTypingEffectSpeedInMs = 200
)
)
screen.theme = THEME
screen.display()
}
}
| apache-2.0 | 8c572c5dee3fed32364b0976fc67d2ba | 28.471698 | 90 | 0.651729 | 4.514451 | false | false | false | false |
baguslich997/MasteringKotlin | part2/src/Substract.kt | 3 | 290 | fun main(args: Array<String>) {
var firstNum = 100
var lastNum = 20
var result:Int?
result = firstNum - lastNum
println("Hai, $firstNum - $lastNum = $result")
println("Hello, ${11 - lastNum}")
// println("Hai2 " + firstNum + " + " + lastNum + " = "+ result)
} | apache-2.0 | 27e601591e6487d88ef6c822e4391761 | 21.384615 | 67 | 0.568966 | 3.258427 | false | false | false | false |
kevinmost/extensions-kotlin | core/src/test/java/com/kevinmost/koolbelt/util/WhenWithFallthroughTest.kt | 2 | 1159 | package com.kevinmost.koolbelt.util
import org.junit.Assert.assertTrue
import org.junit.Test
class WhenWithFallthroughTest {
@Test fun `test breakAfter works`() {
val casesHit = mutableSetOf<Int>()
whenWithFallthrough(4) {
case(2) { casesHit += 0 }
case(5) { casesHit += 1 }
case(predicate = { it < 6 }) {
casesHit += 2
}
case(predicate = { it % 2 == 1 }, breakAfter = true) {
casesHit += 3
}
default {
casesHit += 4
}
}
assertTrue(!casesHit.contains(0))
assertTrue(!casesHit.contains(1))
assertTrue(casesHit.contains(2))
assertTrue(casesHit.contains(3))
assertTrue(!casesHit.contains(4))
}
@Test fun `test default hit when nothing else is`() {
val casesHit = mutableSetOf<Int>()
whenWithFallthrough(1) {
case(2) { casesHit += 0 }
case(5) { casesHit += 1 }
case(predicate = { it > 6 }) {
casesHit += 2
}
default { casesHit += 3 }
}
assertTrue(!casesHit.contains(0))
assertTrue(!casesHit.contains(1))
assertTrue(!casesHit.contains(2))
assertTrue(casesHit.contains(3))
}
}
| apache-2.0 | 6b53f0cc89aeb0d98a664fcef15b74f1 | 22.653061 | 60 | 0.590164 | 3.610592 | false | true | false | false |
akakim/akakim.github.io | Android/KotlinRepository/QSalesPrototypeKotilnVersion/main/java/tripath/com/samplekapp/data/AdvisorItem.kt | 1 | 2010 | package tripath.com.samplekapp.data
import android.os.Parcel
import android.os.Parcelable
import com.fasterxml.jackson.annotation.JsonProperty
import com.google.gson.annotations.SerializedName
/**
* Created by SSLAB on 2017-08-11.
*/
class AdvisorItem : Parcelable{
@JsonProperty ("roomSeq") lateinit var roomSeq : String
@JsonProperty("advisorSeq") lateinit var advisorSeq : String
@JsonProperty ("authCode") lateinit var authCode : String
@JsonProperty ("roomStatus") lateinit var roomStatus : String
constructor() : this("","","","")
constructor(parcel: Parcel) {
roomSeq = parcel.readString()
advisorSeq = parcel.readString()
authCode = parcel.readString()
roomStatus = parcel.readString()
}
constructor(roomSeq :String,advisorSeq :String,authCode :String,roomStatus : String ){
this.roomSeq = roomSeq
this.advisorSeq = advisorSeq
this.authCode = authCode
this.roomStatus = roomStatus
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(roomSeq)
parcel.writeString(advisorSeq)
parcel.writeString(authCode)
parcel.writeString(roomStatus)
}
override fun describeContents(): Int {
return 0
}
override fun toString(): String {
val stringBuilder : StringBuilder = StringBuilder()
val arrayFields = javaClass.declaredFields
for( field in arrayFields){
stringBuilder.append( field.name + "[")
stringBuilder.append( field.toGenericString())
stringBuilder.append( field.name + "]")
}
return stringBuilder.toString()
}
companion object CREATOR : Parcelable.Creator<AdvisorItem> {
override fun createFromParcel(parcel: Parcel): AdvisorItem {
return AdvisorItem(parcel)
}
override fun newArray(size: Int): Array<AdvisorItem?> {
return arrayOfNulls(size)
}
}
} | gpl-3.0 | 0d88553eec4c1014fb51ce5dce1adca9 | 25.460526 | 90 | 0.654229 | 4.599542 | false | true | false | false |
android/nowinandroid | core/data/src/test/java/com/google/samples/apps/nowinandroid/core/data/model/NetworkEntityKtTest.kt | 1 | 4070 | /*
* 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.data.model
import com.google.samples.apps.nowinandroid.core.model.data.NewsResourceType.Article
import com.google.samples.apps.nowinandroid.core.network.model.NetworkAuthor
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResource
import com.google.samples.apps.nowinandroid.core.network.model.NetworkNewsResourceExpanded
import com.google.samples.apps.nowinandroid.core.network.model.NetworkTopic
import kotlin.test.assertEquals
import kotlinx.datetime.Instant
import org.junit.Test
class NetworkEntityKtTest {
@Test
fun network_author_can_be_mapped_to_author_entity() {
val networkModel = NetworkAuthor(
id = "0",
name = "Test",
imageUrl = "something",
twitter = "twitter",
mediumPage = "mediumPage",
bio = "bio",
)
val entity = networkModel.asEntity()
assertEquals("0", entity.id)
assertEquals("Test", entity.name)
assertEquals("something", entity.imageUrl)
}
@Test
fun network_topic_can_be_mapped_to_topic_entity() {
val networkModel = NetworkTopic(
id = "0",
name = "Test",
shortDescription = "short description",
longDescription = "long description",
url = "URL",
imageUrl = "image URL",
)
val entity = networkModel.asEntity()
assertEquals("0", entity.id)
assertEquals("Test", entity.name)
assertEquals("short description", entity.shortDescription)
assertEquals("long description", entity.longDescription)
assertEquals("URL", entity.url)
assertEquals("image URL", entity.imageUrl)
}
@Test
fun network_news_resource_can_be_mapped_to_news_resource_entity() {
val networkModel =
NetworkNewsResource(
id = "0",
title = "title",
content = "content",
url = "url",
headerImageUrl = "headerImageUrl",
publishDate = Instant.fromEpochMilliseconds(1),
type = Article,
)
val entity = networkModel.asEntity()
assertEquals("0", entity.id)
assertEquals("title", entity.title)
assertEquals("content", entity.content)
assertEquals("url", entity.url)
assertEquals("headerImageUrl", entity.headerImageUrl)
assertEquals(Instant.fromEpochMilliseconds(1), entity.publishDate)
assertEquals(Article, entity.type)
val expandedNetworkModel =
NetworkNewsResourceExpanded(
id = "0",
title = "title",
content = "content",
url = "url",
headerImageUrl = "headerImageUrl",
publishDate = Instant.fromEpochMilliseconds(1),
type = Article,
)
val entityFromExpanded = expandedNetworkModel.asEntity()
assertEquals("0", entityFromExpanded.id)
assertEquals("title", entityFromExpanded.title)
assertEquals("content", entityFromExpanded.content)
assertEquals("url", entityFromExpanded.url)
assertEquals("headerImageUrl", entityFromExpanded.headerImageUrl)
assertEquals(Instant.fromEpochMilliseconds(1), entityFromExpanded.publishDate)
assertEquals(Article, entityFromExpanded.type)
}
}
| apache-2.0 | 9069b89c18e9c4d18f88991bfa3881c9 | 36 | 90 | 0.643735 | 4.721578 | false | true | false | false |
hermantai/samples | kotlin/udacity-kotlin-bootcamp/HelloKotlin/src/playclasses.kt | 1 | 1169 | class SimpleSpice() {
val name = "curry"
val spiciness = "mild"
val heat: Int
get() {
return 5
}
}
fun mainForClasses() {
val simpleSpice = SimpleSpice()
println("${simpleSpice.name} ${simpleSpice.heat}")
}
class Spice(var name: String, var spiciness: String = "mild") {
val heat: Int
get() {
return when (spiciness) {
"mild" -> 1
"medium" -> 3
"spicy" -> 5
"very spicy" -> 7
"extremely spicy" -> 10
else -> 0
}
}
init {
println("Spice: name=$name, spiciness=$spiciness, heat=$heat")
}
}
// It's better to use helper methods than second constructors
fun makeSalt() = Spice("Salt")
fun mainForConstructors() {
val spices1 = listOf(
Spice("curry", "mild"),
Spice("pepper", "medium"),
Spice("cayenne", "spicy"),
Spice("ginger", "mild"),
Spice("red curry", "medium"),
Spice("green curry", "mild"),
Spice("hot pepper", "extremely spicy")
)
val spice = Spice("cayenne", spiciness = "spicy")
val spicelist = spices1.filter {it.heat < 5}
}
fun main(args: Array<String>) {
mainForClasses()
mainForConstructors()
} | apache-2.0 | be9851e202b9446995db89ba92f12bb6 | 19.892857 | 66 | 0.578272 | 3.125668 | false | false | false | false |
mobilesolutionworks/works-controller-android | test-app/src/androidTest/kotlin/com/mobilesolutionworks/android/controller/test/util/HostAndController.kt | 1 | 1331 | package com.mobilesolutionworks.android.controller.test.util
import com.mobilesolutionworks.android.app.controller.WorksController
import com.mobilesolutionworks.android.controller.test.GetController
import org.junit.Assert.*
/**
* Created by yunarta on 12/3/17.
*/
class HostAndController<C : WorksController> @JvmOverloads constructor(private val mChangeHost: Boolean = true) {
var controller: C? = null
private set
private var mHostHash: Int = 0
private var mControllerHash: Int = 0
fun set(host: GetController<C>) {
assertNotNull(host)
controller = host.controller
assertNotNull(controller)
mHostHash = System.identityHashCode(host)
mControllerHash = System.identityHashCode(controller)
}
fun validate(host: GetController<C>) {
assertNotNull(host)
assertNotNull(host.controller)
if (mChangeHost) {
assertNotEquals("Host changed after rotation", mHostHash.toLong(), System.identityHashCode(host).toLong())
} else {
assertEquals("Host didn't changed after rotation", mHostHash.toLong(), System.identityHashCode(host).toLong())
}
assertEquals("Controller is not retain during rotation", mControllerHash.toLong(), System.identityHashCode(host.controller).toLong())
}
}
| apache-2.0 | a55f4b597fa63359fe7667b1e8522d16 | 30.690476 | 141 | 0.705485 | 4.68662 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/breakpoints/InspectBreakpointApplicabilityAction.kt | 4 | 2865 | // 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.debugger.core.breakpoints
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.TextAnnotationGutterProvider
import com.intellij.openapi.editor.colors.ColorKey
import com.intellij.openapi.editor.colors.EditorFontType
import org.jetbrains.kotlin.idea.base.psi.getLineCount
import org.jetbrains.kotlin.idea.debugger.core.breakpoints.BreakpointChecker.BreakpointType
import org.jetbrains.kotlin.idea.util.application.isApplicationInternalMode
import org.jetbrains.kotlin.psi.KtFile
import java.awt.Color
import java.util.*
class InspectBreakpointApplicabilityAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val data = e.getData() ?: return
if (data.editor.gutter.isAnnotationsShown) {
data.editor.gutter.closeAllAnnotations()
}
val checker = BreakpointChecker()
val lineCount = data.file.getLineCount()
val breakpoints = (0..lineCount).map { line -> checker.check(data.file, line) }
val gutterProvider = BreakpointsGutterProvider(breakpoints)
data.editor.gutter.registerTextAnnotation(gutterProvider)
}
private class BreakpointsGutterProvider(private val breakpoints: List<EnumSet<BreakpointType>>) : TextAnnotationGutterProvider {
override fun getLineText(line: Int, editor: Editor?): String? {
val breakpoints = breakpoints.getOrNull(line) ?: return null
return breakpoints.map { it.prefix }.distinct().joinToString()
}
override fun getToolTip(line: Int, editor: Editor?): String? = null
override fun getStyle(line: Int, editor: Editor?) = EditorFontType.PLAIN
override fun getPopupActions(line: Int, editor: Editor?) = emptyList<AnAction>()
override fun getColor(line: Int, editor: Editor?): ColorKey? = null
override fun getBgColor(line: Int, editor: Editor?): Color? = null
override fun gutterClosed() {}
}
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
e.presentation.isVisible = isApplicationInternalMode()
e.presentation.isEnabled = e.getData() != null
}
class ActionData(val editor: Editor, val file: KtFile)
private fun AnActionEvent.getData(): ActionData? {
val editor = getData(CommonDataKeys.EDITOR) ?: return null
val file = getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return null
return ActionData(editor, file)
}
}
| apache-2.0 | 5cd0663f415cd41166a18dc3b64d34c0 | 43.076923 | 132 | 0.736475 | 4.554849 | false | false | false | false |
GunoH/intellij-community | platform/platform-api/src/com/intellij/openapi/ui/UiUtils.kt | 4 | 5240 | // 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.
@file:JvmName("UiUtils")
package com.intellij.openapi.ui
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.NaturalComparator
import com.intellij.ui.CollectionComboBoxModel
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.fields.ExtendableTextComponent
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.util.ui.ComponentWithEmptyText
import org.jetbrains.annotations.NonNls
import java.awt.Component
import java.awt.MouseInfo
import java.awt.Rectangle
import java.awt.event.*
import java.io.File
import javax.swing.*
import javax.swing.text.JTextComponent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.tree.TreeModel
import javax.swing.tree.TreePath
val PREFERRED_FOCUSED_COMPONENT = Key.create<JComponent>("JComponent.preferredFocusedComponent")
fun JComponent.getPreferredFocusedComponent(): JComponent? {
if (this is DialogPanel) {
return preferredFocusedComponent
}
return getUserData(PREFERRED_FOCUSED_COMPONENT)
}
fun JComponent.addPreferredFocusedComponent(component: JComponent) {
putUserData(PREFERRED_FOCUSED_COMPONENT, component)
}
fun <T> JComponent.putUserData(key: Key<T>, data: T?) {
putClientProperty(key, data)
}
inline fun <reified T> JComponent.getUserData(key: Key<T>): T? {
return getClientProperty(key) as? T
}
fun JTextComponent.isTextUnderMouse(e: MouseEvent): Boolean {
val position = viewToModel2D(e.point)
return position in 1 until text.length
}
fun Component.isComponentUnderMouse(): Boolean {
val pointerInfo = MouseInfo.getPointerInfo() ?: return false
val location = pointerInfo.location
SwingUtilities.convertPointFromScreen(location, this)
val bounds = Rectangle(0, 0, width, height)
return bounds.contains(location)
}
fun getActionShortcutText(actionId: String): String {
val keymapManager = KeymapManager.getInstance()
val activeKeymap = keymapManager.activeKeymap
val shortcuts = activeKeymap.getShortcuts(actionId)
return KeymapUtil.getShortcutsText(shortcuts)
}
fun getKeyStrokes(vararg actionIds: String): List<KeyStroke> {
val keymapManager = KeymapManager.getInstance()
val activeKeymap = keymapManager.activeKeymap
return actionIds.asSequence()
.flatMap { activeKeymap.getShortcuts(it).asSequence() }
.filterIsInstance<KeyboardShortcut>()
.flatMap { sequenceOf(it.firstKeyStroke, it.secondKeyStroke) }
.filterNotNull()
.toList()
}
fun JComponent.removeKeyboardAction(vararg keyStrokes: KeyStroke) {
removeKeyboardAction(keyStrokes.toList())
}
fun JComponent.removeKeyboardAction(keyStrokes: List<KeyStroke>) {
var map: InputMap? = inputMap
while (map != null) {
for (keyStroke in keyStrokes) {
map.remove(keyStroke)
}
map = map.parent
}
}
fun JComponent.addKeyboardAction(vararg keyStrokes: KeyStroke, action: (ActionEvent) -> Unit) {
addKeyboardAction(keyStrokes.toList(), action)
}
fun JComponent.addKeyboardAction(keyStrokes: List<KeyStroke>, action: (ActionEvent) -> Unit) {
for (keyStroke in keyStrokes) {
registerKeyboardAction(action, keyStroke, JComponent.WHEN_FOCUSED)
}
}
fun ExtendableTextField.addExtension(
icon: Icon,
hoverIcon: Icon = icon,
tooltip: @NlsContexts.Tooltip String? = null,
action: () -> Unit
) {
addExtension(ExtendableTextComponent.Extension.create(icon, hoverIcon, tooltip, action))
}
fun <T> ListModel<T>.asSequence() = sequence<T> {
for (i in 0 until size) {
yield(getElementAt(i))
}
}
fun TreeModel.asSequence(): Sequence<DefaultMutableTreeNode> {
val root = root ?: return emptySequence()
return (root as DefaultMutableTreeNode)
.depthFirstEnumeration()
.asSequence()
.map { it as DefaultMutableTreeNode }
}
fun TreeModel.getTreePath(userObject: Any?): TreePath? =
asSequence()
.filter { it.userObject == userObject }
.firstOrNull()
?.let { TreePath(it.path) }
val TextFieldWithBrowseButton.emptyText
get() = (textField as JBTextField).emptyText
fun <C> C.setEmptyState(
text: @NlsContexts.StatusText String
): C where C : Component, C : ComponentWithEmptyText = apply {
getAccessibleContext().accessibleName = text
emptyText.text = text
}
val <E> ComboBox<E>.collectionModel: CollectionComboBoxModel<E>
get() = model as CollectionComboBoxModel
fun <T> Iterable<T>.naturalSorted() = sortedWith(Comparator.comparing({ it.toString() }, NaturalComparator.INSTANCE))
fun getPresentablePath(path: @NonNls String): @NlsSafe String {
return FileUtil.getLocationRelativeToUserHome(FileUtil.toSystemDependentName(path.trim()), false)
}
@JvmOverloads
fun getCanonicalPath(path: @NonNls String, removeLastSlash: Boolean = true): @NonNls String {
return FileUtil.toCanonicalPath(FileUtil.expandUserHome(path.trim()), File.separatorChar, removeLastSlash)
}
| apache-2.0 | 474d0d0462445fc1deb4198eb59b7f88 | 32.164557 | 140 | 0.775191 | 4.242915 | false | false | false | false |
NiciDieNase/chaosflix | common/src/main/java/de/nicidienase/chaosflix/common/mediadata/entities/recording/RecordingDto.kt | 1 | 1215 | package de.nicidienase.chaosflix.common.mediadata.entities.recording
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
@Keep
data class RecordingDto(
var size: Int = 0,
var length: Int = 0,
@SerializedName("mime_type")
var mimeType: String = "",
var language: String = "",
var filename: String = "",
var state: String = "",
var folder: String = "",
@SerializedName("high_quality")
var isHighQuality: Boolean = false,
var width: Int = 0,
var height: Int = 0,
@SerializedName("updated_at")
var updatedAt: String? = "",
@SerializedName("recording_url")
var recordingUrl: String = "",
var url: String = "",
@SerializedName("event_url")
var eventUrl: String = "",
@SerializedName("conference_url")
var conferenceUrl: String? = ""
) {
val recordingID: Long
get() {
val strings = url.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return (strings[strings.size - 1]).toLong()
}
fun getEventString(): String {
val split = eventUrl.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return (split[split.size - 1])
}
}
| mit | 5aeb3a4ba47ab2867e7f85dfe07e66e0 | 29.375 | 95 | 0.631276 | 4.090909 | false | false | false | false |
emanuelpalm/palm-compute | core/src/main/java/se/ltu/emapal/compute/io/ComputeServiceTcpListener.kt | 1 | 4823 | package se.ltu.emapal.compute.io
import rx.Observable
import rx.lang.kotlin.PublishSubject
import se.ltu.emapal.compute.util.time.Duration
import java.io.Closeable
import java.net.InetSocketAddress
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.ServerSocketChannel
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
/**
* Listens for incoming TCP connections and turns any received into [ComputeServiceTcp] objects.
*/
class ComputeServiceTcpListener : Closeable {
private val timeout: Duration
private val executorDelay: Duration
private val executorInterval: Duration
private val executor: ScheduledExecutorService
private val isOwningExecutor: Boolean
private val isClosed = AtomicBoolean(false)
private val selector: Selector
private val serverChannel: ServerSocketChannel
private val whenConnectSubject = PublishSubject<ComputeService>()
private val whenExceptionSubject = PublishSubject<Throwable>()
/**
* Creates new TCP [ComputeService], scheduling its work using [executor].
*
* @param hostAddress The local address at which incoming connections will be accepted.
* @param timeout Duration after which a stale connection times out.
* @param executor Executor service to use for handling incoming connections.
* @param executorDelay Delay after which socket polling is started.
* @param executorInterval Interval at which socket polling is scheduled.
*/
constructor(
hostAddress: InetSocketAddress,
timeout: Duration = Duration.ofSeconds(30),
executor: ScheduledExecutorService? = null,
executorDelay: Duration = Duration.ofMilliseconds(10),
executorInterval: Duration = Duration.ofMilliseconds(250)
) {
this.timeout = timeout
this.executorDelay = executorDelay
this.executorInterval = executorInterval
if (executor != null) {
this.executor = executor
isOwningExecutor = false
} else {
this.executor = Executors.newSingleThreadScheduledExecutor()
isOwningExecutor = true
}
selector = Selector.open()
serverChannel = ServerSocketChannel.open()
serverChannel.configureBlocking(false)
serverChannel.socket().bind(hostAddress)
serverChannel.register(selector, SelectionKey.OP_ACCEPT)
// Schedule accepting.
this.executor.scheduleAtFixedRate(
{
if (isClosed.get()) {
return@scheduleAtFixedRate
}
try {
poll()
} catch (e: Throwable) {
if (e !is InterruptedException) {
whenExceptionSubject.onNext(e)
}
close()
}
},
executorDelay.toMilliseconds(),
executorInterval.toMilliseconds(),
TimeUnit.MILLISECONDS)
}
private fun poll() {
if (selector.isOpen) {
selector.selectNow()
selector.selectedKeys().removeAll { key ->
if (key.isValid && key.isAcceptable) {
accept(key)
}
true
}
}
}
private fun accept(key: SelectionKey) {
if (key.channel() !== serverChannel) {
throw IllegalStateException("key.channel() !== serverChannel")
}
val socket = serverChannel.accept()
val service = ComputeServiceTcp(
socket = socket,
timeout = timeout,
executor = this.executor,
executorDelay = executorDelay,
executorInterval = executorInterval,
isClosing = { isClosed.get() }
)
whenConnectSubject.onNext(service)
}
/** Publishes generated exceptions. */
val whenException: Observable<Throwable>
get() = whenExceptionSubject
/** Publishes successful connection attempts. */
val whenConnect: Observable<ComputeService>
get() = whenConnectSubject
override fun close() {
if (isClosed.compareAndSet(false, true)) {
try {
whenConnectSubject.onCompleted()
whenExceptionSubject.onCompleted()
} finally {
if (isOwningExecutor) {
executor.awaitTermination(3, TimeUnit.SECONDS)
}
selector.close()
serverChannel.close()
}
}
}
} | mit | f7f9f58a05bba0640edb0b96f4b3d4c8 | 33.705036 | 96 | 0.609579 | 5.530963 | false | false | false | false |
Palleas/buddybuild-ultron | app/src/main/java/buddybuild/com/ultron/BuildsRecyclerViewAdapter.kt | 1 | 2343 | package buddybuild.com.ultron
import android.content.res.Resources
import android.support.v4.content.ContextCompat
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import buddybuild.com.ultron.model.Build
import butterknife.BindView
import butterknife.ButterKnife
class BuildsRecyclerViewAdapter(private val builds: List<Build>) : RecyclerView.Adapter<BuildsRecyclerViewAdapter.BuildHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BuildHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.build_item, parent, false)
return BuildHolder(view)
}
override fun onBindViewHolder(holder: BuildHolder, position: Int) {
holder.bind(builds[position])
}
override fun getItemCount(): Int {
return builds.size
}
inner class BuildHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(R.id.commit_message) lateinit var commitMessageView: TextView
@BindView(R.id.author) lateinit var authorView: TextView
init {
ButterKnife.bind(this, itemView)
}
fun bind(build: Build) {
commitMessageView!!.text = build.commit!!.message
authorView!!.text = build.commit!!.author
if (build.buildStatus.equals("cancelled", ignoreCase = true)) {
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.cancelled))
} else if (build.buildStatus.equals("failed", ignoreCase = true)) {
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.failed))
} else if (build.buildStatus.equals("queued", ignoreCase = true)) {
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.queued))
} else if (build.buildStatus.equals("running", ignoreCase = true)) {
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.running))
} else if (build.buildStatus.equals("success", ignoreCase = true)) {
itemView.setBackgroundColor(ContextCompat.getColor(itemView.context, R.color.success))
}
}
}
}
| mit | f2635620e68b7576c14392fc77dfe15b | 40.105263 | 130 | 0.693982 | 4.603143 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/download/model/DownloadQueue.kt | 2 | 3927 | package eu.kanade.tachiyomi.data.download.model
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.DownloadStore
import eu.kanade.tachiyomi.source.model.Page
import rx.Observable
import rx.subjects.PublishSubject
import java.util.concurrent.CopyOnWriteArrayList
class DownloadQueue(
private val store: DownloadStore,
private val queue: MutableList<Download> = CopyOnWriteArrayList()
) : List<Download> by queue {
private val statusSubject = PublishSubject.create<Download>()
private val updatedRelay = PublishRelay.create<Unit>()
fun addAll(downloads: List<Download>) {
downloads.forEach { download ->
download.setStatusSubject(statusSubject)
download.setStatusCallback(::setPagesFor)
download.status = Download.State.QUEUE
}
queue.addAll(downloads)
store.addAll(downloads)
updatedRelay.call(Unit)
}
fun remove(download: Download) {
val removed = queue.remove(download)
store.remove(download)
download.setStatusSubject(null)
download.setStatusCallback(null)
if (download.status == Download.State.DOWNLOADING || download.status == Download.State.QUEUE) {
download.status = Download.State.NOT_DOWNLOADED
}
if (removed) {
updatedRelay.call(Unit)
}
}
fun remove(chapter: Chapter) {
find { it.chapter.id == chapter.id }?.let { remove(it) }
}
fun remove(chapters: List<Chapter>) {
for (chapter in chapters) {
remove(chapter)
}
}
fun remove(manga: Manga) {
filter { it.manga.id == manga.id }.forEach { remove(it) }
}
fun clear() {
queue.forEach { download ->
download.setStatusSubject(null)
download.setStatusCallback(null)
if (download.status == Download.State.DOWNLOADING || download.status == Download.State.QUEUE) {
download.status = Download.State.NOT_DOWNLOADED
}
}
queue.clear()
store.clear()
updatedRelay.call(Unit)
}
fun getActiveDownloads(): Observable<Download> =
Observable.from(this).filter { download -> download.status == Download.State.DOWNLOADING }
fun getStatusObservable(): Observable<Download> = statusSubject.onBackpressureBuffer()
fun getUpdatedObservable(): Observable<List<Download>> = updatedRelay.onBackpressureBuffer()
.startWith(Unit)
.map { this }
private fun setPagesFor(download: Download) {
if (download.status == Download.State.DOWNLOADED || download.status == Download.State.ERROR) {
setPagesSubject(download.pages, null)
}
}
fun getProgressObservable(): Observable<Download> {
return statusSubject.onBackpressureBuffer()
.startWith(getActiveDownloads())
.flatMap { download ->
if (download.status == Download.State.DOWNLOADING) {
val pageStatusSubject = PublishSubject.create<Int>()
setPagesSubject(download.pages, pageStatusSubject)
return@flatMap pageStatusSubject
.onBackpressureBuffer()
.filter { it == Page.READY }
.map { download }
} else if (download.status == Download.State.DOWNLOADED || download.status == Download.State.ERROR) {
setPagesSubject(download.pages, null)
}
Observable.just(download)
}
.filter { it.status == Download.State.DOWNLOADING }
}
private fun setPagesSubject(pages: List<Page>?, subject: PublishSubject<Int>?) {
pages?.forEach { it.setStatusSubject(subject) }
}
}
| apache-2.0 | 5deccc64b287a53ba5ad7194857fc9ed | 35.027523 | 117 | 0.632035 | 4.702994 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMLLJIT.kt | 4 | 8721 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package llvm.templates
import llvm.*
import org.lwjgl.generator.*
val LLVMLLJIT = "LLVMLLJIT".nativeClass(
Module.LLVM,
prefixConstant = "LLVM",
prefixMethod = "LLVM",
binding = LLVM_BINDING_DELEGATE
) {
documentation = "Requires LLVM 11.0 or higher."
LLVMOrcLLJITBuilderRef(
"OrcCreateLLJITBuilder",
"""
Create an {@code LLVMOrcLLJITBuilder}.
The client owns the resulting {@code LLJITBuilder} and should dispose of it using #OrcDisposeLLJITBuilder() once they are done with it.
""",
void()
)
void(
"OrcDisposeLLJITBuilder",
"""
Dispose of an {@code LLVMOrcLLJITBuilderRef}.
This should only be called if ownership has not been passed to {@code LLVMOrcCreateLLJIT} (e.g. because some error prevented that function from being
called).
""",
LLVMOrcLLJITBuilderRef("Builder", "")
)
void(
"OrcLLJITBuilderSetJITTargetMachineBuilder",
"""
Set the {@code JITTargetMachineBuilder} to be used when constructing the {@code LLJIT} instance.
Calling this function is optional: if it is not called then the {@code LLJITBuilder} will use {@code JITTargeTMachineBuilder::detectHost} to construct
a {@code JITTargetMachineBuilder}.
This function takes ownership of the {@code JTMB} argument: clients should not dispose of the {@code JITTargetMachineBuilder} after calling this
function.
""",
LLVMOrcLLJITBuilderRef("Builder", ""),
LLVMOrcJITTargetMachineBuilderRef("JTMB", "")
)
void(
"OrcLLJITBuilderSetObjectLinkingLayerCreator",
"Set an {@code ObjectLinkingLayer} creator function for this {@code LLJIT} instance.",
LLVMOrcLLJITBuilderRef("Builder", ""),
LLVMOrcLLJITBuilderObjectLinkingLayerCreatorFunction("F", ""),
opaque_p("Ctx", ""),
since = "12"
)
LLVMErrorRef(
"OrcCreateLLJIT",
"""
Create an {@code LLJIT} instance from an {@code LLJITBuilder}.
This operation takes ownership of the {@code Builder} argument: clients should not dispose of the builder after calling this function (even if the
function returns an error). If a null {@code Builder} argument is provided then a default-constructed {@code LLJITBuilder} will be used.
On success the resulting {@code LLJIT} instance is uniquely owned by the client and automatically manages the memory of all JIT'd code and all modules
that are transferred to it (e.g. via #OrcLLJITAddLLVMIRModule()). Disposing of the {@code LLJIT} instance will free all memory managed by the JIT,
including JIT'd code and not-yet compiled modules.
""",
Check(1)..LLVMOrcLLJITRef.p("Result", ""),
LLVMOrcLLJITBuilderRef("Builder", "")
)
LLVMErrorRef(
"OrcDisposeLLJIT",
"Dispose of an LLJIT instance.",
LLVMOrcLLJITRef("J", "")
)
LLVMOrcExecutionSessionRef(
"OrcLLJITGetExecutionSession",
"""
Get a reference to the {@code ExecutionSession} for this {@code LLJIT} instance.
The {@code ExecutionSession} is owned by the {@code LLJIT} instance. The client is not responsible for managing its memory.
""",
LLVMOrcLLJITRef("J", "")
)
LLVMOrcJITDylibRef(
"OrcLLJITGetMainJITDylib",
"""
Return a reference to the Main {@code JITDylib}.
The {@code JITDylib} is owned by the {@code LLJIT} instance. The client is not responsible for managing its memory.
""",
LLVMOrcLLJITRef("J", "")
)
charUTF8.const.p(
"OrcLLJITGetTripleString",
"Return the target triple for this {@code LLJIT} instance. This string is owned by the {@code LLJIT} instance and should not be freed by the client.",
LLVMOrcLLJITRef("J", "")
)
char(
"OrcLLJITGetGlobalPrefix",
"Returns the global prefix character according to the {@code LLJIT}'s {@code DataLayout}.",
LLVMOrcLLJITRef("J", "")
)
LLVMOrcSymbolStringPoolEntryRef(
"OrcLLJITMangleAndIntern",
"""
Mangles the given string according to the {@code LLJIT} instance's {@code DataLayout}, then interns the result in the {@code SymbolStringPool} and
returns a reference to the pool entry.
Clients should call #OrcReleaseSymbolStringPoolEntry() to decrement the ref-count on the pool entry once they are finished with this value.
""",
LLVMOrcLLJITRef("J", ""),
charUTF8.const.p("UnmangledName", "")
)
LLVMErrorRef(
"OrcLLJITAddObjectFile",
"""
Add a buffer representing an object file to the given {@code JITDylib} in the given {@code LLJIT} instance. This operation transfers ownership of the
buffer to the {@code LLJIT} instance. The buffer should not be disposed of or referenced once this function returns.
Resources associated with the given object will be tracked by the given {@code JITDylib}'s default resource tracker.
""",
LLVMOrcLLJITRef("J", ""),
LLVMOrcJITDylibRef("JD", ""),
LLVMMemoryBufferRef("ObjBuffer", "")
)
LLVMErrorRef(
"OrcLLJITAddObjectFileWithRT",
"""
Add a buffer representing an object file to the given {@code ResourceTracker}'s {@code JITDylib} in the given {@code LLJIT} instance. This operation
transfers ownership of the buffer to the {@code LLJIT} instance. The buffer should not be disposed of or referenced once this function returns.
Resources associated with the given object will be tracked by {@code ResourceTracker} {@code RT}.
""",
LLVMOrcLLJITRef("J", ""),
LLVMOrcResourceTrackerRef("RT", ""),
LLVMMemoryBufferRef("ObjBuffer", ""),
since = "12"
)
LLVMErrorRef(
"OrcLLJITAddLLVMIRModule",
"""
Add an IR module to the given {@code JITDylib} in the given {@code LLJIT} instance. This operation transfers ownership of the {@code TSM} argument to
the {@code LLJIT} instance. The {@code TSM} argument should not be disposed of or referenced once this function returns.
Resources associated with the given {@code Module} will be tracked by the given {@code JITDylib}'s default resource tracker.
""",
LLVMOrcLLJITRef("J", ""),
LLVMOrcJITDylibRef("JD", ""),
LLVMOrcThreadSafeModuleRef("TSM", "")
)
LLVMErrorRef(
"OrcLLJITAddLLVMIRModuleWithRT",
"""
Add an IR module to the given {@code ResourceTracker}'s {@code JITDylib} in the given {@code LLJIT} instance. This operation transfers ownership of the
{@code TSM} argument to the {@code LLJIT} instance. The {@code TSM} argument should not be disposed of or referenced once this function returns.
Resources associated with the given {@code Module} will be tracked by {@code ResourceTracker} {@code RT}.
""",
LLVMOrcLLJITRef("J", ""),
LLVMOrcResourceTrackerRef("JD", ""),
LLVMOrcThreadSafeModuleRef("TSM", ""),
since = "12"
)
LLVMErrorRef(
"OrcLLJITLookup",
"""
Look up the given symbol in the main {@code JITDylib} of the given {@code LLJIT} instance.
This operation does not take ownership of the Name argument.
""",
LLVMOrcLLJITRef("J", ""),
Check(1)..LLVMOrcExecutorAddress.p("Result", ""),
charUTF8.const.p("Name", "")
)
LLVMOrcObjectLayerRef(
"OrcLLJITGetObjLinkingLayer",
"Returns a non-owning reference to the {@code LLJIT} instance's object linking layer.",
LLVMOrcLLJITRef("J", ""),
since = "12"
)
LLVMOrcObjectTransformLayerRef(
"OrcLLJITGetObjTransformLayer",
"Returns a non-owning reference to the {@code LLJIT} instance's object linking layer.",
LLVMOrcLLJITRef("J", ""),
since = "12"
)
LLVMOrcIRTransformLayerRef(
"OrcLLJITGetIRTransformLayer",
"Returns a non-owning reference to the {@code LLJIT} instance's IR transform layer.",
LLVMOrcLLJITRef("J", ""),
since = "12"
)
charUTF8.const.p(
"OrcLLJITGetDataLayoutStr",
"""
Get the {@code LLJIT} instance's default data layout string.
This string is owned by the {@code LLJIT} instance and does not need to be freed by the caller.
""",
LLVMOrcLLJITRef("J", ""),
since = "12"
)
} | bsd-3-clause | ab45e3f1e6c24d724a77607bc6163015 | 33.474308 | 159 | 0.639262 | 4.653682 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/configure/ConfigureFragment.kt | 1 | 10627 | package org.wikipedia.feed.configure
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.Constants
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.analytics.FeedConfigureFunnel
import org.wikipedia.auth.AccountUtil
import org.wikipedia.databinding.FragmentFeedConfigureBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.feed.FeedContentType
import org.wikipedia.settings.Prefs
import org.wikipedia.settings.SettingsActivity
import org.wikipedia.util.log.L
import org.wikipedia.views.DefaultViewHolder
import org.wikipedia.views.DrawableItemDecoration
import java.util.*
class ConfigureFragment : Fragment(), ConfigureItemView.Callback {
private var _binding: FragmentFeedConfigureBinding? = null
private val binding get() = _binding!!
private lateinit var itemTouchHelper: ItemTouchHelper
private lateinit var funnel: FeedConfigureFunnel
private val orderedContentTypes = mutableListOf<FeedContentType>()
private val disposables = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentFeedConfigureBinding.inflate(inflater, container, false)
setupRecyclerView()
funnel = FeedConfigureFunnel(WikipediaApp.getInstance(), WikipediaApp.getInstance().wikiSite,
requireActivity().intent.getIntExtra(Constants.INTENT_EXTRA_INVOKE_SOURCE, -1))
disposables.add(ServiceFactory.getRest(WikiSite("wikimedia.org")).feedAvailability
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doAfterTerminate { prepareContentTypeList() }
.subscribe({ result ->
// apply the new availability rules to our content types
FeedContentType.NEWS.langCodesSupported.clear()
if (isLimitedToDomains(result.news())) {
addDomainNamesAsLangCodes(FeedContentType.NEWS.langCodesSupported, result.news())
}
FeedContentType.ON_THIS_DAY.langCodesSupported.clear()
if (isLimitedToDomains(result.onThisDay())) {
addDomainNamesAsLangCodes(FeedContentType.ON_THIS_DAY.langCodesSupported, result.onThisDay())
}
FeedContentType.TRENDING_ARTICLES.langCodesSupported.clear()
if (isLimitedToDomains(result.mostRead())) {
addDomainNamesAsLangCodes(FeedContentType.TRENDING_ARTICLES.langCodesSupported, result.mostRead())
}
FeedContentType.FEATURED_ARTICLE.langCodesSupported.clear()
if (isLimitedToDomains(result.featuredArticle())) {
addDomainNamesAsLangCodes(FeedContentType.FEATURED_ARTICLE.langCodesSupported, result.featuredArticle())
}
FeedContentType.FEATURED_IMAGE.langCodesSupported.clear()
if (isLimitedToDomains(result.featuredPicture())) {
addDomainNamesAsLangCodes(FeedContentType.FEATURED_IMAGE.langCodesSupported, result.featuredPicture())
}
FeedContentType.saveState()
}) { caught -> L.e(caught) })
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun onPause() {
super.onPause()
FeedContentType.saveState()
}
override fun onDestroyView() {
disposables.clear()
if (orderedContentTypes.isNotEmpty()) {
funnel.done(orderedContentTypes)
}
super.onDestroyView()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_feed_configure, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_feed_configure_select_all -> {
FeedContentType.values().map { it.isEnabled = true }
touch()
binding.contentTypesRecycler.adapter?.notifyDataSetChanged()
true
}
R.id.menu_feed_configure_deselect_all -> {
FeedContentType.values().map { it.isEnabled = false }
touch()
binding.contentTypesRecycler.adapter?.notifyDataSetChanged()
true
}
R.id.menu_feed_configure_reset -> {
Prefs.resetFeedCustomizations()
FeedContentType.restoreState()
prepareContentTypeList()
touch()
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun prepareContentTypeList() {
orderedContentTypes.clear()
orderedContentTypes.addAll(FeedContentType.values())
orderedContentTypes.sortWith { a, b -> a.order.compareTo(b.order) }
// Remove items for which there are no available languages
val i = orderedContentTypes.iterator()
while (i.hasNext()) {
val feedContentType = i.next()
if (!feedContentType.showInConfig()) {
i.remove()
continue
}
if (!AccountUtil.isLoggedIn && feedContentType === FeedContentType.SUGGESTED_EDITS) {
i.remove()
continue
}
val supportedLanguages = feedContentType.langCodesSupported
if (supportedLanguages.isEmpty()) {
continue
}
val atLeastOneSupported = WikipediaApp.getInstance().language().appLanguageCodes.any { supportedLanguages.contains(it) }
if (!atLeastOneSupported) {
i.remove()
}
}
binding.contentTypesRecycler.adapter?.notifyDataSetChanged()
}
private fun setupRecyclerView() {
binding.contentTypesRecycler.setHasFixedSize(true)
val adapter = ConfigureItemAdapter()
binding.contentTypesRecycler.adapter = adapter
binding.contentTypesRecycler.layoutManager = LinearLayoutManager(activity)
binding.contentTypesRecycler.addItemDecoration(DrawableItemDecoration(requireContext(), R.attr.list_separator_drawable))
itemTouchHelper = ItemTouchHelper(RearrangeableItemTouchHelperCallback(adapter))
itemTouchHelper.attachToRecyclerView(binding.contentTypesRecycler)
}
override fun onCheckedChanged(contentType: FeedContentType, checked: Boolean) {
touch()
contentType.isEnabled = checked
}
override fun onLanguagesChanged(contentType: FeedContentType) {
touch()
}
private fun updateItemOrder() {
touch()
for (i in orderedContentTypes.indices) {
orderedContentTypes[i].order = i
}
}
private fun touch() {
requireActivity().setResult(SettingsActivity.ACTIVITY_RESULT_FEED_CONFIGURATION_CHANGED)
}
private inner class ConfigureItemHolder constructor(itemView: ConfigureItemView) : DefaultViewHolder<ConfigureItemView>(itemView) {
fun bindItem(contentType: FeedContentType) {
view.setContents(contentType)
}
}
private inner class ConfigureItemAdapter : RecyclerView.Adapter<ConfigureItemHolder>() {
override fun getItemCount(): Int {
return orderedContentTypes.size
}
override fun onCreateViewHolder(parent: ViewGroup, type: Int): ConfigureItemHolder {
return ConfigureItemHolder(ConfigureItemView(requireContext()))
}
override fun onBindViewHolder(holder: ConfigureItemHolder, pos: Int) {
holder.bindItem(orderedContentTypes[pos])
}
override fun onViewAttachedToWindow(holder: ConfigureItemHolder) {
super.onViewAttachedToWindow(holder)
holder.view.setDragHandleTouchListener { v, event ->
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> itemTouchHelper.startDrag(holder)
MotionEvent.ACTION_UP -> v.performClick()
}
false
}
holder.view.callback = this@ConfigureFragment
}
override fun onViewDetachedFromWindow(holder: ConfigureItemHolder) {
holder.view.callback = null
holder.view.setDragHandleTouchListener(null)
super.onViewDetachedFromWindow(holder)
}
fun onMoveItem(oldPosition: Int, newPosition: Int) {
Collections.swap(orderedContentTypes, oldPosition, newPosition)
updateItemOrder()
notifyItemMoved(oldPosition, newPosition)
}
}
private inner class RearrangeableItemTouchHelperCallback constructor(private val adapter: ConfigureItemAdapter) : ItemTouchHelper.Callback() {
override fun isLongPressDragEnabled(): Boolean {
return true
}
override fun isItemViewSwipeEnabled(): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {}
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int {
return makeMovementFlags(ItemTouchHelper.UP or ItemTouchHelper.DOWN, 0)
}
override fun onMove(recyclerView: RecyclerView, source: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
adapter.onMoveItem(source.absoluteAdapterPosition, target.absoluteAdapterPosition)
return true
}
}
companion object {
private fun isLimitedToDomains(domainNames: List<String>): Boolean {
return domainNames.isNotEmpty() && !domainNames[0].contains("*")
}
private fun addDomainNamesAsLangCodes(outList: MutableList<String>, domainNames: List<String>) {
outList.addAll(domainNames.map { WikiSite(it).languageCode() })
}
fun newInstance(): ConfigureFragment {
return ConfigureFragment()
}
}
}
| apache-2.0 | 5921bfcc17ff475ee8b828a62fdec127 | 39.561069 | 146 | 0.664722 | 5.383485 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/BasicCompletionSession.kt | 3 | 43197 | // 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.completion
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.completion.impl.BetterPrefixMatcher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElementDecorator
import com.intellij.codeInsight.lookup.LookupElementPresentation
import com.intellij.codeInsight.template.TemplateManager
import com.intellij.openapi.module.Module
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.*
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.ProcessingContext
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.base.facet.platform.platform
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.util.resolveToDescriptor
import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper
import org.jetbrains.kotlin.idea.completion.keywords.DefaultCompletionKeywordHandlerProvider
import org.jetbrains.kotlin.idea.completion.keywords.createLookups
import org.jetbrains.kotlin.idea.completion.smart.*
import org.jetbrains.kotlin.idea.core.ExpectedInfo
import org.jetbrains.kotlin.idea.core.KotlinIndicesHelper
import org.jetbrains.kotlin.idea.core.NotPropertiesService
import org.jetbrains.kotlin.idea.core.completion.DeclarationLookupObject
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.base.indices.KotlinPackageIndexUtils
import org.jetbrains.kotlin.idea.util.CallType
import org.jetbrains.kotlin.idea.util.CallTypeAndReceiver
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptorKindExclude
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindExclude
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.ExplicitImportsScope
import org.jetbrains.kotlin.resolve.scopes.utils.addImportingScope
import org.jetbrains.kotlin.util.kind
import org.jetbrains.kotlin.util.supertypesWithAny
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class BasicCompletionSession(
configuration: CompletionSessionConfiguration,
parameters: CompletionParameters,
resultSet: CompletionResultSet,
) : CompletionSession(configuration, parameters, resultSet) {
private interface CompletionKind {
val descriptorKindFilter: DescriptorKindFilter?
fun doComplete()
fun shouldDisableAutoPopup() = false
fun addWeighers(sorter: CompletionSorter) = sorter
}
private val completionKind by lazy { detectCompletionKind() }
override val descriptorKindFilter: DescriptorKindFilter? get() = completionKind.descriptorKindFilter
private val smartCompletion = expression?.let {
SmartCompletion(
expression = it,
resolutionFacade = resolutionFacade,
bindingContext = bindingContext,
moduleDescriptor = moduleDescriptor,
visibilityFilter = isVisibleFilter,
indicesHelper = indicesHelper(false),
prefixMatcher = prefixMatcher,
inheritorSearchScope = GlobalSearchScope.EMPTY_SCOPE,
toFromOriginalFileMapper = toFromOriginalFileMapper,
callTypeAndReceiver = callTypeAndReceiver,
isJvmModule = isJvmModule,
forBasicCompletion = true,
)
}
override val expectedInfos: Collection<ExpectedInfo> get() = smartCompletion?.expectedInfos ?: emptyList()
private fun detectCompletionKind(): CompletionKind {
if (nameExpression == null) {
return if ((position.parent as? KtNamedDeclaration)?.nameIdentifier == position) DECLARATION_NAME else KEYWORDS_ONLY
}
if (OPERATOR_NAME.isApplicable()) {
return OPERATOR_NAME
}
if (NamedArgumentCompletion.isOnlyNamedArgumentExpected(nameExpression, resolutionFacade)) {
return NAMED_ARGUMENTS_ONLY
}
if (nameExpression.getStrictParentOfType<KtSuperExpression>() != null) {
return SUPER_QUALIFIER
}
return ALL
}
fun shouldDisableAutoPopup(): Boolean = completionKind.shouldDisableAutoPopup()
override fun shouldCompleteTopLevelCallablesFromIndex() = super.shouldCompleteTopLevelCallablesFromIndex() && prefix.isNotEmpty()
override fun doComplete() {
assert(parameters.completionType == CompletionType.BASIC)
if (parameters.isAutoPopup) {
collector.addLookupElementPostProcessor { lookupElement ->
lookupElement.putUserData(LookupCancelService.AUTO_POPUP_AT, position.startOffset)
lookupElement
}
if (isInFunctionLiteralStart(position)) {
collector.addLookupElementPostProcessor { lookupElement ->
lookupElement.putUserData(KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING, Unit)
lookupElement
}
}
}
collector.addLookupElementPostProcessor { lookupElement ->
position.argList?.let { lookupElement.argList = it }
lookupElement
}
completionKind.doComplete()
}
private fun isInFunctionLiteralStart(position: PsiElement): Boolean {
var prev = position.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment }
if (prev?.node?.elementType == KtTokens.LPAR) {
prev = prev?.prevLeaf { it !is PsiWhiteSpace && it !is PsiComment }
}
if (prev?.node?.elementType != KtTokens.LBRACE) return false
val functionLiteral = prev!!.parent as? KtFunctionLiteral ?: return false
return functionLiteral.lBrace == prev
}
override fun createSorter(): CompletionSorter {
var sorter = super.createSorter()
if (smartCompletion != null) {
val smartCompletionInBasicWeigher = SmartCompletionInBasicWeigher(
smartCompletion,
callTypeAndReceiver,
resolutionFacade,
bindingContext,
)
sorter = sorter.weighBefore(
KindWeigher.toString(),
smartCompletionInBasicWeigher,
CallableReferenceWeigher(callTypeAndReceiver.callType),
)
}
sorter = completionKind.addWeighers(sorter)
return sorter
}
private val ALL = object : CompletionKind {
override val descriptorKindFilter: DescriptorKindFilter by lazy {
callTypeAndReceiver.callType.descriptorKindFilter.let { filter ->
filter.takeIf { it.kindMask.and(DescriptorKindFilter.PACKAGES_MASK) != 0 }
?.exclude(DescriptorKindExclude.TopLevelPackages)
?: filter
}
}
override fun shouldDisableAutoPopup(): Boolean =
isStartOfExtensionReceiverFor() is KtProperty && wasAutopopupRecentlyCancelled(parameters)
override fun doComplete() {
val declaration = isStartOfExtensionReceiverFor()
if (declaration != null) {
completeDeclarationNameFromUnresolvedOrOverride(declaration)
if (declaration is KtProperty) {
// we want to insert type only if the property is lateinit,
// because lateinit var cannot have its type deduced from initializer
completeParameterOrVarNameAndType(withType = declaration.hasModifier(KtTokens.LATEINIT_KEYWORD))
}
// no auto-popup on typing after "val", "var" and "fun" because it's likely the name of the declaration which is being typed by user
if (parameters.invocationCount == 0 && (
// suppressOtherCompletion
declaration !is KtNamedFunction && declaration !is KtProperty ||
prefixMatcher.prefix.let { it.isEmpty() || it[0].isLowerCase() /* function name usually starts with lower case letter */ }
)
) {
return
}
}
fun completeWithSmartCompletion(lookupElementFactory: LookupElementFactory) {
if (smartCompletion != null) {
val (additionalItems, @Suppress("UNUSED_VARIABLE") inheritanceSearcher) = smartCompletion.additionalItems(
lookupElementFactory
)
// all additional items should have SMART_COMPLETION_ITEM_PRIORITY_KEY to be recognized by SmartCompletionInBasicWeigher
for (item in additionalItems) {
if (item.getUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY) == null) {
item.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, SmartCompletionItemPriority.DEFAULT)
}
}
collector.addElements(additionalItems)
}
}
withCollectRequiredContextVariableTypes { lookupFactory ->
DslMembersCompletion(
prefixMatcher,
lookupFactory,
receiverTypes,
collector,
indicesHelper(true),
callTypeAndReceiver,
).completeDslFunctions()
}
KEYWORDS_ONLY.doComplete()
val contextVariableTypesForSmartCompletion = withCollectRequiredContextVariableTypes(::completeWithSmartCompletion)
val contextVariableTypesForReferenceVariants = withCollectRequiredContextVariableTypes { lookupElementFactory ->
when {
prefix.isEmpty() ||
callTypeAndReceiver.receiver != null ||
CodeInsightSettings.getInstance().completionCaseSensitive == CodeInsightSettings.NONE
-> {
addReferenceVariantElements(lookupElementFactory, descriptorKindFilter)
}
prefix[0].isLowerCase() -> {
addReferenceVariantElements(lookupElementFactory, USUALLY_START_LOWER_CASE.intersect(descriptorKindFilter))
addReferenceVariantElements(lookupElementFactory, USUALLY_START_UPPER_CASE.intersect(descriptorKindFilter))
}
else -> {
addReferenceVariantElements(lookupElementFactory, USUALLY_START_UPPER_CASE.intersect(descriptorKindFilter))
addReferenceVariantElements(lookupElementFactory, USUALLY_START_LOWER_CASE.intersect(descriptorKindFilter))
}
}
referenceVariantsCollector!!.collectingFinished()
}
// getting root packages from scope is very slow so we do this in alternative way
if (callTypeAndReceiver.receiver == null &&
callTypeAndReceiver.callType.descriptorKindFilter.kindMask.and(DescriptorKindFilter.PACKAGES_MASK) != 0
) {
//TODO: move this code somewhere else?
val packageNames = KotlinPackageIndexUtils.getSubPackageFqNames(FqName.ROOT, searchScope, prefixMatcher.asNameFilter())
.toHashSet()
if ((parameters.originalFile as KtFile).platform.isJvm()) {
JavaPsiFacade.getInstance(project).findPackage("")?.getSubPackages(searchScope)?.forEach { psiPackage ->
val name = psiPackage.name
if (Name.isValidIdentifier(name!!)) {
packageNames.add(FqName(name))
}
}
}
packageNames.forEach { collector.addElement(basicLookupElementFactory.createLookupElementForPackage(it)) }
}
flushToResultSet()
NamedArgumentCompletion.complete(collector, expectedInfos, callTypeAndReceiver.callType)
flushToResultSet()
val contextVariablesProvider = RealContextVariablesProvider(referenceVariantsHelper, position)
withContextVariablesProvider(contextVariablesProvider) { lookupElementFactory ->
if (receiverTypes != null) {
ExtensionFunctionTypeValueCompletion(receiverTypes, callTypeAndReceiver.callType, lookupElementFactory)
.processVariables(contextVariablesProvider)
.forEach {
val lookupElements = it.factory.createStandardLookupElementsForDescriptor(
it.invokeDescriptor,
useReceiverTypes = true,
)
collector.addElements(lookupElements)
}
}
if (contextVariableTypesForSmartCompletion.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() }) {
completeWithSmartCompletion(lookupElementFactory)
}
if (contextVariableTypesForReferenceVariants.any { contextVariablesProvider.functionTypeVariables(it).isNotEmpty() }) {
val (imported, notImported) = referenceVariantsWithSingleFunctionTypeParameter()!!
collector.addDescriptorElements(imported, lookupElementFactory)
collector.addDescriptorElements(notImported, lookupElementFactory, notImported = true)
}
val staticMembersCompletion = StaticMembersCompletion(
prefixMatcher,
resolutionFacade,
lookupElementFactory,
referenceVariantsCollector!!.allCollected.imported,
isJvmModule
)
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
staticMembersCompletion.completeFromImports(file, collector)
}
completeNonImported(lookupElementFactory)
flushToResultSet()
if (isDebuggerContext) {
val variantsAndFactory = getRuntimeReceiverTypeReferenceVariants(lookupElementFactory)
if (variantsAndFactory != null) {
val variants = variantsAndFactory.first
val resultLookupElementFactory = variantsAndFactory.second
collector.addDescriptorElements(variants.imported, resultLookupElementFactory, withReceiverCast = true)
collector.addDescriptorElements(
variants.notImportedExtensions,
resultLookupElementFactory,
withReceiverCast = true,
notImported = true
)
flushToResultSet()
}
}
if (!receiverTypes.isNullOrEmpty()) {
// N.B.: callable references to member extensions are forbidden
val shouldCompleteExtensionsFromObjects = when (callTypeAndReceiver.callType) {
CallType.DEFAULT, CallType.DOT, CallType.SAFE, CallType.INFIX -> true
else -> false
}
if (shouldCompleteExtensionsFromObjects) {
val receiverKotlinTypes = receiverTypes.map { it.type }
staticMembersCompletion.completeObjectMemberExtensionsFromIndices(
indicesHelper(mayIncludeInaccessible = false),
receiverKotlinTypes,
callTypeAndReceiver,
collector
)
staticMembersCompletion.completeExplicitAndInheritedMemberExtensionsFromIndices(
indicesHelper(mayIncludeInaccessible = false),
receiverKotlinTypes,
callTypeAndReceiver,
collector
)
}
}
if (configuration.staticMembers && prefix.isNotEmpty()) {
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
staticMembersCompletion.completeFromIndices(indicesHelper(false), collector)
}
}
}
}
private fun completeNonImported(lookupElementFactory: LookupElementFactory) {
if (shouldCompleteTopLevelCallablesFromIndex()) {
processTopLevelCallables {
collector.addDescriptorElements(it, lookupElementFactory, notImported = true)
flushToResultSet()
}
}
if (callTypeAndReceiver.receiver == null && prefix.isNotEmpty()) {
val classKindFilter: ((ClassKind) -> Boolean)? = when (callTypeAndReceiver) {
is CallTypeAndReceiver.ANNOTATION -> {
{ it == ClassKind.ANNOTATION_CLASS }
}
is CallTypeAndReceiver.DEFAULT, is CallTypeAndReceiver.TYPE -> {
{ it != ClassKind.ENUM_ENTRY }
}
else -> null
}
if (classKindFilter != null) {
val prefixMatcher = if (configuration.useBetterPrefixMatcherForNonImportedClasses)
BetterPrefixMatcher(prefixMatcher, collector.bestMatchingDegree)
else
prefixMatcher
addClassesFromIndex(
kindFilter = classKindFilter,
prefixMatcher = prefixMatcher,
completionParameters = parameters,
indicesHelper = indicesHelper(true),
classifierDescriptorCollector = {
collector.addElement(basicLookupElementFactory.createLookupElement(it), notImported = true)
},
javaClassCollector = {
collector.addElement(basicLookupElementFactory.createLookupElementForJavaClass(it), notImported = true)
}
)
}
} else if (callTypeAndReceiver is CallTypeAndReceiver.DOT) {
val qualifier = bindingContext[BindingContext.QUALIFIER, callTypeAndReceiver.receiver]
if (qualifier != null) return
val receiver = callTypeAndReceiver.receiver as? KtSimpleNameExpression ?: return
val descriptors = mutableListOf<ClassifierDescriptorWithTypeParameters>()
val fullTextPrefixMatcher = object : PrefixMatcher(receiver.getReferencedName()) {
override fun prefixMatches(name: String): Boolean = name == prefix
override fun cloneWithPrefix(prefix: String): PrefixMatcher = throw UnsupportedOperationException("Not implemented")
}
addClassesFromIndex(
kindFilter = { true },
prefixMatcher = fullTextPrefixMatcher,
completionParameters = parameters.withPosition(receiver, receiver.startOffset),
indicesHelper = indicesHelper(false),
classifierDescriptorCollector = { descriptors += it },
javaClassCollector = { descriptors.addIfNotNull(it.resolveToDescriptor(resolutionFacade)) },
)
val foundDescriptors = HashSet<DeclarationDescriptor>()
val classifiers = descriptors.asSequence().filter {
it.kind == ClassKind.OBJECT ||
it.kind == ClassKind.ENUM_CLASS ||
it.kind == ClassKind.ENUM_ENTRY ||
it.hasCompanionObject ||
it is JavaClassDescriptor
}
for (classifier in classifiers) {
val scope = nameExpression?.getResolutionScope(bindingContext) ?: return
val desc = classifier.getImportableDescriptor()
val newScope = scope.addImportingScope(ExplicitImportsScope(listOf(desc)))
val newContext = (nameExpression.parent as KtExpression).analyzeInContext(newScope)
val rvHelper = ReferenceVariantsHelper(
newContext,
resolutionFacade,
moduleDescriptor,
isVisibleFilter,
NotPropertiesService.getNotProperties(position)
)
val rvCollector = ReferenceVariantsCollector(
referenceVariantsHelper = rvHelper,
indicesHelper = indicesHelper(true),
prefixMatcher = prefixMatcher,
nameExpression = nameExpression,
callTypeAndReceiver = callTypeAndReceiver,
resolutionFacade = resolutionFacade,
bindingContext = newContext,
importableFqNameClassifier = importableFqNameClassifier,
configuration = configuration,
allowExpectedDeclarations = allowExpectedDeclarations,
)
val receiverTypes = detectReceiverTypes(newContext, nameExpression, callTypeAndReceiver)
val factory = lookupElementFactory.copy(
receiverTypes = receiverTypes,
standardLookupElementsPostProcessor = { lookupElement ->
val lookupDescriptor = lookupElement.`object`
.safeAs<DeclarationLookupObject>()
?.descriptor as? MemberDescriptor
?: return@copy lookupElement
if (!desc.isAncestorOf(lookupDescriptor, false)) return@copy lookupElement
if (lookupDescriptor is CallableMemberDescriptor &&
lookupDescriptor.isExtension &&
lookupDescriptor.extensionReceiverParameter?.importableFqName != desc.fqNameSafe
) {
return@copy lookupElement
}
val fqNameToImport = lookupDescriptor.containingDeclaration.importableFqName ?: return@copy lookupElement
object : LookupElementDecorator<LookupElement>(lookupElement) {
val name = fqNameToImport.shortName()
val packageName = fqNameToImport.parent()
override fun handleInsert(context: InsertionContext) {
super.handleInsert(context)
context.commitDocument()
val file = context.file as? KtFile
if (file != null) {
val receiverInFile = file.findElementAt(receiver.startOffset)
?.getParentOfType<KtSimpleNameExpression>(false)
?: return
receiverInFile.mainReference.bindToFqName(fqNameToImport, FORCED_SHORTENING)
}
}
override fun renderElement(presentation: LookupElementPresentation?) {
super.renderElement(presentation)
presentation?.appendTailText(
KotlinIdeaCompletionBundle.message(
"presentation.tail.for.0.in.1",
name,
packageName,
),
true,
)
}
}
},
)
rvCollector.collectReferenceVariants(descriptorKindFilter) { (imported, notImportedExtensions) ->
val unique = imported.asSequence()
.filterNot { it.original in foundDescriptors }
.onEach { foundDescriptors += it.original }
val uniqueNotImportedExtensions = notImportedExtensions.asSequence()
.filterNot { it.original in foundDescriptors }
.onEach { foundDescriptors += it.original }
collector.addDescriptorElements(
unique.toList(), factory,
prohibitDuplicates = true
)
collector.addDescriptorElements(
uniqueNotImportedExtensions.toList(), factory,
notImported = true, prohibitDuplicates = true
)
flushToResultSet()
}
}
}
}
private fun isStartOfExtensionReceiverFor(): KtCallableDeclaration? {
val userType = nameExpression!!.parent as? KtUserType ?: return null
if (userType.qualifier != null) return null
val typeRef = userType.parent as? KtTypeReference ?: return null
if (userType != typeRef.typeElement) return null
return when (val parent = typeRef.parent) {
is KtNamedFunction -> parent.takeIf { typeRef == it.receiverTypeReference }
is KtProperty -> parent.takeIf { typeRef == it.receiverTypeReference }
else -> null
}
}
}
private fun wasAutopopupRecentlyCancelled(parameters: CompletionParameters) =
LookupCancelService.getInstance(project).wasAutoPopupRecentlyCancelled(parameters.editor, position.startOffset)
private val KEYWORDS_ONLY = object : CompletionKind {
override val descriptorKindFilter: DescriptorKindFilter? get() = null
private val keywordCompletion = KeywordCompletion(object : KeywordCompletion.LanguageVersionSettingProvider {
override fun getLanguageVersionSetting(element: PsiElement) = element.languageVersionSettings
override fun getLanguageVersionSetting(module: Module) = module.languageVersionSettings
})
override fun doComplete() {
val keywordsToSkip = HashSet<String>()
val keywordValueConsumer = object : KeywordValues.Consumer {
override fun consume(
lookupString: String,
expectedInfoMatcher: (ExpectedInfo) -> ExpectedInfoMatch,
suitableOnPsiLevel: PsiElement.() -> Boolean,
priority: SmartCompletionItemPriority,
factory: () -> LookupElement
) {
keywordsToSkip.add(lookupString)
val lookupElement = factory()
val matched = expectedInfos.any {
val match = expectedInfoMatcher(it)
assert(!match.makeNotNullable) { "Nullable keyword values not supported" }
match.isMatch()
}
// 'expectedInfos' is filled with the compiler's insight.
// In cases like missing import statement or undeclared variable desired data cannot be retrieved. Here is where we can
// analyse PSI and calling 'suitableOnPsiLevel()' does the trick.
if (matched || (expectedInfos.isEmpty() && position.suitableOnPsiLevel())) {
lookupElement.putUserData(SmartCompletionInBasicWeigher.KEYWORD_VALUE_MATCHED_KEY, Unit)
lookupElement.putUserData(SMART_COMPLETION_ITEM_PRIORITY_KEY, priority)
}
collector.addElement(lookupElement)
}
}
KeywordValues.process(
keywordValueConsumer,
callTypeAndReceiver,
bindingContext,
resolutionFacade,
moduleDescriptor,
isJvmModule
)
keywordCompletion.complete(expression ?: position, resultSet.prefixMatcher, isJvmModule) { lookupElement ->
val keyword = lookupElement.lookupString
if (keyword in keywordsToSkip) return@complete
val completionKeywordHandler = DefaultCompletionKeywordHandlerProvider.getHandlerForKeyword(keyword)
if (completionKeywordHandler != null) {
val lookups = completionKeywordHandler.createLookups(parameters, expression, lookupElement, project)
collector.addElements(lookups)
return@complete
}
when (keyword) {
// if "this" is parsed correctly in the current context - insert it and all this@xxx items
"this" -> {
if (expression != null) {
collector.addElements(
thisExpressionItems(
bindingContext,
expression,
prefix,
resolutionFacade
).map { it.createLookupElement() })
} else {
// for completion in secondary constructor delegation call
collector.addElement(lookupElement)
}
}
// if "return" is parsed correctly in the current context - insert it and all return@xxx items
"return" -> {
if (expression != null) {
collector.addElements(returnExpressionItems(bindingContext, expression))
}
}
"override" -> {
collector.addElement(lookupElement)
OverridesCompletion(collector, basicLookupElementFactory).complete(position, declaration = null)
}
"class" -> {
if (callTypeAndReceiver !is CallTypeAndReceiver.CALLABLE_REFERENCE) { // otherwise it should be handled by KeywordValues
collector.addElement(lookupElement)
}
}
"suspend", "out", "in" -> {
if (position.isInsideKtTypeReference) {
// aforementioned keyword modifiers are rarely needed in the type references and
// most of the time can be quickly prefix-selected by typing the corresponding letter.
// We mark them as low-priority, so they do not shadow actual types
lookupElement.keywordProbability = KeywordProbability.LOW
}
collector.addElement(lookupElement)
}
else -> collector.addElement(lookupElement)
}
}
}
}
private val NAMED_ARGUMENTS_ONLY = object : CompletionKind {
override val descriptorKindFilter: DescriptorKindFilter? get() = null
override fun doComplete(): Unit = NamedArgumentCompletion.complete(collector, expectedInfos, callTypeAndReceiver.callType)
}
private val OPERATOR_NAME = object : CompletionKind {
override val descriptorKindFilter: DescriptorKindFilter? get() = null
fun isApplicable(): Boolean {
if (nameExpression == null || nameExpression != expression) return false
val func = position.getParentOfType<KtNamedFunction>(strict = false) ?: return false
val funcNameIdentifier = func.nameIdentifier ?: return false
val identifierInNameExpression = nameExpression.nextLeaf {
it is LeafPsiElement && it.elementType == KtTokens.IDENTIFIER
} ?: return false
if (!func.hasModifier(KtTokens.OPERATOR_KEYWORD) || identifierInNameExpression != funcNameIdentifier) return false
val originalFunc = toFromOriginalFileMapper.toOriginalFile(func) ?: return false
return !originalFunc.isTopLevel || (originalFunc.isExtensionDeclaration())
}
override fun doComplete() {
OperatorNameCompletion.doComplete(collector, descriptorNameFilter)
flushToResultSet()
}
}
private val DECLARATION_NAME = object : CompletionKind {
override val descriptorKindFilter: DescriptorKindFilter? get() = null
override fun doComplete() {
val declaration = declaration()
if (declaration is KtParameter && !shouldCompleteParameterNameAndType()) return // do not complete also keywords and from unresolved references in such case
collector.addLookupElementPostProcessor { lookupElement ->
lookupElement.putUserData(KotlinCompletionCharFilter.SUPPRESS_ITEM_SELECTION_BY_CHARS_ON_TYPING, Unit)
lookupElement
}
KEYWORDS_ONLY.doComplete()
completeDeclarationNameFromUnresolvedOrOverride(declaration)
when (declaration) {
is KtParameter -> completeParameterOrVarNameAndType(withType = true)
is KtClassOrObject -> {
if (declaration.isTopLevel()) {
completeTopLevelClassName()
}
}
}
}
override fun shouldDisableAutoPopup(): Boolean = when {
TemplateManager.getInstance(project).getActiveTemplate(parameters.editor) != null -> true
declaration() is KtParameter && wasAutopopupRecentlyCancelled(parameters) -> true
else -> false
}
//workaround to avoid false-positive: KTIJ-19892
override fun addWeighers(sorter: CompletionSorter): CompletionSorter = if (shouldCompleteParameterNameAndType())
sorter.weighBefore("prefix", VariableOrParameterNameWithTypeCompletion.Weigher)
else
sorter
private fun completeTopLevelClassName() {
val name = parameters.originalFile.virtualFile.nameWithoutExtension
if (!(Name.isValidIdentifier(name) && Name.identifier(name).render() == name && name[0].isUpperCase())) return
if ((parameters.originalFile as KtFile).declarations.any { it is KtClassOrObject && it.name == name }) return
collector.addElement(LookupElementBuilder.create(name))
}
private fun declaration() = position.parent as KtNamedDeclaration
private fun shouldCompleteParameterNameAndType(): Boolean {
val parameter = declaration() as? KtParameter ?: return false
val list = parameter.parent as? KtParameterList ?: return false
return when (val owner = list.parent) {
is KtCatchClause, is KtPropertyAccessor, is KtFunctionLiteral -> false
is KtNamedFunction -> owner.nameIdentifier != null
is KtPrimaryConstructor -> !owner.getContainingClassOrObject().isAnnotation()
else -> true
}
}
}
private val SUPER_QUALIFIER = object : CompletionKind {
override val descriptorKindFilter: DescriptorKindFilter
get() = DescriptorKindFilter.NON_SINGLETON_CLASSIFIERS
override fun doComplete() {
val classOrObject = position.parents.firstIsInstanceOrNull<KtClassOrObject>() ?: return
val classDescriptor = resolutionFacade.resolveToDescriptor(classOrObject, BodyResolveMode.PARTIAL) as ClassDescriptor
var superClasses = classDescriptor.defaultType.constructor.supertypesWithAny()
.mapNotNull { it.constructor.declarationDescriptor as? ClassDescriptor }
if (callTypeAndReceiver.receiver != null) {
val referenceVariantsSet = referenceVariantsCollector!!.collectReferenceVariants(descriptorKindFilter).imported.toSet()
superClasses = superClasses.filter { it in referenceVariantsSet }
}
superClasses
.map { basicLookupElementFactory.createLookupElement(it, qualifyNestedClasses = true, includeClassTypeArguments = false) }
.forEach { collector.addElement(it) }
}
}
private fun completeDeclarationNameFromUnresolvedOrOverride(declaration: KtNamedDeclaration) {
if (declaration is KtCallableDeclaration && declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
OverridesCompletion(collector, basicLookupElementFactory).complete(position, declaration)
} else {
val referenceScope = referenceScope(declaration) ?: return
val originalScope = toFromOriginalFileMapper.toOriginalFile(referenceScope) ?: return
val afterOffset = if (referenceScope is KtBlockExpression) parameters.offset else null
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration]
FromUnresolvedNamesCompletion(collector, prefixMatcher).addNameSuggestions(originalScope, afterOffset, descriptor)
}
}
private fun addClassesFromIndex(
kindFilter: (ClassKind) -> Boolean,
prefixMatcher: PrefixMatcher,
completionParameters: CompletionParameters,
indicesHelper: KotlinIndicesHelper,
classifierDescriptorCollector: (ClassifierDescriptorWithTypeParameters) -> Unit,
javaClassCollector: (PsiClass) -> Unit,
) {
AllClassesCompletion(
parameters = completionParameters,
kotlinIndicesHelper = indicesHelper,
prefixMatcher = prefixMatcher,
resolutionFacade = resolutionFacade,
kindFilter = kindFilter,
includeTypeAliases = true,
includeJavaClassesNotToBeUsed = configuration.javaClassesNotToBeUsed,
).collect({ processWithShadowedFilter(it, classifierDescriptorCollector) }, javaClassCollector)
}
private fun addReferenceVariantElements(lookupElementFactory: LookupElementFactory, descriptorKindFilter: DescriptorKindFilter) {
fun addReferenceVariants(referenceVariants: ReferenceVariants) {
collector.addDescriptorElements(
referenceVariantsHelper.excludeNonInitializedVariable(referenceVariants.imported, position),
lookupElementFactory, prohibitDuplicates = true
)
collector.addDescriptorElements(
referenceVariants.notImportedExtensions, lookupElementFactory,
notImported = true, prohibitDuplicates = true
)
}
val referenceVariantsCollector = referenceVariantsCollector!!
referenceVariantsCollector.collectReferenceVariants(descriptorKindFilter) { referenceVariants ->
addReferenceVariants(referenceVariants)
flushToResultSet()
}
}
private fun completeParameterOrVarNameAndType(withType: Boolean) {
val nameWithTypeCompletion = VariableOrParameterNameWithTypeCompletion(
collector,
basicLookupElementFactory,
prefixMatcher,
resolutionFacade,
withType,
)
// if we are typing parameter name, restart completion each time we type an upper case letter
// because new suggestions will appear (previous words can be used as user prefix)
val prefixPattern = StandardPatterns.string().with(object : PatternCondition<String>("Prefix ends with uppercase letter") {
override fun accepts(prefix: String, context: ProcessingContext?) = prefix.isNotEmpty() && prefix.last().isUpperCase()
})
collector.restartCompletionOnPrefixChange(prefixPattern)
nameWithTypeCompletion.addFromParametersInFile(position, resolutionFacade, isVisibleFilterCheckAlways)
flushToResultSet()
nameWithTypeCompletion.addFromImportedClasses(position, bindingContext, isVisibleFilterCheckAlways)
flushToResultSet()
nameWithTypeCompletion.addFromAllClasses(parameters, indicesHelper(false))
}
}
private val USUALLY_START_UPPER_CASE = DescriptorKindFilter(
DescriptorKindFilter.CLASSIFIERS_MASK or DescriptorKindFilter.FUNCTIONS_MASK,
listOf(NonSamConstructorFunctionExclude, DescriptorKindExclude.Extensions /* needed for faster getReferenceVariants */)
)
private val USUALLY_START_LOWER_CASE = DescriptorKindFilter(
DescriptorKindFilter.CALLABLES_MASK or DescriptorKindFilter.PACKAGES_MASK,
listOf(SamConstructorDescriptorKindExclude)
)
private object NonSamConstructorFunctionExclude : DescriptorKindExclude() {
override fun excludes(descriptor: DeclarationDescriptor) = descriptor is FunctionDescriptor && descriptor !is SamConstructorDescriptor
override val fullyExcludedDescriptorKinds: Int get() = 0
}
| apache-2.0 | 0d3e3e6f82a1f277375853b153da427e | 47.865385 | 168 | 0.60701 | 6.623275 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/utils/SlideInItemAnimator.kt | 1 | 4794 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.utils
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.os.Handler
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.RecyclerView
import android.view.Gravity
import android.view.View
import java.util.*
/**
* A [RecyclerView.ItemAnimator] that fades & slides newly added items in from a given
* direction.
*/
class SlideInItemAnimator @JvmOverloads constructor(
slideFromEdge: Int = Gravity.BOTTOM,
layoutDirection: Int = -1
) : DefaultItemAnimator() {
private val pendingAdds = ArrayList<RecyclerView.ViewHolder>()
private val slideFromEdge: Int = Gravity.getAbsoluteGravity(slideFromEdge, layoutDirection)
private var useDefaultAnimator = false
init {
addDuration = 160L
}
override fun animateAdd(holder: RecyclerView.ViewHolder): Boolean {
if (useDefaultAnimator) {
return super.animateAdd(holder)
}
holder.itemView.alpha = 0f
when (slideFromEdge) {
Gravity.START -> holder.itemView.translationX = (-holder.itemView.width / 3).toFloat()
Gravity.TOP -> holder.itemView.translationY = (-holder.itemView.height / 3).toFloat()
Gravity.END -> holder.itemView.translationX = (holder.itemView.width / 3).toFloat()
else // Gravity.BOTTOM
-> holder.itemView.translationY = (holder.itemView.height / 3).toFloat()
}
pendingAdds.add(holder)
return true
}
override fun runPendingAnimations() {
super.runPendingAnimations()
if (!pendingAdds.isEmpty()) {
for (i in pendingAdds.indices.reversed()) {
val holder = pendingAdds[i]
Handler().postDelayed(
{
holder.itemView.animate()
.alpha(1f)
.translationX(0f)
.translationY(0f)
.setDuration(addDuration)
.setListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
dispatchAddStarting(holder)
}
override fun onAnimationEnd(animation: Animator) {
animation.listeners.remove(this)
dispatchAddFinished(holder)
dispatchFinishedWhenDone()
}
override fun onAnimationCancel(animation: Animator) {
clearAnimatedValues(holder.itemView)
}
}).interpolator = LinearOutSlowInInterpolator()
},
(holder.adapterPosition * 30).toLong()
)
pendingAdds.removeAt(i)
}
useDefaultAnimator = true
}
}
override fun endAnimation(holder: RecyclerView.ViewHolder) {
holder.itemView.animate().cancel()
if (pendingAdds.remove(holder)) {
dispatchAddFinished(holder)
clearAnimatedValues(holder.itemView)
}
super.endAnimation(holder)
}
override fun endAnimations() {
for (i in pendingAdds.indices.reversed()) {
val holder = pendingAdds[i]
clearAnimatedValues(holder.itemView)
dispatchAddFinished(holder)
pendingAdds.removeAt(i)
}
super.endAnimations()
}
override fun isRunning(): Boolean {
return !pendingAdds.isEmpty() || super.isRunning()
}
private fun dispatchFinishedWhenDone() {
if (!isRunning) {
dispatchAnimationsFinished()
}
}
private fun clearAnimatedValues(view: View) {
view.alpha = 1f
view.translationX = 0f
view.translationY = 0f
view.animate().startDelay = 0
}
}
/**
* Default to sliding in upward.
*/// undefined layout dir; bottom isn't relative
| gpl-2.0 | 049c5851ca524cb61d927674b88c6b1d | 34.25 | 98 | 0.591781 | 5.250821 | false | false | false | false |
raniejade/zerofx | zerofx-view-helpers/src/main/kotlin/io/polymorphicpanda/zerofx/template/helpers/Builder.kt | 1 | 2203 | package io.polymorphicpanda.zerofx.template.helpers
import javafx.scene.Node
/**
* @author Ranie Jade Ramiso
*/
open class Builder<T: Node>(val node: T) {
fun styleClass() = node.styleClass
fun styleClass(vararg classes: String) {
styleClass().addAll(classes)
}
fun focusedProperty() = node.focusedProperty()
val focused = focusedProperty().get()
fun hoveredProperty() = node.hoverProperty()
val hovered = hoveredProperty().get()
fun focusTraversableProperty() = node.focusTraversableProperty()
var focusTraversable: Boolean
get() = focusTraversableProperty().get()
set(value) {
focusTraversableProperty().set(value)
}
fun disableProperty() = node.disableProperty()
var disable: Boolean
get() = disableProperty().get()
set(value) {
disableProperty().set(value)
}
fun visibleProperty() = node.visibleProperty()
var visible: Boolean
get() = visibleProperty().get()
set(value) {
visibleProperty().set(value)
}
fun managedProperty() = node.managedProperty()
var managed: Boolean
get() = managedProperty().get()
set(value) {
managedProperty().set(value)
}
fun idProperty() = node.idProperty()
var id: String
get() = idProperty().get()
set(value) {
idProperty().set(value)
}
fun Node.styleClass(vararg styleClass: String) {
this.styleClass.addAll(*styleClass)
}
fun Node.addStyleClass(styleClass: String) {
this.styleClass.apply {
if (!contains(styleClass)) {
add(styleClass)
}
}
}
fun Node.hasStyleClass(vararg styleClass: String): Boolean {
return this.styleClass.containsAll(listOf(*styleClass))
}
fun Node.removeStyleClass(styleClass: String) {
this.styleClass.removeAll {
it == styleClass
}
}
fun Node.toggleStyleClass(styleClass: String) {
if (hasStyleClass(styleClass)) {
removeStyleClass(styleClass)
} else {
addStyleClass(styleClass)
}
}
}
| mit | 307bfc94356e90af60407aa53b1351b4 | 25.22619 | 68 | 0.599183 | 4.46856 | false | false | false | false |
flesire/ontrack | ontrack-service/src/test/java/net/nemerosa/ontrack/service/labels/LabelManagementServiceIT.kt | 1 | 5803 | package net.nemerosa.ontrack.service.labels
import net.nemerosa.ontrack.it.AbstractDSLTestSupport
import net.nemerosa.ontrack.model.labels.LabelForm
import net.nemerosa.ontrack.model.labels.LabelManagement
import net.nemerosa.ontrack.test.TestUtils.uid
import org.junit.Test
import org.springframework.security.access.AccessDeniedException
import kotlin.test.*
class LabelManagementServiceIT : AbstractDSLTestSupport() {
@Test
fun `Creating, updating and deleting a label`() {
val category = uid("C")
val name = uid("N")
asUser().with(LabelManagement::class.java).execute {
val label = labelManagementService.newLabel(
LabelForm(
category = category,
name = name,
description = null,
color = "#FFFFFF"
)
)
assertTrue(label.id > 0)
assertEquals(category, label.category)
assertEquals(name, label.name)
assertNull(label.description)
assertEquals("#FFFFFF", label.color)
assertNull(label.computedBy)
// Updating the description
val updatedLabel = labelManagementService.updateLabel(
label.id,
LabelForm(
category = category,
name = name,
description = "New description",
color = "#FFFFFF"
)
)
assertEquals(label.id, updatedLabel.id)
assertEquals(category, updatedLabel.category)
assertEquals(name, updatedLabel.name)
assertEquals("New description", updatedLabel.description)
assertEquals("#FFFFFF", updatedLabel.color)
assertNull(updatedLabel.computedBy)
// Deleting the label
labelManagementService.deleteLabel(label.id)
val deletedLabel = labelManagementService.labels.find { it.id == label.id }
assertNull(deletedLabel)
}
}
@Test
fun `Null category is allowed`() {
val label = label(category = null)
assertNull(label.category)
}
@Test
fun `Cannot create a label if not authorized`() {
val category = uid("C")
val name = uid("N")
assertFailsWith(AccessDeniedException::class) {
labelManagementService.newLabel(
LabelForm(
category = category,
name = name,
description = null,
color = "#FFFFFF"
)
)
}
}
@Test
fun `Cannot update a label if not authorized`() {
val label = label()
assertFailsWith(AccessDeniedException::class) {
labelManagementService.updateLabel(
label.id,
LabelForm(
category = label.category,
name = label.name,
description = "New description",
color = label.color
)
)
}
}
@Test
fun `Cannot delete a label if not authorized`() {
val label = label()
assertFailsWith(AccessDeniedException::class) {
labelManagementService.deleteLabel(label.id)
}
}
@Test
fun `Associating a list of labels for a project`() {
val labels = (1..5).map { label() }
project {
// Sets some labels for the projects
this.labels = labels.subList(0, 3)
// Checks the labels of the projects
assertEquals(
labels.subList(0, 3).map { it.name },
this.labels.map { it.name }
)
// Sets other labels for the projects (with some intersection)
this.labels = labels.subList(3, 5)
// Checks the labels of the projects
assertEquals(
labels.subList(3, 5).map { it.name },
this.labels.map { it.name }
)
}
}
@Test
fun `Looking for labels per category`() {
val category = uid("C")
(1..5).map { label(category = category, name = "name-$it") }
// Other arbitrary labels
(1..5).map { label() }
// Looking for labels per category
val labels = labelManagementService.findLabels(category, null)
assertTrue(
labels.all {
it.category == category && it.name.matches("name-\\d".toRegex())
}
)
}
@Test
fun `Looking for labels per name only`() {
val name = uid("C")
(1..5).map { label(category = uid("C"), name = name) }
// Other arbitrary labels
(1..5).map { label() }
// Looking for labels per name
val labels = labelManagementService.findLabels(null, name)
assertEquals(5, labels.size)
assertTrue(
labels.all {
it.name == name
}
)
}
@Test
fun `Looking for labels per category and name`() {
val category = uid("C")
val name = uid("N")
label(category = category, name = name)
// Other arbitrary labels
(1..5).map { label() }
// Looking for labels per category and name
val labels = labelManagementService.findLabels(category, name)
assertEquals(1, labels.size)
assertNotNull(labels.firstOrNull()) {
assertEquals(category, it.category)
assertEquals(name, it.name)
}
}
} | mit | 562b1bb9148c0868c7cd55ded6bc5455 | 33.343195 | 87 | 0.519387 | 5.08589 | false | true | false | false |
google/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/ChangesTreeCellRenderer.kt | 6 | 3561 | // 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.vcs.changes.ui
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.ui.CellRendererPanel
import com.intellij.util.ui.ThreeStateCheckBox
import com.intellij.util.ui.accessibility.AccessibleContextDelegate
import com.intellij.util.ui.accessibility.AccessibleContextDelegateWithContextMenu
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Container
import java.awt.Dimension
import javax.accessibility.Accessible
import javax.accessibility.AccessibleContext
import javax.accessibility.AccessibleRole
import javax.swing.JTree
import javax.swing.tree.TreeCellRenderer
open class ChangesTreeCellRenderer(protected val textRenderer: ChangesBrowserNodeRenderer) : CellRendererPanel(), TreeCellRenderer {
private val component = ThreeStateCheckBox()
init {
buildLayout()
}
private fun buildLayout() {
layout = BorderLayout()
add(component, BorderLayout.WEST)
add(textRenderer, BorderLayout.CENTER)
}
override fun getTreeCellRendererComponent(
tree: JTree,
value: Any,
selected: Boolean,
expanded: Boolean,
leaf: Boolean,
row: Int,
hasFocus: Boolean
): Component {
tree as ChangesTree
value as ChangesBrowserNode<*>
customize(this, selected)
textRenderer.apply {
isOpaque = false
isTransparentIconBackground = true
toolTipText = null
getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus)
}
component.apply {
background = null
isOpaque = false
isVisible = tree.run { isShowCheckboxes && isInclusionVisible(value) }
if (isVisible) {
state = tree.getNodeStatus(value)
isEnabled = tree.run { isEnabled && isInclusionEnabled(value) }
}
}
return this
}
override fun getAccessibleContext(): AccessibleContext {
val accessibleComponent = component as? Accessible ?: return super.getAccessibleContext()
if (accessibleContext == null) {
accessibleContext = object : AccessibleContextDelegateWithContextMenu(accessibleComponent.accessibleContext) {
override fun doShowContextMenu() {
ActionManager.getInstance().tryToExecute(ActionManager.getInstance().getAction("ShowPopupMenu"), null, null, null, true)
}
override fun getDelegateParent(): Container? = parent
override fun getAccessibleName(): String? {
accessibleComponent.accessibleContext.accessibleName = textRenderer.accessibleContext.accessibleName
return accessibleComponent.accessibleContext.accessibleName
}
override fun getAccessibleRole(): AccessibleRole {
// Because of a problem with NVDA we have to make this a LABEL,
// or otherwise NVDA will read out the entire tree path, causing confusion.
return AccessibleRole.LABEL
}
}
}
return accessibleContext
}
/**
* Otherwise incorrect node sizes are cached - see [com.intellij.ui.tree.ui.DefaultTreeUI.createNodeDimensions].
* And [com.intellij.ui.ExpandableItemsHandler] does not work correctly.
*/
override fun getPreferredSize(): Dimension = layout.preferredLayoutSize(this)
override fun getToolTipText(): String? = textRenderer.toolTipText
companion object {
fun customize(panel: CellRendererPanel, selected: Boolean) {
panel.background = null
panel.isSelected = selected
}
}
} | apache-2.0 | 5ff5673e5256324f300061d9be68ea6a | 32.28972 | 132 | 0.733783 | 5.043909 | false | false | false | false |
algra/pact-jvm | pact-jvm-model/src/main/kotlin/au/com/dius/pact/model/FilteredPact.kt | 1 | 576 | package au.com.dius.pact.model
import java.util.function.Predicate
class FilteredPact<I>(val pact: Pact<I>, private val interactionPredicate: Predicate<I>) : Pact<I> by pact
where I: Interaction {
override val interactions: List<I>
get() = pact.interactions.filter { interactionPredicate.test(it) }
fun isNotFiltered() = pact.interactions.all { interactionPredicate.test(it) }
fun isFiltered() = pact.interactions.any { !interactionPredicate.test(it) }
override fun toString(): String {
return "FilteredPact(pact=$pact, filtered=${isFiltered()})"
}
}
| apache-2.0 | 7b6e4c96e3878b41e39336ab90d42f1d | 32.882353 | 106 | 0.730903 | 3.81457 | false | true | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/DynamicObject.kt | 1 | 3027 | package org.runestar.client.updater.mapper.std.classes
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.OrderMapper
import org.runestar.client.updater.mapper.DependsOn
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Instruction2
import org.runestar.client.updater.mapper.Method2
@DependsOn(Entity::class, SeqType::class)
class DynamicObject : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == type<Entity>() }
.and { it.instanceMethods.size == 1 }
.and { it.instanceFields.count { it.type == type<SeqType>() } == 1 }
@DependsOn(SeqType::class)
class seqType : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == type<SeqType>() }
}
class id : OrderMapper.InConstructor.Field(DynamicObject::class, 0) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
class type : OrderMapper.InConstructor.Field(DynamicObject::class, 1) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
class orientation : OrderMapper.InConstructor.Field(DynamicObject::class, 2) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
class plane : OrderMapper.InConstructor.Field(DynamicObject::class, 3) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
class x : OrderMapper.InConstructor.Field(DynamicObject::class, 4) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
class y : OrderMapper.InConstructor.Field(DynamicObject::class, 5) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
class frame : OrderMapper.InConstructor.Field(DynamicObject::class, 6) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
// todo
class cycleStart : OrderMapper.InConstructor.Field(DynamicObject::class, 7) {
override val predicate = predicateOf<Instruction2> { it.opcode == Opcodes.PUTFIELD && it.fieldType == Type.INT_TYPE }
}
@MethodParameters()
@DependsOn(Entity.getModel::class)
class getModel : InstanceMethod() {
override val predicate = predicateOf<Method2> { it.mark == method<Entity.getModel>().mark }
}
} | mit | 74cfe241888dd52a6747a671d88dcbbb | 44.878788 | 125 | 0.717872 | 4.180939 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/AbstractMultifileRefactoringTest.kt | 5 | 5209 | // 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.refactoring
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.idea.jsonUtils.getNullableString
import org.jetbrains.kotlin.idea.refactoring.rename.loadTestConfiguration
import org.jetbrains.kotlin.idea.test.*
import org.jetbrains.kotlin.util.prefixIfNot
import java.io.File
abstract class AbstractMultifileRefactoringTest : KotlinLightCodeInsightFixtureTestCase() {
interface RefactoringAction {
fun runRefactoring(rootDir: VirtualFile, mainFile: PsiFile, elementsAtCaret: List<PsiElement>, config: JsonObject)
}
override fun getProjectDescriptor(): LightProjectDescriptor {
val testConfigurationFile = File(super.getTestDataPath(), fileName())
val config = loadTestConfiguration(testConfigurationFile)
val withRuntime = config["withRuntime"]?.asBoolean ?: false
if (withRuntime) {
return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
}
return KotlinLightProjectDescriptor.INSTANCE
}
protected abstract fun runRefactoring(path: String, config: JsonObject, rootDir: VirtualFile, project: Project)
protected fun doTest(unused: String) {
val testFile = dataFile()
val config = JsonParser.parseString(FileUtil.loadFile(testFile, true)) as JsonObject
doTestCommittingDocuments(testFile) { rootDir ->
val opts = config.getNullableString("customCompilerOpts")?.prefixIfNot("// ") ?: ""
withCustomCompilerOptions(opts, project, module) {
runRefactoring(testFile.path, config, rootDir, project)
}
}
}
override val testDataDirectory: File
get() {
val name = getTestName(true).substringBeforeLast('_').replace('_', '/')
return super.testDataDirectory.resolve(name)
}
override fun fileName() = testDataDirectory.name + ".test"
private fun doTestCommittingDocuments(testFile: File, action: (VirtualFile) -> Unit) {
val beforeVFile = myFixture.copyDirectoryToProject("before", "")
PsiDocumentManager.getInstance(myFixture.project).commitAllDocuments()
val afterDir = File(testFile.parentFile, "after")
val afterVFile = LocalFileSystem.getInstance().findFileByIoFile(afterDir)?.apply {
UsefulTestCase.refreshRecursively(this)
} ?: error("`after` directory not found")
action(beforeVFile)
PsiDocumentManager.getInstance(project).commitAllDocuments()
FileDocumentManager.getInstance().saveAllDocuments()
PlatformTestUtil.assertDirectoriesEqual(afterVFile, beforeVFile) { file -> !KotlinTestUtils.isMultiExtensionName(file.name) }
}
}
fun runRefactoringTest(
path: String,
config: JsonObject,
rootDir: VirtualFile,
project: Project,
action: AbstractMultifileRefactoringTest.RefactoringAction
) {
val mainFilePath = config.getNullableString("mainFile") ?: config.getAsJsonArray("filesToMove").first().asString
val conflictFile = File(File(path).parentFile, "conflicts.txt")
val mainFile = rootDir.findFileByRelativePath(mainFilePath)!!
val mainPsiFile = PsiManager.getInstance(project).findFile(mainFile)!!
val document = FileDocumentManager.getInstance().getDocument(mainFile)!!
val editor = EditorFactory.getInstance()!!.createEditor(document, project)!!
val caretOffsets = document.extractMultipleMarkerOffsets(project)
val elementsAtCaret = caretOffsets.map {
TargetElementUtil.getInstance().findTargetElement(
editor,
TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED or TargetElementUtil.ELEMENT_NAME_ACCEPTED,
it
)!!
}
try {
action.runRefactoring(rootDir, mainPsiFile, elementsAtCaret, config)
assert(!conflictFile.exists())
} catch (e: BaseRefactoringProcessor.ConflictsInTestsException) {
KotlinTestUtils.assertEqualsToFile(conflictFile, e.messages.distinct().sorted().joinToString("\n"))
BaseRefactoringProcessor.ConflictsInTestsException.withIgnoredConflicts<Throwable> {
// Run refactoring again with ConflictsInTestsException suppressed
action.runRefactoring(rootDir, mainPsiFile, elementsAtCaret, config)
}
} finally {
EditorFactory.getInstance()!!.releaseEditor(editor)
}
} | apache-2.0 | c0d3389806d31f52f1b4e4fad934c036 | 42.057851 | 133 | 0.742561 | 5.266936 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.