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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
davidwhitman/changelogs | app/src/main/java/com/thunderclouddev/changelogs/ui/home/HomeUi.kt | 1 | 3151 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.changelogs.ui.home
import android.support.v7.util.DiffUtil
import com.thunderclouddev.changelogs.ui.StateRenderer
import com.thunderclouddev.dataprovider.AppInfosByPackage
import com.thunderclouddev.dataprovider.Progress
import io.reactivex.Observable
/**
* @author David Whitman on 07 May, 2017.
*/
interface HomeUi : StateRenderer<HomeUi.State> {
val state: State
override fun render(state: State)
interface Intentions {
fun scanForUpdatesRequest(): Observable<Unit>
fun loadCachedItems(): Observable<Unit>
fun clearDatabase(): Observable<Unit>
fun refresh(): Observable<Unit>
fun addTestApp(): Observable<Unit>
fun addTestApps(): Observable<Unit>
fun removeTestApp(): Observable<Unit>
}
interface Actions {
fun displayItems(diffResult: RecyclerViewBinding<AppInfosByPackage>)
fun showLoading(marketBulkDetailsProgress: Progress)
fun setRefreshEnabled(enabled: Boolean)
fun showError(error: String)
fun hideError()
}
data class State(val appInfos: List<AppInfosByPackage>,
// val detectingLocalAppsProgress: Progress,
// val fdfeBulkDetailsProgress: Progress,
val marketBulkDetailsProgress: Progress
// val fdfeDetailsProgress: Progress
) {
fun reduce(change: Change): State = when (change) {
is Change.UpdateLoadingMarketBulkDetails -> this.copy(marketBulkDetailsProgress = change.refreshingState)
is Change.Error -> this.copy()
is Change.ReadFromDatabaseComplete -> this.copy(appInfos = change.data)
Change.ReadFromDatabaseRequested -> this.copy()
}
fun isLoading() = marketBulkDetailsProgress.inProgress
sealed class Change(val logString: String) {
// class UpdateDetectingLocalChanges(val refreshingState: Progress)
// class UpdateLoadingFdfeBulkDetails(val refreshingState: Progress)
class UpdateLoadingMarketBulkDetails(val refreshingState: Progress) : Change("Updated market bulk details - $refreshingState")
class ReadFromDatabaseComplete(val data: List<AppInfosByPackage>) : Change("Read apps from database - $data")
// class UpdateLoadingFdfeDetails(val refreshingState: Progress)
class Error(val throwable: Throwable) : Change("Error - ${throwable.message}")
object ReadFromDatabaseRequested : Change("Read from database requested")
}
companion object {
val EMPTY by lazy {
State(appInfos = emptyList(),
marketBulkDetailsProgress = Progress.NONE)
}
}
}
}
data class RecyclerViewBinding<out T>(
val new: List<T>,
val diff: DiffUtil.DiffResult
) | gpl-3.0 | 0f1fac7443838b3ec74293742ff87924 | 35.229885 | 138 | 0.66106 | 4.788754 | false | false | false | false |
mediathekview/MediathekView | src/main/java/mediathek/tool/http/ByteCounter.kt | 1 | 6014 | package mediathek.tool.http
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.InetAddress
import java.net.Socket
import java.util.concurrent.atomic.AtomicLong
import javax.net.SocketFactory
class ByteCounter {
private val socketFactory: SocketFactory = CountSocketFactory()
private val bytesWritten = AtomicLong()
private val bytesRead = AtomicLong()
private val totalBytesRead = AtomicLong()
private val totalBytesWritten = AtomicLong()
fun resetCounters() {
bytesWritten.set(0)
bytesRead.set(0)
}
fun socketFactory(): SocketFactory {
return socketFactory
}
fun bytesWritten(): Long {
return bytesWritten.get()
}
fun bytesRead(): Long {
return bytesRead.get()
}
fun totalBytesRead(): Long {
return totalBytesRead.get()
}
fun totalBytesWritten(): Long {
return totalBytesWritten.get()
}
fun bytesRead(length: Int) {
bytesRead.getAndAdd(length.toLong())
totalBytesRead.getAndAdd(length.toLong())
}
fun bytesWritten(length: Int) {
bytesWritten.getAndAdd(length.toLong())
totalBytesWritten.getAndAdd(length.toLong())
}
internal inner class CountSocketFactory : SocketFactory() {
override fun createSocket(): Socket {
return CountingSocket()
}
@Throws(IOException::class)
override fun createSocket(s: String, i: Int): Socket {
return CountingSocket(s, i)
}
@Throws(IOException::class)
override fun createSocket(s: String, i: Int, inetAddress: InetAddress, i1: Int): Socket {
return CountingSocket(s, i, inetAddress, i1)
}
@Throws(IOException::class)
override fun createSocket(inetAddress: InetAddress, i: Int): Socket {
return CountingSocket(inetAddress, i)
}
@Throws(IOException::class)
override fun createSocket(
inetAddress: InetAddress, i: Int, inetAddress1: InetAddress,
i1: Int
): Socket {
return CountingSocket(inetAddress, i, inetAddress1, i1)
}
}
internal inner class CountingSocket : Socket {
private val lock = Any()
private var outputStream: OutputStream? = null
private var inputStream: InputStream? = null
constructor() : super()
constructor(host: String?, port: Int) : super(host, port)
constructor(address: InetAddress?, port: Int) : super(address, port)
constructor(host: String?, port: Int, localAddr: InetAddress?, localPort: Int) : super(
host,
port,
localAddr,
localPort
)
constructor(address: InetAddress?, port: Int, localAddr: InetAddress?, localPort: Int) : super(
address,
port,
localAddr,
localPort
)
@Throws(IOException::class)
override fun getInputStream(): InputStream {
synchronized(lock) {
if (inputStream == null) {
inputStream = CountingInputStream(super.getInputStream(), this@ByteCounter)
}
}
return inputStream!!
}
@Throws(IOException::class)
override fun getOutputStream(): OutputStream {
synchronized(lock) {
if (outputStream == null) {
outputStream = CountingOutputStream(super.getOutputStream(), this@ByteCounter)
}
}
return outputStream!!
}
}
internal class CountingOutputStream(private val delegate: OutputStream, private val byteCounter: ByteCounter) :
OutputStream() {
@Throws(IOException::class)
override fun write(b: Int) {
delegate.write(b)
byteCounter.bytesWritten(1)
}
@Throws(IOException::class)
override fun write(b: ByteArray) {
delegate.write(b)
byteCounter.bytesWritten(b.size)
}
@Throws(IOException::class)
override fun write(b: ByteArray, off: Int, len: Int) {
delegate.write(b, off, len)
byteCounter.bytesWritten(len)
}
@Throws(IOException::class)
override fun flush() {
delegate.flush()
}
@Throws(IOException::class)
override fun close() {
delegate.close()
}
}
internal class CountingInputStream(private val delegate: InputStream, private val byteCounter: ByteCounter) :
InputStream() {
@Throws(IOException::class)
override fun read(): Int {
val read = delegate.read()
if (read > 0) byteCounter.bytesRead(1)
return read
}
@Throws(IOException::class)
override fun read(b: ByteArray): Int {
val read = delegate.read(b)
if (read > 0) byteCounter.bytesRead(read)
return read
}
@Throws(IOException::class)
override fun read(b: ByteArray, off: Int, len: Int): Int {
val read = delegate.read(b, off, len)
if (read > 0) byteCounter.bytesRead(read)
return read
}
@Throws(IOException::class)
override fun skip(n: Long): Long {
return delegate.skip(n)
}
@Throws(IOException::class)
override fun available(): Int {
return delegate.available()
}
@Throws(IOException::class)
override fun close() {
delegate.close()
}
@Synchronized
override fun mark(readlimit: Int) {
delegate.mark(readlimit)
}
@Synchronized
@Throws(IOException::class)
override fun reset() {
delegate.reset()
}
override fun markSupported(): Boolean {
return delegate.markSupported()
}
}
} | gpl-3.0 | 4bc5498e2d6ce3355471e6a5d771c092 | 27.779904 | 115 | 0.579814 | 4.957955 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/adapter/BlackListCursorListViewAdapter.kt | 1 | 1580 | package me.ykrank.s1next.view.adapter
import android.app.Activity
import android.content.Context
import android.database.Cursor
import androidx.databinding.DataBindingUtil
import androidx.cursoradapter.widget.CursorAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import me.ykrank.s1next.R
import me.ykrank.s1next.data.db.BlackListDbWrapper
import me.ykrank.s1next.data.db.dbmodel.BlackList
import me.ykrank.s1next.databinding.ItemBlacklistBinding
import me.ykrank.s1next.viewmodel.BlackListViewModel
class BlackListCursorListViewAdapter(activity: Activity) : androidx.cursoradapter.widget.CursorAdapter(activity, null, true) {
private val mLayoutInflater: LayoutInflater = activity.layoutInflater
override fun newView(context: Context, cursor: Cursor, parent: ViewGroup): View {
val itemBlacklistBinding = DataBindingUtil.inflate<ItemBlacklistBinding>(mLayoutInflater,
R.layout.item_blacklist, parent, false)
itemBlacklistBinding.blackListViewModel = BlackListViewModel()
return itemBlacklistBinding.root
}
override fun bindView(view: View, context: Context, cursor: Cursor) {
val binding = DataBindingUtil.findBinding<ItemBlacklistBinding>(view)
binding?.blackListViewModel?.blacklist?.set(BlackListDbWrapper.getInstance().fromBlackListCursor(cursor))
}
override fun getItem(position: Int): BlackList {
val cursor = super.getItem(position) as Cursor
return BlackListDbWrapper.getInstance().fromBlackListCursor(cursor)
}
}
| apache-2.0 | d650c2300cf03211ade77a10916fa7e8 | 40.578947 | 126 | 0.788608 | 4.413408 | false | false | false | false |
Mauin/detekt | detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/Tasks.kt | 1 | 832 | package io.gitlab.arturbosch.detekt.core
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import java.util.concurrent.ForkJoinPool
import java.util.function.Supplier
/**
* @author Artur Bosch
*/
fun <T> withExecutor(executor: Executor? = null, block: Executor.() -> T): T {
if (executor == null) {
val defaultExecutor = ForkJoinPool.commonPool()
return block.invoke(defaultExecutor).apply {
defaultExecutor.shutdown()
}
}
return block.invoke(executor)
}
fun <T> Executor.runAsync(block: () -> T): CompletableFuture<T> {
return task(this) { block() }
}
fun <T> task(executor: Executor, task: () -> T): CompletableFuture<T> {
return CompletableFuture.supplyAsync(Supplier { task() }, executor)
}
fun <T> awaitAll(futures: List<CompletableFuture<T>>) = futures.map { it.join() }
| apache-2.0 | 841e1ea5ef805ceda95231f248a74413 | 26.733333 | 81 | 0.722356 | 3.452282 | false | false | false | false |
GDG-Nantes/devfest-android | app/src/main/kotlin/com/gdgnantes/devfest/android/content/RemindersReceiver.kt | 1 | 1897 | package com.gdgnantes.devfest.android.content
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.PowerManager
import com.gdgnantes.devfest.android.app.PREFIX_ACTION
import com.gdgnantes.devfest.android.app.PREFIX_EXTRA
import com.gdgnantes.devfest.android.util.asArrayList
class RemindersReceiver : BroadcastReceiver() {
companion object {
private const val ACTION_SHOW_REMINDERS = "${PREFIX_ACTION}SHOW_REMINDERS"
private const val EXTRA_REMINDER_INFOS = "${PREFIX_EXTRA}REMINDER_INFOS"
private const val WAKE_LOCK_LIFE_TIME = 30 * 1000L
fun newShowRemindersIntent(context: Context, reminderInfos: List<Bundle>): Intent
= Intent(context, RemindersReceiver::class.java)
.setAction(ACTION_SHOW_REMINDERS)
.putParcelableArrayListExtra(EXTRA_REMINDER_INFOS, reminderInfos.asArrayList())
}
override fun onReceive(context: Context, intent: Intent) {
val wakeLock = acquireWakeLock(context)
val result = goAsync()
Thread({
val manager = RemindersManager.from(context)
when (intent.action) {
ACTION_SHOW_REMINDERS -> {
manager.showNotification(intent.getParcelableArrayListExtra<Bundle>(EXTRA_REMINDER_INFOS))
}
}
manager.updateAlarm()
wakeLock.release()
result.finish()
}).start()
}
private fun acquireWakeLock(context: Context): PowerManager.WakeLock {
val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
return powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "devfest-wake-lock").apply {
setReferenceCounted(false)
acquire(WAKE_LOCK_LIFE_TIME)
}
}
} | apache-2.0 | 59b51c72f75d082820fff103355a4d38 | 35.5 | 110 | 0.677912 | 4.754386 | false | false | false | false |
AcapellaSoft/Aconite | aconite-server/src/io/aconite/server/Interceptors.kt | 1 | 1882 | package io.aconite.server
import io.aconite.Request
import io.aconite.annotations.AfterRequest
import io.aconite.annotations.BeforeRequest
import java.util.concurrent.ConcurrentHashMap
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.full.findAnnotation
import kotlin.reflect.full.functions
internal typealias Interceptor = suspend (obj: Any, url: String, request: Request) -> Unit
internal class Interceptors(private val server: AconiteServer) {
private val beforeMap = ConcurrentHashMap<Class<*>, Interceptor>()
private val afterMap = ConcurrentHashMap<Class<*>, Interceptor>()
suspend fun beforeRequest(obj: Any, url: String, request: Request) {
val before = beforeMap.computeIfAbsent(obj.javaClass) { buildBefore(obj::class) }
before(obj, url, request)
}
suspend fun afterRequest(obj: Any, url: String, request: Request) {
val after = afterMap.computeIfAbsent(obj.javaClass) { buildAfter(obj::class) }
after(obj, url, request)
}
private fun buildBefore(clazz: KClass<*>) = buildInterceptFunction<BeforeRequest>(clazz)
private fun buildAfter(clazz: KClass<*>) = buildInterceptFunction<AfterRequest>(clazz)
private inline fun <reified T : Annotation> buildInterceptFunction(clazz: KClass<*>): Interceptor {
val interceptFunctions = clazz.functions
.filter { it.findAnnotation<T>() != null }
.map { InterceptWrapper(server, it) }
return { obj, _, request ->
for (fn in interceptFunctions) fn(obj, request)
}
}
}
internal class InterceptWrapper(server: AconiteServer, private val fn: KFunction<*>) {
private val args = transformRequestParams(server, server.parser.parseArguments(fn))
suspend operator fun invoke(obj: Any, request: Request) {
fn.httpCall(args, obj, request)
}
} | mit | e81230dcc49e5ae6e357d7ab25982190 | 37.428571 | 103 | 0.713603 | 4.356481 | false | false | false | false |
googlesamples/mlkit | android/material-showcase/app/src/main/java/com/google/mlkit/md/barcodedetection/BarcodeGraphicBase.kt | 1 | 2962 | /*
* 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.barcodedetection
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.CornerPathEffect
import android.graphics.Paint
import android.graphics.Paint.Style
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
import androidx.core.content.ContextCompat
import com.google.mlkit.md.camera.GraphicOverlay
import com.google.mlkit.md.camera.GraphicOverlay.Graphic
import com.google.mlkit.md.R
import com.google.mlkit.md.settings.PreferenceUtils
internal abstract class BarcodeGraphicBase(overlay: GraphicOverlay) : Graphic(overlay) {
private val boxPaint: Paint = Paint().apply {
color = ContextCompat.getColor(context, R.color.barcode_reticle_stroke)
style = Style.STROKE
strokeWidth = context.resources.getDimensionPixelOffset(R.dimen.barcode_reticle_stroke_width).toFloat()
}
private val scrimPaint: Paint = Paint().apply {
color = ContextCompat.getColor(context, R.color.barcode_reticle_background)
}
private val eraserPaint: Paint = Paint().apply {
strokeWidth = boxPaint.strokeWidth
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
}
val boxCornerRadius: Float =
context.resources.getDimensionPixelOffset(R.dimen.barcode_reticle_corner_radius).toFloat()
val pathPaint: Paint = Paint().apply {
color = Color.WHITE
style = Style.STROKE
strokeWidth = boxPaint.strokeWidth
pathEffect = CornerPathEffect(boxCornerRadius)
}
val boxRect: RectF = PreferenceUtils.getBarcodeReticleBox(overlay)
override fun draw(canvas: Canvas) {
// Draws the dark background scrim and leaves the box area clear.
canvas.drawRect(0f, 0f, canvas.width.toFloat(), canvas.height.toFloat(), scrimPaint)
// As the stroke is always centered, so erase twice with FILL and STROKE respectively to clear
// all area that the box rect would occupy.
eraserPaint.style = Style.FILL
canvas.drawRoundRect(boxRect, boxCornerRadius, boxCornerRadius, eraserPaint)
eraserPaint.style = Style.STROKE
canvas.drawRoundRect(boxRect, boxCornerRadius, boxCornerRadius, eraserPaint)
// Draws the box.
canvas.drawRoundRect(boxRect, boxCornerRadius, boxCornerRadius, boxPaint)
}
}
| apache-2.0 | e702bf286271fba9d2e1dab58fae6ce2 | 39.027027 | 111 | 0.741053 | 4.401189 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/activities/TagSettingsActivity.kt | 1 | 5202 | /*
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package org.tasks.activities
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.inputmethod.InputMethodManager
import androidx.core.widget.addTextChangedListener
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.todoroo.astrid.activity.MainActivity
import com.todoroo.astrid.activity.TaskListFragment
import com.todoroo.astrid.api.TagFilter
import com.todoroo.astrid.helper.UUIDHelper
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.Strings.isNullOrEmpty
import org.tasks.data.TagDao
import org.tasks.data.TagData
import org.tasks.data.TagDataDao
import org.tasks.databinding.ActivityTagSettingsBinding
import javax.inject.Inject
@AndroidEntryPoint
class TagSettingsActivity : BaseListSettingsActivity() {
@Inject lateinit var tagDataDao: TagDataDao
@Inject lateinit var tagDao: TagDao
private lateinit var name: TextInputEditText
private lateinit var nameLayout: TextInputLayout
private var isNewTag = false
private lateinit var tagData: TagData
override fun onCreate(savedInstanceState: Bundle?) {
tagData = intent.getParcelableExtra(EXTRA_TAG_DATA)
?: TagData().apply {
isNewTag = true
remoteId = UUIDHelper.newUUID()
}
super.onCreate(savedInstanceState)
if (savedInstanceState == null) {
selectedColor = tagData.getColor()!!
selectedIcon = tagData.getIcon()!!
}
name.setText(tagData.name)
val autopopulateName = intent.getStringExtra(TOKEN_AUTOPOPULATE_NAME)
if (!isNullOrEmpty(autopopulateName)) {
name.setText(autopopulateName)
intent.removeExtra(TOKEN_AUTOPOPULATE_NAME)
} else if (isNewTag) {
name.requestFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(name, InputMethodManager.SHOW_IMPLICIT)
}
updateTheme()
}
override val isNew: Boolean
get() = isNewTag
override val toolbarTitle: String
get() = if (isNew) getString(R.string.new_tag) else tagData.name!!
private val newName: String
get() = name.text.toString().trim { it <= ' ' }
private suspend fun clashes(newName: String): Boolean {
return ((isNewTag || !newName.equals(tagData.name, ignoreCase = true))
&& tagDataDao.getTagByName(newName) != null)
}
override suspend fun save() {
val newName = newName
if (isNullOrEmpty(newName)) {
nameLayout.error = getString(R.string.name_cannot_be_empty)
return
}
if (clashes(newName)) {
nameLayout.error = getString(R.string.tag_already_exists)
return
}
if (isNewTag) {
tagData.name = newName
tagData.setColor(selectedColor)
tagData.setIcon(selectedIcon)
tagDataDao.createNew(tagData)
setResult(Activity.RESULT_OK, Intent().putExtra(MainActivity.OPEN_FILTER, TagFilter(tagData)))
} else if (hasChanges()) {
tagData.name = newName
tagData.setColor(selectedColor)
tagData.setIcon(selectedIcon)
tagDataDao.update(tagData)
tagDao.rename(tagData.remoteId!!, newName)
setResult(
Activity.RESULT_OK,
Intent(TaskListFragment.ACTION_RELOAD)
.putExtra(MainActivity.OPEN_FILTER, TagFilter(tagData)))
}
finish()
}
override fun hasChanges(): Boolean {
return if (isNewTag) {
selectedColor >= 0 || selectedIcon >= 0 || !isNullOrEmpty(newName)
} else {
selectedColor != tagData.getColor()
|| selectedIcon != tagData.getIcon()
|| newName != tagData.name
}
}
override fun finish() {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(name.windowToken, 0)
super.finish()
}
override fun bind() = ActivityTagSettingsBinding.inflate(layoutInflater).let {
name = it.name.apply {
addTextChangedListener(
onTextChanged = { _, _, _, _ -> nameLayout.error = null }
)
}
nameLayout = it.nameLayout
it.root
}
override suspend fun delete() {
val uuid = tagData.remoteId
tagDataDao.delete(tagData)
setResult(
Activity.RESULT_OK,
Intent(TaskListFragment.ACTION_DELETED).putExtra(EXTRA_TAG_UUID, uuid))
finish()
}
companion object {
const val TOKEN_AUTOPOPULATE_NAME = "autopopulateName" // $NON-NLS-1$
const val EXTRA_TAG_DATA = "tagData" // $NON-NLS-1$
private const val EXTRA_TAG_UUID = "uuid" // $NON-NLS-1$
}
} | gpl-3.0 | d796560ff0bc9d9a9d8465e8c3f93c0d | 34.155405 | 106 | 0.638985 | 4.551181 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/dialogs/FilterPickerViewModel.kt | 1 | 3952 | package org.tasks.dialogs
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.todoroo.astrid.api.Filter
import com.todoroo.astrid.api.FilterListItem
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.tasks.LocalBroadcastManager
import org.tasks.R
import org.tasks.billing.Inventory
import org.tasks.data.CaldavDao
import org.tasks.data.GoogleTaskDao
import org.tasks.dialogs.FilterPicker.Companion.EXTRA_LISTS_ONLY
import org.tasks.filters.FilterProvider
import org.tasks.filters.NavigationDrawerSubheader
import org.tasks.preferences.Preferences
import org.tasks.themes.ColorProvider
import org.tasks.themes.CustomIcons
import javax.inject.Inject
@HiltViewModel
class FilterPickerViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
@ApplicationContext private val context: Context,
private val filterProvider: FilterProvider,
private val localBroadcastManager: LocalBroadcastManager,
private val inventory: Inventory,
private val colorProvider: ColorProvider,
private val preferences: Preferences,
private val googleTaskDao: GoogleTaskDao,
private val caldavDao: CaldavDao,
) : ViewModel() {
private val listsOnly = savedStateHandle[EXTRA_LISTS_ONLY] ?: false
data class ViewState(
val filters: List<FilterListItem> = emptyList(),
)
private val _viewState = MutableStateFlow(ViewState())
val viewState: StateFlow<ViewState>
get() = _viewState.asStateFlow()
private val refreshReceiver: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
refresh()
}
}
private fun refresh() = viewModelScope.launch {
val items = if (listsOnly) {
filterProvider.listPickerItems()
} else {
filterProvider.filterPickerItems()
}
_viewState.update { it.copy(filters = items) }
}
fun onClick(subheader: NavigationDrawerSubheader) = viewModelScope.launch {
val collapsed = !subheader.isCollapsed
when (subheader.subheaderType) {
NavigationDrawerSubheader.SubheaderType.PREFERENCE ->
preferences.setBoolean(subheader.id.toInt(), collapsed)
NavigationDrawerSubheader.SubheaderType.GOOGLE_TASKS ->
googleTaskDao.setCollapsed(subheader.id, collapsed)
NavigationDrawerSubheader.SubheaderType.CALDAV,
NavigationDrawerSubheader.SubheaderType.TASKS,
NavigationDrawerSubheader.SubheaderType.ETESYNC ->
caldavDao.setCollapsed(subheader.id, collapsed)
}
localBroadcastManager.broadcastRefreshList()
}
fun getIcon(filter: Filter): Int {
if (filter.icon < 1000 || inventory.hasPro) {
val icon = CustomIcons.getIconResId(filter.icon)
if (icon != null) {
return icon
}
}
return R.drawable.ic_list_24px
}
fun getColor(filter: Filter): Int {
if (filter.tint != 0) {
val color = colorProvider.getThemeColor(filter.tint, true)
if (color.isFree || inventory.purchasedThemes()) {
return color.primaryColor
}
}
return context.getColor(R.color.text_primary)
}
override fun onCleared() {
localBroadcastManager.unregisterReceiver(refreshReceiver)
}
init {
localBroadcastManager.registerRefreshListReceiver(refreshReceiver)
refresh()
}
} | gpl-3.0 | 3b89da1183c5e614a35f766688ecad70 | 34.612613 | 83 | 0.715334 | 4.903226 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/util/process/BufferedSink.kt | 1 | 1657 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.util.process
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
open class BufferedSink() : Sink {
var reader: BufferedReader? = null
var handler: ((String) -> Unit)? = null
constructor(handler: (String) -> Unit) : this() {
this.handler = handler
}
override fun setStream(stream: InputStream) {
reader = BufferedReader(InputStreamReader(stream))
}
override fun run() {
val reader = this.reader ?: return
try {
while (true) {
val line = reader.readLine() ?: break
sink(line)
}
} catch (e: IOException) {
sinkError(e)
} finally {
reader.close()
}
}
protected open fun sink(line: String) {
handler?.let { it(line) }
}
protected open fun sinkError(e: IOException) {
// Do nothing
}
}
| gpl-3.0 | bff49b82eca3bd032f4d5066ebfe6aab | 25.301587 | 69 | 0.658419 | 4.337696 | false | false | false | false |
googlecodelabs/kotlin-coroutines | advanced-coroutines-codelab/finished_code/src/main/java/com/example/android/advancedcoroutines/NetworkService.kt | 1 | 1629 | package com.example.android.advancedcoroutines
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
class NetworkService {
private val retrofit = Retrofit.Builder()
.baseUrl("https://raw.githubusercontent.com/")
.client(OkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build()
private val sunflowerService = retrofit.create(SunflowerService::class.java)
suspend fun allPlants(): List<Plant> = withContext(Dispatchers.Default) {
delay(1500)
val result = sunflowerService.getAllPlants()
result.shuffled()
}
suspend fun plantsByGrowZone(growZone: GrowZone) = withContext(Dispatchers.Default) {
delay(1500)
val result = sunflowerService.getAllPlants()
result.filter { it.growZoneNumber == growZone.number }.shuffled()
}
suspend fun customPlantSortOrder(): List<String> = withContext(Dispatchers.Default) {
val result = sunflowerService.getCustomPlantSortOrder()
result.map { plant -> plant.plantId }
}
}
interface SunflowerService {
@GET("googlecodelabs/kotlin-coroutines/master/advanced-coroutines-codelab/sunflower/src/main/assets/plants.json")
suspend fun getAllPlants() : List<Plant>
@GET("googlecodelabs/kotlin-coroutines/master/advanced-coroutines-codelab/sunflower/src/main/assets/custom_plant_sort_order.json")
suspend fun getCustomPlantSortOrder() : List<Plant>
} | apache-2.0 | 7f70332d23be8b797f67f30df880cb99 | 35.222222 | 134 | 0.740945 | 4.355615 | false | false | false | false |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/structure/Branch.kt | 1 | 3125 | package net.nemerosa.ontrack.model.structure
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonView
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.YesNo
import javax.validation.constraints.Size
/**
* Representation of a branch inside a [Project]. They are usually associated
* to a branch of the SCM associated with the parent project.
*/
data class Branch(
override val id: ID,
@Size(max = NAME_MAX_LENGTH)
val name: String,
override val description: String?,
@JsonProperty("disabled")
val isDisabled: Boolean,
@JsonProperty("project")
@get:JsonView(value = [
PromotionView::class, Branch::class, Build::class, PromotionLevel::class, ValidationStamp::class,
PromotionRun::class, ValidationRun::class, PromotionRunView::class
])
@get:JsonIgnore(false) // Overridding default at [ProjectEntity] level
override val project: Project,
override val signature: Signature
) : ProjectEntity {
fun withId(id: ID) = Branch(id, name, description, isDisabled, project, signature)
fun withDescription(description: String?) = Branch(id, name, description, isDisabled, project, signature)
fun withDisabled(isDisabled: Boolean) = Branch(id, name, description, isDisabled, project, signature)
fun withSignature(signature: Signature) = Branch(id, name, description, isDisabled, project, signature)
companion object {
/**
* Maximum length for the name of a branch.
*/
const val NAME_MAX_LENGTH = 120
@JvmStatic
fun of(project: Project, nameDescription: NameDescription) =
of(project, nameDescription.asState())
@JvmStatic
fun of(project: Project, nameDescription: NameDescriptionState) =
Branch(
ID.NONE,
nameDescription.name,
nameDescription.description,
nameDescription.isDisabled,
project,
Signature.anonymous()
)
@JvmStatic
fun form(): Form = Form.create()
.with(
Form.defaultNameField().length(120)
)
.description()
.with(
YesNo.of("disabled").label("Disabled").help("Check if the branch must be disabled.")
)
}
override val parent: ProjectEntity? get() = project
override val projectEntityType: ProjectEntityType = ProjectEntityType.BRANCH
override val entityDisplayName: String
get() = "Branch ${project.name}/$name"
fun toForm(): Form = form()
.fill("name", name)
.fill("description", description)
.fill("disabled", isDisabled)
fun update(form: NameDescriptionState): Branch =
of(project, form)
.withId(id).withDisabled(form.isDisabled)
}
| mit | e70e8e5b6c145dc2c34afda5f9ce434d | 34.11236 | 109 | 0.616 | 5.008013 | false | false | false | false |
wiltonlazary/kotlin-native | tools/benchmarks/shared/src/main/kotlin/report/BenchmarksReport.kt | 1 | 13991 | /*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.report
import org.jetbrains.report.json.*
interface JsonSerializable {
fun serializeFields(): String
fun toJson(): String {
return """
{
${serializeFields()}
}
"""
}
// Convert iterable objects arrays, lists to json.
fun <T> arrayToJson(data: Iterable<T>): String {
return data.joinToString(prefix = "[", postfix = "]") {
if (it is JsonSerializable) it.toJson() else it.toString()
}
}
}
interface EntityFromJsonFactory<T> : ConvertedFromJson {
fun create(data: JsonElement): T
}
// Parse array with benchmarks to list
fun parseBenchmarksArray(data: JsonElement): List<BenchmarkResult> {
if (data is JsonArray) {
return data.jsonArray.map {
if (MeanVarianceBenchmark.isMeanVarianceBenchmark(it))
MeanVarianceBenchmark.create(it as JsonObject)
else BenchmarkResult.create(it as JsonObject)
}
} else {
error("Benchmarks field is expected to be an array. Please, check origin files.")
}
}
// Class for benchmarks report with all information of run.
open class BenchmarksReport(val env: Environment, benchmarksList: List<BenchmarkResult>, val compiler: Compiler) :
JsonSerializable {
companion object : EntityFromJsonFactory<BenchmarksReport> {
override fun create(data: JsonElement): BenchmarksReport {
if (data is JsonObject) {
val env = Environment.create(data.getRequiredField("env"))
val benchmarksObj = data.getRequiredField("benchmarks")
val compiler = Compiler.create(data.getRequiredField("kotlin"))
val buildNumberField = data.getOptionalField("buildNumber")
val benchmarksList = parseBenchmarksArray(benchmarksObj)
val report = BenchmarksReport(env, benchmarksList, compiler)
buildNumberField?.let { report.buildNumber = (it as JsonLiteral).unquoted() }
return report
} else {
error("Top level entity is expected to be an object. Please, check origin files.")
}
}
// Made a map of becnhmarks with name as key from list.
private fun structBenchmarks(benchmarksList: List<BenchmarkResult>) =
benchmarksList.groupBy { it.name }
}
val benchmarks = structBenchmarks(benchmarksList)
var buildNumber: String? = null
override fun serializeFields(): String {
val buildNumberField = buildNumber?.let {
""",
"buildNumber": "$buildNumber"
"""
} ?: ""
return """
"env": ${env.toJson()},
"kotlin": ${compiler.toJson()},
"benchmarks": ${arrayToJson(benchmarks.flatMap { it.value })}$buildNumberField
""".trimIndent()
}
fun merge(other: BenchmarksReport): BenchmarksReport {
val mergedBenchmarks = HashMap(benchmarks)
other.benchmarks.forEach {
if (it.key in mergedBenchmarks) {
error("${it.key} already exists in report!")
}
}
mergedBenchmarks.putAll(other.benchmarks)
return BenchmarksReport(env, mergedBenchmarks.flatMap { it.value }, compiler)
}
// Concatenate benchmarks report if they have same environment and compiler.
operator fun plus(other: BenchmarksReport): BenchmarksReport {
if (compiler != other.compiler || env != other.env) {
error("It's impossible to concat reports from different machines!")
}
return merge(other)
}
}
// Class for kotlin compiler
data class Compiler(val backend: Backend, val kotlinVersion: String) : JsonSerializable {
enum class BackendType(val type: String) {
JVM("jvm"),
NATIVE("native")
}
companion object : EntityFromJsonFactory<Compiler> {
override fun create(data: JsonElement): Compiler {
if (data is JsonObject) {
val backend = Backend.create(data.getRequiredField("backend"))
val kotlinVersion = elementToString(data.getRequiredField("kotlinVersion"), "kotlinVersion")
return Compiler(backend, kotlinVersion)
} else {
error("Kotlin entity is expected to be an object. Please, check origin files.")
}
}
fun backendTypeFromString(s: String): BackendType? = BackendType.values().find { it.type == s }
}
// Class for compiler backend
data class Backend(val type: BackendType, val version: String, val flags: List<String>) : JsonSerializable {
companion object : EntityFromJsonFactory<Backend> {
override fun create(data: JsonElement): Backend {
if (data is JsonObject) {
val typeElement = data.getRequiredField("type")
if (typeElement is JsonLiteral) {
val type = backendTypeFromString(typeElement.unquoted())
?: error("Backend type should be 'jvm' or 'native'")
val version = elementToString(data.getRequiredField("version"), "version")
val flagsArray = data.getOptionalField("flags")
var flags: List<String> = emptyList()
if (flagsArray != null && flagsArray is JsonArray) {
flags = flagsArray.jsonArray.map { it.toString() }
}
return Backend(type, version, flags)
} else {
error("Backend type should be string literal.")
}
} else {
error("Backend entity is expected to be an object. Please, check origin files.")
}
}
}
override fun serializeFields(): String {
val result = """
"type": "${type.type}",
"version": "${version}""""
// Don't print flags field if there is no one.
if (flags.isEmpty()) {
return """$result
"""
} else {
return """
$result,
"flags": ${arrayToJson(flags.map { if (it.startsWith("\"")) it else "\"$it\"" })}
"""
}
}
}
override fun serializeFields(): String {
return """
"backend": ${backend.toJson()},
"kotlinVersion": "${kotlinVersion}"
"""
}
}
// Class for description of environment of benchmarks run
data class Environment(val machine: Machine, val jdk: JDKInstance) : JsonSerializable {
companion object : EntityFromJsonFactory<Environment> {
override fun create(data: JsonElement): Environment {
if (data is JsonObject) {
val machine = Machine.create(data.getRequiredField("machine"))
val jdk = JDKInstance.create(data.getRequiredField("jdk"))
return Environment(machine, jdk)
} else {
error("Environment entity is expected to be an object. Please, check origin files.")
}
}
}
// Class for description of machine used for benchmarks run.
data class Machine(val cpu: String, val os: String) : JsonSerializable {
companion object : EntityFromJsonFactory<Machine> {
override fun create(data: JsonElement): Machine {
if (data is JsonObject) {
val cpu = elementToString(data.getRequiredField("cpu"), "cpu")
val os = elementToString(data.getRequiredField("os"), "os")
return Machine(cpu, os)
} else {
error("Machine entity is expected to be an object. Please, check origin files.")
}
}
}
override fun serializeFields(): String {
return """
"cpu": "$cpu",
"os": "$os"
"""
}
}
// Class for description of jdk used for benchmarks run.
data class JDKInstance(val version: String, val vendor: String) : JsonSerializable {
companion object : EntityFromJsonFactory<JDKInstance> {
override fun create(data: JsonElement): JDKInstance {
if (data is JsonObject) {
val version = elementToString(data.getRequiredField("version"), "version")
val vendor = elementToString(data.getRequiredField("vendor"), "vendor")
return JDKInstance(version, vendor)
} else {
error("JDK entity is expected to be an object. Please, check origin files.")
}
}
}
override fun serializeFields(): String {
return """
"version": "$version",
"vendor": "$vendor"
"""
}
}
override fun serializeFields(): String {
return """
"machine": ${machine.toJson()},
"jdk": ${jdk.toJson()}
"""
}
}
open class BenchmarkResult(val name: String, val status: Status,
val score: Double, val metric: Metric, val runtimeInUs: Double,
val repeat: Int, val warmup: Int) : JsonSerializable {
enum class Metric(val suffix: String, val value: String) {
EXECUTION_TIME("", "EXECUTION_TIME"),
CODE_SIZE(".codeSize", "CODE_SIZE"),
COMPILE_TIME(".compileTime", "COMPILE_TIME"),
BUNDLE_SIZE(".bundleSize", "BUNDLE_SIZE")
}
constructor(name: String, score: Double) : this(name, Status.PASSED, score, Metric.EXECUTION_TIME, 0.0, 0, 0)
companion object : EntityFromJsonFactory<BenchmarkResult> {
override fun create(data: JsonElement): BenchmarkResult {
if (data is JsonObject) {
var name = elementToString(data.getRequiredField("name"), "name")
val metricElement = data.getOptionalField("metric")
val metric = if (metricElement != null && metricElement is JsonLiteral)
metricFromString(metricElement.unquoted()) ?: Metric.EXECUTION_TIME
else Metric.EXECUTION_TIME
name += metric.suffix
val statusElement = data.getRequiredField("status")
if (statusElement is JsonLiteral) {
val status = statusFromString(statusElement.unquoted())
?: error("Status should be PASSED or FAILED")
val score = elementToDouble(data.getRequiredField("score"), "score")
val runtimeInUs = elementToDouble(data.getRequiredField("runtimeInUs"), "runtimeInUs")
val repeat = elementToInt(data.getRequiredField("repeat"), "repeat")
val warmup = elementToInt(data.getRequiredField("warmup"), "warmup")
return BenchmarkResult(name, status, score, metric, runtimeInUs, repeat, warmup)
} else {
error("Status should be string literal.")
}
} else {
error("Benchmark entity is expected to be an object. Please, check origin files.")
}
}
fun statusFromString(s: String): Status? = Status.values().find { it.value == s }
fun metricFromString(s: String): Metric? = Metric.values().find { it.value == s }
}
enum class Status(val value: String) {
PASSED("PASSED"),
FAILED("FAILED")
}
override fun serializeFields(): String {
return """
"name": "${name.removeSuffix(metric.suffix)}",
"status": "${status.value}",
"score": ${score},
"metric": "${metric.value}",
"runtimeInUs": ${runtimeInUs},
"repeat": ${repeat},
"warmup": ${warmup}
"""
}
val shortName: String
get() = name.removeSuffix(metric.suffix)
}
// Entity to describe avarage values which conssists of mean and variance values.
data class MeanVariance(val mean: Double, val variance: Double)
// Processed benchmark result with calculated mean and variance value.
open class MeanVarianceBenchmark(name: String, status: BenchmarkResult.Status, score: Double, metric: BenchmarkResult.Metric,
runtimeInUs: Double, repeat: Int, warmup: Int, val variance: Double) :
BenchmarkResult(name, status, score, metric, runtimeInUs, repeat, warmup) {
constructor(name: String, score: Double, variance: Double) : this(name, BenchmarkResult.Status.PASSED, score,
BenchmarkResult.Metric.EXECUTION_TIME, 0.0, 0, 0, variance)
companion object : EntityFromJsonFactory<MeanVarianceBenchmark> {
fun isMeanVarianceBenchmark(data: JsonElement) = data is JsonObject && data.getOptionalField("variance") != null
override fun create(data: JsonElement): MeanVarianceBenchmark {
if (data is JsonObject) {
val baseBenchmark = BenchmarkResult.create(data)
val variance = elementToDouble(data.getRequiredField("variance"), "variance")
return MeanVarianceBenchmark(baseBenchmark.name, baseBenchmark.status, baseBenchmark.score, baseBenchmark.metric,
baseBenchmark.runtimeInUs, baseBenchmark.repeat, baseBenchmark.warmup, variance)
} else {
error("Benchmark entity is expected to be an object. Please, check origin files.")
}
}
}
override fun serializeFields(): String {
return """
${super.serializeFields()},
"variance": $variance
"""
}
} | apache-2.0 | da73f7b04873fc64e6da6790e6c73573 | 38.863248 | 129 | 0.5778 | 5.007516 | false | false | false | false |
neo4j-contrib/neo4j-apoc-procedures | extended/src/main/kotlin/apoc/nlp/azure/azure/RealAzureClient.kt | 1 | 3673 | package apoc.nlp.azure
import apoc.result.NodeWithMapResult
import apoc.util.JsonUtil
import org.neo4j.graphdb.Node
import org.neo4j.logging.Log
import java.io.DataOutputStream
import java.net.URL
import javax.net.ssl.HttpsURLConnection
enum class AzureEndpoint(val method: String) {
SENTIMENT("/text/analytics/v2.1/sentiment"),
KEY_PHRASES("/text/analytics/v2.1/keyPhrases"),
VISION("/vision/v2.1/analyze"),
ENTITIES("/text/analytics/v2.1/entities")
}
class RealAzureClient(private val baseUrl: String, private val key: String, private val log: Log, val config: Map<String, Any>) : AzureClient {
private val nodeProperty = config.getOrDefault("nodeProperty", "text").toString()
companion object {
fun responseToNodeWithMapResult(resp: Map<String, Any>, source: List<Node>): NodeWithMapResult {
val nodeId = resp.getValue("id").toString().toLong()
val node = source.find { it.id == nodeId }
return NodeWithMapResult(node, resp, emptyMap())
}
}
private fun postData(method: String, subscriptionKeyValue: String, data: List<Map<String, Any>>, config: Map<String, Any> = emptyMap()): List<Map<String, Any>> {
val fullUrl = baseUrl + method + config.map { "${it.key}=${it.value}" }
.joinToString("&")
.also { if (it.isNullOrBlank()) it else "?$it" }
val url = URL(fullUrl)
return postData(url, subscriptionKeyValue, data)
}
private fun postData(url: URL, subscriptionKeyValue: String, data: List<Map<String, Any>>): List<Map<String, Any>> {
val connection = url.openConnection() as HttpsURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Ocp-Apim-Subscription-Key", subscriptionKeyValue)
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json")
DataOutputStream(connection.outputStream).use { it.write(JsonUtil.writeValueAsBytes(mapOf("documents" to convertInput(data)))) }
return connection.inputStream
.use { JsonUtil.OBJECT_MAPPER.readValue(it, Any::class.java) }
.let { result ->
val documents = (result as Map<String, Any?>)["documents"] as List<Map<String, Any?>>
documents.map { it as Map<String, Any> }
}
}
private fun convertInput(data: Any): List<Map<String, Any>> {
return when (data) {
is Map<*, *> -> listOf(data as Map<String, Any>)
is Collection<*> -> data.filterNotNull().map { convertInput(it) }.flatten()
is String -> convertInput(mapOf("id" to 1, "text" to data))
else -> throw java.lang.RuntimeException("Class ${data::class.java.name} not supported")
}
}
override fun entities(nodes: List<Node>, batchId: Int): List<Map<String, Any>> {
val data = nodes.map { node -> mapOf("id" to node.id, "text" to node.getProperty(nodeProperty)) }
return postData(AzureEndpoint.ENTITIES.method, key, data)
}
override fun sentiment(nodes: List<Node>, batchId: Int): List<Map<String, Any>> {
val data = nodes.map { node -> mapOf("id" to node.id, "text" to node.getProperty(nodeProperty)) }
val result = postData(AzureEndpoint.SENTIMENT.method, key, data)
return result
}
override fun keyPhrases(nodes: List<Node>, batchId: Int): List<Map<String, Any>> {
val data = nodes.map { node -> mapOf("id" to node.id, "text" to node.getProperty(nodeProperty)) }
val result = postData(AzureEndpoint.KEY_PHRASES.method, key, data)
return result
}
} | apache-2.0 | c875b1c0cfee8ec4d63fc25f06338467 | 43.804878 | 165 | 0.647427 | 3.996736 | false | false | false | false |
sinnerschrader/account-tool | src/main/kotlin/com/sinnerschrader/s2b/accounttool/config/ldap/LdapQueries.kt | 1 | 1081 | package com.sinnerschrader.s2b.accounttool.config.ldap
object LdapQueries {
fun searchUser(searchTerm: String)= "(&(objectClass=posixAccount)(|(uid=$searchTerm)(givenName=$searchTerm)(sn=$searchTerm)(mail=$searchTerm)(cn=$searchTerm)))"
fun findUserByUid(uid: String)= "(&(objectClass=posixAccount)(uid=$uid))"
fun findUserByUidNumber(uidNumber: String)= "(&(objectClass=posixAccount)(uidNumber=$uidNumber))"
fun findGroupByCn(cn: String)= "(&(|(objectClass=posixGroup)(objectClass=groupOfUniqueNames)(objectClass=groupOfNames))(cn=$cn))"
fun findGroupsByUser(uid: String, userDN: String)= "(|(&(objectClass=posixGroup)(memberUid=$uid))(&(objectClass=groupOfUniqueNames)(uniqueMember=$userDN))(&(objectClass=groupOfNames)(member=$userDN)))"
const val listAllGroups= "(|(objectClass=posixGroup)(objectClass=groupOfUniqueNames)(objectClass=groupOfNames))"
const val listAllUsers= "(&(objectClass=inetOrgPerson)(objectClass=posixAccount))"
fun checkUniqAttribute(attribute: String, value: String)= "(&(objectClass=posixAccount)($attribute=$value))"
}
| mit | fe656be2469e39fcb69873616927be73 | 89.083333 | 205 | 0.758557 | 3.664407 | false | true | false | false |
ShikiEiki/GFTools | app/src/main/java/com/gftools/GFTools.kt | 1 | 1332 | package com.gftools
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
/**
* Created by FH on 2017/8/10.
*/
class GFTools : Application() {
companion object {
lateinit var sp : SharedPreferences
fun getMainForceIndex() : Int {
return sp.getInt("main_force" , -1)
}
fun setMainForceIndex(mainforceIndex : Int){
sp.edit().putInt("main_force" , mainforceIndex).apply()
}
fun setBattleIndex(battleIndex : Int){
sp.edit().putInt("battle" , battleIndex).apply()
}
fun getBattleIndex() : Int {
return sp.getInt("battle" , -1)
}
fun setCannonFodderIndex(cannonFodderIndex : Int){
sp.edit().putInt("cannonFodder" , cannonFodderIndex).apply()
}
fun getCannonFodderIndex() : Int {
return sp.getInt("cannonFodder" , -1)
}
}
override fun onCreate() {
super.onCreate()
sp = getSharedPreferences("config" , Context.MODE_PRIVATE)
if (getMainForceIndex() == -1){
setMainForceIndex(0)
}
if (getBattleIndex() == -1){
setBattleIndex(0)
}
if (getCannonFodderIndex() == -1){
setCannonFodderIndex(3)
}
}
}
| apache-2.0 | 2d30621e1ca6d32fa15850247edd0f10 | 27.956522 | 72 | 0.570571 | 3.849711 | false | false | false | false |
arturbosch/TiNBo | tinbo-projects/src/main/kotlin/io/gitlab/arturbosch/tinbo/psp/PSPCommands.kt | 1 | 4091 | package io.gitlab.arturbosch.tinbo.psp
import io.gitlab.arturbosch.tinbo.api.TinboTerminal
import io.gitlab.arturbosch.tinbo.api.config.ModeManager
import io.gitlab.arturbosch.tinbo.api.marker.Addable
import io.gitlab.arturbosch.tinbo.api.marker.Command
import io.gitlab.arturbosch.tinbo.api.marker.Listable
import io.gitlab.arturbosch.tinbo.api.model.Project
import io.gitlab.arturbosch.tinbo.api.utils.dateFormatter
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.shell.core.annotation.CliAvailabilityIndicator
import org.springframework.shell.core.annotation.CliCommand
import org.springframework.shell.core.annotation.CliOption
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.time.format.DateTimeParseException
/**
* @author Artur Bosch
*/
@Component
class PSPCommands @Autowired constructor(private val console: TinboTerminal,
private val currentProject: CurrentProject,
private val csvProjects: CSVProjects) : Command, Listable, Addable {
override val id: String = "projects"
override fun list(categoryName: String, all: Boolean): String {
return if (categoryName.isNotEmpty()) showProject(categoryName) else csvProjects.convert()
}
override fun add(): String {
return newProject(console.readLine("Enter project name: "))
}
@CliAvailabilityIndicator("showAll", "show-project", "new-project", "open-project", "close-project")
fun available() = ModeManager.isCurrentMode(PSPMode) || ModeManager.isCurrentMode(ProjectsMode)
@CliCommand("show-project", help = "Summarizes the specified project.")
fun showProject(@CliOption(key = [""], help = "Name the project must start with.") name: String?): String {
return name?.let { currentProject.showProject(it) } ?: "Specify a project by its name!"
}
@CliCommand("new-project", help = "Creates a new project.")
fun newProject(@CliOption(key = [""], help = "Name the project must start with.") name: String?): String {
val wrong = "Enter a valid and non existing name..."
return name?.let {
if (currentProject.projectWithNameExists(name)) return wrong
return try {
val description = console.readLine("Enter project description: ")
val start = console.readLine("Enter start date of project (empty if today): ")
val end = console.readLine("Enter end date of project(empty if not yet known): ")
val startDate = if (start.isEmpty()) LocalDate.now() else LocalDate.parse(start, dateFormatter)
val endDate = if (end.isEmpty()) null else LocalDate.parse(end, dateFormatter)
currentProject.persistProject(Project(name, description, startDate, endDate))
"Successfully added project $name"
} catch (e: Exception) {
e.message ?: throw e
}
} ?: wrong
}
@CliCommand("open-project", help = "Opens project with given name.")
fun openProject(@CliOption(key = [""], help = "Name the project must start with.") name: String?): String {
val wrong = "No such project, enter an existing name..."
return name?.let {
if (!currentProject.projectWithNameExists(name)) return wrong
val realName = currentProject.enter(name)
ModeManager.current = PSPMode
console.changePrompt(realName)
return "Opening project $realName..."
} ?: wrong
}
@CliCommand("close-project", help = "Sets the end date of a project.")
fun closeProject(@CliOption(key = [""]) name: String?,
@CliOption(key = ["end"]) end: String?): String {
try {
if (name.isNullOrEmpty() && currentProject.isSpecified()) {
val date = end?.let { LocalDate.parse(end, dateFormatter) } ?: LocalDate.now()
currentProject.closeProject(currentProject.name(), date)
return "Finished ${currentProject.name()}"
}
if (name.isNullOrEmpty()) return "Specify project name or open a project."
val date = end?.let { LocalDate.parse(end, dateFormatter) } ?: LocalDate.now()
currentProject.closeProject(name!!, date)
ModeManager.current = ProjectsMode
return "Closed $name project"
} catch (e: DateTimeParseException) {
return "Could not parse given date string!"
}
}
}
| apache-2.0 | 61aed1410bb47873c781d08c39d35337 | 40.323232 | 108 | 0.733806 | 3.952657 | false | false | false | false |
kiruto/kotlin-android-mahjong | mahjanmodule/src/main/kotlin/dev/yuriel/kotmahjan/rules/yaku/yakuimpl/10_自風牌.kt | 1 | 1684 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* 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 dev.yuriel.kotmahjan.rules.yaku.yakuimpl
import dev.yuriel.kotmahjan.models.PlayerContext
import dev.yuriel.kotmahjan.models.RoundContext
import dev.yuriel.kotmahjan.rules.MentsuSupport
/**
* Created by yuriel on 7/24/16.
*/
fun 自風牌Impl(r: RoundContext?, p: PlayerContext?, s: MentsuSupport): Boolean {
if (r == null || p == null) {
return false
}
for (kotsu in s.kotsuKantsu) {
if (kotsu.getHai() == p.getJikaze()) {
return true
}
}
return false
} | mit | 6053a6c7558a9b54c33cbc462f1bc8fe | 37.159091 | 81 | 0.725864 | 4.023981 | false | false | false | false |
RocketChat/Rocket.Chat.Android.Lily | app/src/play/java/chat/rocket/android/infrastructure/CrashlyticsWrapper.kt | 2 | 2780 | package chat.rocket.android.infrastructure
import android.app.Application
import chat.rocket.android.BuildConfig
import chat.rocket.android.server.domain.AccountsRepository
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.SITE_URL
import com.crashlytics.android.Crashlytics
import kotlinx.coroutines.runBlocking
fun installCrashlyticsWrapper(
context: Application,
currentServerInteractor: GetCurrentServerInteractor,
settingsInteractor: GetSettingsInteractor,
accountRepository: AccountsRepository,
localRepository: LocalRepository
) {
if (isCrashlyticsEnabled()) {
Thread.setDefaultUncaughtExceptionHandler(
RocketChatUncaughtExceptionHandler(
currentServerInteractor,
settingsInteractor, accountRepository, localRepository
)
)
}
}
private fun isCrashlyticsEnabled(): Boolean {
return !BuildConfig.DEBUG
}
private class RocketChatUncaughtExceptionHandler(
val currentServerInteractor: GetCurrentServerInteractor,
val settingsInteractor: GetSettingsInteractor,
val accountRepository: AccountsRepository,
val localRepository: LocalRepository
) : Thread.UncaughtExceptionHandler {
val crashlyticsHandler: Thread.UncaughtExceptionHandler? =
Thread.getDefaultUncaughtExceptionHandler()
override fun uncaughtException(t: Thread, e: Throwable) {
val currentServer = currentServerInteractor.get() ?: "<unknown>"
Crashlytics.setString(KEY_CURRENT_SERVER, currentServer)
runBlocking {
val accounts = accountRepository.load()
Crashlytics.setString(KEY_ACCOUNTS, accounts.toString())
}
val settings = settingsInteractor.get(currentServer)
Crashlytics.setInt(KEY_SETTINGS_SIZE, settings.size)
val baseUrl = settings[SITE_URL]?.toString()
Crashlytics.setString(KEY_SETTINGS_BASE_URL, baseUrl)
val user = localRepository.getCurrentUser(currentServer)
Crashlytics.setString(KEY_CURRENT_USER, user?.toString())
Crashlytics.setString(KEY_CURRENT_USERNAME, localRepository.username())
if (crashlyticsHandler != null) {
crashlyticsHandler.uncaughtException(t, e)
} else {
throw RuntimeException("Missing default exception handler")
}
}
}
private const val KEY_CURRENT_SERVER = "CURRENT_SERVER"
private const val KEY_CURRENT_USER = "CURRENT_USER"
private const val KEY_CURRENT_USERNAME = "CURRENT_USERNAME"
private const val KEY_ACCOUNTS = "ACCOUNTS"
private const val KEY_SETTINGS_SIZE = "SETTINGS_SIZE"
private const val KEY_SETTINGS_BASE_URL = "SETTINGS_BASE_URL" | mit | 93f0bc4f98c337486759ffded167fff6 | 37.09589 | 79 | 0.744604 | 5.072993 | false | false | false | false |
a11n/kotlin-game-of-life | src/main/kotlin/Universe.kt | 1 | 1110 | class Universe(val size: Int) {
val cells = Array(size * size, { Cell() })
init {
cells.forEachIndexed { i, cell -> cell.setupNeighbors(i) }
}
fun evolve() {
val livingNeighborCounts = cells.map { it.neighbors.count { it.isAlive } }
cells.forEachIndexed { i, cell -> cell.evolve(livingNeighborCounts[i]) }
}
private fun Cell.setupNeighbors(index: Int) {
neighbors.apply {
neighborCoordinatesOf(index.toX(), index.toY())
.filter { it.isInBounds() }.map { it.toIndex() }
.forEach { add(cells[it]) }
}
}
private fun neighborCoordinatesOf(x: Int, y: Int)
= arrayOf(Pair(x - 1, y - 1), Pair(x, y - 1), Pair(x + 1, y - 1), Pair(x - 1, y),
Pair(x + 1, y), Pair(x - 1, y + 1), Pair(x, y + 1), Pair(x + 1, y + 1))
private fun Pair<Int, Int>.isInBounds() = !((first < 0).or(first >= size).or(second < 0).or(second >= size))
fun Pair<Int, Int>.toIndex() = second * size + first
private fun Int.toX() = this % size
private fun Int.toY() = this / size
}
| mit | ed1b9623aad55d8a3382a67511f51603 | 37.275862 | 112 | 0.545946 | 3.353474 | false | false | false | false |
ARostovsky/teamcity-rest-client | teamcity-rest-client-impl/src/main/kotlin/org/jetbrains/teamcity/rest/rest.kt | 1 | 17288 | @file:Suppress("RemoveRedundantBackticks")
package org.jetbrains.teamcity.rest
import retrofit.client.Response
import retrofit.http.*
import retrofit.mime.TypedString
import kotlin.collections.ArrayList
internal interface TeamCityService {
@Streaming
@Headers("Accept: application/json")
@GET("/{path}")
fun root(@Path("path", encode = false) path: String): Response
@Headers("Accept: application/json")
@GET("/app/rest/builds")
fun builds(@Query("locator") buildLocator: String): BuildListBean
@Headers("Accept: application/json")
@GET("/app/rest/buildQueue")
fun queuedBuilds(@Query("locator") locator: String?): BuildListBean
@Headers("Accept: application/json")
@GET("/app/rest/builds/id:{id}")
fun build(@Path("id") id: String): BuildBean
@Headers("Accept: application/json")
@GET("/app/rest/investigations")
fun investigations(@Query("locator") investigationLocator: String?): InvestigationListBean
@Headers("Accept: application/json")
@GET("/app/rest/investigations/id:{id}")
fun investigation(@Path("id") id: String): InvestigationBean
@Headers("Accept: application/json")
@GET("/app/rest/changes")
fun changes(@Query("locator") locator: String, @Query("fields") fields: String): ChangesBean
@Headers("Accept: application/json")
@GET("/app/rest/testOccurrences/")
fun testOccurrences(@Query("locator") locator: String, @Query("fields") fields: String?): TestOccurrencesBean
@Headers("Accept: application/json")
@GET("/app/rest/vcs-roots")
fun vcsRoots(@Query("locator") locator: String? = null): VcsRootListBean
@Headers("Accept: application/json")
@GET("/app/rest/vcs-roots/id:{id}")
fun vcsRoot(@Path("id") id: String): VcsRootBean
@POST("/app/rest/builds/id:{id}/tags/")
fun addTag(@Path("id") buildId: String, @Body tag: TypedString): Response
@PUT("/app/rest/builds/id:{id}/tags/")
fun replaceTags(@Path("id") buildId: String, @Body tags: TagsBean): Response
@PUT("/app/rest/builds/id:{id}/pin/")
fun pin(@Path("id") buildId: String, @Body comment: TypedString): Response
//The standard DELETE annotation doesn't allow to include a body, so we need to use our own.
//Probably it would be better to change Rest API here (https://youtrack.jetbrains.com/issue/TW-49178).
@DELETE_WITH_BODY("/app/rest/builds/id:{id}/pin/")
fun unpin(@Path("id") buildId: String, @Body comment: TypedString): Response
@Streaming
@GET("/app/rest/builds/id:{id}/artifacts/content/{path}")
fun artifactContent(@Path("id") buildId: String, @Path("path", encode = false) artifactPath: String): Response
@Headers("Accept: application/json")
@GET("/app/rest/builds/id:{id}/artifacts/children/{path}")
fun artifactChildren(@Path("id") buildId: String,
@Path("path", encode = false) artifactPath: String,
@Query("locator") locator: String,
@Query("fields") fields: String): ArtifactFileListBean
@Headers("Accept: application/json")
@GET("/app/rest/builds/id:{id}/resulting-properties")
fun resultingProperties(@Path("id") buildId: String): ParametersBean
@Headers("Accept: application/json")
@GET("/app/rest/projects/id:{id}")
fun project(@Path("id") id: String): ProjectBean
@Headers("Accept: application/json")
@GET("/app/rest/buildTypes/id:{id}")
fun buildConfiguration(@Path("id") buildTypeId: String): BuildTypeBean
@Headers("Accept: application/json")
@GET("/app/rest/buildTypes/id:{id}/buildTags")
fun buildTypeTags(@Path("id") buildTypeId: String): TagsBean
@Headers("Accept: application/json")
@GET("/app/rest/buildTypes/id:{id}/triggers")
fun buildTypeTriggers(@Path("id") buildTypeId: String): TriggersBean
@Headers("Accept: application/json")
@GET("/app/rest/buildTypes/id:{id}/artifact-dependencies")
fun buildTypeArtifactDependencies(@Path("id") buildTypeId: String): ArtifactDependenciesBean
@PUT("/app/rest/projects/id:{id}/parameters/{name}")
fun setProjectParameter(@Path("id") projectId: String, @Path("name") name: String, @Body value: TypedString): Response
@PUT("/app/rest/buildTypes/id:{id}/parameters/{name}")
fun setBuildTypeParameter(@Path("id") buildTypeId: String, @Path("name") name: String, @Body value: TypedString): Response
@PUT("/app/rest/buildTypes/id:{id}/settings/{name}")
fun setBuildTypeSettings(@Path("id") buildTypeId: String, @Path("name") name: String, @Body value: TypedString): Response
@Headers("Accept: application/json")
@POST("/app/rest/buildQueue")
fun triggerBuild(@Body value: TriggerBuildRequestBean): TriggeredBuildBean
@Headers("Accept: application/json")
@POST("/app/rest/builds/id:{id}")
fun cancelBuild(@Path("id") buildId: String, @Body value: BuildCancelRequestBean): Response
@Headers("Accept: application/json")
@POST("/app/rest/buildQueue/id:{id}")
fun removeQueuedBuild(@Path("id") buildId: String, @Body value: BuildCancelRequestBean): Response
@Headers("Accept: application/json")
@GET("/app/rest/users")
fun users(): UserListBean
@Headers("Accept: application/json")
@GET("/app/rest/users/{userLocator}")
fun users(@Path("userLocator") userLocator: String): UserBean
@Headers("Accept: application/json")
@GET("/app/rest/agents")
fun agents(): BuildAgentsBean
@Headers("Accept: application/json")
@GET("/app/rest/agentPools")
fun agentPools(): BuildAgentPoolsBean
@Headers("Accept: application/json")
@GET("/app/rest/agents/{locator}")
fun agents(@Path("locator") agentLocator: String? = null): BuildAgentBean
@Headers("Accept: application/json")
@GET("/app/rest/agentPools/{locator}")
fun agentPools(@Path("locator") agentLocator: String? = null): BuildAgentPoolBean
@Headers("Accept: application/json")
@GET("/app/rest/problemOccurrences")
fun problemOccurrences(@Query("locator") locator: String, @Query("fields") fields: String): BuildProblemOccurrencesBean
@POST("/app/rest/projects")
@Headers("Accept: application/json", "Content-Type: application/xml")
fun createProject(@Body projectDescriptionXml: TypedString): ProjectBean
@POST("/app/rest/vcs-roots")
@Headers("Accept: application/json", "Content-Type: application/xml")
fun createVcsRoot(@Body vcsRootXml: TypedString): VcsRootBean
@POST("/app/rest/buildTypes")
@Headers("Accept: application/json", "Content-Type: application/xml")
fun createBuildType(@Body buildTypeXml: TypedString): BuildTypeBean
@Streaming
@GET("/downloadBuildLog.html")
fun buildLog(@Query ("buildId") id: String): Response
@Headers("Accept: application/json")
@GET("/app/rest/changes/buildType:{id},version:{version}")
fun change(@Path("id") buildType: String, @Path("version") version: String): ChangeBean
@Headers("Accept: application/json")
@GET("/app/rest/changes/id:{id}")
fun change(@Path("id") changeId: String): ChangeBean
@Headers("Accept: application/json")
@GET("/app/rest/changes/{id}/firstBuilds")
fun changeFirstBuilds(@Path("id") id: String): BuildListBean
}
internal class ProjectsBean {
var project: List<ProjectBean> = ArrayList()
}
internal class BuildAgentsBean {
var agent: List<BuildAgentBean> = ArrayList()
}
internal class BuildAgentPoolsBean {
var agentPool: List<BuildAgentPoolBean> = ArrayList()
}
internal class ArtifactFileListBean {
var file: List<ArtifactFileBean> = ArrayList()
}
internal class ArtifactFileBean {
var name: String? = null
var fullName: String? = null
var size: Long? = null
var modificationTime: String? = null
companion object {
val FIELDS = "${ArtifactFileBean::fullName.name},${ArtifactFileBean::name.name},${ArtifactFileBean::size.name},${ArtifactFileBean::modificationTime.name}"
}
}
internal open class IdBean {
var id: String? = null
}
internal class VcsRootListBean {
var nextHref: String? = null
var `vcs-root`: List<VcsRootBean> = ArrayList()
}
internal open class VcsRootBean: IdBean() {
var name: String? = null
var properties: NameValuePropertiesBean? = null
}
internal open class VcsRootInstanceBean {
var `vcs-root-id`: String? = null
var name: String? = null
}
internal class BuildListBean {
var nextHref: String? = null
var build: List<BuildBean> = ArrayList()
}
internal class UserListBean {
var user: List<UserBean> = ArrayList()
}
internal open class BuildBean: IdBean() {
var buildTypeId: String? = null
var canceledInfo: BuildCanceledBean? = null
var number: String? = null
var status: BuildStatus? = null
var state: String? = null
var personal: Boolean? = null
var branchName: String? = null
var defaultBranch: Boolean? = null
var composite: Boolean? = null
var statusText: String? = null
var queuedDate: String? = null
var startDate: String? = null
var finishDate: String? = null
var tags: TagsBean? = null
var `running-info`: BuildRunningInfoBean? = null
var revisions: RevisionsBean? = null
var pinInfo: PinInfoBean? = null
var triggered: TriggeredBean? = null
var comment: BuildCommentBean? = null
var agent: BuildAgentBean? = null
var properties: ParametersBean? = ParametersBean()
var buildType: BuildTypeBean? = BuildTypeBean()
var `snapshot-dependencies`: BuildListBean? = null
}
internal class BuildRunningInfoBean {
val percentageComplete: Int = 0
val elapsedSeconds: Long = 0
val estimatedTotalSeconds: Long = 0
val outdated: Boolean = false
val probablyHanging: Boolean = false
}
internal class BuildTypeBean: IdBean() {
var name: String? = null
var projectId: String? = null
var paused: Boolean? = null
var settings: BuildTypeSettingsBean? = null
}
internal class BuildTypeSettingsBean {
var property: List<NameValuePropertyBean> = ArrayList()
}
internal class BuildProblemBean {
var id: String? = null
var type: String? = null
var identity: String? = null
}
internal class BuildProblemOccurrencesBean {
var nextHref: String? = null
var problemOccurrence: List<BuildProblemOccurrenceBean> = ArrayList()
}
internal class BuildProblemOccurrenceBean {
var details: String? = null
var additionalData: String? = null
var problem: BuildProblemBean? = null
var build: BuildBean? = null
}
internal class BuildTypesBean {
var buildType: List<BuildTypeBean> = ArrayList()
}
internal class TagBean {
var name: String? = null
}
internal class TagsBean {
var tag: List<TagBean>? = ArrayList()
}
internal open class TriggerBuildRequestBean {
var branchName: String? = null
var personal: Boolean? = null
var triggeringOptions: TriggeringOptionsBean? = null
var properties: ParametersBean? = null
var buildType: BuildTypeBean? = null
var comment: CommentBean? = null
// TODO: lastChanges
// <lastChanges>
// <change id="modificationId"/>
// </lastChanges>
}
internal class TriggeringOptionsBean {
var cleanSources: Boolean? = null
var rebuildAllDependencies: Boolean? = null
var queueAtTop: Boolean? = null
}
internal class CommentBean {
var text: String? = null
}
internal class TriggerBean {
var id: String? = null
var type: String? = null
var properties: ParametersBean? = ParametersBean()
}
internal class TriggersBean {
var trigger: List<TriggerBean>? = ArrayList()
}
internal class ArtifactDependencyBean: IdBean() {
var type: String? = null
var disabled: Boolean? = false
var inherited: Boolean? = false
var properties: ParametersBean? = ParametersBean()
var `source-buildType`: BuildTypeBean = BuildTypeBean()
}
internal class ArtifactDependenciesBean {
var `artifact-dependency`: List<ArtifactDependencyBean>? = ArrayList()
}
internal class ProjectBean: IdBean() {
var name: String? = null
var parentProjectId: String? = null
var archived: Boolean? = null
var projects: ProjectsBean? = ProjectsBean()
var parameters: ParametersBean? = ParametersBean()
var buildTypes: BuildTypesBean? = BuildTypesBean()
}
internal class BuildAgentBean: IdBean() {
var name: String? = null
var connected: Boolean? = null
var enabled: Boolean? = null
var authorized: Boolean? = null
var uptodate: Boolean? = null
var ip: String? = null
var enabledInfo: EnabledInfoBean? = null
var authorizedInfo: AuthorizedInfoBean? = null
var properties: ParametersBean? = null
var pool: BuildAgentPoolBean? = null
var build: BuildBean? = null
}
internal class BuildAgentPoolBean: IdBean() {
var name: String? = null
var projects: ProjectsBean? = ProjectsBean()
var agents: BuildAgentsBean? = BuildAgentsBean()
}
internal class ChangesBean {
var change: List<ChangeBean>? = ArrayList()
}
internal class ChangeBean: IdBean() {
var version: String? = null
var user: UserBean? = null
var date: String? = null
var comment: String? = null
var username: String? = null
}
internal class UserBean: IdBean() {
var username: String? = null
var name: String? = null
var email: String? = null
}
internal class ParametersBean() {
var property: List<ParameterBean>? = ArrayList()
constructor(properties: List<ParameterBean>) : this() {
property = properties
}
}
internal class ParameterBean() {
var name: String? = null
var value: String? = null
var own: Boolean? = null
constructor(name: String, value: String) : this() {
this.name = name
this.value = value
}
}
internal class PinInfoBean {
var user: UserBean? = null
var timestamp: String? = null
}
internal class TriggeredBean {
var user: UserBean? = null
val build: BuildBean? = null
}
internal class BuildCommentBean {
var user: UserBean? = null
var timestamp: String? = null
var text: String? = null
}
internal class EnabledInfoCommentBean {
var user: UserBean? = null
var timestamp: String? = null
var text: String? = null
}
internal class EnabledInfoBean {
var comment: EnabledInfoCommentBean? = null
}
internal class AuthorizedInfoCommentBean {
var user: UserBean? = null
var timestamp: String? = null
var text: String? = null
}
internal class AuthorizedInfoBean {
var comment: AuthorizedInfoCommentBean? = null
}
internal class BuildCanceledBean {
var user: UserBean? = null
val timestamp: String? = null
}
internal class TriggeredBuildBean {
val id: Int? = null
val buildTypeId: String? = null
}
internal class RevisionsBean {
var revision: List<RevisionBean>? = ArrayList()
}
internal class RevisionBean {
var version: String? = null
var vcsBranchName: String? = null
var `vcs-root-instance`: VcsRootInstanceBean? = null
}
internal class NameValuePropertiesBean {
var property: List<NameValuePropertyBean>? = ArrayList()
}
internal class NameValuePropertyBean {
var name: String? = null
var value: String? = null
}
internal class BuildCancelRequestBean {
var comment: String = ""
var readdIntoQueue = false
}
internal open class TestOccurrencesBean {
var nextHref: String? = null
var testOccurrence: List<TestOccurrenceBean> = ArrayList()
}
internal open class TestBean {
var id: String? = null
}
internal open class TestOccurrenceBean {
var name: String? = null
var status: String? = null
var ignored: Boolean? = null
var duration: Long? = null
var ignoreDetails: String? = null
var details: String? = null
val currentlyMuted: Boolean? = null
val muted: Boolean? = null
val newFailure: Boolean? = null
var build: BuildBean? = null
var test: TestBean? = null
companion object {
val filter = "testOccurrence(name,status,ignored,muted,currentlyMuted,newFailure,duration,ignoreDetails,details,build(id),test(id))"
}
}
internal class InvestigationListBean {
var investigation: List<InvestigationBean> = ArrayList()
}
internal class InvestigationBean: IdBean() {
val state: InvestigationState? = null
val assignee: UserBean? = null
val assignment: AssignmentBean? = null
val resolution: InvestigationResolutionBean? = null
val scope: InvestigationScopeBean? = null
val target: InvestigationTargetBean? = null
}
class InvestigationResolutionBean {
val type: String? = null
}
internal class AssignmentBean {
val user: UserBean? = null
val text: String? = null
val timestamp: String? = null
}
internal open class InvestigationTargetBean {
val tests : TestUnderInvestigationListBean? = null
val problems: ProblemUnderInvestigationListBean? = null
val anyProblem: Boolean? = null
}
internal class TestUnderInvestigationListBean {
val count : Int? = null
var test : List<TestBean> = ArrayList()
}
internal class ProblemUnderInvestigationListBean {
val count : Int? = null
var problem : List<BuildProblemBean> = ArrayList()
}
internal class InvestigationScopeBean {
val buildTypes : BuildTypesBean? = null
val project : ProjectBean? = null
} | apache-2.0 | 8a7135fd93898fba6377497b2766e6b4 | 29.067826 | 162 | 0.692214 | 3.960596 | false | false | false | false |
Mashape/httpsnippet | test/fixtures/output/kotlin/okhttp/cookies.kt | 1 | 212 | val client = OkHttpClient()
val request = Request.Builder()
.url("http://mockbin.com/har")
.post(null)
.addHeader("cookie", "foo=bar; bar=baz")
.build()
val response = client.newCall(request).execute()
| mit | 571d94283f5900feda925f5442dfc51f | 22.555556 | 48 | 0.674528 | 3.212121 | false | false | false | false |
tgirard12/sqlitektgen | sqlitektgen-sample/src/main/kotlin/com/tgirard12/sqlitektgen/sample/UserDb.kt | 1 | 1696 |
package com.tgirard12.sqlitektgen.sample
import android.content.ContentValues
import android.database.Cursor
data class UserDb (
val _id: Long = -1,
val name: String,
val email: String? = "",
val createdAt: Long,
val groupId: Long? = null,
val group: GroupDb? = null) {
constructor (cursor: Cursor) : this(
_id = cursor.getLong(cursor.getColumnIndex(_ID)),
name = cursor.getString(cursor.getColumnIndex(NAME)),
email = cursor.getString(cursor.getColumnIndex(EMAIL)),
createdAt = cursor.getLong(cursor.getColumnIndex(CREATEDAT)),
groupId = cursor.getLong(cursor.getColumnIndex(GROUPID)))
companion object {
const val TABLE_NAME = "UserDb"
const val _ID = "_id"
const val NAME = "name"
const val EMAIL = "email"
const val CREATEDAT = "createdAt"
const val GROUPID = "groupId"
const val CREATE_TABLE = """CREATE TABLE UserDb (
_id INTEGER NOT NULL NOT NULL PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL ,
email TEXT ,
createdAt INTEGER NOT NULL ,
groupId INTEGER
)"""
const val SELECT_ALL_ORDER_BY_NAME = "select * from UserDb left join GroupDb on UserDb.groupId = GroupDb.groupId order by UserDb.name"
}
val contentValue: ContentValues
get() {
val cv = ContentValues()
cv.put(NAME, name)
if (email == null) cv.putNull(EMAIL) else cv.put(EMAIL, email)
cv.put(CREATEDAT, createdAt)
if (groupId == null) cv.putNull(GROUPID) else cv.put(GROUPID, groupId)
return cv
}
}
| apache-2.0 | 6b3a39f7f0244ab83d61cea5d8c3b801 | 32.92 | 142 | 0.601415 | 4.229426 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/managers/DayNightAlarmLiveData.kt | 1 | 5723 | /*
* Copyright (c) 2018 ThanksMister LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thanksmister.iot.mqtt.alarmpanel.managers
import android.app.AlarmManager
import android.app.PendingIntent
import android.arch.lifecycle.MutableLiveData
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Handler
import android.os.Looper
import com.thanksmister.iot.mqtt.alarmpanel.ui.Configuration
import com.thanksmister.iot.mqtt.alarmpanel.utils.DateUtils
import timber.log.Timber
import java.util.*
class DayNightAlarmLiveData(private val context: Context, private val configuration: Configuration) : MutableLiveData<String>() {
//private var pendingIntent: PendingIntent? = null
//private val intentFilter = IntentFilter(ALARM_ACTION)
//private val alarmManager: AlarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
private var timeHandler: Handler? = null
private val timeRunnable = object : Runnable {
override fun run() {
setNightDayMode()
if (timeHandler != null) {
timeHandler!!.postDelayed(this, INTERVAL_FIFTEEN_MINUTES)
}
}
}
init {
}
override fun onActive() {
super.onActive()
//context.registerReceiver(alarmReceiver, IntentFilter(intentFilter))
startDayNightMode()
}
override fun onInactive() {
super.onInactive()
//context.unregisterReceiver(alarmReceiver)
cancelDayNightMode()
}
private fun cancelDayNightMode() {
Timber.d("cancelDayNightMode")
if (timeHandler != null) {
timeHandler!!.removeCallbacks(timeRunnable)
timeHandler = null
}
/*if(pendingIntent != null) {
Timber.d("cancelDayNightMode")
pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, Intent(ALARM_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager.cancel(pendingIntent)
pendingIntent?.cancel()
pendingIntent = null
}*/
}
private fun startDayNightMode() {
Timber.d("startDayNightMode")
if(timeHandler == null && configuration.useNightDayMode) {
val firstTime = (5 * 1000).toLong();
timeHandler = Handler(Looper.getMainLooper())
timeHandler!!.postDelayed(timeRunnable, firstTime)
}
/*if(pendingIntent == null && configuration.useNightDayMode) {
configuration.dayNightMode = Configuration.DISPLAY_MODE_DAY
pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, Intent(ALARM_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);
val firstTime = SystemClock.elapsedRealtime() + 30 * 1000;
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, INTERVAL_FIFTEEN_MINUTES, pendingIntent)
}*/
}
private fun getPendingIntent(): PendingIntent {
val pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, Intent(ALARM_ACTION), PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent
}
private val alarmReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Timber.d("alarmReceiver")
setNightDayMode()
}
}
private fun setNightDayMode() {
val nowTime = "${Calendar.getInstance().get(Calendar.HOUR_OF_DAY)}.${Calendar.getInstance().get(Calendar.MINUTE)}".toFloat()
val startTime = DateUtils.getHourAndMinutesFromTimePicker(configuration.dayNightModeStartTime)
val endTime = DateUtils.getHourAndMinutesFromTimePicker(configuration.dayNightModeEndTime)
if(startTime == endTime) {
Timber.d("Tis forever night")
configuration.dayNightMode = Configuration.DISPLAY_MODE_NIGHT
value = Configuration.DISPLAY_MODE_NIGHT
} else if(endTime < startTime) {
if(nowTime >= startTime || nowTime <= endTime) {
Timber.d("Tis the night")
configuration.dayNightMode = Configuration.DISPLAY_MODE_NIGHT
value = Configuration.DISPLAY_MODE_NIGHT
} else {
Timber.d("Tis the day")
configuration.dayNightMode = Configuration.DISPLAY_MODE_DAY
value = Configuration.DISPLAY_MODE_DAY
}
} else if (endTime > startTime) {
if(nowTime >= startTime && nowTime <= endTime) {
Timber.d("Tis the night")
configuration.dayNightMode = Configuration.DISPLAY_MODE_NIGHT
value = Configuration.DISPLAY_MODE_NIGHT
} else {
Timber.d("Tis the day")
configuration.dayNightMode = Configuration.DISPLAY_MODE_DAY
value = Configuration.DISPLAY_MODE_DAY
}
}
}
companion object {
const val INTERVAL_FIFTEEN_MINUTES = (15 * 60 * 1000).toLong()
const val ALARM_ACTION = "com.thanksmister.iot.mqtt.alarmpanel.DayNightAlarmReceiver"
const val REQUEST_CODE = 888
}
}
| apache-2.0 | 0207f2754c3493036909cc5c11032d61 | 39.020979 | 135 | 0.665036 | 4.741508 | false | true | false | false |
scenerygraphics/SciView | src/main/kotlin/sc/iview/commands/demo/animation/VolumeTimeseriesDemo.kt | 1 | 5861 | /*-
* #%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.demo.animation
import bdv.util.BdvFunctions
import graphics.scenery.numerics.OpenSimplexNoise
import graphics.scenery.volumes.Volume
import net.imglib2.FinalInterval
import net.imglib2.Localizable
import net.imglib2.RandomAccessibleInterval
import net.imglib2.img.Img
import net.imglib2.img.array.ArrayImgs
import net.imglib2.position.FunctionRandomAccessible
import net.imglib2.type.numeric.integer.UnsignedByteType
import net.imglib2.view.Views
import org.scijava.command.Command
import org.scijava.command.CommandService
import org.scijava.plugin.Menu
import org.scijava.plugin.Parameter
import org.scijava.plugin.Plugin
import sc.iview.SciView
import sc.iview.commands.MenuWeights
import java.util.*
import java.util.function.BiConsumer
import kotlin.math.abs
import kotlin.math.sqrt
/**
* A demo of volume rendering + time
*
* @author Kyle Harrington
*/
@Plugin(type = Command::class,
label = "Volume Timeseries",
menuRoot = "SciView",
menu = [Menu(label = "Demo", weight = MenuWeights.DEMO),
Menu(label = "Animation", weight = MenuWeights.DEMO_ANIMATION),
Menu(label = "Volume Timeseries", weight = MenuWeights.DEMO_ANIMATION_VOLUMETIMESERIES)])
class VolumeTimeseriesDemo : Command {
@Parameter
private lateinit var sciView: SciView
override fun run() {
val dataset = makeDataset()
val bdv = BdvFunctions.show(dataset, "test")
sciView.addVolume(dataset, floatArrayOf(1f, 1f, 1f, 1f)) {
pixelToWorldRatio = 10f
name = "Volume Render Demo"
this.geometryOrNull()?.dirty = true
this.spatialOrNull()?.needsUpdate = true
bdv.bdvHandle.viewerPanel.addTimePointListener { t ->
goToTimepoint(t.coerceIn(0, timepointCount-1))
}
sciView.setActiveNode(this)
}
sciView.centerOnNode(sciView.activeNode)
}
fun makeDataset(): RandomAccessibleInterval<UnsignedByteType> {
// Interval is 30x30x30 w/ 100 timepoints
val interval = FinalInterval(longArrayOf(0, 0, 0, 0), longArrayOf(30, 30, 30, 100))
val center = (interval.max(2) / 2).toDouble()
val noise = OpenSimplexNoise()
val rng = Random(System.nanoTime())
val dx: Float
val dy: Float
val dz: Float
dx = rng.nextFloat()
dy = rng.nextFloat()
dz = rng.nextFloat()
val f = 3.0 / interval.max(2).toDouble()
val dt = 0.618
val radius = 0.35
val pixelmapper = BiConsumer<Localizable, UnsignedByteType> { localizable, value ->
val x = center - localizable.getDoublePosition(0)
val y = center - localizable.getDoublePosition(1)
val z = center - localizable.getDoublePosition(2)
val t = localizable.getDoublePosition(3)
val d = sqrt(x * x + y * y + z * z) / interval.max(2).toDouble()
val offset = abs(
noise.random3D(
(x + t * dt * dx) * f,
(y + t * dt * dy) * f,
(z + t * dt * dz) * f))
val v: Double
v = if (d - offset < radius) d - offset else 0.0
value.set((255.0 * v).toInt())
}
val fra = FunctionRandomAccessible(
4, pixelmapper, { UnsignedByteType() })
return hardCopy(Views.interval(fra, interval))
}
fun hardCopy(img: RandomAccessibleInterval<UnsignedByteType>): Img<UnsignedByteType> {
val out: Img<UnsignedByteType> = ArrayImgs.unsignedBytes(
img.dimension(0),
img.dimension(1),
img.dimension(2),
img.dimension(3))
val imgAccess = img.randomAccess()
val outCur = out.localizingCursor()
while (outCur.hasNext()) {
outCur.fwd()
imgAccess.setPosition(outCur)
outCur.get().set(imgAccess.get())
}
return out
}
companion object {
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
val sv = SciView.create()
val command = sv.scijavaContext!!.getService(CommandService::class.java)
val argmap = HashMap<String, Any>()
command.run(VolumeTimeseriesDemo::class.java, true, argmap)
}
}
}
| bsd-2-clause | 258bbce145ea242d89fbebf7567de561 | 37.81457 | 105 | 0.649377 | 4.156738 | false | false | false | false |
kotlinx/kotlinx.html | src/commonMain/kotlin/api.kt | 1 | 3623 | package kotlinx.html
import org.w3c.dom.events.*
interface TagConsumer<out R> {
fun onTagStart(tag: Tag)
fun onTagAttributeChange(tag: Tag, attribute: String, value: String?)
fun onTagEvent(tag: Tag, event: String, value: (Event) -> Unit)
fun onTagEnd(tag: Tag)
fun onTagContent(content: CharSequence)
fun onTagContentEntity(entity: Entities)
fun onTagContentUnsafe(block: Unsafe.() -> Unit)
fun onTagComment(content: CharSequence)
fun onTagError(tag: Tag, exception: Throwable): Unit = throw exception
fun finalize(): R
}
@HtmlTagMarker
interface Tag {
val tagName: String
val consumer: TagConsumer<*>
val namespace: String?
val attributes: MutableMap<String, String>
val attributesEntries: Collection<Map.Entry<String, String>>
val inlineTag: Boolean
val emptyTag: Boolean
operator fun Entities.unaryPlus(): Unit {
entity(this)
}
operator fun String.unaryPlus(): Unit {
text(this)
}
fun text(s: String) {
consumer.onTagContent(s)
}
fun text(n: Number) {
text(n.toString())
}
fun entity(e: Entities) {
consumer.onTagContentEntity(e)
}
fun comment(s: String) {
consumer.onTagComment(s)
}
}
@HtmlTagMarker
interface Unsafe {
operator fun String.unaryPlus()
operator fun Entities.unaryPlus() = +text
fun raw(s: String) {
+s
}
fun raw(entity: Entities) {
+entity
}
fun raw(n: Number) {
+n.toString()
}
}
interface AttributeEnum {
val realValue: String
}
inline fun <T : Tag> T.visit(crossinline block: T.() -> Unit) = visitTag { block() }
inline fun <T : Tag, R> T.visitAndFinalize(consumer: TagConsumer<R>, crossinline block: T.() -> Unit): R
= visitTagAndFinalize(consumer) { block() }
fun attributesMapOf() = emptyMap
fun attributesMapOf(key: String, value: String?): Map<String, String> = when (value) {
null -> emptyMap
else -> singletonMapOf(key, value)
}
fun attributesMapOf(vararg pairs: String?): Map<String, String> {
var result: MutableMap<String, String>? = null
for (i in 0..pairs.size - 1 step 2) {
val k = pairs[i]
val v = pairs[i + 1]
if (k != null && v != null) {
if (result == null) {
result = linkedMapOf()
}
result.put(k, v)
}
}
return result ?: emptyMap
}
fun singletonMapOf(key: String, value: String): Map<String, String> = SingletonStringMap(key, value)
fun HTMLTag.unsafe(block: Unsafe.() -> Unit): Unit = consumer.onTagContentUnsafe(block)
val emptyMap: Map<String, String> = emptyMap()
class DefaultUnsafe : Unsafe {
private val sb = StringBuilder()
override fun String.unaryPlus() {
sb.append(this)
}
override fun toString(): String = sb.toString()
}
@DslMarker
annotation class HtmlTagMarker
typealias HtmlContent = FlowOrPhrasingContent
private data class SingletonStringMap(override val key: String, override val value: String) : Map<String, String>,
Map.Entry<String, String> {
override val entries: Set<Map.Entry<String, String>>
get() = setOf(this)
override val keys: Set<String>
get() = setOf(key)
override val size: Int
get() = 1
override val values: Collection<String>
get() = listOf(value)
override fun containsKey(key: String) = key == this.key
override fun containsValue(value: String) = value == this.value
override fun get(key: String): String? = if (key == this.key) value else null
override fun isEmpty() = false
}
| apache-2.0 | ea52f7b6f3851497b1d35f0d82161e18 | 24.159722 | 114 | 0.639525 | 3.866596 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/organizeImports/importsCollector.kt | 1 | 6022 | /*******************************************************************************
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.ui.editors.organizeImports
import org.jetbrains.kotlin.psi.KtVisitorVoid
import org.jetbrains.kotlin.psi.KtFile
import java.util.HashSet
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtImportList
import org.jetbrains.kotlin.psi.KtPackageDirective
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.resolve.scopes.utils.findFunction
import org.jetbrains.kotlin.resolve.scopes.utils.findVariable
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.ui.editors.codeassist.getResolutionScope
import org.jetbrains.kotlin.resolve.scopes.utils.replaceImportingScopes
import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.core.references.createReferences
import org.jetbrains.kotlin.eclipse.ui.utils.getBindingContext
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.core.references.canBeResolvedViaImport
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
fun collectDescriptorsToImport(file: KtFile): Set<DeclarationDescriptor> {
val visitor = CollectUsedDescriptorsVisitor(file)
file.accept(visitor)
return visitor.descriptors
}
private class CollectUsedDescriptorsVisitor(val file: KtFile) : KtVisitorVoid() {
private val _descriptors = HashSet<DeclarationDescriptor>()
private val currentPackageName = file.packageFqName
private val bindingContext = getBindingContext(file)!!
val descriptors: Set<DeclarationDescriptor>
get() = _descriptors
override fun visitElement(element: PsiElement) {
element.acceptChildren(this)
}
override fun visitImportList(importList: KtImportList) {
}
override fun visitPackageDirective(directive: KtPackageDirective) {
}
override fun visitReferenceExpression(expression: KtReferenceExpression) {
val references = createReferences(expression)
for (reference in references) {
val targets = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, expression]
?.let { listOf(it) }
?: reference.getTargetDescriptors(bindingContext)
val referencedName = (expression as? KtNameReferenceExpression)?.getReferencedNameAsName()
for (target in targets) {
val importableFqName = target.importableFqName ?: continue
val parentFqName = importableFqName.parent()
if (target is PackageViewDescriptor && parentFqName == FqName.ROOT) continue // no need to import top-level packages
if (target !is PackageViewDescriptor && parentFqName == currentPackageName) continue
if (!reference.canBeResolvedViaImport(target)) continue
val importableDescriptor = target.getImportableDescriptor()
if (referencedName != null && importableDescriptor.name != referencedName) continue // resolved via alias
if (isAccessibleAsMember(importableDescriptor, expression, bindingContext)) continue
_descriptors.add(importableDescriptor)
}
}
super.visitReferenceExpression(expression)
}
private fun isAccessibleAsMember(target: DeclarationDescriptor, place: KtElement, bindingContext: BindingContext): Boolean {
if (target.containingDeclaration !is ClassDescriptor) return false
fun isInScope(scope: HierarchicalScope): Boolean {
return when (target) {
is FunctionDescriptor ->
scope.findFunction(target.name, NoLookupLocation.FROM_IDE) { it == target } != null
is PropertyDescriptor ->
scope.findVariable(target.name, NoLookupLocation.FROM_IDE) { it == target } != null
is ClassDescriptor ->
scope.findClassifier(target.name, NoLookupLocation.FROM_IDE) == target
else -> false
}
}
val resolutionScope = place.getResolutionScope(bindingContext)
val noImportsScope = resolutionScope.replaceImportingScopes(null)
if (isInScope(noImportsScope)) return true
if (target !is ClassDescriptor) { // classes not accessible through receivers, only their constructors
if (resolutionScope.getImplicitReceiversHierarchy().any { isInScope(it.type.memberScope.memberScopeAsImportingScope()) }) return true
}
return false
}
} | apache-2.0 | faaf60e4d2fea4bc9f0af1bcbf8759e2 | 44.628788 | 145 | 0.721687 | 5.410602 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/domain/entity/ContentDirectoryEntity.kt | 1 | 3721 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.domain.entity
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import net.mm2d.android.upnp.cds.CdsObject
import net.mm2d.dmsexplorer.domain.model.ExploreListener
import net.mm2d.dmsexplorer.domain.model.ExploreListenerAdapter
import net.mm2d.dmsexplorer.settings.Settings
import net.mm2d.dmsexplorer.settings.SortKey.*
import net.mm2d.log.Logger
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class ContentDirectoryEntity private constructor(
val parentId: String,
override val parentName: String
) : DirectoryEntity {
private val list = mutableListOf<ContentEntity>()
private var sortedList = emptyList<ContentEntity>()
private var entryListener: ExploreListener = ENTRY_LISTENER
@Volatile
override var isInProgress = true
private set
@Volatile
private var disposable: Disposable? = null
override val entities: List<ContentEntity>
get() = sortedList
private var _selectedEntity: ContentEntity? = null
override var selectedEntity: ContentEntity?
get() = _selectedEntity
set(entity) {
if (entity == null || !list.contains(entity)) {
_selectedEntity = null
return
}
_selectedEntity = entity
}
constructor() : this(ROOT_OBJECT_ID, ROOT_TITLE)
fun terminate() {
setExploreListener(null)
disposable?.dispose()
disposable = null
}
fun enterChild(entity: ContentEntity): ContentDirectoryEntity? {
if (!list.contains(entity)) {
return null
}
if (entity.type != ContentType.CONTAINER) {
return null
}
_selectedEntity = entity
val cdsObject = entity.rawEntity as CdsObject
return ContentDirectoryEntity(cdsObject.objectId, cdsObject.title)
}
fun setExploreListener(listener: ExploreListener?) {
entryListener = listener ?: ENTRY_LISTENER
}
fun clearState() {
disposable?.dispose()
disposable = null
_selectedEntity = null
isInProgress = true
list.clear()
sortedList = emptyList()
entryListener.onStart()
}
fun startBrowse(observable: Observable<CdsObject>) {
entryListener.onStart()
disposable = observable
.subscribeOn(Schedulers.io())
.subscribe({ cdsObject ->
list.add(CdsContentEntity(cdsObject))
sort()
entryListener.onUpdate(sortedList)
}, {
Logger.w(it)
}, {
isInProgress = false
entryListener.onComplete()
})
}
private fun sort() {
val settings = Settings.get()
val isAscending = settings.isAscendingSortOrder
sortedList = when (settings.sortKey) {
NONE -> list.toList()
NAME -> list.sortedByText(isAscending) { it.name }
DATE -> list.sortedBy(isAscending) { it.date }
}
}
fun onUpdateSortSettings() {
Completable.fromAction {
sort()
entryListener.onUpdate(sortedList)
}
.subscribeOn(Schedulers.io())
.subscribe()
}
companion object {
private const val ROOT_OBJECT_ID = "0"
private const val ROOT_TITLE = ""
private val ENTRY_LISTENER: ExploreListener = ExploreListenerAdapter()
}
}
| mit | 92033f6e15407c8d5b1245c5b823e424 | 28.173228 | 78 | 0.625101 | 4.654523 | false | false | false | false |
bazelbuild/rules_kotlin | src/main/kotlin/io/bazel/kotlin/builder/utils/jars/JarCreator.kt | 1 | 7936 | /*
* Copyright 2018 The Bazel Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.bazel.kotlin.builder.utils.jars
import java.io.BufferedOutputStream
import java.io.ByteArrayOutputStream
import java.io.Closeable
import java.io.FileInputStream
import java.io.IOException
import java.io.UncheckedIOException
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths.get
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.util.TreeMap
import java.util.jar.Attributes
import java.util.jar.JarOutputStream
import java.util.jar.Manifest
/**
* A class for creating Jar files. Allows normalization of Jar entries by setting their timestamp to
* the DOS epoch. All Jar entries are sorted alphabetically.
*/
@Suppress("unused")
class JarCreator(
path: Path,
normalize: Boolean = true,
verbose: Boolean = false,
) : JarHelper(path, normalize, verbose), Closeable {
// Map from Jar entry names to files. Use TreeMap so we can establish a canonical order for the
// entries regardless in what order they get added.
private val jarEntries = TreeMap<String, Path>()
private var manifestFile: String? = null
private var mainClass: String? = null
private var targetLabel: String? = null
private var injectingRuleKind: String? = null
/**
* Adds an entry to the Jar file, normalizing the name.
*
* @param entryName the name of the entry in the Jar file
* @param path the path of the input for the entry
* @return true iff a new entry was added
*/
private fun addEntry(entryName: String, path: Path): Boolean {
var normalizedEntryName = entryName
if (normalizedEntryName.startsWith("/")) {
normalizedEntryName = normalizedEntryName.substring(1)
} else if (normalizedEntryName.length >= 3 &&
Character.isLetter(normalizedEntryName[0]) &&
normalizedEntryName[1] == ':' &&
(normalizedEntryName[2] == '\\' || normalizedEntryName[2] == '/')
) {
// Windows absolute path, e.g. "D:\foo" or "e:/blah".
// Windows paths are case-insensitive, and support both backslashes and forward slashes.
normalizedEntryName = normalizedEntryName.substring(3)
} else if (normalizedEntryName.startsWith("./")) {
normalizedEntryName = normalizedEntryName.substring(2)
}
return jarEntries.put(normalizedEntryName, path) == null
}
/**
* Adds an entry to the Jar file, normalizing the name.
*
* @param entryName the name of the entry in the Jar file
* @param fileName the name of the input file for the entry
* @return true iff a new entry was added
*/
fun addEntry(entryName: String, fileName: String): Boolean {
return addEntry(entryName, get(fileName))
}
/**
* Adds the contents of a directory to the Jar file. All files below this directory will be added
* to the Jar file using the name relative to the directory as the name for the Jar entry.
*
* @param directory the directory to add to the jar
*/
fun addDirectory(directory: Path) {
if (!Files.exists(directory)) {
throw IllegalArgumentException("directory does not exist: $directory")
}
try {
Files.walkFileTree(
directory,
object : SimpleFileVisitor<Path>() {
@Throws(IOException::class)
override fun preVisitDirectory(path: Path, attrs: BasicFileAttributes): FileVisitResult {
if (path != directory) {
// For consistency with legacy behaviour, include entries for directories except for
// the root.
addEntry(path, /* isDirectory= */ true)
}
return FileVisitResult.CONTINUE
}
@Throws(IOException::class)
override fun visitFile(path: Path, attrs: BasicFileAttributes): FileVisitResult {
addEntry(path, /* isDirectory= */ false)
return FileVisitResult.CONTINUE
}
fun addEntry(path: Path, isDirectory: Boolean) {
val sb = StringBuilder()
var first = true
for (entry in directory.relativize(path)) {
if (!first) {
// use `/` as the directory separator for jar paths, even on Windows
sb.append('/')
}
sb.append(entry.fileName)
first = false
}
if (isDirectory) {
sb.append('/')
}
jarEntries[sb.toString()] = path
}
},
)
} catch (e: IOException) {
throw UncheckedIOException(e)
}
}
/**
* Adds a collection of entries to the jar, each with a given source path, and with the resulting
* file in the root of the jar.
*
* <pre>
* some/long/path.foo => (path.foo, some/long/path.foo)
</pre> *
*/
fun addRootEntries(entries: Collection<String>) {
for (entry in entries) {
val path = get(entry)
jarEntries[path.fileName.toString()] = path
}
}
/**
* Sets the main.class entry for the manifest. A value of `null` (the default) will
* omit the entry.
*
* @param mainClass the fully qualified name of the main class
*/
fun setMainClass(mainClass: String) {
this.mainClass = mainClass
}
fun setJarOwner(targetLabel: String, injectingRuleKind: String) {
this.targetLabel = targetLabel
this.injectingRuleKind = injectingRuleKind
}
/**
* Sets filename for the manifest content. If this is set the manifest will be read from this file
* otherwise the manifest content will get generated on the fly.
*
* @param manifestFile the filename of the manifest file.
*/
fun setManifestFile(manifestFile: String) {
this.manifestFile = manifestFile
}
@Throws(IOException::class)
private fun manifestContent(): ByteArray {
if (manifestFile != null) {
FileInputStream(manifestFile!!).use { `in` -> return manifestContentImpl(Manifest(`in`)) }
} else {
return manifestContentImpl(Manifest())
}
}
@Throws(IOException::class)
private fun manifestContentImpl(manifest: Manifest): ByteArray {
val attributes = manifest.mainAttributes
attributes[Attributes.Name.MANIFEST_VERSION] = "1.0"
val createdBy = Attributes.Name("Created-By")
if (attributes.getValue(createdBy) == null) {
attributes[createdBy] = "io.bazel.rules.kotlin"
}
if (mainClass != null) {
attributes[Attributes.Name.MAIN_CLASS] = mainClass
}
if (targetLabel != null) {
attributes[TARGET_LABEL] = targetLabel
}
if (injectingRuleKind != null) {
attributes[INJECTING_RULE_KIND] = injectingRuleKind
}
val out = ByteArrayOutputStream()
manifest.write(out)
return out.toByteArray()
}
override fun close() {
execute()
}
/**
* Executes the creation of the Jar file.
*
* @throws IOException if the Jar cannot be written or any of the entries cannot be read.
*/
@Throws(IOException::class)
fun execute() {
Files.newOutputStream(jarPath).use { os ->
BufferedOutputStream(os).use { bos ->
JarOutputStream(bos).use { out ->
// Create the manifest entry in the Jar file
writeManifestEntry(out, manifestContent())
for ((key, value) in jarEntries) {
out.copyEntry(key, value)
}
}
}
}
}
}
| apache-2.0 | 47d8fe54135f06c42f7a900134334123 | 32.485232 | 100 | 0.661668 | 4.382109 | false | false | false | false |
Shockah/Godwit | core/src/pl/shockah/godwit/geom/Degrees.kt | 1 | 1811 | package pl.shockah.godwit.geom
import pl.shockah.godwit.ease.ease
import pl.shockah.godwit.inCycle
inline class Degrees @Deprecated("Use Degrees.Companion.of(value: Float) or Float.degrees instead") constructor(
val value: Float
) : IAngle<Degrees> {
companion object {
val ZERO = Degrees()
val HALF = Degrees.of(180f)
operator fun invoke(): Degrees {
return of(0f)
}
fun of(value: Float): Degrees {
@Suppress("DEPRECATION")
return Degrees(value.inCycle(-180f, 180f))
}
fun of(value: Double): Degrees {
@Suppress("DEPRECATION")
return Degrees(value.inCycle(-180.0, 180.0).toFloat())
}
}
override val degrees: Degrees
get() = this
override val radians: Radians
get() = Radians.of(Math.toRadians(value.toDouble()).toFloat())
override val sin: Float
get() = radians.sin
override val cos: Float
get() = radians.cos
override val tan: Float
get() = radians.tan
override infix fun delta(angle: Angle): Degrees {
val r = angle.degrees.value - value
return Degrees.of(r + if (r > 180) -360 else if (r < -180) 360 else 0)
}
override fun ease(other: Angle, f: Float): Degrees {
val delta = this delta other
return if (delta.value > 0)
Degrees.of(f.ease(value, other.degrees.value))
else
Degrees.of(f.ease(value + 360, other.degrees.value))
}
override operator fun plus(other: Angle): Degrees {
return Degrees.of(value + other.degrees.value)
}
override operator fun minus(other: Angle): Degrees {
return Degrees.of(value - other.degrees.value)
}
operator fun plus(degrees: Float): Degrees {
return Degrees.of(value + degrees)
}
operator fun minus(degrees: Float): Degrees {
return Degrees.of(value - degrees)
}
override fun rotated(fullRotations: Float): Degrees {
return Degrees.of(value + fullRotations * 360f)
}
} | apache-2.0 | cfec1e06fa7b73f10df4e3d602acd8b2 | 23.16 | 112 | 0.695748 | 3.069492 | false | false | false | false |
CoderLine/alphaTab | src.kotlin/alphaTab/alphaTab/src/androidMain/kotlin/alphaTab/platform/android/AndroidRootViewContainer.kt | 1 | 3157 | package alphaTab.platform.android
import alphaTab.*
import alphaTab.platform.IContainer
import alphaTab.platform.IMouseEventArgs
import android.annotation.SuppressLint
import android.view.View
import android.widget.HorizontalScrollView
import android.widget.ScrollView
import kotlin.contracts.ExperimentalContracts
@ExperimentalContracts
@ExperimentalUnsignedTypes
@SuppressLint("ClickableViewAccessibility")
internal class AndroidRootViewContainer : IContainer, View.OnLayoutChangeListener {
private val _outerScroll: HorizontalScrollView
private val _innerScroll: ScrollView
internal val renderSurface: AlphaTabRenderSurface
public constructor(
outerScroll: HorizontalScrollView,
innerScroll: ScrollView,
renderSurface: AlphaTabRenderSurface
) {
_innerScroll = innerScroll
_outerScroll = outerScroll
this.renderSurface = renderSurface
outerScroll.addOnLayoutChangeListener(this)
}
fun destroy() {
_outerScroll.removeOnLayoutChangeListener(this)
}
override fun setBounds(x: Double, y: Double, w: Double, h: Double) {
}
override var width: Double
get() = (_outerScroll.measuredWidth / Environment.HighDpiFactor)
set(value) {
}
override var height: Double
get() = (_outerScroll.measuredHeight / Environment.HighDpiFactor)
set(value) {
}
override val isVisible: Boolean
get() = _outerScroll.visibility == View.VISIBLE
override var scrollLeft: Double
get() = _outerScroll.scrollX.toDouble()
set(value) {
_outerScroll.scrollX = value.toInt()
}
override var scrollTop: Double
get() = _innerScroll.scrollY.toDouble()
set(value) {
_innerScroll.scrollY = value.toInt()
}
override fun appendChild(child: IContainer) {
}
override fun stopAnimation() {
}
override fun transitionToX(duration: Double, x: Double) {
}
override fun clear() {
}
override var resize: IEventEmitter = EventEmitter()
override var mouseDown: IEventEmitterOfT<IMouseEventArgs> = EventEmitterOfT()
override var mouseMove: IEventEmitterOfT<IMouseEventArgs> = EventEmitterOfT()
override var mouseUp: IEventEmitterOfT<IMouseEventArgs> = EventEmitterOfT()
override fun onLayoutChange(
v: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
val widthChanged = (right - left) != (oldRight - oldLeft)
val heightChanged = (bottom - top) != (oldTop - oldBottom)
if (widthChanged || heightChanged) {
(resize as EventEmitter).trigger()
}
}
fun scrollToX(offset: Double) {
_outerScroll.smoothScrollTo(
(offset * Environment.HighDpiFactor).toInt(),
_outerScroll.scrollY
)
}
fun scrollToY(offset: Double) {
_innerScroll.smoothScrollTo(
_innerScroll.scrollX,
(offset * Environment.HighDpiFactor).toInt()
)
}
}
| mpl-2.0 | dad989715f573c2f12b8773cfbfef5c4 | 28.231481 | 83 | 0.658537 | 4.608759 | false | false | false | false |
wax911/AniTrendApp | app/src/main/java/com/mxt/anitrend/util/IntentBundleUtil.kt | 1 | 4228 | package com.mxt.anitrend.util
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import androidx.core.app.ShareCompat
import androidx.fragment.app.FragmentActivity
import com.mxt.anitrend.util.markdown.RegexUtil
import java.util.regex.Matcher
/**
* Created by max on 2017/12/01.
* Intent data formatter and helper methods
*/
class IntentBundleUtil(private val intent: Intent) {
var sharedIntent: ShareCompat.IntentReader? = null
private val deepLinkMatcher: Matcher? by lazy(LazyThreadSafetyMode.NONE) {
RegexUtil.findIntentKeys(intentData?.path)
}
private val intentAction: String? = intent.action
private val intentData: Uri? = intent.data
private fun hasDepth(key: String?): Array<String>? {
return if (key?.contains("/") == true)
key.split("/".toRegex())
.dropLastWhile {
it.isEmpty()
}.toTypedArray()
else null
}
private fun injectIntentParams() {
deepLinkMatcher?.also {
val type = it.group(1)
val groupLimit = it.groupCount()
var lastKey = it.group(groupLimit)
val splitKeys = hasDepth(lastKey)
when (type) {
KeyUtil.DEEP_LINK_ACTIVITY -> {
if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
}
KeyUtil.DEEP_LINK_USER -> when {
TextUtils.isDigitsOnly(lastKey) -> intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
else -> {
if (lastKey?.contains("/") == true)
lastKey = lastKey.replace("/", "")
intent.putExtra(KeyUtil.arg_userName, lastKey)
}
}
KeyUtil.DEEP_LINK_MANGA -> {
if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
intent.putExtra(KeyUtil.arg_mediaType, KeyUtil.MANGA)
}
KeyUtil.DEEP_LINK_ANIME -> {
if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
intent.putExtra(KeyUtil.arg_mediaType, KeyUtil.ANIME)
}
KeyUtil.DEEP_LINK_CHARACTER -> if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
KeyUtil.DEEP_LINK_ACTOR -> if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
KeyUtil.DEEP_LINK_STAFF -> if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
KeyUtil.DEEP_LINK_STUDIO -> if (splitKeys != null)
intent.putExtra(KeyUtil.arg_id, splitKeys[0].toLong())
else
intent.putExtra(KeyUtil.arg_id, lastKey?.toLong())
}
}
}
fun checkIntentData(context: FragmentActivity) {
if (context.intent?.hasExtra(KeyUtil.arg_shortcut_used) == true && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1)
ShortcutUtil.reportShortcutUsage(context, context.intent.getIntExtra(KeyUtil.arg_shortcut_used, KeyUtil.SHORTCUT_SEARCH))
if (!intentAction.isNullOrEmpty() && intentAction == Intent.ACTION_SEND)
sharedIntent = ShareCompat.IntentReader.from(context)
else if (deepLinkMatcher != null)
injectIntentParams()
}
}
| lgpl-3.0 | c00c4448840fe148221bf9a95558e7d3 | 38.148148 | 133 | 0.550615 | 4.697778 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/QuestUtil.kt | 1 | 2948 | package de.westnordost.streetcomplete.quests
import android.content.res.Resources
import android.text.Html
import android.text.Spanned
import androidx.core.os.ConfigurationCompat
import androidx.core.os.LocaleListCompat
import androidx.core.text.parseAsHtml
import de.westnordost.osmapi.map.data.Element
import de.westnordost.osmfeatures.FeatureDictionary
import de.westnordost.streetcomplete.data.osm.osmquest.OsmElementQuestType
import de.westnordost.streetcomplete.data.quest.QuestType
import de.westnordost.streetcomplete.ktx.toList
import de.westnordost.streetcomplete.ktx.toTypedArray
import java.util.*
import java.util.concurrent.FutureTask
fun Resources.getQuestTitle(questType: QuestType<*>, element: Element?, featureDictionaryFuture: FutureTask<FeatureDictionary>?): String {
val localeList = ConfigurationCompat.getLocales(configuration)
val arguments = getTemplateArguments(questType, element, localeList, featureDictionaryFuture)
return getString(getQuestTitleResId(questType, element), *arguments)
}
fun Resources.getHtmlQuestTitle(questType: QuestType<*>, element: Element?, featureDictionaryFuture: FutureTask<FeatureDictionary>?): Spanned {
val localeList = ConfigurationCompat.getLocales(configuration)
val arguments = getTemplateArguments(questType, element, localeList, featureDictionaryFuture)
val spannedArguments = arguments.map {"<i>" + Html.escapeHtml(it) + "</i>"}.toTypedArray()
return getString(getQuestTitleResId(questType, element), *spannedArguments).parseAsHtml()
}
private fun getTemplateArguments(
questType: QuestType<*>,
element: Element?,
localeList: LocaleListCompat,
featureDictionaryFuture: FutureTask<FeatureDictionary>?
): Array<String> {
val tags = element?.tags ?: emptyMap()
val typeName = lazy { findTypeName(tags, featureDictionaryFuture, localeList) }
return ((questType as? OsmElementQuestType<*>)?.getTitleArgs(tags, typeName)) ?: emptyArray()
}
private fun findTypeName(
tags: Map<String, String>,
featureDictionaryFuture: FutureTask<FeatureDictionary>?,
localeList: LocaleListCompat
): String? {
val dict = featureDictionaryFuture?.get() ?: return null
val locales = localeList.toList().toMutableList()
/* add fallback to English if (some) English is not part of the locale list already as the
fallback for text is also always English in this app (strings.xml) independent of, or rather
additionally to what is in the user's LocaleList. */
if (locales.none { it.language == Locale.ENGLISH.language }) {
locales.add(Locale.ENGLISH)
}
return dict
.byTags(tags)
.isSuggestion(false)
.forLocale(*locales.toTypedArray())
.find()
.firstOrNull()
?.name
}
private fun getQuestTitleResId(questType: QuestType<*>, element: Element?) =
(questType as? OsmElementQuestType<*>)?.getTitle(element?.tags ?: emptyMap()) ?: questType.title
| gpl-3.0 | 839c172b73014c16ab5f2ae159671a35 | 44.353846 | 143 | 0.761194 | 4.872727 | false | true | false | false |
kmizu/kotbinator | src/main/kotlin/com/github/kmizu/kotbinator/ParseResult.kt | 1 | 1197 | package com.github.kmizu.kotbinator
import com.github.kmizu.kotbinator.util.block
sealed class ParseResult<out T> {
class ParseSuccess<T>(val value: T, val rest: String): ParseResult<T>() {
override fun equals(other: Any?): Boolean = block {
when (other) {
is ParseSuccess<*> -> value == other.value && rest == other.rest
else -> false
}
}
override fun hashCode(): Int = block {
val v = value?.hashCode()
when (v) {
null -> rest.hashCode()
else -> v.hashCode() + rest.hashCode()
}
}
override fun toString(): String = block {
"Success($value, $rest)"
}
}
class ParseFailure(val rest: String) : ParseResult<Nothing>() {
override fun equals(other: Any?): Boolean = block {
when (other) {
is ParseFailure -> rest == other.rest
else -> false
}
}
override fun hashCode(): Int = block {
rest.hashCode()
}
override fun toString(): String = block {
"Failure($rest)"
}
}
}
| mit | a1ee266ecdb0925aff42c3ef61d3ef4d | 27.5 | 80 | 0.493734 | 4.657588 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/lui.kt | 1 | 394 | package venus.riscv.insts
import venus.riscv.InstructionField
import venus.riscv.insts.dsl.UTypeInstruction
val lui = UTypeInstruction(
name = "lui",
opcode = 0b0110111,
impl32 = { mcode, sim ->
val imm = mcode[InstructionField.IMM_31_12] shl 12
sim.setReg(mcode[InstructionField.RD], imm)
sim.incrementPC(mcode.length)
}
)
| mit | f20a29b2fdffe6bf0b9183abe2d185a5 | 27.142857 | 62 | 0.637056 | 3.54955 | false | false | false | false |
hurricup/intellij-community | platform/projectModel-impl/src/com/intellij/configurationStore/ExternalizableSchemeAdapter.kt | 1 | 1625 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.options
import com.intellij.configurationStore.SchemeExtensionProvider
import org.jdom.Element
import kotlin.properties.Delegates
abstract class ExternalizableSchemeAdapter : ExternalizableScheme {
private var myName: String by Delegates.notNull()
override fun getName() = myName
override fun setName(value: String) {
myName = value
}
override fun toString() = name
}
abstract class BaseSchemeProcessor<SCHEME : Scheme, MUTABLE_SCHEME : SCHEME> : NonLazySchemeProcessor<SCHEME, MUTABLE_SCHEME>(), SchemeExtensionProvider {
override val isUpgradeNeeded = false
override val schemeExtension = ".xml"
}
abstract class NonLazySchemeProcessor<SCHEME : Scheme, MUTABLE_SCHEME : SCHEME> : SchemeProcessor<SCHEME, MUTABLE_SCHEME>() {
/**
* @param duringLoad If occurred during [SchemeManager.loadSchemes] call
* * Returns null if element is not valid.
*/
@Throws(Exception::class)
abstract fun readScheme(element: Element, duringLoad: Boolean): MUTABLE_SCHEME?
} | apache-2.0 | 5ca3fff8ded0282734f4d3ca0ee41e7e | 33.595745 | 154 | 0.759385 | 4.439891 | false | false | false | false |
prt2121/android-workspace | Everywhere/app/src/main/kotlin/com/prt2121/everywhere/GroupRecyclerViewAdapter.kt | 1 | 1901 | package com.prt2121.everywhere
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.prt2121.everywhere.GroupFragment.OnListFragmentInteractionListener
import com.prt2121.everywhere.meetup.model.Group
import java.util.*
/**
* Created by pt2121 on 1/18/16.
*
* [RecyclerView.Adapter] that can display a [Group] and makes a call to the
* specified [OnListFragmentInteractionListener].
*/
class GroupRecyclerViewAdapter(private val groups: MutableList<Group>,
private val listener: OnListFragmentInteractionListener?) :
RecyclerView.Adapter<GroupRecyclerViewAdapter.ViewHolder>(), Function1<ArrayList<Group>, Unit> {
override fun invoke(p1: ArrayList<Group>) {
this.groups.clear()
this.groups.addAll(p1)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_group, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.item = groups[position]
holder.idView.text = groups[position].name
holder.contentView.text = groups[position].city
holder.view.setOnClickListener {
listener?.onListFragmentInteraction(holder.item!!)
}
}
override fun getItemCount(): Int {
return groups.size
}
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
val idView: TextView
val contentView: TextView
var item: Group? = null
init {
idView = view.findViewById(R.id.id) as TextView
contentView = view.findViewById(R.id.content) as TextView
}
override fun toString(): String {
return super.toString() + " '" + contentView.text + "'"
}
}
}
| apache-2.0 | 6c2b2668c417ce7c1dddbd281ef21a9f | 30.163934 | 100 | 0.725408 | 4.281532 | false | false | false | false |
ThoseGrapefruits/intellij-rust | src/test/kotlin/org/rust/lang/commenter/RustCommenterTest.kt | 1 | 1345 | package org.rust.lang.commenter
import com.intellij.openapi.actionSystem.IdeActions
import org.rust.lang.RustTestCase
/**
* @see RustCommenter
*/
class RustCommenterTest : RustTestCase() {
override fun getTestDataPath() = "src/test/resources/org/rust/lang/commenter/fixtures"
private fun doTest(actionId: String) {
myFixture.configureByFile(fileName)
myFixture.performEditorAction(actionId)
myFixture.checkResultByFile(fileName.replace(".rs", "_after.rs"), true)
}
fun testSingleLine() = doTest(IdeActions.ACTION_COMMENT_LINE)
fun testMultiLine() = doTest(IdeActions.ACTION_COMMENT_LINE)
fun testSingleLineBlock() = doTest(IdeActions.ACTION_COMMENT_BLOCK)
fun testMultiLineBlock() = doTest(IdeActions.ACTION_COMMENT_BLOCK)
fun testSingleLineUncomment() = doTest(IdeActions.ACTION_COMMENT_LINE)
fun testMultiLineUncomment() = doTest(IdeActions.ACTION_COMMENT_LINE)
fun testSingleLineBlockUncomment() = doTest(IdeActions.ACTION_COMMENT_BLOCK)
fun testMultiLineBlockUncomment() = doTest(IdeActions.ACTION_COMMENT_BLOCK)
fun testSingleLineUncommentWithSpace() = doTest(IdeActions.ACTION_COMMENT_LINE)
fun testNestedBlockComments() = doTest(IdeActions.ACTION_COMMENT_BLOCK) // FIXME
fun testIndentedSingleLineComment() = doTest(IdeActions.ACTION_COMMENT_LINE)
}
| mit | a385c960daff0d019c8c846cd3ab50ae | 42.387097 | 90 | 0.764312 | 4.283439 | false | true | false | false |
android/architecture-components-samples | LiveDataSample/app/src/test/java/com/android/example/livedatabuilder/util/LiveDataTestUtil.kt | 1 | 2152 | /*
* Copyright (C) 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 com.android.example.livedatabuilder.util
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
/**
* Gets the value of a [LiveData] or waits for it to have one, with a timeout.
*
* Use this extension from host-side (JVM) tests. It's recommended to use it alongside
* `InstantTaskExecutorRule` or a similar mechanism to execute tasks synchronously.
*/
fun <T> LiveData<T>.getOrAwaitValue(
time: Long = 2,
timeUnit: TimeUnit = TimeUnit.SECONDS,
afterObserve: () -> Unit = {}
): T {
var data: T? = null
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(o: T?) {
data = o
latch.countDown()
[email protected](this)
}
}
this.observeForever(observer)
afterObserve.invoke()
// Don't wait indefinitely if the LiveData is not set.
if (!latch.await(time, timeUnit)) {
this.removeObserver(observer)
throw TimeoutException("LiveData value was never set.")
}
@Suppress("UNCHECKED_CAST")
return data as T
}
/**
* Observes a [LiveData] until the `block` is done executing.
*/
suspend fun <T> LiveData<T>.observeForTesting(block: suspend () -> Unit) {
val observer = Observer<T> { }
try {
observeForever(observer)
block()
} finally {
removeObserver(observer)
}
}
| apache-2.0 | 76b0133aa62f3fe22dc15b7b1a39e573 | 30.188406 | 86 | 0.686803 | 4.138462 | false | false | false | false |
RadiationX/ForPDA | app/src/main/java/forpdateam/ru/forpda/model/data/cache/qms/QmsCache.kt | 1 | 4368 | package forpdateam.ru.forpda.model.data.cache.qms
import com.jakewharton.rxrelay2.BehaviorRelay
import forpdateam.ru.forpda.entity.db.qms.QmsContactBd
import forpdateam.ru.forpda.entity.db.qms.QmsThemesBd
import forpdateam.ru.forpda.entity.remote.qms.QmsContact
import forpdateam.ru.forpda.entity.remote.qms.QmsTheme
import forpdateam.ru.forpda.entity.remote.qms.QmsThemes
import io.reactivex.Observable
import io.realm.Realm
import java.lang.Exception
class QmsCache {
private val contactsRelay = BehaviorRelay.create<List<QmsContact>>()
private val themesRelays = mutableMapOf<Int, BehaviorRelay<QmsThemes>>()
fun observeContacts(): Observable<List<QmsContact>> = contactsRelay.hide()
fun observeThemes(userId: Int): Observable<QmsThemes> = getOrCreateThemesRelay(userId).hide()
fun getContacts(): List<QmsContact> = Realm.getDefaultInstance().use { realm ->
realm.where(QmsContactBd::class.java).findAll().map { QmsContact(it) }
}.also {
if (!contactsRelay.hasValue()) {
contactsRelay.accept(it)
}
}
fun saveContacts(items: List<QmsContact>) = Realm.getDefaultInstance().use { realm ->
realm.executeTransaction { realmTr ->
realmTr.delete(QmsContactBd::class.java)
realmTr.copyToRealmOrUpdate(items.map { QmsContactBd(it) })
}
contactsRelay.accept(getContacts())
}
fun updateContact(item:QmsContact) = Realm.getDefaultInstance().use { realm->
realm.executeTransaction {realmTr->
realmTr.copyToRealmOrUpdate(QmsContactBd(item))
}
if (contactsRelay.hasValue()) {
realm.where(QmsContactBd::class.java)
.equalTo("id", item.id)
.findFirst()
?.also { newItem ->
val currentItems = contactsRelay.value!!.toMutableList()
val index = currentItems.indexOfFirst { newItem.id == it.id }
if (index == -1) {
contactsRelay.accept(getContacts())
} else {
currentItems[index] = QmsContact(newItem)
contactsRelay.accept(currentItems)
}
}
}
}
fun getThemes(userId: Int): QmsThemes = Realm.getDefaultInstance().use { realm ->
realm.where(QmsThemesBd::class.java).equalTo("userId", userId).findAll().last()?.let { result ->
QmsThemes(result).also { themes ->
themes.themes.addAll(result.themes.map {
QmsTheme(it).also { theme ->
theme.nick = themes.nick
theme.userId = themes.userId
}
})
}
} ?: throw Exception("Not found by userId=$userId")
}.also { themes ->
getOrCreateThemesRelay(userId).also {
if (!it.hasValue()) {
it.accept(themes)
}
}
}
fun getAllThemes(): List<QmsThemes> = Realm.getDefaultInstance().use { realm ->
realm.where(QmsThemesBd::class.java).findAll().map { themesDb ->
QmsThemes(themesDb).also { themes ->
themes.themes.addAll(themesDb.themes.map {
QmsTheme(it).also { theme ->
theme.nick = themes.nick
theme.userId = themes.userId
}
})
}
}
}.also { themesList ->
themesList.forEach { themes ->
getOrCreateThemesRelay(themes.userId).also {
if (!it.hasValue()) {
it.accept(themes)
}
}
}
}
fun saveThemes(data: QmsThemes) = Realm.getDefaultInstance().use { realm ->
realm.executeTransaction { realmTr ->
realmTr.where(QmsThemesBd::class.java).equalTo("userId", data.userId).findAll().deleteAllFromRealm()
realmTr.copyToRealmOrUpdate(QmsThemesBd(data))
}
getOrCreateThemesRelay(data.userId).accept(getThemes(data.userId))
}
private fun getOrCreateThemesRelay(userId: Int): BehaviorRelay<QmsThemes> = themesRelays[userId]
?: BehaviorRelay.create<QmsThemes>().also {
themesRelays[userId] = it
}
} | gpl-3.0 | bb58d6e4a9855a83f5a1055424de2200 | 37.663717 | 112 | 0.576923 | 4.722162 | false | false | false | false |
DanielGrech/anko | dsl/testData/functional/15/ViewTest.kt | 3 | 54062 | @suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
public inline fun ViewManager.gestureOverlayView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView = addView<android.gesture.GestureOverlayView> {
ctx ->
val view = android.gesture.GestureOverlayView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
public inline fun Context.gestureOverlayView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView = addView<android.gesture.GestureOverlayView> {
ctx ->
val view = android.gesture.GestureOverlayView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.gestureOverlayView(): android.gesture.GestureOverlayView = gestureOverlayView({})
public inline fun Activity.gestureOverlayView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.gesture.GestureOverlayView.() -> Unit): android.gesture.GestureOverlayView = addView<android.gesture.GestureOverlayView> {
ctx ->
val view = android.gesture.GestureOverlayView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.extractEditText(): android.inputmethodservice.ExtractEditText = extractEditText({})
public inline fun ViewManager.extractEditText(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.inputmethodservice.ExtractEditText.() -> Unit): android.inputmethodservice.ExtractEditText = addView<android.inputmethodservice.ExtractEditText> {
ctx ->
val view = android.inputmethodservice.ExtractEditText(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.gLSurfaceView(): android.opengl.GLSurfaceView = gLSurfaceView({})
public inline fun ViewManager.gLSurfaceView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.opengl.GLSurfaceView.() -> Unit): android.opengl.GLSurfaceView = addView<android.opengl.GLSurfaceView> {
ctx ->
val view = android.opengl.GLSurfaceView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.surfaceView(): android.view.SurfaceView = surfaceView({})
public inline fun ViewManager.surfaceView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.view.SurfaceView.() -> Unit): android.view.SurfaceView = addView<android.view.SurfaceView> {
ctx ->
val view = android.view.SurfaceView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.textureView(): android.view.TextureView = textureView({})
public inline fun ViewManager.textureView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.view.TextureView.() -> Unit): android.view.TextureView = addView<android.view.TextureView> {
ctx ->
val view = android.view.TextureView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.view(): android.view.View = view({})
public inline fun ViewManager.view(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.view.View.() -> Unit): android.view.View = addView<android.view.View> {
ctx ->
val view = android.view.View(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.viewStub(): android.view.ViewStub = viewStub({})
public inline fun ViewManager.viewStub(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.view.ViewStub.() -> Unit): android.view.ViewStub = addView<android.view.ViewStub> {
ctx ->
val view = android.view.ViewStub(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
public inline fun ViewManager.adapterViewFlipper(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper = addView<android.widget.AdapterViewFlipper> {
ctx ->
val view = android.widget.AdapterViewFlipper(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
public inline fun Context.adapterViewFlipper(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper = addView<android.widget.AdapterViewFlipper> {
ctx ->
val view = android.widget.AdapterViewFlipper(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.adapterViewFlipper(): android.widget.AdapterViewFlipper = adapterViewFlipper({})
public inline fun Activity.adapterViewFlipper(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.AdapterViewFlipper.() -> Unit): android.widget.AdapterViewFlipper = addView<android.widget.AdapterViewFlipper> {
ctx ->
val view = android.widget.AdapterViewFlipper(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.analogClock(): android.widget.AnalogClock = analogClock({})
public inline fun ViewManager.analogClock(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.AnalogClock.() -> Unit): android.widget.AnalogClock = addView<android.widget.AnalogClock> {
ctx ->
val view = android.widget.AnalogClock(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.autoCompleteTextView(): android.widget.AutoCompleteTextView = autoCompleteTextView({})
public inline fun ViewManager.autoCompleteTextView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.AutoCompleteTextView.() -> Unit): android.widget.AutoCompleteTextView = addView<android.widget.AutoCompleteTextView> {
ctx ->
val view = android.widget.AutoCompleteTextView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.button(): android.widget.Button = button({})
public inline fun ViewManager.button(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Button.() -> Unit): android.widget.Button = addView<android.widget.Button> {
ctx ->
val view = android.widget.Button(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.calendarView(): android.widget.CalendarView = calendarView({})
public inline fun ViewManager.calendarView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView = addView<android.widget.CalendarView> {
ctx ->
val view = android.widget.CalendarView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.calendarView(): android.widget.CalendarView = calendarView({})
public inline fun Context.calendarView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView = addView<android.widget.CalendarView> {
ctx ->
val view = android.widget.CalendarView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.calendarView(): android.widget.CalendarView = calendarView({})
public inline fun Activity.calendarView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.CalendarView.() -> Unit): android.widget.CalendarView = addView<android.widget.CalendarView> {
ctx ->
val view = android.widget.CalendarView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.checkBox(): android.widget.CheckBox = checkBox({})
public inline fun ViewManager.checkBox(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.CheckBox.() -> Unit): android.widget.CheckBox = addView<android.widget.CheckBox> {
ctx ->
val view = android.widget.CheckBox(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.checkedTextView(): android.widget.CheckedTextView = checkedTextView({})
public inline fun ViewManager.checkedTextView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.CheckedTextView.() -> Unit): android.widget.CheckedTextView = addView<android.widget.CheckedTextView> {
ctx ->
val view = android.widget.CheckedTextView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.chronometer(): android.widget.Chronometer = chronometer({})
public inline fun ViewManager.chronometer(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Chronometer.() -> Unit): android.widget.Chronometer = addView<android.widget.Chronometer> {
ctx ->
val view = android.widget.Chronometer(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.datePicker(): android.widget.DatePicker = datePicker({})
public inline fun ViewManager.datePicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker = addView<android.widget.DatePicker> {
ctx ->
val view = android.widget.DatePicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.datePicker(): android.widget.DatePicker = datePicker({})
public inline fun Context.datePicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker = addView<android.widget.DatePicker> {
ctx ->
val view = android.widget.DatePicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.datePicker(): android.widget.DatePicker = datePicker({})
public inline fun Activity.datePicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DatePicker.() -> Unit): android.widget.DatePicker = addView<android.widget.DatePicker> {
ctx ->
val view = android.widget.DatePicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
public inline fun ViewManager.dialerFilter(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter = addView<android.widget.DialerFilter> {
ctx ->
val view = android.widget.DialerFilter(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
public inline fun Context.dialerFilter(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter = addView<android.widget.DialerFilter> {
ctx ->
val view = android.widget.DialerFilter(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.dialerFilter(): android.widget.DialerFilter = dialerFilter({})
public inline fun Activity.dialerFilter(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DialerFilter.() -> Unit): android.widget.DialerFilter = addView<android.widget.DialerFilter> {
ctx ->
val view = android.widget.DialerFilter(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.digitalClock(): android.widget.DigitalClock = digitalClock({})
public inline fun ViewManager.digitalClock(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.DigitalClock.() -> Unit): android.widget.DigitalClock = addView<android.widget.DigitalClock> {
ctx ->
val view = android.widget.DigitalClock(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.editText(): android.widget.EditText = editText({})
public inline fun ViewManager.editText(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.EditText.() -> Unit): android.widget.EditText = addView<android.widget.EditText> {
ctx ->
val view = android.widget.EditText(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.expandableListView(): android.widget.ExpandableListView = expandableListView({})
public inline fun ViewManager.expandableListView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView = addView<android.widget.ExpandableListView> {
ctx ->
val view = android.widget.ExpandableListView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.expandableListView(): android.widget.ExpandableListView = expandableListView({})
public inline fun Context.expandableListView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView = addView<android.widget.ExpandableListView> {
ctx ->
val view = android.widget.ExpandableListView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.expandableListView(): android.widget.ExpandableListView = expandableListView({})
public inline fun Activity.expandableListView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ExpandableListView.() -> Unit): android.widget.ExpandableListView = addView<android.widget.ExpandableListView> {
ctx ->
val view = android.widget.ExpandableListView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.imageButton(): android.widget.ImageButton = imageButton({})
public inline fun ViewManager.imageButton(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ImageButton.() -> Unit): android.widget.ImageButton = addView<android.widget.ImageButton> {
ctx ->
val view = android.widget.ImageButton(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.imageView(): android.widget.ImageView = imageView({})
public inline fun ViewManager.imageView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ImageView.() -> Unit): android.widget.ImageView = addView<android.widget.ImageView> {
ctx ->
val view = android.widget.ImageView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.listView(): android.widget.ListView = listView({})
public inline fun ViewManager.listView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ListView.() -> Unit): android.widget.ListView = addView<android.widget.ListView> {
ctx ->
val view = android.widget.ListView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.listView(): android.widget.ListView = listView({})
public inline fun Context.listView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ListView.() -> Unit): android.widget.ListView = addView<android.widget.ListView> {
ctx ->
val view = android.widget.ListView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.listView(): android.widget.ListView = listView({})
public inline fun Activity.listView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ListView.() -> Unit): android.widget.ListView = addView<android.widget.ListView> {
ctx ->
val view = android.widget.ListView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.multiAutoCompleteTextView(): android.widget.MultiAutoCompleteTextView = multiAutoCompleteTextView({})
public inline fun ViewManager.multiAutoCompleteTextView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.MultiAutoCompleteTextView.() -> Unit): android.widget.MultiAutoCompleteTextView = addView<android.widget.MultiAutoCompleteTextView> {
ctx ->
val view = android.widget.MultiAutoCompleteTextView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.numberPicker(): android.widget.NumberPicker = numberPicker({})
public inline fun ViewManager.numberPicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker = addView<android.widget.NumberPicker> {
ctx ->
val view = android.widget.NumberPicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.numberPicker(): android.widget.NumberPicker = numberPicker({})
public inline fun Context.numberPicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker = addView<android.widget.NumberPicker> {
ctx ->
val view = android.widget.NumberPicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.numberPicker(): android.widget.NumberPicker = numberPicker({})
public inline fun Activity.numberPicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.NumberPicker.() -> Unit): android.widget.NumberPicker = addView<android.widget.NumberPicker> {
ctx ->
val view = android.widget.NumberPicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.progressBar(): android.widget.ProgressBar = progressBar({})
public inline fun ViewManager.progressBar(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ProgressBar.() -> Unit): android.widget.ProgressBar = addView<android.widget.ProgressBar> {
ctx ->
val view = android.widget.ProgressBar(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.quickContactBadge(): android.widget.QuickContactBadge = quickContactBadge({})
public inline fun ViewManager.quickContactBadge(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.QuickContactBadge.() -> Unit): android.widget.QuickContactBadge = addView<android.widget.QuickContactBadge> {
ctx ->
val view = android.widget.QuickContactBadge(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.radioButton(): android.widget.RadioButton = radioButton({})
public inline fun ViewManager.radioButton(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.RadioButton.() -> Unit): android.widget.RadioButton = addView<android.widget.RadioButton> {
ctx ->
val view = android.widget.RadioButton(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.ratingBar(): android.widget.RatingBar = ratingBar({})
public inline fun ViewManager.ratingBar(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.RatingBar.() -> Unit): android.widget.RatingBar = addView<android.widget.RatingBar> {
ctx ->
val view = android.widget.RatingBar(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.searchView(): android.widget.SearchView = searchView({})
public inline fun ViewManager.searchView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SearchView.() -> Unit): android.widget.SearchView = addView<android.widget.SearchView> {
ctx ->
val view = android.widget.SearchView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.searchView(): android.widget.SearchView = searchView({})
public inline fun Context.searchView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SearchView.() -> Unit): android.widget.SearchView = addView<android.widget.SearchView> {
ctx ->
val view = android.widget.SearchView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.searchView(): android.widget.SearchView = searchView({})
public inline fun Activity.searchView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SearchView.() -> Unit): android.widget.SearchView = addView<android.widget.SearchView> {
ctx ->
val view = android.widget.SearchView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.seekBar(): android.widget.SeekBar = seekBar({})
public inline fun ViewManager.seekBar(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SeekBar.() -> Unit): android.widget.SeekBar = addView<android.widget.SeekBar> {
ctx ->
val view = android.widget.SeekBar(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
public inline fun ViewManager.slidingDrawer(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer = addView<android.widget.SlidingDrawer> {
ctx ->
val view = android.widget.SlidingDrawer(ctx, null)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
public inline fun Context.slidingDrawer(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer = addView<android.widget.SlidingDrawer> {
ctx ->
val view = android.widget.SlidingDrawer(ctx, null)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.slidingDrawer(): android.widget.SlidingDrawer = slidingDrawer({})
public inline fun Activity.slidingDrawer(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.SlidingDrawer.() -> Unit): android.widget.SlidingDrawer = addView<android.widget.SlidingDrawer> {
ctx ->
val view = android.widget.SlidingDrawer(ctx, null)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.space(): android.widget.Space = space({})
public inline fun ViewManager.space(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Space.() -> Unit): android.widget.Space = addView<android.widget.Space> {
ctx ->
val view = android.widget.Space(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.spinner(): android.widget.Spinner = spinner({})
public inline fun ViewManager.spinner(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Spinner.() -> Unit): android.widget.Spinner = addView<android.widget.Spinner> {
ctx ->
val view = android.widget.Spinner(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.spinner(): android.widget.Spinner = spinner({})
public inline fun Context.spinner(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Spinner.() -> Unit): android.widget.Spinner = addView<android.widget.Spinner> {
ctx ->
val view = android.widget.Spinner(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.spinner(): android.widget.Spinner = spinner({})
public inline fun Activity.spinner(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Spinner.() -> Unit): android.widget.Spinner = addView<android.widget.Spinner> {
ctx ->
val view = android.widget.Spinner(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.stackView(): android.widget.StackView = stackView({})
public inline fun ViewManager.stackView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.StackView.() -> Unit): android.widget.StackView = addView<android.widget.StackView> {
ctx ->
val view = android.widget.StackView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.stackView(): android.widget.StackView = stackView({})
public inline fun Context.stackView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.StackView.() -> Unit): android.widget.StackView = addView<android.widget.StackView> {
ctx ->
val view = android.widget.StackView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.stackView(): android.widget.StackView = stackView({})
public inline fun Activity.stackView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.StackView.() -> Unit): android.widget.StackView = addView<android.widget.StackView> {
ctx ->
val view = android.widget.StackView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.switch(): android.widget.Switch = switch({})
public inline fun ViewManager.switch(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.Switch.() -> Unit): android.widget.Switch = addView<android.widget.Switch> {
ctx ->
val view = android.widget.Switch(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.tabHost(): android.widget.TabHost = tabHost({})
public inline fun ViewManager.tabHost(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TabHost.() -> Unit): android.widget.TabHost = addView<android.widget.TabHost> {
ctx ->
val view = android.widget.TabHost(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.tabHost(): android.widget.TabHost = tabHost({})
public inline fun Context.tabHost(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TabHost.() -> Unit): android.widget.TabHost = addView<android.widget.TabHost> {
ctx ->
val view = android.widget.TabHost(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.tabHost(): android.widget.TabHost = tabHost({})
public inline fun Activity.tabHost(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TabHost.() -> Unit): android.widget.TabHost = addView<android.widget.TabHost> {
ctx ->
val view = android.widget.TabHost(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.tabWidget(): android.widget.TabWidget = tabWidget({})
public inline fun ViewManager.tabWidget(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget = addView<android.widget.TabWidget> {
ctx ->
val view = android.widget.TabWidget(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.tabWidget(): android.widget.TabWidget = tabWidget({})
public inline fun Context.tabWidget(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget = addView<android.widget.TabWidget> {
ctx ->
val view = android.widget.TabWidget(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.tabWidget(): android.widget.TabWidget = tabWidget({})
public inline fun Activity.tabWidget(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TabWidget.() -> Unit): android.widget.TabWidget = addView<android.widget.TabWidget> {
ctx ->
val view = android.widget.TabWidget(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.textView(): android.widget.TextView = textView({})
public inline fun ViewManager.textView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TextView.() -> Unit): android.widget.TextView = addView<android.widget.TextView> {
ctx ->
val view = android.widget.TextView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.timePicker(): android.widget.TimePicker = timePicker({})
public inline fun ViewManager.timePicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker = addView<android.widget.TimePicker> {
ctx ->
val view = android.widget.TimePicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.timePicker(): android.widget.TimePicker = timePicker({})
public inline fun Context.timePicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker = addView<android.widget.TimePicker> {
ctx ->
val view = android.widget.TimePicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.timePicker(): android.widget.TimePicker = timePicker({})
public inline fun Activity.timePicker(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TimePicker.() -> Unit): android.widget.TimePicker = addView<android.widget.TimePicker> {
ctx ->
val view = android.widget.TimePicker(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.toggleButton(): android.widget.ToggleButton = toggleButton({})
public inline fun ViewManager.toggleButton(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ToggleButton.() -> Unit): android.widget.ToggleButton = addView<android.widget.ToggleButton> {
ctx ->
val view = android.widget.ToggleButton(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
public inline fun ViewManager.twoLineListItem(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem = addView<android.widget.TwoLineListItem> {
ctx ->
val view = android.widget.TwoLineListItem(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
public inline fun Context.twoLineListItem(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem = addView<android.widget.TwoLineListItem> {
ctx ->
val view = android.widget.TwoLineListItem(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.twoLineListItem(): android.widget.TwoLineListItem = twoLineListItem({})
public inline fun Activity.twoLineListItem(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.TwoLineListItem.() -> Unit): android.widget.TwoLineListItem = addView<android.widget.TwoLineListItem> {
ctx ->
val view = android.widget.TwoLineListItem(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.videoView(): android.widget.VideoView = videoView({})
public inline fun ViewManager.videoView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.VideoView.() -> Unit): android.widget.VideoView = addView<android.widget.VideoView> {
ctx ->
val view = android.widget.VideoView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
public inline fun ViewManager.viewFlipper(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper = addView<android.widget.ViewFlipper> {
ctx ->
val view = android.widget.ViewFlipper(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
public inline fun Context.viewFlipper(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper = addView<android.widget.ViewFlipper> {
ctx ->
val view = android.widget.ViewFlipper(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.viewFlipper(): android.widget.ViewFlipper = viewFlipper({})
public inline fun Activity.viewFlipper(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ViewFlipper.() -> Unit): android.widget.ViewFlipper = addView<android.widget.ViewFlipper> {
ctx ->
val view = android.widget.ViewFlipper(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.zoomButton(): android.widget.ZoomButton = zoomButton({})
public inline fun ViewManager.zoomButton(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ZoomButton.() -> Unit): android.widget.ZoomButton = addView<android.widget.ZoomButton> {
ctx ->
val view = android.widget.ZoomButton(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.zoomControls(): android.widget.ZoomControls = zoomControls({})
public inline fun ViewManager.zoomControls(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls = addView<android.widget.ZoomControls> {
ctx ->
val view = android.widget.ZoomControls(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.zoomControls(): android.widget.ZoomControls = zoomControls({})
public inline fun Context.zoomControls(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls = addView<android.widget.ZoomControls> {
ctx ->
val view = android.widget.ZoomControls(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.zoomControls(): android.widget.ZoomControls = zoomControls({})
public inline fun Activity.zoomControls(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: android.widget.ZoomControls.() -> Unit): android.widget.ZoomControls = addView<android.widget.ZoomControls> {
ctx ->
val view = android.widget.ZoomControls(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
public inline fun ViewManager.appWidgetHostView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView = addView<android.appwidget.AppWidgetHostView> {
ctx ->
val view = _AppWidgetHostView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
public inline fun Context.appWidgetHostView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView = addView<android.appwidget.AppWidgetHostView> {
ctx ->
val view = _AppWidgetHostView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.appWidgetHostView(): android.appwidget.AppWidgetHostView = appWidgetHostView({})
public inline fun Activity.appWidgetHostView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _AppWidgetHostView.() -> Unit): android.appwidget.AppWidgetHostView = addView<android.appwidget.AppWidgetHostView> {
ctx ->
val view = _AppWidgetHostView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.webView(): android.webkit.WebView = webView({})
public inline fun ViewManager.webView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _WebView.() -> Unit): android.webkit.WebView = addView<android.webkit.WebView> {
ctx ->
val view = _WebView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.webView(): android.webkit.WebView = webView({})
public inline fun Context.webView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _WebView.() -> Unit): android.webkit.WebView = addView<android.webkit.WebView> {
ctx ->
val view = _WebView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.webView(): android.webkit.WebView = webView({})
public inline fun Activity.webView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _WebView.() -> Unit): android.webkit.WebView = addView<android.webkit.WebView> {
ctx ->
val view = _WebView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
public inline fun ViewManager.absoluteLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout = addView<android.widget.AbsoluteLayout> {
ctx ->
val view = _AbsoluteLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
public inline fun Context.absoluteLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout = addView<android.widget.AbsoluteLayout> {
ctx ->
val view = _AbsoluteLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.absoluteLayout(): android.widget.AbsoluteLayout = absoluteLayout({})
public inline fun Activity.absoluteLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _AbsoluteLayout.() -> Unit): android.widget.AbsoluteLayout = addView<android.widget.AbsoluteLayout> {
ctx ->
val view = _AbsoluteLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.frameLayout(): android.widget.FrameLayout = frameLayout({})
public inline fun ViewManager.frameLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _FrameLayout.() -> Unit): android.widget.FrameLayout = addView<android.widget.FrameLayout> {
ctx ->
val view = _FrameLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.frameLayout(): android.widget.FrameLayout = frameLayout({})
public inline fun Context.frameLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _FrameLayout.() -> Unit): android.widget.FrameLayout = addView<android.widget.FrameLayout> {
ctx ->
val view = _FrameLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.frameLayout(): android.widget.FrameLayout = frameLayout({})
public inline fun Activity.frameLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _FrameLayout.() -> Unit): android.widget.FrameLayout = addView<android.widget.FrameLayout> {
ctx ->
val view = _FrameLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.gallery(): android.widget.Gallery = gallery({})
public inline fun ViewManager.gallery(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _Gallery.() -> Unit): android.widget.Gallery = addView<android.widget.Gallery> {
ctx ->
val view = _Gallery(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.gallery(): android.widget.Gallery = gallery({})
public inline fun Context.gallery(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _Gallery.() -> Unit): android.widget.Gallery = addView<android.widget.Gallery> {
ctx ->
val view = _Gallery(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.gallery(): android.widget.Gallery = gallery({})
public inline fun Activity.gallery(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _Gallery.() -> Unit): android.widget.Gallery = addView<android.widget.Gallery> {
ctx ->
val view = _Gallery(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.gridLayout(): android.widget.GridLayout = gridLayout({})
public inline fun ViewManager.gridLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _GridLayout.() -> Unit): android.widget.GridLayout = addView<android.widget.GridLayout> {
ctx ->
val view = _GridLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.gridLayout(): android.widget.GridLayout = gridLayout({})
public inline fun Context.gridLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _GridLayout.() -> Unit): android.widget.GridLayout = addView<android.widget.GridLayout> {
ctx ->
val view = _GridLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.gridLayout(): android.widget.GridLayout = gridLayout({})
public inline fun Activity.gridLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _GridLayout.() -> Unit): android.widget.GridLayout = addView<android.widget.GridLayout> {
ctx ->
val view = _GridLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.gridView(): android.widget.GridView = gridView({})
public inline fun ViewManager.gridView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _GridView.() -> Unit): android.widget.GridView = addView<android.widget.GridView> {
ctx ->
val view = _GridView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.gridView(): android.widget.GridView = gridView({})
public inline fun Context.gridView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _GridView.() -> Unit): android.widget.GridView = addView<android.widget.GridView> {
ctx ->
val view = _GridView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.gridView(): android.widget.GridView = gridView({})
public inline fun Activity.gridView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _GridView.() -> Unit): android.widget.GridView = addView<android.widget.GridView> {
ctx ->
val view = _GridView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
public inline fun ViewManager.horizontalScrollView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView = addView<android.widget.HorizontalScrollView> {
ctx ->
val view = _HorizontalScrollView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
public inline fun Context.horizontalScrollView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView = addView<android.widget.HorizontalScrollView> {
ctx ->
val view = _HorizontalScrollView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.horizontalScrollView(): android.widget.HorizontalScrollView = horizontalScrollView({})
public inline fun Activity.horizontalScrollView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _HorizontalScrollView.() -> Unit): android.widget.HorizontalScrollView = addView<android.widget.HorizontalScrollView> {
ctx ->
val view = _HorizontalScrollView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
public inline fun ViewManager.imageSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher = addView<android.widget.ImageSwitcher> {
ctx ->
val view = _ImageSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
public inline fun Context.imageSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher = addView<android.widget.ImageSwitcher> {
ctx ->
val view = _ImageSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.imageSwitcher(): android.widget.ImageSwitcher = imageSwitcher({})
public inline fun Activity.imageSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ImageSwitcher.() -> Unit): android.widget.ImageSwitcher = addView<android.widget.ImageSwitcher> {
ctx ->
val view = _ImageSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.linearLayout(): android.widget.LinearLayout = linearLayout({})
public inline fun ViewManager.linearLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): android.widget.LinearLayout = addView<android.widget.LinearLayout> {
ctx ->
val view = _LinearLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.linearLayout(): android.widget.LinearLayout = linearLayout({})
public inline fun Context.linearLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): android.widget.LinearLayout = addView<android.widget.LinearLayout> {
ctx ->
val view = _LinearLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.linearLayout(): android.widget.LinearLayout = linearLayout({})
public inline fun Activity.linearLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _LinearLayout.() -> Unit): android.widget.LinearLayout = addView<android.widget.LinearLayout> {
ctx ->
val view = _LinearLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.radioGroup(): android.widget.RadioGroup = radioGroup({})
public inline fun ViewManager.radioGroup(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _RadioGroup.() -> Unit): android.widget.RadioGroup = addView<android.widget.RadioGroup> {
ctx ->
val view = _RadioGroup(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.radioGroup(): android.widget.RadioGroup = radioGroup({})
public inline fun Context.radioGroup(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _RadioGroup.() -> Unit): android.widget.RadioGroup = addView<android.widget.RadioGroup> {
ctx ->
val view = _RadioGroup(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.radioGroup(): android.widget.RadioGroup = radioGroup({})
public inline fun Activity.radioGroup(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _RadioGroup.() -> Unit): android.widget.RadioGroup = addView<android.widget.RadioGroup> {
ctx ->
val view = _RadioGroup(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
public inline fun ViewManager.relativeLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout = addView<android.widget.RelativeLayout> {
ctx ->
val view = _RelativeLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
public inline fun Context.relativeLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout = addView<android.widget.RelativeLayout> {
ctx ->
val view = _RelativeLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.relativeLayout(): android.widget.RelativeLayout = relativeLayout({})
public inline fun Activity.relativeLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _RelativeLayout.() -> Unit): android.widget.RelativeLayout = addView<android.widget.RelativeLayout> {
ctx ->
val view = _RelativeLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.scrollView(): android.widget.ScrollView = scrollView({})
public inline fun ViewManager.scrollView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ScrollView.() -> Unit): android.widget.ScrollView = addView<android.widget.ScrollView> {
ctx ->
val view = _ScrollView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.scrollView(): android.widget.ScrollView = scrollView({})
public inline fun Context.scrollView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ScrollView.() -> Unit): android.widget.ScrollView = addView<android.widget.ScrollView> {
ctx ->
val view = _ScrollView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.scrollView(): android.widget.ScrollView = scrollView({})
public inline fun Activity.scrollView(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ScrollView.() -> Unit): android.widget.ScrollView = addView<android.widget.ScrollView> {
ctx ->
val view = _ScrollView(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.tableLayout(): android.widget.TableLayout = tableLayout({})
public inline fun ViewManager.tableLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TableLayout.() -> Unit): android.widget.TableLayout = addView<android.widget.TableLayout> {
ctx ->
val view = _TableLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.tableLayout(): android.widget.TableLayout = tableLayout({})
public inline fun Context.tableLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TableLayout.() -> Unit): android.widget.TableLayout = addView<android.widget.TableLayout> {
ctx ->
val view = _TableLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.tableLayout(): android.widget.TableLayout = tableLayout({})
public inline fun Activity.tableLayout(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TableLayout.() -> Unit): android.widget.TableLayout = addView<android.widget.TableLayout> {
ctx ->
val view = _TableLayout(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.tableRow(): android.widget.TableRow = tableRow({})
public inline fun ViewManager.tableRow(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TableRow.() -> Unit): android.widget.TableRow = addView<android.widget.TableRow> {
ctx ->
val view = _TableRow(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.tableRow(): android.widget.TableRow = tableRow({})
public inline fun Context.tableRow(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TableRow.() -> Unit): android.widget.TableRow = addView<android.widget.TableRow> {
ctx ->
val view = _TableRow(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.tableRow(): android.widget.TableRow = tableRow({})
public inline fun Activity.tableRow(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TableRow.() -> Unit): android.widget.TableRow = addView<android.widget.TableRow> {
ctx ->
val view = _TableRow(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
public inline fun ViewManager.textSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher = addView<android.widget.TextSwitcher> {
ctx ->
val view = _TextSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
public inline fun Context.textSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher = addView<android.widget.TextSwitcher> {
ctx ->
val view = _TextSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.textSwitcher(): android.widget.TextSwitcher = textSwitcher({})
public inline fun Activity.textSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _TextSwitcher.() -> Unit): android.widget.TextSwitcher = addView<android.widget.TextSwitcher> {
ctx ->
val view = _TextSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
public inline fun ViewManager.viewAnimator(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator = addView<android.widget.ViewAnimator> {
ctx ->
val view = _ViewAnimator(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
public inline fun Context.viewAnimator(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator = addView<android.widget.ViewAnimator> {
ctx ->
val view = _ViewAnimator(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.viewAnimator(): android.widget.ViewAnimator = viewAnimator({})
public inline fun Activity.viewAnimator(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ViewAnimator.() -> Unit): android.widget.ViewAnimator = addView<android.widget.ViewAnimator> {
ctx ->
val view = _ViewAnimator(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun ViewManager.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
public inline fun ViewManager.viewSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher = addView<android.widget.ViewSwitcher> {
ctx ->
val view = _ViewSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Context.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
public inline fun Context.viewSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher = addView<android.widget.ViewSwitcher> {
ctx ->
val view = _ViewSwitcher(ctx)
view.init()
view
}
@suppress("NOTHING_TO_INLINE")
public inline fun Activity.viewSwitcher(): android.widget.ViewSwitcher = viewSwitcher({})
public inline fun Activity.viewSwitcher(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) init: _ViewSwitcher.() -> Unit): android.widget.ViewSwitcher = addView<android.widget.ViewSwitcher> {
ctx ->
val view = _ViewSwitcher(ctx)
view.init()
view
} | apache-2.0 | b5ef45c0ad591b7ab5bcb78c7f41eb43 | 43.205233 | 256 | 0.750361 | 4.199316 | false | false | false | false |
mdaniel/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowToolbar.kt | 2 | 4945 | // 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.toolWindow
import com.intellij.openapi.actionSystem.ActionPlaces.TOOLWINDOW_TOOLBAR_BAR
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.impl.AbstractDroppableStripe
import com.intellij.openapi.wm.impl.LayoutData
import com.intellij.openapi.wm.impl.SquareStripeButton
import com.intellij.ui.ComponentUtil
import com.intellij.util.ui.JBUI
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Point
import java.awt.Rectangle
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.border.Border
internal abstract class ToolWindowToolbar : JPanel() {
lateinit var defaults: List<String>
abstract val bottomStripe: StripeV2
abstract val topStripe: StripeV2
protected fun init() {
layout = BorderLayout()
isOpaque = true
background = JBUI.CurrentTheme.ToolWindow.background()
val topWrapper = JPanel(BorderLayout())
border = createBorder()
topStripe.background = JBUI.CurrentTheme.ToolWindow.background()
bottomStripe.background = JBUI.CurrentTheme.ToolWindow.background()
topWrapper.background = JBUI.CurrentTheme.ToolWindow.background()
topWrapper.add(topStripe, BorderLayout.NORTH)
add(topWrapper, BorderLayout.NORTH)
add(bottomStripe, BorderLayout.SOUTH)
}
open fun createBorder():Border = JBUI.Borders.empty()
open fun getBorderColor(): Color? = JBUI.CurrentTheme.ToolWindow.borderColor()
abstract fun getStripeFor(anchor: ToolWindowAnchor): AbstractDroppableStripe
fun getButtonFor(toolWindowId: String): StripeButtonManager? {
return topStripe.getButtons().find { it.id == toolWindowId } ?: bottomStripe.getButtons().find { it.id == toolWindowId }
}
open fun getStripeFor(screenPoint: Point): AbstractDroppableStripe? {
if (!isShowing) {
return null
}
val topLeftRect = Rectangle(topStripe.locationOnScreen, topStripe.size).also {
if (it.width == 0) it.width = SHADOW_WIDTH
it.height = height - maxOf(SHADOW_WIDTH, bottomStripe.height + SHADOW_WIDTH)
}
return if (topLeftRect.contains(screenPoint)) {
topStripe
}
else if (Rectangle(locationOnScreen, size).also {
it.y -= SHADOW_WIDTH
it.height += SHADOW_WIDTH
}.contains(screenPoint)) {
bottomStripe
}
else {
null
}
}
fun removeStripeButton(toolWindow: ToolWindow, anchor: ToolWindowAnchor) {
remove(getStripeFor(anchor), toolWindow)
}
fun hasButtons() = topStripe.getButtons().isNotEmpty() || bottomStripe.getButtons().isNotEmpty()
fun reset() {
topStripe.reset()
bottomStripe.reset()
}
fun startDrag() {
revalidate()
repaint()
}
fun stopDrag() = startDrag()
fun tryDroppingOnGap(data: LayoutData, gap: Int, dropRectangle: Rectangle, doLayout: () -> Unit) {
val sideDistance = data.eachY + gap - dropRectangle.y + dropRectangle.height
if (sideDistance > 0) {
data.dragInsertPosition = -1
data.dragToSide = false
data.dragTargetChosen = true
doLayout()
}
}
companion object {
val SHADOW_WIDTH = JBUI.scale(40)
fun updateButtons(panel: JComponent) {
ComponentUtil.findComponentsOfType(panel, SquareStripeButton::class.java).forEach { it.update() }
panel.revalidate()
panel.repaint()
}
fun remove(panel: AbstractDroppableStripe, toolWindow: ToolWindow) {
val component = panel.components.firstOrNull { it is SquareStripeButton && it.toolWindow.id == toolWindow.id } ?: return
panel.remove(component)
panel.revalidate()
panel.repaint()
}
}
open class ToolwindowActionToolbar(val panel: JComponent) : ActionToolbarImpl(TOOLWINDOW_TOOLBAR_BAR, DefaultActionGroup(), false) {
override fun actionsUpdated(forced: Boolean, newVisibleActions: List<AnAction>) = updateButtons(panel)
}
internal class StripeV2(private val toolBar: ToolWindowToolbar,
paneId: String,
override val anchor: ToolWindowAnchor,
override val split: Boolean = false) : AbstractDroppableStripe(paneId, VerticalFlowLayout(0, 0)) {
override val isNewStripes: Boolean
get() = true
override fun getButtonFor(toolWindowId: String) = toolBar.getButtonFor(toolWindowId)
override fun tryDroppingOnGap(data: LayoutData, gap: Int, insertOrder: Int) {
toolBar.tryDroppingOnGap(data, gap, dropRectangle) {
layoutDragButton(data, gap)
}
}
override fun toString() = "StripeNewUi(anchor=$anchor)"
}
} | apache-2.0 | b722e10a18e2ef9757a4dea7af7a00ff | 33.110345 | 134 | 0.722548 | 4.379982 | false | false | false | false |
ingokegel/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/service/execution/GradleExecutionUtil.kt | 12 | 5768 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("GradleExecutionUtil")
package org.jetbrains.plugins.gradle.service.execution
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType.EXECUTE_TASK
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemExecutionAware.Companion.getExtensions
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemExecutionAware.Companion.setEnvironmentConfigurationProvider
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkProvider
import com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask
import com.intellij.openapi.externalSystem.service.remote.ExternalSystemProgressNotificationManagerImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.io.systemIndependentPath
import org.gradle.tooling.GradleConnector
import org.gradle.util.GradleVersion
import org.jetbrains.plugins.gradle.service.GradleInstallationManager
import org.jetbrains.plugins.gradle.settings.DistributionType
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
import org.jetbrains.plugins.gradle.util.GradleBundle
import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID
import org.jetbrains.plugins.gradle.util.GradleUtil
import java.nio.file.Path
fun ensureInstalledWrapper(project: Project, externalProjectPath: Path, gradleVersion: GradleVersion, callback: Runnable) {
val ensureInstalledWrapperTask = EnsureInstalledWrapperExecutionTask(project, externalProjectPath, gradleVersion)
val title = GradleBundle.message("gradle.project.generation.wrapper.progress.title")
val task = object : Task.Backgroundable(project, title, true) {
override fun run(indicator: ProgressIndicator) {
val listener = object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onEnd(id: ExternalSystemTaskId) = callback.run()
}
ensureInstalledWrapperTask.execute(indicator, listener)
}
}
task.queue()
}
private class EnsureInstalledWrapperExecutionTask(
project: Project,
externalProjectPath: Path,
private val gradleVersion: GradleVersion
) : AbstractExternalSystemTask(SYSTEM_ID, EXECUTE_TASK, project, externalProjectPath.systemIndependentPath) {
private val progressNotificationManager = ExternalSystemProgressNotificationManagerImpl.getInstanceImpl()
private val newCancellationTokenSource = GradleConnector.newCancellationTokenSource()
private fun createExecutionSettings(): GradleExecutionSettings {
val settings = GradleSettings.getInstance(ideProject)
val executionSettings = GradleExecutionSettings(
getGradleHome(),
settings.serviceDirectoryPath,
getDistributionType(),
settings.gradleVmOptions,
settings.isOfflineWork
)
val jdkProvider = ExternalSystemJdkProvider.getInstance()
executionSettings.javaHome = jdkProvider.internalJdk.homePath
for (executionAware in getExtensions(externalSystemId)) {
val environmentConfigurationProvider = executionAware.getEnvironmentConfigurationProvider(externalProjectPath, false, ideProject)
if (environmentConfigurationProvider != null) {
executionSettings.setEnvironmentConfigurationProvider(environmentConfigurationProvider)
break
}
}
return executionSettings
}
private fun getGradleHome(): String? {
val installationManager = GradleInstallationManager.getInstance()
val gradleHome = installationManager.getGradleHome(ideProject, externalProjectPath)
return FileUtil.toCanonicalPath(gradleHome?.path)
}
private fun getDistributionType(): DistributionType {
val settings = GradleSettings.getInstance(ideProject)
val projectSettings = settings.getLinkedProjectSettings(externalProjectPath)
return when {
projectSettings != null -> projectSettings.distributionType ?: DistributionType.LOCAL
GradleUtil.isGradleDefaultWrapperFilesExist(externalProjectPath) -> DistributionType.DEFAULT_WRAPPED
else -> DistributionType.BUNDLED
}
}
private fun ensureInstalledWrapper(listener: ExternalSystemTaskNotificationListener) {
GradleExecutionHelper().ensureInstalledWrapper(
id,
externalProjectPath,
createExecutionSettings(),
gradleVersion,
listener,
newCancellationTokenSource.token()
)
}
override fun doExecute() {
val progressNotificationListener = wrapWithListener(progressNotificationManager)
try {
progressNotificationManager.onStart(id, externalProjectPath)
ensureInstalledWrapper(progressNotificationListener)
progressNotificationManager.onSuccess(id)
}
catch (e: ProcessCanceledException) {
progressNotificationManager.onCancel(id)
throw e
}
catch (e: Exception) {
progressNotificationManager.onFailure(id, e)
throw e
}
finally {
progressNotificationManager.onEnd(id)
}
}
override fun doCancel(): Boolean {
progressNotificationManager.beforeCancel(id)
newCancellationTokenSource.cancel()
progressNotificationManager.onCancel(id)
return true
}
} | apache-2.0 | 4f5454436627196955ef48d80f827773 | 43.72093 | 140 | 0.807559 | 5.286893 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SpecifySuperTypeFix.kt | 1 | 5708 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopupStep
import com.intellij.openapi.ui.popup.PopupStep
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
class SpecifySuperTypeFix(
superExpression: KtSuperExpression,
private val superTypes: List<String>
) : KotlinQuickFixAction<KtSuperExpression>(superExpression) {
override fun getText() = KotlinBundle.message("intention.name.specify.supertype")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (editor == null) return
val superExpression = element ?: return
CommandProcessor.getInstance().runUndoTransparentAction {
if (superTypes.size == 1) {
superExpression.specifySuperType(superTypes.first())
} else {
JBPopupFactory
.getInstance()
.createListPopup(createListPopupStep(superExpression, superTypes))
.showInBestPositionFor(editor)
}
}
}
private fun KtSuperExpression.specifySuperType(superType: String) {
project.executeWriteCommand(KotlinBundle.message("intention.name.specify.supertype")) {
val label = this.labelQualifier?.text ?: ""
replace(KtPsiFactory(this).createExpression("super<$superType>$label"))
}
}
private fun createListPopupStep(superExpression: KtSuperExpression, superTypes: List<String>): ListPopupStep<*> {
return object : BaseListPopupStep<String>(KotlinBundle.message("popup.title.choose.supertype"), superTypes) {
override fun isAutoSelectionEnabled() = false
override fun onChosen(selectedValue: String, finalChoice: Boolean): PopupStep<*>? {
if (finalChoice) {
superExpression.specifySuperType(selectedValue)
}
return PopupStep.FINAL_CHOICE
}
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): KotlinQuickFixAction<KtSuperExpression>? {
val superExpression = diagnostic.psiElement as? KtSuperExpression ?: return null
val qualifiedExpression = superExpression.getQualifiedExpressionForReceiver() ?: return null
val selectorExpression = qualifiedExpression.selectorExpression ?: return null
val containingClassOrObject = superExpression.getStrictParentOfType<KtClassOrObject>() ?: return null
val superTypeListEntries = containingClassOrObject.superTypeListEntries
if (superTypeListEntries.isEmpty()) return null
val context = superExpression.analyze(BodyResolveMode.PARTIAL)
val superTypes = superTypeListEntries.mapNotNull {
val typeReference = it.typeReference ?: return@mapNotNull null
val typeElement = it.typeReference?.typeElement ?: return@mapNotNull null
val kotlinType = context[BindingContext.TYPE, typeReference] ?: return@mapNotNull null
typeElement to kotlinType
}
if (superTypes.size != superTypeListEntries.size) return null
val psiFactory = KtPsiFactory(superExpression)
val superTypesForSuperExpression = superTypes.mapNotNull { (typeElement, kotlinType) ->
if (superTypes.any { it.second != kotlinType && it.second.isSubtypeOf(kotlinType) }) return@mapNotNull null
val fqName = kotlinType.fqName ?: return@mapNotNull null
val fqNameAsString = fqName.asString()
val name = if (typeElement.text.startsWith(fqNameAsString)) fqNameAsString else fqName.shortName().asString()
val newQualifiedExpression = psiFactory.createExpressionByPattern("super<$name>.$0", selectorExpression, reformat = false)
val newContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, context)
if (newQualifiedExpression.getResolvedCall(newContext)?.resultingDescriptor == null) return@mapNotNull null
if (newContext.diagnostics.noSuppression().forElement(newQualifiedExpression).isNotEmpty()) return@mapNotNull null
name
}
if (superTypesForSuperExpression.isEmpty()) return null
return SpecifySuperTypeFix(superExpression, superTypesForSuperExpression)
}
}
}
| apache-2.0 | 9c80d3e833124dc0ae19309cb9be305a | 52.345794 | 158 | 0.71794 | 5.685259 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNamesToCallArgumentsIntention.kt | 1 | 2548 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.idea.base.psi.textRangeIn
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedIntention
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicabilityRanges
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddArgumentNamesApplicators
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtValueArgument
internal class AddNamesToCallArgumentsIntention :
AbstractKotlinApplicatorBasedIntention<KtCallElement, AddArgumentNamesApplicators.MultipleArgumentsInput>(KtCallElement::class) {
override fun getApplicator() =
AddArgumentNamesApplicators.multipleArgumentsApplicator
override fun getApplicabilityRange() = applicabilityRanges { element: KtCallElement ->
// Note: Applicability range matches FE 1.0 (see AddNamesToCallArgumentsIntention).
val calleeExpression = element.calleeExpression ?: return@applicabilityRanges emptyList()
val calleeExpressionTextRange = calleeExpression.textRangeIn(element)
val arguments = element.valueArguments
if (arguments.size < 2) {
listOf(calleeExpressionTextRange)
} else {
val firstArgument = arguments.firstOrNull() as? KtValueArgument ?: return@applicabilityRanges emptyList()
val endOffset = firstArgument.textRangeIn(element).endOffset
listOf(TextRange(calleeExpressionTextRange.startOffset, endOffset))
}
}
override fun getInputProvider() = inputProvider { element: KtCallElement ->
val resolvedCall = element.resolveCall().singleFunctionCallOrNull() ?: return@inputProvider null
if (!resolvedCall.symbol.hasStableParameterNames) {
return@inputProvider null
}
val arguments = element.valueArgumentList?.arguments ?: return@inputProvider null
AddArgumentNamesApplicators.MultipleArgumentsInput(arguments.associateWith {
getArgumentNameIfCanBeUsedForCalls(it, resolvedCall) ?: return@inputProvider null
})
}
} | apache-2.0 | dae030a39a6d816d2e1eb6c627a613f1 | 53.234043 | 158 | 0.777865 | 5.364211 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/dsl/State.kt | 1 | 7491 | package org.snakeskin.dsl
import org.snakeskin.executor.ExceptionHandlingRunnable
import org.snakeskin.measure.Seconds
import org.snakeskin.measure.time.TimeMeasureSeconds
import org.snakeskin.state.*
import org.snakeskin.state.StateMachine
import org.snakeskin.subsystem.States
/**
* @author Cameron Earle
* @version 8/16/17
*/
@DslMarker
annotation class DslMarkerState
@DslMarkerState
class StateMachineBuilder<T> {
internal val machine = StateMachine<T>()
/**
* Checks if the machine is in the state given
* @param state The state to check
* @return true if the machine is in the state, false otherwise
*/
fun isInState(state: T) = machine.isInState(state)
/**
* Checks if the machine was in the state given
* @param state The state to check
* @return true if the machine was in the state, false otherwise
*/
fun wasInState(state: T) = machine.wasInState(state)
/**
* Rejects all of the given states if the condition is met
* @param states The states to reject
* @param condition The condition to reject on
*/
fun rejectAllIf(vararg states: T, condition: () -> Boolean) {
machine.addGlobalRejection(states.toList(), condition)
}
/**
* Adds a state to the state machine
* @param state The name of the state to add
* @param setup The function responsible for building the state. @see MutableStateBuilder
*/
fun state(state: T, setup: MutableStateBuilder<T>.() -> Unit) {
val stateBuilder = MutableStateBuilder(state, machine)
stateBuilder.setup()
machine.addState(stateBuilder.state)
}
/**
* Adds the "disabled" state to the machine
* @see state
*/
fun disabled(setup: StateBuilder<String>.() -> Unit) {
val stateBuilder = StateBuilder(States.DISABLED, machine)
stateBuilder.setup()
machine.addState(stateBuilder.state)
}
}
/**
* Builds a State object
*/
@DslMarkerState
open class StateBuilder<T>(name: T, private val machine: StateMachine<*>) {
@DslMarkerState
object Context
@DslMarkerState
inner class ActionContext(val async: Boolean) {
/**
* Sets the state of this machine
* @param state The state to set
*/
fun setState(state: T) = [email protected](state as Any, async)
/**
* Sets the machine to the disabled state
*/
fun disable() = [email protected](async)
/**
* Sets the machine to the state it was last in
*/
fun back() = [email protected](async)
}
internal val state = State(name)
/**
* Adds the entry method to the state
* @param entryBlock The function to run on the state's entry
*/
fun entry(entryBlock: Context.() -> Unit) {
val context = Context
state.entry = ExceptionHandlingRunnable { context.entryBlock() }
}
/**
* Adds the action method to the state
* @param rate The rate, in ms, to run the action loop at
* @param actionBlock The function to run on the state's loop
*/
fun action(rate: TimeMeasureSeconds = TimeMeasureSeconds(0.02), actionBlock: ActionContext.() -> Unit) {
val context = ActionContext(false)
state.actionManager = DefaultStateActionManager({ context.actionBlock() }, rate)
}
/**
* Adds a "real-time" action method to the state. This action will be run on a real time executor instead of the default
* @param executorName The name of the real-time executor to use. If not provided, the default RT executor is used
* @param rtActionBlock The function to run on the state's loop. The first parameter is the timestamp, the second is the dt
*/
fun rtAction(executorName: String? = null, rtActionBlock: ActionContext.(timestamp: TimeMeasureSeconds, dt: TimeMeasureSeconds) -> Unit) {
val context = ActionContext(true)
state.actionManager = RealTimeStateActionManager({ t, d -> context.rtActionBlock(t, d) }, executorName, state.name.toString())
}
/**
* Adds a ticked action method to the state. This action will check the given condition,
* and if it evaluates to true for the given time threshold, then the action block will be executed
* @param timeThreshold The amount of time the condition must evaluate to true for before the action runs
* @param condition The condition to check. Must return a boolean.
* @param actionBlock The function to run once the condition has evaluated to true. This function will run continuously after this.
* @param rate The rate at which to check the condition and execute the loop at. Defaults to 20 milliseconds.
*/
fun tickedAction(timeThreshold: TimeMeasureSeconds, condition: () -> Boolean, actionBlock: ActionContext.() -> Unit, rate: TimeMeasureSeconds = TimeMeasureSeconds(0.02)) {
val context = ActionContext(false)
state.actionManager = TickedActionManager(condition, { context.actionBlock() }, timeThreshold, rate)
}
/**
* Adds the exit method to the state
* @param exitBlock The function to run on the state's exit
*/
fun exit(exitBlock: Context.() -> Unit) {
val context = Context
state.exit = ExceptionHandlingRunnable { context.exitBlock() }
}
}
/**
* Adds functionality to the StateBuilder, with certain special functions that can't be used in default or disabled states
*/
@DslMarkerState
class MutableStateBuilder<T>(name: T, val machine: StateMachine<T>): StateBuilder<T>(name, machine) {
@DslMarkerState
inner class RejectContext {
/**
* Checks if the machine is in the state given
* @param state The state to check
* @return true if the machine is in the state, false otherwise
*/
fun isInState(state: T) = [email protected](state)
/**
* Checks if the machine was in the state given
* @param state The state to check
* @return true if the machine was in the state, false otherwise
*/
fun wasInState(state: T) = [email protected](state)
}
/**
* Adds rejection conditions for this state.
* @param condition The function to run to check the conditions. Should return true if the state change should be rejected
*/
fun rejectIf(condition: RejectContext.() -> Boolean) {
val context = RejectContext()
state.rejectionConditions = { context.condition() }
}
/**
* Sets up the timeout for this state
* @param timeout The time to wait for the timeout
* @param timeoutTo The name of the state to timeout to
*/
fun timeout(timeout: TimeMeasureSeconds, timeoutTo: T) {
state.timeout = timeout
state.timeoutTo = timeoutTo as Any
}
/**
* Sets out the timeout for this state to transition to disabled
* @param timeout The time to wait for the timeout
*/
fun timeoutToDisabled(timeout: TimeMeasureSeconds) {
state.timeout = timeout
state.timeoutTo = States.DISABLED
}
}
/**
* Creates a map that forces the input type S and output type V, which mapOf doesn't
* Essentially makes type inference work in command machines
*/
fun <S, V> stateMap(vararg pairs: Pair<S, V>): Map<S, V> {
return mapOf(*pairs)
} | gpl-3.0 | 3c1e092c003e08557918900c75647b6b | 35.546341 | 175 | 0.66947 | 4.432544 | false | false | false | false |
androidstarters/androidstarters.com | templates/buffer-clean-architecture-components-kotlin/presentation/src/main/java/org/buffer/android/boilerplate/presentation/browse/BrowseBufferoosViewModel.kt | 1 | 1786 | package <%= appPackage %>.presentation.browse
import android.arch.lifecycle.LiveData
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import io.reactivex.subscribers.DisposableSubscriber
import <%= appPackage %>.domain.interactor.browse.GetBufferoos
import <%= appPackage %>.domain.model.Bufferoo
import <%= appPackage %>.presentation.data.Resource
import <%= appPackage %>.presentation.data.ResourceState
import <%= appPackage %>.presentation.mapper.BufferooMapper
import <%= appPackage %>.presentation.model.BufferooView
import javax.inject.Inject
open class BrowseBufferoosViewModel @Inject internal constructor(
private val getBufferoos: GetBufferoos,
private val bufferooMapper: BufferooMapper) : ViewModel() {
private val bufferoosLiveData: MutableLiveData<Resource<List<BufferooView>>> =
MutableLiveData()
init {
fetchBufferoos()
}
override fun onCleared() {
getBufferoos.dispose()
super.onCleared()
}
fun getBufferoos(): LiveData<Resource<List<BufferooView>>> {
return bufferoosLiveData
}
fun fetchBufferoos() {
bufferoosLiveData.postValue(Resource(ResourceState.LOADING, null, null))
return getBufferoos.execute(BufferooSubscriber())
}
inner class BufferooSubscriber: DisposableSubscriber<List<Bufferoo>>() {
override fun onComplete() { }
override fun onNext(t: List<Bufferoo>) {
bufferoosLiveData.postValue(Resource(ResourceState.SUCCESS,
t.map { bufferooMapper.mapToView(it) }, null))
}
override fun onError(exception: Throwable) {
bufferoosLiveData.postValue(Resource(ResourceState.ERROR, null, exception.message))
}
}
} | mit | f11b39204feb7d3def67ab0ba3525e1d | 31.490909 | 95 | 0.709966 | 5.117479 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/CastExpressionFix.kt | 2 | 3625 | // 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.quickfix
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ErrorsJvm
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.asFlexibleType
import org.jetbrains.kotlin.types.isDefinitelyNotNullType
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.makeNullable
class CastExpressionFix(element: KtExpression, type: KotlinType) : KotlinQuickFixAction<KtExpression>(element), LowPriorityAction {
private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_TYPES_WITH_SHORT_NAMES.renderType(type)
private val typeSourceCode = IdeDescriptorRenderers.SOURCE_CODE_TYPES.renderType(type).let {
if (type.isDefinitelyNotNullType) "($it)" else it
}
private val upOrDownCast: Boolean = run {
val expressionType = element.analyze(BodyResolveMode.PARTIAL).getType(element)
expressionType != null && (type.isSubtypeOf(expressionType) || expressionType.isSubtypeOf(type))
&& expressionType != type.makeNullable() //covered by AddExclExclCallFix
}
override fun getFamilyName() = KotlinBundle.message("fix.cast.expression.family")
override fun getText() = element?.let { KotlinBundle.message("fix.cast.expression.text", it.text, typePresentation) } ?: ""
override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = upOrDownCast
public override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val expressionToInsert = KtPsiFactory(file).createExpressionByPattern("$0 as $1", element, typeSourceCode)
val newExpression = element.replaced(expressionToInsert)
ShortenReferences.DEFAULT.process((KtPsiUtil.safeDeparenthesize(newExpression) as KtBinaryExpressionWithTypeRHS).right!!)
editor?.caretModel?.moveToOffset(newExpression.endOffset)
}
abstract class Factory : KotlinSingleIntentionActionFactoryWithDelegate<KtExpression, KotlinType>(IntentionActionPriority.LOW) {
override fun getElementOfInterest(diagnostic: Diagnostic) = diagnostic.psiElement as? KtExpression
override fun createFix(originalElement: KtExpression, data: KotlinType) = CastExpressionFix(originalElement, data)
}
object SmartCastImpossibleFactory : Factory() {
override fun extractFixData(element: KtExpression, diagnostic: Diagnostic) = Errors.SMARTCAST_IMPOSSIBLE.cast(diagnostic).a
}
object GenericVarianceConversion : Factory() {
override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): KotlinType {
return ErrorsJvm.JAVA_TYPE_MISMATCH.cast(diagnostic).b.asFlexibleType().upperBound
}
}
}
| apache-2.0 | 5752c947c21ba77cd4047e53f007681b | 54.769231 | 132 | 0.785103 | 4.826897 | false | false | false | false |
abertschi/ad-free | app/src/main/java/ch/abertschi/adfree/detector/UserDefinedTextDetector.kt | 1 | 2357 | package ch.abertschi.adfree.detector
import android.app.Notification
import android.os.Bundle
import ch.abertschi.adfree.model.TextRepository
import ch.abertschi.adfree.model.TextRepositoryData
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.warn
import java.util.*
class UserDefinedTextDetector(private val repo: TextRepository) : AdDetectable, AnkoLogger {
override fun canHandle(payload: AdPayload): Boolean {
var notificationKey: String? =
payload?.statusbarNotification?.key?.toLowerCase() ?: return false
var canHandle = false;
for (entry in repo.getAllEntries()) {
val key = entry.packageName
if (key.isEmpty() || key.isBlank()) {
continue
}
if (notificationKey?.contains(key.toLowerCase().trim()) == true) {
payload.matchedTextDetectorEntries.add(entry)
canHandle = true;
}
}
return canHandle
}
private fun extractString(extras: Bundle?, s: String): String? {
return try {
(extras?.get(s) as CharSequence?)
?.toString()?.trim()?.toLowerCase()
} catch (e: Exception) {
warn { e }
null
}
}
override fun flagAsAdvertisement(payload: AdPayload): Boolean {
val extras = payload.statusbarNotification?.notification?.extras
val title = extractString(extras, Notification.EXTRA_TITLE)
val subTitle = extractString(extras, Notification.EXTRA_SUB_TEXT)
for (entry in payload.matchedTextDetectorEntries) {
for (entryLine in entry.content) {
if (entryLine.trim().isEmpty()) {
continue
}
val matchTitle = title != null && title.contains(entryLine.trim().toLowerCase())
val matchSubtitle =
subTitle != null && subTitle.contains(entryLine.trim().toLowerCase())
if (matchTitle || matchSubtitle) {
return true;
}
}
}
return false;
}
override fun getMeta(): AdDetectorMeta = AdDetectorMeta(
"User defined text", "flag a notification based on the presence of text",
false,
category = "General",
debugOnly = false
)
}
| apache-2.0 | 210c1ee6972466ea1287bcda172c73d0 | 33.661765 | 96 | 0.593127 | 4.849794 | false | false | false | false |
CzBiX/v2ex-android | app/src/main/kotlin/com/czbix/v2ex/db/Comment.kt | 1 | 2471 | package com.czbix.v2ex.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.czbix.v2ex.model.Ignorable
import com.czbix.v2ex.model.Thankable
import com.czbix.v2ex.network.RequestHelper
@Entity
data class Comment(
@PrimaryKey
val id: Int,
@ColumnInfo(index = true)
val topicId: Int,
val page: Int,
val content: String,
val username: String,
val addAt: String,
val thanks: Int,
val floor: Int,
val thanked: Boolean
) : Thankable, Ignorable {
override fun getIgnoreUrl(): String {
return String.format("%s/ignore/reply/%d", RequestHelper.BASE_URL, id)
}
override fun getThankUrl(): String {
return String.format("%s/thank/reply/%d", RequestHelper.BASE_URL, id)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Comment
if (id != other.id) return false
if (topicId != other.topicId) return false
if (page != other.page) return false
if (content != other.content) return false
if (username != other.username) return false
if (addAt != other.addAt) return false
if (thanks != other.thanks) return false
if (floor != other.floor) return false
if (thanked != other.thanked) return false
return true
}
override fun hashCode(): Int {
var result = id
result = 31 * result + topicId
result = 31 * result + page
result = 31 * result + content.hashCode()
result = 31 * result + username.hashCode()
result = 31 * result + addAt.hashCode()
result = 31 * result + thanks
result = 31 * result + floor
result = 31 * result + thanked.hashCode()
return result
}
class Builder {
var topicId: Int = 0
var id: Int = 0
var page: Int = 0
lateinit var content: String
lateinit var username: String
lateinit var addAt: String
var thanks: Int = 0
var floor: Int = 0
var thanked: Boolean = false
fun build(): Comment {
check(topicId > 0)
check(id > 0)
check(floor > 0)
check(page > 0)
return Comment(id, topicId, page, content, username, addAt, thanks, floor, thanked)
}
}
}
| apache-2.0 | 7207077ca73ca0affd1bd673cd3dc5d7 | 28.070588 | 95 | 0.587616 | 4.152941 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-darwin-legacy/darwin/src/io/ktor/client/engine/darwin/internal/DarwinLegacySession.kt | 1 | 2066 | package io.ktor.client.engine.darwin.internal
import io.ktor.client.engine.darwin.*
import io.ktor.client.request.*
import io.ktor.util.*
import io.ktor.utils.io.core.*
import kotlinx.atomicfu.*
import kotlinx.cinterop.*
import kotlinx.coroutines.*
import platform.Foundation.*
import kotlin.coroutines.*
@OptIn(UnsafeNumber::class)
internal class DarwinLegacySession(
private val config: DarwinLegacyClientEngineConfig,
private val requestQueue: NSOperationQueue
) : Closeable {
private val closed = atomic(false)
private val sessionAndDelegate = config.sessionAndDelegate ?: createSession(config, requestQueue)
private val session = sessionAndDelegate.first
private val delegate = sessionAndDelegate.second
@OptIn(InternalAPI::class)
internal suspend fun execute(request: HttpRequestData, callContext: CoroutineContext): HttpResponseData {
val nativeRequest = request.toNSUrlRequest()
.apply(config.requestConfig)
val task = session.dataTaskWithRequest(nativeRequest)
val response = delegate.read(request, callContext, task)
task.resume()
try {
return response.await()
} catch (cause: Throwable) {
if (task.state == NSURLSessionTaskStateRunning) task.cancel()
throw cause
}
}
override fun close() {
if (!closed.compareAndSet(false, true)) return
session.finishTasksAndInvalidate()
}
}
@OptIn(UnsafeNumber::class)
internal fun createSession(
config: DarwinLegacyClientEngineConfig,
requestQueue: NSOperationQueue
): Pair<NSURLSession, KtorLegacyNSURLSessionDelegate> {
val configuration = NSURLSessionConfiguration.defaultSessionConfiguration().apply {
setupProxy(config)
setHTTPCookieStorage(null)
config.sessionConfig(this)
}
val delegate = KtorLegacyNSURLSessionDelegate(config.challengeHandler)
return NSURLSession.sessionWithConfiguration(
configuration,
delegate,
delegateQueue = requestQueue
) to delegate
}
| apache-2.0 | 188cf32c7a21c626b3daf917bf302ff7 | 30.784615 | 109 | 0.722168 | 4.738532 | false | true | false | false |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/addedittask/AddEditTaskActionProcessorHolder.kt | 1 | 5848 | package com.example.android.architecture.blueprints.todoapp.addedittask
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskAction.CreateTaskAction
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskAction.PopulateTaskAction
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskAction.UpdateTaskAction
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskResult.CreateTaskResult
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskResult.PopulateTaskResult
import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskResult.UpdateTaskResult
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import com.example.android.architecture.blueprints.todoapp.mvibase.MviAction
import com.example.android.architecture.blueprints.todoapp.mvibase.MviResult
import com.example.android.architecture.blueprints.todoapp.mvibase.MviViewModel
import com.example.android.architecture.blueprints.todoapp.util.schedulers.BaseSchedulerProvider
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
/**
* Contains and executes the business logic for all emitted [MviAction]
* and returns one unique [Observable] of [MviResult].
*
*
* This could have been included inside the [MviViewModel]
* but was separated to ease maintenance, as the [MviViewModel] was getting too big.
*/
class AddEditTaskActionProcessorHolder(
private val tasksRepository: TasksRepository,
private val schedulerProvider: BaseSchedulerProvider
) {
private val populateTaskProcessor =
ObservableTransformer<PopulateTaskAction, PopulateTaskResult> { actions ->
actions.flatMap { action ->
tasksRepository.getTask(action.taskId)
// Transform the Single to an Observable to allow emission of multiple
// events down the stream (e.g. the InFlight event)
.toObservable()
// Wrap returned data into an immutable object
.map(PopulateTaskResult::Success)
.cast(PopulateTaskResult::class.java)
// Wrap any error into an immutable object and pass it down the stream
// without crashing.
// Because errors are data and hence, should just be part of the stream.
.onErrorReturn(PopulateTaskResult::Failure)
.subscribeOn(schedulerProvider.io())
.observeOn(schedulerProvider.ui())
// Emit an InFlight event to notify the subscribers (e.g. the UI) we are
// doing work and waiting on a response.
// We emit it after observing on the UI thread to allow the event to be emitted
// on the current frame and avoid jank.
.startWith(PopulateTaskResult.InFlight)
}
}
private val createTaskProcessor =
ObservableTransformer<CreateTaskAction, CreateTaskResult> { actions ->
actions
.map { action -> Task(title = action.title, description = action.description) }
.publish { task ->
Observable.merge(
task.filter(Task::empty).map { CreateTaskResult.Empty },
task.filter { !it.empty }.flatMap {
tasksRepository.saveTask(it).andThen(Observable.just(CreateTaskResult.Success))
}
)
}
}
private val updateTaskProcessor =
ObservableTransformer<UpdateTaskAction, UpdateTaskResult> { actions ->
actions.flatMap { action ->
tasksRepository.saveTask(
Task(title = action.title, description = action.description, id = action.taskId)
).andThen(Observable.just(UpdateTaskResult))
}
}
/**
* Splits the [Observable] to match each type of [MviAction] to
* its corresponding business logic processor. Each processor takes a defined [MviAction],
* returns a defined [MviResult]
* The global actionProcessor then merges all [Observable] back to
* one unique [Observable].
*
*
* The splitting is done using [Observable.publish] which allows almost anything
* on the passed [Observable] as long as one and only one [Observable] is returned.
*
*
* An security layer is also added for unhandled [MviAction] to allow early crash
* at runtime to easy the maintenance.
*/
internal var actionProcessor =
ObservableTransformer<AddEditTaskAction, AddEditTaskResult> { actions ->
actions.publish { shared ->
Observable.merge<AddEditTaskResult>(
// Match PopulateTasks to populateTaskProcessor
shared.ofType(AddEditTaskAction.PopulateTaskAction::class.java)
.compose(populateTaskProcessor),
// Match CreateTasks to createTaskProcessor
shared.ofType(AddEditTaskAction.CreateTaskAction::class.java)
.compose(createTaskProcessor),
// Match UpdateTasks to updateTaskProcessor
shared.ofType(AddEditTaskAction.UpdateTaskAction::class.java)
.compose(updateTaskProcessor))
.mergeWith(
// Error for not implemented actions
shared.filter { v ->
v !is AddEditTaskAction.PopulateTaskAction &&
v !is AddEditTaskAction.CreateTaskAction &&
v !is AddEditTaskAction.UpdateTaskAction
}
.flatMap { w ->
Observable.error<AddEditTaskResult>(
IllegalArgumentException("Unknown Action type: " + w))
})
}
}
}
| apache-2.0 | 266831304cb7edcf931afd51f0fd01fb | 48.142857 | 107 | 0.680062 | 5.107424 | false | false | false | false |
cmzy/okhttp | okhttp/src/main/kotlin/okhttp3/internal/http2/Http2.kt | 2 | 5227 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.internal.http2
import okhttp3.internal.format
import okio.ByteString.Companion.encodeUtf8
object Http2 {
@JvmField
val CONNECTION_PREFACE = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".encodeUtf8()
/** The initial max frame size, applied independently writing to, or reading from the peer. */
const val INITIAL_MAX_FRAME_SIZE = 0x4000 // 16384
const val TYPE_DATA = 0x0
const val TYPE_HEADERS = 0x1
const val TYPE_PRIORITY = 0x2
const val TYPE_RST_STREAM = 0x3
const val TYPE_SETTINGS = 0x4
const val TYPE_PUSH_PROMISE = 0x5
const val TYPE_PING = 0x6
const val TYPE_GOAWAY = 0x7
const val TYPE_WINDOW_UPDATE = 0x8
const val TYPE_CONTINUATION = 0x9
const val FLAG_NONE = 0x0
const val FLAG_ACK = 0x1 // Used for settings and ping.
const val FLAG_END_STREAM = 0x1 // Used for headers and data.
const val FLAG_END_HEADERS = 0x4 // Used for headers and continuation.
const val FLAG_END_PUSH_PROMISE = 0x4
const val FLAG_PADDED = 0x8 // Used for headers and data.
const val FLAG_PRIORITY = 0x20 // Used for headers.
const val FLAG_COMPRESSED = 0x20 // Used for data.
/** Lookup table for valid frame types. */
private val FRAME_NAMES = arrayOf(
"DATA", "HEADERS", "PRIORITY", "RST_STREAM", "SETTINGS", "PUSH_PROMISE", "PING", "GOAWAY",
"WINDOW_UPDATE", "CONTINUATION"
)
/**
* Lookup table for valid flags for DATA, HEADERS, CONTINUATION. Invalid combinations are
* represented in binary.
*/
private val FLAGS = arrayOfNulls<String>(0x40) // Highest bit flag is 0x20.
private val BINARY = Array(256) {
format("%8s", Integer.toBinaryString(it)).replace(' ', '0')
}
init {
FLAGS[FLAG_NONE] = ""
FLAGS[FLAG_END_STREAM] = "END_STREAM"
val prefixFlags = intArrayOf(FLAG_END_STREAM)
FLAGS[FLAG_PADDED] = "PADDED"
for (prefixFlag in prefixFlags) {
FLAGS[prefixFlag or FLAG_PADDED] = FLAGS[prefixFlag] + "|PADDED"
}
FLAGS[FLAG_END_HEADERS] = "END_HEADERS" // Same as END_PUSH_PROMISE.
FLAGS[FLAG_PRIORITY] = "PRIORITY" // Same as FLAG_COMPRESSED.
FLAGS[FLAG_END_HEADERS or FLAG_PRIORITY] = "END_HEADERS|PRIORITY" // Only valid on HEADERS.
val frameFlags = intArrayOf(FLAG_END_HEADERS, FLAG_PRIORITY, FLAG_END_HEADERS or FLAG_PRIORITY)
for (frameFlag in frameFlags) {
for (prefixFlag in prefixFlags) {
FLAGS[prefixFlag or frameFlag] = FLAGS[prefixFlag] + '|'.toString() + FLAGS[frameFlag]
FLAGS[prefixFlag or frameFlag or FLAG_PADDED] =
FLAGS[prefixFlag] + '|'.toString() + FLAGS[frameFlag] + "|PADDED"
}
}
for (i in FLAGS.indices) { // Fill in holes with binary representation.
if (FLAGS[i] == null) FLAGS[i] = BINARY[i]
}
}
/**
* Returns human-readable representation of HTTP/2 frame headers.
*
* The format is:
*
* ```
* direction streamID length type flags
* ```
*
* Where direction is `<<` for inbound and `>>` for outbound.
*
* For example, the following would indicate a HEAD request sent from the client.
* ```
* `<< 0x0000000f 12 HEADERS END_HEADERS|END_STREAM
* ```
*/
fun frameLog(
inbound: Boolean,
streamId: Int,
length: Int,
type: Int,
flags: Int
): String {
val formattedType = formattedType(type)
val formattedFlags = formatFlags(type, flags)
val direction = if (inbound) "<<" else ">>"
return format("%s 0x%08x %5d %-13s %s",
direction, streamId, length, formattedType, formattedFlags)
}
internal fun formattedType(type: Int): String =
if (type < FRAME_NAMES.size) FRAME_NAMES[type] else format("0x%02x", type)
/**
* Looks up valid string representing flags from the table. Invalid combinations are represented
* in binary.
*/
// Visible for testing.
fun formatFlags(type: Int, flags: Int): String {
if (flags == 0) return ""
when (type) {
// Special case types that have 0 or 1 flag.
TYPE_SETTINGS, TYPE_PING -> return if (flags == FLAG_ACK) "ACK" else BINARY[flags]
TYPE_PRIORITY, TYPE_RST_STREAM, TYPE_GOAWAY, TYPE_WINDOW_UPDATE -> return BINARY[flags]
}
val result = if (flags < FLAGS.size) FLAGS[flags]!! else BINARY[flags]
// Special case types that have overlap flag values.
return when {
type == TYPE_PUSH_PROMISE && flags and FLAG_END_PUSH_PROMISE != 0 -> {
result.replace("HEADERS", "PUSH_PROMISE") // TODO: Avoid allocation.
}
type == TYPE_DATA && flags and FLAG_COMPRESSED != 0 -> {
result.replace("PRIORITY", "COMPRESSED") // TODO: Avoid allocation.
}
else -> result
}
}
}
| apache-2.0 | c5621ed803dbb33ec02ba5f7567738e7 | 34.080537 | 99 | 0.660991 | 3.572796 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/volumes/Volume.kt | 1 | 28912 | @file:Suppress("DEPRECATION")
package graphics.scenery.volumes
import bdv.BigDataViewer
import bdv.ViewerImgLoader
import bdv.cache.CacheControl
import bdv.spimdata.SpimDataMinimal
import bdv.spimdata.WrapBasicImgLoader
import bdv.spimdata.XmlIoSpimDataMinimal
import bdv.tools.brightness.ConverterSetup
import bdv.util.AxisOrder
import bdv.util.AxisOrder.DEFAULT
import bdv.util.RandomAccessibleIntervalSource
import bdv.util.RandomAccessibleIntervalSource4D
import bdv.util.volatiles.VolatileView
import bdv.util.volatiles.VolatileViewData
import bdv.viewer.DisplayMode
import bdv.viewer.Source
import bdv.viewer.SourceAndConverter
import bdv.viewer.state.ViewerState
import graphics.scenery.DefaultNode
import graphics.scenery.DisableFrustumCulling
import graphics.scenery.Hub
import graphics.scenery.Origin
import graphics.scenery.attribute.DelegationType
import graphics.scenery.attribute.geometry.DelegatesGeometry
import graphics.scenery.attribute.geometry.Geometry
import graphics.scenery.attribute.material.DelegatesMaterial
import graphics.scenery.attribute.material.Material
import graphics.scenery.attribute.renderable.DelegatesRenderable
import graphics.scenery.attribute.renderable.Renderable
import graphics.scenery.attribute.spatial.DefaultSpatial
import graphics.scenery.attribute.spatial.HasCustomSpatial
import graphics.scenery.numerics.OpenSimplexNoise
import graphics.scenery.numerics.Random
import graphics.scenery.utils.LazyLogger
import graphics.scenery.volumes.Volume.VolumeDataSource.SpimDataMinimalSource
import io.scif.SCIFIO
import io.scif.util.FormatTools
import mpicbg.spim.data.generic.sequence.AbstractSequenceDescription
import mpicbg.spim.data.sequence.FinalVoxelDimensions
import net.imglib2.RandomAccessibleInterval
import net.imglib2.Volatile
import net.imglib2.realtransform.AffineTransform3D
import net.imglib2.type.numeric.ARGBType
import net.imglib2.type.numeric.NumericType
import net.imglib2.type.numeric.integer.*
import net.imglib2.type.numeric.real.FloatType
import org.joml.Matrix4f
import org.joml.Vector3f
import org.joml.Vector3i
import org.joml.Vector4f
import org.lwjgl.system.MemoryUtil
import org.scijava.io.location.FileLocation
import tpietzsch.example2.VolumeViewerOptions
import java.io.FileInputStream
import java.nio.ByteBuffer
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.atomic.AtomicInteger
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.properties.Delegates
import kotlin.streams.toList
@Suppress("DEPRECATION")
open class Volume(val dataSource: VolumeDataSource, val options: VolumeViewerOptions, @Transient val hub: Hub) : DefaultNode("Volume"),
DelegatesRenderable, DelegatesGeometry, DelegatesMaterial, DisableFrustumCulling, HasCustomSpatial<Volume.VolumeSpatial> {
private val delegationType: DelegationType = DelegationType.OncePerDelegate
override fun getDelegationType(): DelegationType {
return delegationType
}
override fun getDelegateRenderable(): Renderable? {
return volumeManager.renderableOrNull()
}
override fun getDelegateGeometry(): Geometry? {
return volumeManager.geometryOrNull()
}
override fun getDelegateMaterial(): Material? {
return volumeManager.materialOrNull()
}
val converterSetups = ArrayList<ConverterSetup>()
var timepointCount: Int
val viewerState: ViewerState
/** The transfer function to use for the volume. Flat by default. */
var transferFunction: TransferFunction = TransferFunction.flat(0.5f)
/** The color map for the volume. */
var colormap: Colormap = Colormap.get("viridis")
set(m) {
field = m
if(::volumeManager.isInitialized) {
volumeManager.removeCachedColormapFor(this)
}
modifiedAt = System.nanoTime()
}
/** Pixel-to-world scaling ratio. Default: 1 px = 1mm in world space*/
var pixelToWorldRatio: Float by Delegates.observable(0.001f) { property, old, new -> spatial().propertyChanged(property, old, new, "pixelToWorldRatio") }
/** What to use as the volume's origin, scenery's default is [Origin.Center], BVV's default is [Origin.FrontBottomLeft]. **/
var origin = Origin.Center
/** Rendering method */
var renderingMethod = RenderingMethod.AlphaBlending
set(value) {
field = value
volumeManager.renderingMethod = value
}
/** Plane equations for slicing planes mapped to origin */
var slicingPlaneEquations = mapOf<SlicingPlane, Vector4f>()
/** Modes how assigned slicing planes interact with the volume */
var slicingMode = SlicingMode.None
enum class SlicingMode(val id: Int){
// Volume is rendered as it is
None(0),
// Volume is cut along the assigned slicing plane and the lower half is rendered.
// For multiple slicing planes the inner hull is rendered.
Cropping(1),
// Only a slice around the slicing planes is rendered with no transparency.
Slicing(2),
// The slice around the slicing planes is rendered with no transparency
// while also the cropping rule applies for the rest of the volume.
Both(3)
}
@Transient
lateinit var volumeManager: VolumeManager
// TODO IS THIS REQUIRED??
var cacheControls = CacheControl.CacheControls()
/** Current timepoint. */
var currentTimepoint: Int = 0
get() { return viewerState.currentTimepoint }
set(value) {
viewerState.currentTimepoint = value
modifiedAt = System.nanoTime()
field = value
}
sealed class VolumeDataSource {
class SpimDataMinimalSource(val spimData : SpimDataMinimal) : VolumeDataSource()
class RAISource<T: NumericType<T>>(
val type: NumericType<T>,
val sources: List<SourceAndConverter<T>>,
val converterSetups: ArrayList<ConverterSetup>,
val numTimepoints: Int,
val cacheControl: CacheControl? = null) : VolumeDataSource()
class NullSource(val numTimepoints: Int): VolumeDataSource()
}
/**
* Enum class for selecting a rendering method.
*/
enum class RenderingMethod {
MaxProjection,
MinProjection,
AlphaBlending
}
init {
name = "Volume"
addSpatial()
when (dataSource) {
is SpimDataMinimalSource -> {
val spimData = dataSource.spimData
val seq: AbstractSequenceDescription<*, *, *> = spimData.sequenceDescription
timepointCount = seq.timePoints.size() - 1
cacheControls.addCacheControl((seq.imgLoader as ViewerImgLoader).cacheControl)
// wraps legacy image formats (e.g., TIFF) if referenced in BDV XML
WrapBasicImgLoader.wrapImgLoaderIfNecessary(spimData)
val sources = ArrayList<SourceAndConverter<*>>()
// initialises setups and converters for all channels, and creates source.
// These are then stored in [converterSetups] and [sources_].
BigDataViewer.initSetups(spimData, converterSetups, sources)
viewerState = ViewerState(sources, timepointCount)
WrapBasicImgLoader.removeWrapperIfPresent(spimData)
}
is VolumeDataSource.RAISource<*> -> {
timepointCount = dataSource.numTimepoints
// FIXME: bigdataviewer-core > 9.0.0 doesn't enjoy having 0 timepoints anymore :-(
// We tell it here to have a least one, so far no ill side effects from that
viewerState = ViewerState(dataSource.sources, max(1, timepointCount))
converterSetups.addAll(dataSource.converterSetups)
}
is VolumeDataSource.NullSource -> {
viewerState = ViewerState(emptyList(), dataSource.numTimepoints)
timepointCount = dataSource.numTimepoints
}
}
viewerState.sources.forEach { s -> s.isActive = true }
viewerState.displayMode = DisplayMode.FUSED
if (dataSource !is VolumeDataSource.NullSource) {
converterSetups.forEach {
it.color = ARGBType(Int.MAX_VALUE)
}
val vm = hub.get<VolumeManager>()
val volumes = ArrayList<Volume>(10)
if (vm != null) {
volumes.addAll(vm.nodes)
hub.remove(vm)
}
volumeManager = if (vm != null) {
hub.add(VolumeManager(hub, vm.useCompute, vm.customSegments, vm.customBindings))
} else {
hub.add(VolumeManager(hub))
}
vm?.customTextures?.forEach {
volumeManager.customTextures.add(it)
volumeManager.material().textures[it] = vm.material().textures[it]!!
}
volumeManager.add(this)
volumes.forEach {
volumeManager.add(it)
it.volumeManager = volumeManager
}
}
}
override fun createSpatial(): VolumeSpatial {
return VolumeSpatial(this)
}
/**
* Returns array of slicing plane equations for planes assigned to this volume.
*/
fun slicingArray(): FloatArray {
if (slicingPlaneEquations.size > MAX_SUPPORTED_SLICING_PLANES)
logger.warn("More than ${MAX_SUPPORTED_SLICING_PLANES} slicing planes for ${this.name} set. Ignoring additional planes.")
val fa = FloatArray(4 * MAX_SUPPORTED_SLICING_PLANES)
slicingPlaneEquations.entries.take(MAX_SUPPORTED_SLICING_PLANES).forEachIndexed { i, entry ->
fa[0+i*4] = entry.value.x
fa[1+i*4] = entry.value.y
fa[2+i*4] = entry.value.z
fa[3+i*4] = entry.value.w
}
return fa
}
/**
* Goes to the next available timepoint, returning the number of the updated timepoint.
*/
fun nextTimepoint(): Int {
return goToTimepoint(viewerState.currentTimepoint + 1)
}
/** Goes to the previous available timepoint, returning the number of the updated timepoint. */
fun previousTimepoint(): Int {
return goToTimepoint(viewerState.currentTimepoint - 1)
}
/** Goes to the [timepoint] given, returning the number of the updated timepoint. */
open fun goToTimepoint(timepoint: Int): Int {
val tp = if(timepoint == -1) {
timepointCount
} else {
timepoint
}
val current = viewerState.currentTimepoint
currentTimepoint = min(max(tp, 0), timepointCount - 1)
logger.debug("Going to timepoint ${viewerState.currentTimepoint+1} of $timepointCount")
if(current != viewerState.currentTimepoint) {
volumeManager.notifyUpdate(this)
}
modifiedAt = System.nanoTime()
return viewerState.currentTimepoint
}
/**
* Goes to the last timepoint.
*/
open fun goToLastTimepoint(): Int {
return goToTimepoint(-1)
}
/**
* Goes to the first timepoint.
*/
open fun goToFirstTimepoint(): Int {
return goToTimepoint(0)
}
fun prepareNextFrame() {
cacheControls.prepareNextFrame()
}
/**
* Returns the local scaling of the volume, taking voxel size and [pixelToWorldRatio] into account.
*/
open fun localScale(): Vector3f {
// we are using the first visible source here, which might of course change.
// TODO: Figure out a better way to do this. It might be an issue for multi-view datasets.
// TODO: are the voxel sizes determined here really not used?
// val index = viewerState.visibleSourceIndices.firstOrNull()
// var voxelSizes: VoxelDimensions = FinalVoxelDimensions("um", 1.0, 1.0, 1.0)
// if(index != null) {
// val source = viewerState.sources[index]
// voxelSizes = source.spimSource.voxelDimensions ?: voxelSizes
// }
return Vector3f(
// voxelSizes.dimension(0).toFloat() * pixelToWorldRatio,
// voxelSizes.dimension(1).toFloat() * pixelToWorldRatio,
// voxelSizes.dimension(2).toFloat() * pixelToWorldRatio
pixelToWorldRatio,
-1.0f * pixelToWorldRatio,
pixelToWorldRatio
)
}
/**
* Samples a point from the currently used volume, [uv] is the texture coordinate of the volume, [0.0, 1.0] for
* all of the components.
*
* Returns the sampled value as a [Float], or null in case nothing could be sampled.
*/
open fun sample(uv: Vector3f, interpolate: Boolean = true): Float? {
return null
}
/**
* Takes samples along the ray from [start] to [end] from the currently active volume.
* Values beyond [0.0, 1.0] for [start] and [end] will be clamped to that interval.
*
* Returns the list of samples (which might include `null` values in case a sample failed),
* as well as the delta used along the ray, or null if the start/end coordinates are invalid.
*/
open fun sampleRay(start: Vector3f, end: Vector3f): Pair<List<Float?>, Vector3f>? {
return null
}
companion object {
val setupId = AtomicInteger(0)
val scifio: SCIFIO = SCIFIO()
private val logger by LazyLogger()
@JvmStatic @JvmOverloads fun fromSpimData(
spimData: SpimDataMinimal,
hub : Hub,
options : VolumeViewerOptions = VolumeViewerOptions()
): Volume {
val ds = SpimDataMinimalSource(spimData)
return Volume(ds, options, hub)
}
@JvmStatic @JvmOverloads fun fromXML(
path: String,
hub: Hub,
options : VolumeViewerOptions = VolumeViewerOptions()
): Volume {
val spimData = XmlIoSpimDataMinimal().load(path)
val ds = SpimDataMinimalSource(spimData)
return Volume(ds, options, hub)
}
@JvmStatic @JvmOverloads fun <T: NumericType<T>> fromRAI(
img: RandomAccessibleInterval<T>,
type: T,
axisOrder: AxisOrder = DEFAULT,
name: String,
hub: Hub,
options: VolumeViewerOptions = VolumeViewerOptions()
): Volume {
val converterSetups: ArrayList<ConverterSetup> = ArrayList()
val stacks: ArrayList<RandomAccessibleInterval<T>> = AxisOrder.splitInputStackIntoSourceStacks(img, AxisOrder.getAxisOrder(axisOrder, img, false))
val sourceTransform = AffineTransform3D()
val sources: ArrayList<SourceAndConverter<T>> = ArrayList()
var numTimepoints = 1
for (stack in stacks) {
val s: Source<T>
if (stack.numDimensions() > 3) {
numTimepoints = stack.max(3).toInt() + 1
s = RandomAccessibleIntervalSource4D<T>(stack, type, sourceTransform, name)
} else {
s = RandomAccessibleIntervalSource<T>(stack, type, sourceTransform, name)
}
val source: SourceAndConverter<T> = BigDataViewer.wrapWithTransformedSource(
SourceAndConverter<T>(s, BigDataViewer.createConverterToARGB(type)))
converterSetups.add(BigDataViewer.createConverterSetup(source, setupId.getAndIncrement()))
sources.add(source)
}
@Suppress("UNCHECKED_CAST")
val cacheControl = if (img is VolatileView<*, *>) {
val viewData: VolatileViewData<T, Volatile<T>> = (img as VolatileView<T, Volatile<T>>).volatileViewData
viewData.cacheControl
} else {
null
}
val ds = VolumeDataSource.RAISource<T>(type, sources, converterSetups, numTimepoints, cacheControl)
return RAIVolume(ds, options, hub)
}
@JvmStatic @JvmOverloads fun <T: NumericType<T>> fromSourceAndConverter(
source: SourceAndConverter<T>,
type: T,
name: String,
hub: Hub,
options: VolumeViewerOptions = VolumeViewerOptions()
): Volume {
val converterSetups: ArrayList<ConverterSetup> = ArrayList()
val sources = arrayListOf(source)
val numTimepoints = 1
val img = source.spimSource.getSource(0, 0)
@Suppress("UNCHECKED_CAST")
val cacheControl = if (img is VolatileView<*, *>) {
val viewData: VolatileViewData<T, Volatile<T>> = (img as VolatileView<T, Volatile<T>>).volatileViewData
viewData.cacheControl
} else {
null
}
val ds = VolumeDataSource.RAISource<T>(type, sources, converterSetups, numTimepoints, cacheControl)
val volume = RAIVolume(ds, options, hub)
volume.name = name
return volume
}
@Deprecated("Please use the version that takes List<Timepoint> as input instead of this one.")
@JvmStatic @JvmOverloads fun <T: NumericType<T>> fromBuffer(
volumes: LinkedHashMap<String, ByteBuffer>,
width: Int,
height: Int,
depth: Int,
type: T,
hub: Hub,
voxelDimensions: FloatArray = floatArrayOf(1.0f, 1.0f, 1.0f),
voxelUnit: String = "um",
options: VolumeViewerOptions = VolumeViewerOptions()
): BufferedVolume {
val list = CopyOnWriteArrayList<BufferedVolume.Timepoint>()
volumes.forEach {
list.add(BufferedVolume.Timepoint(it.key, it.value))
}
return fromBuffer(list, width, height, depth, type, hub, voxelDimensions, voxelUnit, options)
}
@JvmStatic @JvmOverloads fun <T: NumericType<T>> fromBuffer(
volumes: List<BufferedVolume.Timepoint>,
width: Int,
height: Int,
depth: Int,
type: T,
hub: Hub,
voxelDimensions: FloatArray = floatArrayOf(1.0f, 1.0f, 1.0f),
voxelUnit: String = "um",
options: VolumeViewerOptions = VolumeViewerOptions()
): BufferedVolume {
val converterSetups: ArrayList<ConverterSetup> = ArrayList()
val sources: ArrayList<SourceAndConverter<T>> = ArrayList()
val timepoints = CopyOnWriteArrayList<BufferedVolume.Timepoint>(volumes)
val s = BufferSource(timepoints, width, height, depth, FinalVoxelDimensions(voxelUnit, *(voxelDimensions.map { it.toDouble() }.toDoubleArray())), "", type)
val source: SourceAndConverter<T> = BigDataViewer.wrapWithTransformedSource(
SourceAndConverter<T>(s, BigDataViewer.createConverterToARGB(type)))
converterSetups.add(BigDataViewer.createConverterSetup(source, setupId.getAndIncrement()))
sources.add(source)
val ds = VolumeDataSource.RAISource<T>(type, sources, converterSetups, volumes.size)
return BufferedVolume(ds, options, hub)
}
/**
* Generates a procedural volume based on the open simplex noise algorithm, with [size]^3 voxels.
* [radius] sets the blob radius, while [shift] can be used to move through the continuous noise
* volume, essentially offsetting the volume by the value given. [intoBuffer] can be used to
* funnel the data into a pre-existing buffer, otherwise one will be allocated. [seed] can be
* used to choose a seed for the PRNG.
*
* Returns the newly-allocated [ByteBuffer], or the one given in [intoBuffer], set to position 0.
*/
@JvmStatic fun generateProceduralVolume(size: Long, radius: Float = 0.0f,
seed: Long = Random.randomFromRange(0.0f, 133333337.0f).toLong(),
shift: Vector3f = Vector3f(0.0f),
intoBuffer: ByteBuffer? = null, use16bit: Boolean = false): ByteBuffer {
val f = 3.0f / size
val center = size / 2.0f + 0.5f
val noise = OpenSimplexNoise(seed)
val (range, bytesPerVoxel) = if(use16bit) {
65535 to 2
} else {
255 to 1
}
val byteSize = (size*size*size*bytesPerVoxel).toInt()
val buffer = intoBuffer ?: MemoryUtil.memAlloc(byteSize * bytesPerVoxel)
// (0 until byteSize/bytesPerVoxel).chunked(byteSize/4).forEachParallel { subList ->
(0 until byteSize/bytesPerVoxel).forEach {
// subList.forEach {
val x = it.rem(size)
val y = (it / size).rem(size)
val z = it / (size * size)
val dx = center - x
val dy = center - y
val dz = center - z
val offset = abs(noise.random3D((x + shift.x()) * f, (y + shift.y()) * f, (z + shift.z()) * f))
val d = sqrt(dx * dx + dy * dy + dz * dz) / size
val result = if(radius > Math.ulp(1.0f)) {
if(d - offset < radius) { ((d-offset)*range).toInt().toShort() } else { 0 }
} else {
((d - offset) * range).toInt().toShort()
}
if(use16bit) {
buffer.asShortBuffer().put(it, result)
} else {
buffer.put(it, result.toByte())
}
// }
}
return buffer
}
/**
* Reads a volume from the given [file].
*/
@JvmStatic fun fromPath(file: Path, hub: Hub): BufferedVolume {
if(file.normalize().toString().endsWith("raw")) {
return fromPathRaw(file, hub)
}
val id = file.fileName.toString()
val reader = scifio.initializer().initializeReader(FileLocation(file.toFile()))
val dims = Vector3i()
with(reader.openPlane(0, 0)) {
dims.x = lengths[0].toInt()
dims.y = lengths[1].toInt()
dims.z = reader.getPlaneCount(0).toInt()
}
val bytesPerVoxel = reader.openPlane(0, 0).imageMetadata.bitsPerPixel/8
reader.openPlane(0, 0).imageMetadata.pixelType
val type: NumericType<*> = when(reader.openPlane(0, 0).imageMetadata.pixelType) {
FormatTools.INT8 -> ByteType()
FormatTools.INT16 -> ShortType()
FormatTools.INT32 -> IntType()
FormatTools.UINT8 -> UnsignedByteType()
FormatTools.UINT16 -> UnsignedShortType()
FormatTools.UINT32 -> UnsignedIntType()
FormatTools.FLOAT -> FloatType()
else -> {
logger.error("Unknown scif.io pixel type ${reader.openPlane(0, 0).imageMetadata.pixelType}, assuming unsigned byte.")
UnsignedByteType()
}
}
logger.debug("Loading $id from disk")
val imageData: ByteBuffer = MemoryUtil.memAlloc((bytesPerVoxel * dims.x * dims.y * dims.z))
logger.debug("${file.fileName}: Allocated ${imageData.capacity()} bytes for $type ${8*bytesPerVoxel}bit image of $dims")
val start = System.nanoTime()
// if(reader.openPlane(0, 0).imageMetadata.isLittleEndian) {
logger.debug("Volume is little endian")
(0 until reader.getPlaneCount(0)).forEach { plane ->
imageData.put(reader.openPlane(0, plane).bytes)
}
// } else {
// logger.info("Volume is big endian")
// (0 until reader.getPlaneCount(0)).forEach { plane ->
// imageData.put(swapEndianUnsafe(reader.openPlane(0, plane).bytes))
// }
// }
val duration = (System.nanoTime() - start) / 10e5
logger.debug("Reading took $duration ms")
imageData.flip()
val volumes = CopyOnWriteArrayList<BufferedVolume.Timepoint>()
volumes.add(BufferedVolume.Timepoint(id, imageData))
// TODO: Kotlin compiler issue, see https://youtrack.jetbrains.com/issue/KT-37955
return when(type) {
is ByteType -> fromBuffer(volumes, dims.x, dims.y, dims.z, ByteType(), hub)
is UnsignedByteType -> fromBuffer(volumes, dims.x, dims.y, dims.z, UnsignedByteType(), hub)
is ShortType -> fromBuffer(volumes, dims.x, dims.y, dims.z, ShortType(), hub)
is UnsignedShortType -> fromBuffer(volumes, dims.x, dims.y, dims.z, UnsignedShortType(), hub)
is IntType -> fromBuffer(volumes, dims.x, dims.y, dims.z, IntType(), hub)
is UnsignedIntType -> fromBuffer(volumes, dims.x, dims.y, dims.z, UnsignedIntType(), hub)
is FloatType -> fromBuffer(volumes, dims.x, dims.y, dims.z, FloatType(), hub)
else -> throw UnsupportedOperationException("Image type ${type.javaClass.simpleName} not supported for volume data.")
}
}
/**
* Reads raw volumetric data from a [file].
*
* Returns the new volume.
*/
@JvmStatic fun fromPathRaw(file: Path, hub: Hub): BufferedVolume {
val infoFile: Path
val volumeFiles: List<Path>
if(Files.isDirectory(file)) {
volumeFiles = Files.list(file).filter { it.toString().endsWith(".raw") && Files.isRegularFile(it) && Files.isReadable(it) }.toList()
infoFile = file.resolve("stacks.info")
} else {
volumeFiles = listOf(file)
infoFile = file.resolveSibling("stacks.info")
}
val lines = Files.lines(infoFile).toList()
logger.debug("reading stacks.info (${lines.joinToString()}) (${lines.size} lines)")
val dimensions = Vector3i(lines.get(0).split(",").map { it.toInt() }.toIntArray())
logger.debug("setting dim to ${dimensions.x}/${dimensions.y}/${dimensions.z}")
logger.debug("Got ${volumeFiles.size} volumes")
val volumes = CopyOnWriteArrayList<BufferedVolume.Timepoint>()
volumeFiles.forEach { v ->
val id = v.fileName.toString()
val buffer: ByteBuffer by lazy {
logger.debug("Loading $id from disk")
val buffer = ByteArray(1024 * 1024)
val stream = FileInputStream(v.toFile())
val imageData: ByteBuffer = MemoryUtil.memAlloc((2 * dimensions.x * dimensions.y * dimensions.z))
logger.debug("${v.fileName}: Allocated ${imageData.capacity()} bytes for UINT16 image of $dimensions")
val start = System.nanoTime()
var bytesRead = stream.read(buffer, 0, buffer.size)
while (bytesRead > -1) {
imageData.put(buffer, 0, bytesRead)
bytesRead = stream.read(buffer, 0, buffer.size)
}
val duration = (System.nanoTime() - start) / 10e5
logger.debug("Reading took $duration ms")
imageData.flip()
imageData
}
volumes.add(BufferedVolume.Timepoint(id, buffer))
}
return fromBuffer(volumes, dimensions.x, dimensions.y, dimensions.z, UnsignedShortType(), hub)
}
/** Amount of supported slicing planes per volume, see also sampling shader segments */
private const val MAX_SUPPORTED_SLICING_PLANES = 16
}
open class VolumeSpatial(val volume: Volume): DefaultSpatial(volume) {
/**
* Composes the world matrix for this volume node, taken voxel size and [pixelToWorldRatio]
* into account.
*/
override fun composeModel() {
@Suppress("SENSELESS_COMPARISON")
if(position != null && rotation != null && scale != null) {
model.translation(position)
model.mul(Matrix4f().set(this.rotation))
if(volume.origin == Origin.Center) {
model.translate(-2.0f, -2.0f, -2.0f)
}
model.scale(scale)
model.scale(volume.localScale())
}
}
}
}
| lgpl-3.0 | cda9494c074897d1bfec4c5c743ca70b | 39.436364 | 167 | 0.606876 | 4.443898 | false | false | false | false |
dimagi/commcare-android | app/unit-tests/src/org/commcare/update/UpdateWorkerTest.kt | 1 | 4510 | package org.commcare.update
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.work.ListenableWorker
import androidx.work.testing.TestListenableWorkerBuilder
import io.mockk.every
import io.mockk.mockkObject
import kotlinx.coroutines.runBlocking
import org.commcare.CommCareApplication
import org.commcare.CommCareTestApplication
import org.commcare.android.mocks.ModernHttpRequesterMock
import org.commcare.android.util.TestAppInstaller
import org.commcare.android.util.UpdateUtils
import org.commcare.preferences.ServerUrls.PREFS_APP_SERVER_KEY
import org.commcare.resources.model.InstallRequestSource
import org.commcare.network.RequestStats
import org.commcare.utils.TimeProvider
import org.hamcrest.CoreMatchers.`is`
import org.junit.Assert
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.annotation.Config
import java.io.File
import java.util.*
@Config(application = CommCareTestApplication::class)
@RunWith(AndroidJUnit4::class)
class UpdateWorkerTest {
companion object {
const val REF_BASE_DIR = "jr://resource/commcare-apps/update_tests/"
}
private lateinit var context: Context
@Before
fun setUp() {
context = ApplicationProvider.getApplicationContext()
TestAppInstaller.installAppAndLogin(
UpdateUtils.buildResourceRef(REF_BASE_DIR, "base_app", "profile.ccpr"),
"test", "123")
}
@Test
fun testValidUpdate_shouldSucceed() {
val profileRef = UpdateUtils.buildResourceRef(REF_BASE_DIR, "valid_update", "profile.ccpr")
runAndTestUpdateWorker(profileRef, ListenableWorker.Result.success())
}
@Test
fun testNoLocalStorage_shouldFail() {
// nuke local folder that CommCare uses to stage updates.
val dir = File(CommCareApplication.instance().androidFsTemp)
assertTrue(dir.delete())
val profileRef = UpdateUtils.buildResourceRef(REF_BASE_DIR, "valid_update", "profile.ccpr")
runAndTestUpdateWorker(profileRef, ListenableWorker.Result.failure())
}
@Test
fun testInvalidResource_shouldFail() {
val profileRef = UpdateUtils.buildResourceRef(REF_BASE_DIR, "invalid_update", "profile.ccpr")
runAndTestUpdateWorker(profileRef, ListenableWorker.Result.failure())
}
@Test
fun testMissingResource_shouldFail() {
val profileRef = UpdateUtils.buildResourceRef(REF_BASE_DIR, "valid_update_without_multimedia_present", "profile.ccpr")
runAndTestUpdateWorker(profileRef, ListenableWorker.Result.failure())
}
@Test
fun testIncompatibleVersion_shouldFail() {
val profileRef = UpdateUtils.buildResourceRef(REF_BASE_DIR, "invalid_version", "profile.ccpr")
runAndTestUpdateWorker(profileRef, ListenableWorker.Result.failure())
}
@Test
fun testNetworkFailure_shouldRetry() {
ModernHttpRequesterMock.setRequestPayloads(arrayOf("null", "null", "null", "null")) // should cause an IO Exception
val profileRef = UpdateUtils.buildResourceRef("https://", "fake_update", "fake.ccpr")
runAndTestUpdateWorker(profileRef, ListenableWorker.Result.retry())
}
private fun runAndTestUpdateWorker(profileRef: String, expectedResult: ListenableWorker.Result) {
setUpdatePreference(profileRef)
val worker = TestListenableWorkerBuilder<UpdateWorker>(context).build()
runBlocking {
val result = worker.doWork()
assertThat(result, `is`(expectedResult))
}
// override date to today + 100 days and check for request age
mockkObject(TimeProvider)
every { TimeProvider.getCurrentDate() } returns Date(Date().time + 100 * 24 * 60 * 60 * 1000L)
val requestAge = RequestStats.getRequestAge(
(context as CommCareApplication).currentApp,
InstallRequestSource.BACKGROUND_UPDATE)
if (expectedResult == ListenableWorker.Result.success()) {
assertEquals(RequestStats.RequestAge.LT_10, requestAge)
} else {
assertEquals(RequestStats.RequestAge.LT_120, requestAge)
}
}
private fun setUpdatePreference(profileRef: String) {
(context as CommCareApplication).currentApp.appPreferences
.edit()
.putString(PREFS_APP_SERVER_KEY, profileRef)
.apply()
}
} | apache-2.0 | 4536025f0b54386710013bc190cc3141 | 37.555556 | 126 | 0.719512 | 4.417238 | false | true | false | false |
zeapo/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/utils/PasswordRecyclerAdapter.kt | 1 | 4790 | package com.zeapo.pwdstore.utils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.view.ActionMode
import com.zeapo.pwdstore.PasswordFragment
import com.zeapo.pwdstore.PasswordStore
import com.zeapo.pwdstore.R
import java.util.ArrayList
import java.util.TreeSet
class PasswordRecyclerAdapter(private val activity: PasswordStore,
private val listener: PasswordFragment.OnFragmentInteractionListener,
values: ArrayList<PasswordItem>
) : EntryRecyclerAdapter(values) {
var actionMode: ActionMode? = null
private var canEdit: Boolean = false
private val actionModeCallback = object : ActionMode.Callback {
// Called when the action mode is created; startActionMode() was called
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
// Inflate a menu resource providing context menu items
mode.menuInflater.inflate(R.menu.context_pass, menu)
// hide the fab
activity.findViewById<View>(R.id.fab).visibility = View.GONE
return true
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
menu.findItem(R.id.menu_edit_password).isVisible = canEdit
return true // Return false if nothing is done
}
// Called when the user selects a contextual menu item
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_delete_password -> {
activity.deletePasswords(this@PasswordRecyclerAdapter, TreeSet(selectedItems))
mode.finish() // Action picked, so close the CAB
return true
}
R.id.menu_edit_password -> {
activity.editPassword(values[selectedItems.iterator().next()])
mode.finish()
return true
}
R.id.menu_move_password -> {
val selectedPasswords = ArrayList<PasswordItem>()
for (id in selectedItems) {
selectedPasswords.add(values[id])
}
activity.movePasswords(selectedPasswords)
return false
}
else -> return false
}
}
// Called when the user exits the action mode
override fun onDestroyActionMode(mode: ActionMode) {
val it = selectedItems.iterator()
while (it.hasNext()) {
// need the setSelected line in onBind
notifyItemChanged(it.next())
it.remove()
}
actionMode = null
// show the fab
activity.findViewById<View>(R.id.fab).visibility = View.VISIBLE
}
}
override fun getOnLongClickListener(holder: ViewHolder, pass: PasswordItem): View.OnLongClickListener {
return View.OnLongClickListener {
if (actionMode != null) {
return@OnLongClickListener false
}
toggleSelection(holder.adapterPosition)
canEdit = pass.type == PasswordItem.TYPE_PASSWORD
// Start the CAB using the ActionMode.Callback
actionMode = activity.startSupportActionMode(actionModeCallback)
actionMode?.title = "" + selectedItems.size
actionMode?.invalidate()
notifyItemChanged(holder.adapterPosition)
true
}
}
override fun getOnClickListener(holder: ViewHolder, pass: PasswordItem): View.OnClickListener {
return View.OnClickListener {
if (actionMode != null) {
toggleSelection(holder.adapterPosition)
actionMode?.title = "" + selectedItems.size
if (selectedItems.isEmpty()) {
actionMode?.finish()
} else if (selectedItems.size == 1 && (canEdit.not())) {
if (values[selectedItems.iterator().next()].type == PasswordItem.TYPE_PASSWORD) {
canEdit = true
actionMode?.invalidate()
}
} else if (selectedItems.size >= 1 && canEdit) {
canEdit = false
actionMode?.invalidate()
}
} else {
listener.onFragmentInteraction(pass)
}
notifyItemChanged(holder.adapterPosition)
}
}
}
| gpl-3.0 | b452a45104c540c94306634415cb487c | 40.293103 | 107 | 0.579541 | 5.576251 | false | false | false | false |
raniejade/zerofx | zerofx-core/src/main/kotlin/io/polymorphicpanda/zerofx/ZeroApp.kt | 1 | 1622 | package io.polymorphicpanda.zerofx
import io.polymorphicpanda.zerofx.component.Component
import io.polymorphicpanda.zerofx.template.Template
import javafx.event.EventHandler
import javafx.scene.Group
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
import javafx.stage.WindowEvent
import kotlin.reflect.KClass
import kotlin.reflect.primaryConstructor
/**
* @author Ranie Jade Ramiso
*/
abstract class ZeroApp(val stage: Stage) {
abstract val main: KClass<out Component<*>>
abstract protected fun createScene(root: Parent): Scene
internal lateinit var instance: Component<*>
fun init() {
// should we allow users to override this?
stage.onCloseRequest = EventHandler {
onClose(it)
}
instance = create(main, null) {
val root = when (template.root) {
is Parent -> template.root as Parent
else -> Group(template.root)
}
stage.scene = createScene(root)
}
}
fun destroy() {
instance.destroy()
}
open fun onClose(): Boolean = true
private fun onClose(event: WindowEvent) {
if (onClose()) {
destroy()
} else {
event.consume()
}
}
fun <T: Component<*>> create(klass: KClass<out T>, parent: Template?, attach: T.() -> Unit): T {
return klass.primaryConstructor!!.call(this).apply {
if (parent != null) {
parent.components.add(this)
}
attach(this)
template.init()
init()
}
}
}
| mit | a8011d62252f76ddf4a87b33a4644676 | 25.590164 | 100 | 0.602959 | 4.530726 | false | false | false | false |
Pagejects/pagejects-core | src/test/kotlin/net/pagejects/core/testdata/UserActions.kt | 1 | 2161 | package net.pagejects.core.testdata
import net.pagejects.core.UserActionResolver
import net.pagejects.core.annotation.UserAction
import net.pagejects.core.reflaction.userActionAnnotations
import java.lang.reflect.Method
@UserAction
annotation class CustomAction1
@UserAction
annotation class CustomAction2
@UserAction
annotation class CustomAction3
@UserAction
annotation class CustomAction4
class UserActionTestResolver1 : UserActionResolver {
override fun getUserAction(pageObjectInterface: Class<*>, userActionMethod: Method): net.pagejects.core.UserAction<*> {
return when (userActionMethod.userActionAnnotations.single()) {
is CustomAction1 -> UserAction1Handler()
is CustomAction2 -> UserAction2Handler()
is CustomAction3 -> UserAction3_1Handler()
else -> throw IllegalStateException()
}
}
override fun isSupported(userActionAnnotation: Annotation) = when (userActionAnnotation) {
is CustomAction1 -> true
is CustomAction2 -> true
is CustomAction3 -> true
else -> false
}
}
class UserActionTestResolver2 : UserActionResolver {
override fun getUserAction(pageObjectInterface: Class<*>, userActionMethod: Method): net.pagejects.core.UserAction<*> {
return when (userActionMethod.userActionAnnotations.single()) {
is CustomAction3 -> UserAction3_2Handler()
else -> throw IllegalStateException()
}
}
override fun isSupported(userActionAnnotation: Annotation) = when (userActionAnnotation) {
is CustomAction3 -> true
else -> false
}
}
class UserAction1Handler : net.pagejects.core.UserAction<String> {
override fun perform(params: Array<out Any>?) = "Value1"
}
class UserAction2Handler : net.pagejects.core.UserAction<String> {
override fun perform(params: Array<out Any>?) = "Value2"
}
class UserAction3_1Handler : net.pagejects.core.UserAction<String> {
override fun perform(params: Array<out Any>?) = "Value3_1"
}
class UserAction3_2Handler : net.pagejects.core.UserAction<String> {
override fun perform(params: Array<out Any>?) = "Value3_2"
}
| apache-2.0 | 1f9e7aa93ce369617a413a366b090cb2 | 31.742424 | 123 | 0.723276 | 4.374494 | false | false | false | false |
auricgoldfinger/Memento-Namedays | android_mobile/src/main/java/com/alexstyl/resources/AndroidColors.kt | 3 | 1538 | package com.alexstyl.resources
import android.content.Context
import android.support.v4.content.ContextCompat
import com.alexstyl.specialdates.R
import com.alexstyl.specialdates.events.database.EventTypeId
import com.alexstyl.specialdates.events.peopleevents.EventType
class AndroidColors(private val context: Context) : Colors {
override fun getColorFor(eventType: EventType) = when (eventType.id) {
EventTypeId.TYPE_BIRTHDAY -> ContextCompat.getColor(context, R.color.birthday_red)
EventTypeId.TYPE_NAMEDAY -> ContextCompat.getColor(context, R.color.nameday_blue)
EventTypeId.TYPE_ANNIVERSARY -> ContextCompat.getColor(context, R.color.anniversary_yellow)
EventTypeId.TYPE_CUSTOM -> ContextCompat.getColor(context, R.color.purple_custom_event)
EventTypeId.TYPE_OTHER -> ContextCompat.getColor(context, R.color.purple_custom_event)
else -> {
throw IllegalStateException("No color matching for $eventType")
}
}
override fun getDateHeaderTextColor(): Int = ContextCompat.getColor(context, R.color.upcoming_header_text_color)
override fun getTodayHeaderTextColor(): Int = ContextCompat.getColor(context, R.color.upcoming_header_today_text_color)
override fun getDailyReminderColor(): Int = ContextCompat.getColor(context, R.color.main_red)
override fun getNamedaysColor(): Int = ContextCompat.getColor(context, R.color.nameday_blue)
override fun getBankholidaysColor(): Int = ContextCompat.getColor(context, R.color.bankholiday_green)
}
| mit | 1c048fe138c25b7a6e6696f5928a790e | 50.266667 | 123 | 0.76593 | 4.202186 | false | false | false | false |
google/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/ide.kt | 1 | 3899 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.actions
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.lookup.Lookup
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.navigation.impl.NavigationRequestor
import com.intellij.codeInsight.navigation.impl.gtdTargetNavigatable
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.ui.UISettings
import com.intellij.idea.ActionsBundle
import com.intellij.lang.LanguageNamesValidation
import com.intellij.navigation.NavigationRequest
import com.intellij.navigation.impl.RawNavigationRequest
import com.intellij.navigation.impl.SourceNavigationRequest
import com.intellij.openapi.actionSystem.ex.ActionUtil.underModalProgress
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiFile
import com.intellij.util.ui.EDT
import java.awt.event.MouseEvent
internal fun navigateToLookupItem(project: Project): Boolean {
val activeLookup: Lookup? = LookupManager.getInstance(project).activeLookup
if (activeLookup == null) {
return false
}
val currentItem = activeLookup.currentItem
navigateRequestLazy(project) {
TargetElementUtil.targetElementFromLookupElement(currentItem)
?.gtdTargetNavigatable()
?.navigationRequest()
}
return true
}
/**
* Obtains a [NavigationRequest] instance from [requestor] on a background thread, and calls [navigateRequest].
*/
internal fun navigateRequestLazy(project: Project, requestor: NavigationRequestor) {
EDT.assertIsEdt()
@Suppress("DialogTitleCapitalization")
val request = underModalProgress(project, ActionsBundle.actionText("GotoDeclarationOnly")) {
requestor.navigationRequest()
}
if (request != null) {
navigateRequest(project, request)
}
}
internal fun navigateRequest(project: Project, request: NavigationRequest) {
EDT.assertIsEdt()
IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation()
when (request) {
is SourceNavigationRequest -> {
// TODO support pure source request without OpenFileDescriptor
val openFileDescriptor = OpenFileDescriptor(project, request.file, request.offset)
if (UISettings.getInstance().openInPreviewTabIfPossible && Registry.`is`("editor.preview.tab.navigation")) {
openFileDescriptor.isUsePreviewTab = true
}
openFileDescriptor.navigate(true)
}
is RawNavigationRequest -> {
request.navigatable.navigate(true)
}
else -> {
error("unsupported request ${request.javaClass.name}")
}
}
}
internal fun notifyNowhereToGo(project: Project, editor: Editor, file: PsiFile, offset: Int) {
// Disable the 'no declaration found' notification for keywords
if (Registry.`is`("ide.gtd.show.error") && !isUnderDoubleClick() && !isKeywordUnderCaret(project, file, offset)) {
HintManager.getInstance().showInformationHint(editor, CodeInsightBundle.message("declaration.navigation.nowhere.to.go"))
}
}
private fun isUnderDoubleClick(): Boolean {
val event = IdeEventQueue.getInstance().trueCurrentEvent
return event is MouseEvent && event.clickCount == 2
}
private fun isKeywordUnderCaret(project: Project, file: PsiFile, offset: Int): Boolean {
val elementAtCaret = file.findElementAt(offset) ?: return false
val namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(elementAtCaret.language)
return namesValidator.isKeyword(elementAtCaret.text, project)
}
| apache-2.0 | b0d69c01b1af7108a7810df3335fc59c | 40.924731 | 158 | 0.790972 | 4.528455 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnnecessaryOptInAnnotationInspection.kt | 2 | 18116 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.SmartPsiElementPointer
import com.intellij.psi.util.parentOfType
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.base.psi.KotlinPsiHeuristics
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.getDirectlyOverriddenDeclarations
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.references.ReadWriteAccessChecker
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.SINCE_KOTLIN_FQ_NAME
import org.jetbrains.kotlin.resolve.checkers.OptInNames
import org.jetbrains.kotlin.resolve.checkers.OptInNames.OPT_IN_FQ_NAMES
import org.jetbrains.kotlin.resolve.constants.ArrayValue
import org.jetbrains.kotlin.resolve.constants.KClassValue
import org.jetbrains.kotlin.resolve.constants.StringValue
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* An inspection to detect unnecessary (obsolete) `@OptIn` annotations.
*
* The `@OptIn(SomeExperimentalMarker::class)` annotation is necessary for the code that
* uses experimental library API marked with `@SomeExperimentalMarker` but is not experimental by itself.
* When the library authors decide that the API is not experimental anymore, and they remove
* the experimental marker, the corresponding `@OptIn` annotation in the client code becomes unnecessary
* and may be removed so the people working with the code would not be misguided.
*
* For each `@OptIn` annotation, the inspection checks if in its scope there are names marked with
* the experimental marker mentioned in the `@OptIn`, and it reports the marker classes that don't match
* any names. For these redundant markers, the inspection proposes a quick fix to remove the marker
* or the entire unnecessary `@OptIn` annotation if it contains a single marker.
*/
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class UnnecessaryOptInAnnotationInspection : AbstractKotlinInspection() {
/**
* Get the PSI element to which the given `@OptIn` annotation applies.
*
* @receiver the `@OptIn` annotation entry
* @return the annotated element, or null if no such element is found
*/
private fun KtAnnotationEntry.getOwner(): KtElement? = getStrictParentOfType<KtAnnotated>()
/**
* A temporary storage for expected experimental markers.
*
* @param expression a smart pointer to the argument expression to create a quick fix
* @param fqName the resolved fully qualified name
*/
private data class ResolvedMarker(
val expression: SmartPsiElementPointer<KtClassLiteralExpression>,
val fqName: FqName
)
// Short names for `kotlin.OptIn` and `kotlin.UseExperimental` for faster comparison without name resolution
private val OPT_IN_SHORT_NAMES = OPT_IN_FQ_NAMES.map { it.shortName().asString() }.toSet()
/**
* Main inspection visitor to traverse all annotation entries.
*/
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
val file = holder.file
val optInAliases = if (file is KtFile) KotlinPsiHeuristics.getImportAliases(file, OPT_IN_SHORT_NAMES) else emptySet()
return annotationEntryVisitor { annotationEntry ->
val annotationEntryArguments = annotationEntry.valueArguments.ifEmpty {
return@annotationEntryVisitor
}
// Fast check if the annotation may be `@OptIn`/`@UseExperimental` or any of their import aliases
val entryShortName = annotationEntry.shortName?.asString()
if (entryShortName != null && entryShortName !in OPT_IN_SHORT_NAMES && entryShortName !in optInAliases)
return@annotationEntryVisitor
// Resolve the candidate annotation entry. If it is an `@OptIn`/`@UseExperimental` annotation,
// resolve all expected experimental markers.
val resolutionFacade = annotationEntry.getResolutionFacade()
val annotationContext = annotationEntry.analyze(resolutionFacade)
val annotationFqName = annotationContext[BindingContext.ANNOTATION, annotationEntry]?.fqName
if (annotationFqName !in OPT_IN_FQ_NAMES) return@annotationEntryVisitor
val resolvedMarkers = mutableListOf<ResolvedMarker>()
for (arg in annotationEntryArguments) {
val argumentExpression = arg.getArgumentExpression()?.safeAs<KtClassLiteralExpression>() ?: continue
val markerFqName = annotationContext[
BindingContext.REFERENCE_TARGET,
argumentExpression.lhs?.safeAs<KtNameReferenceExpression>()
]?.fqNameSafe ?: continue
resolvedMarkers.add(ResolvedMarker(argumentExpression.createSmartPointer(), markerFqName))
}
// Find the scope of the `@OptIn` declaration and collect all its experimental markers.
val markerProcessor = MarkerCollector(resolutionFacade)
annotationEntry.getOwner()?.accept(OptInMarkerVisitor(), markerProcessor)
val unusedMarkers = resolvedMarkers.filter { markerProcessor.isUnused(it.fqName) }
if (annotationEntryArguments.size == unusedMarkers.size) {
// If all markers in the `@OptIn` annotation are useless, create a quick fix to remove
// the entire annotation.
holder.registerProblem(
annotationEntry,
KotlinBundle.message("inspection.unnecessary.opt_in.redundant.annotation"),
RemoveAnnotationEntry()
)
} else {
// Check each resolved marker whether it is actually used in the scope of the `@OptIn`.
// Create a quick fix to remove the unnecessary marker if no marked names have been found.
for (marker in unusedMarkers) {
val expression = marker.expression.element ?: continue
holder.registerProblem(
expression,
KotlinBundle.message(
"inspection.unnecessary.opt_in.redundant.marker",
marker.fqName.shortName().render()
),
RemoveAnnotationArgumentOrEntireEntry()
)
}
}
}
}
}
/**
* A processor that collects experimental markers referred by names in the `@OptIn` annotation scope.
*/
private class MarkerCollector(private val resolutionFacade: ResolutionFacade) {
// Experimental markers found during a check for a specific annotation entry
private val foundMarkers = mutableSetOf<FqName>()
// A checker instance for setter call detection
private val readWriteAccessChecker = ReadWriteAccessChecker.getInstance(resolutionFacade.project)
/**
* Check if a specific experimental marker is not used in the scope of a specific `@OptIn` annotation.
*
* @param marker the fully qualified name of the experimental marker of interest
* @return true if no marked names was found during the check, false if there is at least one marked name
*/
fun isUnused(marker: FqName): Boolean = marker !in foundMarkers
/**
* Collect experimental markers for a declaration and add them to [foundMarkers].
*
* The `@OptIn` annotation is useful for declarations that override a marked declaration (e.g., overridden
* functions or properties in classes/objects). If the declaration overrides another name, we should
* collect experimental markers from the overridden declaration.
*
* @param declaration the declaration to process
*/
fun collectMarkers(declaration: KtDeclaration?) {
if (declaration == null) return
if (declaration !is KtFunction && declaration !is KtProperty && declaration !is KtParameter) return
if (declaration.hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
val descriptor = declaration.resolveToDescriptorIfAny(resolutionFacade)?.safeAs<CallableMemberDescriptor>() ?: return
descriptor.getDirectlyOverriddenDeclarations().forEach { it.collectMarkers(declaration.languageVersionSettings.apiVersion) }
}
}
/**
* Collect experimental markers for an expression and add them to [foundMarkers].
*
* @param expression the expression to process
*/
fun collectMarkers(expression: KtReferenceExpression?) {
if (expression == null) return
// Resolve the reference to descriptors, then analyze the annotations
// For each descriptor, we also check a corresponding importable descriptor
// if it is not equal to the descriptor itself. The goal is to correctly
// resolve class names. For example, the `Foo` reference in the code fragment
// `val x = Foo()` is resolved as a constructor, while the corresponding
// class descriptor can be found as the constructor's importable name.
// Both constructor and class may be annotated with an experimental API marker,
// so we should check both of them.
val descriptorList = expression
.resolveMainReferenceToDescriptors()
.flatMap { setOf(it, it.getImportableDescriptor()) }
val moduleApiVersion = expression.languageVersionSettings.apiVersion
for (descriptor in descriptorList) {
descriptor.collectMarkers(moduleApiVersion)
// A special case: a property has no experimental markers but its setter is experimental.
// We need to additionally collect markers from the setter if it is invoked in the expression.
if (descriptor is PropertyDescriptor) {
val setter = descriptor.setter
if (setter != null && expression.isSetterCall()) setter.collectMarkers(moduleApiVersion)
}
// The caller implicitly uses argument types and return types of a declaration,
// so we need to check whether these types have experimental markers
// regardless of the `@OptIn` annotation on the declaration itself.
if (descriptor is CallableDescriptor) {
descriptor.valueParameters.forEach { it.type.collectMarkers(moduleApiVersion)}
descriptor.returnType?.collectMarkers(moduleApiVersion)
}
}
}
/**
* Collect markers from a declaration descriptor corresponding to a Kotlin type.
*
* @receiver the type to collect markers
* @param moduleApiVersion the API version of the current module to check `@WasExperimental` annotations
*/
private fun KotlinType.collectMarkers(moduleApiVersion: ApiVersion) {
arguments.forEach {
if (!it.isStarProjection) {
it.type.collectMarkers(moduleApiVersion)
}
}
val descriptor = this.constructor.declarationDescriptor ?: return
descriptor.collectMarkers(moduleApiVersion)
}
/**
* Actually collect markers for a resolved descriptor and add them to [foundMarkers].
*
* @receiver the descriptor to collect markers
* @param moduleApiVersion the API version of the current module to check `@WasExperimental` annotations
*/
private fun DeclarationDescriptor.collectMarkers(moduleApiVersion: ApiVersion) {
for (ann in annotations) {
val annotationFqName = ann.fqName ?: continue
val annotationClass = ann.annotationClass ?: continue
// Add the annotation class as a marker if it has `@RequireOptIn` annotation.
if (annotationClass.annotations.hasAnnotation(OptInNames.REQUIRES_OPT_IN_FQ_NAME)
|| annotationClass.annotations.hasAnnotation(OptInNames.OLD_EXPERIMENTAL_FQ_NAME)) {
foundMarkers += annotationFqName
}
val wasExperimental = annotations.findAnnotation(OptInNames.WAS_EXPERIMENTAL_FQ_NAME) ?: continue
val sinceKotlin = annotations.findAnnotation(SINCE_KOTLIN_FQ_NAME) ?: continue
// If there are both `@SinceKotlin` and `@WasExperimental` annotations,
// and Kotlin API version of the module is less than the version specified by `@SinceKotlin`,
// then the `@OptIn` for `@WasExperimental` marker is necessary and should be added
// to the set of found markers.
//
// For example, consider a function
// ```
// @SinceKotlin("1.6")
// @WasExperimental(Marker::class)
// fun foo() { ... }
// ```
// This combination of annotations means that `foo` was experimental before Kotlin 1.6
// and required `@OptIn(Marker::class) or `@Marker` annotation. When the client code
// is compiled as Kotlin 1.6 code, there are no problems, and the `@OptIn(Marker::class)`
// annotation would not be necessary. At the same time, when the code is compiled with
// `apiVersion = 1.5`, the non-experimental declaration of `foo` will be hidden
// from the resolver, so `@OptIn` is necessary for the code to compile.
val sinceKotlinApiVersion = sinceKotlin.allValueArguments[VERSION_ARGUMENT]
?.safeAs<StringValue>()?.value?.let {
ApiVersion.parse(it)
}
if (sinceKotlinApiVersion != null && moduleApiVersion < sinceKotlinApiVersion) {
wasExperimental.allValueArguments[OptInNames.WAS_EXPERIMENTAL_ANNOTATION_CLASS]?.safeAs<ArrayValue>()?.value
?.mapNotNull { it.safeAs<KClassValue>()?.getArgumentType(module)?.fqName }
?.forEach { foundMarkers.add(it) }
}
}
}
/**
* Check if the reference expression is a part of a property setter invocation.
*
* @receiver the expression to check
*/
private fun KtReferenceExpression.isSetterCall(): Boolean =
readWriteAccessChecker.readWriteAccessWithFullExpression(this, true).first.isWrite
private val VERSION_ARGUMENT = Name.identifier("version")
}
/**
* The marker collecting visitor that navigates the PSI tree in the scope of the `@OptIn` declaration
* and collects experimental markers.
*/
private class OptInMarkerVisitor : KtTreeVisitor<MarkerCollector>() {
override fun visitNamedDeclaration(declaration: KtNamedDeclaration, markerCollector: MarkerCollector): Void? {
markerCollector.collectMarkers(declaration)
return super.visitNamedDeclaration(declaration, markerCollector)
}
override fun visitReferenceExpression(expression: KtReferenceExpression, markerCollector: MarkerCollector): Void? {
markerCollector.collectMarkers(expression)
return super.visitReferenceExpression(expression, markerCollector)
}
}
/**
* A quick fix that removes the argument from the value argument list of an annotation entry,
* or the entire entry if the argument was the only argument of the annotation.
*/
private class RemoveAnnotationArgumentOrEntireEntry : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("inspection.unnecessary.opt_in.remove.marker.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val valueArgument = descriptor.psiElement?.parentOfType<KtValueArgument>() ?: return
val annotationEntry = valueArgument.parentOfType<KtAnnotationEntry>() ?: return
if (annotationEntry.valueArguments.size == 1) {
annotationEntry.delete()
} else {
annotationEntry.valueArgumentList?.removeArgument(valueArgument)
}
}
}
/**
* A quick fix that removes the entire annotation entry.
*/
private class RemoveAnnotationEntry : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("inspection.unnecessary.opt_in.remove.annotation.fix.family.name")
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val annotationEntry = descriptor.psiElement?.safeAs<KtAnnotationEntry>() ?: return
annotationEntry.delete()
}
}
| apache-2.0 | e346d0a291bfc7f86fcbf24a0c45d032 | 50.175141 | 136 | 0.704515 | 5.325103 | false | false | false | false |
apache/isis | incubator/clients/kroviz/src/test/kotlin/org/apache/causeway/client/kroviz/util/StringUtilsTest.kt | 2 | 1189 | package org.apache.causeway.client.kroviz.util
import org.apache.causeway.client.kroviz.ui.core.Constants
import org.apache.causeway.client.kroviz.ui.core.SessionManager
import org.apache.causeway.client.kroviz.utils.StringUtils
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class StringUtilsTest {
@Test
fun testShortTitle() {
// given
SessionManager.login(Constants.demoUrl, Constants.demoUser, Constants.demoPass)
val url = "http://localhost:8080/restful/domain-types/demo.JavaLangStrings/collections/entities"
// when
val protocolHostPort = SessionManager.getBaseUrl()!!
// then
assertTrue(protocolHostPort.startsWith("http://"))
// when
val actual = StringUtils.shortTitle(url)
// then
val expected = "/domain-types/demo.JavaLangStrings/collections/entities"
assertEquals(expected, actual)
}
@Test
fun testFormat() {
// given
val int = 123456789
// when
val actual = StringUtils.format(int)
// then
val expected = "123.456.789"
assertEquals(expected, actual)
}
}
| apache-2.0 | 7ce21fec9299a63ffdcac7d928421340 | 29.487179 | 104 | 0.674516 | 4.371324 | false | true | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/highlight/HaskellColorsAndFontsPage.kt | 1 | 4784 | package org.jetbrains.haskell.highlight
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.fileTypes.SyntaxHighlighter
import com.intellij.openapi.options.colors.AttributesDescriptor
import com.intellij.openapi.options.colors.ColorDescriptor
import com.intellij.openapi.options.colors.ColorSettingsPage
import org.jetbrains.annotations.NonNls
import org.jetbrains.haskell.icons.HaskellIcons
import javax.swing.*
import java.util.HashMap
class HaskellColorsAndFontsPage : ColorSettingsPage {
override fun getDisplayName(): String {
return "Haskell"
}
override fun getIcon(): Icon? {
return HaskellIcons.HASKELL
}
override fun getAttributeDescriptors(): Array<AttributesDescriptor> {
return ATTRS
}
override fun getColorDescriptors(): Array<ColorDescriptor> {
return arrayOf()
}
override fun getHighlighter(): SyntaxHighlighter {
return HaskellHighlighter()
}
override fun getDemoText(): String {
return "<keyword>module</keyword> <cons>Main</cons> <keyword>where</keyword>\n" +
"<pragma>{-# LANGUAGE CPP #-}</pragma>\n" +
"<comment>-- Comment</comment>\n" +
"\n" +
"<keyword>class</keyword> <class>YesNo a</class> <keyword>where</keyword>\n" +
" <sig>yesno</sig> <dcolon>::</dcolon> <type>a -> Bool</type>\n" +
"\n" +
"\n" + "<keyword>data</keyword> <type>Maybe a</type> <equal>=</equal> <cons>Nothing</cons> | <cons>Just</cons> <type>a</type>\n" +
"\n" + "<sig>main</sig> <dcolon>::</dcolon> <type>IO ()</type>\n" +
"<id>main</id> = <keyword>do</keyword>\n" +
" <id>putStrLn</id> <string>\"Hello\"</string> <operator>++</operator> <string>\" world!!\"</string>\n" +
"<id>t</id> <equal>=</equal> <number>5</number>\n" +
"<par>(</par><id>t</id><par>)</par>\n" +
"<curly>{}</curly>\n" +
"<brackets>[]</brackets>\n"
}
override fun getAdditionalHighlightingTagToDescriptorMap(): Map<String, TextAttributesKey>? {
val map = HashMap<String, TextAttributesKey>()
map.put("brackets", HaskellHighlighter.HASKELL_BRACKETS)
map.put("class", HaskellHighlighter.HASKELL_CLASS)
map.put("curly", HaskellHighlighter.HASKELL_CURLY)
map.put("cons", HaskellHighlighter.HASKELL_CONSTRUCTOR)
map.put("comment", HaskellHighlighter.HASKELL_COMMENT)
map.put("dcolon", HaskellHighlighter.HASKELL_DOUBLE_COLON)
map.put("equal", HaskellHighlighter.HASKELL_EQUAL)
map.put("id", HaskellHighlighter.HASKELL_IDENTIFIER)
map.put("keyword", HaskellHighlighter.HASKELL_KEYWORD)
map.put("number", HaskellHighlighter.HASKELL_NUMBER)
map.put("operator", HaskellHighlighter.HASKELL_OPERATOR)
map.put("par", HaskellHighlighter.HASKELL_PARENTHESIS)
map.put("pragma", HaskellHighlighter.HASKELL_PRAGMA)
map.put("sig", HaskellHighlighter.HASKELL_SIGNATURE)
map.put("string", HaskellHighlighter.HASKELL_STRING_LITERAL)
map.put("type", HaskellHighlighter.HASKELL_TYPE)
return map
}
companion object {
private val ATTRS = arrayOf(AttributesDescriptor("Brackets", HaskellHighlighter.HASKELL_BRACKETS),
AttributesDescriptor("Class", HaskellHighlighter.HASKELL_CLASS),
AttributesDescriptor("Comment", HaskellHighlighter.HASKELL_COMMENT),
AttributesDescriptor("Curly brackets", HaskellHighlighter.HASKELL_CURLY),
AttributesDescriptor("Constructor or Type", HaskellHighlighter.HASKELL_CONSTRUCTOR),
AttributesDescriptor("Double color", HaskellHighlighter.HASKELL_DOUBLE_COLON),
AttributesDescriptor("Equal", HaskellHighlighter.HASKELL_EQUAL),
AttributesDescriptor("Identifier", HaskellHighlighter.HASKELL_IDENTIFIER),
AttributesDescriptor("Keyword", HaskellHighlighter.HASKELL_KEYWORD),
AttributesDescriptor("Number", HaskellHighlighter.HASKELL_NUMBER),
AttributesDescriptor("Operator", HaskellHighlighter.HASKELL_OPERATOR),
AttributesDescriptor("Parenthesis", HaskellHighlighter.HASKELL_PARENTHESIS),
AttributesDescriptor("Pragma", HaskellHighlighter.HASKELL_PRAGMA),
AttributesDescriptor("Signature", HaskellHighlighter.HASKELL_SIGNATURE),
AttributesDescriptor("String", HaskellHighlighter.HASKELL_STRING_LITERAL),
AttributesDescriptor("Type", HaskellHighlighter.HASKELL_TYPE))
}
}
| apache-2.0 | c93ab8e50d1a9980a162eb659c01fad3 | 49.357895 | 146 | 0.66158 | 4.911704 | false | false | false | false |
allotria/intellij-community | plugins/grazie/src/main/kotlin/com/intellij/grazie/grammar/strategy/impl/RuleGroup.kt | 2 | 1160 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.grazie.grammar.strategy.impl
import com.intellij.grazie.utils.LinkedSet
/**
* A group of Grazie grammar rules.
*
* This class represent a user-defined set of rules.
*/
data class RuleGroup(val rules: LinkedSet<String>) {
constructor(vararg rules: String) : this(LinkedSet(rules.toSet()))
companion object {
val EMPTY = RuleGroup()
/** Rule for checking double whitespaces */
@Deprecated("Use getStealthyRanges() in GrammarCheckingStrategy and StrategyUtils.indentIndexes()")
val WHITESPACES = RuleGroup("WHITESPACE_RULE")
/** Rules for checking casing errors */
val CASING = RuleGroup("UPPERCASE_SENTENCE_START")
/** Rules for checking punctuation errors */
val PUNCTUATION = RuleGroup("PUNCTUATION_PARAGRAPH_END", "UNLIKELY_OPENING_PUNCTUATION")
/** Rules that are usually disabled for literal strings */
val LITERALS = CASING + PUNCTUATION
}
operator fun plus(other: RuleGroup) = RuleGroup((rules + other.rules) as LinkedSet<String>)
}
| apache-2.0 | bbe99c7d106d1b09d47a6c0994687cf4 | 35.25 | 140 | 0.72931 | 4.084507 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/ProblemsViewState.kt | 2 | 1483 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.analysis.problemsView.toolWindow
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.components.*
import com.intellij.openapi.project.Project
import com.intellij.util.xmlb.annotations.XCollection
import java.util.*
import java.util.concurrent.ConcurrentHashMap
internal class ProblemsViewState : BaseState() {
companion object {
@JvmStatic
fun getInstance(project: Project) = project.getService(ProblemsViewStateManager::class.java).state
}
var selectedIndex by property(0)
var proportion by property(0.5f)
var autoscrollToSource by property(false)
var showPreview by property(false)
var showToolbar by property(true)
var groupByToolId by property(false)
var sortFoldersFirst by property(true)
var sortBySeverity by property(true)
var sortByName by property(false)
@get:XCollection(style = XCollection.Style.v2)
val hideBySeverity: MutableSet<Int> by property(Collections.newSetFromMap(ConcurrentHashMap()), { it.isEmpty() })
}
@State(name = "ProblemsViewState", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE))])
internal class ProblemsViewStateManager : SimplePersistentStateComponent<ProblemsViewState>(ProblemsViewState()) {
override fun noStateLoaded() {
state.autoscrollToSource = UISettings.instance.state.defaultAutoScrollToSource
}
}
| apache-2.0 | 0fe249c74961bf4d7334037568611b2a | 38.026316 | 140 | 0.792987 | 4.348974 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/src/Timeout.kt | 1 | 8929 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:OptIn(ExperimentalContracts::class)
package kotlinx.coroutines
import kotlinx.coroutines.internal.*
import kotlinx.coroutines.intrinsics.*
import kotlinx.coroutines.selects.*
import kotlin.contracts.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
import kotlin.jvm.*
import kotlin.time.*
/**
* Runs a given suspending [block] of code inside a coroutine with a specified [timeout][timeMillis] and throws
* a [TimeoutCancellationException] if the timeout was exceeded.
*
* The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of
* the cancellable suspending function inside the block throws a [TimeoutCancellationException].
*
* The sibling function that does not throw an exception on timeout is [withTimeoutOrNull].
* Note that the timeout action can be specified for a [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
*
* **The timeout event is asynchronous with respect to the code running in the block** and may happen at any time,
* even right before the return from inside of the timeout [block]. Keep this in mind if you open or acquire some
* resource inside the [block] that needs closing or release outside of the block.
* See the
* [Asynchronous timeout and resources][https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#asynchronous-timeout-and-resources]
* section of the coroutines guide for details.
*
* > Implementation note: how the time is tracked exactly is an implementation detail of the context's [CoroutineDispatcher].
*
* @param timeMillis timeout time in milliseconds.
*/
public suspend fun <T> withTimeout(timeMillis: Long, block: suspend CoroutineScope.() -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
if (timeMillis <= 0L) throw TimeoutCancellationException("Timed out immediately")
return suspendCoroutineUninterceptedOrReturn { uCont ->
setupTimeout(TimeoutCoroutine(timeMillis, uCont), block)
}
}
/**
* Runs a given suspending [block] of code inside a coroutine with the specified [timeout] and throws
* a [TimeoutCancellationException] if the timeout was exceeded.
*
* The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of
* the cancellable suspending function inside the block throws a [TimeoutCancellationException].
*
* The sibling function that does not throw an exception on timeout is [withTimeoutOrNull].
* Note that the timeout action can be specified for a [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
*
* **The timeout event is asynchronous with respect to the code running in the block** and may happen at any time,
* even right before the return from inside of the timeout [block]. Keep this in mind if you open or acquire some
* resource inside the [block] that needs closing or release outside of the block.
* See the
* [Asynchronous timeout and resources][https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#asynchronous-timeout-and-resources]
* section of the coroutines guide for details.
*
* > Implementation note: how the time is tracked exactly is an implementation detail of the context's [CoroutineDispatcher].
*/
public suspend fun <T> withTimeout(timeout: Duration, block: suspend CoroutineScope.() -> T): T {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return withTimeout(timeout.toDelayMillis(), block)
}
/**
* Runs a given suspending block of code inside a coroutine with a specified [timeout][timeMillis] and returns
* `null` if this timeout was exceeded.
*
* The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of
* cancellable suspending function inside the block throws a [TimeoutCancellationException].
*
* The sibling function that throws an exception on timeout is [withTimeout].
* Note that the timeout action can be specified for a [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
*
* **The timeout event is asynchronous with respect to the code running in the block** and may happen at any time,
* even right before the return from inside of the timeout [block]. Keep this in mind if you open or acquire some
* resource inside the [block] that needs closing or release outside of the block.
* See the
* [Asynchronous timeout and resources][https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#asynchronous-timeout-and-resources]
* section of the coroutines guide for details.
*
* > Implementation note: how the time is tracked exactly is an implementation detail of the context's [CoroutineDispatcher].
*
* @param timeMillis timeout time in milliseconds.
*/
public suspend fun <T> withTimeoutOrNull(timeMillis: Long, block: suspend CoroutineScope.() -> T): T? {
if (timeMillis <= 0L) return null
var coroutine: TimeoutCoroutine<T?, T?>? = null
try {
return suspendCoroutineUninterceptedOrReturn { uCont ->
val timeoutCoroutine = TimeoutCoroutine(timeMillis, uCont)
coroutine = timeoutCoroutine
setupTimeout<T?, T?>(timeoutCoroutine, block)
}
} catch (e: TimeoutCancellationException) {
// Return null if it's our exception, otherwise propagate it upstream (e.g. in case of nested withTimeouts)
if (e.coroutine === coroutine) {
return null
}
throw e
}
}
/**
* Runs a given suspending block of code inside a coroutine with the specified [timeout] and returns
* `null` if this timeout was exceeded.
*
* The code that is executing inside the [block] is cancelled on timeout and the active or next invocation of
* cancellable suspending function inside the block throws a [TimeoutCancellationException].
*
* The sibling function that throws an exception on timeout is [withTimeout].
* Note that the timeout action can be specified for a [select] invocation with [onTimeout][SelectBuilder.onTimeout] clause.
*
* **The timeout event is asynchronous with respect to the code running in the block** and may happen at any time,
* even right before the return from inside of the timeout [block]. Keep this in mind if you open or acquire some
* resource inside the [block] that needs closing or release outside of the block.
* See the
* [Asynchronous timeout and resources][https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html#asynchronous-timeout-and-resources]
* section of the coroutines guide for details.
*
* > Implementation note: how the time is tracked exactly is an implementation detail of the context's [CoroutineDispatcher].
*/
public suspend fun <T> withTimeoutOrNull(timeout: Duration, block: suspend CoroutineScope.() -> T): T? =
withTimeoutOrNull(timeout.toDelayMillis(), block)
private fun <U, T: U> setupTimeout(
coroutine: TimeoutCoroutine<U, T>,
block: suspend CoroutineScope.() -> T
): Any? {
// schedule cancellation of this coroutine on time
val cont = coroutine.uCont
val context = cont.context
coroutine.disposeOnCompletion(context.delay.invokeOnTimeout(coroutine.time, coroutine, coroutine.context))
// restart the block using a new coroutine with a new job,
// however, start it undispatched, because we already are in the proper context
return coroutine.startUndispatchedOrReturnIgnoreTimeout(coroutine, block)
}
private class TimeoutCoroutine<U, in T: U>(
@JvmField val time: Long,
uCont: Continuation<U> // unintercepted continuation
) : ScopeCoroutine<T>(uCont.context, uCont), Runnable {
override fun run() {
cancelCoroutine(TimeoutCancellationException(time, this))
}
override fun nameString(): String =
"${super.nameString()}(timeMillis=$time)"
}
/**
* This exception is thrown by [withTimeout] to indicate timeout.
*/
public class TimeoutCancellationException internal constructor(
message: String,
@JvmField @Transient internal val coroutine: Job?
) : CancellationException(message), CopyableThrowable<TimeoutCancellationException> {
/**
* Creates a timeout exception with the given message.
* This constructor is needed for exception stack-traces recovery.
*/
@Suppress("UNUSED")
internal constructor(message: String) : this(message, null)
// message is never null in fact
override fun createCopy(): TimeoutCancellationException =
TimeoutCancellationException(message ?: "", coroutine).also { it.initCause(this) }
}
@Suppress("FunctionName")
internal fun TimeoutCancellationException(
time: Long,
coroutine: Job
) : TimeoutCancellationException = TimeoutCancellationException("Timed out waiting for $time ms", coroutine)
| apache-2.0 | d604bd3f80e248a94896579b8ba9829f | 47.527174 | 155 | 0.748012 | 4.694532 | false | false | false | false |
RichoDemus/chronicler | server/dropwizard/src/main/kotlin/com/richodemus/chronicler/server/dropwizard/EventResource.kt | 1 | 2941 | package com.richodemus.chronicler.server.dropwizard
import com.fasterxml.jackson.databind.ObjectMapper
import com.richodemus.chronicler.server.api.api.EventsApi
import com.richodemus.chronicler.server.api.model.Event
import com.richodemus.chronicler.server.api.model.EventWithoutPage
import com.richodemus.chronicler.server.core.Chronicle
import com.richodemus.chronicler.server.core.WrongPageException
import java.math.BigDecimal
import javax.inject.Inject
import javax.ws.rs.core.Response
internal class EventResource @Inject constructor(val chronicle: Chronicle) : EventsApi() {
override fun eventsGet(ids: MutableList<String>?): Response {
val events = chronicle.getEvents().map { it.toDtoEvent() }
// Why do I need to do this manually?
val string = ObjectMapper().writeValueAsString(events)
return string.let { Response.ok(it).build() }
}
override fun eventsPageGet(page: Long?): Response {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()
}
/**
* Used when specifying a page exactly
*/
override fun eventsPagePut(page: Long?, event: EventWithoutPage?): Response {
if (event == null || page == null) {
//todo can this even happen?
return Response.status(Response.Status.BAD_REQUEST).build()
}
try {
chronicle.addEvent(com.richodemus.chronicler.server.core.Event(event.id, event.type, page, event.data))
return Response.ok().build()
} catch(e: WrongPageException) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.message).build()
}
}
/**
* Used when not caring about which page number is assigned, i.e. not caring about being up to date
*/
override fun eventsPost(event: EventWithoutPage?): Response {
if (event == null) {
//todo can this even happen?
return Response.status(Response.Status.BAD_REQUEST).build()
}
try {
chronicle.addEvent(com.richodemus.chronicler.server.core.Event(event.id, event.type, null, event.data))
return Response.ok().build()
} catch(e: WrongPageException) {
//language=JSON
val msg = "{\"msg\":\"${e.message}\"}"
return Response.status(Response.Status.BAD_REQUEST).entity(msg).build()
}
}
private fun com.richodemus.chronicler.server.core.Event.toDtoEvent(): Event {
val coolId = this.id
val coolType = this.type
val coolPage = this.page ?: throw IllegalStateException("Got a pageless event from the event store, this shouldn't be possible :O")
val coolData = this.data
return Event().apply {
id = coolId
type = coolType
page = coolPage.toBigDecimal()
data = coolData
}
}
private fun Long.toBigDecimal() = BigDecimal.valueOf(this)
}
| gpl-3.0 | adff51ad80dbf5933b8deadfe3b944fe | 38.213333 | 139 | 0.655899 | 4.243867 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/psi/data/PSDataDeclaration.kt | 1 | 1429 | package org.purescript.psi.data
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiNameIdentifierOwner
import org.purescript.psi.name.PSProperName
import org.purescript.psi.PSPsiElement
/**
* A data declaration, e.g.
*
* ```
* data CatQueue a = CatQueue (List a) (List a)
* ```
*/
class PSDataDeclaration(node: ASTNode) :
PSPsiElement(node),
PsiNameIdentifierOwner {
/**
* @return the [PSProperName] that identifies this declaration
*/
internal val identifier: PSProperName
get() = findNotNullChildByClass(PSProperName::class.java)
/**
* @return the [PSDataConstructorList] in this declaration,
* or null if it's an empty declaration
*/
internal val dataConstructorList: PSDataConstructorList?
get() = findChildByClass(PSDataConstructorList::class.java)
/**
* @return the [PSDataConstructor] elements belonging to this
* declaration, or an empty array if it's an empty declaration
*/
val dataConstructors: Array<PSDataConstructor>
get() = dataConstructorList?.dataConstructors
?: emptyArray()
override fun setName(name: String): PsiElement? {
return null
}
override fun getNameIdentifier(): PSProperName = identifier
override fun getName(): String = nameIdentifier.name
override fun getTextOffset(): Int = nameIdentifier.textOffset
}
| bsd-3-clause | e7758766dc3e82520135b076070f02b2 | 27.58 | 67 | 0.70119 | 4.654723 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRDataProviderImpl.kt | 1 | 9425 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import com.intellij.util.EventDispatcher
import git4idea.GitCommit
import git4idea.commands.Git
import git4idea.fetch.GitFetchSupport
import git4idea.history.GitHistoryUtils
import git4idea.history.GitLogUtil
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GHGQLRequests
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.data.GHCommit
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestReviewThread
import org.jetbrains.plugins.github.api.util.SimpleGHGQLPagesLoader
import org.jetbrains.plugins.github.pullrequest.GHNotFoundException
import org.jetbrains.plugins.github.pullrequest.ui.timeline.GHPRTimelineMergingModel
import org.jetbrains.plugins.github.util.GitRemoteUrlCoordinates
import org.jetbrains.plugins.github.util.GithubAsyncUtil
import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue
import java.util.concurrent.CancellationException
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionException
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
internal class GHPRDataProviderImpl(private val project: Project,
private val progressManager: ProgressManager,
private val git: Git,
private val requestExecutor: GithubApiRequestExecutor,
private val gitRemote: GitRemoteUrlCoordinates,
private val repository: GHRepositoryCoordinates,
override val number: Long)
: GHPRDataProvider {
private val requestsChangesEventDispatcher = EventDispatcher.create(GHPRDataProvider.RequestsChangedListener::class.java)
private var lastKnownBaseSha: String? = null
private var lastKnownHeadSha: String? = null
private val detailsRequestValue = backingValue {
val details = requestExecutor.execute(it, GHGQLRequests.PullRequest.findOne(repository, number))
?: throw GHNotFoundException("Pull request $number does not exist")
invokeAndWaitIfNeeded {
var needReload = false
lastKnownBaseSha?.run { if (this != details.baseRefOid) needReload = true }
lastKnownBaseSha = details.baseRefOid
lastKnownHeadSha?.run { if (this != details.headRefOid) needReload = true }
lastKnownHeadSha = details.headRefOid
if (needReload) reloadChanges()
}
details
}
override val detailsRequest by backgroundProcessValue(detailsRequestValue)
private val headBranchFetchRequestValue = backingValue {
GitFetchSupport.fetchSupport(project)
.fetch(gitRemote.repository, gitRemote.remote, "refs/pull/${number}/head:").throwExceptionIfFailed()
}
override val headBranchFetchRequest by backgroundProcessValue(headBranchFetchRequestValue)
private val baseBranchFetchRequestValue = backingValue {
val details = detailsRequestValue.value.joinCancellable()
GitFetchSupport.fetchSupport(project)
.fetch(gitRemote.repository, gitRemote.remote, details.baseRefName).throwExceptionIfFailed()
if (!git.getObjectType(gitRemote.repository, details.baseRefOid).outputAsJoinedString.equals("commit", true))
error("Base revision \"${details.baseRefOid}\" was not fetched from \"${gitRemote.remote.name} ${details.baseRefName}\"")
}
private val apiCommitsRequestValue = backingValue { indicator ->
SimpleGHGQLPagesLoader(requestExecutor, { p ->
GHGQLRequests.PullRequest.commits(repository, number, p)
}).loadAll(indicator).map { it.commit }
}
override val apiCommitsRequest by backgroundProcessValue(apiCommitsRequestValue)
private val logCommitsRequestValue = backingValue<List<GitCommit>> {
val baseFetch = baseBranchFetchRequestValue.value
val headFetch = headBranchFetchRequestValue.value
val detailsRequest = detailsRequestValue.value
baseFetch.joinCancellable()
headFetch.joinCancellable()
val details = detailsRequest.joinCancellable()
val gitCommits = mutableListOf<GitCommit>()
GitLogUtil.readFullDetails(project, gitRemote.repository.root, Consumer {
gitCommits.add(it)
}, "${details.baseRefOid}..${details.headRefOid}")
gitCommits.asReversed()
}
override val logCommitsRequest by backgroundProcessValue(logCommitsRequestValue)
private val changesProviderValue = backingValue {
val baseFetch = baseBranchFetchRequestValue.value
val headFetch = headBranchFetchRequestValue.value
val detailsRequest = detailsRequestValue.value
val commitsRequest = apiCommitsRequestValue.value
val details = detailsRequest.joinCancellable()
val commits: List<GHCommit> = commitsRequest.joinCancellable()
val commitsWithDiffs = commits.map { commit ->
val commitDiff = requestExecutor.execute(it,
GithubApiRequests.Repos.Commits.getDiff(repository, commit.oid))
val cumulativeDiff = requestExecutor.execute(it,
GithubApiRequests.Repos.Commits.getDiff(repository, details.baseRefOid, commit.oid))
Triple(commit, commitDiff, cumulativeDiff)
}
//TODO: ??? move to diff and load merge base via API
baseFetch.joinCancellable()
headFetch.joinCancellable()
val mergeBaseRev =
GitHistoryUtils.getMergeBase(project, gitRemote.repository.root, details.baseRefOid, details.headRefOid)?.rev
?: error("Could not calculate merge base for PR branch")
GHPRChangesProviderImpl(gitRemote.repository, mergeBaseRev, commitsWithDiffs)
}
override val changesProviderRequest: CompletableFuture<out GHPRChangesProvider> by backgroundProcessValue(changesProviderValue)
private val reviewThreadsRequestValue = backingValue {
SimpleGHGQLPagesLoader(requestExecutor, { p ->
GHGQLRequests.PullRequest.reviewThreads(repository, number, p)
}).loadAll(it)
}
override val reviewThreadsRequest: CompletableFuture<List<GHPullRequestReviewThread>> by backgroundProcessValue(reviewThreadsRequestValue)
private val timelineLoaderHolder = GHPRCountingTimelineLoaderHolder {
val timelineModel = GHPRTimelineMergingModel()
GHPRTimelineLoader(progressManager, requestExecutor,
repository.serverPath, repository.repositoryPath, number,
timelineModel)
}
override val timelineLoader get() = timelineLoaderHolder.timelineLoader
override fun acquireTimelineLoader(disposable: Disposable) = timelineLoaderHolder.acquireTimelineLoader(disposable)
@CalledInAwt
override fun reloadDetails() {
detailsRequestValue.drop()
requestsChangesEventDispatcher.multicaster.detailsRequestChanged()
}
@CalledInAwt
override fun reloadChanges() {
baseBranchFetchRequestValue.drop()
headBranchFetchRequestValue.drop()
logCommitsRequestValue.drop()
changesProviderValue.drop()
requestsChangesEventDispatcher.multicaster.commitsRequestChanged()
reloadReviewThreads()
}
@CalledInAwt
override fun reloadReviewThreads() {
reviewThreadsRequestValue.drop()
requestsChangesEventDispatcher.multicaster.reviewThreadsRequestChanged()
}
@Throws(ProcessCanceledException::class)
private fun <T> CompletableFuture<T>.joinCancellable(): T {
try {
return join()
}
catch (e: CancellationException) {
throw ProcessCanceledException(e)
}
catch (e: CompletionException) {
if (GithubAsyncUtil.isCancellation(e)) throw ProcessCanceledException(e)
throw GithubAsyncUtil.extractError(e)
}
}
private fun <T> backingValue(supplier: (ProgressIndicator) -> T) =
object : LazyCancellableBackgroundProcessValue<T>(progressManager) {
override fun compute(indicator: ProgressIndicator) = supplier(indicator)
}
private fun <T> backgroundProcessValue(backingValue: LazyCancellableBackgroundProcessValue<T>): ReadOnlyProperty<Any?, CompletableFuture<T>> =
object : ReadOnlyProperty<Any?, CompletableFuture<T>> {
override fun getValue(thisRef: Any?, property: KProperty<*>) =
GithubAsyncUtil.futureOfMutable { invokeAndWaitIfNeeded { backingValue.value } }
}
override fun addRequestsChangesListener(listener: GHPRDataProvider.RequestsChangedListener) =
requestsChangesEventDispatcher.addListener(listener)
override fun addRequestsChangesListener(disposable: Disposable, listener: GHPRDataProvider.RequestsChangedListener) =
requestsChangesEventDispatcher.addListener(listener, disposable)
override fun removeRequestsChangesListener(listener: GHPRDataProvider.RequestsChangedListener) =
requestsChangesEventDispatcher.removeListener(listener)
} | apache-2.0 | eb8640c3749c0a5199965e1f1d0aeea8 | 44.317308 | 144 | 0.767215 | 5.127856 | false | false | false | false |
leafclick/intellij-community | platform/build-scripts/icons/src/org/jetbrains/intellij/build/images/sync/syncIcons.kt | 1 | 3798 | // 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.intellij.build.images.sync
import java.io.File
internal fun syncIconsRepo(context: Context) {
if (context.doSyncIconsRepo) {
log("Syncing ${context.iconsRepoName}:")
syncIconsRepo(context, context.byDev)
}
}
internal fun syncDevRepo(context: Context) {
if (context.doSyncDevRepo) {
log("Syncing ${context.devRepoName}:")
syncAdded(context.devRepoDir, context.iconsRepoDir, context.byDesigners.added)
syncModified(context.devRepoDir, context.iconsRepoDir, context.byDesigners.modified)
if (context.doSyncRemovedIconsInDev) {
syncRemoved(context.devRepoDir, context.byDesigners.removed)
}
}
}
internal fun syncIconsRepo(context: Context, byDev: Changes) {
syncAdded(context.iconsRepoDir, context.devRepoDir, byDev.added)
syncModified(context.iconsRepoDir, context.devRepoDir, byDev.modified)
syncRemoved(context.iconsRepoDir, byDev.removed)
}
private fun syncAdded(targetRoot: File, sourceRoot: File, added: MutableCollection<String>) {
stageChanges(added) { change, skip, stage ->
val source = sourceRoot.resolve(change)
if (!source.exists()) {
log("Sync added: unable to find $change in source repo")
return@stageChanges
}
val target = targetRoot.resolve(change)
when {
!target.exists() -> {
source.copyTo(target, overwrite = true)
val repo = findRepo(target)
stage(repo, target.relativeTo(repo).path)
}
same(source, target) -> {
log("Skipping $change")
skip()
}
else -> source.copyTo(target, overwrite = true)
}
}
}
private fun same(f1: File, f2: File) = f1.readBytes().contentEquals(f2.readBytes())
private fun syncModified(targetRoot: File, sourceRoot: File, modified: MutableCollection<String>) {
stageChanges(modified) { change, skip, stage ->
val source = sourceRoot.resolve(change)
if (!source.exists()) {
log("Sync modified: unable to find $change in source repo")
return@stageChanges
}
val target = targetRoot.resolve(change)
if (target.exists() && same(source, target)) {
log("$change is not modified, skipping")
skip()
return@stageChanges
}
if (!target.exists()) log("$change should be modified but not exist, creating")
source.copyTo(target, overwrite = true)
val repo = findRepo(target)
stage(repo, target.toRelativeString(repo))
}
}
private fun syncRemoved(targetRoot: File, removed: MutableCollection<String>) {
stageChanges(removed) { change, skip, stage ->
val target = targetRoot.resolve(change)
if (!target.exists()) {
log("$change is already removed, skipping")
skip()
return@stageChanges
}
if (target.exists()) {
if (target.delete()) {
val repo = findRepo(target)
stage(repo, target.toRelativeString(repo))
}
else log("Failed to delete ${target.absolutePath}")
}
cleanDir(target.parentFile)
}
}
private fun cleanDir(dir: File?) {
if (dir?.list()?.isEmpty() == true && dir.delete()) {
cleanDir(dir.parentFile)
}
}
private fun stageChanges(changes: MutableCollection<String>,
action: (String, () -> Unit, (File, String) -> Unit) -> Unit) {
callSafely {
val toStage = mutableMapOf<File, MutableList<String>>()
val iterator = changes.iterator()
while (iterator.hasNext()) {
action(iterator.next(), iterator::remove) { repo, change ->
if (!toStage.containsKey(repo)) toStage[repo] = mutableListOf()
toStage.getValue(repo) += change
}
}
toStage.forEach { (repo, change) ->
stageFiles(change, repo)
}
}
} | apache-2.0 | 7f73342dfee2e2e1e1fcebcd6c1c1448 | 32.034783 | 140 | 0.668773 | 3.832492 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/controlStructures/forNullableIntArray.kt | 5 | 265 | fun box() : String {
val b : Array<Int?> = arrayOfNulls<Int> (5)
var i = 0
var sum = 0
while(i < 5) {
b[i] = i++
}
sum = 0
for (el in b) {
sum = sum + (el ?: 0)
}
if(sum != 10) return "b failed"
return "OK"
}
| apache-2.0 | 2a33a7868fbed49d8869d464485b33f8 | 16.666667 | 47 | 0.418868 | 2.819149 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/reflection/properties/privateClassVar.kt | 1 | 795 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.full.*
import kotlin.reflect.jvm.isAccessible
class A {
private var value = 0
fun ref() = A::class.memberProperties.single() as KMutableProperty1<A, Int>
}
fun box(): String {
val a = A()
val p = a.ref()
try {
p.set(a, 1)
return "Fail: private property is accessible by default"
} catch(e: IllegalCallableAccessException) { }
p.isAccessible = true
p.set(a, 2)
p.get(a)
p.isAccessible = false
try {
p.set(a, 3)
return "Fail: setAccessible(false) had no effect"
} catch(e: IllegalCallableAccessException) { }
return "OK"
}
| apache-2.0 | 1f20b89fe335dbf4ce9e834a46b17aca | 21.083333 | 79 | 0.646541 | 3.597285 | false | false | false | false |
FirebaseExtended/mlkit-material-android | app/src/main/java/com/google/firebase/ml/md/kotlin/objectdetection/MultiObjectProcessor.kt | 1 | 7773 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.firebase.ml.md.kotlin.objectdetection
import android.graphics.PointF
import android.util.Log
import android.util.SparseArray
import androidx.annotation.MainThread
import androidx.core.util.forEach
import androidx.core.util.set
import com.google.android.gms.tasks.Task
import com.google.firebase.ml.vision.FirebaseVision
import com.google.firebase.ml.vision.common.FirebaseVisionImage
import com.google.firebase.ml.vision.objects.FirebaseVisionObject
import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetector
import com.google.firebase.ml.vision.objects.FirebaseVisionObjectDetectorOptions
import com.google.firebase.ml.md.kotlin.camera.CameraReticleAnimator
import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay
import com.google.firebase.ml.md.R
import com.google.firebase.ml.md.kotlin.camera.WorkflowModel
import com.google.firebase.ml.md.kotlin.camera.FrameProcessorBase
import com.google.firebase.ml.md.kotlin.settings.PreferenceUtils
import java.io.IOException
import java.util.ArrayList
import kotlin.math.hypot
/** A processor to run object detector in multi-objects mode. */
class MultiObjectProcessor(graphicOverlay: GraphicOverlay, private val workflowModel: WorkflowModel) :
FrameProcessorBase<List<FirebaseVisionObject>>() {
private val confirmationController: ObjectConfirmationController = ObjectConfirmationController(graphicOverlay)
private val cameraReticleAnimator: CameraReticleAnimator = CameraReticleAnimator(graphicOverlay)
private val objectSelectionDistanceThreshold: Int = graphicOverlay
.resources
.getDimensionPixelOffset(R.dimen.object_selection_distance_threshold)
private val detector: FirebaseVisionObjectDetector
// Each new tracked object plays appearing animation exactly once.
private val objectDotAnimatorArray = SparseArray<ObjectDotAnimator>()
init {
val optionsBuilder = FirebaseVisionObjectDetectorOptions.Builder()
.setDetectorMode(FirebaseVisionObjectDetectorOptions.STREAM_MODE)
.enableMultipleObjects()
if (PreferenceUtils.isClassificationEnabled(graphicOverlay.context)) {
optionsBuilder.enableClassification()
}
this.detector = FirebaseVision.getInstance().getOnDeviceObjectDetector(optionsBuilder.build())
}
override fun stop() {
try {
detector.close()
} catch (e: IOException) {
Log.e(TAG, "Failed to close object detector!", e)
}
}
override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionObject>> {
return detector.processImage(image)
}
@MainThread
override fun onSuccess(
image: FirebaseVisionImage,
results: List<FirebaseVisionObject>,
graphicOverlay: GraphicOverlay
) {
var objects = results
if (!workflowModel.isCameraLive) {
return
}
if (PreferenceUtils.isClassificationEnabled(graphicOverlay.context)) {
val qualifiedObjects = ArrayList<FirebaseVisionObject>()
for (result in objects) {
if (result.classificationCategory != FirebaseVisionObject.CATEGORY_UNKNOWN) {
qualifiedObjects.add(result)
}
}
objects = qualifiedObjects
}
removeAnimatorsFromUntrackedObjects(objects)
graphicOverlay.clear()
var selectedObject: DetectedObject? = null
for (i in objects.indices) {
val result = objects[i]
if (selectedObject == null && shouldSelectObject(graphicOverlay, result)) {
selectedObject = DetectedObject(result, i, image)
// Starts the object confirmation once an object is regarded as selected.
confirmationController.confirming(result.trackingId)
graphicOverlay.add(ObjectConfirmationGraphic(graphicOverlay, confirmationController))
graphicOverlay.add(
ObjectGraphicInMultiMode(
graphicOverlay, selectedObject, confirmationController))
} else {
if (confirmationController.isConfirmed) {
// Don't render other objects when an object is in confirmed state.
continue
}
val trackingId = result.trackingId ?: return
val objectDotAnimator = objectDotAnimatorArray.get(trackingId) ?: let {
ObjectDotAnimator(graphicOverlay).apply {
start()
objectDotAnimatorArray[trackingId] = this
}
}
graphicOverlay.add(
ObjectDotGraphic(
graphicOverlay, DetectedObject(result, i, image), objectDotAnimator
)
)
}
}
if (selectedObject == null) {
confirmationController.reset()
graphicOverlay.add(ObjectReticleGraphic(graphicOverlay, cameraReticleAnimator))
cameraReticleAnimator.start()
} else {
cameraReticleAnimator.cancel()
}
graphicOverlay.invalidate()
if (selectedObject != null) {
workflowModel.confirmingObject(selectedObject, confirmationController.progress)
} else {
workflowModel.setWorkflowState(
if (objects.isEmpty()) {
WorkflowModel.WorkflowState.DETECTING
} else {
WorkflowModel.WorkflowState.DETECTED
}
)
}
}
private fun removeAnimatorsFromUntrackedObjects(detectedObjects: List<FirebaseVisionObject>) {
val trackingIds = detectedObjects.mapNotNull { it.trackingId }
// Stop and remove animators from the objects that have lost tracking.
val removedTrackingIds = ArrayList<Int>()
objectDotAnimatorArray.forEach { key, value ->
if (!trackingIds.contains(key)) {
value.cancel()
removedTrackingIds.add(key)
}
}
removedTrackingIds.forEach {
objectDotAnimatorArray.remove(it)
}
}
private fun shouldSelectObject(graphicOverlay: GraphicOverlay, visionObject: FirebaseVisionObject): Boolean {
// Considers an object as selected when the camera reticle touches the object dot.
val box = graphicOverlay.translateRect(visionObject.boundingBox)
val objectCenter = PointF((box.left + box.right) / 2f, (box.top + box.bottom) / 2f)
val reticleCenter = PointF(graphicOverlay.width / 2f, graphicOverlay.height / 2f)
val distance =
hypot((objectCenter.x - reticleCenter.x).toDouble(), (objectCenter.y - reticleCenter.y).toDouble())
return distance < objectSelectionDistanceThreshold
}
override fun onFailure(e: Exception) {
Log.e(TAG, "Object detection failed!", e)
}
companion object {
private const val TAG = "MultiObjectProcessor"
}
}
| apache-2.0 | 69434d589eb543f0e3fb89f10e5c3101 | 40.126984 | 115 | 0.664094 | 5.164784 | false | false | false | false |
nextras/orm-intellij | src/main/kotlin/org/nextras/orm/intellij/typeProvider/CollectionTypeProvider.kt | 1 | 4043 | package org.nextras.orm.intellij.typeProvider
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.jetbrains.php.PhpIndex
import com.jetbrains.php.lang.psi.elements.FieldReference
import com.jetbrains.php.lang.psi.elements.MethodReference
import com.jetbrains.php.lang.psi.elements.PhpNamedElement
import com.jetbrains.php.lang.psi.elements.Variable
import com.jetbrains.php.lang.psi.resolve.types.PhpType
import com.jetbrains.php.lang.psi.resolve.types.PhpTypeProvider4
import com.jetbrains.php.lang.psi.resolve.types.PhpTypeSignatureKey
import org.nextras.orm.intellij.utils.OrmUtils
import org.nextras.orm.intellij.utils.PhpIndexUtils
class CollectionTypeProvider : PhpTypeProvider4 {
override fun getKey(): Char {
return '\u0241'
}
override fun getType(element: PsiElement): PhpType? {
if (element !is MethodReference || element.classReference == null) {
return null
}
val methodName = element.name
if (!allMethods.contains(methodName)) {
return null
}
val isPluralMethod = pluralMethods.contains(methodName)
val arraySuffix = if (isPluralMethod) "[]" else ""
val parent = element.classReference!!
when (parent) {
is MethodReference -> {
val type = PhpType()
parent.type.types
.filter { it.startsWith("#$key") } // we propagate further only our signature
.forEach { subType ->
if (!isPluralMethod) {
type.add(subType.removeSuffix("[]"))
} else {
type.add(subType)
}
}
if (type.isEmpty) {
parent.type.types.forEach { subType ->
type.add("#$key$subType")
}
}
return type
}
is FieldReference -> {
if (!parent.resolveLocalType().isEmpty) {
return PhpType().add("#$key${parent.signature}$arraySuffix")
}
// allowed type -> general processing
}
is Variable -> {
// allowed type -> general processing
}
else -> {
return null
}
}
val type = PhpType()
parent.type.types
.forEach { subType ->
if (subType.startsWith("#$key")) {
if (!isPluralMethod) {
type.add(subType.removeSuffix("[]"))
} else {
type.add(subType)
}
} else {
type.add("#$key${subType.removeSuffix("[]")}$arraySuffix")
}
}
return type
}
override fun complete(expression: String, project: Project): PhpType? {
return null
}
override fun getBySignature(expression: String, visited: Set<String>, depth: Int, project: Project): Collection<PhpNamedElement>? {
if (expression.endsWith("[]")) {
return null
}
val index = PhpIndex.getInstance(project)
val classTypes = PhpIndexUtils.getByType(PhpType().add(expression), index)
if (classTypes.isEmpty()) {
return null
}
// $orm->books->getById()
val repoClassesList = classTypes.filter { OrmUtils.OrmClass.REPOSITORY.`is`(it, index) }
if (repoClassesList.isNotEmpty()) {
return OrmUtils.findRepositoryEntities(repoClassesList);
}
// $books->tags->toCollection()->getById()
val hasHasManyType = classTypes.any { OrmUtils.OrmClass.HAS_MANY.`is`(it, index) }
if (hasHasManyType && expression.startsWith("#")) {
val arrayElementType = PhpType().add(PhpTypeSignatureKey.ARRAY_ELEMENT.sign(expression))
return PhpIndexUtils.getByType(arrayElementType, index, visited, depth)
}
// $myCollection->getById()
val entityClassesList = classTypes.filter { OrmUtils.OrmClass.ENTITY.`is`(it, index) }
if (entityClassesList.isNotEmpty()) {
return entityClassesList
}
return null
}
companion object {
private val relationshipMethods = setOf("get", "toCollection")
private val collectionPluralMethods = setOf("findBy", "orderBy", "limitBy", "fetchAll", "findAll", "findById")
private val collectionSingularMethods = setOf("fetch", "getBy", "getById", "getByChecked", "getByIdChecked")
private val collectionMethods = collectionPluralMethods + collectionSingularMethods
private val pluralMethods = relationshipMethods + collectionPluralMethods
private val allMethods = relationshipMethods + collectionMethods
}
}
| mit | 81c4e0b5ddebe6fae9b81808055d1026 | 30.341085 | 132 | 0.706653 | 3.71258 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/ignore/actions/GitExcludeActions.kt | 6 | 4411 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.ignore.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.ProjectLevelVcsManager
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.IgnoredBeanFactory
import com.intellij.openapi.vcs.changes.actions.ScheduleForAdditionAction
import com.intellij.openapi.vcs.changes.ignore.actions.getSelectedFiles
import com.intellij.openapi.vcs.changes.ignore.actions.writeIgnoreFileEntries
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcsUtil.VcsUtil
import git4idea.GitUtil
import git4idea.GitVcs
import git4idea.i18n.GitBundle.messagePointer
import git4idea.ignore.lang.GitExcludeFileType
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NotNull
import java.util.function.Supplier
import kotlin.streams.toList
abstract class DefaultGitExcludeAction(dynamicText: @NotNull Supplier<@Nls String>,
dynamicDescription: @NotNull Supplier<@Nls String>)
: DumbAwareAction(dynamicText, dynamicDescription, GitExcludeFileType.INSTANCE.icon) {
override fun update(e: AnActionEvent) {
val enabled = isEnabled(e)
e.presentation.isVisible = enabled
e.presentation.isEnabled = enabled
}
protected open fun isEnabled(e: AnActionEvent): Boolean {
val project = e.getData(CommonDataKeys.PROJECT)
return (project != null && GitUtil.getRepositories(project).isNotEmpty())
}
}
class AddToGitExcludeAction : DefaultGitExcludeAction(
messagePointer("git.add.to.exclude.file.action.text"),
messagePointer("git.add.to.exclude.file.action.description")
) {
override fun isEnabled(e: AnActionEvent): Boolean {
val project = e.getData(CommonDataKeys.PROJECT) ?: return false
val selectedFiles = getSelectedFiles(e)
val unversionedFiles = ScheduleForAdditionAction.getUnversionedFiles(e, project)
return isEnabled(project, selectedFiles, unversionedFiles.toList())
}
internal fun isEnabled(project: Project, selectedFiles: List<VirtualFile>, unversionedFiles: List<VirtualFile>): Boolean {
val changeListManager = ChangeListManager.getInstance(project)
//ScheduleForAdditionAction.getUnversionedFiles can return already ignored directories for VCS which doesn't support directory versioning, should filter it here
if (unversionedFiles.none { !it.isDirectory || !changeListManager.isIgnoredFile(it) }) return false
val vcsManager = ProjectLevelVcsManager.getInstance(project)
return selectedFiles.any { vcsManager.getVcsFor(it)?.name == GitVcs.NAME }
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.getRequiredData(CommonDataKeys.PROJECT)
val gitVcs = GitVcs.getInstance(project)
val selectedFiles = getSelectedFiles(e)
if (selectedFiles.isEmpty()) return
val filesToIgnore =
VcsUtil.computeWithModalProgress(project, VcsBundle.message("ignoring.files.progress.title"), false) {
GitUtil.sortFilesByRepositoryIgnoringMissing(project, selectedFiles)
}
for ((repository, filesToAdd) in filesToIgnore) {
val gitExclude = repository.repositoryFiles.excludeFile.let { VfsUtil.findFileByIoFile(it, true) } ?: continue
val ignores = filesToAdd.map { file -> IgnoredBeanFactory.ignoreFile(file, project) }
writeIgnoreFileEntries(project, gitExclude, ignores, gitVcs, repository.root)
}
}
}
class OpenGitExcludeAction : DefaultGitExcludeAction(
messagePointer("git.open.exclude.file.action.text"),
messagePointer("git.open.exclude.file.action.description")
) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.getRequiredData(CommonDataKeys.PROJECT)
val excludeToOpen = GitUtil.getRepositories(project).map { it.repositoryFiles.excludeFile }
for (gitExclude in excludeToOpen) {
VfsUtil.findFileByIoFile(gitExclude, true)?.let { excludeVf ->
OpenFileDescriptor(project, excludeVf).navigate(true)
}
}
}
}
| apache-2.0 | 9a5365f9d8051ad1a42fd862fa91ae39 | 43.555556 | 164 | 0.781909 | 4.482724 | false | false | false | false |
smmribeiro/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereFileFeaturesProvider.kt | 1 | 5899 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.filePrediction.features.history.FileHistoryManagerWrapper
import com.intellij.ide.actions.GotoFileItemProvider
import com.intellij.ide.actions.searcheverywhere.FileSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.statistics.SearchEverywhereUsageTriggerCollector
import com.intellij.ide.favoritesTreeView.FavoritesManager
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.impl.EditorHistoryManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.util.PathUtil
import com.intellij.util.Time.*
internal class SearchEverywhereFileFeaturesProvider
: SearchEverywhereClassOrFileFeaturesProvider(FileSearchEverywhereContributor::class.java) {
companion object {
internal const val IS_DIRECTORY_DATA_KEY = "isDirectory"
internal const val FILETYPE_DATA_KEY = "fileType"
internal const val IS_FAVORITE_DATA_KEY = "isFavorite"
internal const val IS_OPENED_DATA_KEY = "isOpened"
internal const val RECENT_INDEX_DATA_KEY = "recentFilesIndex"
internal const val PREDICTION_SCORE_DATA_KEY = "predictionScore"
internal const val PRIORITY_DATA_KEY = "priority"
internal const val IS_EXACT_MATCH_DATA_KEY = "isExactMatch"
internal const val FILETYPE_MATCHES_QUERY_DATA_KEY = "fileTypeMatchesQuery"
internal const val TIME_SINCE_LAST_MODIFICATION_DATA_KEY = "timeSinceLastModification"
internal const val WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY = "wasModifiedInLastMinute"
internal const val WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY = "wasModifiedInLastHour"
internal const val WAS_MODIFIED_IN_LAST_DAY_DATA_KEY = "wasModifiedInLastDay"
internal const val WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY = "wasModifiedInLastMonth"
}
override fun getElementFeatures(element: PsiElement,
presentation: TargetPresentation?,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: Cache?): Map<String, Any> {
val item = (element as? PsiFileSystemItem) ?: return emptyMap()
val data = hashMapOf<String, Any>(
IS_FAVORITE_DATA_KEY to isFavorite(item),
IS_DIRECTORY_DATA_KEY to item.isDirectory,
PRIORITY_DATA_KEY to elementPriority,
IS_EXACT_MATCH_DATA_KEY to (elementPriority == GotoFileItemProvider.EXACT_MATCH_DEGREE),
SearchEverywhereUsageTriggerCollector.TOTAL_SYMBOLS_AMOUNT_DATA_KEY to searchQuery.length,
)
val nameOfItem = item.virtualFile.nameWithoutExtension
// Remove the directory and the extension if they are present
val fileNameFromQuery = FileUtil.getNameWithoutExtension(PathUtil.getFileName(searchQuery))
data.putAll(getNameMatchingFeatures(nameOfItem, fileNameFromQuery))
if (item.isDirectory) {
// Rest of the features are only applicable to files, not directories
return data
}
data[IS_OPENED_DATA_KEY] = isOpened(item)
data[FILETYPE_DATA_KEY] = item.virtualFile.fileType.name
data.putIfValueNotNull(FILETYPE_MATCHES_QUERY_DATA_KEY, matchesFileTypeInQuery(item, searchQuery))
data[RECENT_INDEX_DATA_KEY] = getRecentFilesIndex(item)
data[PREDICTION_SCORE_DATA_KEY] = getPredictionScore(item)
data.putAll(getModificationTimeStats(item, currentTime))
return data
}
private fun isFavorite(item: PsiFileSystemItem): Boolean {
val favoritesManager = FavoritesManager.getInstance(item.project)
return ReadAction.compute<Boolean, Nothing> { favoritesManager.getFavoriteListName(null, item.virtualFile) != null }
}
private fun isOpened(item: PsiFileSystemItem): Boolean {
val openedFiles = FileEditorManager.getInstance(item.project).openFiles
return item.virtualFile in openedFiles
}
private fun matchesFileTypeInQuery(item: PsiFileSystemItem, searchQuery: String): Boolean? {
val fileExtension = item.virtualFile.extension
val extensionInQuery = searchQuery.substringAfterLast('.', missingDelimiterValue = "")
if (extensionInQuery.isEmpty() || fileExtension == null) {
return null
}
return extensionInQuery == fileExtension
}
private fun getRecentFilesIndex(item: PsiFileSystemItem): Int {
val historyManager = EditorHistoryManager.getInstance(item.project)
val recentFilesList = historyManager.fileList
val fileIndex = recentFilesList.indexOf(item.virtualFile)
if (fileIndex == -1) {
return fileIndex
}
// Give the most recent files the lowest index value
return recentFilesList.size - fileIndex
}
private fun getModificationTimeStats(item: PsiFileSystemItem, currentTime: Long): Map<String, Any> {
val timeSinceLastMod = currentTime - item.virtualFile.timeStamp
return hashMapOf(
TIME_SINCE_LAST_MODIFICATION_DATA_KEY to timeSinceLastMod,
WAS_MODIFIED_IN_LAST_MINUTE_DATA_KEY to (timeSinceLastMod <= MINUTE),
WAS_MODIFIED_IN_LAST_HOUR_DATA_KEY to (timeSinceLastMod <= HOUR),
WAS_MODIFIED_IN_LAST_DAY_DATA_KEY to (timeSinceLastMod <= DAY),
WAS_MODIFIED_IN_LAST_MONTH_DATA_KEY to (timeSinceLastMod <= (4 * WEEK.toLong()))
)
}
private fun getPredictionScore(item: PsiFileSystemItem): Double {
val historyManagerWrapper = FileHistoryManagerWrapper.getInstance(item.project)
val probability = historyManagerWrapper.calcNextFileProbability(item.virtualFile)
return roundDouble(probability)
}
}
| apache-2.0 | cd311d03dbbcded10397252af4147692 | 45.81746 | 158 | 0.751822 | 4.565789 | false | false | false | false |
smmribeiro/intellij-community | java/java-impl/src/com/intellij/internal/statistic/libraryJar/libraryJarUtil.kt | 6 | 1706 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.libraryJar
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiPackage
import com.intellij.psi.search.ProjectScope
import java.util.jar.Attributes
private const val DIGIT_VERSION_PATTERN_PART = "(\\d+.\\d+|\\d+)"
private val JAR_FILE_NAME_PATTERN = Regex("[\\w|\\-.]+-($DIGIT_VERSION_PATTERN_PART[\\w|.]*)jar")
private fun versionByJarManifest(file: VirtualFile): String? = JarUtil.getJarAttribute(
VfsUtilCore.virtualToIoFile(file),
Attributes.Name.IMPLEMENTATION_VERSION,
)
private fun versionByJarFileName(fileName: String): String? {
val fileNameMatcher = JAR_FILE_NAME_PATTERN.matchEntire(fileName) ?: return null
val value = fileNameMatcher.groups[1]?.value ?: return null
return value.trimEnd('.')
}
private fun PsiElement.findCorrespondingVirtualFile(): VirtualFile? =
if (this is PsiPackage)
getDirectories(ProjectScope.getLibrariesScope(project)).firstOrNull()?.virtualFile
else
containingFile?.virtualFile
internal fun findJarVersion(elementFromJar: PsiElement): String? {
val vFile = elementFromJar.findCorrespondingVirtualFile() ?: return null
val jarFile = JarFileSystem.getInstance().getVirtualFileForJar(vFile) ?: return null
val version = versionByJarManifest(jarFile) ?: versionByJarFileName(jarFile.name) ?: return null
return version.takeIf(String::isNotEmpty)
}
| apache-2.0 | 8732ae61ea25d5c8be34938ed6cf46ae | 43.894737 | 158 | 0.784877 | 4.130751 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/ide/projectView/actions/MarkAsContentRootAction.kt | 8 | 1916 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.projectView.actions
import com.intellij.ide.projectView.impl.ProjectRootsUtil
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
class MarkAsContentRootAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY)
val module = MarkRootActionBase.getModule(e, files)
if (module == null || files == null) {
e.presentation.isEnabledAndVisible = false
return
}
val fileIndex = ProjectRootManager.getInstance(module.project).fileIndex
e.presentation.isEnabledAndVisible = files.all {
it.isDirectory && fileIndex.isExcluded(it) && ProjectRootsUtil.findExcludeFolder(module, it) == null
}
}
override fun actionPerformed(e: AnActionEvent) {
val files = e.getData(CommonDataKeys.VIRTUAL_FILE_ARRAY) ?: return
val module = MarkRootActionBase.getModule(e, files) ?: return
val model = ModuleRootManager.getInstance(module).modifiableModel
files.forEach {
model.addContentEntry(it)
}
MarkRootActionBase.commitModel(module, model)
}
}
| apache-2.0 | 6d6052d0156ca62c91542eeb4d12d58e | 38.916667 | 106 | 0.757829 | 4.374429 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/gtdProviders.kt | 1 | 3066 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.navigation.impl
import com.intellij.codeInsight.TargetElementUtil
import com.intellij.codeInsight.navigation.CtrlMouseInfo
import com.intellij.codeInsight.navigation.MultipleTargetElementsInfo
import com.intellij.codeInsight.navigation.SingleTargetElementInfo
import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandler
import com.intellij.codeInsight.navigation.impl.NavigationActionResult.SingleTarget
import com.intellij.codeInsight.navigation.targetPresentation
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
internal fun fromGTDProviders(project: Project, editor: Editor, offset: Int): GTDActionData? {
return processInjectionThenHost(editor, offset) { _editor, _offset ->
fromGTDProvidersInner(project, _editor, _offset)
}
}
/**
* @see com.intellij.codeInsight.navigation.actions.GotoDeclarationAction.findTargetElementsFromProviders
*/
private fun fromGTDProvidersInner(project: Project, editor: Editor, offset: Int): GTDActionData? {
val document = editor.document
val file = PsiDocumentManager.getInstance(project).getPsiFile(document) ?: return null
val adjustedOffset: Int = TargetElementUtil.adjustOffset(file, document, offset)
val leafElement: PsiElement = file.findElementAt(adjustedOffset) ?: return null
for (handler in GotoDeclarationHandler.EP_NAME.extensionList) {
val fromProvider: Array<out PsiElement>? = handler.getGotoDeclarationTargets(leafElement, offset, editor)
if (fromProvider.isNullOrEmpty()) {
continue
}
return GTDProviderData(leafElement, fromProvider.toList(), handler)
}
return null
}
private class GTDProviderData(
private val leafElement: PsiElement,
private val targetElements: Collection<PsiElement>,
private val navigationProvider: GotoDeclarationHandler
) : GTDActionData {
init {
require(targetElements.isNotEmpty())
}
override fun ctrlMouseInfo(): CtrlMouseInfo {
val singleTarget = targetElements.singleOrNull()
return if (singleTarget == null) {
MultipleTargetElementsInfo(leafElement)
}
else {
SingleTargetElementInfo(leafElement, singleTarget)
}
}
override fun result(): NavigationActionResult? {
return when (targetElements.size) {
0 -> null
1 -> {
targetElements.single().gtdTargetNavigatable()?.navigationRequest()?.let { request ->
SingleTarget(request, navigationProvider)
}
}
else -> {
val targets = targetElements.map { targetElement ->
LazyTargetWithPresentation(
{ targetElement.psiNavigatable()?.navigationRequest() },
targetPresentation(targetElement),
navigationProvider
)
}
NavigationActionResult.MultipleTargets(targets)
}
}
}
}
| apache-2.0 | d97636c9d1039a096c76bb8a05c13f95 | 37.325 | 158 | 0.754729 | 4.874404 | false | false | false | false |
devjn/GithubSearch | common/src/main/kotlin/com/github/devjn/githubsearch/model/db/DataBaseField.kt | 1 | 1034 | package com.github.devjn.githubsearch.model.db
class DataBaseField {
val fieldName: String
val fieldType: String
var isPrimaryKey: Boolean = false
var isAutoIncrement: Boolean = false
var isNotNull: Boolean = false
constructor(name: String, type: String, primaryKey: Boolean = false, autoIncrement: Boolean = false, notNull: Boolean) {
this.fieldName = name
this.fieldType = type
this.isPrimaryKey = primaryKey
this.isAutoIncrement = autoIncrement
this.isNotNull = notNull
}
constructor(name: String, type: String, primaryKey: Boolean, autoIncrement: Boolean) {
this.fieldName = name
this.fieldType = type
this.isPrimaryKey = primaryKey
this.isAutoIncrement = autoIncrement
this.isNotNull = false
}
constructor(name: String, type: String) {
this.fieldName = name
this.fieldType = type
this.isPrimaryKey = false
this.isAutoIncrement = false
this.isNotNull = true
}
} | apache-2.0 | 1ffa684ee02c15ab1ba75df9c07919bf | 29.441176 | 124 | 0.661509 | 4.764977 | false | false | false | false |
johnjohndoe/Umweltzone | Umweltzone/src/main/java/de/avpptr/umweltzone/zones/viewholders/TwoZonesViewHolder.kt | 1 | 2282 | /*
* Copyright (C) 2020 Tobias Preuss
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.avpptr.umweltzone.zones.viewholders
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.view.View
import androidx.annotation.LayoutRes
import de.avpptr.umweltzone.R
import de.avpptr.umweltzone.zones.viewmodels.ZoneViewModel
import kotlinx.android.synthetic.main.zones_list_item_two_zones.view.*
class TwoZonesViewHolder(
val view: View,
private val onItemClick: (view: View) -> Unit
) : ZoneViewHolder<ZoneViewModel.TwoZonesViewModel>(view) {
private val zoneShape1View: GradientDrawable
private val zoneShape2View: GradientDrawable
init {
val badge1Background = view.zoneTwoZonesBadge1View.background as LayerDrawable
zoneShape1View = badge1Background.findDrawableByLayerId(R.id.zone_shape) as GradientDrawable
val badge2Background = view.zoneTwoZonesBadge2View.background as LayerDrawable
zoneShape2View = badge2Background.findDrawableByLayerId(R.id.zone_shape) as GradientDrawable
}
override fun bind(viewModel: ZoneViewModel.TwoZonesViewModel) = with(view) {
tag = viewModel
setOnClickListener(onItemClick)
zoneTwoZonesNameView.text = viewModel.name
zoneTwoZonesNameView.setTextColor(viewModel.nameTextColor)
zoneTwoZonesBadge1View.setBadge(zoneShape1View, viewModel.badge1ViewModel)
zoneTwoZonesBadge2View.setBadge(zoneShape2View, viewModel.badge2ViewModel)
}
companion object {
@LayoutRes
const val layout = R.layout.zones_list_item_two_zones
}
}
| gpl-3.0 | dc2ddf6c8089ad51ecf2ee0710084af3 | 37.677966 | 100 | 0.756354 | 4.210332 | false | false | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/application/options/editor/EditorSmartKeysConfigurable.kt | 1 | 9576 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application.options.editor
import com.intellij.codeInsight.CodeInsightSettings.*
import com.intellij.codeInsight.editorActions.SmartBackspaceMode
import com.intellij.lang.CodeDocumentationAwareCommenter
import com.intellij.lang.Language
import com.intellij.lang.LanguageCommenters
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.keymap.impl.ModifierKeyDoubleClickHandler
import com.intellij.openapi.options.*
import com.intellij.openapi.options.ex.ConfigurableWrapper
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.EnumComboBoxModel
import com.intellij.ui.layout.*
import org.jetbrains.annotations.NonNls
import java.awt.event.KeyEvent
import javax.swing.DefaultComboBoxModel
// @formatter:off
private val editorSettings = EditorSettingsExternalizable.getInstance()
private val codeInsightSettings = getInstance()
private val myCbSmartHome get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.smart.home"), PropertyBinding(editorSettings::isSmartHome, editorSettings::setSmartHome))
private val myCbSmartEnd get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.smart.end.on.blank.line"), codeInsightSettings::SMART_END_ACTION.toBinding())
private val myCbInsertPairBracket get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.insert.pair.bracket"), codeInsightSettings::AUTOINSERT_PAIR_BRACKET.toBinding())
private val myCbInsertPairQuote get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.insert.pair.quote"), codeInsightSettings::AUTOINSERT_PAIR_QUOTE.toBinding())
private val myCbReformatBlockOnTypingRBrace get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.reformat.on.typing.rbrace"), codeInsightSettings::REFORMAT_BLOCK_ON_RBRACE.toBinding())
private val myCbCamelWords get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.use.camelhumps.words"), PropertyBinding(editorSettings::isCamelWords, editorSettings::setCamelWords))
private val myCbSurroundSelectionOnTyping get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.surround.selection.on.typing.quote.or.brace"), codeInsightSettings::SURROUND_SELECTION_ON_QUOTE_TYPED.toBinding())
private val myCbTabExistsBracketsAndQuotes get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.tab.exists.brackets.and.quotes"), codeInsightSettings::TAB_EXITS_BRACKETS_AND_QUOTES.toBinding())
private val myCbEnableAddingCaretsOnDoubleCtrlArrows get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.enable.double.ctrl", KeyEvent.getKeyText(ModifierKeyDoubleClickHandler.getMultiCaretActionModifier())), PropertyBinding(editorSettings::addCaretsOnDoubleCtrl, editorSettings::setAddCaretsOnDoubleCtrl))
private val myCbSmartIndentOnEnter get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.smart.indent"), codeInsightSettings::SMART_INDENT_ON_ENTER.toBinding())
private val myCbInsertPairCurlyBraceOnEnter get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.insert.pair.curly.brace"), codeInsightSettings::INSERT_BRACE_ON_ENTER.toBinding())
private val myCbInsertJavadocStubOnEnter get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.javadoc.stub.after.slash.star.star"), codeInsightSettings::JAVADOC_STUB_ON_ENTER.toBinding())
internal val myCbHonorCamelHumpsWhenSelectingByClicking get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.honor.camelhumps.words.settings.on.double.click"), PropertyBinding(editorSettings::isMouseClickSelectionHonorsCamelWords, editorSettings::setMouseClickSelectionHonorsCamelWords))
// @formatter:on
private val childOptions = EditorSmartKeysConfigurable().configurables
.map { c -> if (c is ConfigurableWrapper) c.configurable else c }
.flatMap { c -> if (c is ConfigurableWithOptionDescriptors) c.getOptionDescriptors(ID, { s -> s }) else emptyList() }
internal val editorSmartKeysOptionDescriptors = listOf(
myCbSmartHome,
myCbSmartEnd,
myCbInsertPairBracket,
myCbInsertPairQuote,
myCbReformatBlockOnTypingRBrace,
myCbCamelWords,
myCbSurroundSelectionOnTyping,
myCbTabExistsBracketsAndQuotes,
myCbEnableAddingCaretsOnDoubleCtrlArrows,
myCbSmartIndentOnEnter,
myCbInsertPairCurlyBraceOnEnter,
myCbInsertJavadocStubOnEnter,
myCbHonorCamelHumpsWhenSelectingByClicking
).map(CheckboxDescriptor::asOptionDescriptor) + childOptions
@NonNls
const val ID = "editor.preferences.smartKeys"
/**
* To provide additional options in Editor | Smart Keys section register implementation of {@link com.intellij.openapi.options.UnnamedConfigurable} in the plugin.xml:
* <p/>
* <extensions defaultExtensionNs="com.intellij"><br>
* <editorSmartKeysConfigurable instance="class-name"/><br>
* </extensions>
* <p>
* A new instance of the specified class will be created each time then the Settings dialog is opened
*
* @author yole
*/
class EditorSmartKeysConfigurable : Configurable.WithEpDependencies, BoundCompositeSearchableConfigurable<UnnamedConfigurable>(
ApplicationBundle.message("group.smart.keys"),
"reference.settingsdialog.IDE.editor.smartkey",
ID
), SearchableConfigurable.Parent {
override fun createPanel(): DialogPanel {
return panel {
row {
checkBox(myCbSmartHome)
}
row {
checkBox(myCbSmartEnd)
}
row {
checkBox(myCbInsertPairBracket)
}
row {
checkBox(myCbInsertPairQuote)
}
row {
checkBox(myCbReformatBlockOnTypingRBrace)
}
row {
checkBox(myCbCamelWords)
}
row {
checkBox(myCbHonorCamelHumpsWhenSelectingByClicking)
}
row {
checkBox(myCbSurroundSelectionOnTyping)
}
row {
checkBox(myCbEnableAddingCaretsOnDoubleCtrlArrows)
}
row {
checkBox(myCbTabExistsBracketsAndQuotes)
}
titledRow(ApplicationBundle.message("group.enter.title")) {
row {
checkBox(myCbSmartIndentOnEnter)
}
row {
checkBox(myCbInsertPairCurlyBraceOnEnter)
}
if (hasAnyDocAwareCommenters()) {
row {
checkBox(myCbInsertJavadocStubOnEnter)
}
}
}
row(ApplicationBundle.message("combobox.smart.backspace")) {
comboBox(
EnumComboBoxModel(SmartBackspaceMode::class.java),
PropertyBinding(codeInsightSettings::getBackspaceMode, codeInsightSettings::setBackspaceMode).toNullable(),
renderer = listCellRenderer { value, _, _ ->
setText(when(value) {
SmartBackspaceMode.OFF -> ApplicationBundle.message("combobox.smart.backspace.off")
SmartBackspaceMode.INDENT -> ApplicationBundle.message("combobox.smart.backspace.simple")
SmartBackspaceMode.AUTOINDENT -> ApplicationBundle.message("combobox.smart.backspace.smart")
else -> ""
})
})
}
row(ApplicationBundle.message("combobox.paste.reformat")) {
comboBox(
DefaultComboBoxModel(arrayOf(NO_REFORMAT, INDENT_BLOCK, INDENT_EACH_LINE, REFORMAT_BLOCK)),
codeInsightSettings::REFORMAT_ON_PASTE,
renderer = listCellRenderer { value, _, _ ->
setText(when(value) {
NO_REFORMAT -> ApplicationBundle.message("combobox.paste.reformat.none")
INDENT_BLOCK -> ApplicationBundle.message("combobox.paste.reformat.indent.block")
INDENT_EACH_LINE -> ApplicationBundle.message("combobox.paste.reformat.indent.each.line")
REFORMAT_BLOCK -> ApplicationBundle.message("combobox.paste.reformat.reformat.block")
else -> ""
})
}
)
}
for (configurable in configurables) {
row {
configurable.createComponent()?.invoke(growX)
}
}
}
}
private fun hasAnyDocAwareCommenters(): Boolean {
return Language.getRegisteredLanguages().any {
val commenter = LanguageCommenters.INSTANCE.forLanguage(it)
commenter is CodeDocumentationAwareCommenter && commenter.documentationCommentLinePrefix != null
}
}
override fun apply() {
super.apply()
ApplicationManager.getApplication().messageBus.syncPublisher(EditorOptionsListener.SMART_KEYS_CONFIGURABLE_TOPIC).changesApplied()
}
override fun createConfigurables(): List<UnnamedConfigurable> {
return ConfigurableWrapper.createConfigurables(EP_NAME).filterNot { it is Configurable }
}
override fun getConfigurables(): Array<Configurable> {
val configurables = ConfigurableWrapper.createConfigurables(EP_NAME)
return configurables.filterIsInstance<Configurable>().toTypedArray()
}
override fun hasOwnContent() = true
override fun getDependencies() = listOf(EP_NAME)
companion object {
private val EP_NAME = ExtensionPointName.create<EditorSmartKeysConfigurableEP>("com.intellij.editorSmartKeysConfigurable")
}
}
| apache-2.0 | c2053c410994436b697111df5ff4817d | 49.4 | 327 | 0.73444 | 4.68952 | false | true | false | false |
siosio/intellij-community | platform/elevation/client/src/com/intellij/execution/process/mediator/client/MediatedProcess.kt | 1 | 8304 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("EXPERIMENTAL_API_USAGE")
package com.intellij.execution.process.mediator.client
import com.google.protobuf.ByteString
import com.intellij.execution.process.SelfKiller
import com.intellij.execution.process.mediator.daemon.QuotaExceededException
import com.intellij.execution.process.mediator.util.ChannelInputStream
import com.intellij.execution.process.mediator.util.ChannelOutputStream
import com.intellij.execution.process.mediator.util.blockingGet
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.future.asCompletableFuture
import java.io.*
import java.lang.ref.Cleaner
import java.util.concurrent.CompletableFuture
import kotlin.coroutines.coroutineContext
private val CLEANER = Cleaner.create()
class MediatedProcess private constructor(
private val handle: MediatedProcessHandle,
command: List<String>, workingDir: File, environVars: Map<String, String>,
inFile: File?, outFile: File?, errFile: File?, redirectErrorStream: Boolean
) : Process(), SelfKiller {
companion object {
@Throws(IOException::class,
QuotaExceededException::class,
CancellationException::class)
fun create(processMediatorClient: ProcessMediatorClient,
processBuilder: ProcessBuilder): MediatedProcess {
val workingDir = processBuilder.directory() ?: File(".").normalize() // defaults to current working directory
val inFile = processBuilder.redirectInput().file()
val outFile = processBuilder.redirectOutput().file()
val errFile = processBuilder.redirectError().file()
val handle = MediatedProcessHandle.create(processMediatorClient)
return try {
MediatedProcess(handle,
processBuilder.command(), workingDir, processBuilder.environment(),
inFile, outFile, errFile, processBuilder.redirectErrorStream()).apply {
val cleanable = CLEANER.register(this, handle::releaseAsync)
onExit().thenRun { cleanable.clean() }
}
}
catch (e: Throwable) {
handle.rpcScope.cancel(e as? CancellationException ?: CancellationException("Failed to create process", e))
throw e
}
}
}
private val pid = runBlocking {
handle.rpc { handleId ->
createProcess(handleId, command, workingDir, environVars, inFile, outFile, errFile, redirectErrorStream)
}
}
private val stdin: OutputStream = if (inFile == null) createOutputStream(0) else NullOutputStream
private val stdout: InputStream = if (outFile == null) createInputStream(1) else NullInputStream
private val stderr: InputStream = if (errFile == null && !redirectErrorStream) createInputStream(2) else NullInputStream
private val termination: Deferred<Int> = handle.rpcScope.async {
handle.rpc { handleId ->
awaitTermination(handleId)
}
}
override fun pid(): Long = pid
override fun getOutputStream(): OutputStream = stdin
override fun getInputStream(): InputStream = stdout
override fun getErrorStream(): InputStream = stderr
@Suppress("EXPERIMENTAL_API_USAGE")
private fun createOutputStream(@Suppress("SameParameterValue") fd: Int): OutputStream {
val ackFlow = MutableStateFlow<Long?>(0L)
val channel = handle.rpcScope.actor<ByteString>(capacity = Channel.BUFFERED) {
handle.rpc { handleId ->
try {
// NOTE: Must never consume the channel associated with the actor. In fact, the channel IS the actor coroutine,
// and cancelling it makes the coroutine die in a horrible way leaving the remote call in a broken state.
writeStream(handleId, fd, channel.receiveAsFlow())
.onCompletion { ackFlow.value = null }
.fold(0L) { l, _ ->
(l + 1).also {
ackFlow.value = it
}
}
}
catch (e: IOException) {
channel.cancel(CancellationException(e.message, e))
}
}
}
val stream = ChannelOutputStream(channel, ackFlow)
return BufferedOutputStream(stream)
}
@Suppress("EXPERIMENTAL_API_USAGE")
private fun createInputStream(fd: Int): InputStream {
val channel = handle.rpcScope.produce<ByteString>(capacity = Channel.BUFFERED) {
handle.rpc { handleId ->
try {
readStream(handleId, fd).collect(channel::send)
}
catch (e: IOException) {
channel.close(e)
}
}
}
val stream = ChannelInputStream(channel)
return BufferedInputStream(stream)
}
override fun waitFor(): Int = termination.blockingGet()
override fun onExit(): CompletableFuture<Process> = termination.asCompletableFuture().thenApply { this }
override fun exitValue(): Int {
return try {
@Suppress("EXPERIMENTAL_API_USAGE")
termination.getCompleted()
}
catch (e: IllegalStateException) {
throw IllegalThreadStateException(e.message)
}
}
override fun destroy() {
destroy(false)
}
override fun destroyForcibly(): Process {
destroy(true)
return this
}
fun destroy(force: Boolean, destroyGroup: Boolean = false) {
// In case this is called after releasing the handle (due to process termination),
// it just does nothing, without throwing any error.
handle.rpcScope.launch {
handle.rpc { handleId ->
destroyProcess(handleId, force, destroyGroup)
}
}
}
private object NullInputStream : InputStream() {
override fun read(): Int = -1
override fun available(): Int = 0
}
private object NullOutputStream : OutputStream() {
override fun write(b: Int) = throw IOException("Stream closed")
}
}
/**
* All remote calls are performed using the provided [ProcessMediatorClient],
* and the whole process lifecycle is contained within the coroutine scope of the client.
* Normal remote calls (those besides process creation and release) are performed within the scope of the handle object.
*/
private class MediatedProcessHandle private constructor(
private val client: ProcessMediatorClient,
private val handleId: Long,
private val lifetimeChannel: ReceiveChannel<*>,
) {
companion object {
fun create(client: ProcessMediatorClient): MediatedProcessHandle {
val lifetimeChannel = client.openHandle().produceIn(client.coroutineScope)
try {
val handleId = runBlocking {
lifetimeChannel.receiveOrNull() ?: throw IOException("Failed to receive handleId")
}
return MediatedProcessHandle(client, handleId, lifetimeChannel)
}
catch (e: Throwable) {
lifetimeChannel.cancel(e as? CancellationException ?: CancellationException("Failed to initialize client-side handle", e))
throw e
}
}
}
private val parentScope: CoroutineScope = client.coroutineScope
private val lifetimeJob = parentScope.launch {
try {
lifetimeChannel.receive()
}
catch (e: ClosedReceiveChannelException) {
throw CancellationException("closed", e)
}
error("unreachable")
}
private val rpcJob: CompletableJob = SupervisorJob(lifetimeJob).apply {
invokeOnCompletion { e ->
lifetimeChannel.cancel(e as? CancellationException ?: CancellationException("Complete", e))
}
}
val rpcScope: CoroutineScope = parentScope + rpcJob
suspend fun <R> rpc(block: suspend ProcessMediatorClient.(handleId: Long) -> R): R {
rpcScope.ensureActive()
coroutineContext.ensureActive()
// Perform the call in the scope of this handle, so that it is dispatched in the same way as OpenHandle().
// This overrides the parent so that we can await for the call to complete before closing the lifetimeChannel;
// at the same time we ensure the caller is still able to cancel it.
val deferred = rpcScope.async {
client.block(handleId)
}
return try {
deferred.await()
}
catch (e: CancellationException) {
deferred.cancel(e)
throw e
}
}
fun releaseAsync() {
// let ongoing operations finish gracefully,
// and once all of them finish don't accept new calls
rpcJob.complete()
}
}
| apache-2.0 | 48a46c8eb72021984bc84dc53022782b | 35.262009 | 140 | 0.69605 | 4.670416 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/jps/jps-common/src/org/jetbrains/kotlin/platform/IdePlatformKind.kt | 1 | 3210 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("IdePlatformKindUtil")
package org.jetbrains.kotlin.platform
import com.intellij.openapi.diagnostic.Logger
import org.jetbrains.kotlin.cli.common.arguments.CommonCompilerArguments
import org.jetbrains.kotlin.config.isJps
import org.jetbrains.kotlin.extensions.ApplicationExtensionDescriptor
import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
abstract class IdePlatformKind<Kind : IdePlatformKind<Kind>> {
abstract fun supportsTargetPlatform(platform: TargetPlatform): Boolean
abstract val defaultPlatform: TargetPlatform
@Suppress("DEPRECATION_ERROR", "DeprecatedCallableAddReplaceWith")
@Deprecated(
message = "IdePlatform is deprecated and will be removed soon, please, migrate to org.jetbrains.kotlin.platform.TargetPlatform",
level = DeprecationLevel.ERROR
)
abstract fun getDefaultPlatform(): IdePlatform<*, *>
abstract fun platformByCompilerArguments(arguments: CommonCompilerArguments): TargetPlatform?
abstract val argumentsClass: Class<out CommonCompilerArguments>
abstract val name: String
abstract fun createArguments(): CommonCompilerArguments
override fun equals(other: Any?): Boolean = javaClass == other?.javaClass
override fun hashCode(): Int = javaClass.hashCode()
override fun toString() = name
companion object {
// We can't use the ApplicationExtensionDescriptor class directly because it's missing in the JPS process
private val extension = run {
if (isJps) return@run null
ApplicationExtensionDescriptor("org.jetbrains.kotlin.idePlatformKind", IdePlatformKind::class.java)
}
// For using only in JPS
private val JPS_KINDS
get() = listOf(
JvmIdePlatformKind,
JsIdePlatformKind,
CommonIdePlatformKind,
NativeIdePlatformKind
)
val ALL_KINDS by lazy {
val kinds = extension?.getInstances() ?: return@lazy JPS_KINDS
require(kinds.isNotEmpty()) { "Platform kind list is empty" }
kinds
}
fun <Args : CommonCompilerArguments> platformByCompilerArguments(arguments: Args): TargetPlatform? =
ALL_KINDS.firstNotNullResult { it.platformByCompilerArguments(arguments) }
}
}
val TargetPlatform.idePlatformKind: IdePlatformKind<*>
get() = IdePlatformKind.ALL_KINDS.filter { it.supportsTargetPlatform(this) }.let { list ->
when {
list.size == 1 -> list.first()
list.size > 1 -> list.first().also {
Logger.getInstance(IdePlatformKind.javaClass).warn("Found more than one IdePlatformKind [$list] for target [$this].")
}
else -> error("Unknown platform $this")
}
} | apache-2.0 | 9a94079c73cda4c6b96d20097e4b5944 | 39.1375 | 158 | 0.709969 | 5.202593 | false | false | false | false |
idea4bsd/idea4bsd | platform/script-debugger/backend/src/StandaloneVmHelper.kt | 10 | 3132 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.util.io.addChannelListener
import com.intellij.util.io.shutdownIfOio
import io.netty.channel.Channel
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.errorIfNotMessage
import org.jetbrains.concurrency.nullPromise
import org.jetbrains.jsonProtocol.Request
import org.jetbrains.rpc.CONNECTION_CLOSED_MESSAGE
import org.jetbrains.rpc.LOG
import org.jetbrains.rpc.MessageProcessor
open class StandaloneVmHelper(private val vm: Vm, private val messageProcessor: MessageProcessor, channel: Channel) : AttachStateManager {
private @Volatile var channel: Channel? = channel
fun getChannelIfActive(): Channel? {
val currentChannel = channel
return if (currentChannel == null || !currentChannel.isActive) null else currentChannel
}
fun write(content: Any): Boolean {
val channel = getChannelIfActive()
return channel != null && !channel.writeAndFlush(content).isCancelled
}
interface VmEx : Vm {
fun createDisconnectRequest(): Request<out Any>?
}
override val isAttached: Boolean
get() = channel != null
override fun detach(): Promise<*> {
val currentChannel = channel ?: return nullPromise()
messageProcessor.cancelWaitingRequests()
val disconnectRequest = (vm as? VmEx)?.createDisconnectRequest()
val promise = AsyncPromise<Any?>()
if (disconnectRequest == null) {
messageProcessor.closed()
channel = null
}
else {
messageProcessor.send(disconnectRequest)
.rejected {
if (it.message != CONNECTION_CLOSED_MESSAGE) {
LOG.errorIfNotMessage(it)
}
}
// we don't wait response because 1) no response to "disconnect" message (V8 for example) 2) closed message manager just ignore any incoming messages
currentChannel.flush()
messageProcessor.closed()
channel = null
messageProcessor.cancelWaitingRequests()
}
closeChannel(currentChannel, promise)
return promise
}
protected open fun closeChannel(channel: Channel, promise: AsyncPromise<Any?>) {
doCloseChannel(channel, promise)
}
}
fun doCloseChannel(channel: Channel, promise: AsyncPromise<Any?>) {
channel.close().addChannelListener {
try {
it.channel().eventLoop().shutdownIfOio()
}
finally {
val error = it.cause()
if (error == null) {
promise.setResult(null)
}
else {
promise.setError(error)
}
}
}
} | apache-2.0 | eb1297afbc4b65288eb00961cae1602f | 31.298969 | 155 | 0.714559 | 4.436261 | false | false | false | false |
stoyicker/dinger | data/src/main/kotlin/data/stoyicker/versioncheck/VersionCheckSourceModule.kt | 1 | 1803 | package data.stoyicker.versioncheck
import com.nytimes.android.external.store3.base.Fetcher
import com.nytimes.android.external.store3.base.impl.FluentMemoryPolicyBuilder
import com.nytimes.android.external.store3.base.impl.FluentStoreBuilder
import com.nytimes.android.external.store3.base.impl.StalePolicy
import com.nytimes.android.external.store3.base.impl.Store
import com.nytimes.android.external.store3.middleware.moshi.MoshiParserFactory
import com.squareup.moshi.Moshi
import dagger.Module
import dagger.Provides
import data.crash.CrashReporterModule
import data.network.ParserModule
import data.stoyicker.StoyickerApi
import data.stoyicker.StoyickerApiModule
import okio.BufferedSource
import reporter.CrashReporter
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
import dagger.Lazy as DaggerLazy
@Module(includes = [
ParserModule::class, StoyickerApiModule::class, CrashReporterModule::class])
internal class VersionCheckSourceModule {
@Provides
@Singleton
fun store(moshiBuilder: Moshi.Builder, api: StoyickerApi) =
FluentStoreBuilder.parsedWithKey<Unit, BufferedSource, VersionCheckResponse>(
Fetcher { fetch(api) }) {
parsers = listOf(MoshiParserFactory.createSourceParser(
moshiBuilder.build(), VersionCheckResponse::class.java))
memoryPolicy = FluentMemoryPolicyBuilder.build {
expireAfterWrite = 1
expireAfterTimeUnit = TimeUnit.SECONDS
memorySize = 0
}
stalePolicy = StalePolicy.REFRESH_ON_STALE
}
@Provides
@Singleton
fun source(store: DaggerLazy<Store<VersionCheckResponse, Unit>>,
crashReporter: CrashReporter) = VersionCheckSource(store, crashReporter)
private fun fetch(api: StoyickerApi) = api.versionCheck().map { it.source() }
}
| mit | 23fe35dbb28efb4504ac08eefd25a267 | 38.195652 | 85 | 0.780921 | 4.303103 | false | false | false | false |
androidx/androidx | benchmark/benchmark/src/androidTest/java/androidx/benchmark/benchmark/ParameterizedBenchmark.kt | 3 | 1427 | /*
* 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.benchmark.benchmark
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.filters.LargeTest
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
@LargeTest
@RunWith(Parameterized::class)
class ParameterizedBenchmark(
@Suppress("unused") private val input: Int,
@Suppress("unused") private val stringInput: String
) {
companion object {
@JvmStatic
@Parameters(name = "size={0},str:{1}")
fun data(): Collection<Array<Any>> = List(2) { arrayOf(it, "$it=:") }
}
@get:Rule
val benchmarkRule = BenchmarkRule()
@Test
fun noop() = benchmarkRule.measureRepeated {}
}
| apache-2.0 | aa45943de81b148f3d4b9129864b3d1b | 30.711111 | 77 | 0.733707 | 4.16035 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KotlinMemberSelectionTable.kt | 4 | 2894 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.icons.AllIcons
import com.intellij.refactoring.classMembers.MemberInfoModel
import com.intellij.refactoring.ui.AbstractMemberSelectionTable
import com.intellij.ui.RowIcon
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinIconProvider
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import javax.swing.Icon
class KotlinMemberSelectionTable(
memberInfos: List<KotlinMemberInfo>,
memberInfoModel: MemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>?,
@Nls abstractColumnHeader: String?
) : AbstractMemberSelectionTable<KtNamedDeclaration, KotlinMemberInfo>(memberInfos, memberInfoModel, abstractColumnHeader) {
override fun getAbstractColumnValue(memberInfo: KotlinMemberInfo): Any? {
if (memberInfo.isStatic || memberInfo.isCompanionMember) return null
val member = memberInfo.member
if (member !is KtNamedFunction && member !is KtProperty && member !is KtParameter) return null
if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
myMemberInfoModel.isFixedAbstract(memberInfo)?.let { return it }
}
if (myMemberInfoModel.isAbstractEnabled(memberInfo)) return memberInfo.isToAbstract
return myMemberInfoModel.isAbstractWhenDisabled(memberInfo)
}
override fun isAbstractColumnEditable(rowIndex: Int): Boolean {
val memberInfo = myMemberInfos[rowIndex]
if (memberInfo.isStatic) return false
val member = memberInfo.member
if (member !is KtNamedFunction && member !is KtProperty && member !is KtParameter) return false
if (member.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
myMemberInfoModel.isFixedAbstract(memberInfo)?.let { return false }
}
return memberInfo.isChecked && myMemberInfoModel.isAbstractEnabled(memberInfo)
}
override fun setVisibilityIcon(memberInfo: KotlinMemberInfo, icon: RowIcon) {
icon.setIcon(KotlinIconProvider.getVisibilityIcon(memberInfo.member.modifierList), 1)
}
override fun getOverrideIcon(memberInfo: KotlinMemberInfo): Icon? {
val defaultIcon = EMPTY_OVERRIDE_ICON
val member = memberInfo.member
if (member !is KtNamedFunction && member !is KtProperty && member !is KtParameter) return defaultIcon
return when (memberInfo.overrides) {
true -> AllIcons.General.OverridingMethod
false -> AllIcons.General.ImplementingMethod
else -> defaultIcon
}
}
} | apache-2.0 | acc608bd2e9878d087fbfce2cc770de2 | 42.208955 | 158 | 0.750864 | 5.077193 | false | false | false | false |
SDS-Studios/ScoreKeeper | app/src/main/java/io/github/sdsstudios/ScoreKeeper/Fragment/ObservableRecyclerViewFragment.kt | 1 | 1875 | package io.github.sdsstudios.ScoreKeeper.Fragment
import android.arch.lifecycle.Observer
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import io.github.sdsstudios.ScoreKeeper.Adapters.BaseRecyclerViewAdapter
import io.github.sdsstudios.ScoreKeeper.R
/**
* Created by sethsch1 on 29/10/17.
*/
abstract class ObservableRecyclerViewFragment<T, A : BaseRecyclerViewAdapter<T, *>>
: RecyclerViewFragment<A>() {
protected val observer = Observer<List<T>> { list ->
adapter.modelList = list!!
adapter.notifyDataSetChanged()
onFinishedLoading()
}
private lateinit var mProgressBar: ProgressBar
private lateinit var mTextViewNoItems: TextView
private var mFinishedLoading = false
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mProgressBar = view.findViewById(R.id.progressBar)
mTextViewNoItems = view.findViewById(R.id.textViewNoItems)
mTextViewNoItems.text = getNoItemsText()
if (mFinishedLoading) {
determineTextNoItemsVisibility()
attachAdapterToRecyclerView()
} else {
mProgressBar.visibility = View.VISIBLE
}
}
fun determineTextNoItemsVisibility() {
if (adapter.modelList.isEmpty()) {
recyclerView.visibility = View.GONE
mTextViewNoItems.visibility = View.VISIBLE
} else {
recyclerView.visibility = View.VISIBLE
mTextViewNoItems.visibility = View.GONE
}
}
fun onFinishedLoading() {
determineTextNoItemsVisibility()
mFinishedLoading = true
mProgressBar.visibility = View.GONE
attachAdapterToRecyclerView()
}
abstract fun getNoItemsText(): CharSequence
} | gpl-3.0 | 35bf7cd86c4b11af569ddfca37594854 | 28.3125 | 83 | 0.694933 | 4.844961 | false | false | false | false |
siosio/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/ExtractMethodHelper.kt | 1 | 10767 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.extractMethod.newImpl
import com.intellij.codeInsight.Nullability
import com.intellij.codeInsight.NullableNotNullManager
import com.intellij.codeInsight.PsiEquivalenceUtil
import com.intellij.codeInsight.generation.GenerateMembersUtil
import com.intellij.codeInsight.intention.AddAnnotationPsiFix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.formatter.java.MultipleFieldDeclarationHelper
import com.intellij.psi.impl.source.DummyHolder
import com.intellij.psi.impl.source.codeStyle.JavaCodeStyleManagerImpl
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput.*
import com.intellij.refactoring.extractMethod.newImpl.structures.ExtractOptions
import com.intellij.refactoring.extractMethod.newImpl.structures.InputParameter
import com.intellij.refactoring.util.RefactoringUtil
object ExtractMethodHelper {
@JvmStatic
fun findEditorSelection(editor: Editor): TextRange? {
val selectionModel = editor.selectionModel
return if (selectionModel.hasSelection()) TextRange(selectionModel.selectionStart, selectionModel.selectionEnd) else null
}
fun isNullabilityAvailable(extractOptions: ExtractOptions): Boolean {
val project = extractOptions.project
val scope = extractOptions.elements.first().resolveScope
val defaultNullable = NullableNotNullManager.getInstance(project).defaultNullable
val annotationClass = JavaPsiFacade.getInstance(project).findClass(defaultNullable, scope)
return annotationClass != null
}
fun wrapWithCodeBlock(elements: List<PsiElement>): List<PsiCodeBlock> {
require(elements.isNotEmpty())
val codeBlock = PsiElementFactory.getInstance(elements.first().project).createCodeBlock()
elements.forEach { codeBlock.add(it) }
return listOf(codeBlock)
}
fun findUsedTypeParameters(source: PsiTypeParameterList?, searchScope: List<PsiElement>): List<PsiTypeParameter> {
val typeParameterList = RefactoringUtil.createTypeParameterListWithUsedTypeParameters(source, *searchScope.toTypedArray())
return typeParameterList?.typeParameters.orEmpty().toList()
}
fun inputParameterOf(externalReference: ExternalReference): InputParameter {
return InputParameter(externalReference.references, requireNotNull(externalReference.variable.name), externalReference.variable.type)
}
fun PsiElement.addSiblingAfter(element: PsiElement): PsiElement {
return this.parent.addAfter(element, this)
}
fun getValidParentOf(element: PsiElement): PsiElement {
val parent = element.parent
val physicalParent = when (parent) {
is DummyHolder -> parent.context
null -> element.context
else -> parent
}
return physicalParent ?: throw IllegalArgumentException()
}
fun normalizedAnchor(anchor: PsiMember): PsiMember {
return if (anchor is PsiField) {
MultipleFieldDeclarationHelper.findLastFieldInGroup(anchor.node).psi as? PsiField ?: anchor
} else {
anchor
}
}
fun addNullabilityAnnotation(owner: PsiModifierListOwner, nullability: Nullability) {
val nullabilityManager = NullableNotNullManager.getInstance(owner.project)
val annotation = when (nullability) {
Nullability.NOT_NULL -> nullabilityManager.defaultNotNull
Nullability.NULLABLE -> nullabilityManager.defaultNullable
else -> return
}
val target: PsiAnnotationOwner? = if (owner is PsiParameter) owner.typeElement else owner.modifierList
if (target == null) return
val annotationElement = AddAnnotationPsiFix.addPhysicalAnnotationIfAbsent(annotation, PsiNameValuePair.EMPTY_ARRAY, target)
if (annotationElement != null) {
JavaCodeStyleManager.getInstance(owner.project).shortenClassReferences(annotationElement)
}
}
private fun findVariableReferences(element: PsiElement): Sequence<PsiVariable> {
val references = PsiTreeUtil.findChildrenOfAnyType(element, PsiReferenceExpression::class.java)
return references.asSequence().mapNotNull { reference -> (reference.resolve() as? PsiVariable) }
}
fun hasConflictResolve(name: String?, scopeToIgnore: List<PsiElement>): Boolean {
require(scopeToIgnore.isNotEmpty())
if (name == null) return false
val lastElement = scopeToIgnore.last()
val helper = JavaPsiFacade.getInstance(lastElement.project).resolveHelper
val resolvedRange = helper.resolveAccessibleReferencedVariable(name, lastElement.context)?.textRange ?: return false
return resolvedRange !in TextRange(scopeToIgnore.first().textRange.startOffset, scopeToIgnore.last().textRange.endOffset)
}
fun uniqueNameOf(name: String?, scopeToIgnore: List<PsiElement>, reservedNames: List<String>): String? {
require(scopeToIgnore.isNotEmpty())
if (name == null) return null
val lastElement = scopeToIgnore.last()
if (hasConflictResolve(name, scopeToIgnore) || name in reservedNames){
val styleManager = JavaCodeStyleManager.getInstance(lastElement.project) as JavaCodeStyleManagerImpl
return styleManager.suggestUniqueVariableName(name, lastElement, true)
} else {
return name
}
}
fun guessName(expression: PsiExpression): String {
val codeStyleManager = JavaCodeStyleManager.getInstance(expression.project) as JavaCodeStyleManagerImpl
return findVariableReferences(expression).mapNotNull { variable -> variable.name }.firstOrNull()
?: codeStyleManager.suggestSemanticNames(expression).firstOrNull()
?: "x"
}
fun createDeclaration(variable: PsiVariable): PsiDeclarationStatement {
val factory = PsiElementFactory.getInstance(variable.project)
val declaration = factory.createVariableDeclarationStatement(requireNotNull(variable.name), variable.type, null)
val declaredVariable = declaration.declaredElements.first() as PsiVariable
PsiUtil.setModifierProperty(declaredVariable, PsiModifier.FINAL, variable.hasModifierProperty(PsiModifier.FINAL))
variable.annotations.forEach { annotation -> declaredVariable.modifierList?.add(annotation) }
return declaration
}
tailrec fun findTopmostParenthesis(expression: PsiExpression): PsiExpression {
val parent = expression.parent as? PsiParenthesizedExpression
return if (parent != null) findTopmostParenthesis(parent) else expression
}
fun getExpressionType(expression: PsiExpression): PsiType {
val type = RefactoringUtil.getTypeByExpressionWithExpectedType(expression)
return when {
type != null -> type
expression.parent is PsiExpressionStatement -> PsiType.VOID
else -> PsiType.getJavaLangObject(expression.manager, GlobalSearchScope.allScope(expression.project))
}
}
fun areSame(elements: List<PsiElement?>): Boolean {
val first = elements.firstOrNull()
return elements.all { element -> areSame(first, element) }
}
fun areSame(first: PsiElement?, second: PsiElement?): Boolean {
return when {
first != null && second != null -> PsiEquivalenceUtil.areElementsEquivalent(first, second)
first == null && second == null -> true
else -> false
}
}
private fun boxedTypeOf(type: PsiType, context: PsiElement): PsiType {
return (type as? PsiPrimitiveType)?.getBoxedType(context) ?: type
}
fun PsiModifierListOwner?.hasExplicitModifier(modifier: String): Boolean {
return this?.modifierList?.hasExplicitModifier(modifier) == true
}
fun DataOutput.withBoxedType(): DataOutput {
return when (this) {
is VariableOutput -> copy(type = boxedTypeOf(type, variable))
is ExpressionOutput -> copy(type = boxedTypeOf(type, returnExpressions.first()))
ArtificialBooleanOutput, is EmptyOutput -> this
}
}
fun areSemanticallySame(statements: List<PsiStatement>): Boolean {
if (statements.isEmpty()) return true
if (! areSame(statements)) return false
val returnExpressions = statements.mapNotNull { statement -> (statement as? PsiReturnStatement)?.returnValue }
return returnExpressions.all { expression -> PsiUtil.isConstantExpression(expression) || expression.type == PsiType.NULL }
}
fun haveReferenceToScope(elements: List<PsiElement>, scope: List<PsiElement>): Boolean {
val scopeRange = TextRange(scope.first().textRange.startOffset, scope.last().textRange.endOffset)
return elements.asSequence()
.flatMap { PsiTreeUtil.findChildrenOfAnyType(it, false, PsiJavaCodeReferenceElement::class.java).asSequence() }
.mapNotNull { reference -> reference.resolve() }
.any{ referencedElement -> referencedElement.textRange in scopeRange }
}
fun guessMethodName(options: ExtractOptions): List<String> {
val project = options.project
val initialMethodNames: MutableSet<String> = LinkedHashSet()
val codeStyleManager = JavaCodeStyleManager.getInstance(project) as JavaCodeStyleManagerImpl
val returnType = options.dataOutput.type
val expression = options.elements.singleOrNull() as? PsiExpression
if (expression != null || returnType !is PsiPrimitiveType) {
codeStyleManager.suggestVariableName(VariableKind.FIELD, null, expression, returnType).names
.forEach { name ->
initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD)
}
}
val outVariable = (options.dataOutput as? VariableOutput)?.variable
if (outVariable != null) {
val outKind = codeStyleManager.getVariableKind(outVariable)
val propertyName = codeStyleManager.variableNameToPropertyName(outVariable.name!!, outKind)
val names = codeStyleManager.suggestVariableName(VariableKind.FIELD, propertyName, null, outVariable.type).names
names.forEach { name ->
initialMethodNames += codeStyleManager.variableNameToPropertyName(name, VariableKind.FIELD)
}
}
val normalizedType = (returnType as? PsiEllipsisType)?.toArrayType() ?: returnType
val field = JavaPsiFacade.getElementFactory(project).createField("fieldNameToReplace", normalizedType)
fun suggestGetterName(name: String): String {
field.name = name
return GenerateMembersUtil.suggestGetterName(field)
}
return initialMethodNames.filter { PsiNameHelper.getInstance(project).isIdentifier(it) }
.map { propertyName -> suggestGetterName(propertyName) }
}
} | apache-2.0 | 8de4cf92862bfdc77524d48e41b0dab6 | 45.817391 | 140 | 0.76753 | 4.991655 | false | false | false | false |
siosio/intellij-community | platform/workspaceModel/jps/src/com/intellij/workspaceModel/ide/impl/jps/serialization/FileInDirectorySourceNames.kt | 3 | 3087 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.impl.jps.serialization
import com.intellij.openapi.util.io.FileUtil
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ArtifactEntity
import com.intellij.workspaceModel.storage.bridgeEntities.FacetEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleEntity
/**
* This class is used to reuse [JpsFileEntitySource.FileInDirectory] instances when project is synchronized with JPS files after loading
* storage from binary cache.
*/
class FileInDirectorySourceNames private constructor(entitiesBySource: Map<EntitySource, Map<Class<out WorkspaceEntity>, List<WorkspaceEntity>>>) {
private val mainEntityToSource: Map<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>
init {
val sourcesMap = HashMap<Pair<Class<out WorkspaceEntity>, String>, JpsFileEntitySource.FileInDirectory>()
for ((source, entities) in entitiesBySource) {
val (type, entityName) = when {
ModuleEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(ModuleEntity::class.java).first() as ModuleEntity).name
FacetEntity::class.java in entities -> ModuleEntity::class.java to (entities.getValue(FacetEntity::class.java).first() as FacetEntity).module.name
LibraryEntity::class.java in entities -> LibraryEntity::class.java to (entities.getValue(LibraryEntity::class.java).first() as LibraryEntity).name
ArtifactEntity::class.java in entities -> ArtifactEntity::class.java to (entities.getValue(ArtifactEntity::class.java).first() as ArtifactEntity).name
else -> null to null
}
if (type != null && entityName != null) {
val fileName = when {
type == ModuleEntity::class.java && (source as? JpsImportedEntitySource)?.storedExternally == true -> "$entityName.xml"
type == ModuleEntity::class.java -> "$entityName.iml"
else -> FileUtil.sanitizeFileName(entityName) + ".xml"
}
sourcesMap[type to fileName] = getInternalFileSource(source) as JpsFileEntitySource.FileInDirectory
}
}
mainEntityToSource = sourcesMap
}
fun findSource(entityClass: Class<out WorkspaceEntity>, fileName: String): JpsFileEntitySource.FileInDirectory? =
mainEntityToSource[entityClass to fileName]
companion object {
fun from(storage: WorkspaceEntityStorage) = FileInDirectorySourceNames(
storage.entitiesBySource { getInternalFileSource(it) is JpsFileEntitySource.FileInDirectory }
)
fun empty() = FileInDirectorySourceNames(emptyMap())
}
} | apache-2.0 | fb4be38365e798945c70acb4fa81b81e | 56.185185 | 158 | 0.770975 | 5.145 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RenameClassToContainingFileNameIntention.kt | 4 | 1904 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.io.FileUtil
import com.intellij.refactoring.rename.RenameProcessor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.renderer.render
class RenameClassToContainingFileNameIntention : SelfTargetingRangeIntention<KtClassOrObject>(
KtClassOrObject::class.java, KotlinBundle.lazyMessage("rename.class.to.containing.file.name")
) {
override fun startInWriteAction() = false
override fun applicabilityRange(element: KtClassOrObject): TextRange? {
if (!element.isTopLevel()) return null
val fileName = FileUtil.getNameWithoutExtension(element.containingKtFile.name)
if (fileName == element.name
|| fileName.isEmpty()
|| fileName[0].isLowerCase()
|| !Name.isValidIdentifier(fileName)
|| Name.identifier(fileName).render() != fileName
|| element.containingKtFile.declarations.any { it is KtClassOrObject && it.name == fileName }
) return null
setTextGetter(KotlinBundle.lazyMessage("rename.class.to.0", fileName))
return element.nameIdentifier?.textRange
}
override fun applyTo(element: KtClassOrObject, editor: Editor?) {
val file = element.containingKtFile
val fileName = FileUtil.getNameWithoutExtension(element.containingKtFile.name)
RenameProcessor(file.project, element, fileName, false, false).run()
}
} | apache-2.0 | d347f29da4ab8a2e88e2b03d8885a718 | 47.846154 | 158 | 0.751576 | 4.808081 | false | false | false | false |
raniejade/spek-idea-plugin | plugin-studio3.0/src/main/kotlin/org/jetbrains/spek/studio/SpekAndroidParameterPatcher.kt | 1 | 6319 | package org.jetbrains.spek.studio
import com.android.builder.model.JavaArtifact
import com.android.tools.idea.gradle.project.GradleProjectInfo
import com.android.tools.idea.gradle.project.facet.java.JavaFacet
import com.android.tools.idea.gradle.project.model.AndroidModuleModel
import com.android.tools.idea.io.FilePaths
import com.android.tools.idea.testartifacts.scopes.FileRootSearchScope
import com.android.tools.idea.testartifacts.scopes.TestArtifactSearchScopes
import com.intellij.execution.configurations.JavaParameters
import com.intellij.openapi.compiler.CompilerManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.util.io.FileUtil
import com.intellij.util.PathsList
import org.jetbrains.android.sdk.AndroidPlatform
import org.jetbrains.spek.idea.SpekJvmParameterPatcher
import java.io.File
class SpekAndroidParameterPatcher: SpekJvmParameterPatcher {
override fun patch(module: Module?, parameters: JavaParameters) {
if (module != null && GradleProjectInfo.getInstance(module.project).isBuildWithGradle) {
val androidModel = AndroidModuleModel.get(module)
val classPath = parameters.classPath
if (androidModel == null) {
addFoldersToClasspath(module, null, classPath)
} else {
val testArtifact = androidModel.selectedVariant.unitTestArtifact
if (testArtifact != null) {
val testScopes = TestArtifactSearchScopes.get(module)
if (testScopes != null) {
val excludeScope = testScopes.unitTestExcludeScope
val iterator = classPath.pathList.iterator()
var current: String?
while (iterator.hasNext()) {
current = iterator.next()
if (excludeScope.accept(File(current))) {
classPath.remove(current)
}
}
val platform = AndroidPlatform.getInstance(module)
if (platform != null) {
try {
replaceAndroidJarWithMockableJar(classPath, platform, testArtifact)
addFoldersToClasspath(module, testArtifact, classPath)
} catch (e: Throwable) {
throw RuntimeException("Failed to patch classpath.", e)
}
}
}
}
}
}
}
private fun addFoldersToClasspath(module: Module, testArtifact: JavaArtifact?, classPath: PathsList) {
val compileManager = CompilerManager.getInstance(module.project)
val scope = compileManager.createModulesCompileScope(arrayOf(module), true, true)
if (testArtifact != null) {
classPath.add(testArtifact.javaResourcesFolder)
testArtifact.additionalClassesFolders.forEach {
classPath.add(it)
}
}
var excludeScope: FileRootSearchScope? = null
val testScopes = TestArtifactSearchScopes.get(module)
if (testScopes != null) {
excludeScope = testScopes.unitTestExcludeScope
}
scope.affectedModules.forEach { affectedModule ->
val affectedAndroidModel = AndroidModuleModel.get(affectedModule)
if (affectedAndroidModel != null) {
val mainArtifact = affectedAndroidModel.mainArtifact
addToClassPath(mainArtifact.javaResourcesFolder, classPath, excludeScope)
mainArtifact.additionalClassesFolders.forEach {
addToClassPath(it, classPath, excludeScope)
}
}
val javaFacet = JavaFacet.getInstance(affectedModule)
if (javaFacet != null) {
val javaModel = javaFacet.javaModuleModel
if (javaModel != null) {
val output = javaModel.compilerOutput
val javaTestResources = output?.testResourcesDir
if (javaTestResources != null) {
addToClassPath(javaTestResources, classPath, excludeScope)
}
val javaMainResources = output?.mainResourcesDir
if (javaMainResources != null) {
addToClassPath(javaMainResources, classPath, excludeScope)
}
if (javaModel.buildFolderPath != null) {
val kotlinClasses = javaModel.buildFolderPath!!.toPath().resolve("classes/kotlin").toFile()
if (kotlinClasses.exists()) {
addToClassPath(File(kotlinClasses, "main"), classPath, excludeScope)
addToClassPath(File(kotlinClasses, "test"), classPath, excludeScope)
}
}
}
}
}
}
private fun replaceAndroidJarWithMockableJar(classPath: PathsList, platform: AndroidPlatform,
artifact: JavaArtifact) {
val androidJarPath = platform.target.getPath(1)
classPath.pathList
.filter { FileUtil.pathsEqual(androidJarPath, it) }
.forEach { classPath.remove(it) }
val mockableJars = ArrayList<String>()
classPath.pathList
.filter { FilePaths.toSystemDependentPath(it)!!.name.startsWith("mockable-") }
.forEach { mockableJars.add(it) }
mockableJars.forEach(classPath::remove)
val mockableJar = artifact.mockablePlatformJar
if (mockableJar != null) {
classPath.addTail(mockableJar.path)
} else {
for (jar in mockableJars) {
if (jar.endsWith("-${platform.apiLevel}.jar")) {
classPath.addTail(jar)
break
}
}
}
}
private fun addToClassPath(folder: File, classPath: PathsList, excludeScope: FileRootSearchScope?) {
if (excludeScope == null || !excludeScope.accept(folder)) {
classPath.add(folder)
}
}
}
| mit | 3f26edfe025ee37572149b6ff244cc70 | 40.847682 | 115 | 0.583637 | 5.274624 | false | true | false | false |
smmribeiro/intellij-community | plugins/devkit/devkit-core/src/internal/AnalyzeUnloadablePluginsAction.kt | 3 | 14496 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.devkit.internal
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.util.NlsSafe
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScopesCore
import com.intellij.psi.xml.XmlFile
import com.intellij.testFramework.LightVirtualFile
import com.intellij.util.text.DateFormatUtil
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.dom.Dependency
import org.jetbrains.idea.devkit.dom.IdeaPlugin
import org.jetbrains.idea.devkit.util.DescriptorUtil
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
@Suppress("HardCodedStringLiteral")
class AnalyzeUnloadablePluginsAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val view = e.getData(LangDataKeys.IDE_VIEW)
val dir = view?.orChooseDirectory
val result = mutableListOf<PluginUnloadabilityStatus>()
val show = ProgressManager.getInstance().runProcessWithProgressSynchronously(
{
runReadAction {
val pi = ProgressManager.getInstance().progressIndicator
pi.isIndeterminate = false
val searchScope = when (dir) {
null -> GlobalSearchScopesCore.projectProductionScope(project)
else -> GlobalSearchScopesCore.directoryScope(dir, true)
}
val pluginXmlFiles = FilenameIndex.getFilesByName(project, PluginManagerCore.PLUGIN_XML, searchScope)
.ifEmpty { FilenameIndex.getFilesByName(project, PluginManagerCore.PLUGIN_XML, GlobalSearchScopesCore.projectProductionScope(project)) }
.filterIsInstance<XmlFile>()
for ((processed, pluginXmlFile) in pluginXmlFiles.withIndex()) {
pi.checkCanceled()
pi.fraction = (processed.toDouble() / pluginXmlFiles.size)
if (!ProjectRootManager.getInstance(project).fileIndex.isUnderSourceRootOfType(pluginXmlFile.virtualFile,
JavaModuleSourceRootTypes.PRODUCTION)) {
continue
}
val ideaPlugin = DescriptorUtil.getIdeaPlugin(pluginXmlFile) ?: continue
if (ideaPlugin.requireRestart.value == true) continue
val status = analyzeUnloadable(ideaPlugin, pluginXmlFiles)
result.add(status)
pi.text = status.pluginId
}
}
}, DevKitBundle.message("action.AnalyzeUnloadablePlugins.progress.title", dir?.name ?: "Project"), true, e.project)
if (show) showReport(project, result)
}
private fun showReport(project: Project, result: List<PluginUnloadabilityStatus>) {
@NlsSafe val report = buildString {
if (result.any { it.analysisErrors.isNotEmpty() }) {
appendLine("Analysis errors:")
for (status in result.filter { it.analysisErrors.isNotEmpty() }) {
appendLine(status.pluginId)
for (analysisError in status.analysisErrors) {
appendLine(analysisError)
}
appendLine()
}
}
val unloadablePlugins = result.filter { it.getStatus() == UnloadabilityStatus.UNLOADABLE }
appendLine("Can unload ${unloadablePlugins.size} plugins out of ${result.size}")
for (status in unloadablePlugins) {
appendLine(status.pluginId)
}
appendLine()
val pluginsUsingComponents = result.filter { it.getStatus() == UnloadabilityStatus.USES_COMPONENTS }.sortedByDescending { it.components.size }
appendLine("Plugins using components (${pluginsUsingComponents.size}):")
for (status in pluginsUsingComponents) {
appendLine("${status.pluginId} (${status.components.size})")
for (componentName in status.components) {
appendLine(" $componentName")
}
}
appendLine()
val pluginsUsingServiceOverrides = result.filter { it.getStatus() == UnloadabilityStatus.USES_SERVICE_OVERRIDES }.sortedByDescending { it.serviceOverrides.size }
appendLine("Plugins using service overrides (${pluginsUsingServiceOverrides.size}):")
for (status in pluginsUsingServiceOverrides) {
appendLine("${status.pluginId} (${status.serviceOverrides.joinToString()})")
}
appendLine()
val pluginsWithOptionalDependencies = result.filter { it.getStatus() == UnloadabilityStatus.NON_DYNAMIC_IN_DEPENDENCIES }
appendLine("Plugins not unloadable because of non-dynamic EPs in optional dependencies (${pluginsWithOptionalDependencies.size}):")
for (status in pluginsWithOptionalDependencies) {
appendLine(status.pluginId)
for ((pluginId, eps) in status.nonDynamicEPsInDependencies) {
appendLine(" ${pluginId} - ${eps.joinToString()}")
}
}
appendLine()
val pluginsWithDependenciesWithoutSeparateClassloaders = result.filter { it.getStatus() == UnloadabilityStatus.DEPENDENCIES_WITHOUT_SEPARATE_CLASSLOADERS }
appendLine("Plugins not unloadable because of optional dependencies without separate classloaders (${pluginsWithDependenciesWithoutSeparateClassloaders.size}):")
for (status in pluginsWithDependenciesWithoutSeparateClassloaders) {
appendLine(status.pluginId)
for (pluginId in status.dependenciesWithoutSeparateClassloaders) {
appendLine(" $pluginId")
}
}
appendLine()
val nonDynamicPlugins = result.filter { it.getStatus() == UnloadabilityStatus.USES_NON_DYNAMIC_EPS }
if (nonDynamicPlugins.isNotEmpty()) {
appendLine("Plugins with EPs explicitly marked as dynamic=false:")
for (nonDynamicPlugin in nonDynamicPlugins) {
appendLine("${nonDynamicPlugin.pluginId} (${nonDynamicPlugin.nonDynamicEPs.size})")
for (ep in nonDynamicPlugin.nonDynamicEPs) {
appendLine(" $ep")
}
}
appendLine()
}
val closePlugins = result.filter { it.unspecifiedDynamicEPs.any { !it.startsWith("cidr") && !it.startsWith("appcode") } }
if (closePlugins.isNotEmpty()) {
appendLine("Plugins with non-dynamic EPs (${closePlugins.size}):")
for (status in closePlugins.sortedBy { it.unspecifiedDynamicEPs.size }) {
appendLine("${status.pluginId} (${status.unspecifiedDynamicEPs.size})")
for (ep in status.unspecifiedDynamicEPs) {
appendLine(" $ep")
}
}
appendLine()
}
val epUsagesMap = mutableMapOf<String, Int>()
for (pluginUnloadabilityStatus in result) {
for (ep in pluginUnloadabilityStatus.unspecifiedDynamicEPs) {
epUsagesMap[ep] = epUsagesMap.getOrDefault(ep, 0) + 1
}
}
val epUsagesList = epUsagesMap.toList().filter { !it.first.startsWith("cidr") }.sortedByDescending { it.second }
appendLine("EP usage statistics (${epUsagesList.size} non-dynamic EPs remaining):")
for (pair in epUsagesList) {
append("${pair.second}: ${pair.first}")
appendLine()
}
}
val fileName = String.format("AnalyzeUnloadablePlugins-Report-%s.txt", DateFormatUtil.formatDateTime(System.currentTimeMillis()))
val file = LightVirtualFile(fileName, report)
val descriptor = OpenFileDescriptor(project, file)
FileEditorManager.getInstance(project).openEditor(descriptor, true)
}
private fun analyzeUnloadable(ideaPlugin: IdeaPlugin, allPlugins: List<XmlFile>): PluginUnloadabilityStatus {
val unspecifiedDynamicEPs = mutableSetOf<String>()
val nonDynamicEPs = mutableSetOf<String>()
val analysisErrors = mutableListOf<String>()
val serviceOverrides = mutableListOf<String>()
val components = mutableListOf<String>()
analyzePluginFile(ideaPlugin, analysisErrors, components, nonDynamicEPs, unspecifiedDynamicEPs, serviceOverrides, true)
fun analyzeDependencies(ideaPlugin: IdeaPlugin) {
for (dependency in ideaPlugin.depends) {
val configFileName = dependency.configFile.stringValue ?: continue
val depIdeaPlugin = resolvePluginDependency(dependency)
if (depIdeaPlugin == null) {
analysisErrors.add("Failed to resolve dependency descriptor file $configFileName")
continue
}
analyzePluginFile(depIdeaPlugin, analysisErrors, components, nonDynamicEPs, unspecifiedDynamicEPs, serviceOverrides, true)
analyzeDependencies(depIdeaPlugin)
}
}
analyzeDependencies(ideaPlugin)
val componentsInOptionalDependencies = mutableListOf<String>()
val nonDynamicEPsInOptionalDependencies = mutableMapOf<String, MutableSet<String>>()
val serviceOverridesInDependencies = mutableListOf<String>()
val dependenciesWithoutSeparateClassloaders = mutableListOf<String>()
for (descriptor in allPlugins.mapNotNull { DescriptorUtil.getIdeaPlugin(it) }) {
for (dependency in descriptor.depends) {
if (dependency.optional.value == true && dependency.value == ideaPlugin) {
val depIdeaPlugin = resolvePluginDependency(dependency)
if (depIdeaPlugin == null) {
if (dependency.configFile.stringValue != null) {
analysisErrors.add("Failed to resolve dependency descriptor file ${dependency.configFile.stringValue}")
}
continue
}
descriptor.pluginId?.let { pluginId ->
if (depIdeaPlugin.`package`.rawText == null) {
dependenciesWithoutSeparateClassloaders.add(pluginId)
}
}
val nonDynamicEPsInDependency = mutableSetOf<String>()
analyzePluginFile(depIdeaPlugin, analysisErrors, componentsInOptionalDependencies, nonDynamicEPsInDependency, nonDynamicEPsInDependency, serviceOverridesInDependencies, false)
if (nonDynamicEPsInDependency.isNotEmpty()) {
nonDynamicEPsInOptionalDependencies[descriptor.pluginId ?: "<unknown>"] = nonDynamicEPsInDependency
}
}
}
}
return PluginUnloadabilityStatus(
ideaPlugin.pluginId ?: "?",
unspecifiedDynamicEPs, nonDynamicEPs, nonDynamicEPsInOptionalDependencies, dependenciesWithoutSeparateClassloaders,
components, serviceOverrides, analysisErrors
)
}
private fun resolvePluginDependency(dependency: Dependency): IdeaPlugin? {
var xmlFile = dependency.resolvedConfigFile
val configFileName = dependency.configFile.stringValue
if (xmlFile == null && configFileName != null) {
val project = dependency.manager.project
val matchingFiles = FilenameIndex.getFilesByName(project, configFileName, GlobalSearchScopesCore.projectProductionScope(project))
xmlFile = matchingFiles.singleOrNull() as? XmlFile?
}
return xmlFile?.let { DescriptorUtil.getIdeaPlugin(it) }
}
private fun analyzePluginFile(ideaPlugin: IdeaPlugin,
analysisErrors: MutableList<String>,
components: MutableList<String>,
nonDynamicEPs: MutableSet<String>,
unspecifiedDynamicEPs: MutableSet<String>,
serviceOverrides: MutableList<String>,
allowOwnEPs: Boolean) {
for (extension in ideaPlugin.extensions.flatMap { it.collectExtensions() }) {
val ep = extension.extensionPoint
if (ep == null) {
analysisErrors.add("Cannot resolve EP ${extension.xmlElementName}")
continue
}
if (allowOwnEPs && (ep.module == ideaPlugin.module || ep.module == extension.module)) continue // a plugin can have extensions for its own non-dynamic EPs
when (ep.dynamic.value) {
false -> nonDynamicEPs.add(ep.effectiveQualifiedName)
null -> unspecifiedDynamicEPs.add(ep.effectiveQualifiedName)
}
if ((ep.effectiveQualifiedName == "com.intellij.applicationService" ||
ep.effectiveQualifiedName == "com.intellij.projectService" ||
ep.effectiveQualifiedName == "com.intellij.moduleService") &&
extension.xmlTag.getAttributeValue("overrides") == "true") {
serviceOverrides.add(extension.xmlTag.getAttributeValue("serviceInterface") ?: "<unknown>")
}
}
ideaPlugin.applicationComponents.flatMap { it.components }.mapTo(components) { it.implementationClass.rawText ?: "?" }
ideaPlugin.projectComponents.flatMap { it.components }.mapTo(components) { it.implementationClass.rawText ?: "?" }
ideaPlugin.moduleComponents.flatMap { it.components }.mapTo(components) { it.implementationClass.rawText ?: "?" }
}
}
enum class UnloadabilityStatus {
UNLOADABLE, USES_COMPONENTS, USES_SERVICE_OVERRIDES, USES_NON_DYNAMIC_EPS, USES_UNSPECIFIED_DYNAMIC_EPS, NON_DYNAMIC_IN_DEPENDENCIES,
DEPENDENCIES_WITHOUT_SEPARATE_CLASSLOADERS
}
private data class PluginUnloadabilityStatus(
@NlsSafe val pluginId: String,
val unspecifiedDynamicEPs: Set<String>,
val nonDynamicEPs: Set<String>,
val nonDynamicEPsInDependencies: Map<String, Set<String>>,
val dependenciesWithoutSeparateClassloaders: List<String>,
val components: List<String>,
val serviceOverrides: List<String>,
val analysisErrors: List<String>
) {
fun getStatus(): UnloadabilityStatus {
return when {
components.isNotEmpty() -> UnloadabilityStatus.USES_COMPONENTS
serviceOverrides.isNotEmpty() -> UnloadabilityStatus.USES_SERVICE_OVERRIDES
nonDynamicEPs.isNotEmpty() -> UnloadabilityStatus.USES_NON_DYNAMIC_EPS
unspecifiedDynamicEPs.isNotEmpty() -> UnloadabilityStatus.USES_UNSPECIFIED_DYNAMIC_EPS
dependenciesWithoutSeparateClassloaders.isNotEmpty() -> UnloadabilityStatus.DEPENDENCIES_WITHOUT_SEPARATE_CLASSLOADERS
nonDynamicEPsInDependencies.isNotEmpty() -> UnloadabilityStatus.NON_DYNAMIC_IN_DEPENDENCIES
else -> UnloadabilityStatus.UNLOADABLE
}
}
}
| apache-2.0 | 5f7237234af30bce4bebd8dfdcefc1e3 | 47.32 | 185 | 0.704125 | 4.882452 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/components/CheckboxComponent.kt | 2 | 1566 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.components.JBCheckBox
import com.intellij.util.ui.UIUtil
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.SettingValidator
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.componentWithCommentAtBottom
import javax.swing.JComponent
class CheckboxComponent(
context: Context,
@NlsContexts.Checkbox labelText: String? = null,
description: String? = null,
initialValue: Boolean? = null,
validator: SettingValidator<Boolean>? = null,
onValueUpdate: (Boolean, isByUser: Boolean) -> Unit = { _, _ -> }
) : UIComponent<Boolean>(
context,
labelText = null,
validator = validator,
onValueUpdate = onValueUpdate
) {
private val checkbox = JBCheckBox(labelText, initialValue ?: false).apply {
font = UIUtil.getButtonFont()
addItemListener {
fireValueUpdated([email protected])
}
}
override val alignTarget: JComponent? get() = checkbox
override val uiComponent = componentWithCommentAtBottom(checkbox, description, gap = 2)
override fun updateUiValue(newValue: Boolean) = safeUpdateUi {
checkbox.isSelected = newValue
}
override fun getUiValue(): Boolean = checkbox.isSelected
} | apache-2.0 | 0d2038a5235d82864f4eeade2c08e50c | 37.219512 | 158 | 0.742018 | 4.411268 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/suite/AbstractFixtureMeasurementScope.kt | 1 | 1426 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.perf.suite
import org.jetbrains.kotlin.idea.testFramework.Fixture
import org.jetbrains.kotlin.idea.testFramework.Stats
import org.jetbrains.kotlin.idea.testFramework.commitAllDocuments
abstract class AbstractFixtureMeasurementScope<T>(
protected val fixture: Fixture,
typeTestPrefix: String = "",
name: String,
stats: Stats,
config: StatsScopeConfig,
after: (() -> Unit)? = null,
var revertChangesAtTheEnd: Boolean = true,
) : MeasurementScope<T>(listOf(typeTestPrefix, name).filter { it.isNotEmpty() }.joinToString(" "), stats, config, after = after) {
protected fun <V> doFixturePerformanceTest(setUp: () -> Unit = {}, test:() -> V?, tearDown: () -> Unit = {}) {
doPerformanceTest(
setUp = {
fixture.storeText()
setUp()
before.invoke()
},
test = test,
tearDown = {
try {
tearDown()
} finally {
if (revertChangesAtTheEnd) {
fixture.restoreText()
commitAllDocuments()
}
after?.invoke()
}
}
)
}
} | apache-2.0 | 1af9585bb9d1c539cf747c498594af3c | 36.552632 | 158 | 0.567321 | 4.866894 | false | true | false | false |
smmribeiro/intellij-community | build/tasks/src/org/jetbrains/intellij/build/io/zipReader.kt | 9 | 9946 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.intellij.build.io
import com.intellij.util.lang.DirectByteBufferPool
import com.intellij.util.lang.ImmutableZipFile
import java.io.EOFException
import java.io.IOException
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.FileChannel
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.*
import java.util.zip.DataFormatException
import java.util.zip.Inflater
import java.util.zip.ZipException
import kotlin.experimental.and
typealias EntryProcessor = (String, ZipEntry) -> Unit
// only files are processed
fun readZipFile(file: Path, entryProcessor: EntryProcessor) {
// FileChannel is strongly required because only FileChannel provides `read(ByteBuffer dst, long position)` method -
// ability to read data without setting channel position, as setting channel position will require synchronization
mapFileAndUse(file) { buffer, fileSize ->
readZipEntries(buffer, fileSize, entryProcessor)
}
}
internal fun mapFileAndUse(file: Path, consumer: (ByteBuffer, fileSize: Int) -> Unit) {
// FileChannel is strongly required because only FileChannel provides `read(ByteBuffer dst, long position)` method -
// ability to read data without setting channel position, as setting channel position will require synchronization
var fileSize: Int
var mappedBuffer: ByteBuffer
FileChannel.open(file, EnumSet.of(StandardOpenOption.READ)).use { fileChannel ->
fileSize = fileChannel.size().toInt()
mappedBuffer = try {
fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize.toLong())
}
catch (e: UnsupportedOperationException) {
// in memory fs
val buffer = ByteBuffer.allocate(fileSize)
while (buffer.hasRemaining()) {
fileChannel.read(buffer)
}
buffer.rewind()
buffer
}
mappedBuffer.order(ByteOrder.LITTLE_ENDIAN)
}
try {
consumer(mappedBuffer, fileSize)
}
catch (e: IOException) {
throw IOException(file.toString(), e)
}
finally {
if (mappedBuffer.isDirect) {
unmapBuffer(mappedBuffer)
}
}
}
private fun readCentralDirectory(buffer: ByteBuffer,
centralDirPosition: Int,
centralDirSize: Int,
entryProcessor: EntryProcessor) {
var offset = centralDirPosition
// assume that file name is not greater than ~2 KiB
// JDK impl cheats — it uses jdk.internal.misc.JavaLangAccess.newStringUTF8NoRepl (see ZipCoder.UTF8)
// StandardCharsets.UTF_8.decode doesn't benefit from using direct buffer and introduces char buffer allocation for each decode
val tempNameBytes = ByteArray(4096)
var prevEntry: ZipEntry? = null
var prevEntryExpectedDataOffset = -1
val endOffset = centralDirPosition + centralDirSize
while (offset < endOffset) {
if (buffer.getInt(offset) != 33639248) {
throw EOFException("Expected central directory size " + centralDirSize +
" but only at " + offset + " no valid central directory file header signature")
}
val compressedSize = buffer.getInt(offset + 20)
val uncompressedSize = buffer.getInt(offset + 24)
val headerOffset = buffer.getInt(offset + 42)
val method: Byte = (buffer.getShort(offset + 10) and 0xffff.toShort()).toByte()
val nameLengthInBytes: Int = (buffer.getShort(offset + 28) and 0xffff.toShort()).toInt()
val extraFieldLength: Int = (buffer.getShort(offset + 30) and 0xffff.toShort()).toInt()
val commentLength: Int = (buffer.getShort(offset + 32) and 0xffff.toShort()).toInt()
if (prevEntry != null && prevEntryExpectedDataOffset == headerOffset - prevEntry.compressedSize) {
prevEntry.dataOffset = prevEntryExpectedDataOffset
}
offset += 46
buffer.position(offset)
val isDir = buffer.get(offset + nameLengthInBytes - 1) == '/'.code.toByte()
offset += nameLengthInBytes + extraFieldLength + commentLength
if (!isDir) {
buffer.get(tempNameBytes, 0, nameLengthInBytes)
val entry = ZipEntry(compressedSize = compressedSize,
uncompressedSize = uncompressedSize,
headerOffset = headerOffset,
nameLengthInBytes = nameLengthInBytes,
method = method,
buffer = buffer)
prevEntry = entry
prevEntryExpectedDataOffset = headerOffset + 30 + nameLengthInBytes + extraFieldLength
val name = String(tempNameBytes, 0, nameLengthInBytes, Charsets.UTF_8)
if (name != INDEX_FILENAME) {
entryProcessor(name, entry)
}
}
}
}
class ZipEntry(@JvmField val compressedSize: Int,
private val uncompressedSize: Int,
headerOffset: Int,
nameLengthInBytes: Int,
private val method: Byte,
private val buffer: ByteBuffer) {
companion object {
const val STORED: Byte = 0
const val DEFLATED: Byte = 8
}
// headerOffset and nameLengthInBytes
private val offsets = headerOffset.toLong() shl 32 or (nameLengthInBytes.toLong() and 0xffffffffL)
@JvmField
var dataOffset = -1
val isCompressed: Boolean
get() = method != STORED
fun getData(): ByteArray {
if (uncompressedSize < 0) {
throw IOException("no data")
}
if (buffer.capacity() < dataOffset + compressedSize) {
throw EOFException()
}
when (method) {
STORED -> {
val inputBuffer = computeDataOffsetIfNeededAndReadInputBuffer(buffer)
val result = ByteArray(uncompressedSize)
inputBuffer.get(result)
return result
}
DEFLATED -> {
run {
val inputBuffer = computeDataOffsetIfNeededAndReadInputBuffer(buffer)
val inflater = Inflater(true)
inflater.setInput(inputBuffer)
var count = uncompressedSize
val result = ByteArray(count)
var offset = 0
try {
while (count > 0) {
val n = inflater.inflate(result, offset, count)
check(n != 0) { "Inflater wants input, but input was already set" }
offset += n
count -= n
}
return result
}
catch (e: DataFormatException) {
val s = e.message
throw ZipException(s ?: "Invalid ZLIB data format")
}
finally {
inflater.end()
}
}
}
else -> throw ZipException("Found unsupported compression method $method")
}
}
fun getByteBuffer(): ByteBuffer {
if (uncompressedSize < 0) {
throw IOException("no data")
}
if (buffer.capacity() < dataOffset + compressedSize) {
throw EOFException()
}
when (method) {
STORED -> {
return computeDataOffsetIfNeededAndReadInputBuffer(buffer)
}
DEFLATED -> {
val inputBuffer = computeDataOffsetIfNeededAndReadInputBuffer(buffer)
val inflater = Inflater(true)
inflater.setInput(inputBuffer)
try {
val result = DirectByteBufferPool.DEFAULT_POOL.allocate(uncompressedSize)
while (result.hasRemaining()) {
check(inflater.inflate(result) != 0) { "Inflater wants input, but input was already set" }
}
result.rewind()
return result
}
catch (e: DataFormatException) {
val s = e.message
throw ZipException(s ?: "Invalid ZLIB data format")
}
finally {
inflater.end()
}
}
else -> throw ZipException("Found unsupported compression method $method")
}
}
private fun computeDataOffsetIfNeededAndReadInputBuffer(mappedBuffer: ByteBuffer): ByteBuffer {
var dataOffset = dataOffset
if (dataOffset == -1) {
dataOffset = computeDataOffset(mappedBuffer)
}
val inputBuffer = mappedBuffer.asReadOnlyBuffer()
inputBuffer.position(dataOffset)
inputBuffer.limit(dataOffset + compressedSize)
return inputBuffer
}
private fun computeDataOffset(mappedBuffer: ByteBuffer): Int {
val headerOffset = (offsets shr 32).toInt()
val start = headerOffset + 28
// read actual extra field length
val extraFieldLength = (mappedBuffer.getShort(start) and 0xffff.toShort()).toInt()
if (extraFieldLength > 128) {
// assert just to be sure that we don't read a lot of data in case of some error in zip file or our impl
throw UnsupportedOperationException("extraFieldLength expected to be less than 128 bytes but $extraFieldLength")
}
val nameLengthInBytes = offsets.toInt()
val result = start + 2 + nameLengthInBytes + extraFieldLength
dataOffset = result
return result
}
}
internal fun readZipEntries(buffer: ByteBuffer, fileSize: Int, entryProcessor: EntryProcessor) {
var offset = fileSize - ImmutableZipFile.MIN_EOCD_SIZE
var finished = false
// first, EOCD
while (offset >= 0) {
if (buffer.getInt(offset) == 0x6054B50) {
finished = true
break
}
offset--
}
if (!finished) {
throw ZipException("Archive is not a ZIP archive")
}
var isZip64 = true
if (buffer.getInt(offset - 20) == 0x07064b50) {
offset = buffer.getLong(offset - (20 - 8)).toInt()
assert(buffer.getInt(offset) == 0x06064b50)
}
else {
isZip64 = false
}
val centralDirSize: Int
val centralDirPosition: Int
if (isZip64) {
centralDirSize = buffer.getLong(offset + 40).toInt()
centralDirPosition = buffer.getLong(offset + 48).toInt()
}
else {
centralDirSize = buffer.getInt(offset + 12)
centralDirPosition = buffer.getInt(offset + 16)
}
readCentralDirectory(buffer, centralDirPosition, centralDirSize, entryProcessor)
buffer.clear()
}
| apache-2.0 | 5fabc9d216f36400ccecd55088cf5398 | 34.014085 | 158 | 0.661404 | 4.469213 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/basicsettings/usecases/GetAvailableBrowserPackageNamesUseCase.kt | 1 | 1385 | package ch.rmy.android.http_shortcuts.activities.editor.basicsettings.usecases
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.net.toUri
import ch.rmy.android.framework.extensions.runIf
import ch.rmy.android.http_shortcuts.activities.editor.basicsettings.models.InstalledBrowser
import javax.inject.Inject
class GetAvailableBrowserPackageNamesUseCase
@Inject
constructor(
private val context: Context,
) {
operator fun invoke(currentValue: String): List<InstalledBrowser> =
context.packageManager.queryIntentActivities(
Intent(Intent.ACTION_VIEW, "https://http-shortcuts.rmy.ch".toUri()),
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PackageManager.MATCH_ALL else 0,
)
.map {
InstalledBrowser(
packageName = it.activityInfo.packageName,
appName = it.activityInfo.applicationInfo.loadLabel(context.packageManager).toString(),
)
}
.let { browsers ->
browsers.runIf(currentValue.isNotEmpty() && browsers.none { it.packageName == currentValue }) {
plus(InstalledBrowser(packageName = currentValue))
}
}
.sortedBy { it.appName ?: it.packageName }
}
| mit | 0898c0b1299f24f847e81832507d94db | 38.571429 | 111 | 0.672924 | 4.726962 | false | false | false | false |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Base/BaseDialogFragment.kt | 1 | 1420 | package stan.androiddemo.project.petal.Base
import android.content.Context
import android.support.v7.app.AppCompatDialogFragment
import rx.Subscription
import rx.subscriptions.CompositeSubscription
abstract class BaseDialogFragment : AppCompatDialogFragment() {
protected val TAG = getTAGInfo()
abstract fun getTAGInfo():String
var mAuthorization:String = ""
override fun toString(): String {
return javaClass.simpleName + " @" + Integer.toHexString(hashCode());
}
private var mCompositeSubscription: CompositeSubscription? = null
fun getCompositeSubscription(): CompositeSubscription {
if (this.mCompositeSubscription == null) {
this.mCompositeSubscription = CompositeSubscription()
}
return this.mCompositeSubscription!!
}
fun addSubscription(s: Subscription?) {
if (s == null) {
return
}
if (this.mCompositeSubscription == null) {
this.mCompositeSubscription = CompositeSubscription()
}
this.mCompositeSubscription!!.add(s)
}
fun throwRuntimeException(context: Context) {
throw RuntimeException(context.toString() + " must implement OnDialogInteractionListener")
}
override fun onDestroy() {
super.onDestroy()
if (this.mCompositeSubscription != null){
this.mCompositeSubscription = null
}
}
}
| mit | 5017d4499daad36664fbefa71a1ff441 | 25.792453 | 98 | 0.675352 | 5.546875 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/data/DevAuthenticationManager.kt | 1 | 1057 | package com.marverenic.reader.data
import com.marverenic.reader.BuildConfig
import io.reactivex.Single
class DevAuthenticationManager: AuthenticationManager {
override val loginUrl: String
get() = throw UnsupportedOperationException()
override val redirectUrlPrefix: String
get() = throw UnsupportedOperationException()
private val authToken: String? = BuildConfig.DEV_OAUTH_TOKEN
private val userId: String? = BuildConfig.DEV_USER_ID
override fun isLoggedIn() = Single.just(true)
override fun getFeedlyAuthToken(): Single<String> {
return authToken.takeIf { !it.isNullOrBlank() }?.let { Single.just(it) }
?: throw RuntimeException("Invalid dev oauth key")
}
override fun getFeedlyUserId(): Single<String> {
return userId.takeIf { !it.isNullOrBlank() }?.let { Single.just(it) }
?: throw RuntimeException("Invalid dev username")
}
override fun logIn(callbackUrl: String): Single<Boolean> {
throw UnsupportedOperationException()
}
}
| apache-2.0 | ab55b9cc699c2c2fb160485ae5c3a92e | 31.030303 | 80 | 0.694418 | 4.826484 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.