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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
googlesamples/mlkit | android/vision-quickstart/app/src/main/java/com/google/mlkit/vision/demo/kotlin/ChooserActivity.kt | 1 | 3985 | /*
* Copyright 2020 Google LLC. 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 com.google.mlkit.vision.demo.kotlin
import android.content.Context
import android.content.Intent
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import androidx.core.app.ActivityCompat
import com.google.mlkit.vision.demo.R
/** Demo app chooser which allows you pick from all available testing Activities. */
class ChooserActivity :
AppCompatActivity(), ActivityCompat.OnRequestPermissionsResultCallback, OnItemClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
setContentView(R.layout.activity_chooser)
// Set up ListView and Adapter
val listView = findViewById<ListView>(R.id.test_activity_list_view)
val adapter = MyArrayAdapter(this, android.R.layout.simple_list_item_2, CLASSES)
adapter.setDescriptionIds(DESCRIPTION_IDS)
listView.adapter = adapter
listView.onItemClickListener = this
}
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val clicked = CLASSES[position]
startActivity(Intent(this, clicked))
}
private class MyArrayAdapter(
private val ctx: Context,
resource: Int,
private val classes: Array<Class<*>>
) : ArrayAdapter<Class<*>>(ctx, resource, classes) {
private var descriptionIds: IntArray? = null
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var view = convertView
if (convertView == null) {
val inflater = ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = inflater.inflate(android.R.layout.simple_list_item_2, null)
}
(view!!.findViewById<View>(android.R.id.text1) as TextView).text =
classes[position].simpleName
descriptionIds?.let {
(view.findViewById<View>(android.R.id.text2) as TextView).setText(it[position])
}
return view
}
fun setDescriptionIds(descriptionIds: IntArray) {
this.descriptionIds = descriptionIds
}
}
companion object {
private const val TAG = "ChooserActivity"
private val CLASSES =
if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP)
arrayOf<Class<*>>(
LivePreviewActivity::class.java,
StillImageActivity::class.java,
)
else
arrayOf<Class<*>>(
LivePreviewActivity::class.java,
StillImageActivity::class.java,
CameraXLivePreviewActivity::class.java,
CameraXSourceDemoActivity::class.java
)
private val DESCRIPTION_IDS =
if (VERSION.SDK_INT < VERSION_CODES.LOLLIPOP)
intArrayOf(
R.string.desc_camera_source_activity,
R.string.desc_still_image_activity,
)
else
intArrayOf(
R.string.desc_camera_source_activity,
R.string.desc_still_image_activity,
R.string.desc_camerax_live_preview_activity,
R.string.desc_cameraxsource_demo_activity
)
}
}
| apache-2.0 | b018ab707947910a4f4fda4c8cda4ad1 | 33.353448 | 95 | 0.712673 | 4.340959 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/parameters/ShortcutParameter.kt | 1 | 3891 | /*
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.parameters
import javafx.event.EventHandler
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import javafx.scene.input.KeyEvent
import uk.co.nickthecoder.paratask.gui.ApplicationAction
import uk.co.nickthecoder.paratask.parameters.fields.ButtonField
import uk.co.nickthecoder.paratask.util.uncamel
class ShortcutParameter(
name: String,
label: String = name.uncamel(),
description: String = "",
value: KeyCodeCombination? = null)
: SimpleGroupParameter(name, label, description) {
val keyP = ChoiceParameter<KeyCode?>("shortcutKey", label = "Key", required = false, value = null).nullableEnumChoices()
val controlP = BooleanParameter("control", required = false, value = false)
val shiftP = BooleanParameter("shift", required = false, value = false)
val altP = BooleanParameter("alt", required = false, value = false)
val chooseKeyP = ButtonParameter("keyPress", label = "", buttonText = "Click to Pick Key Combination") { onChooseKey(it) }
private var cachedKCC: KeyCodeCombination? = null
var keyCodeCombination: KeyCodeCombination?
get() {
if (dirty) {
cachedKCC = keyP.value?.let {
ApplicationAction.createKeyCodeCombination(
it,
control = controlP.value,
shift = shiftP.value,
alt = altP.value
)
}
dirty = false
}
return cachedKCC
}
set(v) {
keyP.value = v?.code
controlP.value = modifierToBoolean(v?.control)
shiftP.value = modifierToBoolean(v?.shift)
altP.value = modifierToBoolean(v?.alt)
}
private var dirty: Boolean = true
init {
keyCodeCombination = value
addParameters(keyP, controlP, shiftP, altP, chooseKeyP)
keyP.listen { dirty = true }
controlP.listen { dirty = true }
shiftP.listen { dirty = true }
altP.listen { dirty = true }
}
private fun modifierToBoolean(mod: KeyCombination.ModifierValue?): Boolean? {
if (mod == null) {
return false
}
return when (mod) {
KeyCombination.ModifierValue.ANY -> null
KeyCombination.ModifierValue.DOWN -> true
KeyCombination.ModifierValue.UP -> false
}
}
private var keyPressHandler: EventHandler<KeyEvent>? = null
private fun onChooseKey(buttonField: ButtonField) {
keyPressHandler = EventHandler { event ->
if (event.code != KeyCode.SHIFT && event.code != KeyCode.CONTROL && event.code != KeyCode.ALT) {
keyP.value = event.code
controlP.value = event.isControlDown
shiftP.value = event.isShiftDown
altP.value = event.isAltDown
buttonField.button?.removeEventFilter(KeyEvent.KEY_PRESSED, keyPressHandler)
}
}
buttonField.button?.addEventFilter(KeyEvent.KEY_PRESSED, keyPressHandler)
}
}
| gpl-3.0 | 728a7e7b5fecfc44ed9170ceea63ed36 | 36.413462 | 126 | 0.640966 | 4.566901 | false | false | false | false |
cout970/ComputerMod | src/main/kotlin/com/cout970/computer/gui/GuiHandler.kt | 1 | 1446 | package com.cout970.computer.gui
import com.cout970.computer.gui.guis.ContainerOldComputer
import com.cout970.computer.gui.guis.ContainerOldComputerBack
import com.cout970.computer.gui.guis.GuiOldComputer
import com.cout970.computer.gui.guis.GuiOldComputerBack
import com.cout970.computer.tileentity.TileOldComputer
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
import net.minecraftforge.fml.common.network.IGuiHandler
/**
* Created by cout970 on 20/05/2016.
*/
object GuiHandler : IGuiHandler {
override fun getClientGuiElement(ID: Int, player: EntityPlayer?, world: World?, x: Int, y: Int, z: Int): Any? {
val tile = world?.getTileEntity(BlockPos(x,y,z))
if(tile is TileOldComputer){
if(ID == 0) {
return GuiOldComputer(tile, player!!)
}else{
return GuiOldComputerBack(tile, player!!.inventory)
}
}
return null
}
override fun getServerGuiElement(ID: Int, player: EntityPlayer?, world: World?, x: Int, y: Int, z: Int): Any? {
val tile = world?.getTileEntity(BlockPos(x,y,z))
if(tile is TileOldComputer){
if(ID == 0) {
return ContainerOldComputer(tile, player!!)
}else{
return ContainerOldComputerBack(tile, player!!.inventory)
}
}
return null
}
} | gpl-3.0 | 0ed05b13653fcd0edb012c47bf4d7c0d | 32.651163 | 115 | 0.659751 | 3.887097 | false | false | false | false |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/tools/places/FindTool.kt | 1 | 7573 | /*
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.tools.places
import javafx.scene.image.ImageView
import uk.co.nickthecoder.paratask.ParameterException
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.gui.DragFilesHelper
import uk.co.nickthecoder.paratask.misc.Thumbnailer
import uk.co.nickthecoder.paratask.misc.WrappedFile
import uk.co.nickthecoder.paratask.parameters.*
import uk.co.nickthecoder.paratask.project.Header
import uk.co.nickthecoder.paratask.project.HeaderRow
import uk.co.nickthecoder.paratask.table.*
import uk.co.nickthecoder.paratask.table.filter.RowFilter
import uk.co.nickthecoder.paratask.tools.AbstractCommandTool
import uk.co.nickthecoder.paratask.util.HasDirectory
import uk.co.nickthecoder.paratask.util.process.OSCommand
import java.io.File
class FindTool : AbstractCommandTool<WrappedFile>(), HasDirectory {
enum class MatchType { GLOB_CASE_SENSITIVE, GLOB_CASE_INSENSITIVE, REGEX_CASE_SENSITIVE, REGEX_CASE_INSENSITIVE }
val directoryP = FileParameter("directory", expectFile = false, mustExist = true)
override val directory by directoryP
val filenameP = StringParameter("filename", required = false)
val matchTypeP = ChoiceParameter("matchType", value = MatchType.GLOB_CASE_INSENSITIVE).enumChoices(true)
val wholeNameP = BooleanParameter("wholeName", value = false)
val nameGroupP = SimpleGroupParameter("matchName")
.addParameters(filenameP, matchTypeP, wholeNameP)
val followSymlinksP = BooleanParameter("followSymlinks", value = false)
val otherFileSystemsP = BooleanParameter("otherFileSystems", value = true)
val minDepthP = IntParameter("minDepth", required = false)
val maxDepthP = IntParameter("maxDepth", required = false)
val traverseGroupP = SimpleGroupParameter("traverseOptions")
.addParameters(followSymlinksP, otherFileSystemsP, minDepthP, maxDepthP)
val userP = StringParameter("user", required = false)
val groupP = StringParameter("group", required = false)
val typeP = ChoiceParameter<String?>("type", value = null, required = false)
.addChoice("any", null, "Any")
.addChoice("f", "f", "Regular File")
.addChoice("d", "d", "Directory")
.addChoice("l", "l", "Symbolic Link")
.addChoice("s", "s", "Socket Link")
.addChoice("p", "p", "Named Pipe")
.addChoice("b", "b", "Special Block File")
.addChoice("c", "c", "Special Character File")
val xtypeP = BooleanParameter("typeFollowsSymlink", value = true)
val emptyFilesP = BooleanParameter("emptyFiles", value = false)
val newerThanFileP = FileParameter("newerThanFile", required = false, mustExist = true)
val filterGroupP = SimpleGroupParameter("filter")
.addParameters(userP, groupP, typeP, xtypeP, emptyFilesP, newerThanFileP)
val thumbnailer = Thumbnailer()
override val taskD = TaskDescription("find", description = "Find files using the Unix 'find' command")
.addParameters(directoryP, nameGroupP, filterGroupP, traverseGroupP, thumbnailer.heightP)
override val rowFilter = RowFilter(this, columns, WrappedFile(File("")))
init {
taskD.unnamedParameter = directoryP
matchTypeP.listen {
if (matchTypeP.value == MatchType.REGEX_CASE_SENSITIVE || matchTypeP.value == MatchType.REGEX_CASE_INSENSITIVE) {
wholeNameP.value = true
}
}
columns.add(Column<WrappedFile, ImageView>("icon", label = "", getter = { thumbnailer.thumbnailImageView(it.file) }))
columns.add(BaseFileColumn<WrappedFile>("file", base = directory!!, getter = { it.file }))
columns.add(TimestampColumn<WrappedFile>("modified", getter = { it.file.lastModified() }))
columns.add(SizeColumn<WrappedFile>("size", getter = { it.file.length() }))
}
override fun customCheck() {
if (wholeNameP.value != true && (matchTypeP.value == MatchType.REGEX_CASE_SENSITIVE || matchTypeP.value == MatchType.GLOB_CASE_SENSITIVE)) {
throw(ParameterException(matchTypeP, "Can only use regex for whole-name matching"))
}
}
override fun run() {
longTitle = "Find in ${directory}"
super.run()
}
override fun createCommand(): OSCommand {
val command = OSCommand("find")
command.directory = directory!!
if (followSymlinksP.value == true) {
command.addArgument("-L")
}
minDepthP.value?.let {
command.addArgument("-mindepth")
command.addArgument(it)
}
maxDepthP.value?.let {
command.addArguments("-maxdepth", it)
}
if (otherFileSystemsP.value == false) {
command.addArgument("-mount")
}
if (emptyFilesP.value == true) {
command.addArgument("")
}
if (filenameP.value.isNotBlank()) {
if (wholeNameP.value == true) {
when (matchTypeP.value) {
MatchType.GLOB_CASE_INSENSITIVE -> command.addArguments("-iwholename", filenameP.value)
MatchType.GLOB_CASE_SENSITIVE -> command.addArguments("-wholename", filenameP.value)
MatchType.REGEX_CASE_SENSITIVE -> command.addArguments("-regex", filenameP.value)
MatchType.REGEX_CASE_INSENSITIVE -> command.addArguments("-iregex", filenameP.value)
}
} else {
when (matchTypeP.value) {
MatchType.GLOB_CASE_INSENSITIVE -> command.addArguments("-iname", filenameP.value)
MatchType.GLOB_CASE_SENSITIVE -> command.addArguments("-name", filenameP.value)
MatchType.REGEX_CASE_SENSITIVE -> throw(ParameterException(matchTypeP, "Can only use regex for whole-name matching"))
MatchType.REGEX_CASE_INSENSITIVE -> throw(ParameterException(matchTypeP, "Can only use regex for whole-name matching"))
}
}
}
typeP.value?.let {
if (xtypeP.value == true) {
command.addArguments("-xtype", it)
} else {
command.addArguments("-type", it)
}
}
return command
}
override fun processLine(line: String) {
val l2 = if (line.startsWith("./")) line.substring(2) else line
val file = directory!!.resolve(File(l2))
list.add(WrappedFile(file))
}
override fun createHeader(): Header? {
return Header(this, HeaderRow(directoryP), HeaderRow(filenameP, matchTypeP, typeP))
}
override fun createTableResults(): TableResults<WrappedFile> {
val results = super.createTableResults()
results.dragHelper = DragFilesHelper {
results.selectedRows().map { it.file }
}
return results
}
}
| gpl-3.0 | 284af63ed06200c324ace3b42d273138 | 40.382514 | 148 | 0.662749 | 4.300398 | false | false | false | false |
olonho/carkot | translator/src/test/kotlin/tests/bytearray_1/bytearray_1.kt | 1 | 497 | fun bytearray_1(x: Byte): Byte {
val z = ByteArray(10)
z.set(1, x)
val r = z.clone()
return r.get(1)
}
fun bytearray_1_array(): Int {
val size = 256
val z= ByteArray(size)
var ind = 0
while(ind < size){
z[ind] = ind.toByte()
ind +=1
}
val newInstance = z.clone()
ind = 0
var result = true
while(ind < size){
result = result and (newInstance[ind] == ind.toByte())
ind += 1
}
assert(result)
return 1
}
| mit | 4c12420f4034bd742796e38759ac05a0 | 18.88 | 62 | 0.519115 | 3.185897 | false | false | false | false |
openHPI/android-app | app/src/main/java/de/xikolo/storages/ApplicationPreferences.kt | 1 | 4735 | package de.xikolo.storages
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
import de.xikolo.App
import de.xikolo.R
import de.xikolo.controllers.helper.VideoSettingsHelper
class ApplicationPreferences {
private val preferences: SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(App.instance)
private val context: Context = App.instance
var storage: String?
get() = getString(context.getString(R.string.preference_storage), context.getString(R.string.settings_default_value_storage))
set(value) = putString(context.getString(R.string.preference_storage), value)
var isVideoQualityLimitedOnMobile: Boolean
get() = getBoolean(context.getString(R.string.preference_video_quality))
set(value) = putBoolean(context.getString(R.string.preference_video_quality), value)
var isDownloadNetworkLimitedOnMobile: Boolean
get() = getBoolean(context.getString(R.string.preference_download_network))
set(value) = putBoolean(context.getString(R.string.preference_download_network), value)
var videoPlaybackSpeed: VideoSettingsHelper.PlaybackSpeed
get() = VideoSettingsHelper.PlaybackSpeed.get(getString(
context.getString(R.string.preference_video_playback_speed),
context.getString(R.string.settings_default_value_video_playback_speed)
))
set(speed) = putString(context.getString(R.string.preference_video_playback_speed), speed.toString())
var videoSubtitlesLanguage: String?
get() {
val language = getString(
context.getString(R.string.preference_video_subtitles_language),
context.getString(R.string.settings_default_value_video_subtitles_language)
)
return if (!language.equals(context.getString(R.string.settings_default_value_video_subtitles_language))) language else null
}
set(language) {
val value = language
?: context.getString(R.string.settings_default_value_video_subtitles_language)
putString(
context.getString(R.string.preference_video_subtitles_language),
value
)
}
var isVideoShownImmersive: Boolean
get() = getBoolean(
context.getString(R.string.preference_video_immersive),
context.resources.getBoolean(R.bool.settings_default_value_video_immersive)
)
set(value) = putBoolean(context.getString(R.string.preference_video_immersive), value)
var confirmBeforeDeleting: Boolean
get() = getBoolean(context.getString(R.string.preference_confirm_delete))
set(value) = putBoolean(context.getString(R.string.preference_confirm_delete), value)
var confirmOpenExternalContentLti: Boolean
get() = getBoolean(context.getString(R.string.preference_confirm_open_external_content_lti))
set(value) = putBoolean(context.getString(R.string.preference_confirm_open_external_content_lti), value)
var confirmOpenExternalContentPeer: Boolean
get() = getBoolean(context.getString(R.string.preference_confirm_open_external_content_peer))
set(value) = putBoolean(context.getString(R.string.preference_confirm_open_external_content_peer), value)
var firstAndroid4DeprecationWarningShown: Boolean
get() = getBoolean(context.getString(R.string.preference_first_android_4_deprecation_dialog), false)
set(value) = putBoolean(context.getString(R.string.preference_first_android_4_deprecation_dialog), value)
var secondAndroid4DeprecationWarningShown: Boolean
get() = getBoolean(context.getString(R.string.preference_second_android_4_deprecation_dialog), false)
set(value) = putBoolean(context.getString(R.string.preference_second_android_4_deprecation_dialog), value)
private fun getBoolean(key: String, defValue: Boolean = true) = preferences.getBoolean(key, defValue)
private fun putBoolean(key: String, value: Boolean) {
val editor = preferences.edit()
editor.putBoolean(key, value)
editor.apply()
}
private fun getString(key: String, defValue: String? = null): String? = preferences.getString(key, defValue)
private fun putString(key: String, value: String?) {
val editor = preferences.edit()
editor.putString(key, value)
editor.apply()
}
fun delete() {
val editor = preferences.edit()
editor.clear()
editor.apply()
}
fun contains(key: String): Boolean = preferences.contains(key)
fun setToDefault(key: String, default: String) = putString(key, getString(key, default))
}
| bsd-3-clause | 40cfa043fa80d5c0440ae25045d133e1 | 43.669811 | 136 | 0.710032 | 4.360037 | false | false | false | false |
material-components/material-components-android-examples | Owl/app/src/main/java/com/materialstudies/owl/util/ContentViewBindingDelegate.kt | 1 | 1639 | /*
* 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.materialstudies.owl.util
import android.app.Activity
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import kotlin.reflect.KProperty
/**
* A delegate who lazily inflates a data binding layout, calls [Activity.setContentView], sets the lifecycle owner and
* returns the binding.
*/
class ContentViewBindingDelegate<in R : AppCompatActivity, out T : ViewDataBinding>(
@LayoutRes private val layoutRes: Int
) {
private var binding: T? = null
operator fun getValue(activity: R, property: KProperty<*>): T {
if (binding == null) {
binding = DataBindingUtil.setContentView<T>(activity, layoutRes).apply {
lifecycleOwner = activity
}
}
return binding!!
}
}
fun <R : AppCompatActivity, T : ViewDataBinding> contentView(
@LayoutRes layoutRes: Int
): ContentViewBindingDelegate<R, T> = ContentViewBindingDelegate(layoutRes)
| apache-2.0 | a786b55531a8e0fe0a8685cecd6fcb5a | 33.145833 | 118 | 0.731544 | 4.578212 | false | false | false | false |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/dao/HiddenThreadAccess.kt | 1 | 1158 | package com.emogoth.android.phone.mimi.db.dao
import androidx.room.Dao
import androidx.room.Query
import com.emogoth.android.phone.mimi.db.MimiDatabase
import com.emogoth.android.phone.mimi.db.models.HiddenThread
import io.reactivex.Single
@Dao
abstract class HiddenThreadAccess : BaseDao<HiddenThread>() {
@Query("SELECT * FROM ${MimiDatabase.HIDDEN_THREADS_TABLE}")
abstract fun getAll(): Single<List<HiddenThread>>
@Query("SELECT * FROM ${MimiDatabase.HIDDEN_THREADS_TABLE} WHERE ${HiddenThread.BOARD_NAME} = :boardName")
abstract fun getHiddenThreadsForBoard(boardName: String): Single<List<HiddenThread>>
@Query("UPDATE ${MimiDatabase.HIDDEN_THREADS_TABLE} SET ${HiddenThread.STICKY} = :sticky WHERE ${HiddenThread.BOARD_NAME} = :boardName AND ${HiddenThread.THREAD_ID} = :threadId")
abstract fun hideThread(boardName: String, threadId: Long, sticky: Boolean)
@Query("DELETE FROM ${MimiDatabase.HIDDEN_THREADS_TABLE} WHERE ${HiddenThread.TIME} < :timestamp AND ${HiddenThread.STICKY} = 0")
abstract fun prune(timestamp: Long)
@Query("DELETE FROM ${MimiDatabase.HIDDEN_THREADS_TABLE}")
abstract fun clear()
} | apache-2.0 | ba36a8882de69142a986dc70e72a9a54 | 45.36 | 182 | 0.75475 | 3.925424 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/Drawer.kt | 1 | 13121 | package tornadofx
import javafx.beans.property.*
import javafx.beans.value.ObservableValue
import javafx.collections.FXCollections
import javafx.event.EventTarget
import javafx.geometry.Orientation
import javafx.geometry.Side
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.control.ContextMenu
import javafx.scene.control.ToggleButton
import javafx.scene.control.ToolBar
import javafx.scene.layout.BorderPane
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import javafx.scene.paint.Color
fun EventTarget.drawer(
side: Side = Side.LEFT,
multiselect: Boolean = false,
floatingContent: Boolean = false,
op: Drawer.() -> Unit
) = Drawer(side, multiselect, floatingContent).attachTo(this, op)
class Drawer(side: Side, multiselect: Boolean, floatingContent: Boolean) : BorderPane() {
val dockingSideProperty: ObjectProperty<Side> = SimpleObjectProperty(side)
var dockingSide by dockingSideProperty
val floatingDrawersProperty: BooleanProperty = SimpleBooleanProperty(floatingContent)
var floatingDrawers by floatingDrawersProperty
val maxContentSizeProperty: ObjectProperty<Number> = SimpleObjectProperty<Number>()
var maxContentSize by maxContentSizeProperty
val fixedContentSizeProperty: ObjectProperty<Number> = SimpleObjectProperty<Number>()
var fixedContentSize by fixedContentSizeProperty
val buttonArea = ToolBar().addClass(DrawerStyles.buttonArea)
val contentArea = ExpandedDrawerContentArea()
val items = FXCollections.observableArrayList<DrawerItem>()
val multiselectProperty: BooleanProperty = SimpleBooleanProperty(multiselect)
var multiselect by multiselectProperty
val contextMenu = ContextMenu()
override fun getUserAgentStylesheet() = DrawerStyles().base64URL.toExternalForm()
fun item(title: String? = null, icon: Node? = null, expanded: Boolean = false, showHeader: Boolean = multiselect, op: DrawerItem.() -> Unit) =
item(SimpleStringProperty(title), SimpleObjectProperty(icon), expanded, showHeader, op)
fun item(title: ObservableValue<String?>, icon: ObservableValue<Node?>? = null, expanded: Boolean = multiselect, showHeader: Boolean = true, op: DrawerItem.() -> Unit): DrawerItem {
val item = DrawerItem(this, title, icon, showHeader)
item.button.textProperty().bind(title)
op(item)
items.add(item)
if (expanded) item.button.isSelected = true
(parent?.uiComponent<UIComponent>() as? Workspace)?.apply {
if (root.dynamicComponentMode) {
root.dynamicComponents.add(item)
}
}
return item
}
fun item(uiComponent: UIComponent, expanded: Boolean = false, showHeader: Boolean = multiselect, op: DrawerItem.() -> Unit = {}): DrawerItem {
val item = DrawerItem(this, uiComponent.titleProperty, uiComponent.iconProperty, showHeader)
item.button.textProperty().bind(uiComponent.headingProperty)
item.children.add(uiComponent.root)
op(item)
items.add(item)
if (expanded) item.button.isSelected = true
(parent?.uiComponent<UIComponent>() as? Workspace)?.apply {
if (root.dynamicComponentMode) {
root.dynamicComponents.add(item)
}
}
return item
}
init {
addClass(DrawerStyles.drawer)
configureDockingSide()
configureContextMenu()
enforceMultiSelect()
// Redraw if floating mode is toggled
floatingDrawersProperty.onChange {
updateContentArea()
parent?.requestLayout()
scene?.root?.requestLayout()
}
// Adapt docking behavior to parent
parentProperty().onChange {
if (it is BorderPane) {
if (it.left == this) dockingSide = Side.LEFT
else if (it.right == this) dockingSide = Side.RIGHT
else if (it.bottom == this) dockingSide = Side.BOTTOM
else if (it.top == this) dockingSide = Side.TOP
}
}
// Track side property change
dockingSideProperty.onChange { configureDockingSide() }
// Track button additions/removal
items.onChange { change ->
while (change.next()) {
if (change.wasAdded()) {
change.addedSubList.asSequence().mapEach { button }.forEach {
configureRotation(it)
buttonArea += Group(it)
}
}
if (change.wasRemoved()) {
change.removed.forEach {
val group = it.button.parent
it.button.removeFromParent()
group.removeFromParent()
contentArea.children.remove(it)
}
}
}
}
}
private fun enforceMultiSelect() {
multiselectProperty.onChange {
if (!multiselect) {
contentArea.children.drop(1).forEach {
(it as DrawerItem).button.isSelected = false
}
}
}
}
private fun configureContextMenu() {
contextMenu.checkmenuitem("Floating drawers") {
selectedProperty().bindBidirectional(floatingDrawersProperty)
}
contextMenu.checkmenuitem("Multiselect") {
selectedProperty().bindBidirectional(multiselectProperty)
}
buttonArea.setOnContextMenuRequested {
contextMenu.show(buttonArea, it.screenX, it.screenY)
}
}
private fun configureRotation(button: ToggleButton) {
button.rotate = when (dockingSide) {
Side.LEFT -> -90.0
Side.RIGHT -> 90.0
else -> 0.0
}
}
private fun configureDockingSide() {
when (dockingSide) {
Side.LEFT -> {
left = buttonArea
right = null
bottom = null
top = null
buttonArea.orientation = Orientation.VERTICAL
}
Side.RIGHT -> {
left = null
right = buttonArea
bottom = null
top = null
buttonArea.orientation = Orientation.VERTICAL
}
Side.BOTTOM -> {
left = null
right = null
bottom = buttonArea
top = null
buttonArea.orientation = Orientation.HORIZONTAL
}
Side.TOP -> {
left = null
right = null
bottom = null
top = buttonArea
buttonArea.orientation = Orientation.HORIZONTAL
}
}
buttonArea.items.forEach {
val button = (it as Group).children.first() as ToggleButton
configureRotation(button)
}
}
internal fun updateExpanded(item: DrawerItem) {
if (item.expanded) {
if (item !in contentArea.children) {
if (!multiselect) {
contentArea.children.toTypedArray().forEach {
(it as DrawerItem).button.isSelected = false
}
}
// Insert into content area in position according to item order
val itemIndex = items.indexOf(item)
var inserted = false
for (child in contentArea.children) {
val childIndex = items.indexOf(child)
if (childIndex > itemIndex) {
val childIndexInContentArea = contentArea.children.indexOf(child)
contentArea.children.add(childIndexInContentArea, item)
inserted = true
break
}
}
if (!inserted) {
contentArea.children.add(item)
}
}
} else if (item in contentArea.children) {
contentArea.children.remove(item)
}
updateContentArea()
}
// Dock is a child when there are expanded children
private fun updateContentArea() {
if (contentArea.children.isEmpty()) {
center = null
children.remove(contentArea)
} else {
if (fixedContentSize != null) {
when (dockingSide) {
Side.LEFT, Side.RIGHT -> {
contentArea.maxWidth = fixedContentSize.toDouble()
contentArea.minWidth = fixedContentSize.toDouble()
}
Side.TOP, Side.BOTTOM -> {
contentArea.maxHeight = fixedContentSize.toDouble()
contentArea.minHeight = fixedContentSize.toDouble()
}
}
} else {
contentArea.maxWidth = USE_COMPUTED_SIZE
contentArea.minWidth = USE_COMPUTED_SIZE
contentArea.maxHeight = USE_COMPUTED_SIZE
contentArea.minHeight = USE_COMPUTED_SIZE
if (maxContentSize != null) {
when (dockingSide) {
Side.LEFT, Side.RIGHT -> contentArea.maxWidth = maxContentSize.toDouble()
Side.TOP, Side.BOTTOM -> contentArea.maxHeight = maxContentSize.toDouble()
}
}
}
if (floatingDrawers) {
contentArea.isManaged = false
if (contentArea !in children) children.add(contentArea)
} else {
contentArea.isManaged = true
if (contentArea in children) children.remove(contentArea)
center = contentArea
}
}
}
override fun layoutChildren() {
super.layoutChildren()
if (floatingDrawers && contentArea.children.isNotEmpty()) {
val buttonBounds = buttonArea.layoutBounds
when (dockingSide) {
Side.RIGHT -> contentArea.resizeRelocate(buttonBounds.minX - contentArea.prefWidth(-1.0), buttonBounds.minY, contentArea.prefWidth(-1.0), buttonBounds.height)
else -> contentArea.resizeRelocate(buttonBounds.maxX, buttonBounds.minY, contentArea.prefWidth(-1.0), buttonBounds.height)
}
}
}
}
class ExpandedDrawerContentArea : VBox() {
init {
addClass(DrawerStyles.contentArea)
children.onChange { change ->
while (change.next()) {
if (change.wasAdded()) {
change.addedSubList.asSequence()
.filter { VBox.getVgrow(it) == null }
.forEach { VBox.setVgrow(it, Priority.ALWAYS) }
}
}
}
}
}
class DrawerItem(val drawer: Drawer, title: ObservableValue<String?>? = null, icon: ObservableValue<Node?>? = null, showHeader: Boolean) : VBox() {
internal val button = ToggleButton().apply {
if (title != null) textProperty().bind(title)
if (icon != null) graphicProperty().bind(icon)
}
val expandedProperty = button.selectedProperty()
var expanded by expandedProperty
init {
addClass(DrawerStyles.drawerItem)
if (showHeader) {
titledpane {
textProperty().bind(title)
isCollapsible = false
}
}
button.selectedProperty().onChange { drawer.updateExpanded(this) }
drawer.updateExpanded(this)
children.onChange { change ->
while (change.next()) {
if (change.wasAdded()) {
change.addedSubList.asSequence()
.filter { VBox.getVgrow(it) == null }
.forEach { VBox.setVgrow(it, Priority.ALWAYS) }
}
}
}
}
}
class DrawerStyles : Stylesheet() {
companion object {
val drawer by cssclass()
val drawerItem by cssclass()
val buttonArea by cssclass()
val contentArea by cssclass()
}
init {
drawer {
contentArea {
borderColor += box(Color.DARKGRAY)
borderWidth += box(0.5.px)
}
buttonArea {
spacing = 0.px
padding = box(0.px)
toggleButton {
backgroundInsets += box(0.px)
backgroundRadius += box(0.px)
and(selected) {
backgroundColor += c("#818181")
textFill = Color.WHITE
}
}
}
}
drawerItem child titledPane {
title {
backgroundRadius += box(0.px)
padding = box(2.px, 5.px)
}
content {
borderColor += box(Color.TRANSPARENT)
}
}
}
} | apache-2.0 | abf870138fe51c65ee5681fefaeeed92 | 34.657609 | 185 | 0.55293 | 5.196436 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/dialog/RxDialogSure.kt | 1 | 3241 | package com.tamsiree.rxui.view.dialog
import android.content.Context
import android.content.DialogInterface
import android.text.method.LinkMovementMethod
import android.text.method.ScrollingMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.tamsiree.rxkit.RxDataTool.Companion.isNullString
import com.tamsiree.rxkit.RxRegTool.isURL
import com.tamsiree.rxkit.RxTextTool.getBuilder
import com.tamsiree.rxui.R
/**
* @author tamsiree
* @date 2016/7/19
* 确认 弹出框
*/
class RxDialogSure : RxDialog {
lateinit var logoView: ImageView
private set
lateinit var titleView: TextView
private set
lateinit var contentView: TextView
private set
lateinit var sureView: TextView
private set
private var title: String = ""
private var logoIcon = -1
constructor(context: Context?, themeResId: Int) : super(context!!, themeResId) {
initView()
}
constructor(context: Context?, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context!!, cancelable, cancelListener) {
initView()
}
constructor(context: Context?) : super(context!!) {
initView()
}
constructor(context: Context?, alpha: Float, gravity: Int) : super(context, alpha, gravity) {
initView()
}
fun setSureListener(listener: View.OnClickListener?) {
sureView.setOnClickListener(listener)
}
fun setSure(content: String?) {
sureView.text = content
}
fun setContent(str: String?) {
if (isURL(str)) {
// 响应点击事件的话必须设置以下属性
contentView.movementMethod = LinkMovementMethod.getInstance()
contentView.text = getBuilder("").setBold().append(str!!).setUrl(str).create() //当内容为网址的时候,内容变为可点击
} else {
contentView.text = str
}
}
private fun initView() {
val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_sure, null)
sureView = dialogView.findViewById(R.id.tv_sure)
titleView = dialogView.findViewById(R.id.tv_title)
titleView.setTextIsSelectable(true)
contentView = dialogView.findViewById(R.id.tv_content)
contentView.movementMethod = ScrollingMovementMethod.getInstance()
contentView.setTextIsSelectable(true)
logoView = dialogView.findViewById(R.id.iv_logo)
if (isNullString(title)) {
titleView.visibility = View.GONE
}
if (logoIcon == -1) {
logoView.visibility = View.GONE
}
setContentView(dialogView)
}
fun setLogo(resId: Int) {
logoIcon = resId
if (logoIcon == -1) {
logoView.visibility = View.GONE
return
}
logoView.visibility = View.VISIBLE
logoView.setImageResource(logoIcon)
}
fun setTitle(titleStr: String) {
title = titleStr
if (isNullString(title)) {
titleView.visibility = View.GONE
return
}
titleView.visibility = View.VISIBLE
titleView.text = title
}
} | apache-2.0 | 365402ae9748d1caf2e727a2ecdc784d | 29.442308 | 155 | 0.657188 | 4.451477 | false | false | false | false |
vondear/RxTools | RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityWheelHorizontal.kt | 1 | 5806 | package com.tamsiree.rxdemo.activity
import android.os.Bundle
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxBarTool.noTitle
import com.tamsiree.rxkit.RxDataTool.Companion.stringToInt
import com.tamsiree.rxkit.RxDeviceTool.setPortrait
import com.tamsiree.rxkit.TLog
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.view.RxRulerWheelView
import com.tamsiree.rxui.view.RxRulerWheelView.OnWheelItemSelectedListener
import com.tamsiree.rxui.view.wheelhorizontal.AbstractWheel
import com.tamsiree.rxui.view.wheelhorizontal.ArrayWheelAdapter
import com.tamsiree.rxui.view.wheelhorizontal.OnWheelScrollListener
import kotlinx.android.synthetic.main.activity_wheel_horizontal.*
import java.util.*
/**
* @author tamsiree
*/
class ActivityWheelHorizontal : ActivityBase() {
private val listYearMonth: MutableList<String> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
noTitle(this)
setContentView(R.layout.activity_wheel_horizontal)
setPortrait(this)
}
override fun initView() {
rx_title.setLeftFinish(mContext)
initRulerView()
}
override fun initData() {
listYearMonth.clear()
val calendar = Calendar.getInstance(Locale.CHINA)
for (i in calendar[Calendar.YEAR] - 3..calendar[Calendar.YEAR] + 2) {
for (j in 1..12) {
listYearMonth.add(i.toString() + "年" + j + "月")
}
}
val arr = listYearMonth.toTypedArray()
var CurrentIndex = 0
for (i in arr.indices) {
if (arr[i] == calendar[Calendar.YEAR].toString() + "年" + (calendar[Calendar.MONTH] + 1) + "月") {
CurrentIndex = i
break
}
}
val ampmAdapter = ArrayWheelAdapter(
this, arr)
ampmAdapter.itemResource = R.layout.item_wheel_year_month
ampmAdapter.itemTextResource = R.id.tv_year
wheelView_year_month.viewAdapter = ampmAdapter
// set current time
wheelView_year_month.currentItem = CurrentIndex
wheelView_year_month.addScrollingListener(object : OnWheelScrollListener {
var before: String? = null
var behind: String? = null
override fun onScrollingStarted(wheel: AbstractWheel) {
before = listYearMonth[wheel.currentItem]
}
override fun onScrollingFinished(wheel: AbstractWheel) {
behind = listYearMonth[wheel.currentItem]
TLog.v("addScrollingListener", "listYearMonth:" + listYearMonth[wheel.currentItem])
if (before != behind) {
val year = stringToInt(listYearMonth[wheel.currentItem].substring(0, 4))
val month = stringToInt(listYearMonth[wheel.currentItem].substring(5, 6))
//initBarChart(VonUtil.getDaysByYearMonth(year, month));
}
}
})
wheelView_year_month.addClickingListener { wheel, itemIndex ->
TLog.v("addScrollingListener", "listYearMonth:" + listYearMonth[itemIndex])
wheelView_year_month.setCurrentItem(itemIndex, true)
/*
* int year =
* VonUtil.StringToInt(listYearMonth.get(itemIndex)
* .substring(0, 4)); int month =
* VonUtil.StringToInt(listYearMonth
* .get(itemIndex).substring(5, 6));
* initBarChart(VonUtil.getDaysByYearMonth(year, month));
*/
}
}
private fun initRulerView() {
val items: MutableList<String> = ArrayList()
for (i in 1..40) {
items.add((i * 1000).toString())
}
wheelview.items = items
wheelview.selectIndex(8)
wheelview.setAdditionCenterMark("元")
val items2: MutableList<String> = ArrayList()
items2.add("一月")
items2.add("二月")
items2.add("三月")
items2.add("四月")
items2.add("五月")
items2.add("六月")
items2.add("七月")
items2.add("八月")
items2.add("九月")
items2.add("十月")
items2.add("十一月")
items2.add("十二月")
wheelview2.items = items2
val items3: MutableList<String> = ArrayList()
items3.add("1")
items3.add("2")
items3.add("3")
items3.add("5")
items3.add("7")
items3.add("11")
items3.add("13")
items3.add("17")
items3.add("19")
items3.add("23")
items3.add("29")
items3.add("31")
wheelview3.items = items3
wheelview3.setAdditionCenterMark("m")
// mWheelview4.setItems(items);
// mWheelview4.setEnabled(false);
wheelview5.items = items
wheelview5.minSelectableIndex = 3
wheelview5.maxSelectableIndex = items.size - 3
items.removeAt(items.size - 1)
items.removeAt(items.size - 2)
items.removeAt(items.size - 3)
items.removeAt(items.size - 4)
selected_tv.text = String.format("onWheelItemSelected:%1\$s", "")
changed_tv.text = String.format("onWheelItemChanged:%1\$s", "")
wheelview4.setOnWheelItemSelectedListener(object : OnWheelItemSelectedListener {
override fun onWheelItemSelected(wheelView: RxRulerWheelView, position: Int) {
selected_tv.text = String.format("onWheelItemSelected:%1\$s", wheelView.items[position])
}
override fun onWheelItemChanged(wheelView: RxRulerWheelView, position: Int) {
changed_tv.text = String.format("onWheelItemChanged:%1\$s", wheelView.items[position])
}
})
wheelview4.postDelayed(Runnable { wheelview4.items = items }, 3000)
}
} | apache-2.0 | 4b8066f22b2618d68d08b3c0430aaf86 | 36.253247 | 108 | 0.622211 | 3.955862 | false | false | false | false |
dtarnawczyk/modernlrs | src/main/org/lrs/kmodernlrs/controllers/AgentsController.kt | 1 | 3637 | package org.lrs.kmodernlrs.controllers
import com.google.gson.Gson
import org.lrs.kmodernlrs.event.XapiEvent
import org.lrs.kmodernlrs.event.XapiEventData
import org.lrs.kmodernlrs.gson.GsonFactoryProvider
import org.lrs.kmodernlrs.domain.Actor
import org.lrs.kmodernlrs.controllers.security.UserAccount
import org.lrs.kmodernlrs.services.AgentsService
import org.lrs.kmodernlrs.util.InverseFunctionalIdentifierHelper
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.Cacheable
import org.springframework.context.ApplicationEventPublisher
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.web.bind.annotation.RestController
import java.sql.Timestamp
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.ws.rs.*
import javax.ws.rs.core.Context
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.SecurityContext
@RestController
@Path(ApiEndpoints.AGENTS_ENDPOINT)
open class AgentsController {
val log: Logger = LoggerFactory.getLogger(AgentsController::class.java)
@Autowired lateinit var service: AgentsService
@Autowired lateinit var eventPublisher: ApplicationEventPublisher
lateinit var gson: Gson
@Autowired
fun setGsonProvider(gsonFactory: GsonFactoryProvider){
gson = gsonFactory.gsonFactory()
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Cacheable("statements")
fun getAgents(@Context request: HttpServletRequest, @Context context: SecurityContext,
agentDetailsJson: String) : Response {
if(agentDetailsJson.isNullOrEmpty()){
throw WebApplicationException(
Response.status(HttpServletResponse.SC_NO_CONTENT)
.entity("Agent JSON is empty").build())
}
val actor: Actor = gson.fromJson(agentDetailsJson, Actor::class.java)
log.debug(">> Actor: $actor")
val actorDetails: Actor? = service.getAgentDetails(actor)
if (actorDetails != null) {
agentEventCalled(request, context, actor, "POST")
return Response.status(HttpServletResponse.SC_OK).entity(actorDetails).build()
} else {
log.debug(">>> No Agent found")
throw WebApplicationException(
Response.status(HttpServletResponse.SC_NOT_FOUND).build())
}
}
fun agentEventCalled(request: HttpServletRequest, context: SecurityContext,
actor: Actor, method: String) {
val remoteIp = request.remoteAddr
var userName:String
if(context.userPrincipal is UsernamePasswordAuthenticationToken){
val userPassAuthToken = context.userPrincipal as UsernamePasswordAuthenticationToken
userName = (userPassAuthToken.principal as UserAccount).name
} else {
userName = context.userPrincipal.name
}
val currentTime = Timestamp(Calendar.getInstance().time.time).toString()
val attrsMap = InverseFunctionalIdentifierHelper.getAvailableAttrsFromActor(actor)
val ids: MutableList<String> = mutableListOf()
for ((key, value) in attrsMap) {
ids.add(key +"="+ value)
}
val xapiData = XapiEventData("Agent", ids)
val event = XapiEvent(userName, currentTime, xapiData , method, remoteIp)
eventPublisher.publishEvent(event)
}
}
| apache-2.0 | eb1dc7a27d5e3a3cad88d568039149fc | 40.329545 | 96 | 0.722299 | 4.680824 | false | false | false | false |
bl-lia/kktAPK | app/src/main/kotlin/com/bl_lia/kirakiratter/domain/value_object/StatusForm.kt | 1 | 441 | package com.bl_lia.kirakiratter.domain.value_object
data class StatusForm(
val status: String,
val inReplyToId: Int? = null,
val mediaIds: List<Int> = listOf(),
val sensitive: Boolean = false,
val spoilerText: String? = null,
val visibility: String? = null) {
fun debug(): String =
"status: %s, spoilerText: %s, mediaId: %s".format(status, spoilerText, mediaIds.joinToString())
} | mit | 7da3ef0ff4a2a26f7aa54d7149beb940 | 33 | 103 | 0.630385 | 3.902655 | false | false | false | false |
alexcustos/linkasanote | app/src/main/java/com/bytesforge/linkasanote/manageaccounts/AccountsAdapter.kt | 1 | 4403 | /*
* LaaNo Android application
*
* @author Aleksandr Borisenko <[email protected]>
* Copyright (C) 2017 Aleksandr Borisenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bytesforge.linkasanote.manageaccounts
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bytesforge.linkasanote.databinding.ItemManageAccountsAddBinding
import com.bytesforge.linkasanote.databinding.ItemManageAccountsBinding
import java.security.InvalidParameterException
class AccountsAdapter(
private val presenter: ManageAccountsPresenter,
private val accountItems: MutableList<AccountItem>
) : RecyclerView.Adapter<AccountsAdapter.ViewHolder>() {
class ViewHolder(private val binding: ViewDataBinding) : RecyclerView.ViewHolder(
binding.root
) {
fun bind(accountItem: AccountItem) {
if (accountItem.type == AccountItem.TYPE_ACCOUNT) {
(binding as ItemManageAccountsBinding).accountItem = accountItem
}
binding.executePendingBindings()
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val inflater = LayoutInflater.from(parent.context)
return when (viewType) {
AccountItem.TYPE_ACCOUNT -> {
val binding = ItemManageAccountsBinding.inflate(
inflater,
parent,
false
)
binding.presenter = presenter
ViewHolder(binding)
}
AccountItem.TYPE_ACTION_ADD -> {
val binding = ItemManageAccountsAddBinding.inflate(
inflater,
parent,
false
)
binding.presenter = presenter
ViewHolder(binding)
}
else -> {
throw InvalidParameterException("Unexpected AccountItem type ID [$viewType]")
}
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val accountItem = accountItems[position]
holder.bind(accountItem)
}
override fun getItemCount(): Int {
return accountItems.size
}
override fun getItemViewType(position: Int): Int {
return accountItems[position].type
}
fun swapItems(accountItems: List<AccountItem>) {
val diffCallback = AccountItemDiffCallback(this.accountItems, accountItems)
val diffResult = DiffUtil.calculateDiff(diffCallback)
this.accountItems.clear()
this.accountItems.addAll(accountItems)
diffResult.dispatchUpdatesTo(this)
}
inner class AccountItemDiffCallback(
private val oldList: List<AccountItem>,
private val newList: List<AccountItem>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldAccountName = oldList[oldItemPosition].accountName
val newAccountName = newList[newItemPosition].accountName
return (oldAccountName == null && newAccountName == null
|| oldAccountName != null && oldAccountName == newAccountName)
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
return oldItem == newItem
}
}
} | gpl-3.0 | c8f2ad722375b30a4317ab0c822469e7 | 35.7 | 94 | 0.658188 | 5.298436 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/concurrency/Threads.kt | 1 | 2016 | package au.com.codeka.warworlds.server.concurrency
import com.google.common.base.Preconditions
/**
* An enumeration of the thread types within War Worlds. Has some helper methods to ensure you run
* on a particular thread.
*/
enum class Threads {
/**
* A special "class" of thread that actually represents a pool of background workers.
*/
BACKGROUND;
private var isInitialized = false
private var taskQueue: TaskQueue? = null
private var thread: Thread? = null
private var threadPool: ThreadPool? = null
fun setThread(thread: Thread?, taskQueue: TaskQueue) {
Preconditions.checkState(!isInitialized || this.taskQueue === taskQueue)
this.thread = thread
this.taskQueue = taskQueue
this.isInitialized = true
}
fun setThreadPool(threadPool: ThreadPool?) {
Preconditions.checkState(!isInitialized)
this.threadPool = threadPool
this.isInitialized = true
}
val isCurrentThread: Boolean
get() {
Preconditions.checkState(isInitialized)
return if (thread != null) {
thread === Thread.currentThread()
} else if (threadPool != null) {
threadPool!!.isThread(this)
} else {
throw IllegalStateException("thread is null and threadPool is null")
}
}
fun runTask(runnable: Runnable) {
when {
threadPool != null -> {
threadPool!!.runTask(runnable)
}
taskQueue != null -> {
taskQueue!!.postTask(runnable)
}
else -> {
throw IllegalStateException("Cannot run task, no handler, taskQueue or threadPool!")
}
}
}
companion object {
fun checkOnThread(thread: Threads) {
// Note: We don't use Preconditions.checkState because we want a nice error message and don't
// want to allocate the string for the message every time.
check(thread.isCurrentThread) { "Unexpectedly not on $thread" }
}
fun checkNotOnThread(thread: Threads) {
check(!thread.isCurrentThread) { "Unexpectedly on $thread" }
}
}
} | mit | 2634c3bb3e7c71a321655fe3746ed185 | 27.814286 | 99 | 0.668155 | 4.55079 | false | false | false | false |
salRoid/Filmy | app/src/main/java/tech/salroid/filmy/workers/TrendingWorker.kt | 1 | 1735 | package tech.salroid.filmy.workers
import android.content.Context
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.work.ListenableWorker
import androidx.work.WorkerParameters
import com.google.common.util.concurrent.ListenableFuture
import tech.salroid.filmy.data.network.NetworkUtil
class TrendingWorker(
context: Context,
workParameters: WorkerParameters
) : ListenableWorker(context, workParameters) {
override fun startWork(): ListenableFuture<Result> {
NetworkUtil.getTrendingMovies({
// TODO save to DB
}, {
})
return CallbackToFutureAdapter.getFuture {
it.set(Result.success())
}
}
/* private fun syncNowTrending() {
val url =
"https://api.themoviedb.org/3/movie/popular?api_key=${BuildConfig.TMDB_API_KEY}"
val jsonObjectRequest = JsonObjectRequest(url, null,
{ response: JSONObject ->
parseOutput(response.toString())
taskFinished++
if (taskFinished == 3) {
//jobFinished(workParameters, false);
taskFinished = 0
}
}
) { error: VolleyError ->
val networkResponse = error.networkResponse
if (networkResponse != null) sendFetchFailedMessage(networkResponse.statusCode) else sendFetchFailedMessage(
0
)
}
tmdbRequestQueue.add(jsonObjectRequest)
}*/
/*private fun sendFetchFailedMessage(message: Int) {
val intent = Intent("fetch-failed")
intent.putExtra("message", message)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
}*/
} | apache-2.0 | f086b48bf1ed0a1c6bcb52c93409daee | 31.148148 | 120 | 0.635159 | 4.928977 | false | false | false | false |
exponent/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/views/ViewManagerWrapperDelegate.kt | 2 | 2173 | package expo.modules.kotlin.views
import android.content.Context
import android.util.Log
import android.view.View
import com.facebook.react.bridge.ReadableMap
import expo.modules.core.utilities.ifNull
import expo.modules.kotlin.ModuleHolder
import expo.modules.kotlin.callbacks.ViewCallbackDelegate
import kotlin.reflect.full.declaredMemberProperties
import kotlin.reflect.jvm.isAccessible
class ViewManagerWrapperDelegate(internal var moduleHolder: ModuleHolder) {
private val definition: ViewManagerDefinition
get() = requireNotNull(moduleHolder.definition.viewManagerDefinition)
val name: String
get() = moduleHolder.name
fun createView(context: Context): View {
return definition
.createView(context)
.also {
configureView(it)
}
}
fun setProxiedProperties(view: View, proxiedProperties: ReadableMap) {
definition.setProps(proxiedProperties, view)
}
fun onDestroy(view: View) =
definition.onViewDestroys?.invoke(view)
fun getExportedCustomDirectEventTypeConstants(): Map<String, Any>? {
return definition
.callbacksDefinition
?.names
?.map {
it to mapOf(
"registrationName" to it
)
}
?.toMap()
}
private fun configureView(view: View) {
val callbacks = definition.callbacksDefinition?.names ?: return
val kClass = view.javaClass.kotlin
val propertiesMap = kClass
.declaredMemberProperties
.map { it.name to it }
.toMap()
callbacks.forEach {
val property = propertiesMap[it].ifNull {
Log.w("ExpoModuleCore", "Property `$it` does not exist in ${kClass.simpleName}.")
return@forEach
}
property.isAccessible = true
val delegate = property.getDelegate(view).ifNull {
Log.w("ExpoModulesCore", "Property delegate for `$it` in ${kClass.simpleName} does not exist.")
return@forEach
}
val viewDelegate = (delegate as? ViewCallbackDelegate<*>).ifNull {
Log.w("ExpoModulesCore", "Property delegate for `$it` cannot be cased to `ViewCallbackDelegate`.")
return@forEach
}
viewDelegate.isValidated = true
}
}
}
| bsd-3-clause | 24aa9d79354cc85ca682c83a09620022 | 27.592105 | 106 | 0.696733 | 4.434694 | false | false | false | false |
Undin/intellij-rust | ml-completion/src/main/kotlin/org/rust/ml/RsContextFeatureProvider.kt | 2 | 1820 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ml
import com.intellij.codeInsight.completion.ml.CompletionEnvironment
import com.intellij.codeInsight.completion.ml.ContextFeatureProvider
import com.intellij.codeInsight.completion.ml.MLFeatureValue
import org.rust.lang.core.macros.findExpansionElementOrSelf
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.ext.ancestorOrSelf
import org.rust.lang.core.psi.ext.isInAsyncContext
import org.rust.lang.core.psi.ext.isInConstContext
import org.rust.lang.core.psi.ext.isInUnsafeContext
/**
* Note that there is a common context feature provider for all languages:
* [com.intellij.completion.ml.common.CommonLocationFeatures].
*
* @see RsElementFeatureProvider
*/
@Suppress("UnstableApiUsage")
class RsContextFeatureProvider : ContextFeatureProvider {
override fun getName(): String = "rust"
override fun calculateFeatures(environment: CompletionEnvironment): Map<String, MLFeatureValue> {
val result = hashMapOf<String, MLFeatureValue>()
val position = environment.parameters.position.findExpansionElementOrSelf()
val ancestorExpr = position.ancestorOrSelf<RsExpr>()
result[IS_UNSAFE_CONTEXT] = MLFeatureValue.binary(ancestorExpr?.isInUnsafeContext == true)
result[IS_ASYNC_CONTEXT] = MLFeatureValue.binary(ancestorExpr?.isInAsyncContext == true)
result[IS_CONST_CONTEXT] = MLFeatureValue.binary(ancestorExpr?.isInConstContext == true)
return result
}
companion object {
private const val IS_UNSAFE_CONTEXT: String = "is_unsafe_context"
private const val IS_ASYNC_CONTEXT: String = "is_async_context"
private const val IS_CONST_CONTEXT: String = "is_const_context"
}
}
| mit | 37839c04ddde89f5d18a0951c93b5582 | 39.444444 | 101 | 0.760989 | 4.193548 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/completion/RsExternAbiCompletionProvider.kt | 3 | 2188 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import org.rust.ide.annotator.fixes.AddFeatureAttributeFix
import org.rust.lang.core.FeatureAvailability.AVAILABLE
import org.rust.lang.core.FeatureAvailability.CAN_BE_ADDED
import org.rust.lang.core.or
import org.rust.lang.core.psi.RsElementTypes.RAW_STRING_LITERAL
import org.rust.lang.core.psi.RsElementTypes.STRING_LITERAL
import org.rust.lang.core.psi.RsExternAbi
import org.rust.lang.core.withSuperParent
import org.rust.lang.utils.SUPPORTED_CALLING_CONVENTIONS
object RsExternAbiCompletionProvider : RsCompletionProvider() {
override val elementPattern: ElementPattern<out PsiElement>
get() = psiElement(STRING_LITERAL)
.or(psiElement(RAW_STRING_LITERAL))
.withSuperParent<RsExternAbi>(2)
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val file = parameters.originalFile
val lookups = SUPPORTED_CALLING_CONVENTIONS.mapNotNull { (conventionName, compilerFeature) ->
val availability = compilerFeature?.availability(file) ?: AVAILABLE
if (availability != AVAILABLE && availability != CAN_BE_ADDED) return@mapNotNull null
var builder = LookupElementBuilder.create(conventionName)
if (compilerFeature != null) {
builder = builder.withInsertHandler { _, _ ->
if (compilerFeature.availability(file) == CAN_BE_ADDED) {
AddFeatureAttributeFix.addFeatureAttribute(file.project, file, compilerFeature.name)
}
}
}
builder
}
result.addAllElements(lookups)
}
}
| mit | fb972bb3afc89df8124154c4e6e26682 | 44.583333 | 124 | 0.732633 | 4.558333 | false | false | false | false |
MeilCli/Twitter4HK | library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/AbsPost.kt | 1 | 600 | package com.twitter.meil_mitu.twitter4hk
import java.io.File
import java.util.*
abstract class AbsPost<T>(protected var oauth: AbsOauth) : AbsMethod<T>() {
internal val fileMap = HashMap<String, File>()
val fileParam: Set<Map.Entry<String, File>> = fileMap.entries
val fileSize = fileMap.size
// pair first is startByte, second is endByte
val separateFileMap = HashMap<String,Pair<Long,Long>>()
override val method = "POST"
init {
}
protected fun fileParam(key: String)
= Param<AbsMethod<T>, File, File>(fileMap, key, { x -> x }, { x -> x })
}
| mit | cfa587f39aa3b1e881f1f03bc234ec94 | 26.272727 | 83 | 0.658333 | 3.592814 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/suggested/RsSuggestedRefactoringSupport.kt | 2 | 2352 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.suggested
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.suggested.*
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.RsPatBinding
import org.rust.lang.core.psi.RsPatIdent
import org.rust.lang.core.psi.RsValueParameterList
import org.rust.lang.core.psi.ext.RsNameIdentifierOwner
class RsSuggestedRefactoringSupport : SuggestedRefactoringSupport {
override val availability: SuggestedRefactoringAvailability
get() = RsSuggestedRefactoringAvailability(this)
override val execution: SuggestedRefactoringExecution
get() = RsSuggestedRefactoringExecution(this)
override val stateChanges: SuggestedRefactoringStateChanges
get() = RsSuggestedRefactoringStateChanges(this)
override val ui: SuggestedRefactoringUI
get() = RsSuggestedRefactoringUI()
override fun importsRange(psiFile: PsiFile): TextRange? = null
override fun isAnchor(psiElement: PsiElement): Boolean = when (psiElement) {
// May return true for const pat binding since we can't distinguish them
// without name resolution, which is forbidden here.
// Refactoring for constants is suppressed by `RsSuggestedRefactoringAvailability`.
is RsPatBinding -> psiElement.parent is RsPatIdent && psiElement.parentOfType<RsValueParameterList>() == null
is RsNameIdentifierOwner -> true
else -> false
}
override fun isIdentifierPart(c: Char): Boolean = Character.isUnicodeIdentifierStart(c)
override fun isIdentifierStart(c: Char): Boolean = Character.isUnicodeIdentifierPart(c)
override fun nameRange(anchor: PsiElement): TextRange? = (anchor as? RsNameIdentifierOwner)?.nameIdentifier?.textRange
override fun signatureRange(anchor: PsiElement): TextRange? {
if (anchor is RsFunction) {
val start = anchor.identifier
val end = anchor.valueParameterList?.lastChild ?: anchor.identifier
return TextRange(start.startOffset, end.endOffset)
}
return (anchor as? RsNameIdentifierOwner)?.nameIdentifier?.textRange
}
}
| mit | e5015594a804bda5cbc7f71224364ddd | 44.230769 | 122 | 0.753401 | 4.993631 | false | false | false | false |
Noisyfox/itertools-kotlin | src/main/kotlin/cn/noisyfox/kotlin/itertools/NullElse.kt | 1 | 3948 | /*
* Copyright 2017 Noisyfox.
*
* 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 cn.noisyfox.kotlin.itertools
/**
* Created by Noisyfox on 2017/5/11.
*/
/**
* Returns the first element matching the given [predicate],
* or the result of calling the [defaultValue] function if no such element is found.
*/
inline fun <T> Iterable<T>.firstOrElse(predicate: (T) -> Boolean, defaultValue: () -> T): T {
for (element in this) if (predicate(element)) return element
return defaultValue()
}
/**
* Returns the first element which is not null.
* @throws [NoSuchElementException] if there are no elements or all elements are null.
*/
fun <T> Iterable<T?>.firstNotNull(): T = this.first { it != null } as T
/**
* Returns the first element which is not null.
* @throws [NoSuchElementException] if there are no elements or all elements are null.
*/
fun <T> List<T?>.firstNotNull(): T = this.first { it != null } as T
/**
* Returns the first element which is not null,
* or the result of calling the [defaultValue] function if there are no elements or all elements are null.
*/
inline fun <T> Iterable<T?>.firstNotNullOrElse(defaultValue: () -> T): T = firstOrElse({ it != null }, defaultValue) as T
/**
* Returns the first element which is not null,
* or the result of calling the [defaultValue] function if there are no elements or all elements are null.
*/
inline fun <T> List<T?>.firstNotNullOrElse(defaultValue: () -> T): T = firstOrElse({ it != null }, defaultValue) as T
/**
* Returns the last element matching the given [predicate],
* or the result of calling the [defaultValue] function if no such element is found.
*/
inline fun <T> Iterable<T>.lastOrElse(predicate: (T) -> Boolean, defaultValue: () -> T): T {
var last: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
last = element
found = true
}
}
if (!found) {
return defaultValue()
}
return last as T
}
/**
* Returns the last element matching the given [predicate],
* or the result of calling the [defaultValue] function if no such element is found.
*/
inline fun <T> List<T>.lastOrElse(predicate: (T) -> Boolean, defaultValue: () -> T): T {
val iterator = this.listIterator(size)
while (iterator.hasPrevious()) {
val element = iterator.previous()
if (predicate(element)) return element
}
return defaultValue()
}
/**
* Returns the last element which is not null.
* @throws [NoSuchElementException] if there are no elements or all elements are null.
*/
fun <T> Iterable<T?>.lastNotNull(): T = this.last { it != null } as T
/**
* Returns the last element which is not null.
* @throws [NoSuchElementException] if there are no elements or all elements are null.
*/
fun <T> List<T?>.lastNotNull(): T = this.last { it != null } as T
/**
* Returns the last element which is not null,
* or the result of calling the [defaultValue] function if there are no elements or all elements are null.
*/
inline fun <T> Iterable<T?>.lastNotNullOrElse(defaultValue: () -> T): T = lastOrElse({ it != null }, defaultValue) as T
/**
* Returns the last element which is not null,
* or the result of calling the [defaultValue] function if there are no elements or all elements are null.
*/
inline fun <T> List<T?>.lastNotNullOrElse(defaultValue: () -> T): T = lastOrElse({ it != null }, defaultValue) as T
| apache-2.0 | 5e62b9b0108b1a3f368a82ad970d8ff3 | 33.938053 | 121 | 0.681358 | 3.901186 | false | false | false | false |
android/enterprise-samples | Work-profile-codelab/app-starter/src/main/java/com/example/workprofile/ContactsAdapter.kt | 2 | 2155 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.workprofile
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
data class Contact(val name: String, val isWork: Boolean)
class ContactsAdapter(private val contactList: MutableList<Contact>) :
RecyclerView.Adapter<ContactsAdapter.ContactViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, position: Int): ContactViewHolder {
val view = LayoutInflater.from(viewGroup.context)
.inflate(R.layout.contact_item_layout, viewGroup, false)
return ContactViewHolder(view)
}
override fun onBindViewHolder(holder: ContactViewHolder, position: Int) {
val contact = contactList[position]
holder.contact?.let {
it.text = contact.name
it.setCompoundDrawablesRelativeWithIntrinsicBounds(
it.resources?.getDrawable(
when (contact.isWork) {
true -> R.drawable.ic_person_primary_40dp
false -> R.drawable.ic_person_green_40dp
},
null
),
null,
null,
null
)
}
}
override fun getItemCount(): Int = contactList.size
class ContactViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var contact: TextView? = itemView.findViewById(R.id.contact_name_tv) as TextView
}
}
| apache-2.0 | 722707c0607644b6f6690fe939052b19 | 34.916667 | 93 | 0.666357 | 4.694989 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/TextButtonTokens.kt | 3 | 1618 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
import androidx.compose.ui.unit.dp
internal object TextButtonTokens {
val ContainerHeight = 40.0.dp
val ContainerShape = ShapeKeyTokens.CornerFull
val DisabledLabelTextColor = ColorSchemeKeyTokens.OnSurface
const val DisabledLabelTextOpacity = 0.38f
val FocusLabelTextColor = ColorSchemeKeyTokens.Primary
val HoverLabelTextColor = ColorSchemeKeyTokens.Primary
val LabelTextColor = ColorSchemeKeyTokens.Primary
val LabelTextFont = TypographyKeyTokens.LabelLarge
val PressedLabelTextColor = ColorSchemeKeyTokens.Primary
val DisabledIconColor = ColorSchemeKeyTokens.OnSurface
const val DisabledIconOpacity = 0.38f
val FocusIconColor = ColorSchemeKeyTokens.Primary
val HoverIconColor = ColorSchemeKeyTokens.Primary
val IconColor = ColorSchemeKeyTokens.Primary
val IconSize = 18.0.dp
val PressedIconColor = ColorSchemeKeyTokens.Primary
} | apache-2.0 | 88d29051e0a21715b1ea07579250e3f9 | 39.475 | 75 | 0.775649 | 4.801187 | false | false | false | false |
outlying/card-check | domain/src/main/kotlin/com/antyzero/cardcheck/card/mpk/MpkCard.kt | 1 | 1968 | package com.antyzero.cardcheck.card.mpk
import com.antyzero.cardcheck.card.Card
/**
* Each MPK card is identified by two numbers:
*
* - Card ID, which is unique for all cards in MPK database / system
* - Client ID for user identification
*
* However it's different for students cards. Students cards are only identified by album number,
* but each college have it's own sets of numbers, ergo, we can have 1234 album number in college
* A, B, C to Z.
*/
sealed class MpkCard(val clientId: Int, val cityCardId: Long?, val cardType: Type = Type.KKM) : Card() {
class Kkm(clientId: Int, cardId: Long) : MpkCard(clientId, cityCardId = cardId, cardType = Type.KKM) {
override fun toString(): String {
return "KKM #$cityCardId"
}
}
class Student(clientId: Int, cardType: Type) : MpkCard(clientId = clientId, cityCardId = null, cardType = cardType) {
init {
if (cardType == Type.KKM) {
throw IllegalArgumentException("For KKM cards use MpkCard.Kkm class")
}
}
override fun toString(): String {
return "$cardType #$clientId"
}
}
// TODO as soon as Kotlin 1.1 is released we can change above classes to data classes
// then solution below won't be needed anymore
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || other.javaClass != this.javaClass) return false
val kkm: Kkm = other as? Kkm ?: return false
if (clientId != kkm.clientId) return false
if (cityCardId != kkm.cityCardId) return false
if (cardType != kkm.cardType) return false
return true
}
override fun hashCode(): Int {
var result = cardType.hashCode()
result = 31 * result + clientId.hashCode()
if (cityCardId != null) {
result = 31 * result + cityCardId.hashCode()
}
return result
}
} | gpl-3.0 | 9fd9fb5e29fe0bc365f646e93f3c45b9 | 31.816667 | 121 | 0.623984 | 4.151899 | false | false | false | false |
actions-on-google/appactions-common-biis-kotlin | app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsViewModel.kt | 1 | 2308 | /*
* Copyright (C) 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.architecture.blueprints.todoapp.statistics
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Error
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import kotlinx.coroutines.launch
/**
* ViewModel for the statistics screen.
*/
class StatisticsViewModel(
private val tasksRepository: TasksRepository
) : ViewModel() {
private val tasks: LiveData<Result<List<Task>>> = tasksRepository.observeTasks()
private val _dataLoading = MutableLiveData(false)
private val stats: LiveData<StatsResult?> = tasks.map {
if (it is Success) {
getActiveAndCompletedStats(it.data)
} else {
null
}
}
val activeTasksPercent = stats.map {
it?.activeTasksPercent ?: 0f }
val completedTasksPercent: LiveData<Float> = stats.map { it?.completedTasksPercent ?: 0f }
val dataLoading: LiveData<Boolean> = _dataLoading
val error: LiveData<Boolean> = tasks.map { it is Error }
val empty: LiveData<Boolean> = tasks.map { (it as? Success)?.data.isNullOrEmpty() }
fun refresh() {
_dataLoading.value = true
viewModelScope.launch {
tasksRepository.refreshTasks()
_dataLoading.value = false
}
}
}
| apache-2.0 | 5d6b486b451ff1fa1fe507ef4914ea72 | 36.225806 | 94 | 0.733102 | 4.338346 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/action/GenerateAccessorHandler.kt | 1 | 20157 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.action
import com.demonwav.mcdev.asset.MCDevBundle
import com.demonwav.mcdev.asset.PlatformAssets
import com.demonwav.mcdev.platform.mixin.MixinModule
import com.demonwav.mcdev.platform.mixin.util.MixinConstants
import com.demonwav.mcdev.platform.mixin.util.isAccessorMixin
import com.demonwav.mcdev.platform.mixin.util.isMixin
import com.demonwav.mcdev.platform.mixin.util.mixinTargets
import com.demonwav.mcdev.util.capitalize
import com.demonwav.mcdev.util.findContainingClass
import com.demonwav.mcdev.util.findModule
import com.demonwav.mcdev.util.fullQualifiedName
import com.demonwav.mcdev.util.invokeDeclaredMethod
import com.demonwav.mcdev.util.invokeLater
import com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind
import com.intellij.codeInsight.generation.ClassMember
import com.intellij.codeInsight.generation.GenerateMembersHandlerBase
import com.intellij.codeInsight.generation.GenerationInfo
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.generation.PsiElementClassMember
import com.intellij.codeInsight.generation.PsiFieldMember
import com.intellij.codeInsight.generation.PsiMethodMember
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.intention.AddAnnotationFix
import com.intellij.codeInsight.intention.impl.CreateClassDialog
import com.intellij.ide.util.ChooseElementsDialog
import com.intellij.ide.util.EditorHelper
import com.intellij.ide.util.MemberChooser
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiField
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifier
import com.intellij.psi.PsiType
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.ui.components.JBCheckBox
import com.intellij.uiDesigner.core.GridConstraints
import com.intellij.uiDesigner.core.GridLayoutManager
import com.intellij.util.IncorrectOperationException
import java.awt.event.ItemEvent
import javax.swing.JComponent
import org.jetbrains.java.generate.exception.GenerateCodeException
class GenerateAccessorHandler : GenerateMembersHandlerBase("Generate Accessor/Invoker") {
private val log =
Logger.getInstance("#com.demonwav.mcdev.platform.mixin.action.GenerateAccessorHandler")
private var generateGetters = false
private var generateSetters = false
// Because "invoke" in the superclass is final, it cannot be overridden directly
fun customInvoke(
project: Project,
editor: Editor,
file: PsiFile
) {
val aClass = OverrideImplementUtil.getContextClass(project, editor, file, false)
if (aClass == null || aClass.isInterface) {
return // ?
}
log.assertTrue(aClass.isValid)
log.assertTrue(aClass.containingFile != null)
try {
val members = chooseOriginalMembers(aClass, project, editor) ?: return
val mixinClass = getOrCreateAccessorMixin(project, aClass) ?: return
val mixinEditor = EditorHelper.openInEditor(mixinClass)
if (!EditorModificationUtil.checkModificationAllowed(mixinEditor)) {
return
}
if (!FileDocumentManager.getInstance().requestWriting(mixinEditor.document, project)) {
return
}
CommandProcessor.getInstance().executeCommand(
project,
{
val offset = mixinEditor.caretModel.offset
try {
this.invokeDeclaredMethod(
"doGenerate",
params = arrayOf(
Project::class.java,
Editor::class.java,
PsiClass::class.java,
Array<ClassMember>::class.java
),
args = arrayOf(
project,
mixinEditor,
mixinClass,
members
),
owner = GenerateMembersHandlerBase::class.java
)
} catch (e: GenerateCodeException) {
val message = e.message ?: "Unknown error"
ApplicationManager.getApplication().invokeLater(
{
if (!mixinEditor.isDisposed) {
mixinEditor.caretModel.moveToOffset(offset)
HintManager.getInstance().showErrorHint(editor, message)
}
},
project.disposed
)
}
},
null,
null
)
} finally {
cleanup()
}
}
override fun hasMembers(aClass: PsiClass): Boolean {
if (aClass.isMixin) {
return false
}
if (aClass.fields.any { canHaveAccessor(it) }) {
return true
}
if (aClass.methods.any { canHaveInvoker(it) }) {
return true
}
return false
}
override fun getAllOriginalMembers(aClass: PsiClass?): Array<ClassMember> {
if (aClass == null) {
return ClassMember.EMPTY_ARRAY
}
val members = mutableListOf<ClassMember>()
members.addAll(
aClass.fields
.filter { canHaveAccessor(it) }
.map { PsiFieldMember(it) }
)
members.addAll(
aClass.methods
.filter { canHaveInvoker(it) }
.map { PsiMethodMember(it) }
)
return members.toTypedArray()
}
override fun chooseOriginalMembers(aClass: PsiClass?, project: Project?, editor: Editor?): Array<ClassMember>? {
project ?: return null
val offset = editor?.caretModel?.offset ?: return null
val element = aClass?.containingFile?.findElementAt(offset) ?: return null
val targetClass = element.findContainingClass() ?: return null
val candidates = getAllOriginalMembers(targetClass)
val headerPanel = HeaderPanel()
val chooser = MemberChooser(candidates, false, true, project, headerPanel, arrayOf())
chooser.selectElements(
candidates.filter { candidate ->
if (candidate !is PsiElementClassMember<*>) {
return@filter false
}
val range = candidate.element.textRange
return@filter range != null && range.contains(offset)
}.toTypedArray()
)
if (!chooser.showAndGet()) {
return null
}
val selectedMembers = chooser.selectedElements
if (selectedMembers.isNullOrEmpty()) {
return null
}
generateGetters = headerPanel.gettersCheckbox.isSelected
generateSetters = headerPanel.settersCheckbox.isSelected
return selectedMembers.toTypedArray()
}
private fun canHaveAccessor(field: PsiField): Boolean {
val isPublic = field.modifierList?.hasExplicitModifier(PsiModifier.PUBLIC) == true
val isFinal = field.modifierList?.hasExplicitModifier(PsiModifier.FINAL) == true
val isEnumConstant = field is PsiEnumConstant
return (!isPublic || isFinal) && !isEnumConstant
}
private fun canHaveInvoker(method: PsiMethod): Boolean {
return !method.modifierList.hasExplicitModifier(PsiModifier.PUBLIC)
}
private fun getOrCreateAccessorMixin(project: Project, targetClass: PsiClass): PsiClass? {
val targetInternalName = targetClass.fullQualifiedName?.replace('.', '/') ?: return null
val mixins = MixinModule.getAllMixinClasses(project, GlobalSearchScope.projectScope(project))
.asSequence()
.filter { it.isWritable }
.filter { it.isAccessorMixin }
.filter { it.mixinTargets.any { target -> target.name == targetInternalName } }
.toList()
return when (mixins.size) {
0 -> createAccessorMixin(project, targetClass)
1 -> mixins[0]
else -> chooseAccessorMixin(project, mixins)
}
}
private fun createAccessorMixin(project: Project, targetClass: PsiClass): PsiClass? {
val config = MixinModule
.getMixinConfigs(project, GlobalSearchScope.projectScope(project))
.maxByOrNull {
countAccessorMixins(project, it.qualifiedMixins) +
countAccessorMixins(project, it.qualifiedClient) +
countAccessorMixins(project, it.qualifiedServer)
}
if (config == null) {
// TODO: generate the mixin configuration file (modding platform dependent)
val message = "There is no matching Mixin configuration file found in the project. " +
"Please create one and try again."
Messages.showInfoMessage(project, message, "Generate Accessor/Invoker")
return null
}
val defaultPkg = config.pkg ?: ""
val defaultName = "${targetClass.name}Accessor"
val defaultModule = config.file?.let { ModuleUtil.findModuleForFile(it, project) }
val dialog = CreateClassDialog(
project,
"Create Accessor Mixin",
defaultName,
defaultPkg,
CreateClassKind.CLASS,
true,
defaultModule
)
if (!dialog.showAndGet()) {
return null
}
val pkg = dialog.targetDirectory ?: return null
val name = dialog.className
return WriteCommandAction.writeCommandAction(project)
.withName("Generate Accessor/Invoker")
.withGroupId("Generate Accessor/Invoker")
.compute<PsiClass, RuntimeException> {
IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace()
val clazz = try {
JavaDirectoryService.getInstance().createInterface(pkg, name)
} catch (e: IncorrectOperationException) {
invokeLater {
val message = MCDevBundle.message(
"intention.error.cannot.create.class.message",
name,
e.localizedMessage
)
Messages.showErrorDialog(
project,
message,
MCDevBundle.message("intention.error.cannot.create.class.title")
)
}
return@compute null
}
val factory = JavaPsiFacade.getElementFactory(project)
val targetAccessible = targetClass.modifierList?.hasExplicitModifier(PsiModifier.PUBLIC) == true &&
targetClass.name != null
val annotationText = if (targetAccessible) {
"@${MixinConstants.Annotations.MIXIN}(${targetClass.qualifiedName}.class)"
} else {
"@${MixinConstants.Annotations.MIXIN}(targets=\"${targetClass.fullQualifiedName}\")"
}
val annotation = factory.createAnnotationFromText(annotationText, clazz)
AddAnnotationFix(MixinConstants.Annotations.MIXIN, clazz, annotation.parameterList.attributes)
.applyFix()
val module = clazz.findModule() ?: return@compute null
val configToWrite = MixinModule.getBestWritableConfigForMixinClass(
project,
GlobalSearchScope.moduleScope(module),
clazz.fullQualifiedName ?: ""
)
configToWrite?.qualifiedMixins?.add(clazz.fullQualifiedName)
return@compute clazz
}
}
private fun countAccessorMixins(project: Project, names: List<String?>): Int {
return names.asSequence()
.filterNotNull()
.map { it.replace('$', '.') }
.distinct()
.flatMap {
JavaPsiFacade.getInstance(project).findClasses(it, GlobalSearchScope.projectScope(project)).asSequence()
}
.filter { it.isAccessorMixin }
.count()
}
private fun chooseAccessorMixin(project: Project, mixins: List<PsiClass>): PsiClass? {
val title = "Choose Accessor Mixin"
val description = "Select an Accessor Mixin to generate the accessor members in"
val chooser = object : ChooseElementsDialog<PsiClass>(project, mixins, title, description) {
init {
myChooser.setSingleSelectionMode()
}
override fun getItemIcon(item: PsiClass?) = PlatformAssets.MIXIN_ICON
override fun getItemText(item: PsiClass): String {
// keep adding packages from the full qualified name until our name is unique
@Suppress("DialogTitleCapitalization")
val parts = item.qualifiedName?.split(".") ?: return "null"
var name = ""
for (part in parts.asReversed()) {
name = if (name.isEmpty()) {
part
} else {
"$part.$name"
}
if (mixins.none { it !== item && it.qualifiedName?.endsWith(".$name") == true }) {
return name
}
}
return name
}
}
val result = chooser.showAndGetResult()
return if (result.size == 1) result[0] else null
}
override fun generateMemberPrototypes(aClass: PsiClass, originalMember: ClassMember): Array<GenerationInfo> {
return when (originalMember) {
is PsiFieldMember -> {
val accessors = generateAccessors(
aClass.project,
originalMember.element,
aClass,
generateGetters,
generateSetters
)
OverrideImplementUtil.convert2GenerationInfos(accessors).toTypedArray()
}
is PsiMethodMember -> {
val invoker = generateInvoker(
aClass.project,
originalMember.element,
aClass
) ?: return GenerationInfo.EMPTY_ARRAY
arrayOf(OverrideImplementUtil.createGenerationInfo(invoker))
}
else -> GenerationInfo.EMPTY_ARRAY
}
}
private fun generateAccessors(
project: Project,
target: PsiField,
mixin: PsiClass,
generateGetter: Boolean,
generateSetter: Boolean
): List<PsiMethod> {
val factory = JavaPsiFacade.getElementFactory(project)
val isStatic = target.modifierList?.hasExplicitModifier(PsiModifier.STATIC) == true
val accessors = arrayListOf<PsiMethod>()
if (generateGetter) {
val prefix = if (target.type == PsiType.BOOLEAN) "is" else "get"
val method = factory.createMethodFromText(
"""
@${MixinConstants.Annotations.ACCESSOR}
${staticPrefix(isStatic)}ReturnType $prefix${target.name.capitalize()}()${methodBody(isStatic)}
""".trimIndent(),
mixin
)
target.typeElement?.let { method.returnTypeElement?.replace(it) }
accessors.add(method)
}
if (generateSetter) {
val method = factory.createMethodFromText(
"@${MixinConstants.Annotations.ACCESSOR}\n" +
staticPrefix(isStatic) + "void set${target.name.capitalize()}" +
"(ParamType ${target.name})" + methodBody(isStatic),
mixin
)
target.typeElement?.let { method.parameterList.parameters[0].typeElement?.replace(it) }
if (target.modifierList?.hasExplicitModifier(PsiModifier.FINAL) == true) {
AddAnnotationFix(MixinConstants.Annotations.MUTABLE, method).applyFix()
}
accessors.add(method)
}
return accessors
}
private fun generateInvoker(project: Project, target: PsiMethod, mixin: PsiClass): PsiMethod? {
val factory = JavaPsiFacade.getElementFactory(project)
val isStatic = target.modifierList.hasExplicitModifier(PsiModifier.STATIC) || target.isConstructor
val name = if (target.isConstructor) {
"create${target.containingClass?.name?.capitalize()}"
} else {
"call${target.name.capitalize()}"
}
val invokerParams = if (target.isConstructor) {
"(\"<init>\")"
} else {
""
}
val method = factory.createMethodFromText(
"""
@${MixinConstants.Annotations.INVOKER}$invokerParams
${staticPrefix(isStatic)}ReturnType $name()${methodBody(isStatic)}
""".trimIndent(),
mixin
)
if (target.isConstructor) {
val targetClass = target.containingClass ?: return null
method.returnTypeElement?.replace(factory.createTypeElement(factory.createType(targetClass)))
} else {
target.returnTypeElement?.let { method.returnTypeElement?.replace(it) }
}
method.parameterList.replace(target.parameterList)
method.throwsList.replace(target.throwsList)
return method
}
private fun staticPrefix(isStatic: Boolean): String {
return if (isStatic) {
"static "
} else {
""
}
}
private fun methodBody(isStatic: Boolean): String {
return if (isStatic) {
" { throw new java.lang.UnsupportedOperationException(); }"
} else {
";"
}
}
private class HeaderPanel : JComponent() {
val gettersCheckbox = JBCheckBox("Generate getter accessors")
val settersCheckbox = JBCheckBox("Generate setter accessors")
init {
gettersCheckbox.isSelected = true
gettersCheckbox.addItemListener {
if (it.stateChange == ItemEvent.DESELECTED) {
settersCheckbox.isSelected = true
}
}
settersCheckbox.addItemListener {
if (it.stateChange == ItemEvent.DESELECTED) {
gettersCheckbox.isSelected = true
}
}
layout = GridLayoutManager(2, 1)
add(gettersCheckbox, createConstraints(0))
add(settersCheckbox, createConstraints(1))
}
private fun createConstraints(row: Int): GridConstraints {
val constraints = GridConstraints()
constraints.anchor = GridConstraints.ANCHOR_WEST
constraints.row = row
return constraints
}
}
}
| mit | 3ce85b66cc2310fb425d2268b1fd4c3d | 38.601179 | 120 | 0.594682 | 5.531559 | false | false | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/platform/mixin/inspection/reference/InvalidMemberReferenceInspection.kt | 1 | 2888 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.inspection.reference
import com.demonwav.mcdev.platform.mixin.inspection.MixinInspection
import com.demonwav.mcdev.platform.mixin.reference.MethodReference
import com.demonwav.mcdev.platform.mixin.reference.MixinReference
import com.demonwav.mcdev.platform.mixin.reference.isMiscDynamicSelector
import com.demonwav.mcdev.platform.mixin.reference.parseMixinSelector
import com.demonwav.mcdev.platform.mixin.reference.target.TargetReference
import com.demonwav.mcdev.util.annotationFromNameValuePair
import com.demonwav.mcdev.util.constantStringValue
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.JavaElementVisitor
import com.intellij.psi.PsiArrayInitializerMemberValue
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiLiteral
import com.intellij.psi.PsiNameValuePair
class InvalidMemberReferenceInspection : MixinInspection() {
override fun getStaticDescription() =
"""
|Reports invalid usages of member references in Mixin annotations. Two different formats are supported by Mixin:
| - Lcom/example/ExampleClass;execute(II)V
| - com.example.ExampleClass.execute(II)V
""".trimMargin()
override fun buildVisitor(holder: ProblemsHolder): PsiElementVisitor = Visitor(holder)
private class Visitor(private val holder: ProblemsHolder) : JavaElementVisitor() {
override fun visitNameValuePair(pair: PsiNameValuePair) {
val name = pair.name ?: return
val resolver: MixinReference = when (name) {
"method" -> MethodReference
"target" -> TargetReference
else -> return
}
// Check if valid annotation
val qualifiedName = pair.annotationFromNameValuePair?.qualifiedName ?: return
if (!resolver.isValidAnnotation(qualifiedName, pair.project)) {
return
}
val value = pair.value ?: return
// Attempt to parse the reference
when (value) {
is PsiLiteral -> checkMemberReference(value, value.constantStringValue)
is PsiArrayInitializerMemberValue -> value.initializers.forEach {
checkMemberReference(it, it.constantStringValue)
}
}
}
private fun checkMemberReference(element: PsiElement, value: String?) {
val validSelector = value != null &&
(parseMixinSelector(value, element) != null || isMiscDynamicSelector(element.project, value))
if (!validSelector) {
holder.registerProblem(element, "Invalid member reference")
}
}
}
}
| mit | 9b1e05bf78506aaeccaa657f1166937f | 37 | 120 | 0.692175 | 5.102473 | false | false | false | false |
ironjan/MensaUPB | app/src/main/kotlin/de/ironjan/mensaupb/api/model/Menu.kt | 1 | 4627 | package de.ironjan.mensaupb.api.model
import android.os.Parcel
import android.os.Parcelable
import android.os.Parcelable.Creator
import com.github.kittinunf.fuel.core.ResponseDeserializable
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import java.io.Reader
data class Menu(val date: String,
val name_de: String,
val name_en: String,
val description_de: String,
val description_en: String,
val category: String,
val category_de: String,
val category_en: String,
val subcategory_de: String,
val subcategory_en: String,
val priceStudents: Double,
val priceWorkers: Double,
val priceGuests: Double,
val allergens: Array<String>,
val order_info: Int,
val badges: Array<String>,
val restaurant: String,
val pricetype: String,
val image: String,
val key: String)
:Parcelable {
val isWeighted: Boolean
get() = "weighted" == pricetype
val price: Double
get() = priceStudents
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readDouble(),
parcel.readDouble(),
parcel.readDouble(),
parcel.createStringArray(),
parcel.readInt(),
parcel.createStringArray(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString()) {
}
fun localizedName(isEnglish: Boolean) = if(isEnglish) name_en else name_de
fun localizedDescription(isEnglish: Boolean) = if(isEnglish) description_en else description_de
fun localizedCategory(isEnglish: Boolean) = if(isEnglish) category_en else category_de
fun localizedSubCategory(isEnglish: Boolean) = if(isEnglish) subcategory_en else subcategory_de
class Deserializer : ResponseDeserializable<Menu> {
val customDateFormatGson = GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm")
.create()
override fun deserialize(reader: Reader): Menu {
return customDateFormatGson
.fromJson(reader, Menu::class.java)!!
}
override fun deserialize(content: String): Menu {
return customDateFormatGson.fromJson(content, Menu::class.java)!!
}
}
class ArrayDeserializer : ResponseDeserializable<Array<Menu>> {
val customDateFormatGson = GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm")
.create()
override fun deserialize(reader: Reader): Array<Menu>? {
val type = object : TypeToken<Array<Menu>>() {}.type
return customDateFormatGson.fromJson(reader, type)
}
override fun deserialize(content: String): Array<Menu>? {
val type = object : TypeToken<Array<Menu>>() {}.type
return customDateFormatGson.fromJson(content, type)
}
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(date)
parcel.writeString(name_de)
parcel.writeString(name_en)
parcel.writeString(description_de)
parcel.writeString(description_en)
parcel.writeString(category)
parcel.writeString(category_de)
parcel.writeString(category_en)
parcel.writeString(subcategory_de)
parcel.writeString(subcategory_en)
parcel.writeDouble(priceStudents)
parcel.writeDouble(priceWorkers)
parcel.writeDouble(priceGuests)
parcel.writeStringArray(allergens)
parcel.writeInt(order_info)
parcel.writeStringArray(badges)
parcel.writeString(restaurant)
parcel.writeString(pricetype)
parcel.writeString(image)
parcel.writeString(key)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Creator<Menu> {
override fun createFromParcel(parcel: Parcel): Menu {
return Menu(parcel)
}
override fun newArray(size: Int): Array<Menu?> {
return arrayOfNulls(size)
}
}
} | apache-2.0 | 596f1eb83f234320a42f09d2f0107846 | 33.796992 | 99 | 0.599957 | 4.896296 | false | true | false | false |
felipebz/sonar-plsql | zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/NotASelectedExpressionCheck.kt | 1 | 3507 | /**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plsqlopen.checks
import com.felipebz.flr.api.AstNode
import org.sonar.plsqlopen.typeIs
import org.sonar.plugins.plsqlopen.api.DmlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlGrammar
import org.sonar.plugins.plsqlopen.api.PlSqlKeyword
import org.sonar.plugins.plsqlopen.api.annotations.*
@Rule(priority = Priority.CRITICAL, tags = [Tags.BUG])
@ConstantRemediation("5min")
@RuleInfo(scope = RuleInfo.Scope.ALL)
@ActivatedByDefault
class NotASelectedExpressionCheck : AbstractBaseCheck() {
override fun init() {
subscribeTo(DmlGrammar.SELECT_EXPRESSION)
}
override fun visitNode(node: AstNode) {
val firstQueryBlock = node.getFirstChild(DmlGrammar.QUERY_BLOCK)
if (!firstQueryBlock.children[1].typeIs(PlSqlKeyword.DISTINCT) || !node.hasDirectChildren(DmlGrammar.ORDER_BY_CLAUSE)) {
return
}
val columns = firstQueryBlock.getChildren(DmlGrammar.SELECT_COLUMN)
val orderByItems = node.getFirstChild(DmlGrammar.ORDER_BY_CLAUSE).getChildren(DmlGrammar.ORDER_BY_ITEM)
for (orderByItem in orderByItems) {
checkOrderByItem(orderByItem, columns)
}
}
private fun checkOrderByItem(orderByItem: AstNode, columns: List<AstNode>) {
val orderByItemValue = skipVariableName(orderByItem.firstChild)
if (orderByItemValue.typeIs(PlSqlGrammar.LITERAL)) {
return
}
var found = false
for (column in columns) {
val candidates = extractAcceptableValuesFromColumn(column)
for (candidate in candidates) {
if (CheckUtils.containsNode(candidate, orderByItemValue)) {
found = true
}
}
}
if (!found) {
addIssue(orderByItemValue, getLocalizedMessage())
}
}
private fun skipVariableName(node: AstNode): AstNode {
return if (node.typeIs(PlSqlGrammar.VARIABLE_NAME)) {
node.firstChild
} else node
}
private fun extractAcceptableValuesFromColumn(column: AstNode): List<AstNode> {
val values = ArrayList<AstNode>()
val selectedExpression = skipVariableName(column.firstChild)
values.add(selectedExpression)
// if the value is "table.column", "column" can be used in order by
if (selectedExpression.typeIs(PlSqlGrammar.MEMBER_EXPRESSION)) {
values.add(selectedExpression.lastChild)
}
if (column.numberOfChildren > 1) {
val alias = skipVariableName(column.lastChild)
values.add(alias)
}
return values
}
}
| lgpl-3.0 | e0ae22da2075f7dfe4551e6183bdba3f | 33.722772 | 128 | 0.684346 | 4.507712 | false | false | false | false |
BloodWorkXGaming/ExNihiloCreatio | src/main/java/exnihilocreatio/compatibility/crafttweaker/Hammer.kt | 1 | 1822 | package exnihilocreatio.compatibility.crafttweaker
import crafttweaker.IAction
import crafttweaker.annotations.ZenRegister
import crafttweaker.api.item.IIngredient
import crafttweaker.api.item.IItemStack
import crafttweaker.api.minecraft.CraftTweakerMC
import exnihilocreatio.compatibility.crafttweaker.prefab.ENCRemoveAll
import exnihilocreatio.registries.manager.ExNihiloRegistryManager
import exnihilocreatio.registries.types.HammerReward
import net.minecraft.item.ItemStack
import net.minecraft.item.crafting.Ingredient
import stanhebben.zenscript.annotations.ZenClass
import stanhebben.zenscript.annotations.ZenMethod
@ZenClass("mods.exnihilocreatio.Hammer")
@ZenRegister
object Hammer {
@ZenMethod
@JvmStatic
fun removeAll() {
CrTIntegration.removeActions += ENCRemoveAll(ExNihiloRegistryManager.HAMMER_REGISTRY, "Hammer")
}
@ZenMethod
@JvmStatic
fun addRecipe(block: IIngredient, drop: IItemStack, miningLevel: Int, chance: Float, fortuneChance: Float) {
CrTIntegration.addActions += AddRecipe(block, drop, miningLevel, chance, fortuneChance)
}
private class AddRecipe(
block: IIngredient,
private val drop: IItemStack,
private val miningLevel: Int,
private val chance: Float,
private val fortuneChance: Float
) : IAction {
private val input: Ingredient = CraftTweakerMC.getIngredient(block)
override fun apply() {
ExNihiloRegistryManager.HAMMER_REGISTRY.register(input, HammerReward(drop.internal as ItemStack, miningLevel, chance, fortuneChance))
}
override fun describe() = "Adding Hammer recipe for ${input.matchingStacks.joinToString(prefix = "[", postfix = "]")} with drop $drop at a chance of $chance with mining level $miningLevel"
}
}
| mit | 5e124ca987e487c5ffe56d50625129e5 | 37.765957 | 196 | 0.75247 | 4.43309 | false | false | false | false |
jdiazcano/modulartd | editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/lists/MapObjectList.kt | 1 | 1780 | package com.jdiazcano.modulartd.ui.widgets.lists
import com.jdiazcano.modulartd.beans.MapObject
import com.jdiazcano.modulartd.beans.Resource
import com.jdiazcano.modulartd.bus.Bus
import com.jdiazcano.modulartd.bus.BusTopic
import com.jdiazcano.modulartd.ui.MapObjectView
import com.jdiazcano.modulartd.ui.widgets.TableList
import com.jdiazcano.modulartd.utils.clickListener
import mu.KLogging
class MapObjectList<T: MapObject>(objects: MutableList<T>, clazz: Class<T>): TableList<T, MapObjectView>(objects) {
companion object: KLogging()
init {
Bus.register<T>(clazz, BusTopic.CREATED) {
addItem(it)
logger.debug { "Added ${clazz.simpleName}: ${it.name}" }
}
Bus.register<kotlin.Unit>(clazz, BusTopic.RESET) {
clearList()
logger.debug { "Cleared list of: ${clazz.simpleName}" }
}
Bus.register<T>(clazz, BusTopic.DELETED) {
removeItem(it)
}
Bus.register<Resource>(BusTopic.LOAD_FINISHED) {
invalidateList()
}
Bus.register<T>(clazz, BusTopic.UPDATED) {
invalidateList()
}
}
override fun getView(position: Int, lastView: MapObjectView?): MapObjectView {
val item = getItem(position)
val view = if (lastView == null) {
val objectView = MapObjectView(item)
objectView.clickListener { _, _, _ ->
Bus.post(getItem(position), BusTopic.SELECTED)
}
objectView
} else {
lastView
}
view.image.swapResource(item.resource)
view.image.spriteTimer = item.animationTimer
view.rotation = item.rotationAngle
view.labelName.setText(item.name)
return view
}
} | apache-2.0 | bca9adb7397d2f8fd1cc24112c2c22c7 | 30.803571 | 115 | 0.630337 | 4.228029 | false | false | false | false |
Heiner1/AndroidAPS | omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/history/mapper/HistoryMapper.kt | 1 | 778 | package info.nightscout.androidaps.plugins.pump.omnipod.dash.history.mapper
import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.HistoryRecord
import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.database.HistoryRecordEntity
class HistoryMapper {
fun entityToDomain(entity: HistoryRecordEntity): HistoryRecord =
HistoryRecord(
id = entity.id,
createdAt = entity.createdAt,
date = entity.date,
initialResult = entity.initialResult,
commandType = entity.commandType,
record = entity.bolusRecord ?: entity.tempBasalRecord ?: entity.basalProfileRecord,
resolvedResult = entity.resolvedResult,
resolvedAt = entity.resolvedAt
)
}
| agpl-3.0 | a0f9906b09eb1982b9ca40c3a7587eae | 39.947368 | 96 | 0.706941 | 4.715152 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/lw.kt | 1 | 252 | package venus.riscv.insts
import venus.riscv.insts.dsl.LoadTypeInstruction
import venus.simulator.Simulator
val lw = LoadTypeInstruction(
name = "lw",
opcode = 0b0000011,
funct3 = 0b010,
load32 = Simulator::loadWord
)
| mit | d7e87b8c574e14c290e3a68edc14608e | 21.909091 | 48 | 0.686508 | 3.761194 | false | false | false | false |
sjnyag/stamp | app/src/main/java/com/sjn/stamp/utils/LocalPlaylistHelper.kt | 1 | 7378 | package com.sjn.stamp.utils
import android.content.ContentResolver
import android.content.ContentValues
import android.database.Cursor
import android.net.Uri
import android.provider.MediaStore
import android.support.v4.media.MediaMetadataCompat
import java.util.*
object LocalPlaylistHelper {
private val PLAYLIST_URI = MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI
private val COUNT_PROJECTION = arrayOf("count(*)")
private val MEDIA_PROJECTION = arrayOf(MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TRACK, MediaStore.Audio.Media.SIZE, MediaStore.Audio.Playlists.Members.AUDIO_ID, MediaStore.Audio.Media.ALBUM_ID, MediaStore.Audio.Media.DISPLAY_NAME)
private val PLAYLIST_PROJECTION = arrayOf(MediaStore.Audio.Playlists._ID, MediaStore.Audio.Playlists.NAME)
private const val PLAYLIST_ORDER = MediaStore.Audio.Playlists.DEFAULT_SORT_ORDER
private const val MEDIA_ORDER = MediaStore.Audio.Playlists.Members.PLAY_ORDER + " DESC"
fun isExistAudioId(resolver: ContentResolver, audioId: Int, playlistId: Int): Boolean {
findAllMediaCursor(resolver, playlistId).use {
if (it?.moveToFirst() == true) {
do {
if (audioId.toString() == it.getString(7)) {
return true
}
} while (it.moveToNext())
}
}
return false
}
fun isExistPlayListName(resolver: ContentResolver, name: String?): Boolean {
return name != null && name.isNotEmpty() && findPlaylistId(resolver, name) >= 0
}
fun findPlaylistId(resolver: ContentResolver, name: String): Int {
var id = -1
findPlaylistByNameCursor(resolver, name).use {
if (it?.moveToFirst() == true) {
if (!it.isAfterLast) {
id = it.getInt(0)
}
}
}
return id
}
fun findPlaylistName(resolver: ContentResolver, playlistId: Int): String {
var name = ""
findPlaylistByIdCursor(resolver, playlistId).use {
if (it?.moveToFirst() == true) {
if (!it.isAfterLast) {
name = it.getString(1)
}
}
}
return name
}
fun findAllPlaylistMedia(resolver: ContentResolver, playlistId: Int, playlistTitle: String): MutableList<MediaMetadataCompat> {
val mediaList = ArrayList<MediaMetadataCompat>()
findAllMediaCursor(resolver, playlistId).use {
if (it?.moveToFirst() == true) {
do {
mediaList.add(parseCursor(it, playlistTitle))
} while (it.moveToNext())
}
}
return mediaList
}
fun findAllPlaylist(resolver: ContentResolver, playlistMap: MutableMap<String, MutableList<MediaMetadataCompat>>) {
findAllPlaylistCursor(resolver).use {
if (it?.moveToFirst() == true) {
do {
playlistMap[it.getString(1)] = findAllPlaylistMedia(resolver, it.getInt(0), it.getString(1))
} while (it.moveToNext())
}
}
}
fun create(resolver: ContentResolver, name: String): Boolean {
if (!isExistPlayListName(resolver, name)) {
return false
}
return resolver.insert(PLAYLIST_URI, ContentValues(1).apply { put(MediaStore.Audio.Playlists.NAME, name) }) != null
}
fun update(resolver: ContentResolver, srcValue: String, dstValue: String): Int {
if (!isExistPlayListName(resolver, srcValue)) {
return -1
}
return resolver.update(PLAYLIST_URI, ContentValues(1).apply { put(MediaStore.Audio.Playlists.NAME, dstValue) }, wherePlayList(resolver, srcValue), null)
}
fun delete(resolver: ContentResolver, name: String): Int {
return if (!isExistPlayListName(resolver, name)) {
-1
} else resolver.delete(PLAYLIST_URI, wherePlayList(resolver, name), null)
}
//FIXME: delete duplication check
//borrowed from http://stackoverflow.com/questions/3182937
fun add(resolver: ContentResolver, audioId: Int, playlistId: Int): Boolean {
if (isExistAudioId(resolver, audioId, playlistId)) {
return false
}
val uri = createPlaylistUrl(playlistId)
return resolver.insert(uri, ContentValues().apply {
put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, count(resolver, uri) + audioId)
put(MediaStore.Audio.Playlists.Members.AUDIO_ID, audioId)
}) != null
}
//FIXME: all of same medias are removed
fun remove(resolver: ContentResolver, audioId: Int, playlistId: Int): Boolean {
if (isExistAudioId(resolver, audioId, playlistId)) {
return false
}
return 0 < resolver.delete(createPlaylistUrl(playlistId), MediaStore.Audio.Playlists.Members.AUDIO_ID + " = " + audioId, null)
}
private fun count(resolver: ContentResolver, uri: Uri): Int {
resolver.query(uri, COUNT_PROJECTION, null, null, null).use {
if (it?.moveToFirst() == true) {
return it.getInt(0)
}
}
return 0
}
private fun findPlaylistByIdCursor(resolver: ContentResolver, playlistId: Int): Cursor? {
return resolver.query(
PLAYLIST_URI,
PLAYLIST_PROJECTION, MediaStore.Audio.Playlists._ID + "= ?", arrayOf(playlistId.toString()), PLAYLIST_ORDER)
}
private fun findPlaylistByNameCursor(resolver: ContentResolver, name: String): Cursor? {
return resolver.query(
PLAYLIST_URI,
PLAYLIST_PROJECTION, MediaStore.Audio.Playlists.NAME + "= ?", arrayOf(name), PLAYLIST_ORDER)
}
private fun findAllPlaylistCursor(resolver: ContentResolver): Cursor? {
return resolver.query(
PLAYLIST_URI,
PLAYLIST_PROJECTION, null, null, PLAYLIST_ORDER)
}
private fun findAllMediaCursor(resolver: ContentResolver, playlistId: Int): Cursor? {
return resolver.query(
createPlaylistUrl(playlistId),
MEDIA_PROJECTION, null, null, MEDIA_ORDER)
}
private fun parseCursor(cursor: Cursor, playlistTitle: String): MediaMetadataCompat {
val title = cursor.getString(0)
val artist = cursor.getString(1)
val album = cursor.getString(2)
val duration = cursor.getLong(3)
val source = cursor.getString(4)
val trackNumber = cursor.getInt(5)
val totalTrackCount = cursor.getLong(6)
val musicId = cursor.getString(7)
val albumId = cursor.getLong(8)
return MediaItemHelper.createMetadata(musicId, source, album, artist, playlistTitle, duration, MediaRetrieveHelper.makeAlbumArtUri(albumId).toString(), title, trackNumber.toLong(), totalTrackCount, null)
}
private fun createPlaylistUrl(playlistId: Int): Uri {
return MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId.toLong())
}
private fun wherePlayList(resolver: ContentResolver, playlistName: String): String {
return MediaStore.Audio.Playlists._ID + " = " + findPlaylistId(resolver, playlistName)
}
} | apache-2.0 | 85bb0d75f7749cdf7307f862a73d2d37 | 40.223464 | 369 | 0.638113 | 4.545903 | false | false | false | false |
k9mail/k-9 | app/k9mail/src/main/java/com/fsck/k9/widget/unread/KoinModule.kt | 2 | 705 | package com.fsck.k9.widget.unread
import org.koin.dsl.module
val unreadWidgetModule = module {
single { UnreadWidgetRepository(context = get(), dataRetriever = get(), migrations = get()) }
single {
UnreadWidgetDataProvider(
context = get(),
preferences = get(),
messagingController = get(),
defaultFolderProvider = get(),
folderRepository = get(),
folderNameFormatterFactory = get()
)
}
single { UnreadWidgetUpdater(context = get()) }
single { UnreadWidgetUpdateListener(unreadWidgetUpdater = get()) }
single { UnreadWidgetMigrations(accountRepository = get(), folderRepository = get()) }
}
| apache-2.0 | b5c7ecd652fcdf565084f5b48af0dc78 | 34.25 | 97 | 0.635461 | 5 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/testutil/AssertVariableOrdering.kt | 1 | 18907 | /*
* Copyright 2021 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.testutil
/**
* Asserts that a list of values matches a given structure of sequences and groups.
*
* Sequences indicate a causal ordering between values. They do not require that the values
* follow each other immmediately. Parallel sequences are evaluated independently, so they may
* be interleaved with each other (and other unrelated values) in the [actual] list:
*
* actual: A1, B1, B2, x, C1, A2, y, C2 // unmatched values in lower case for clarity
*
* sequence(A1, A2) }
* sequence(B1, B2) } all three sequences will be satisfied
* sequence(C1, C2) }
*
* Groups match the given values in any order, also without requiring adjacency. Parallel groups
* may be interleaved in the same way as sequences:
*
* actual: A, B, c, D, E, F, g, H, I, J, K
*
* group(F, B, D, H) }
* group(E, I) } all three groups will be satisfied
* group(J, K, A) }
*
* Both structures may be arbitrarily nested. Nesting under a sequence indicates causal ordering
* of the contained constraints. Nesting under a group simply groups the contained constraints
* again; this is primarily useful for further sequencing.
*
* actual: g, X, f, Y, p, S, R, z, Q, B1, A1, A2, m, B2, w, K, J
*
* sequence(
* sequence(X, Y), // X->Y must occur first
* group(Q, R, S), // followed by Q, R and S in any order
* group( // then A1->A2 and B1->B2, which may be interleaved
* sequence(A1, A2),
* sequence(B1, B2)
* ),
* group(J, K), // finally J and K must be after both A2 and B2
* )
*
* If more than one item is provided in [constraints] they are implicitly considered a sequence.
* If parallel evaluation is required, wrap the list in an outer group.
*
* By default, all values in [actual] must be matched by a constraint. This can be relaxed by
* setting [allowUnmatched] to true.
*
* [Constraint] objects can be reused, within and across invocations of assertVariableOrdering.
*/
fun <T> assertVariableOrdering(
actual: List<T>,
vararg constraints: Constraint<T>,
allowUnmatched: Boolean = false
) {
// Run top-level constraints in sequence; fail immediately if any do not succeed.
val topLevel = if (constraints.size == 1) {
constraints[0]
} else {
Constraint.NestSequence(constraints.toList())
}
val report = topLevel.process(ResultList(actual.map { Result<T>(it) }))
if (report !is Report.Success) {
throw report.toException()
}
// Unless otherwise directed, fail when any values were not matched by at least one constraint.
if (!allowUnmatched) {
val unmatched = Report.checkUnmatched(report.matches)
if (unmatched !is Report.Success) {
throw unmatched.toException()
}
}
}
/** Helpers for constructing value/nested sequences/groups. */
fun <T> single(value: T) = Constraint.SingleValue(value)
fun <T> sequence(vararg values: T) = Constraint.ValueSequence(values.toList())
fun <T> sequence(values: Iterable<T>) = Constraint.ValueSequence(values.toList())
fun <T> sequence(vararg constraints: Constraint<T>) = Constraint.NestSequence(constraints.toList())
fun <T> sequence(constraints: Iterable<Constraint<T>>) =
Constraint.NestSequence(constraints.toList())
fun <T> group(vararg values: T) = Constraint.ValueGroup(values.toList())
fun <T> group(values: Iterable<T>) = Constraint.ValueGroup(values.toList())
fun <T> group(vararg constraints: Constraint<T>) = Constraint.NestGroup(constraints.toList())
fun <T> group(constraints: Iterable<Constraint<T>>) = Constraint.NestGroup(constraints.toList())
/** Holds the overall results of a call to [assertVariableOrdering]. */
class ResultList<T>(private val items: List<Result<T>>) : List<Result<T>> by items {
fun deepCopy() = ResultList(items.map { it.copy() })
}
/** Holds the result of a [Constraint] match against a single value. */
data class Result<T>(
val value: T,
/** The constraint that matched or failed on [value]. */
var constraint: Constraint<T>? = null,
/** Index of [value] in [constraint]. */
var constraintIndex: Int = -1,
/** Index in the 'actual' list at which [value] was matched or failed to match. */
var actualIndex: Int = -1
) {
fun showIndexed() = constraint?.showIndexed(constraintIndex) ?: ""
}
/** Represents a sequence or group constraint for value type [T]. */
sealed class Constraint<T> {
/** The highest index in the input list successfully matched by this constraint. */
var maxIndex = -1
/**
* A set of the values held by this constraint. For nested constraints, this is the combined set
* of all the contained value constraints. Used to reduce processing for [NestGroup] permutations.
*/
abstract val valueSet: Set<T>
/**
* Evaluates this constraint against the input list provided to [assertVariableOrdering], starting
* at the [from] index. Returns null on success or a [Report] containing details of the match
* failure.
*
* If [failFast] is true, constraints will return an empty error report as soon as a failure is
* encountered (instead of attempting to match as much as possible of a failed constraint).
* This is used to reduce processing for [NestGroup] permutations.
*/
abstract fun process(matches: ResultList<T>, from: Int = 0, failFast: Boolean = false): Report<T>
/**
* For value-based constraints, shows the list of expected values with a specific one
* highlighted: `seq(a, b, >c<, d)`. Unused for nested constraints.
*/
open fun showIndexed(i: Int): String = ""
/** Represents a causally-ordered sequence of values. */
open class ValueSequence<T>(val values: List<T>) : Constraint<T>() {
open val label: String = "sequence"
override val valueSet by lazy { values.toSet() }
override fun process(matches: ResultList<T>, from: Int, failFast: Boolean): Report<T> {
val newMatches = matches.deepCopy()
var varFrom = from
val unmatched = mutableListOf<Result<T>>()
values.forEachIndexed { ci, value ->
val ai = search(newMatches, value, varFrom)
if (ai != -1) {
newMatches[ai].let {
it.constraint = this
it.constraintIndex = ci
it.actualIndex = ai
}
varFrom = ai + 1
maxIndex = ai
} else if (failFast) {
return Report.FastFailure()
} else {
unmatched.add(Result(value, this, ci, varFrom))
}
}
return if (unmatched.isEmpty()) {
Report.Success(newMatches)
} else {
Report.MatchFailure(label, newMatches, unmatched)
}
}
override fun showIndexed(i: Int) = "seq(${showIndexed(values, i)})"
override fun toString() = "seq(${values.joinToString(", ")})"
}
/** Single values are just a sequence of 1, but display failures with better labels. */
class SingleValue<T>(value: T) : ValueSequence<T>(listOf(value)) {
override val label = "single"
override val valueSet = setOf(value)
override fun showIndexed(i: Int) = "sng(${values.first()})"
}
/** Represents an unordered group of values. */
class ValueGroup<T>(val values: List<T>) : Constraint<T>() {
override val valueSet by lazy { values.toSet() }
override fun process(matches: ResultList<T>, from: Int, failFast: Boolean): Report<T> {
val newMatches = matches.deepCopy()
val unmatched = mutableListOf<Result<T>>()
maxIndex = -1
values.forEachIndexed { ci, value ->
val ai = search(newMatches, value, from)
if (ai != -1) {
newMatches[ai].let {
it.constraint = this
it.constraintIndex = ci
it.actualIndex = ai
}
maxIndex = Math.max(ai, maxIndex)
} else if (failFast) {
return Report.FastFailure()
} else {
unmatched.add(Result(value, this, ci, 0))
}
}
return if (unmatched.isEmpty()) {
Report.Success(newMatches)
} else {
unmatched.forEach { it.actualIndex = Math.max(maxIndex + 1, from) }
Report.MatchFailure("group", newMatches, unmatched)
}
}
override fun showIndexed(i: Int) = "grp(${showIndexed(values, i)})"
override fun toString() = "grp(${values.joinToString(", ")})"
}
/** Represents a causally-ordered sequence of constraints. */
class NestSequence<T>(val constraints: List<Constraint<T>>) : Constraint<T>() {
override val valueSet by lazy {
mutableSetOf<T>().also { s -> constraints.forEach { s.addAll(it.valueSet) } }
}
override fun process(matches: ResultList<T>, from: Int, failFast: Boolean): Report<T> {
var varMatches = matches
var varFrom = from
for (c in constraints) {
val report = c.process(varMatches, varFrom, failFast)
if (report !is Report.Success) {
return report
}
varMatches = report.matches
varFrom = c.maxIndex + 1
maxIndex = c.maxIndex
}
return Report.Success(varMatches)
}
override fun toString() = "seq(${constraints.joinToString(", ")})"
}
/**
* Represents an unordered group of constraints.
*
* Processing a nested group is a bit complicated. It's possible that the given order of
* constraints will fail against the input, but a different order will work. For example, an
* input of [A,X,A,Y] against grp(seq(A,Y), seq(A,X)) will match the first A and the Y, leaving
* [X,A] to fail against the second sequence. Swapping the two sequences will work, and more
* generally we need to look at the full set of permutations over the nested constraints.
*
* However, simply brute forcing all permutations quickly hits performance problems. This can be
* mitigated by only permuting the set of constraints that share values, and separately running
* the rest in sequence (order won't matter). For example, given the following nested group:
*
* grp(seq(A,B), grp(B,D), seq(K,L), seq(A,C), grp(M,N))
* 1 2 3 4 5
*
* we want to test 3 and 5 in a single sequential pass and 1, 2, 4 via permutation.
*
* It is still possible for there to be enough constraints with common values to hit a factorial
* explosion. To guard against this, [process] will throw a RuntimeException after an arbitrary
* large number of attempts.
*/
class NestGroup<T>(val constraints: List<Constraint<T>>) : Constraint<T>() {
override val valueSet by lazy {
mutableSetOf<T>().also { s -> constraints.forEach { s.addAll(it.valueSet) } }
}
private var safetyLimit = 0
// Finds the set of "overlapping" constraints that have any common values.
private val toPermute: Set<Constraint<T>> by lazy {
// Build a map of value to constraint.
val valuesToConstraints = mutableMapOf<T, MutableList<Constraint<T>>>()
for (c in constraints) {
for (value in c.valueSet) {
val list = valuesToConstraints.getOrDefault(value, mutableListOf())
list.add(c)
valuesToConstraints[value] = list
}
}
// Collect the constraints from all values that map to more than one constraint.
mutableSetOf<Constraint<T>>().also {
for (list in valuesToConstraints.values) {
if (list.size > 1) {
it.addAll(list)
}
}
}
}
// Finds the set of "non-overlapping" constraints that do not have any common values.
private val noPermute: Set<Constraint<T>> by lazy { constraints.toSet() - toPermute }
override fun process(matches: ResultList<T>, from: Int, failFast: Boolean): Report<T> {
maxIndex = -1
safetyLimit = 0
// First check that all the overlapping constraints can be satisfied individually against
// the initial [matches] state to quickly catch errors where one contains a value that
// simply isn't in the input.
for (c in toPermute) {
val report = c.process(matches, from, failFast)
if (report !is Report.Success) {
return report
}
}
// Now run the non-overlapping constraints as a single sequential pass.
var varMatches = matches
for (c in noPermute) {
val report = c.process(varMatches, from, failFast)
if (report !is Report.Success) {
return report
}
varMatches = report.matches
maxIndex = Math.max(c.maxIndex, maxIndex)
}
// Finally explore permutations of the overlapping constraints. This will call [process]
// with failFast on to disable the generation of error reports.
val report = runPermutations(toPermute.toMutableList(), varMatches, from)
if (report is Report.Success || failFast) {
return report
}
// No luck. Re-run one of the orderings with failFast off to generate a sample error report.
var sample: Report<T> = Report.FastFailure()
for (c in toPermute) {
sample = c.process(varMatches, from, false)
if (sample !is Report.Success) {
break
}
varMatches = sample.matches
}
return Report.MiscFailure(
"no ordering found to satisfy constraints with common values in a nested group",
"[Constraints]\n" + toPermute.joinToString("\n") + "\n\n[Sample failure]\n" + sample.body()
)
}
// Recursively explore the permutation space for the given [candidates] list. Constraints are
// executed as the ordering is built up (rather than building each ordering completely before
// processing), so as soon as one fails we can prune any further sub-orderings from that point
// on - this provides a massive performance improvement.
private fun runPermutations(
candidates: MutableList<Constraint<T>>,
matches: ResultList<T>,
from: Int
): Report<T> {
if (candidates.isEmpty()) return Report.Success(matches)
// This limit empirically allows up to 10 pathologically arranged overlapping constraints
// to be successfully processed in a reasonable time.
if (++safetyLimit == 2_000_000) {
throw RuntimeException("NestGroup required too many permutations to complete: $this")
}
// At each level, run through the list of candidates, taking one from the front of the
// list to process. On success, recurse on the reduced list; if the recursive call finds
// a successful ordering, return immediately. On failure, do not recurse, thus pruning all
// of the sub-orderings under this particular point.
//
// If we haven't found a successful ordering, add the popped front candidate to the end of
// the candidates list and try the next one.
repeat(candidates.size) {
val candidate = candidates.removeAt(0)
val report = candidate.process(matches, from, true)
if (report is Report.Success) {
maxIndex = Math.max(candidate.maxIndex, maxIndex)
val subReport = runPermutations(candidates, report.matches, from)
if (subReport is Report.Success) {
return subReport
}
}
candidates.add(candidate)
}
return Report.FastFailure()
}
override fun toString() = "grp(${constraints.joinToString(", ")})"
}
protected fun search(matches: ResultList<T>, value: T, from: Int): Int {
(from until matches.size).forEach {
if (matches[it].constraint == null && matches[it].value == value) return it
}
return -1
}
protected fun showIndexed(values: List<T>, index: Int) =
values.mapIndexed { i, v -> if (i == index) ">$v<" else "$v" }.joinToString(", ")
}
/**
* Holds the result of a [Constraint.process] call, and for failed constraints can generate
* an AssertionError providing detailed information on how the constraint failed.
*/
sealed class Report<T> {
/** Generate an AssertionError providing detailed information on how the constraint failed. */
fun toException() = AssertionError("assertVariableOrdering: " + description() + "\n\n" + body())
open fun description(): String = ""
open fun body(): String = ""
class Success<T>(val matches: ResultList<T>) : Report<T>()
/** Reports a standard failure to match in a constraint. */
class MatchFailure<T>(
val label: String,
val matches: ResultList<T>,
val unmatched: List<Result<T>>
) : Report<T>() {
override fun description() =
"$label constraint failed with unmatched values: ${unmatched.map { it.value }}"
override fun body(): String {
val rows = mutableListOf(Row(' ', "Actual", "Match result"))
var ai = 0
var ui = 0
while (ai < matches.size || ui < unmatched.size) {
if (ai < matches.size && (ui == unmatched.size || ai < unmatched[ui].actualIndex)) {
rows.add(Row('|', matches[ai].value.toString(), matches[ai].showIndexed(), ai))
ai++
} else {
rows.add(Row(':', "", "?? " + unmatched[ui].showIndexed()))
ui++
}
}
return layout(rows)
}
}
/** Reports other failures. */
class MiscFailure<T>(val descriptionStr: String, val bodyStr: String) : Report<T>() {
override fun description() = descriptionStr
override fun body() = bodyStr
}
/** Used to speed up the handling of permutations in NestGroup processing. */
class FastFailure<T> : Report<T>()
class Row(val sep: Char, val left: String, val right: String, index: Int = -1) {
val indexStr = if (index == -1) "" else index.toString()
}
companion object {
fun <T> checkUnmatched(matches: ResultList<T>): Report<T> {
val summary = mutableListOf<T>()
val rows = matches.mapIndexed { ai, t ->
if (t.constraint == null) {
summary.add(t.value)
Row('|', t.value.toString(), "<- unmatched", ai)
} else {
Row('|', t.value.toString(), "", ai)
}
}
return if (summary.isEmpty()) {
Report.Success(matches)
} else {
Report.MiscFailure(
"all constraints satisfied but some values not matched: $summary",
layout(rows)
)
}
}
protected fun layout(rows: List<Row>): String {
var w1 = 1
var w2 = 1
rows.forEach {
w1 = Math.max(w1, it.indexStr.length)
w2 = Math.max(w2, it.left.length)
}
val rowStrings = rows.map {
"%${w1}s %c %-${w2}s %s".format(it.indexStr, it.sep, it.left, it.right).trimEnd()
}
return rowStrings.joinToString("\n")
}
}
}
| bsd-3-clause | 9e26ea78e875039c01801aff94de0d00 | 36.439604 | 100 | 0.641879 | 4.004024 | false | false | false | false |
Maccimo/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/data/index/IndexDiagnostic.kt | 1 | 5547 | // 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.vcs.log.data.index
import com.intellij.openapi.vcs.changes.ChangesUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.VcsCommitMetadata
import com.intellij.vcs.log.VcsFullCommitDetails
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.data.DataPack
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.graph.api.LiteLinearGraph
import com.intellij.vcs.log.graph.api.permanent.PermanentGraphInfo
import com.intellij.vcs.log.graph.utils.BfsWalk
import com.intellij.vcs.log.graph.utils.IntHashSetFlags
import com.intellij.vcs.log.graph.utils.LinearGraphUtils
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import it.unimi.dsi.fastutil.ints.IntArrayList
internal object IndexDiagnostic {
private const val FILTERED_PATHS_LIMIT = 1000
private const val COMMITS_TO_CHECK = 10
fun IndexDataGetter.getDiffFor(commitsIdsList: List<Int>, commitDetailsList: List<VcsFullCommitDetails>): String {
val report = StringBuilder()
for ((commitId, commitDetails) in commitsIdsList.zip(commitDetailsList)) {
getDiffFor(commitId, commitDetails)?.let { commitReport ->
report.append(commitReport).append("\n")
}
}
return report.toString()
}
private fun IndexDataGetter.getDiffFor(commitId: Int, commitDetails: VcsFullCommitDetails): String? {
val difference = getCommitDetailsDiff(commitDetails, IndexedDetails(this, logStorage, commitId))
?: getFilteringDiff(commitId, commitDetails)
if (difference == null) return null
return VcsLogBundle.message("vcs.log.index.diagnostic.error.for.commit", commitDetails.id.asString(), difference)
}
private fun getCommitDetailsDiff(expected: VcsCommitMetadata, actual: VcsCommitMetadata): String? {
val sb = StringBuilder()
sb.reportDiff(expected, actual, "vcs.log.index.diagnostic.error.attribute.name.author") { it.author }
sb.reportDiff(expected, actual, "vcs.log.index.diagnostic.error.attribute.name.committer") { it.committer }
sb.reportDiff(expected, actual, "vcs.log.index.diagnostic.error.attribute.name.author.time") { it.authorTime }
sb.reportDiff(expected, actual, "vcs.log.index.diagnostic.error.attribute.name.committer.time") { it.commitTime }
sb.reportDiff(expected, actual, "vcs.log.index.diagnostic.error.attribute.name.message") { it.fullMessage }
sb.reportDiff(expected, actual, "vcs.log.index.diagnostic.error.attribute.name.parents") { it.parents }
if (sb.isEmpty()) return null
return sb.toString()
}
private fun StringBuilder.reportDiff(expectedMetadata: VcsCommitMetadata, actualMetadata: VcsCommitMetadata, attributeKey: String,
attributeGetter: (VcsCommitMetadata) -> Any) {
val expectedValue = attributeGetter(expectedMetadata)
val actualValue = attributeGetter(actualMetadata)
if (expectedValue == actualValue) return
append(VcsLogBundle.message("vcs.log.index.diagnostic.error.message",
VcsLogBundle.message(attributeKey),
expectedValue, actualValue))
.append("\n")
}
private fun IndexDataGetter.getFilteringDiff(commitId: Int, details: VcsFullCommitDetails): String? {
val authorFilter = VcsLogFilterObject.fromUser(details.author)
val textFilter = details.fullMessage.lineSequence().first().takeIf { it.length > 3 }?.let {
VcsLogFilterObject.fromPattern(it, false, true)
}
val pathsFilter = VcsLogFilterObject.fromPaths(details.parents.indices.flatMapTo(mutableSetOf()) { parentIndex ->
ChangesUtil.getPaths(details.getChanges(parentIndex))
}.take(FILTERED_PATHS_LIMIT))
val sb = StringBuilder()
for (filter in listOfNotNull(authorFilter, textFilter, pathsFilter)) {
if (!filter(listOf(filter)).contains(commitId)) {
sb.append(VcsLogBundle.message("vcs.log.index.diagnostic.error.filter", filter, details.id.toShortString()))
.append("\n")
}
}
if (sb.isEmpty()) return null
return sb.toString()
}
fun DataPack.getFirstCommits(storage: VcsLogStorage, roots: Collection<VirtualFile>): List<Int> {
val rootsToCheck = roots.toMutableSet()
val commitsToCheck = IntArrayList()
@Suppress("UNCHECKED_CAST") val permanentGraphInfo = permanentGraph as? PermanentGraphInfo<Int> ?: return emptyList()
val graph = LinearGraphUtils.asLiteLinearGraph(permanentGraphInfo.linearGraph)
for (node in graph.nodesCount() - 1 downTo 0) {
if (!graph.getNodes(node, LiteLinearGraph.NodeFilter.DOWN).isEmpty()) continue
val root = storage.getCommitId(permanentGraphInfo.permanentCommitsInfo.getCommitId(node))?.root
if (!rootsToCheck.remove(root)) continue
// initial commit may not have files (in case of shallow clone), or it may have too many files
// checking next commits instead
BfsWalk(node, graph, IntHashSetFlags(COMMITS_TO_CHECK), false).walk { nextNode ->
if (nextNode != node && graph.getNodes(nextNode, LiteLinearGraph.NodeFilter.DOWN).size == 1) {
// skipping merge commits since they can have too many changes
commitsToCheck.add(permanentGraphInfo.permanentCommitsInfo.getCommitId(nextNode))
}
return@walk commitsToCheck.size < COMMITS_TO_CHECK
}
if (rootsToCheck.isEmpty()) break
}
return commitsToCheck
}
} | apache-2.0 | 95e6db257735bb12cd2235b5b6038eed | 48.535714 | 132 | 0.734451 | 4.36428 | false | false | false | false |
dempe/pinterest-java | src/main/java/com/chrisdempewolf/pinterest/methods/pin/PinMethodDelegate.kt | 1 | 4903 | package com.chrisdempewolf.pinterest.methods.pin
import com.chrisdempewolf.pinterest.exceptions.PinterestException
import com.chrisdempewolf.pinterest.fields.pin.PinFields
import com.chrisdempewolf.pinterest.methods.network.NetworkHelper
import com.chrisdempewolf.pinterest.methods.network.ResponseMessageAndStatusCode
import com.chrisdempewolf.pinterest.methods.pin.PinEndPointURIBuilder.buildBasePinUri
import com.chrisdempewolf.pinterest.methods.pin.PinEndPointURIBuilder.buildBoardPinUri
import com.chrisdempewolf.pinterest.methods.pin.PinEndPointURIBuilder.buildMyPinUri
import com.chrisdempewolf.pinterest.methods.pin.PinEndPointURIBuilder.buildPinUri
import com.chrisdempewolf.pinterest.responses.pin.PinPage
import com.chrisdempewolf.pinterest.responses.pin.PinResponse
import com.chrisdempewolf.pinterest.responses.pin.Pins
import com.google.gson.Gson
import org.apache.commons.io.IOUtils
import org.apache.http.HttpStatus
import org.apache.http.client.fluent.Form
import org.apache.http.client.methods.HttpDelete
import org.apache.http.client.methods.HttpPost
import org.apache.http.client.fluent.Request
import java.io.IOException
import java.net.URI
import java.net.URISyntaxException
class PinMethodDelegate(private val accessToken: String) {
fun getPin(id: String, pinFields: PinFields): PinResponse {
try { return Gson().fromJson(IOUtils.toString(buildPinUri(accessToken, id, pinFields.build())), PinResponse::class.java) }
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
/**
* This true/false pattern for deletion was adopted from RestFB: http://restfb.com/
* @param id: Pin ID
* @return true iff deletion was successful
*/
fun deletePin(id: String): Boolean {
try {
val response = NetworkHelper.submitDeleteRequest(buildPinUri(accessToken, id, null))
return response.statusCode == HttpStatus.SC_OK
}
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
fun patchPin(pinID: String, board: String?, note: String?, link: String?): ResponseMessageAndStatusCode {
try {
val patchBodyMap: Map<String, String?> = mapOf(
"board" to board,
"note" to note,
"link" to link)
return NetworkHelper.submitPatchRequest(
buildPinUri(accessToken, pinID, null),
buildNonNullMap(patchBodyMap))
}
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
fun postPin(
boardName: String,
note: String,
image: String,
link: String? = null): ResponseMessageAndStatusCode {
try {
val postBodyMap: Map<String, String?> = mapOf(
"board" to boardName,
"note" to note,
"image_url" to image,
"link" to link)
return NetworkHelper.submitPostRequest(
buildBasePinUri(accessToken),
buildNonNullMap(postBodyMap))
}
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
fun getMyPins(pinFields: PinFields? = null): Pins {
try { return Gson().fromJson(IOUtils.toString(buildMyPinUri(accessToken, pinFields?.build())), Pins::class.java) }
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
fun getPinsFromBoard(boardName: String, pinFields: PinFields? = null): Pins {
try { return Gson().fromJson(IOUtils.toString(buildBoardPinUri(accessToken, boardName, pinFields?.build())), Pins::class.java) }
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
fun getNextPageOfPins(page: PinPage?): Pins? {
if (page == null || page.next == null) { return null }
try { return Gson().fromJson(IOUtils.toString(URI(page.next)), Pins::class.java) }
catch (e: URISyntaxException) { throw PinterestException(e.message, e) }
catch (e: IOException) { throw PinterestException(e.message, e) }
}
/**
* Takes a Map<String, String?> and filters any null or blank values to use for POST and PATCH bodies.
*/
private fun buildNonNullMap(map: Map<String, String?>): Map<String, String>
= map.filter { e -> !e.value.isNullOrBlank() } as Map<String, String>
}
| mit | 56c8b34f48e796c154f088c5f1306405 | 43.981651 | 136 | 0.679176 | 3.995925 | false | false | false | false |
ingokegel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/DefType.kt | 1 | 1517 | package com.intellij.workspaceModel.codegen.deft.model
import org.jetbrains.deft.Obj
import org.jetbrains.deft.ObjBuilder
import com.intellij.workspaceModel.codegen.deft.ObjModule
import com.intellij.workspaceModel.codegen.deft.ObjType
import com.intellij.workspaceModel.codegen.deft.Field
class DefType(
module: ObjModule,
override val name: String,
base: DefType?,
val def: KtInterface,
) : ObjType<Obj, ObjBuilder<Obj>>(
module,
def.module.nextTypeId(),
base
) {
override val packageName: String
get() = def.file?.pkg?.fqn ?: ""
init {
open = def.open
abstract = def.abstract
sealed = def.sealed
}
fun verify(diagnostics: Diagnostics) {
val base = base
if (base != null) {
if (!base.inheritanceAllowed) {
diagnostics.add(
def.nameRange,
"Inheritance not allowed: $base is not `@Open` or `@Enum`"
)
}
}
structure.allFields.forEach {
verify(diagnostics, it)
}
}
private fun verify(diagnostics: Diagnostics, it: Field<out Obj, Any?>) {
val base = it.base
if (base != null) {
if (!base.open) diagnostics.add(it.exDef!!.nameRange,
"Inheritance not allowed: ${fieldDef(base)} is not `@Open`"
)
}
}
private fun fieldDef(field: Field<*, *>): String {
val def = field.exDef
return if (def != null) "`$def` of ${field.owner}" else "`$field`"
}
override fun toString(): String = "`$name` defined at ${def.nameRange.last}"
} | apache-2.0 | 97ef7c6f953affbdff2b9ba391c3b524 | 24.728814 | 97 | 0.633487 | 3.869898 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/migration/AbstractDiagnosticBasedMigrationInspection.kt | 1 | 3780 | // 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.inspections.migration
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactoryWithPsiElement
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.quickfix.QuickFixes
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtTreeVisitorVoid
abstract class AbstractDiagnosticBasedMigrationInspection<T : PsiElement>(val elementType: Class<T>) : AbstractKotlinInspection() {
abstract val diagnosticFactory: DiagnosticFactoryWithPsiElement<T, *>
open fun customIntentionFactory(): ((Diagnostic) -> IntentionAction?)? = null
open fun customHighlightRangeIn(element: T): TextRange? = null
private fun getActionFactory(): (Diagnostic) -> List<IntentionAction> =
customIntentionFactory()?.let { factory -> { diagnostic -> listOfNotNull(factory(diagnostic)) } }
?: QuickFixes.getInstance()
.getActionFactories(diagnosticFactory)
.singleOrNull()
?.let { factory -> { diagnostic -> factory.createActions(diagnostic) } }
?: error("Must have one factory")
override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? {
if (file !is KtFile) return null
val diagnostics by lazy {
file.analyzeWithAllCompilerChecks().bindingContext.diagnostics
}
val problemDescriptors = mutableListOf<ProblemDescriptor>()
val actionFactory = getActionFactory()
file.accept(
object : KtTreeVisitorVoid() {
override fun visitElement(element: PsiElement) {
super.visitElement(element)
if (!elementType.isInstance(element) || element.textLength == 0) return
val diagnostic = diagnostics.forElement(element)
.filter { it.factory == diagnosticFactory }
.ifEmpty { return }
.singleOrNull()
?: error("Must have one diagnostic")
val intentionAction = actionFactory(diagnostic).ifEmpty { return }.singleOrNull() ?: error("Must have one fix")
val text = descriptionMessage() ?: DefaultErrorMessages.render(diagnostic)
problemDescriptors.add(
manager.createProblemDescriptor(
element,
@Suppress("UNCHECKED_CAST") customHighlightRangeIn(element as T),
text,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
false,
IntentionWrapper(intentionAction),
)
)
}
},
)
return problemDescriptors.toTypedArray()
}
@Nls
protected open fun descriptionMessage(): String? = null
} | apache-2.0 | 30b778a8411b3537255a9f8f201d3bcd | 46.860759 | 158 | 0.665344 | 5.753425 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/hid/HIDAxis.kt | 1 | 891 | package org.snakeskin.hid
import org.snakeskin.ability.IInvertable
import org.snakeskin.hid.provider.IAxisValueProvider
import org.snakeskin.logic.scalars.NoScaling
import org.snakeskin.logic.scalars.IScalar
import kotlin.math.abs
class HIDAxis(private val provider: IAxisValueProvider,
private val factoryInvert: Boolean,
override var inverted: Boolean = false,
var deadband: Double = -1.0): IInvertable {
internal var registered = false
var scalar: IScalar = NoScaling
@Synchronized set
@Synchronized fun read(): Double {
if (!registered) return 0.0
val value = if (factoryInvert) -provider.read() else provider.read()
val delta = scalar.scale(value)
if (deadband == -1.0 || abs(delta) > deadband)
return if (inverted) -delta else delta
return 0.0
}
val default = 0.0
}
| gpl-3.0 | 996bfd6c97d46e0fc536d90c5b022c9f | 29.724138 | 76 | 0.676768 | 4.031674 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/RedundantRunCatchingInspection.kt | 4 | 2090 | // 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.inspections.coroutines
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.inspections.collections.AbstractCallChainChecker
import org.jetbrains.kotlin.idea.inspections.collections.SimplifyCallChainFix
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.qualifiedExpressionVisitor
/**
* Test - [org.jetbrains.kotlin.idea.inspections.LocalInspectionTestGenerated.Coroutines.RedundantRunCatching]
*/
class RedundantRunCatchingInspection : AbstractCallChainChecker() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
qualifiedExpressionVisitor(fun(expression) {
val conversion = findQualifiedConversion(expression, conversionGroups) { _, _, _, _ -> true } ?: return
val replacement = conversion.replacement
val descriptor = holder.manager.createProblemDescriptor(
expression,
expression.firstCalleeExpression()!!.textRange.shiftRight(-expression.startOffset),
KotlinBundle.message("redundant.runcatching.call.may.be.reduced.to.0", replacement),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
isOnTheFly,
SimplifyCallChainFix(conversion)
)
holder.registerProblem(descriptor)
})
private val conversionGroups = conversions.group()
companion object {
private val conversions = listOf(
Conversion(
"kotlin.runCatching", // FQNs are hardcoded instead of specifying their names via reflection because
"kotlin.getOrThrow", // referencing function which has generics isn't yet supported in Kotlin KT-12140
"run"
)
)
}
} | apache-2.0 | 7a3bf15ffcfaad449cbf2626ee9aa125 | 46.522727 | 158 | 0.715789 | 5.225 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/service/KotlinVersionProviderService.kt | 3 | 2881 | // 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.tools.projectWizard.core.service
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ProjectKind
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.DefaultRepository
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repositories
import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Repository
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
abstract class KotlinVersionProviderService : WizardService {
abstract fun getKotlinVersion(projectKind: ProjectKind): WizardKotlinVersion
protected fun kotlinVersionWithDefaultValues(version: Version) = WizardKotlinVersion(
version,
getKotlinVersionKind(version),
getKotlinVersionRepository(version),
getBuildSystemPluginRepository(getKotlinVersionKind(version), listOf(getDevVersionRepository())),
)
private fun getKotlinVersionRepository(versionKind: KotlinVersionKind): Repository = when (versionKind) {
KotlinVersionKind.STABLE, KotlinVersionKind.EAP, KotlinVersionKind.M -> DefaultRepository.MAVEN_CENTRAL
KotlinVersionKind.DEV -> getDevVersionRepository()
}
protected open fun getDevVersionRepository(): Repository = Repositories.JETBRAINS_KOTLIN_DEV
protected fun getKotlinVersionRepository(version: Version) =
getKotlinVersionRepository(getKotlinVersionKind(version))
protected fun getKotlinVersionKind(version: Version) = when {
"eap" in version.toString().toLowerCase() -> KotlinVersionKind.EAP
"rc" in version.toString().toLowerCase() -> KotlinVersionKind.EAP
"dev" in version.toString().toLowerCase() -> KotlinVersionKind.DEV
"m" in version.toString().toLowerCase() -> KotlinVersionKind.M
else -> KotlinVersionKind.STABLE
}
companion object {
fun getBuildSystemPluginRepository(
versionKind: KotlinVersionKind,
devRepositories: List<Repository>
): (BuildSystemType) -> List<Repository> =
when (versionKind) {
KotlinVersionKind.STABLE, KotlinVersionKind.EAP, KotlinVersionKind.M -> { buildSystem ->
when (buildSystem) {
BuildSystemType.GradleKotlinDsl, BuildSystemType.GradleGroovyDsl -> listOf(DefaultRepository.GRADLE_PLUGIN_PORTAL)
BuildSystemType.Maven -> listOf(DefaultRepository.MAVEN_CENTRAL)
BuildSystemType.Jps -> emptyList()
}
}
KotlinVersionKind.DEV -> { _ -> devRepositories }
}
}
} | apache-2.0 | 3e46103e6eb0ab9fa838c7fca6484c1e | 50.464286 | 158 | 0.725443 | 5.375 | false | false | false | false |
ktorio/ktor | ktor-client/ktor-client-android/jvm/test/io/ktor/client/engine/android/UrlConnectionUtilsTest.kt | 1 | 1588 | /*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine.android
import io.ktor.client.request.*
import kotlinx.coroutines.*
import java.net.*
import kotlin.test.*
class UrlConnectionUtilsTest {
private val data = HttpRequestBuilder().build()
@Test
fun testTimeoutAwareConnectionCatchesErrorInConnect(): Unit = runBlocking {
val connection = TestConnection(true, false)
assertFailsWith<Throwable>("Connect timeout has expired") {
connection.timeoutAwareConnection(data) {
it.connect()
}
}
}
@Test
fun testTimeoutAwareConnectionCatchesErrorInResponseStatusCode(): Unit = runBlocking {
val connection = TestConnection(false, true)
assertFailsWith<Throwable>("Connect timeout has expired") {
connection.timeoutAwareConnection(data) {
it.responseCode
}
}
}
}
private class TestConnection(
private val throwInConnect: Boolean,
private val throwInResponseCode: Boolean,
) : HttpURLConnection(URL("https://example.com")) {
override fun getResponseCode(): Int {
if (throwInResponseCode) throw ConnectException("Connect timed out")
return 200
}
override fun connect() {
if (throwInConnect) throw SocketTimeoutException()
}
override fun disconnect() {
throw NotImplementedError()
}
override fun usingProxy(): Boolean {
throw NotImplementedError()
}
}
| apache-2.0 | 97a6577969a53554779ed54d0108584b | 26.37931 | 119 | 0.666877 | 4.856269 | false | true | false | false |
google/accompanist | sample/src/main/java/com/google/accompanist/sample/pager/HorizontalPagerBasicSample.kt | 1 | 5552 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.accompanist.sample.pager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.FirstPage
import androidx.compose.material.icons.filled.LastPage
import androidx.compose.material.icons.filled.NavigateBefore
import androidx.compose.material.icons.filled.NavigateNext
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.google.accompanist.pager.ExperimentalPagerApi
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.PagerState
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.sample.AccompanistSampleTheme
import com.google.accompanist.sample.R
import kotlinx.coroutines.launch
class HorizontalPagerBasicSample : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AccompanistSampleTheme {
Surface {
Sample()
}
}
}
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
private fun Sample() {
Scaffold(
topBar = {
TopAppBar(
title = { Text(stringResource(R.string.horiz_pager_title_basics)) },
backgroundColor = MaterialTheme.colors.surface,
)
},
modifier = Modifier.fillMaxSize()
) { padding ->
Column(Modifier.fillMaxSize().padding(padding)) {
val pagerState = rememberPagerState()
// Display 10 items
HorizontalPager(
count = 10,
state = pagerState,
// Add 32.dp horizontal padding to 'center' the pages
contentPadding = PaddingValues(horizontal = 32.dp),
// Add some horizontal spacing between items
itemSpacing = 4.dp,
modifier = Modifier
.weight(1f)
.fillMaxWidth()
) { page ->
PagerSampleItem(
page = page,
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
)
}
ActionsRow(
pagerState = pagerState,
modifier = Modifier.align(Alignment.CenterHorizontally)
)
}
}
}
@OptIn(ExperimentalPagerApi::class)
@Composable
internal fun ActionsRow(
pagerState: PagerState,
modifier: Modifier = Modifier,
infiniteLoop: Boolean = false
) {
Row(modifier) {
val scope = rememberCoroutineScope()
IconButton(
enabled = infiniteLoop.not() && pagerState.currentPage > 0,
onClick = {
scope.launch {
pagerState.animateScrollToPage(0)
}
}
) {
Icon(Icons.Default.FirstPage, null)
}
IconButton(
enabled = infiniteLoop || pagerState.currentPage > 0,
onClick = {
scope.launch {
pagerState.animateScrollToPage(pagerState.currentPage - 1)
}
}
) {
Icon(Icons.Default.NavigateBefore, null)
}
IconButton(
enabled = infiniteLoop || pagerState.currentPage < pagerState.pageCount - 1,
onClick = {
scope.launch {
pagerState.animateScrollToPage(pagerState.currentPage + 1)
}
}
) {
Icon(Icons.Default.NavigateNext, null)
}
IconButton(
enabled = infiniteLoop.not() && pagerState.currentPage < pagerState.pageCount - 1,
onClick = {
scope.launch {
pagerState.animateScrollToPage(pagerState.pageCount - 1)
}
}
) {
Icon(Icons.Default.LastPage, null)
}
}
}
| apache-2.0 | 7ba75ffac687f295c4f5478c704bdc4e | 32.445783 | 94 | 0.637428 | 5.042688 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/util/lang/RxCoroutineBridge.kt | 2 | 2968 | package eu.kanade.tachiyomi.util.lang
import kotlinx.coroutines.CancellableContinuation
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import rx.Emitter
import rx.Observable
import rx.Subscriber
import rx.Subscription
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/*
* Util functions for bridging RxJava and coroutines. Taken from TachiyomiEH/SY.
*/
suspend fun <T> Observable<T>.awaitSingle(): T = single().awaitOne()
private suspend fun <T> Observable<T>.awaitOne(): T = suspendCancellableCoroutine { cont ->
cont.unsubscribeOnCancellation(
subscribe(
object : Subscriber<T>() {
override fun onStart() {
request(1)
}
override fun onNext(t: T) {
cont.resume(t)
}
override fun onCompleted() {
if (cont.isActive) cont.resumeWithException(
IllegalStateException(
"Should have invoked onNext"
)
)
}
override fun onError(e: Throwable) {
/*
* Rx1 observable throws NoSuchElementException if cancellation happened before
* element emission. To mitigate this we try to atomically resume continuation with exception:
* if resume failed, then we know that continuation successfully cancelled itself
*/
val token = cont.tryResumeWithException(e)
if (token != null) {
cont.completeResume(token)
}
}
}
)
)
}
internal fun <T> CancellableContinuation<T>.unsubscribeOnCancellation(sub: Subscription) =
invokeOnCancellation { sub.unsubscribe() }
fun <T> runAsObservable(
backpressureMode: Emitter.BackpressureMode = Emitter.BackpressureMode.NONE,
block: suspend () -> T,
): Observable<T> {
return Observable.create(
{ emitter ->
val job = GlobalScope.launch(Dispatchers.Unconfined, start = CoroutineStart.ATOMIC) {
try {
emitter.onNext(block())
emitter.onCompleted()
} catch (e: Throwable) {
// Ignore `CancellationException` as error, since it indicates "normal cancellation"
if (e !is CancellationException) {
emitter.onError(e)
} else {
emitter.onCompleted()
}
}
}
emitter.setCancellation { job.cancel() }
},
backpressureMode
)
}
| apache-2.0 | a030f06869048496de93afc18e238c05 | 33.917647 | 116 | 0.573113 | 5.578947 | false | false | false | false |
jguerinet/MyMartlet-Android | app/src/main/java/util/KoinModule.kt | 1 | 5800 | /*
* Copyright 2014-2019 Julien Guerinet
*
* 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.guerinet.mymartlet.util
import android.content.Context
import android.preference.PreferenceManager
import android.view.inputmethod.InputMethodManager
import com.guerinet.mymartlet.util.manager.ClearManager
import com.guerinet.mymartlet.util.manager.HomepageManager
import com.guerinet.mymartlet.util.manager.McGillManager
import com.guerinet.mymartlet.util.manager.UpdateManager
import com.guerinet.mymartlet.util.prefs.DefaultTermPref
import com.guerinet.mymartlet.util.prefs.UsernamePref
import com.guerinet.mymartlet.util.retrofit.ConfigService
import com.guerinet.mymartlet.util.room.UserDb
import com.guerinet.mymartlet.viewmodel.EbillViewModel
import com.guerinet.mymartlet.viewmodel.MapViewModel
import com.guerinet.mymartlet.viewmodel.SemesterViewModel
import com.guerinet.mymartlet.viewmodel.TranscriptViewModel
import com.guerinet.room.UpdateDb
import com.guerinet.suitcase.analytics.Analytics
import com.guerinet.suitcase.analytics.FAnalytics
import com.guerinet.suitcase.date.NullDatePref
import com.guerinet.suitcase.prefs.BooleanPref
import com.guerinet.suitcase.prefs.IntPref
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import com.squareup.moshi.Moshi
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.android.ext.koin.androidApplication
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.ext.koin.viewModel
import org.koin.dsl.module.Module
import org.koin.dsl.module.module
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import timber.log.Timber
/**
* Koin modules
* @author Julien Guerinet
* @since 2.0.0
*/
/**
* Base module with generic providers
*/
val appModule: Module = module {
// Analytics
single { FAnalytics(androidContext()) } bind Analytics::class
// Clear Manager
single { ClearManager(get(), get(), get(), get(Prefs.REMEMBER_USERNAME), get()) }
// HomePageManager
single { HomepageManager(get(), androidContext()) }
// InputMethodManager
factory {
androidContext().getSystemService(Context.INPUT_METHOD_SERVICE)
as? InputMethodManager ?: error("InputMethodManager not available")
}
// McGillManager
single { McGillManager(get(), get()) }
// Moshi
single { Moshi.Builder().build() }
// Shared Prefs
single { PreferenceManager.getDefaultSharedPreferences(androidContext()) }
// UpdateManager
single { UpdateManager(get(), get()) }
}
val dbModule = module {
// CourseDao
single { get<UserDb>().courseDao() }
// CourseResultDao
single { get<UserDb>().courseResultDao() }
// SemesterDao
single { get<UserDb>().semesterDao() }
// StatementDao
single { get<UserDb>().statementDao() }
// TranscriptDao
single { get<UserDb>().transcriptDao() }
// TranscriptCourseDao
single { get<UserDb>().transcriptCourseDao() }
// UpdateDao
single { get<UpdateDb>().updateDao() }
// UpdateDb
single { UpdateDb.init(androidContext()) }
// UserDb
single { UserDb.init(androidContext()) }
}
val networkModule: Module = module {
// ConfigService
single { get<Retrofit>().create(ConfigService::class.java) }
// HttpLoggingInterceptor
single {
HttpLoggingInterceptor { message -> Timber.tag("OkHttp").i(message) }
.apply { level = HttpLoggingInterceptor.Level.BASIC }
} bind Interceptor::class
// McGillService
single { get<McGillManager>().mcGillService }
// OkHttp
single { OkHttpClient.Builder().addInterceptor(get()).build() }
// Retrofit
single {
Retrofit.Builder()
.client(get())
.baseUrl("https://mymartlet.herokuapp.com/api/v2/")
.addConverterFactory(MoshiConverterFactory.create(get()))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
}
}
/**
* Contains all of the SharedPreferences providers
*/
val prefsModule: Module = module {
// DefaultTermPref
single { DefaultTermPref(get()) }
// UsernamePref
single { UsernamePref(get(), get()) }
single(Prefs.EULA) { BooleanPref(get(), Prefs.EULA, false) }
single(Prefs.GRADE_CHECKER) { BooleanPref(get(), Prefs.GRADE_CHECKER, false) }
single(Prefs.IMS_CONFIG) { NullDatePref(get(), Prefs.IMS_CONFIG, null) }
single(Prefs.IS_FIRST_OPEN) { BooleanPref(get(), Prefs.IS_FIRST_OPEN, true) }
single(Prefs.MIN_VERSION) { IntPref(get(), Prefs.MIN_VERSION, -1) }
single(Prefs.REMEMBER_USERNAME) { BooleanPref(get(), Prefs.REMEMBER_USERNAME, true) }
single(Prefs.SCHEDULE_24HR) { BooleanPref(get(), Prefs.SCHEDULE_24HR, false) }
single(Prefs.SEAT_CHECKER) { BooleanPref(get(), Prefs.SEAT_CHECKER, false) }
}
val viewModelsModule = module {
// EbillViewModel
viewModel { EbillViewModel(get(), get()) }
// MapViewModel
viewModel { MapViewModel(androidApplication()) }
// SemesterViewModel
viewModel { SemesterViewModel(get(), get()) }
// TranscriptViewModel
viewModel { TranscriptViewModel(get(), get(), get(), get()) }
}
| apache-2.0 | e985759842340d69c2419e6d899bd15f | 29.208333 | 89 | 0.71931 | 4.163676 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/metadata/validator/LocalFileValidationRuleTest.kt | 12 | 2549 | // 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.internal.statistics.metadata.validator
import com.intellij.internal.statistic.eventLog.FeatureUsageData
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomValidationRule
import com.intellij.internal.statistic.eventLog.validator.rules.impl.LocalFileCustomValidationRule
import com.intellij.testFramework.LightPlatformTestCase
import junit.framework.TestCase
import org.junit.Test
class LocalFileValidationRuleTest : LightPlatformTestCase() {
private fun doValidateEventId(validator: CustomValidationRule, eventId: String, eventData: FeatureUsageData) {
val context = EventContext.create(eventId, eventData.build())
doTest(ValidationResultType.ACCEPTED, validator, eventId, context)
}
private fun doRejectEventId(validator: CustomValidationRule, eventId: String, eventData: FeatureUsageData) {
val context = EventContext.create(eventId, eventData.build())
doTest(ValidationResultType.REJECTED, validator, eventId, context)
}
private fun doTest(expected: ValidationResultType, validator: CustomValidationRule, data: String, context: EventContext) {
TestCase.assertEquals(expected, validator.validate(data, context))
}
@Test
fun `test validate first allowed value by file`() {
val validator = TestLocalFileValidationRule()
doValidateEventId(validator, "allowed.value", FeatureUsageData())
}
@Test
fun `test validate second allowed value by file`() {
val validator = TestLocalFileValidationRule()
doValidateEventId(validator, "another.allowed.value", FeatureUsageData())
}
@Test
fun `test reject unknown value`() {
val validator = TestLocalFileValidationRule()
doRejectEventId(validator, "unknown.value", FeatureUsageData())
}
@Test
fun `test reject value if file doesn't exist`() {
val validator = EmptyLocalFileValidationRule()
doRejectEventId(validator, "value", FeatureUsageData())
}
}
private class TestLocalFileValidationRule : LocalFileCustomValidationRule(
"local_file", LocalFileValidationRuleTest::class.java, "file-with-allowed-values.txt"
)
private class EmptyLocalFileValidationRule : LocalFileCustomValidationRule(
"local_file", LocalFileValidationRuleTest::class.java, "not-existing-file.txt"
) | apache-2.0 | 4e49affc27f9f66e5a79835787d599fd | 41.5 | 140 | 0.794037 | 4.764486 | false | true | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddNamesToFollowingArgumentsIntention.kt | 3 | 2102 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtLambdaExpression
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
class AddNamesToFollowingArgumentsIntention : SelfTargetingIntention<KtValueArgument>(
KtValueArgument::class.java, KotlinBundle.lazyMessage("add.names.to.this.argument.and.following.arguments")
), LowPriorityAction {
override fun isApplicableTo(element: KtValueArgument, caretOffset: Int): Boolean {
val argumentList = element.parent as? KtValueArgumentList ?: return false
// Shadowed by AddNamesToCallArguments
if (argumentList.arguments.firstOrNull() == element) return false
// Shadowed by AddNameToArgument
if (argumentList.arguments.lastOrNull { !it.isNamed() } == element) return false
val expression = element.getArgumentExpression() ?: return false
AddNameToArgumentIntention.detectNameToAdd(element, shouldBeLastUnnamed = false) ?: return false
if (expression is KtLambdaExpression) {
val range = expression.textRange
return caretOffset == range.startOffset || caretOffset == range.endOffset
}
return true
}
override fun applyTo(element: KtValueArgument, editor: Editor?) {
val argumentList = element.parent as? KtValueArgumentList ?: return
val callElement = argumentList.parent as? KtCallElement ?: return
val resolvedCall = callElement.resolveToCall() ?: return
for (argument in argumentList.arguments.dropWhile { it != element }) {
AddNameToArgumentIntention.apply(argument, resolvedCall)
}
}
} | apache-2.0 | 842bae23e8e7bb711f39033bb2560467 | 49.071429 | 158 | 0.749286 | 5.101942 | false | false | false | false |
securityfirst/Umbrella_android | app/src/main/java/org/secfirst/umbrella/feature/content/presenter/ContentPresenterImp.kt | 1 | 8778 | package org.secfirst.umbrella.feature.content.presenter
import android.content.Intent
import com.raizlabs.android.dbflow.config.FlowManager
import org.apache.commons.io.FileUtils
import org.secfirst.umbrella.UmbrellaApplication
import org.secfirst.umbrella.data.database.AppDatabase
import org.secfirst.umbrella.data.database.checklist.Checklist
import org.secfirst.umbrella.data.database.difficulty.Difficulty
import org.secfirst.umbrella.data.database.form.Form
import org.secfirst.umbrella.data.database.lesson.Module
import org.secfirst.umbrella.data.database.lesson.Subject
import org.secfirst.umbrella.data.database.segment.Markdown
import org.secfirst.umbrella.data.database.segment.removeHead
import org.secfirst.umbrella.data.database.segment.replaceMarkdownImage
import org.secfirst.umbrella.data.disk.*
import org.secfirst.umbrella.data.disk.*
import org.secfirst.umbrella.feature.base.presenter.BasePresenterImp
import org.secfirst.umbrella.feature.content.ContentService
import org.secfirst.umbrella.feature.content.ContentService.Companion.EXTRA_URL_REPOSITORY
import org.secfirst.umbrella.feature.content.ContentView
import org.secfirst.umbrella.feature.content.interactor.ContentBaseInteractor
import org.secfirst.umbrella.misc.AppExecutors.Companion.uiContext
import org.secfirst.umbrella.misc.appContext
import org.secfirst.umbrella.misc.launchSilent
import org.secfirst.umbrella.misc.parseYmlFile
import java.io.File
import javax.inject.Inject
class ContentPresenterImp<V : ContentView, I : ContentBaseInteractor>
@Inject internal constructor(
interactor: I) : BasePresenterImp<V, I>(
interactor = interactor), ContentBasePresenter<V, I> {
override fun updateContent(pairFiles: List<Pair<String, File>>) {
launchSilent(uiContext) {
val checklists = mutableListOf<Checklist>()
val markdowns = mutableListOf<Markdown>()
val forms = mutableListOf<Form>()
interactor?.let {
pairFiles.forEach { pair ->
val file = pair.second
val pathId = pair.first
val absoluteFilePath = file.path.substringAfterLast(basePath(), "")
val pwd = getWorkDirectory(absoluteFilePath)
when (getDelimiter(file.nameWithoutExtension)) {
TypeFile.SEGMENT.value -> {
val markdownFormatted = file.readText().replaceMarkdownImage(pwd)
val newMarkdown = Markdown(pathId, markdownFormatted).removeHead()
val oldMarkdown = it.getMarkdown(pathId)
oldMarkdown?.let { oldMarkdownSafe ->
markdowns.add(updateMarkdownForeignKey(newMarkdown, oldMarkdownSafe))
}
}
TypeFile.CHECKLIST.value -> {
val newChecklist = parseYmlFile(file, Checklist::class)
newChecklist.id = pathId
val oldChecklist = it.getChecklist(pathId)
oldChecklist?.let { oldChecklistSafe ->
checklists.add(updateChecklistForeignKey(newChecklist, oldChecklistSafe))
}
}
TypeFile.FORM.value -> {
val newForm = parseYmlFile(file, Form::class)
newForm.path = pathId
val oldForm = it.getForm(pathId)
oldForm?.let { oldFormSafe -> updateFormForeignKey(newForm, oldFormSafe) }
forms.add(newForm)
}
else -> {
updateElementFiles(pwd, pathId, file)
}
}
}
it.saveAllMarkdowns(markdowns)
it.saveAllChecklists(checklists)
it.saveAllForms(forms)
getView()?.downloadContentCompleted(true)
}
}
}
override fun manageContent(url: String) {
launchSilent(uiContext) {
interactor?.let {
getView()?.downloadContentInProgress()
val intent = Intent(appContext(), ContentService::class.java).apply {
putExtra(EXTRA_URL_REPOSITORY, url)
action = ContentService.ACTION_START_FOREGROUND_SERVICE
}
appContext().startService(intent)
}
}
}
private suspend fun updateElementFiles(pwd: String, sha1ID: String, file: File) {
val modules = mutableListOf<Module>()
val subjects = mutableListOf<Subject>()
val difficulties = mutableListOf<Difficulty>()
interactor?.let {
when (getLevelOfPath(pwd)) {
ELEMENT_LEVEL -> {
val newElement = parseYmlFile(file, Element::class)
newElement.pathId = sha1ID
val module = newElement.convertToModule
val oldModule = it.getModule(sha1ID)
oldModule?.let { oldModuleSafe ->
// modules.add(module.updateModuleContent(oldModuleSafe))
}
}
SUB_ELEMENT_LEVEL -> {
val newElement = parseYmlFile(file, Element::class)
newElement.pathId = sha1ID
val subject = newElement.convertToSubject
val oldSubject = it.getSubject(sha1ID)
oldSubject?.let { oldSubjectSafe ->
subjects.add(subject.updateSubjectContent(oldSubjectSafe))
}
}
CHILD_LEVEL -> {
val newElement = parseYmlFile(file, Element::class)
newElement.pathId = sha1ID
val difficulty = newElement.convertToDifficulty
val oldDifficulty = it.getDifficulty(sha1ID)
oldDifficulty?.let { oldDiffSafe ->
difficulties.add(difficulty.updateDifficultyContent(oldDiffSafe))
}
}
else -> {
}
}
it.saveAllModule(modules)
it.saveAllDifficulties(difficulties)
it.saveAllSubjects(subjects)
}
}
private fun Difficulty.updateDifficultyContent(oldDifficulty: Difficulty): Difficulty {
markdowns.addAll(oldDifficulty.markdowns)
checklist.addAll(oldDifficulty.checklist)
return this
}
private fun Subject.updateSubjectContent(oldSubject: Subject): Subject {
markdowns = oldSubject.markdowns
difficulties = oldSubject.difficulties
checklist = oldSubject.checklist
return this
}
private fun Module.updateModuleContent(oldModule: Module): Module {
oldModule.icon = icon
oldModule.title = title
oldModule.index = index
return oldModule
}
private fun updateChecklistForeignKey(newChecklist: Checklist, oldChecklist: Checklist): Checklist {
newChecklist.module = oldChecklist.module
newChecklist.subject = oldChecklist.subject
newChecklist.difficulty = oldChecklist.difficulty
for (i in newChecklist.content.indices) {
newChecklist.content[i].id = oldChecklist.content[i].id
}
return newChecklist
}
private fun updateMarkdownForeignKey(newMarkdown: Markdown, oldMarkdown: Markdown): Markdown {
newMarkdown.module = oldMarkdown.module
newMarkdown.subject = oldMarkdown.subject
newMarkdown.difficulty = oldMarkdown.difficulty
return newMarkdown
}
private fun updateFormForeignKey(newForm: Form, oldForm: Form): Form {
for (i in newForm.screens.indices) {
newForm.screens[i].form = oldForm.screens[i].form
newForm.screens[i].id = oldForm.screens[i].id
for (j in newForm.screens[i].items.indices) {
val newItem = newForm.screens[i].items[j]
val oldItem = oldForm.screens[i].items[j]
newItem.id = oldItem.id
newItem.screen = oldItem.screen
for (y in newForm.screens[i].items[j].options.indices) {
val newOption = newForm.screens[i].items[j].options[y]
val oldOption = oldForm.screens[i].items[j].options[y]
newOption.id = oldOption.id
newOption.item = oldOption.item
}
}
}
return newForm
}
}
| gpl-3.0 | 6a67932d2d18a9d27db3e6171397347d | 43.110553 | 105 | 0.594441 | 5.047729 | false | false | false | false |
gorrotowi/Nothing | Android/Nothing/app/src/main/java/com/gorro/nothing/tracking/InstallReferrer.kt | 1 | 1971 | package com.gorro.nothing.tracking
import android.content.Context
import android.os.Bundle
import android.util.Log
import com.android.installreferrer.api.InstallReferrerClient
import com.android.installreferrer.api.InstallReferrerClient.InstallReferrerResponse.OK
import com.android.installreferrer.api.InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED
import com.android.installreferrer.api.InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE
import com.android.installreferrer.api.InstallReferrerStateListener
import com.android.installreferrer.api.ReferrerDetails
import com.google.firebase.analytics.FirebaseAnalytics
const val TAG = "NothingTracking"
fun Context.installReferrerTrack() {
val analytics = FirebaseAnalytics.getInstance(this)
val referrerClient = InstallReferrerClient.newBuilder(this).build()
referrerClient.startConnection(object : InstallReferrerStateListener {
override fun onInstallReferrerSetupFinished(responseCode: Int) {
when (responseCode) {
OK -> {
val response: ReferrerDetails = referrerClient.installReferrer
val referrerUrl: String = response.installReferrer
analytics.logEvent("install_referrer", bundleFromReferrer(referrerUrl))
}
FEATURE_NOT_SUPPORTED -> Log.e(TAG, "onInstallReferrerSetupFinished: Not supported")
SERVICE_UNAVAILABLE -> Log.e(TAG, "onInstallReferrerSetupFinished: Unavailble")
}
}
override fun onInstallReferrerServiceDisconnected() {
//Not implemented
}
})
}
private fun bundleFromReferrer(referrerUrl: String) =
referrerUrl.split("&").fold(Bundle()) { acc, nextParam ->
val keyValue = nextParam.split("=")
acc.putString(
keyValue.first().replace("utm_", ""),
keyValue.last().replace("utm_", "")
)
acc
}
| apache-2.0 | 182b8210b485d6dae1252666c7c005e7 | 40.0625 | 106 | 0.710807 | 4.989873 | false | false | false | false |
arnab/adventofcode | src/main/kotlin/aoc2018/day3/FabricClaimCalculator.kt | 1 | 1978 | package aoc2018.day3
data class Square(val x: Int, val y: Int)
data class Claim(
val id: Int,
val left: Int,
val top: Int,
val width: Int,
val height: Int,
val topLeftSquare: Square = Square(left, top),
val bottomRightSquare: Square = Square(left + width - 1, top + height - 1)
) {
fun includesSquare(square: Square): Boolean {
return topLeftSquare.x <= square.x &&
topLeftSquare.y <= square.y &&
bottomRightSquare.x >= square.x &&
bottomRightSquare.y >= square.y
}
}
object FabricClaimCalculator {
fun findConflictingSquares(claims: List<Claim>): List<Square> {
val maxX = claims.maxBy { it.bottomRightSquare.x }!!.bottomRightSquare.x
val maxY = claims.maxBy { it.bottomRightSquare.y }!!.bottomRightSquare.y
val conflictingSquares = mutableListOf<Square>()
for (x in 0..maxX) {
for (y in 0..maxY) {
val square = Square(x,y)
val claimsIncludingSquare = claims.filter { it.includesSquare(square) }
if (claimsIncludingSquare.size > 1) {
conflictingSquares.add(square)
}
}
}
return conflictingSquares.distinct()
}
fun findNonConflictingClaims(claims: List<Claim>): List<Claim> {
val maxX = claims.maxBy { it.bottomRightSquare.x }!!.bottomRightSquare.x
val maxY = claims.maxBy { it.bottomRightSquare.y }!!.bottomRightSquare.y
val conflictingClaims = mutableListOf<Claim>()
for (x in 0..maxX) {
for (y in 0..maxY) {
val square = Square(x,y)
val claimsIncludingSquare = claims.filter { it.includesSquare(square) }
if (claimsIncludingSquare.size > 1) {
conflictingClaims.addAll(claimsIncludingSquare)
}
}
}
return claims - conflictingClaims.distinct()
}
}
| mit | 43705d54e701a089c3c0102b6121eab4 | 32.525424 | 87 | 0.582406 | 4.3 | false | false | false | false |
peruukki/SimpleCurrencyConverter | app/src/main/java/com/peruukki/simplecurrencyconverter/utils/Settings.kt | 1 | 1543 | package com.peruukki.simplecurrencyconverter.utils
import android.app.Activity
import android.content.Context
import com.peruukki.simplecurrencyconverter.R
import com.peruukki.simplecurrencyconverter.models.ConversionRate
object Settings {
fun readConversionRate(activity: Activity): ConversionRate {
val preferences = activity.getPreferences(Context.MODE_PRIVATE)
val defaultRate = ConversionRate.defaultRate
val fixedCurrency = preferences.getString(activity.getString(R.string.fixed_currency_key),
defaultRate.fixedCurrency)
val variableCurrency = preferences.getString(activity.getString(R.string.variable_currency_key),
defaultRate.variableCurrency)
val rate = preferences.getFloat(activity.getString(R.string.conversion_rate_key),
defaultRate.fixedCurrencyInVariableCurrencyRate)
return ConversionRate(fixedCurrency, variableCurrency, rate)
}
fun writeConversionRate(activity: Activity, conversionRate: ConversionRate) {
val preferences = activity.getPreferences(Context.MODE_PRIVATE)
val editor = preferences.edit()
editor.putString(activity.getString(R.string.fixed_currency_key), conversionRate.fixedCurrency)
editor.putString(activity.getString(R.string.variable_currency_key), conversionRate.variableCurrency)
editor.putFloat(activity.getString(R.string.conversion_rate_key),
conversionRate.fixedCurrencyInVariableCurrencyRate)
editor.commit()
}
}
| mit | 1855b2d15b541acf390df110bb201534 | 43.085714 | 109 | 0.75243 | 4.821875 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/CopiedJavaCode.kt | 2 | 835 | // 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.conversion.copy
import com.intellij.codeInsight.editorActions.TextBlockTransferableData
import java.awt.datatransfer.DataFlavor
class CopiedJavaCode(val fileText: String, val startOffsets: IntArray, val endOffsets: IntArray) : TextBlockTransferableData {
override fun getFlavor() = DATA_FLAVOR
override fun getOffsetCount() = 0
override fun getOffsets(offsets: IntArray?, index: Int) = index
override fun setOffsets(offsets: IntArray?, index: Int) = index
companion object {
val DATA_FLAVOR: DataFlavor = DataFlavor(ConvertJavaCopyPasteProcessor::class.java, "class: ConvertJavaCopyPasteProcessor")
}
}
| apache-2.0 | 685a2bce9dc8b8e4ac6413874de20cd1 | 40.75 | 158 | 0.773653 | 4.441489 | false | false | false | false |
google/intellij-community | plugins/ide-features-trainer/src/training/ui/MessageFactory.kt | 2 | 5071 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package training.ui
import com.intellij.ide.ui.text.paragraph.TextParagraph
import com.intellij.ide.ui.text.parts.*
import com.intellij.ide.ui.text.showActionKeyPopup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.text.Strings
import com.intellij.ui.JBColor
import com.intellij.ui.components.ActionLink
import com.intellij.util.ui.JBUI
import org.intellij.lang.annotations.Language
import org.jdom.Element
import org.jdom.Text
import org.jdom.output.XMLOutputter
import training.dsl.LessonUtil
import training.learn.LearnBundle
import training.statistic.StatisticBase
import training.util.invokeActionForFocusContext
import training.util.openLinkInBrowser
import java.awt.Point
import java.util.regex.Pattern
import javax.swing.JTextPane
internal object MessageFactory {
private val LOG = Logger.getInstance(MessageFactory::class.java)
fun convert(@Language("HTML") text: String): List<TextParagraph> {
return text.splitToSequence("\n")
.map { paragraph ->
val wrappedText = "<root><text>$paragraph</text></root>"
val textAsElement = JDOMUtil.load(wrappedText.byteInputStream()).getChild("text")
?: throw IllegalStateException("Can't parse as XML:\n$paragraph")
val parts = convert(textAsElement)
TextParagraph(parts)
}
.toList()
}
private fun convert(element: Element): List<TextPart> {
val list = mutableListOf<TextPart>()
for (content in element.content) {
if (content is Text) {
var text = content.getValue()
if (Pattern.matches(" *\\p{IsPunctuation}.*", text)) {
val indexOfFirst = text.indexOfFirst { it != ' ' }
text = "\u00A0".repeat(indexOfFirst) + text.substring(indexOfFirst)
}
list.add(RegularTextPart(text))
}
else if (content is Element) {
val outputter = XMLOutputter()
val text: String = Strings.unescapeXmlEntities(outputter.outputString(content.content))
val newPart: TextPart = when (content.name) {
"icon" -> error("Need to return reflection-based icon processing")
"icon_idx" -> {
val icon = LearningUiManager.iconMap[text] ?: error("Not found icon with id: $text")
IconTextPart(icon)
}
"illustration" -> {
val icon = LearningUiManager.iconMap[text] ?: error("Not found icon with id: $text")
IllustrationTextPart(icon)
}
"strong" -> RegularTextPart(text, isBold = true)
"code" -> CodeTextPart(text)
"callback" -> {
val id = content.getAttributeValue("id")
if (id != null) {
val callback = LearningUiManager.getAndClearCallback(id.toInt())
if (callback != null) {
LinkTextPart(text, callback)
}
else error("Unknown callback with id '$id' and text '$text'")
}
else error("'callback' tag with text '$text' should contain 'id' attribute")
}
"a" -> {
val link = content.getAttributeValue("href")
?: error("'a' tag with text '$text' should contain 'href' attribute")
LinkTextPart(text) {
try {
openLinkInBrowser(link)
}
catch (ex: Exception) {
LOG.warn(ex)
}
}
}
"action" -> IftShortcutTextPart(text, isRaw = false)
"shortcut" -> IftShortcutTextPart(text, isRaw = true)
"raw_shortcut" -> IftShortcutTextPart(text, isRaw = true)
"ide" -> RegularTextPart(LessonUtil.productName)
else -> error("Unknown tag: ${content.name}")
}
list.add(newPart)
}
}
return list
}
private class IftShortcutTextPart(text: String, isRaw: Boolean) : ShortcutTextPart(text, isRaw) {
override val onClickAction: ((JTextPane, Point, height: Int) -> Unit)?
get() {
return if (!isRaw) {
{ textPane: JTextPane, point: Point, height: Int ->
val actionId = text
showActionKeyPopupExtended(textPane, point, height, actionId)
StatisticBase.logShortcutClicked(actionId)
}
}
else null
}
private fun showActionKeyPopupExtended(textPane: JTextPane, point: Point, height: Int, actionId: String) {
showActionKeyPopup(textPane, point, height, actionId) { panel ->
panel.add(ActionLink(LearnBundle.message("shortcut.balloon.apply.this.action")) {
val action = ActionManager.getInstance().getAction(actionId)
invokeActionForFocusContext(action)
}.also {
it.foreground = JBColor.namedColor("ToolTip.linkForeground", JBUI.CurrentTheme.Link.Foreground.ENABLED)
})
}
}
}
} | apache-2.0 | 8d0cff63e9f8969e18f4d5a8dfae5143 | 38.625 | 120 | 0.63242 | 4.308411 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/ide/TipOfTheDayStartupActivity.kt | 2 | 1779 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide
import com.intellij.ide.util.TipAndTrickManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.util.Disposer
import com.intellij.util.PlatformUtils
import com.intellij.util.concurrency.EdtScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
internal class TipOfTheDayStartupActivity : StartupActivity.DumbAware {
init {
if (ApplicationManager.getApplication().isHeadlessEnvironment || PlatformUtils.isRider() || !GeneralSettings.getInstance().isShowTipsOnStartup) {
throw ExtensionNotApplicableException.create()
}
}
override fun runActivity(project: Project) {
val disposableRef = AtomicReference<Disposable?>()
val future = EdtScheduledExecutorService.getInstance().schedule({
val disposable = disposableRef.getAndSet(null) ?: return@schedule
Disposer.dispose(disposable)
val tipManager = TipAndTrickManager.getInstance()
if (!project.isDisposed && tipManager.canShowDialogAutomaticallyNow(project)) {
TipsOfTheDayUsagesCollector.triggerDialogShown(TipsOfTheDayUsagesCollector.DialogType.automatically)
tipManager.showTipDialog(project)
}
}, 5, TimeUnit.SECONDS)
val disposable = Disposable {
disposableRef.set(null)
future.cancel(false)
}
disposableRef.set(disposable)
Disposer.register(project, disposable)
}
} | apache-2.0 | 34e9fac1882aa425331d1fae3f65d52b | 40.395349 | 149 | 0.789207 | 4.847411 | false | false | false | false |
google/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/data/pullrequest/GHPullRequestReviewThread.kt | 6 | 1294 | // 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 org.jetbrains.plugins.github.api.data.pullrequest
import com.fasterxml.jackson.annotation.JsonProperty
import com.intellij.collaboration.api.dto.GraphQLFragment
import com.intellij.diff.util.Side
import org.jetbrains.plugins.github.api.data.GHNode
import org.jetbrains.plugins.github.api.data.GHNodes
@GraphQLFragment("/graphql/fragment/pullRequestReviewThread.graphql")
class GHPullRequestReviewThread(id: String,
val isResolved: Boolean,
val isOutdated: Boolean,
val path: String,
@JsonProperty("diffSide") val side: Side,
val line: Int,
val startLine: Int?,
@JsonProperty("comments") comments: GHNodes<GHPullRequestReviewComment>)
: GHNode(id) {
val comments = comments.nodes
private val root = comments.nodes.first()
val state = root.state
val commit = root.commit
val originalCommit = root.originalCommit
val createdAt = root.createdAt
val diffHunk = root.diffHunk
val reviewId = root.reviewId
} | apache-2.0 | 4c90fed77121492c40c505ccbe220080 | 43.655172 | 140 | 0.655332 | 4.739927 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToBlockBodyIntention.kt | 1 | 5546 | // 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.psi.PsiElement
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.codeinsight.utils.adjustLineIndent
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.util.resultingWhens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.isNullabilityFlexible
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class ConvertToBlockBodyIntention : SelfTargetingIntention<KtDeclarationWithBody>(
KtDeclarationWithBody::class.java,
KotlinBundle.lazyMessage("convert.to.block.body")
) {
override fun isApplicableTo(element: KtDeclarationWithBody, caretOffset: Int): Boolean {
if (element is KtFunctionLiteral || element.hasBlockBody() || !element.hasBody()) return false
when (element) {
is KtNamedFunction -> {
val returnType = element.returnType() ?: return false
if (!element.hasDeclaredReturnType() && returnType.isError) return false// do not convert when type is implicit and unknown
return true
}
is KtPropertyAccessor -> return true
else -> error("Unknown declaration type: $element")
}
}
override fun skipProcessingFurtherElementsAfter(element: PsiElement) =
element is KtDeclaration || super.skipProcessingFurtherElementsAfter(element)
override fun applyTo(element: KtDeclarationWithBody, editor: Editor?) {
convert(element, true)
}
companion object {
fun convert(declaration: KtDeclarationWithBody, withReformat: Boolean = false): KtDeclarationWithBody {
val body = declaration.bodyExpression!!
fun generateBody(returnsValue: Boolean): KtExpression {
val bodyType = body.analyze().getType(body)
val psiFactory = KtPsiFactory(declaration.project)
if (bodyType != null && bodyType.isUnit() && body is KtNameReferenceExpression) return psiFactory.createEmptyBody()
val unitWhenAsResult = (bodyType == null || bodyType.isUnit()) && body.resultingWhens().isNotEmpty()
val needReturn = returnsValue && (bodyType == null || (!bodyType.isUnit() && !bodyType.isNothing()))
return if (needReturn || unitWhenAsResult) {
val annotatedExpr = body as? KtAnnotatedExpression
val returnedExpr = annotatedExpr?.baseExpression ?: body
val block = psiFactory.createSingleStatementBlock(psiFactory.createExpressionByPattern("return $0", returnedExpr))
val statement = block.firstStatement
annotatedExpr?.annotationEntries?.forEach {
block.addBefore(it, statement)
block.addBefore(psiFactory.createNewLine(), statement)
}
block
} else {
psiFactory.createSingleStatementBlock(body)
}
}
val newBody = when (declaration) {
is KtNamedFunction -> {
val returnType = declaration.returnType()!!
if (!declaration.hasDeclaredReturnType() && !returnType.isUnit()) {
declaration.setType(returnType)
}
generateBody(!returnType.isUnit() && !returnType.isNothing())
}
is KtPropertyAccessor -> {
val parent = declaration.parent
if (parent is KtProperty && parent.typeReference == null) {
val descriptor = parent.resolveToDescriptorIfAny()
(descriptor as? CallableDescriptor)?.returnType?.let { parent.setType(it) }
}
generateBody(declaration.isGetter)
}
else -> throw RuntimeException("Unknown declaration type: $declaration")
}
declaration.equalsToken!!.delete()
val replaced = body.replace(newBody)
if (withReformat) {
declaration.containingKtFile.adjustLineIndent(replaced.startOffset, replaced.endOffset)
}
return declaration
}
private fun KtNamedFunction.returnType(): KotlinType? {
val descriptor = resolveToDescriptorIfAny()
val returnType = descriptor?.returnType ?: return null
if (returnType.isNullabilityFlexible()
&& descriptor.overriddenDescriptors.firstOrNull()?.returnType?.isMarkedNullable == false
) return returnType.makeNotNullable()
return returnType
}
}
}
| apache-2.0 | 7f03b4bb0a9be96db008af65a87e54cb | 46.810345 | 158 | 0.652362 | 5.705761 | false | false | false | false |
effervescentia/klerik | src/main/kotlin/com/tkstr/klerik/core/ShuntingYard.kt | 1 | 4364 | package com.tkstr.klerik.core
import com.tkstr.klerik.COMMA
import com.tkstr.klerik.Expression
import com.tkstr.klerik.L_PAREN
import com.tkstr.klerik.R_PAREN
import com.tkstr.klerik.core.Util.charEql
import com.tkstr.klerik.core.Util.inPrecedenceOrder
import com.tkstr.klerik.core.Util.isNumber
import com.tkstr.klerik.core.Util.isParenthesis
import com.tkstr.klerik.core.Util.isString
import com.tkstr.klerik.core.Util.test
import java.util.*
/**
* ShuntingYard
*
* @author Ben Teichman
*/
object ShuntingYard {
data class ShuntContext(val exp: Expression) {
val tokenizer = Tokenizer(exp)
val outputQueue = mutableListOf<String>()
val stack = Stack<String>()
var lastFunction: String? = null
var previousToken: String? = null
}
fun evaluate(exp: Expression): List<String> = with(ShuntContext(exp)) {
while (tokenizer.hasNext()) {
val token = tokenizer.next()!!
when {
isValue(exp, token) -> outputQueue.add(token)
exp.isFunction(token) -> handleFunction(this, token)
token[0].isLetter() -> handleSymbol(this, token)
charEql(token, COMMA) -> handleParam(this)
exp.isOperator(token) -> handleOperator(this, token)
charEql(token, L_PAREN) -> handleParenStart(this, token)
charEql(token, R_PAREN) -> handleParamsEnd(this)
}
previousToken = token
}
while (stack.isNotEmpty()) {
val element = stack.pop()
test(isParenthesis(element), "Mismatched parentheses")
test(!(exp.isOperator(element) || isString(element)), "Unknown operator or function '$element'")
outputQueue.add(element)
}
return outputQueue
}
private fun isValue(exp: Expression, token: String) = isNumber(token) || exp.isVariable(token) || isString(token)
private fun handleFunction(ctx: ShuntContext, token: String) {
handleSymbol(ctx, token)
ctx.lastFunction = token
}
private fun handleParamsEnd(ctx: ShuntContext) = with(ctx) {
while (stack.isNotEmpty() && !charEql(stack.peek(), L_PAREN)) outputQueue.add(stack.pop())
test(stack.isEmpty(), "Mismatched parentheses")
stack.pop()
if (stack.isNotEmpty() && exp.isFunction(stack.peek())) outputQueue.add(stack.pop())
}
private fun handleParenStart(ctx: ShuntContext, token: String) = with(ctx) {
if (previousToken != null) {
test(isNumber(previousToken!!), "Missing operator at character position ${tokenizer.pos}")
if (exp.isFunction(previousToken!!)) outputQueue.add(token)
}
handleSymbol(this, token)
}
private fun handleOperator(ctx: ShuntContext, token: String) = with(ctx) {
val op = exp.operators[token]!!
var next = peekOrNull()
while (next != null && exp.isOperator(next) && inPrecedenceOrder(exp, op, next)) {
outputQueue.add(stack.pop())
next = peekOrNull()
}
handleSymbol(this, token)
}
private fun ShuntContext.peekOrNull() = if (stack.isEmpty()) null else stack.peek()
private fun handleSymbol(ctx: ShuntContext, token: String) {
ctx.stack.push(token)
}
private fun handleParam(ctx: ShuntContext) = with(ctx) {
while (stack.isNotEmpty() && !charEql(stack.peek(), L_PAREN)) outputQueue.add(stack.pop())
test(stack.isEmpty(), "Parse error for function '$lastFunction'")
}
fun validate(exp: Expression, rpn: List<String>) = with(Stack<Int>()) {
var counter = 0
rpn.forEach {
when {
charEql(it, L_PAREN) -> {
if (isNotEmpty()) this[lastIndex]++
push(0)
}
isNotEmpty() -> {
if (exp.isFunction(it)) {
counter -= pop() + 1
} else {
this[lastIndex]++
}
}
exp.isOperator(it) -> counter -= 2
}
test(counter < 0, "Too many operators or functions at '$it'")
counter++
}
test(counter > 1, "Too many numbers or variables")
test(counter < 1, "Empty expression")
}
} | mit | 85a59456edb93324889f4d72d3fb3935 | 34.487805 | 117 | 0.588222 | 3.967273 | false | true | false | false |
allotria/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/visible/filters/VcsLogFilters.kt | 2 | 9307 | // 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.vcs.log.visible.filters
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.*
import com.intellij.vcs.log.VcsLogFilterCollection.FilterKey
import com.intellij.vcs.log.VcsLogFilterCollection.HASH_FILTER
import com.intellij.vcs.log.VcsLogRangeFilter.RefRange
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.VcsUserUtil
import com.intellij.vcsUtil.VcsUtil
import it.unimi.dsi.fastutil.Hash
import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet
import org.jetbrains.annotations.Nls
import java.util.*
import java.util.regex.Pattern
import java.util.regex.PatternSyntaxException
object VcsLogFilterObject {
private val LOG = Logger.getInstance("#com.intellij.vcs.log.visible.filters.VcsLogFilters")
const val ME = "*"
@JvmStatic
fun fromPattern(text: String, isRegexpAllowed: Boolean = false, isMatchCase: Boolean = false): VcsLogTextFilter {
if (isRegexpAllowed && VcsLogUtil.isRegexp(text)) {
try {
return VcsLogRegexTextFilter(Pattern.compile(text, if (isMatchCase) 0 else Pattern.CASE_INSENSITIVE))
}
catch (ignored: PatternSyntaxException) {
}
}
return VcsLogTextFilterImpl(text, isMatchCase)
}
@JvmStatic
fun fromPatternsList(patterns: List<String>, isMatchCase: Boolean = false): VcsLogTextFilter {
if (patterns.isEmpty()) return fromPattern("", false, isMatchCase)
if (patterns.size == 1) return fromPattern(patterns.single(), false, isMatchCase)
return VcsLogMultiplePatternsTextFilter(patterns, isMatchCase)
}
@JvmStatic
fun fromBranch(branchName: String): VcsLogBranchFilter {
return fromBranches(listOf(branchName))
}
@JvmStatic
fun fromBranches(branchNames: List<String>): VcsLogBranchFilter {
return VcsLogBranchFilterImpl(branchNames, emptyList(), emptyList(), emptyList())
}
@JvmStatic
fun fromRange(exclusiveRef: String, inclusiveRef: String): VcsLogRangeFilter {
return fromRange(listOf(RefRange(exclusiveRef, inclusiveRef)))
}
@JvmStatic
fun fromRange(ranges: List<RefRange>): VcsLogRangeFilter {
return VcsLogRangeFilterImpl(ranges)
}
@JvmOverloads
@JvmStatic
fun fromBranchPatterns(patterns: Collection<String>,
existingBranches: Set<String>,
excludeNotMatched: Boolean = false): VcsLogBranchFilter {
val includedBranches = ArrayList<String>()
val excludedBranches = ArrayList<String>()
val includedPatterns = ArrayList<Pattern>()
val excludedPatterns = ArrayList<Pattern>()
val shouldExcludeNotMatched = existingBranches.isNotEmpty() && excludeNotMatched
for (pattern in patterns) {
val isExcluded = pattern.startsWith("-")
val string = if (isExcluded) pattern.substring(1) else pattern
val isRegexp = !existingBranches.contains(string) && VcsLogUtil.isRegexp(string)
if (isRegexp) {
try {
val regex = Pattern.compile(string)
if (isExcluded) {
excludedPatterns.add(regex)
}
else {
includedPatterns.add(regex)
}
}
catch (e: PatternSyntaxException) {
LOG.warn("Pattern $string is not a proper regular expression and no branch can be found with that name.", e)
if (shouldExcludeNotMatched) {
continue
}
if (isExcluded) {
excludedBranches.add(string)
}
else {
includedBranches.add(string)
}
}
}
else {
if (shouldExcludeNotMatched && !existingBranches.contains(string)) {
continue
}
if (isExcluded) {
excludedBranches.add(string)
}
else {
includedBranches.add(string)
}
}
}
return VcsLogBranchFilterImpl(includedBranches, includedPatterns, excludedBranches, excludedPatterns)
}
@JvmStatic
fun fromCommit(commit: CommitId): VcsLogRevisionFilter {
return VcsLogRevisionFilterImpl(listOf(commit))
}
@JvmStatic
fun fromCommits(commits: List<CommitId>): VcsLogRevisionFilter {
return VcsLogRevisionFilterImpl(commits)
}
@JvmStatic
fun fromHash(text: String): VcsLogHashFilter? {
val hashes = mutableListOf<String>()
for (word in StringUtil.split(text, " ")) {
if (!VcsLogUtil.HASH_REGEX.matcher(word).matches()) {
return null
}
hashes.add(word)
}
if (hashes.isEmpty()) return null
return fromHashes(hashes)
}
@JvmStatic
fun fromHashes(hashes: Collection<String>): VcsLogHashFilter {
return VcsLogHashFilterImpl(hashes)
}
@JvmStatic
fun fromDates(after: Date?, before: Date?): VcsLogDateFilter {
return VcsLogDateFilterImpl(after, before)
}
@JvmStatic
fun fromDates(after: Long, before: Long): VcsLogDateFilter {
return fromDates(if (after > 0) Date(after) else null, if (before > 0) Date(before) else null)
}
@JvmStatic
fun fromUserNames(userNames: Collection<String>, vcsLogData: VcsLogData): VcsLogUserFilter {
return VcsLogUserFilterImpl(userNames, vcsLogData.currentUser, vcsLogData.allUsers)
}
@JvmStatic
fun fromUser(user: VcsUser, allUsers: Set<VcsUser> = setOf(user)): VcsLogUserFilter {
return fromUserNames(listOf(VcsUserUtil.getShortPresentation(user)), emptyMap(), allUsers)
}
@JvmStatic
fun fromUserNames(userNames: Collection<String>, meData: Map<VirtualFile, VcsUser>, allUsers: Set<VcsUser>): VcsLogUserFilter {
return VcsLogUserFilterImpl(userNames, meData, allUsers)
}
@JvmStatic
fun fromPaths(files: Collection<FilePath>): VcsLogStructureFilter {
return VcsLogStructureFilterImpl(files)
}
@JvmStatic
fun fromVirtualFiles(files: Collection<VirtualFile>): VcsLogStructureFilter {
return fromPaths(files.map { file -> VcsUtil.getFilePath(file) })
}
@JvmStatic
fun fromRoot(root: VirtualFile): VcsLogRootFilter {
return fromRoots(listOf(root))
}
@JvmStatic
fun fromRoots(roots: Collection<VirtualFile>): VcsLogRootFilter {
return VcsLogRootFilterImpl(roots)
}
@JvmStatic
fun collection(vararg filters: VcsLogFilter?): VcsLogFilterCollection {
val filterSet = createFilterSet()
for (f in filters) {
if (f != null && replace(filterSet, f)) {
LOG.warn("Two filters with the same key ${f.key} in filter collection. Keeping only ${f}.")
}
}
return VcsLogFilterCollectionImpl(filterSet)
}
@JvmField
val EMPTY_COLLECTION = collection()
}
fun VcsLogFilterCollection.with(filter: VcsLogFilter?): VcsLogFilterCollection {
if (filter == null) return this
val filterSet = createFilterSet()
filterSet.addAll(this.filters)
replace(filterSet, filter)
return VcsLogFilterCollectionImpl(filterSet)
}
fun VcsLogFilterCollection.without(condition: (VcsLogFilter) -> Boolean): VcsLogFilterCollection {
val filterSet = createFilterSet()
this.filters.forEach { if (!(condition(it))) filterSet.add(it) }
return VcsLogFilterCollectionImpl(filterSet)
}
fun VcsLogFilterCollection.without(filterKey: FilterKey<*>): VcsLogFilterCollection {
return without { it.key == filterKey }
}
fun <T : VcsLogFilter> VcsLogFilterCollection.without(filterClass: Class<T>): VcsLogFilterCollection {
return without { filterClass.isInstance(it) }
}
fun VcsLogFilterCollection.matches(vararg filterKey: FilterKey<*>): Boolean {
return this.filters.mapTo(mutableSetOf()) { it.key } == filterKey.toSet()
}
@Nls
fun VcsLogFilterCollection.getPresentation(): String {
if (get(HASH_FILTER) != null) {
return get(HASH_FILTER)!!.displayText
}
return StringUtil.join(filters, { filter: VcsLogFilter ->
if (filters.size != 1) {
filter.withPrefix()
}
else filter.displayText
}, " ")
}
@Nls
private fun VcsLogFilter.withPrefix(): String {
when (this) {
is VcsLogTextFilter -> return VcsLogBundle.message("vcs.log.filter.text.presentation.with.prefix", displayText)
is VcsLogUserFilter -> return VcsLogBundle.message("vcs.log.filter.user.presentation.with.prefix", displayText)
is VcsLogDateFilter -> return displayTextWithPrefix
is VcsLogBranchFilter -> return VcsLogBundle.message("vcs.log.filter.branch.presentation.with.prefix", displayText)
is VcsLogRootFilter -> return VcsLogBundle.message("vcs.log.filter.root.presentation.with.prefix", displayText)
is VcsLogStructureFilter -> return VcsLogBundle.message("vcs.log.filter.structure.presentation.with.prefix", displayText)
}
return displayText
}
private fun createFilterSet() = ObjectOpenCustomHashSet(object : Hash.Strategy<VcsLogFilter> {
override fun hashCode(o: VcsLogFilter?): Int {
return o?.key?.hashCode() ?: 0
}
override fun equals(o1: VcsLogFilter?, o2: VcsLogFilter?): Boolean {
return o1 === o2 || (o1?.key == o2?.key)
}
})
private fun <T> replace(set: ObjectOpenCustomHashSet<T>, element: T): Boolean {
val isModified = set.remove(element)
set.add(element)
return isModified
} | apache-2.0 | 3a03cd2f0a4d7a9395ce4cd29068917b | 32.362007 | 140 | 0.71559 | 4.406723 | false | false | false | false |
allotria/intellij-community | platform/statistics/src/com/intellij/internal/statistic/local/ActionsLocalSummary.kt | 2 | 3810 | // 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.internal.statistic.local
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.extensions.ExtensionNotApplicableException
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.util.xmlb.annotations.Attribute
import com.intellij.util.xmlb.annotations.Property
import com.intellij.util.xmlb.annotations.Tag
import com.intellij.util.xmlb.annotations.XMap
import kotlin.math.max
import kotlin.math.min
@State(name = "ActionsLocalSummary", storages = [Storage("actionSummary.xml", roamingType = RoamingType.DISABLED)], reportStatistic = false)
@Service
class ActionsLocalSummary : PersistentStateComponent<ActionsLocalSummaryState>, SimpleModificationTracker() {
@Volatile
private var state = ActionsLocalSummaryState()
@Volatile
private var totalSummary: ActionsTotalSummary = ActionsTotalSummary()
override fun getState() = state
override fun loadState(state: ActionsLocalSummaryState) {
this.state = state
this.totalSummary = calculateTotalSummary(state)
}
private fun calculateTotalSummary(state: ActionsLocalSummaryState): ActionsTotalSummary {
var maxUsageCount = 0
var minUsageCount = Integer.MAX_VALUE
for (value in state.data.values) {
maxUsageCount = max(maxUsageCount, value.usageCount)
minUsageCount = min(minUsageCount, value.usageCount)
}
return ActionsTotalSummary(maxUsageCount, minUsageCount)
}
fun getTotalStats(): ActionsTotalSummary = totalSummary
fun getActionsStats(): Map<String, ActionSummary> = if (state.data.isEmpty()) emptyMap() else HashMap(state.data)
internal fun updateActionsSummary(actionId: String) {
val summary = state.data.computeIfAbsent(actionId) { ActionSummary() }
summary.lastUsedTimestamp = System.currentTimeMillis()
summary.usageCount++
totalSummary.maxUsageCount = max(summary.usageCount, totalSummary.maxUsageCount)
totalSummary.minUsageCount = min(summary.usageCount, totalSummary.minUsageCount)
incModificationCount()
}
}
@Tag("i")
class ActionSummary {
@Attribute("c")
@JvmField
var usageCount = 0
@Attribute("l")
@JvmField
var lastUsedTimestamp = System.currentTimeMillis()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ActionSummary
return usageCount == other.usageCount && lastUsedTimestamp == other.lastUsedTimestamp
}
override fun hashCode() = (31 * usageCount) + lastUsedTimestamp.hashCode()
}
data class ActionsLocalSummaryState(@get:XMap(entryTagName = "e", keyAttributeName = "n") @get:Property(surroundWithTag = false) internal val data: MutableMap<String, ActionSummary> = HashMap())
data class ActionsTotalSummary(var maxUsageCount: Int = 0, var minUsageCount: Int = 0)
private class ActionsLocalSummaryListener : AnActionListener {
private val service = ApplicationManager.getApplication().getService(ActionsLocalSummary::class.java)
?: throw ExtensionNotApplicableException.INSTANCE
override fun beforeActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) {
if (getPluginInfo(action::class.java).isSafeToReport()) {
service.updateActionsSummary(event.actionManager.getId(action) ?: action.javaClass.name)
}
}
} | apache-2.0 | cc7be937e7b5191aca3ca1869f1b3b55 | 39.542553 | 194 | 0.77979 | 4.872123 | false | false | false | false |
udevbe/westford | compositor/src/main/kotlin/org/westford/compositor/x11/X11XkbFactory.kt | 3 | 3324 | /*
* Westford Wayland Compositor.
* Copyright (C) 2016 Erik De Rijcke
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.westford.compositor.x11
import org.westford.compositor.core.Xkb
import org.westford.compositor.core.XkbFactory
import org.westford.nativ.libxkbcommon.Libxkbcommon
import org.westford.nativ.libxkbcommon.Libxkbcommon.Companion.XKB_CONTEXT_NO_FLAGS
import org.westford.nativ.libxkbcommon.Libxkbcommon.Companion.XKB_KEYMAP_COMPILE_NO_FLAGS
import org.westford.nativ.libxkbcommonx11.Libxkbcommonx11
import javax.inject.Inject
class X11XkbFactory @Inject internal constructor(private val libxkbcommon: Libxkbcommon,
private val xkbFactory: XkbFactory,
private val libxkbcommonx11: Libxkbcommonx11) {
fun create(xcbConnection: Long): Xkb {
val xkbContext = this.libxkbcommon.xkb_context_new(XKB_CONTEXT_NO_FLAGS)
if (xkbContext == 0L) {
throw RuntimeException("Got an error while trying to create xkb context. " + "Unfortunately the docs of the xkb library do not specify how to get more information " + "about the error, so you'll have to do it with this lousy exception.")
}
val device_id = this.libxkbcommonx11.xkb_x11_get_core_keyboard_device_id(xcbConnection)
if (device_id == -1) {
throw RuntimeException("Got an error while trying to fetch keyboard device id from X11 backend. " + "Unfortunately the docs of the xkb library do not specify how to get more information " + "about the error, so you'll have to do it with this lousy exception.")
}
val keymap = this.libxkbcommonx11.xkb_x11_keymap_new_from_device(xkbContext,
xcbConnection,
device_id,
XKB_KEYMAP_COMPILE_NO_FLAGS)
if (keymap == 0L) {
throw RuntimeException("Got an error while trying to get x11 keymap. " + "Unfortunately the docs of the xkb library do not specify how to get more information " + "about the error, so you'll have to do it with this lousy exception.")
}
val state = this.libxkbcommonx11.xkb_x11_state_new_from_device(keymap,
xcbConnection,
device_id)
return this.xkbFactory.create(xkbContext,
state,
keymap)
}
}
| agpl-3.0 | 7ec8e6a251405f32cdf32965f01aa466 | 54.4 | 272 | 0.621841 | 4.316883 | false | false | false | false |
cortinico/myo-emg-visualizer | myonnaise/src/test/java/com/ncorti/myonnaise/ByteReaderTest.kt | 1 | 1834 | package com.ncorti.myonnaise
import java.nio.ByteBuffer
import java.nio.ByteOrder
import org.junit.Assert.assertEquals
import org.junit.Test
class ByteReaderTest {
@Test
fun getByte() {
val testReader = ByteReader()
testReader.byteData = byteArrayOf(1.toByte())
assertEquals(1.toByte(), testReader.byte)
}
@Test
fun getInt() {
val intArray =
ByteBuffer
.allocate(4)
.order(ByteOrder.nativeOrder())
.putInt(12345)
.array()
val testReader = ByteReader()
testReader.byteData = intArray
assertEquals(12345, testReader.int)
}
@Test
fun getShort() {
val shortArray =
ByteBuffer
.allocate(2)
.order(ByteOrder.nativeOrder())
.putShort(123.toShort())
.array()
val testReader = ByteReader()
testReader.byteData = shortArray
assertEquals(123.toShort(), testReader.short)
}
@Test
fun rewindWorks() {
val testReader = ByteReader()
testReader.byteData = byteArrayOf(1.toByte())
assertEquals(1.toByte(), testReader.byte)
testReader.rewind()
assertEquals(1.toByte(), testReader.byte)
}
@Test
fun getBytes() {
val testReader = ByteReader()
testReader.byteData = byteArrayOf(
0.toByte(),
1.toByte(),
2.toByte(),
3.toByte(),
4.toByte(),
5.toByte(),
6.toByte(),
7.toByte()
)
val resultArray = testReader.getBytes(8)
assertEquals(8, resultArray.size)
for (i in 0 until resultArray.size) {
assertEquals(i.toFloat(), resultArray[i])
}
}
} | mit | c476db25028033151bccb34e541701ef | 22.227848 | 53 | 0.541439 | 4.495098 | false | true | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/HideToolWindowAction.kt | 4 | 2139 | // 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.ide.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ToolWindowType
import com.intellij.openapi.wm.impl.ToolWindowEventSource
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.util.ui.UIUtil
internal class HideToolWindowAction : AnAction(), DumbAware {
companion object {
internal fun shouldBeHiddenByShortCut(manager: ToolWindowManager, id: String): Boolean {
val window = manager.getToolWindow(id)
return window != null && window.isVisible && window.type != ToolWindowType.WINDOWED && window.type != ToolWindowType.FLOATING
}
}
override fun actionPerformed(e: AnActionEvent) {
val toolWindowManager = ToolWindowManager.getInstance(e.project ?: return) as ToolWindowManagerImpl
val id = toolWindowManager.activeToolWindowId ?: toolWindowManager.lastActiveToolWindowId ?: return
toolWindowManager.hideToolWindow(id, false, true, ToolWindowEventSource.HideToolWindowAction)
}
override fun update(event: AnActionEvent) {
val presentation = event.presentation
val project = event.project
if (project == null) {
presentation.isEnabled = false
return
}
val toolWindowManager = ToolWindowManager.getInstance(project)
val id = toolWindowManager.activeToolWindowId ?: toolWindowManager.lastActiveToolWindowId
val window = if (id == null) null else toolWindowManager.getToolWindow(id)
if (window == null) {
presentation.isEnabled = false
return
}
if (window.isVisible && UIUtil.isDescendingFrom(IdeFocusManager.getGlobalInstance().focusOwner, window.component)) {
presentation.isEnabled = true
}
else {
presentation.isEnabled = shouldBeHiddenByShortCut(toolWindowManager, id!!)
}
}
} | apache-2.0 | 7cdb8370032c0e5fb34b0e537141f4bc | 40.960784 | 140 | 0.766713 | 4.894737 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/ide/actions/project/convertModuleGroupsToQualifiedNames.kt | 1 | 9180 | // 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.ide.actions.project
import com.intellij.CommonBundle
import com.intellij.application.runInAllowSaveMode
import com.intellij.codeInsight.intention.IntentionManager
import com.intellij.codeInspection.ex.InspectionProfileImpl
import com.intellij.codeInspection.ex.InspectionProfileWrapper
import com.intellij.codeInspection.ex.InspectionToolsSupplier
import com.intellij.codeInspection.ex.LocalInspectionToolWrapper
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.LineExtensionInfo
import com.intellij.openapi.editor.SpellCheckingEditorCustomizationProvider
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.fileTypes.PlainTextLanguage
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModulePointerManager
import com.intellij.openapi.module.impl.ModulePointerManagerImpl
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiDocumentManager
import com.intellij.ui.*
import com.intellij.ui.components.JBLabel
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.xml.util.XmlStringUtil
import java.awt.Color
import java.awt.Font
import java.util.function.Function
import javax.swing.Action
import javax.swing.JCheckBox
import javax.swing.JComponent
import javax.swing.JPanel
class ConvertModuleGroupsToQualifiedNamesDialog(val project: Project) : DialogWrapper(project) {
private val editorArea: EditorTextField
private val document: Document
get() = editorArea.document
private lateinit var modules: List<Module>
private val recordPreviousNamesCheckBox: JCheckBox
private var modified = false
init {
title = ProjectBundle.message("convert.module.groups.dialog.title")
isModal = false
setOKButtonText(ProjectBundle.message("convert.module.groups.button.text"))
editorArea = EditorTextFieldProvider.getInstance().getEditorField(PlainTextLanguage.INSTANCE, project, listOf(EditorCustomization {
it.settings.apply {
isLineNumbersShown = false
isLineMarkerAreaShown = false
isFoldingOutlineShown = false
isRightMarginShown = false
additionalLinesCount = 0
additionalColumnsCount = 0
isAdditionalPageAtBottom = false
isShowIntentionBulb = false
}
(it as? EditorImpl)?.registerLineExtensionPainter(this::generateLineExtension)
setupHighlighting(it)
}, MonospaceEditorCustomization.getInstance()))
document.addDocumentListener(object: DocumentListener {
override fun documentChanged(event: DocumentEvent) {
modified = true
}
}, disposable)
recordPreviousNamesCheckBox = JCheckBox(ProjectBundle.message("convert.module.groups.record.previous.names.text"), true)
importRenamingScheme(emptyMap())
init()
}
private fun setupHighlighting(editor: Editor) {
editor.putUserData(IntentionManager.SHOW_INTENTION_OPTIONS_KEY, false)
val inspections = InspectionToolsSupplier.Simple(listOf(LocalInspectionToolWrapper(ModuleNamesListInspection())))
val file = PsiDocumentManager.getInstance(project).getPsiFile(document)
file?.putUserData(InspectionProfileWrapper.CUSTOMIZATION_KEY, Function {
val profile = InspectionProfileImpl("Module names", inspections, null)
for (spellCheckingToolName in SpellCheckingEditorCustomizationProvider.getInstance().spellCheckingToolNames) {
profile.getToolsOrNull(spellCheckingToolName, project)?.isEnabled = false
}
InspectionProfileWrapper(profile)
})
}
override fun createCenterPanel(): JPanel {
val text = XmlStringUtil.wrapInHtml(ProjectBundle.message("convert.module.groups.description.text"))
val recordPreviousNames = com.intellij.util.ui.UI.PanelFactory.panel(recordPreviousNamesCheckBox)
.withTooltip(ProjectBundle.message("convert.module.groups.record.previous.names.tooltip",
ApplicationNamesInfo.getInstance().fullProductName)).createPanel()
return JBUI.Panels.simplePanel(0, UIUtil.DEFAULT_VGAP)
.addToCenter(editorArea)
.addToTop(JBLabel(text))
.addToBottom(recordPreviousNames)
}
override fun getPreferredFocusedComponent(): JComponent = editorArea.focusTarget
private fun generateLineExtension(line: Int): Collection<LineExtensionInfo> {
val lineText = document.charsSequence.subSequence(document.getLineStartOffset(line), document.getLineEndOffset(line)).toString()
if (line !in modules.indices || modules[line].name == lineText) return emptyList()
val name = LineExtensionInfo(" <- ${modules[line].name}", JBColor.GRAY, null, null, Font.PLAIN)
val groupPath = ModuleManager.getInstance(project).getModuleGroupPath(modules[line])
if (groupPath == null) {
return listOf(name)
}
val group = LineExtensionInfo(groupPath.joinToString(separator = "/", prefix = " (", postfix = ")"), Color.GRAY, null, null, Font.PLAIN)
return listOf(name, group)
}
fun importRenamingScheme(renamingScheme: Map<String, String>) {
val moduleManager = ModuleManager.getInstance(project)
fun getDefaultName(module: Module) = (moduleManager.getModuleGroupPath(module)?.let { it.joinToString(".") + "." } ?: "") + module.name
val names = moduleManager.modules.associateBy({ it }, { renamingScheme.getOrElse(it.name, { getDefaultName(it) }) })
modules = moduleManager.modules.sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER, { names[it]!! }))
runWriteAction {
document.setText(modules.joinToString("\n") { names[it]!! })
}
modified = false
}
fun getRenamingScheme(): Map<String, String> {
val lines = document.charsSequence.split('\n')
return modules.withIndex().filter { lines[it.index] != it.value.name }.associateByTo(LinkedHashMap(), { it.value.name }, {
if (it.index in lines.indices) lines[it.index] else it.value.name
})
}
override fun doCancelAction() {
if (modified) {
val answer = Messages.showYesNoCancelDialog(project,
ProjectBundle.message("convert.module.groups.do.you.want.to.save.scheme"),
ProjectBundle.message("convert.module.groups.dialog.title"), null)
when (answer) {
Messages.CANCEL -> return
Messages.YES -> {
if (!saveModuleRenamingScheme(this)) {
return
}
}
}
}
super.doCancelAction()
}
override fun doOKAction() {
ModuleNamesListInspection.checkModuleNames(document.charsSequence.lines(), project) { line, message ->
Messages.showErrorDialog(project,
ProjectBundle.message("convert.module.groups.error.at.text", line + 1, StringUtil.decapitalize(message)),
CommonBundle.getErrorTitle())
return
}
val renamingScheme = getRenamingScheme()
if (renamingScheme.isNotEmpty()) {
val model = ModuleManager.getInstance(project).modifiableModel
val byName = modules.associateBy { it.name }
for (entry in renamingScheme) {
model.renameModule(byName[entry.key]!!, entry.value)
}
modules.forEach {
model.setModuleGroupPath(it, null)
}
runInAllowSaveMode(isSaveAllowed = false) {
runWriteAction {
model.commit()
}
if (recordPreviousNamesCheckBox.isSelected) {
(ModulePointerManager.getInstance(project) as ModulePointerManagerImpl).setRenamingScheme(renamingScheme)
}
}
project.save()
}
super.doOKAction()
}
override fun createActions(): Array<Action> {
return arrayOf(okAction, SaveModuleRenamingSchemeAction(this, { modified = false }),
LoadModuleRenamingSchemeAction(this), cancelAction)
}
}
class ConvertModuleGroupsToQualifiedNamesAction : DumbAwareAction(ProjectBundle.message("convert.module.groups.action.text"),
ProjectBundle.message("convert.module.groups.action.description"), null) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
ConvertModuleGroupsToQualifiedNamesDialog(project).show()
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = e.project != null && ModuleManager.getInstance(e.project!!).hasModuleGroups()
}
}
| apache-2.0 | 3e772a406ed1ba4d477fa6a82121efbd | 43.134615 | 140 | 0.73366 | 4.749095 | false | false | false | false |
leafclick/intellij-community | plugins/devkit/devkit-core/src/actions/updateFromSources/UpdateIdeFromSourcesAction.kt | 1 | 16249 | // 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 org.jetbrains.idea.devkit.actions.updateFromSources
import com.intellij.CommonBundle
import com.intellij.execution.configurations.JavaParameters
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.process.ProcessOutputTypes
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ex.ApplicationEx
import com.intellij.openapi.application.impl.ApplicationImpl
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEnumerator
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.io.systemIndependentPath
import com.intellij.task.ProjectTaskManager
import com.intellij.util.SystemProperties
import org.jetbrains.idea.devkit.util.PsiUtil
import java.io.File
import java.util.*
import kotlin.collections.LinkedHashSet
private val LOG = logger<UpdateIdeFromSourcesAction>()
private val notificationGroup by lazy {
NotificationGroup(displayId = "Update from Sources", displayType = NotificationDisplayType.STICKY_BALLOON)
}
internal open class UpdateIdeFromSourcesAction
@JvmOverloads constructor(private val forceShowSettings: Boolean = false)
: AnAction(if (forceShowSettings) "Update IDE from Sources Settings..." else "Update IDE from Sources...",
"Builds an installation of IntelliJ IDEA from the currently opened sources and replace the current installation by it.", null), DumbAware {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
if (forceShowSettings || UpdateFromSourcesSettings.getState().showSettings) {
val ok = UpdateFromSourcesDialog(project, forceShowSettings).showAndGet()
if (!ok) return
}
fun error(message: String) {
Messages.showErrorDialog(project, message, CommonBundle.getErrorTitle())
}
val state = UpdateFromSourcesSettings.getState()
val devIdeaHome = project.basePath ?: return
val workIdeHome = state.workIdePath ?: PathManager.getHomePath()
if (!ApplicationManager.getApplication().isRestartCapable && FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
return error("This IDE cannot restart itself so updating from sources isn't supported")
}
val notIdeHomeMessage = checkIdeHome(workIdeHome)
if (notIdeHomeMessage != null) {
return error("$workIdeHome is not a valid IDE home: $notIdeHomeMessage")
}
val scriptFile = File(devIdeaHome, "build/scripts/idea_ultimate.gant")
if (!scriptFile.exists()) {
return error("$scriptFile doesn't exist")
}
if (!scriptFile.readText().contains(includeBinAndRuntimeProperty)) {
return error("The build scripts is out-of-date, please update to the latest 'master' sources.")
}
val bundledPluginDirsToSkip: List<String> = if (state.buildDisabledPlugins) {
emptyList()
}
else {
val pluginDirectoriesToSkip = LinkedHashSet(state.pluginDirectoriesForDisabledPlugins)
pluginDirectoriesToSkip.removeAll(PluginManagerCore.getLoadedPlugins().asSequence().filter { it.isBundled }.map { it.path }.filter { it.isDirectory }.map { it.name })
PluginManagerCore.getPlugins().filter { it.isBundled && !it.isEnabled }.map { it.path }.filter { it.isDirectory }.mapTo(pluginDirectoriesToSkip) { it.name }
val list = pluginDirectoriesToSkip.toMutableList()
state.pluginDirectoriesForDisabledPlugins = list
list
}
val deployDir = "$devIdeaHome/out/deploy"
val distRelativePath = "dist"
val backupDir = "$devIdeaHome/out/backup-before-update-from-sources"
val params = createScriptJavaParameters(devIdeaHome, project, deployDir, distRelativePath, scriptFile,
bundledPluginDirsToSkip, state.buildDisabledPlugins) ?: return
ProjectTaskManager.getInstance(project)
.buildAllModules()
.onSuccess {
if (!it.isAborted && !it.hasErrors()) {
runUpdateScript(params, project, workIdeHome, "$deployDir/$distRelativePath", backupDir)
}
}
}
private fun checkIdeHome(workIdeHome: String): String? {
val homeDir = File(workIdeHome)
if (!homeDir.exists()) return null
if (homeDir.isFile) return "it is not a directory"
val buildTxt = if (SystemInfo.isMac) "Resources/build.txt" else "build.txt"
for (name in listOf("bin", buildTxt)) {
if (!File(homeDir, name).exists()) {
return "'$name' doesn't exist"
}
}
return null
}
private fun runUpdateScript(params: JavaParameters,
project: Project,
workIdeHome: String,
builtDistPath: String,
backupDir: String) {
object : Task.Backgroundable(project, "Updating from Sources", true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = "Updating IDE from sources..."
backupImportantFilesIfNeeded(workIdeHome, backupDir, indicator)
indicator.text2 = "Deleting $builtDistPath"
FileUtil.delete(File(builtDistPath))
indicator.text2 = "Starting gant script"
val scriptHandler = params.createOSProcessHandler()
val errorLines = Collections.synchronizedList(ArrayList<String>())
scriptHandler.addProcessListener(object : ProcessAdapter() {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
LOG.debug("script: ${event.text}")
if (outputType == ProcessOutputTypes.STDERR) {
errorLines.add(event.text)
}
else if (outputType == ProcessOutputTypes.STDOUT) {
indicator.text2 = event.text
}
}
override fun processTerminated(event: ProcessEvent) {
if (indicator.isCanceled) {
return
}
if (event.exitCode != 0) {
val errorText = errorLines.joinToString("\n")
notificationGroup.createNotification(title = "Update from Sources Failed",
content = "Build script finished with ${event.exitCode}: $errorText",
type = NotificationType.ERROR).notify(project)
return
}
if (!FileUtil.pathsEqual(workIdeHome, PathManager.getHomePath())) {
startCopyingFiles(builtDistPath, workIdeHome, project)
return
}
val command = generateUpdateCommand(builtDistPath, workIdeHome)
if (indicator.isShowing) {
restartWithCommand(command)
}
else {
notificationGroup.createNotification(title = "Update from Sources",
content = "New installation is prepared from sources. <a href=\"#\">Restart</a>?",
listener = NotificationListener { _, _ -> restartWithCommand(command) }).notify(project)
}
}
})
scriptHandler.startNotify()
while (!scriptHandler.isProcessTerminated) {
scriptHandler.waitFor(300)
indicator.checkCanceled()
}
}
}.queue()
}
private fun backupImportantFilesIfNeeded(workIdeHome: String,
backupDirPath: String,
indicator: ProgressIndicator) {
val backupDir = File(backupDirPath)
if (backupDir.exists()) {
LOG.debug("$backupDir already exists, skipping backup")
return
}
LOG.debug("Backing up files from $workIdeHome to $backupDir")
indicator.text2 = "Backing up files"
FileUtil.createDirectory(backupDir)
File(workIdeHome, "bin").listFiles()
?.filter { it.name !in safeToDeleteFilesInBin && it.extension !in safeToDeleteExtensions }
?.forEach { FileUtil.copy(it, File(backupDir, "bin/${it.name}")) }
File(workIdeHome).listFiles()
?.filter { it.name !in safeToDeleteFilesInHome }
?.forEach { FileUtil.copyFileOrDir(it, File(backupDir, it.name)) }
}
private fun startCopyingFiles(builtDistPath: String, workIdeHome: String, project: Project) {
object : Task.Backgroundable(project, "Updating from Sources", true) {
override fun run(indicator: ProgressIndicator) {
indicator.text = "Copying files to IDE distribution..."
indicator.text2 = "Deleting old files"
FileUtil.delete(File(workIdeHome))
indicator.checkCanceled()
indicator.text2 = "Copying new files"
FileUtil.copyDir(File(builtDistPath), File(workIdeHome))
indicator.checkCanceled()
Notification("Update from Sources", "Update from Sources", "New installation is prepared at $workIdeHome.",
NotificationType.INFORMATION).notify(project)
}
}.queue()
}
private fun generateUpdateCommand(builtDistPath: String, workIdeHome: String): Array<String> {
if (SystemInfo.isWindows) {
val restartLogFile = File(PathManager.getLogPath(), "update-from-sources.log")
val updateScript = FileUtil.createTempFile("update", ".cmd", false)
val workHomePath = File(workIdeHome).absolutePath
/* deletion of the IDE files may fail to delete some executable files because they are still used by the IDE process,
so the script wait for some time and try to delete again;
'ping' command is used instead of 'timeout' because the latter doesn't work from batch files;
removal of the script file is performed in separate process to avoid errors while executing the script */
FileUtil.writeToFile(updateScript, """
@echo off
SET count=30
SET time_to_wait=500
:DELETE_DIR
RMDIR /Q /S "$workHomePath"
IF EXIST "$workHomePath" (
IF %count% GEQ 0 (
ECHO "$workHomePath" still exists, wait %time_to_wait%ms and try delete again
PING 127.0.0.1 -n 2 -w %time_to_wait% >NUL
SET /A count=%count%-1
SET /A time_to_wait=%time_to_wait%+1000
ECHO %count% attempts remain
GOTO DELETE_DIR
)
ECHO Failed to delete "$workHomePath", IDE wasn't updated. You may delete it manually and copy files from "${File(builtDistPath).absolutePath}" by hand
GOTO CLEANUP_AND_EXIT
)
XCOPY "${File(builtDistPath).absolutePath}" "$workHomePath"\ /Q /E /Y
:CLEANUP_AND_EXIT
START /b "" cmd /c DEL /Q /F "${updateScript.absolutePath}" & EXIT /b
""".trimIndent())
// 'Runner' class specified as a parameter which is actually not used by the script; this is needed to use a copy of restarter (see com.intellij.util.Restarter.runRestarter)
return arrayOf("cmd", "/c", updateScript.absolutePath, "com.intellij.updater.Runner", ">${restartLogFile.absolutePath}", "2>&1")
}
val command = arrayOf(
"rm -rf \"$workIdeHome\"/*",
"cp -R \"$builtDistPath\"/* \"$workIdeHome\""
)
return arrayOf("/bin/sh", "-c", command.joinToString(" && "))
}
private fun restartWithCommand(command: Array<String>) {
(ApplicationManager.getApplication() as ApplicationImpl).restart(ApplicationEx.FORCE_EXIT or ApplicationEx.EXIT_CONFIRMED or ApplicationEx.SAVE, command)
}
private fun createScriptJavaParameters(devIdeaHome: String,
project: Project,
deployDir: String,
@Suppress("SameParameterValue") distRelativePath: String,
scriptFile: File,
bundledPluginDirsToSkip: List<String>,
buildNonBundledPlugins: Boolean): JavaParameters? {
val sdk = ProjectRootManager.getInstance(project).projectSdk
if (sdk == null) {
LOG.warn("Project SDK is not defined")
return null
}
val params = JavaParameters()
params.isUseClasspathJar = true
params.setDefaultCharset(project)
params.jdk = sdk
//todo use org.jetbrains.idea.maven.utils.MavenUtil.resolveLocalRepository instead
val m2Repo = File(SystemProperties.getUserHome(), ".m2/repository").systemIndependentPath
//todo get from project configuration
val coreClassPath = listOf(
"$m2Repo/org/codehaus/groovy/groovy-all/2.4.17/groovy-all-2.4.17.jar",
"$m2Repo/commons-cli/commons-cli/1.2/commons-cli-1.2.jar",
"$devIdeaHome/community/lib/ant/lib/ant.jar",
"$devIdeaHome/community/lib/ant/lib/ant-launcher.jar"
)
params.classPath.addAll(coreClassPath)
params.mainClass = "org.codehaus.groovy.tools.GroovyStarter"
params.programParametersList.add("--classpath")
val buildScriptsModuleName = "intellij.idea.ultimate.build"
val buildScriptsModule = ModuleManager.getInstance(project).findModuleByName(buildScriptsModuleName)
if (buildScriptsModule == null) {
LOG.warn("Build scripts module $buildScriptsModuleName is not found in the project")
return null
}
val classpath = OrderEnumerator.orderEntries(buildScriptsModule)
.recursively().withoutSdk().runtimeOnly().productionOnly().classes().pathsList
coreClassPath.forEach { classpath.remove(FileUtil.toSystemDependentName(it)) }
params.programParametersList.add(classpath.pathsString)
params.programParametersList.add("--main")
params.programParametersList.add("gant.Gant")
params.programParametersList.add("--file")
params.programParametersList.add(scriptFile.absolutePath)
params.programParametersList.add("update-from-sources")
params.vmParametersList.add("-D$includeBinAndRuntimeProperty=true")
params.vmParametersList.add("-Dintellij.build.bundled.jre.prefix=jbrsdk-")
if (bundledPluginDirsToSkip.isNotEmpty()) {
params.vmParametersList.add("-Dintellij.build.bundled.plugin.dirs.to.skip=${bundledPluginDirsToSkip.joinToString(",")}")
}
if (buildNonBundledPlugins) {
params.vmParametersList.add("-Dintellij.build.local.plugins.repository=true")
}
params.vmParametersList.add("-Dintellij.build.output.root=$deployDir")
params.vmParametersList.add("-DdistOutputRelativePath=$distRelativePath")
return params
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = PsiUtil.isIdeaProject(e.project)
}
}
private const val includeBinAndRuntimeProperty = "intellij.build.generate.bin.and.runtime.for.unpacked.dist"
internal class UpdateIdeFromSourcesSettingsAction : UpdateIdeFromSourcesAction(true)
private val safeToDeleteFilesInHome = setOf(
"bin", "help", "jre", "jre64", "jbr", "lib", "license", "plugins", "redist", "MacOS", "Resources",
"build.txt", "product-info.json", "Install-Linux-tar.txt", "Install-Windows-zip.txt", "ipr.reg"
)
private val safeToDeleteFilesInBin = setOf(
"append.bat", "appletviewer.policy", "format.sh", "format.bat",
"fsnotifier", "fsnotifier64",
"inspect.bat", "inspect.sh",
"restarter"
/*
"idea.properties",
"idea.sh",
"idea.bat",
"idea.exe.vmoptions",
"idea64.exe.vmoptions",
"idea.vmoptions",
"idea64.vmoptions",
"log.xml",
*/
)
private val safeToDeleteExtensions = setOf("exe", "dll", "dylib", "so", "ico", "svg", "png", "py") | apache-2.0 | c62123e55b9d2d99919b74ba075179b8 | 44.774648 | 179 | 0.67758 | 4.7665 | false | false | false | false |
romannurik/muzei | main/src/main/java/com/google/android/apps/muzei/browse/BrowseProviderFragment.kt | 1 | 9158 | /*
* Copyright 2018 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.browse
import android.app.PendingIntent
import android.os.Bundle
import android.view.Menu
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.graphics.drawable.DrawerArrowDrawable
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import coil.load
import com.google.android.apps.muzei.api.internal.ProtocolConstants.METHOD_MARK_ARTWORK_LOADED
import com.google.android.apps.muzei.room.Artwork
import com.google.android.apps.muzei.room.MuzeiDatabase
import com.google.android.apps.muzei.room.getCommands
import com.google.android.apps.muzei.sync.ProviderManager
import com.google.android.apps.muzei.util.ContentProviderClientCompat
import com.google.android.apps.muzei.util.addMenuProvider
import com.google.android.apps.muzei.util.collectIn
import com.google.android.apps.muzei.util.toast
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.BrowseProviderFragmentBinding
import net.nurik.roman.muzei.databinding.BrowseProviderItemBinding
class BrowseProviderFragment: Fragment(R.layout.browse_provider_fragment) {
companion object {
const val REFRESH_DELAY = 300L // milliseconds
}
private val viewModel: BrowseProviderViewModel by viewModels()
private val args: BrowseProviderFragmentArgs by navArgs()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val binding = BrowseProviderFragmentBinding.bind(view)
viewModel.providerInfo.collectIn(viewLifecycleOwner) { providerInfo ->
if (providerInfo != null) {
val pm = requireContext().packageManager
binding.toolbar.title = providerInfo.loadLabel(pm)
} else {
// The contentUri is no longer valid, so we should pop
findNavController().popBackStack()
}
}
binding.swipeRefresh.setOnRefreshListener {
refresh(binding.swipeRefresh)
}
binding.toolbar.apply {
navigationIcon = DrawerArrowDrawable(requireContext()).apply {
progress = 1f
}
setNavigationOnClickListener {
val navController = findNavController()
if (navController.currentDestination?.id == R.id.browse_provider) {
navController.popBackStack()
}
}
addMenuProvider(R.menu.browse_provider_fragment) {
refresh(binding.swipeRefresh)
true
}
}
val adapter = Adapter()
binding.list.adapter = adapter
viewModel.client.collectIn(viewLifecycleOwner) {
adapter.client = it
}
viewModel.artwork.collectIn(viewLifecycleOwner) {
adapter.submitList(it)
}
}
private fun refresh(swipeRefreshLayout: SwipeRefreshLayout) {
viewLifecycleOwner.lifecycleScope.launch {
ProviderManager.requestLoad(requireContext(), args.contentUri)
// Show the refresh indicator for some visible amount of time
// rather than immediately dismissing it. We don't know how long
// the provider will actually take to refresh, if it does at all.
delay(REFRESH_DELAY)
withContext(Dispatchers.Main.immediate) {
swipeRefreshLayout.isRefreshing = false
}
}
}
class ArtViewHolder(
private val owner: LifecycleOwner,
private val binding: BrowseProviderItemBinding,
private val clientProvider: () -> ContentProviderClientCompat?,
): RecyclerView.ViewHolder(binding.root) {
fun bind(artwork: Artwork) {
val context = itemView.context
binding.image.contentDescription = artwork.title
binding.image.load(artwork.imageUri) {
lifecycle(owner)
}
itemView.setOnClickListener {
owner.lifecycleScope.launch(Dispatchers.Main) {
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, artwork.providerAuthority)
param(FirebaseAnalytics.Param.ITEM_NAME, artwork.title ?: "")
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "actions")
param(FirebaseAnalytics.Param.CONTENT_TYPE, "browse")
}
// Ensure the date added is set to the current time
artwork.dateAdded.time = System.currentTimeMillis()
MuzeiDatabase.getInstance(context).artworkDao()
.insert(artwork)
clientProvider.invoke()?.call(METHOD_MARK_ARTWORK_LOADED, artwork.imageUri.toString())
context.toast(if (artwork.title.isNullOrBlank()) {
context.getString(R.string.browse_set_wallpaper)
} else {
context.getString(R.string.browse_set_wallpaper_with_title,
artwork.title)
})
}
}
itemView.setOnCreateContextMenuListener(null)
owner.lifecycleScope.launch(Dispatchers.Main.immediate) {
val actions = artwork.getCommands(context).filterNot {
it.title.isBlank()
}
if (actions.isNotEmpty()) {
itemView.setOnCreateContextMenuListener { menu, _, _ ->
actions.forEachIndexed { index, action ->
menu.add(Menu.NONE, index, index, action.title).apply {
setOnMenuItemClickListener { menuItem ->
Firebase.analytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) {
param(FirebaseAnalytics.Param.ITEM_LIST_ID, artwork.providerAuthority)
param(FirebaseAnalytics.Param.ITEM_NAME, menuItem.title.toString())
param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "actions")
param(FirebaseAnalytics.Param.CONTENT_TYPE, "browse")
}
try {
action.actionIntent.send()
} catch (e: PendingIntent.CanceledException) {
// Why do you give us a cancelled PendingIntent.
// We can't do anything with that.
}
true
}
}
}
}
}
}
}
}
inner class Adapter: ListAdapter<Artwork, ArtViewHolder>(
object: DiffUtil.ItemCallback<Artwork>() {
override fun areItemsTheSame(artwork1: Artwork, artwork2: Artwork) =
artwork1.imageUri == artwork2.imageUri
override fun areContentsTheSame(artwork1: Artwork, artwork2: Artwork) =
artwork1 == artwork2
}
) {
var client: ContentProviderClientCompat? = null
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
) = ArtViewHolder(
viewLifecycleOwner,
BrowseProviderItemBinding.inflate(layoutInflater, parent, false)
) {
client
}
override fun onBindViewHolder(holder: ArtViewHolder, position: Int) {
holder.bind(getItem(position))
}
}
} | apache-2.0 | 7a77ff747dcfef56787844a365cd6d25 | 42.614286 | 110 | 0.615091 | 5.444709 | false | false | false | false |
FirebaseExtended/mlkit-material-android | app/src/main/java/com/google/firebase/ml/md/kotlin/barcodedetection/BarcodeGraphicBase.kt | 1 | 3020 | /*
* 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.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.firebase.ml.md.kotlin.camera.GraphicOverlay
import com.google.firebase.ml.md.kotlin.camera.GraphicOverlay.Graphic
import com.google.firebase.ml.md.R
import com.google.firebase.ml.md.kotlin.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 | bba52666e440bc2b53c91020b08e46de | 39.810811 | 111 | 0.743046 | 4.370478 | false | false | false | false |
JuliusKunze/kotlin-native | performance/src/main/kotlin/org/jetbrains/ring/MatrixMapBenchmark.kt | 2 | 1893 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.ring
import org.jetbrains.ring.BENCHMARK_SIZE
/**
* This class emulates matrix behaviour using a hash map as its implementation
*/
class KMatrix internal constructor(val rows: Int, val columns: Int) {
private val matrix: MutableMap<Pair<Int, Int>, Double> = HashMap();
init {
for (row in 0..rows-1) {
for (col in 0..columns-1) {
matrix.put(Pair(row, col), Random.nextDouble())
}
}
}
fun get(row: Int, col: Int): Double {
return get(Pair(row, col))
}
fun get(pair: Pair<Int, Int>): Double {
return matrix.getOrElse(pair, { 0.0 })
}
fun put(pair: Pair<Int, Int>, elem: Double) {
matrix.put(pair, elem)
}
operator fun plusAssign(other: KMatrix) {
for (entry in matrix.entries) {
put(entry.key, entry.value + other.get(entry.key))
}
}
}
/**
* This class tests hash map performance
*/
open class MatrixMapBenchmark {
//Benchmark
fun add(): KMatrix {
var rows = BENCHMARK_SIZE
var cols = 1
while (rows > cols) {
rows /= 2
cols *= 2
}
val a = KMatrix(rows, cols)
val b = KMatrix(rows, cols)
a += b
return a
}
} | apache-2.0 | b09e37ad3562a4b58d9f95596d281170 | 24.945205 | 78 | 0.610143 | 3.839757 | false | false | false | false |
ianhanniballake/muzei | main/src/main/java/com/google/android/apps/muzei/settings/EffectsFragment.kt | 1 | 10364 | /*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.muzei.settings
import android.app.Activity
import android.content.SharedPreferences
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.content.edit
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.apps.muzei.isPreviewMode
import com.google.android.apps.muzei.render.MuzeiBlurRenderer
import com.google.android.apps.muzei.util.toast
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import net.nurik.roman.muzei.R
import net.nurik.roman.muzei.databinding.EffectsFragmentBinding
@OptIn(ExperimentalCoroutinesApi::class)
val EffectsLockScreenOpen = MutableStateFlow(false)
/**
* Fragment for allowing the user to configure advanced settings.
*/
@OptIn(ExperimentalCoroutinesApi::class)
class EffectsFragment : Fragment(R.layout.effects_fragment) {
private lateinit var binding: EffectsFragmentBinding
private val sharedPreferencesListener = SharedPreferences.OnSharedPreferenceChangeListener {
sp, key ->
val effectsLinked = sp.getBoolean(Prefs.PREF_LINK_EFFECTS, false)
if (key == Prefs.PREF_LINK_EFFECTS) {
if (effectsLinked) {
if (binding.viewPager.currentItem == 0) {
// Update the lock screen effects to match the home screen
sp.edit {
putInt(Prefs.PREF_LOCK_BLUR_AMOUNT,
sp.getInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR))
putInt(Prefs.PREF_LOCK_DIM_AMOUNT,
sp.getInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM))
putInt(Prefs.PREF_LOCK_GREY_AMOUNT,
sp.getInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY))
}
} else {
// Update the home screen effects to match the lock screen
sp.edit {
putInt(Prefs.PREF_BLUR_AMOUNT,
sp.getInt(Prefs.PREF_LOCK_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR))
putInt(Prefs.PREF_DIM_AMOUNT,
sp.getInt(Prefs.PREF_LOCK_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM))
putInt(Prefs.PREF_GREY_AMOUNT,
sp.getInt(Prefs.PREF_LOCK_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY))
}
}
requireContext().toast(R.string.toast_link_effects, Toast.LENGTH_LONG)
} else {
requireContext().toast(R.string.toast_link_effects_off, Toast.LENGTH_LONG)
}
// Update the menu item
updateLinkEffectsMenuItem(effectsLinked)
} else if (effectsLinked) {
when (key) {
Prefs.PREF_BLUR_AMOUNT -> {
// Update the lock screen effect to match the updated home screen
sp.edit {
putInt(Prefs.PREF_LOCK_BLUR_AMOUNT, sp.getInt(Prefs.PREF_BLUR_AMOUNT,
MuzeiBlurRenderer.DEFAULT_BLUR))
}
}
Prefs.PREF_DIM_AMOUNT -> {
// Update the lock screen effect to match the updated home screen
sp.edit {
putInt(Prefs.PREF_LOCK_DIM_AMOUNT, sp.getInt(Prefs.PREF_DIM_AMOUNT,
MuzeiBlurRenderer.DEFAULT_MAX_DIM))
}
}
Prefs.PREF_GREY_AMOUNT -> {
// Update the lock screen effect to match the updated home screen
sp.edit {
putInt(Prefs.PREF_LOCK_GREY_AMOUNT, sp.getInt(Prefs.PREF_GREY_AMOUNT,
MuzeiBlurRenderer.DEFAULT_GREY))
}
}
Prefs.PREF_LOCK_BLUR_AMOUNT -> {
// Update the home screen effect to match the updated lock screen
sp.edit {
putInt(Prefs.PREF_BLUR_AMOUNT, sp.getInt(Prefs.PREF_LOCK_BLUR_AMOUNT,
MuzeiBlurRenderer.DEFAULT_BLUR))
}
}
Prefs.PREF_LOCK_DIM_AMOUNT -> {
// Update the home screen effect to match the updated lock screen
sp.edit {
putInt(Prefs.PREF_DIM_AMOUNT, sp.getInt(Prefs.PREF_LOCK_DIM_AMOUNT,
MuzeiBlurRenderer.DEFAULT_MAX_DIM))
}
}
Prefs.PREF_LOCK_GREY_AMOUNT -> {
// Update the home screen effect to match the updated lock screen
sp.edit {
putInt(Prefs.PREF_GREY_AMOUNT, sp.getInt(Prefs.PREF_LOCK_GREY_AMOUNT,
MuzeiBlurRenderer.DEFAULT_GREY))
}
}
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding = EffectsFragmentBinding.bind(view)
if (requireActivity().isPreviewMode) {
with(binding.toolbar) {
setNavigationIcon(R.drawable.ic_ab_done)
navigationContentDescription = getString(R.string.done)
setNavigationOnClickListener {
requireActivity().run {
setResult(Activity.RESULT_OK)
finish()
}
}
}
}
requireActivity().menuInflater.inflate(R.menu.effects_fragment, binding.toolbar.menu)
updateLinkEffectsMenuItem()
binding.toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_link_effects -> {
val sp = Prefs.getSharedPreferences(requireContext())
val effectsLinked = sp.getBoolean(Prefs.PREF_LINK_EFFECTS, false)
sp.edit {
putBoolean(Prefs.PREF_LINK_EFFECTS, !effectsLinked)
}
true
}
R.id.action_reset_defaults -> {
Prefs.getSharedPreferences(requireContext()).edit {
putInt(Prefs.PREF_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)
putInt(Prefs.PREF_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)
putInt(Prefs.PREF_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)
putInt(Prefs.PREF_LOCK_BLUR_AMOUNT, MuzeiBlurRenderer.DEFAULT_BLUR)
putInt(Prefs.PREF_LOCK_DIM_AMOUNT, MuzeiBlurRenderer.DEFAULT_MAX_DIM)
putInt(Prefs.PREF_LOCK_GREY_AMOUNT, MuzeiBlurRenderer.DEFAULT_GREY)
}
true
}
else -> false
}
}
binding.viewPager.adapter = Adapter(this)
TabLayoutMediator(binding.tabLayout, binding.viewPager) { tab, position ->
tab.text = when(position) {
0 -> getString(R.string.settings_home_screen_title)
else -> getString(R.string.settings_lock_screen_title)
}
}.attach()
binding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
EffectsLockScreenOpen.value = position == 1
}
})
Prefs.getSharedPreferences(requireContext())
.registerOnSharedPreferenceChangeListener(sharedPreferencesListener)
}
override fun onStart() {
super.onStart()
// Reset the value here to restore the state lost in onStop()
EffectsLockScreenOpen.value = binding.viewPager.currentItem == 1
}
private fun updateLinkEffectsMenuItem(
effectsLinked: Boolean = Prefs.getSharedPreferences(requireContext())
.getBoolean(Prefs.PREF_LINK_EFFECTS, false)
) {
with(binding.toolbar.menu.findItem(R.id.action_link_effects)) {
setIcon(if (effectsLinked)
R.drawable.ic_action_link_effects
else
R.drawable.ic_action_link_effects_off)
title = if (effectsLinked)
getString(R.string.action_link_effects)
else
getString(R.string.action_link_effects_off)
}
}
override fun onStop() {
// The lock screen effects screen is no longer visible, so set the value to false
EffectsLockScreenOpen.value = false
super.onStop()
}
override fun onDestroyView() {
Prefs.getSharedPreferences(requireContext())
.unregisterOnSharedPreferenceChangeListener(sharedPreferencesListener)
super.onDestroyView()
}
private class Adapter(fragment: Fragment) : FragmentStateAdapter(fragment) {
override fun getItemCount() = 2
override fun createFragment(position: Int) = when(position) {
0 -> EffectsScreenFragment.create(
Prefs.PREF_BLUR_AMOUNT,
Prefs.PREF_DIM_AMOUNT,
Prefs.PREF_GREY_AMOUNT)
else -> EffectsScreenFragment.create(
Prefs.PREF_LOCK_BLUR_AMOUNT,
Prefs.PREF_LOCK_DIM_AMOUNT,
Prefs.PREF_LOCK_GREY_AMOUNT)
}
}
}
| apache-2.0 | b6ffa2fc6696eb8366c62636f2039314 | 43.672414 | 105 | 0.574489 | 4.937589 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/ide/impl/TrustedPathsSettings.kt | 1 | 1162 | // 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.impl
import com.intellij.openapi.components.*
import com.intellij.util.io.isAncestor
import com.intellij.util.xmlb.annotations.OptionTag
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
@State(name = "Trusted.Paths.Settings", storages = [Storage(value = "trusted-paths.xml", roamingType = RoamingType.DISABLED)])
@Service(Service.Level.APP)
internal class TrustedPathsSettings : SimplePersistentStateComponent<TrustedPathsSettings.State>(State()) {
class State : BaseState() {
@get:OptionTag("TRUSTED_PATHS")
var trustedPaths by list<String>()
}
fun isPathTrusted(path: Path): Boolean {
return state.trustedPaths.map { Paths.get(it) }.any { it.isAncestor(path) }
}
fun getTrustedPaths(): List<String> = Collections.unmodifiableList(state.trustedPaths)
fun setTrustedPaths(paths: List<String>) {
state.trustedPaths = ArrayList<String>(paths)
}
fun addTrustedPath(path: String) {
state.trustedPaths.add(path)
}
} | apache-2.0 | 003952106708f92c025e1edcde0b4b2b | 34.242424 | 158 | 0.753012 | 3.797386 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/introduceImportAlias/KotlinIntroduceImportAliasHandler.kt | 2 | 7651 | // 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.refactoring.introduce.introduceImportAlias
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.core.KotlinNameSuggester
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.refactoring.selectElement
import org.jetbrains.kotlin.idea.references.findPsiDeclarations
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.search.fileScope
import org.jetbrains.kotlin.idea.search.isImportUsage
import org.jetbrains.kotlin.idea.util.ImportInsertHelperImpl
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions
import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.resolve.scopes.utils.findPackage
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
import org.jetbrains.kotlin.utils.checkWithAttachment
object KotlinIntroduceImportAliasHandler : RefactoringActionHandler {
val REFACTORING_NAME = KotlinBundle.message("name.introduce.import.alias")
@get:TestOnly
var suggestedImportAliasNames: Collection<String> = emptyList()
fun doRefactoring(project: Project, editor: Editor, element: KtNameReferenceExpression) {
val fqName = element.resolveMainReferenceToDescriptors().firstOrNull()?.importableFqName ?: return
val file = element.containingKtFile
val declarationDescriptors = file.resolveImportReference(fqName)
val fileSearchScope = file.fileScope()
val resolveScope = file.resolveScope
val usages = declarationDescriptors.flatMap { descriptor ->
val isExtension = descriptor.isExtension
descriptor.findPsiDeclarations(project, resolveScope).flatMap {
ReferencesSearch.search(it, fileSearchScope)
.findAll()
.map { reference -> UsageContext(reference.element.createSmartPointer(), isExtension = isExtension) }
}
}
val elementInImportDirective = element.isInImportDirective()
val oldName = element.mainReference.value
val scopes = usages.mapNotNull {
val expression = it.pointer.element as? KtElement ?: return@mapNotNull null
expression.getResolutionScope(expression.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION))
}.distinct()
val validator = fun(name: String): Boolean {
if (oldName == name) return false
val identifier = Name.identifier(name)
return scopes.all { scope ->
scope.getAllAccessibleFunctions(identifier).isEmpty()
&& scope.getAllAccessibleVariables(identifier).isEmpty()
&& scope.findClassifier(identifier, NoLookupLocation.FROM_IDE) == null
&& scope.findPackage(identifier) == null
}
}
val suggestionsName = KotlinNameSuggester.suggestNamesByFqName(
fqName,
validator = validator,
defaultName = { fqName.asString().replace('.', '_') })
checkWithAttachment(suggestionsName.isNotEmpty(), { "Unable to build any suggestion name for $fqName" }) {
it.withPsiAttachment("file.kt", file)
}
val newName = suggestionsName.first()
suggestedImportAliasNames = suggestionsName
project.executeWriteCommand(KotlinBundle.message("intention.add.import.alias.group.name"), groupId = null) {
val newDirective = ImportInsertHelperImpl.addImport(project, file, fqName, false, Name.identifier(newName))
replaceUsages(usages, newName)
cleanImport(file, fqName)
if (elementInImportDirective) editor.moveCaret(newDirective.alias?.nameIdentifier?.textOffset ?: newDirective.endOffset)
invokeRename(project, editor, newDirective.alias, suggestionsName)
}
}
override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext?) {
if (file !is KtFile) return
selectElement(editor, file, listOf(CodeInsightUtils.ElementKind.EXPRESSION)) {
doRefactoring(project, editor, it as KtNameReferenceExpression)
}
}
override fun invoke(project: Project, elements: Array<out PsiElement>, dataContext: DataContext?) {
throw AssertionError("$REFACTORING_NAME can only be invoked from editor")
}
}
private data class UsageContext(val pointer: SmartPsiElementPointer<PsiElement>, val isExtension: Boolean)
private fun cleanImport(file: KtFile, fqName: FqName) {
file.importDirectives.find { it.alias == null && fqName == it.importedFqName }?.delete()
}
private fun invokeRename(
project: Project,
editor: Editor,
elementToRename: PsiNamedElement?,
suggestionsName: Collection<String>
) {
val pointer = if (elementToRename != null) SmartPointerManager.createPointer(elementToRename) else null
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.document)
val element = pointer?.element ?: return
val rename = VariableInplaceRenamer(element, editor, project)
rename.performInplaceRefactoring(LinkedHashSet(suggestionsName))
}
private fun replaceUsages(usages: List<UsageContext>, newName: String) {
// case: inner element
for (usage in usages.asReversed()) {
val reference = usage.pointer.element?.safeAs<KtElement>()?.mainReference?.takeUnless { it.isImportUsage() } ?: continue
val newExpression = reference.handleElementRename(newName) as? KtNameReferenceExpression ?: continue
if (usage.isExtension) {
newExpression.getQualifiedElementSelector()?.replace(newExpression)
continue
}
val qualifiedElement = newExpression.getQualifiedElement()
if (qualifiedElement != newExpression) {
val parent = newExpression.parent
if (parent is KtCallExpression || parent is KtUserType) {
newExpression.siblings(forward = false, withItself = false).forEach(PsiElement::delete)
qualifiedElement.replace(parent)
} else qualifiedElement.replace(newExpression)
}
}
} | apache-2.0 | cf768b9636b9ca7c2eb862e33f439f8b | 47.738854 | 158 | 0.739511 | 5.107477 | false | false | false | false |
Jamefrus/LibBinder | src/main/kotlin/su/jfdev/libbinder/Binding.kt | 1 | 2578 | package su.jfdev.libbinder
import groovy.lang.GroovyObject
import groovy.util.ConfigObject
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.net.URL
import java.util.*
object Binding {
@JvmStatic @JvmName("parse") operator
fun get(mapOf: Map<String, String>): BindProvider = BindProvider(mapOf)
@JvmStatic @JvmName("parse") operator
fun get(properties: Properties): BindProvider = get(properties.map {
it.key.toString() to it.value.toString()
}.toMap())
@JvmStatic @JvmName("parse") operator
fun get(configObject: ConfigObject) = get(configObject.toProperties())
@JvmStatic @JvmName("parse") operator
fun get(file: File, way: ParsingWay): BindProvider = way(file.readText())
@JvmStatic @JvmName("parse") operator
fun get(file: File): BindProvider = get(file, ParsingWay[file.extension])
@JvmStatic @JvmName("parse") operator
fun get(url: URL): BindProvider {
val extension = url.file.substringAfterLast('.', "")
return get(url, ParsingWay[extension])
}
fun file(path: String): BindProvider {
val file = detect(File(path)) ?: throw FileNotFoundException()
return get(file)
}
private fun detect(file: File?): File? {
if (file == null || file.exists()) return file
val parent = detect(file.absoluteFile.parentFile)
parent?.list()?.forEach {
if (it.startsWith(file.name)) return parent.resolve(it)
}
return null
}
@JvmStatic @JvmName("parse") operator
fun get(groovyObject: GroovyObject, vararg keys: String): BindProvider {
val map = keys.associate {
it to groovyObject.getProperty(it).toString()
}
return get(map)
}
@JvmStatic @JvmName("parse") operator
fun get(url: URL, way: ParsingWay): BindProvider {
val text: String
try {
text = url.readText()
url.cache = text
} catch(e: IOException) {
println("Can't load from URL. Check file cache.")
e.printStackTrace()
text = url.cache ?: throw e
}
return way(text)
}
private var URL.cache: String?
get() = cacheFile.readText()
set(value) {
if (value == null) cacheFile.delete()
else cacheFile.writeText(value)
}
private val URL.cacheFile: File get() = File(libbinderDirectory, this.toString().filter { it.isLetterOrDigit() })
var libbinderDirectory = File("libbinder").apply { mkdirs() }
}
| mit | 8197bb64176f0458113fa1010c765cbc | 30.439024 | 117 | 0.631885 | 4.219313 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/purchases/GiftBalanceGemsFragment.kt | 1 | 2774 | package com.habitrpg.android.habitica.ui.fragments.purchases
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.SocialRepository
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.models.members.Member
import com.habitrpg.android.habitica.ui.AvatarView
import com.habitrpg.android.habitica.ui.fragments.BaseFragment
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.social.UsernameLabel
import io.reactivex.functions.Consumer
import javax.inject.Inject
class GiftBalanceGemsFragment : BaseFragment() {
@Inject
lateinit var socialRepository: SocialRepository
private val avatarView: AvatarView by bindView(R.id.avatar_view)
private val displayNameTextView: UsernameLabel by bindView(R.id.display_name_textview)
private val usernameTextView: TextView by bindView(R.id.username_textview)
private val giftEditText: EditText by bindView(R.id.gift_edit_text)
private val giftButton: Button by bindView(R.id.gift_button)
var giftedMember: Member? = null
set(value) {
field = value
field?.let {
avatarView.setAvatar(it)
displayNameTextView.username = it.profile?.name
displayNameTextView.tier = it.contributor?.level ?: 0
usernameTextView.text = "@${it.username}"
}
}
var onCompleted: (() -> Unit)? = null
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
return container?.inflate(R.layout.fragment_gift_gem_balance)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
giftButton.setOnClickListener { sendGift() }
}
private fun sendGift() {
try {
val amount = giftEditText.text.toString().toInt()
giftedMember?.id?.let {
compositeSubscription.add(socialRepository.transferGems(it, amount).subscribe(Consumer {
onCompleted?.invoke()
}, RxErrorHandler.handleEmptyError()))
}
} catch (ignored: NumberFormatException) {}
}
} | gpl-3.0 | 1dabd66fa2fab6e9dad36d313e83cb69 | 38.084507 | 116 | 0.721341 | 4.654362 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddForLoopIndicesIntention.kt | 1 | 4833 | // 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.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
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.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.utils.ChooseStringExpression
class AddForLoopIndicesIntention : SelfTargetingRangeIntention<KtForExpression>(
KtForExpression::class.java,
KotlinBundle.lazyMessage("add.indices.to.for.loop"),
), LowPriorityAction {
override fun applicabilityRange(element: KtForExpression): TextRange? {
if (element.loopParameter == null) return null
if (element.loopParameter?.destructuringDeclaration != null) return null
val loopRange = element.loopRange ?: return null
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val resolvedCall = loopRange.getResolvedCall(bindingContext)
if (resolvedCall?.resultingDescriptor?.fqNameUnsafe?.asString() in WITH_INDEX_FQ_NAMES) return null // already withIndex() call
val potentialExpression = createWithIndexExpression(loopRange, reformat = false)
val newBindingContext = potentialExpression.analyzeAsReplacement(loopRange, bindingContext)
val newResolvedCall = potentialExpression.getResolvedCall(newBindingContext) ?: return null
if (newResolvedCall.resultingDescriptor.fqNameUnsafe.asString() !in WITH_INDEX_FQ_NAMES) return null
return TextRange(element.startOffset, element.body?.startOffset ?: element.endOffset)
}
override fun applyTo(element: KtForExpression, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val loopRange = element.loopRange!!
val loopParameter = element.loopParameter!!
val psiFactory = KtPsiFactory(element)
loopRange.replace(createWithIndexExpression(loopRange, reformat = true))
var multiParameter = (psiFactory.createExpressionByPattern(
"for((index, $0) in x){}",
loopParameter.text
) as KtForExpression).destructuringDeclaration!!
multiParameter = loopParameter.replaced(multiParameter)
val indexVariable = multiParameter.entries[0]
editor.caretModel.moveToOffset(indexVariable.startOffset)
runTemplate(editor, element, indexVariable)
}
private fun runTemplate(editor: Editor, forExpression: KtForExpression, indexVariable: KtDestructuringDeclarationEntry) {
PsiDocumentManager.getInstance(forExpression.project).doPostponedOperationsAndUnblockDocument(editor.document)
val templateBuilder = TemplateBuilderImpl(forExpression)
templateBuilder.replaceElement(indexVariable, ChooseStringExpression(listOf("index", "i")))
when (val body = forExpression.body) {
is KtBlockExpression -> {
val statement = body.statements.firstOrNull()
if (statement != null) {
templateBuilder.setEndVariableBefore(statement)
} else {
templateBuilder.setEndVariableAfter(body.lBrace)
}
}
null -> forExpression.rightParenthesis.let { templateBuilder.setEndVariableAfter(it) }
else -> templateBuilder.setEndVariableBefore(body)
}
templateBuilder.run(editor, true)
}
private fun createWithIndexExpression(originalExpression: KtExpression, reformat: Boolean): KtExpression =
KtPsiFactory(originalExpression).createExpressionByPattern(
"$0.$WITH_INDEX_NAME()", originalExpression,
reformat = reformat
)
companion object {
private val WITH_INDEX_NAME = "withIndex"
private val WITH_INDEX_FQ_NAMES: Set<String> by lazy {
sequenceOf("collections", "sequences", "text", "ranges").map { "kotlin.$it.$WITH_INDEX_NAME" }.toSet()
}
}
}
| apache-2.0 | 0f7a77b7372dc725342663016958d614 | 45.92233 | 158 | 0.737016 | 5.185622 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/resolve/ProjectResolutionFacade.kt | 1 | 9212 | // 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.caches.resolve
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.containers.SLRUCache
import org.jetbrains.kotlin.analyzer.*
import org.jetbrains.kotlin.caches.resolve.PlatformAnalysisSettings
import org.jetbrains.kotlin.context.GlobalContextImpl
import org.jetbrains.kotlin.context.withProject
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.CompositeBindingContext
import org.jetbrains.kotlin.storage.CancellableSimpleLock
import org.jetbrains.kotlin.storage.guarded
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.util.concurrent.locks.ReentrantLock
internal class ProjectResolutionFacade(
private val debugString: String,
private val resolverDebugName: String,
val project: Project,
val globalContext: GlobalContextImpl,
val settings: PlatformAnalysisSettings,
val reuseDataFrom: ProjectResolutionFacade?,
val moduleFilter: (IdeaModuleInfo) -> Boolean,
dependencies: List<Any>,
private val invalidateOnOOCB: Boolean,
val syntheticFiles: Collection<KtFile> = listOf(),
val allModules: Collection<IdeaModuleInfo>? = null // null means create resolvers for modules from idea model
) {
private val cachedValue = CachedValuesManager.getManager(project).createCachedValue(
{
val resolverProvider = computeModuleResolverProvider()
CachedValueProvider.Result.create(resolverProvider, resolverForProjectDependencies)
},
/* trackValue = */ false
)
private val cachedResolverForProject: ResolverForProject<IdeaModuleInfo>
get() = globalContext.storageManager.compute { cachedValue.value }
private val analysisResultsLock = ReentrantLock()
private val analysisResultsSimpleLock = CancellableSimpleLock(analysisResultsLock,
checkCancelled = {
ProgressManager.checkCanceled()
},
interruptedExceptionHandler = { throw ProcessCanceledException(it) })
private val analysisResults = CachedValuesManager.getManager(project).createCachedValue(
{
val resolverForProject = cachedResolverForProject
val results = object : SLRUCache<KtFile, PerFileAnalysisCache>(2, 3) {
private val lock = ReentrantLock()
override fun createValue(file: KtFile): PerFileAnalysisCache {
return PerFileAnalysisCache(
file,
resolverForProject.resolverForModule(file.getModuleInfo()).componentProvider
)
}
override fun get(key: KtFile?): PerFileAnalysisCache {
lock.lock()
try {
val cache = super.get(key)
if (cache.isValid) {
return cache
}
remove(key)
return super.get(key)
} finally {
lock.unlock()
}
}
override fun getIfCached(key: KtFile?): PerFileAnalysisCache? {
if (lock.tryLock()) {
try {
return super.getIfCached(key)
} finally {
lock.unlock()
}
}
return null
}
}
val allDependencies = resolverForProjectDependencies + listOf(
KotlinCodeBlockModificationListener.getInstance(project).kotlinOutOfCodeBlockTracker
)
CachedValueProvider.Result.create(results, allDependencies)
}, false
)
private val resolverForProjectDependencies = dependencies + listOf(globalContext.exceptionTracker)
private fun computeModuleResolverProvider(): ResolverForProject<IdeaModuleInfo> {
val delegateResolverForProject: ResolverForProject<IdeaModuleInfo> =
reuseDataFrom?.cachedResolverForProject ?: EmptyResolverForProject()
val allModuleInfos = (allModules ?: getModuleInfosFromIdeaModel(project, (settings as? PlatformAnalysisSettingsImpl)?.platform))
.toMutableSet()
val syntheticFilesByModule = syntheticFiles.groupBy(KtFile::getModuleInfo)
val syntheticFilesModules = syntheticFilesByModule.keys
allModuleInfos.addAll(syntheticFilesModules)
val modulesToCreateResolversFor = allModuleInfos.filter(moduleFilter)
return IdeaResolverForProject(
resolverDebugName,
globalContext.withProject(project),
modulesToCreateResolversFor,
syntheticFilesByModule,
delegateResolverForProject,
if (invalidateOnOOCB) KotlinModificationTrackerService.getInstance(project).outOfBlockModificationTracker else null,
settings
)
}
internal fun resolverForModuleInfo(moduleInfo: IdeaModuleInfo) = cachedResolverForProject.resolverForModule(moduleInfo)
internal fun resolverForElement(element: PsiElement): ResolverForModule {
val infos = element.getModuleInfos()
return infos.asIterable().firstNotNullResult { cachedResolverForProject.tryGetResolverForModule(it) }
?: cachedResolverForProject.tryGetResolverForModule(NotUnderContentRootModuleInfo)
?: cachedResolverForProject.diagnoseUnknownModuleInfo(infos.toList())
}
internal fun resolverForDescriptor(moduleDescriptor: ModuleDescriptor) =
cachedResolverForProject.resolverForModuleDescriptor(moduleDescriptor)
internal fun findModuleDescriptor(ideaModuleInfo: IdeaModuleInfo): ModuleDescriptor {
return cachedResolverForProject.descriptorForModule(ideaModuleInfo)
}
internal fun getResolverForProject(): ResolverForProject<IdeaModuleInfo> = cachedResolverForProject
internal fun getAnalysisResultsForElements(
elements: Collection<KtElement>,
callback: DiagnosticSink.DiagnosticsCallback? = null
): AnalysisResult {
assert(elements.isNotEmpty()) { "elements collection should not be empty" }
val cache = analysisResultsSimpleLock.guarded {
analysisResults.value!!
}
val results =
elements.map {
val containingKtFile = it.containingKtFile
val perFileCache = cache[containingKtFile]
try {
perFileCache.getAnalysisResults(it, callback)
} catch (e: Throwable) {
if (e is ControlFlowException) {
throw e
}
val actualCache = analysisResultsSimpleLock.guarded {
analysisResults.upToDateOrNull?.get()
}
if (cache !== actualCache) {
throw IllegalStateException("Cache has been invalidated during performing analysis for $containingKtFile", e)
}
throw e
}
}
val withError = results.firstOrNull { it.isError() }
val bindingContext = CompositeBindingContext.create(results.map { it.bindingContext })
if (withError != null) {
return AnalysisResult.internalError(bindingContext, withError.error)
}
//TODO: (module refactoring) several elements are passed here in debugger
return AnalysisResult.success(bindingContext, findModuleDescriptor(elements.first().getModuleInfo()))
}
internal fun fetchAnalysisResultsForElement(element: KtElement): AnalysisResult? {
val slruCache = if (analysisResultsLock.tryLock()) {
try {
analysisResults.upToDateOrNull?.get()
} finally {
analysisResultsLock.unlock()
}
} else null
return slruCache?.getIfCached(element.containingKtFile)?.fetchAnalysisResults(element)
}
override fun toString(): String {
return "$debugString@${Integer.toHexString(hashCode())}"
}
}
| apache-2.0 | 8b878ffb8f115d68c96922cf382b9f91 | 43.936585 | 158 | 0.653604 | 6.048588 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/IDESettingsFUSCollector.kt | 1 | 3746 | // 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
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfoById
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.base.util.KotlinPlatformUtils
import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightSettings
import org.jetbrains.kotlin.idea.codeInsight.KotlinCodeInsightWorkspaceSettings
import org.jetbrains.kotlin.idea.compiler.configuration.KotlinIdePlugin
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
class IDESettingsFUSCollector : ProjectUsagesCollector() {
override fun getGroup() = GROUP
override fun getMetrics(project: Project): Set<MetricEvent> {
if (KotlinPlatformUtils.isAndroidStudio) {
return emptySet()
}
val metrics = mutableSetOf<MetricEvent>()
val pluginInfo = getPluginInfoById(KotlinIdePlugin.id)
// filling up scriptingAutoReloadEnabled Event
for (definition in ScriptDefinitionsManager.getInstance(project).getAllDefinitions()) {
if (definition.canAutoReloadScriptConfigurationsBeSwitchedOff) {
val scriptingAutoReloadEnabled = KotlinScriptingSettings.getInstance(project).autoReloadConfigurations(definition)
metrics.add(scriptingAREvent.metric(definition.name, scriptingAutoReloadEnabled, pluginInfo))
}
}
val settings: KotlinCodeInsightSettings = KotlinCodeInsightSettings.getInstance()
val projectSettings: KotlinCodeInsightWorkspaceSettings = KotlinCodeInsightWorkspaceSettings.getInstance(project)
// filling up addUnambiguousImportsOnTheFly and optimizeImportsOnTheFly Events
metrics.add(unambiguousImportsEvent.metric(settings.addUnambiguousImportsOnTheFly, pluginInfo))
metrics.add(optimizeImportsEvent.metric(projectSettings.optimizeImportsOnTheFly, pluginInfo))
return metrics
}
companion object {
private val GROUP = EventLogGroup("kotlin.ide.settings", 4)
// scriptingAutoReloadEnabled Event
private val scriptingAREnabledField = EventFields.Boolean("enabled")
private val scriptingDefNameField = EventFields.String(
"definition_name", listOf(
"KotlinInitScript",
"KotlinSettingsScript",
"KotlinBuildScript",
"Script_definition_for_extension_scripts_and_IDE_console",
"MainKtsScript",
"Kotlin_Script",
"Space_Automation"
)
)
private val scriptingPluginInfoField = EventFields.PluginInfo
private val scriptingAREvent = GROUP.registerEvent(
"scriptingAutoReloadEnabled",
scriptingDefNameField,
scriptingAREnabledField,
scriptingPluginInfoField
)
// addUnambiguousImportsOnTheFly Event
private val unambiguousImportsEvent =
GROUP.registerEvent("addUnambiguousImportsOnTheFly", EventFields.Boolean("enabled"), EventFields.PluginInfo)
// optimizeImportsOnTheFly Event
private val optimizeImportsEvent =
GROUP.registerEvent("optimizeImportsOnTheFly", EventFields.Boolean("enabled"), EventFields.PluginInfo)
}
}
| apache-2.0 | e85bd6e98960130bc9cf577ad9a58a64 | 45.825 | 158 | 0.738388 | 5.516937 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/sync/LongSyncTest.kt | 1 | 18660 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.sync
import org.ethereum.config.NoAutoscan
import org.ethereum.config.SystemProperties
import org.ethereum.core.*
import org.ethereum.facade.Ethereum
import org.ethereum.facade.EthereumFactory
import org.ethereum.listener.EthereumListenerAdapter
import org.ethereum.net.eth.handler.Eth62
import org.ethereum.net.eth.handler.EthHandler
import org.ethereum.net.eth.message.*
import org.ethereum.net.message.Message
import org.ethereum.net.p2p.DisconnectMessage
import org.ethereum.net.rlpx.Node
import org.ethereum.net.server.Channel
import org.ethereum.util.FileUtil.recursiveDelete
import org.ethereum.util.blockchain.StandaloneBlockchain
import org.junit.*
import org.junit.Assert.fail
import org.spongycastle.util.encoders.Hex.decode
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Scope
import java.io.File
import java.io.IOException
import java.math.BigInteger
import java.net.URISyntaxException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit.SECONDS
/**
* @author Mikhail Kalinin
* *
* @since 14.12.2015
*/
@Ignore("Long network tests")
open class LongSyncTest {
private var ethereumA: Ethereum? = null
private var ethereumB: Ethereum? = null
private var ethA: EthHandler? = null
private var testDbA: String? = null
private var testDbB: String? = null
@Before
@Throws(InterruptedException::class)
fun setupTest() {
testDbA = "test_db_" + BigInteger(32, Random())
testDbB = "test_db_" + BigInteger(32, Random())
SysPropConfigA.props.setDataBaseDir(testDbA)
SysPropConfigB.props.setDataBaseDir(testDbB)
}
@After
fun cleanupTest() {
recursiveDelete(testDbA)
recursiveDelete(testDbB)
SysPropConfigA.eth62 = null
}
// general case, A has imported 10 blocks
// expected: B downloads blocks from A => B synced
@Test
@Throws(InterruptedException::class)
fun test1() {
setupPeers()
// A == b10, B == genesis
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onBlock(block: Block, receipts: List<TransactionReceipt>) {
if (block.isEqual(b10)) {
semaphore.countDown()
}
}
})
semaphore.await(40, SECONDS)
// check if B == b10
if (semaphore.count > 0) {
fail("PeerB bestBlock is incorrect")
}
}
// bodies validation: A doesn't send bodies for blocks lower than its best block
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test2() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockBodies(msg: GetBlockBodiesMessage) {
val bodies = Arrays.asList<ByteArray>(
mainB1B10!![0].encodedBody
)
val response = BlockBodiesMessage(bodies)
sendMessage(response)
}
}
setupPeers()
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// headers validation: headers count in A respond more than requested limit
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test3() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (Arrays.equals(msg.blockIdentifier.hash, b10!!.hash)) {
super.processGetBlockHeaders(msg)
return
}
val headers = Arrays.asList(
mainB1B10!![0].header,
mainB1B10!![1].header,
mainB1B10!![2].header,
mainB1B10!![3].header
)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// headers validation: A sends empty response
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test4() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (Arrays.equals(msg.blockIdentifier.hash, b10!!.hash)) {
super.processGetBlockHeaders(msg)
return
}
val headers = emptyList<BlockHeader>()
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// headers validation: first header in response doesn't meet expectations
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test5() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (Arrays.equals(msg.blockIdentifier.hash, b10!!.hash)) {
super.processGetBlockHeaders(msg)
return
}
val headers = Arrays.asList(
mainB1B10!![1].header,
mainB1B10!![2].header,
mainB1B10!![3].header
)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// headers validation: first header in response doesn't meet expectations - second story
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test6() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
val headers = listOf(mainB1B10!![1].header)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
ethereumA = EthereumFactory.createEthereum(SysPropConfigA.props, SysPropConfigA::class.java)
val blockchainA = ethereumA!!.blockchain as Blockchain
for (b in mainB1B10!!) {
blockchainA.tryToConnect(b)
}
// A == b10
ethereumB = EthereumFactory.createEthereum(SysPropConfigB.props, SysPropConfigB::class.java)
ethereumB!!.connect(nodeA!!)
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// headers validation: headers order is incorrect, reverse = false
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test7() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (Arrays.equals(msg.blockIdentifier.hash, b10!!.hash)) {
super.processGetBlockHeaders(msg)
return
}
val headers = Arrays.asList(
mainB1B10!![0].header,
mainB1B10!![2].header,
mainB1B10!![1].header
)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
// headers validation: ancestor's parent hash and header's hash does not match, reverse = false
// expected: B drops A
@Test
@Throws(InterruptedException::class)
fun test8() {
SysPropConfigA.eth62 = object : Eth62() {
override fun processGetBlockHeaders(msg: GetBlockHeadersMessage) {
if (Arrays.equals(msg.blockIdentifier.hash, b10!!.hash)) {
super.processGetBlockHeaders(msg)
return
}
val headers = Arrays.asList(
mainB1B10!![0].header,
BlockHeader(ByteArray(32), ByteArray(32), ByteArray(32), ByteArray(32), ByteArray(32),
2, byteArrayOf(0), 0, 0, ByteArray(0), ByteArray(0), ByteArray(0)),
mainB1B10!![2].header
)
val response = BlockHeadersMessage(headers)
sendMessage(response)
}
}
setupPeers()
// A == b10, B == genesis
val semaphoreDisconnect = CountDownLatch(1)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onRecvMessage(channel: Channel, message: Message) {
if (message is DisconnectMessage) {
semaphoreDisconnect.countDown()
}
}
})
semaphoreDisconnect.await(10, SECONDS)
// check if peer was dropped
if (semaphoreDisconnect.count > 0) {
fail("PeerA is not dropped")
}
}
@Throws(InterruptedException::class)
private fun setupPeers(best: Block? = b10) {
ethereumA = EthereumFactory.createEthereum(SysPropConfigA::class.java)
val blockchainA = ethereumA!!.blockchain as Blockchain
for (b in mainB1B10!!) {
val result = blockchainA.tryToConnect(b)
Assert.assertEquals(result, ImportResult.IMPORTED_BEST)
if (b == best) break
}
// A == best
ethereumB = EthereumFactory.createEthereum(SysPropConfigB.props, SysPropConfigB::class.java)
ethereumA!!.addListener(object : EthereumListenerAdapter() {
override fun onEthStatusUpdated(channel: Channel, statusMessage: StatusMessage) {
ethA = channel.ethHandler as EthHandler
}
})
val semaphore = CountDownLatch(1)
ethereumB!!.addListener(object : EthereumListenerAdapter() {
override fun onPeerAddedToSyncPool(peer: Channel) {
semaphore.countDown()
}
})
ethereumB!!.connect(nodeA!!)
semaphore.await(10, SECONDS)
if (semaphore.count > 0) {
fail("Failed to set up peers")
}
}
@Configuration
@NoAutoscan
open class SysPropConfigA {
@Bean
open fun systemProperties(): SystemProperties {
return props
}
@Bean
@Scope("prototype")
@Throws(IllegalAccessException::class, InstantiationException::class)
open fun eth62(): Eth62 {
if (eth62 != null) return eth62!!
return Eth62()
}
companion object {
internal val props = SystemProperties()
internal var eth62: Eth62? = null
}
}
@Configuration
@NoAutoscan
open class SysPropConfigB {
@Bean
open fun systemProperties(): SystemProperties {
return props
}
companion object {
internal val props = SystemProperties()
}
}
companion object {
private var nodeA: Node? = null
private var mainB1B10: List<Block>? = null
private var b10: Block? = null
@BeforeClass
@Throws(IOException::class, URISyntaxException::class)
fun setup() {
nodeA = Node("enode://3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6@localhost:30334")
SysPropConfigA.props.overrideParams(
"peer.listen.port", "30334",
"peer.privateKey", "3ec771c31cac8c0dba77a69e503765701d3c2bb62435888d4ffa38fed60c445c",
// nodeId: 3973cb86d7bef9c96e5d589601d788370f9e24670dcba0480c0b3b1b0647d13d0f0fffed115dd2d4b5ca1929287839dcd4e77bdc724302b44ae48622a8766ee6
"genesis", "genesis-light-old.json"
)
SysPropConfigA.props.blockchainConfig = StandaloneBlockchain.getEasyMiningConfig()
SysPropConfigB.props.overrideParams(
"peer.listen.port", "30335",
"peer.privateKey", "6ef8da380c27cea8fdf7448340ea99e8e2268fc2950d79ed47cbf6f85dc977ec",
"genesis", "genesis-light-old.json",
"sync.enabled", "true",
"sync.max.hashes.ask", "3",
"sync.max.blocks.ask", "2"
)
SysPropConfigB.props.blockchainConfig = StandaloneBlockchain.getEasyMiningConfig()
/*
1 => ed1b6f07d738ad92c5bdc3b98fe25afea9c863dd351711776d9ce1ffb9e3d276
2 => 43808666b662d131c6cff336a0d13608767ead9c9d5f181e95caa3597f3faf14
3 => 1b5c231211f500bc73148dc9d9bdb9de2265465ba441a0db1790ba4b3f5f3e9c
4 => db517e04399dbf5a65caf6b2572b3966c8f98a1d29b1e50dc8db51e54c15d83d
5 => c42d6dbaa756eda7f4244a3507670d764232bd7068d43e6d8ef680c6920132f6
6 => 604c92e8d16dafb64134210d521fcc85aec27452e75aedf708ac72d8240585d3
7 => 3f51b0471eb345b1c5f3c6628e69744358ff81d3f64a3744bbb2edf2adbb0ebc
8 => 62cfd04e29d941954e68ac8ca18ef5cd78b19809eaed860ae72589ebad53a21d
9 => d32fc8e151f158d52fe0be6cba6d0b5c20793a00c4ad0d32db8ccd9269199a29
10 => 22d8c1d909eb142ea0d69d0a38711874f98d6eef1bc669836da36f6b557e9564
*/
mainB1B10 = loadBlocks("sync/main-b1-b10.dmp")
b10 = mainB1B10!![mainB1B10!!.size - 1]
}
@Throws(URISyntaxException::class, IOException::class)
private fun loadBlocks(path: String): List<Block> {
val url = ClassLoader.getSystemResource(path)
val file = File(url.toURI())
val strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8)
val blocks = ArrayList<Block>(strData.size)
strData.mapTo(blocks) { Block(decode(it)) }
return blocks
}
@AfterClass
fun cleanup() {
SystemProperties.resetToDefault()
}
}
}
| mit | b1f80d97c0d11c216fd980271ba3147f | 30.897436 | 180 | 0.601661 | 4.275894 | false | true | false | false |
jwren/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/framework/JsLibraryStdDetectionUtil.kt | 1 | 2844 | // 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.framework
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.io.JarUtil
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifactNames
import org.jetbrains.kotlin.idea.compiler.configuration.IdeKotlinVersion
import org.jetbrains.kotlin.utils.LibraryUtils
import org.jetbrains.kotlin.utils.PathUtil
import java.io.File
import java.util.jar.Attributes
object JsLibraryStdDetectionUtil {
private val IS_JS_LIBRARY_STD_LIB = Key.create<Boolean>("IS_JS_LIBRARY_STD_LIB")
fun hasJsStdlibJar(library: Library, project: Project, ignoreKind: Boolean = false): Boolean {
if (library !is LibraryEx || library.isDisposed) return false
if (!ignoreKind && library.effectiveKind(project) !is JSLibraryKind) return false
val classes = listOf(*library.getFiles(OrderRootType.CLASSES))
return getJsStdLibJar(classes) != null
}
fun getJsLibraryStdVersion(library: Library, project: Project): IdeKotlinVersion? {
if ((library as LibraryEx).effectiveKind(project) !is JSLibraryKind) return null
val jar = getJsStdLibJar(library.getFiles(OrderRootType.CLASSES).toList()) ?: return null
return IdeKotlinVersion.fromManifest(jar)
}
fun getJsStdLibJar(classesRoots: List<VirtualFile>): VirtualFile? {
for (root in classesRoots) {
if (root.fileSystem.protocol !== StandardFileSystems.JAR_PROTOCOL) continue
val name = root.url.substringBefore("!/").substringAfterLast('/')
if (name == KotlinArtifactNames.KOTLIN_STDLIB_JS
|| name == "kotlin-jslib.jar" // Outdated JS stdlib name
|| PathUtil.KOTLIN_STDLIB_JS_JAR_PATTERN.matcher(name).matches()
|| PathUtil.KOTLIN_JS_LIBRARY_JAR_PATTERN.matcher(name).matches()
) {
val jar = VfsUtilCore.getVirtualFileForJar(root) ?: continue
var isJSStdLib = jar.getUserData(IS_JS_LIBRARY_STD_LIB)
if (isJSStdLib == null) {
isJSStdLib = LibraryUtils.isKotlinJavascriptStdLibrary(File(jar.path))
jar.putUserData(IS_JS_LIBRARY_STD_LIB, isJSStdLib)
}
if (isJSStdLib) {
return jar
}
}
}
return null
}
}
| apache-2.0 | 4916f7515fb204af6bce578dd5e15250 | 43.4375 | 158 | 0.694796 | 4.348624 | false | false | false | false |
josecefe/Rueda | src/es/um/josecefe/rueda/resolutor/ResolutorSimple.kt | 1 | 10393 | /*
* Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero
*
* 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 es.um.josecefe.rueda.resolutor
import es.um.josecefe.rueda.modelo.*
import es.um.josecefe.rueda.util.Combinador
import es.um.josecefe.rueda.util.SubSets
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicLong
import java.util.concurrent.atomic.AtomicStampedReference
import kotlin.math.max
import kotlin.math.roundToInt
import kotlin.system.measureTimeMillis
class ResolutorSimple : Resolutor() {
companion object {
private const val DEBUG = true
private const val ESTADISTICAS = true
private const val CADA_EXPANDIDOS_EST = 1000000
private const val UMBRAL_PARALELO = 100
}
private val estGlobal = EstadisticasV8()
override var solucionFinal: Map<Dia, AsignacionDia> = emptyMap()
private set
override fun resolver(horarios: Set<Horario>): Map<Dia, AsignacionDia> {
solucionFinal = emptyMap()
if (horarios.isEmpty()) {
return solucionFinal
}
if (ESTADISTICAS) {
estGlobal.inicia()
}
/* Inicialización */
continuar = true
val contexto = ContextoResolucionSimple(horarios)
/* Fin inicialización */
if (ESTADISTICAS) {
estGlobal.totalPosiblesSoluciones = 0.0
estGlobal.actualizaProgreso()
if (DEBUG) println("Tiempo inicializar = ${estGlobal.tiempoString}")
}
val solucionRef = AtomicStampedReference(solucionFinal, Int.MAX_VALUE)
// SECUENCIAL: var mejorCoste = Double.POSITIVE_INFINITY
//Vamos a ir buscando soluciones de menos veces al tope de veces
for (nivel in contexto.minCond..contexto.dias.size) {
if (solucionRef.stamp < Int.MAX_VALUE) {
//SECUENCIAL: if (!mejorCoste.isInfinite()) {
if (ESTADISTICAS) estGlobal.actualizaProgreso()
if (DEBUG) println("** No examinamos el nivel $nivel al tener ya una solución de un nivel anterior **")
break
} // Hemos terminado
if (!continuar) {
if (DEBUG) println("*** No vamos a examinar el nivel $nivel al haberse interrumpido la resolución ***")
break
}
if (DEBUG) println("* Iniciando examen del nivel $nivel con un total de ${contexto.getSolucionesNivel(
nivel)} en este nivel *")
if (ESTADISTICAS) estGlobal.totalPosiblesSoluciones += contexto.getSolucionesNivel(nivel)
val listSubcon: MutableList<List<Set<Dia>>> = ArrayList(contexto.mapParticipanteDias.size)
for ((key, value) in contexto.mapParticipanteDias) {
val numVecesCond = max(1, (nivel.toDouble() / contexto.coefConduccion.getValue(key)).roundToInt()) - (contexto.diasFijos[key]?.size ?: 0)//Para minorar adecuadamente el valor de i usando el coeficiente de conductor
val diasCambiantes: Set<Dia> = if (contexto.diasFijos[key] != null) value.minus(
contexto.diasFijos.getValue(key)) else value
listSubcon.add(SubSets(diasCambiantes, numVecesCond, numVecesCond).map {
if (contexto.diasFijos[key] != null) contexto.diasFijos.getValue(key).plus(it) else it
})
}
val combinaciones: Combinador<Set<Dia>> = Combinador(listSubcon)
var contador = 0L
val valida = AtomicLong()
if (DEBUG) {
println("Contando (sin generar nada):")
val tiempo = measureTimeMillis {
val solucionesNivel = contexto.getSolucionesNivel(nivel)
for (c in 1..solucionesNivel) {
if (++contador % 10000000L == 0L) {
print(".")
if (contador % 1000000000L == 0L) println("#$contador")
}
}
}
println(" ---> Soluciones a generar del nivel $nivel: ${combinaciones.size}, tiempo base $tiempo ms")
}
if (DEBUG) {
println("Contando (generando):")
contador = 0L
val tiempo = measureTimeMillis {
for (c in combinaciones) {
if (++contador % 10000000L == 0L) {
print(".")
if (contador % 1000000000L == 0L) println("#$contador")
}
}
}
println(" ---> Soluciones a generar del nivel $nivel: ${combinaciones.size}, tiempo base $tiempo ms")
}
runBlocking {
val jobs: MutableList<Job> = mutableListOf()
for (c in combinaciones) {
if (DEBUG) contador++
if (!continuar) break
jobs.add(launch {
val asignacion: MutableMap<Dia, MutableSet<Participante>> = HashMap()
val participaIt = contexto.mapParticipanteDias.keys.iterator()
for (e: Set<Dia> in c) {
val p = participaIt.next()
for (dia in e) {
var participantesSet = asignacion[dia]
if (participantesSet == null) {
participantesSet = HashSet()
asignacion[dia] = participantesSet
}
participantesSet.add(p)
}
}
if (asignacion.size < contexto.solucionesCandidatas.size) {
if (ESTADISTICAS) {
estGlobal.incExpandidos()
estGlobal.addDescartados(1.0)
}
return@launch
}
val solCand = HashMap<Dia, AsignacionDiaSimple>()
for ((dia, participantesDia) in asignacion) {
val sol = contexto.mapaParticipantesSoluciones[dia]?.get(
participantesDia) ?: break // Aquí se queda en blanco, luego no sirve
solCand[dia] = sol
}
// Para ver si es valida bastaria con ver si hay solución en cada día
if (solCand.size == contexto.solucionesCandidatas.size) {
if (DEBUG) valida.incrementAndGet()
if (ESTADISTICAS) estGlobal.addTerminales(1.0)
val apt = nivel * PESO_MAXIMO_VECES_CONDUCTOR
var costeAnt: Int
var solAnt: Map<Dia, AsignacionDia>
do {
costeAnt = solucionRef.stamp
solAnt = solucionRef.reference
} while (apt < costeAnt && !solucionRef.compareAndSet(solAnt, solCand, costeAnt, apt))
if (apt < costeAnt) {
if (DEBUG) println(
"---> Encontrada una mejora: Coste anterior = $costeAnt, nuevo coste = ${solucionRef.stamp}, sol = ${solucionRef.reference}")
if (ESTADISTICAS) {
estGlobal.fitness = solucionRef.stamp
estGlobal.actualizaProgreso()
}
}
continuar = false // No necesitamos seguir
} else {
if (ESTADISTICAS) estGlobal.addDescartados(1.0)
}
if (ESTADISTICAS && estGlobal.incExpandidos() % CADA_EXPANDIDOS_EST == 0L) {
estGlobal.actualizaProgreso()
if (DEBUG) println(estGlobal)
}
})
if (jobs.size > UMBRAL_PARALELO) {
jobs.forEach { it.join() }
jobs.clear()
}
}
if (jobs.isNotEmpty()) {
jobs.forEach { it.join() }
jobs.clear()
}
}
if (DEBUG) println(
" ---> $contador combinaciones generadas en total para este nivel, de las cuales $valida han sido validas")
}
solucionFinal = solucionRef.reference
//Estadisticas finales
if (ESTADISTICAS) {
estGlobal.fitness = solucionRef.stamp
estGlobal.actualizaProgreso()
if (DEBUG) {
println("====================")
println("Estadísticas finales")
println("====================")
println(estGlobal)
println("Solución final=$solucionFinal")
println("-----------------------------------------------")
}
}
return solucionFinal
}
//private fun calculaAptitud(sol: Map<Dia, AsignacionDia>, vecesCond: Int) = vecesCond * PESO_MAXIMO_VECES_CONDUCTOR
override val estadisticas: Estadisticas
get() = estGlobal
override var estrategia
get() = Estrategia.EQUILIBRADO
set(@Suppress("UNUSED_PARAMETER") value) { /* Nada */
}
} | gpl-3.0 | 6196cf8f910bbf1162e14ebaf5922443 | 44.548246 | 242 | 0.514542 | 4.921327 | false | false | false | false |
nielsutrecht/adventofcode | src/main/kotlin/com/nibado/projects/advent/collect/SummedAreaTable.kt | 1 | 1848 | package com.nibado.projects.advent.collect
import com.nibado.projects.advent.Point
// https://en.wikipedia.org/wiki/Summed-area_table
class SummedAreaTable private constructor(private val table: List<IntArray>) {
private fun get(p: Point) = get(p.x, p.y)
private fun get(x: Int, y: Int) = if(x < 0 || y < 0) { 0 } else table[y][x]
fun get(a: Point, b: Point) = get(a.x, a.y, b.x, b.y)
fun get(x1: Int, y1: Int, x2: Int, y2: Int): Int {
val a = Point(x1 - 1, y1 - 1)
val b = Point(x2, y1 - 1)
val c = Point(x1 - 1, y2)
val d = Point(x2, y2)
return get(a) + get(d) - get(b) - get(c)
}
override fun toString() = toString(4)
fun toString(width: Int): String {
val b = StringBuilder()
for (y in table.indices) {
for (x in table[0].indices) {
b.append("%1\$${width}s".format(table[y][x]))
}
b.append('\n')
}
return b.toString()
}
companion object {
fun from(table: List<IntArray>): SummedAreaTable {
return SummedAreaTable(build(table))
}
private fun build(table: List<IntArray>) : List<IntArray> {
val output = table.indices.map { IntArray(table[0].size) }.toList()
for (y in table.indices) {
for (x in table[0].indices) {
output[y][x] = table[y][x]
if (y > 0)
output[y][x] += output[y - 1][x]
if (x > 0) {
output[y][x] += output[y][x - 1]
if (y > 0)
output[y][x] -= output[y - 1][x - 1] // because this is added twice in above two additions
}
}
}
return output
}
}
}
| mit | 7d3ac81dface6352260e465bf1e2ce41 | 27.875 | 118 | 0.475649 | 3.415896 | false | false | false | false |
androidx/androidx | wear/watchface/watchface/src/main/java/androidx/wear/watchface/XmlSchemaAndComplicationSlotsDefinition.kt | 3 | 12314 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.wear.watchface
import android.content.pm.PackageManager
import android.content.res.Resources
import android.content.res.XmlResourceParser
import android.os.Bundle
import androidx.annotation.RestrictTo
import androidx.wear.watchface.complications.ComplicationSlotBounds
import androidx.wear.watchface.complications.DefaultComplicationDataSourcePolicy
import androidx.wear.watchface.complications.NAMESPACE_APP
import androidx.wear.watchface.complications.data.ComplicationExperimental
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.getIntRefAttribute
import androidx.wear.watchface.complications.getStringRefAttribute
import androidx.wear.watchface.complications.hasValue
import androidx.wear.watchface.complications.moveToStart
import androidx.wear.watchface.style.CurrentUserStyleRepository
import androidx.wear.watchface.style.UserStyleFlavors
import androidx.wear.watchface.style.UserStyleSchema
import org.xmlpull.v1.XmlPullParser
import kotlin.jvm.Throws
/** @hide */
@OptIn(ComplicationExperimental::class)
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class XmlSchemaAndComplicationSlotsDefinition(
val schema: UserStyleSchema?,
val complicationSlots: List<ComplicationSlotStaticData>,
val flavors: UserStyleFlavors?
) {
companion object {
@Throws(PackageManager.NameNotFoundException::class)
public fun inflate(
resources: Resources,
parser: XmlResourceParser
): XmlSchemaAndComplicationSlotsDefinition {
parser.moveToStart("XmlWatchFace")
val complicationScaleX =
parser.getAttributeFloatValue(NAMESPACE_APP, "complicationScaleX", 1.0f)
val complicationScaleY =
parser.getAttributeFloatValue(NAMESPACE_APP, "complicationScaleY", 1.0f)
require(complicationScaleX > 0) { "complicationScaleX should be positive" }
require(complicationScaleY > 0) { "complicationScaleY should be positive" }
var schema: UserStyleSchema? = null
var flavors: UserStyleFlavors? = null
val outerDepth = parser.depth
var type = parser.next()
// Parse the XmlWatchFace declaration.
val complicationSlots = ArrayList<ComplicationSlotStaticData>()
do {
if (type == XmlPullParser.START_TAG) {
when (parser.name) {
"UserStyleSchema" -> {
schema = UserStyleSchema.inflate(
resources,
parser,
complicationScaleX,
complicationScaleY
)
}
"ComplicationSlot" -> {
complicationSlots.add(
ComplicationSlotStaticData.inflate(
resources,
parser,
complicationScaleX,
complicationScaleY
)
)
}
"UserStyleFlavors" -> {
require(schema != null) {
"A UserStyleFlavors node requires a previous UserStyleSchema node"
}
flavors = UserStyleFlavors.inflate(resources, parser, schema)
}
else -> throw IllegalArgumentException(
"Unexpected node ${parser.name} at line ${parser.lineNumber}"
)
}
}
type = parser.next()
} while (type != XmlPullParser.END_DOCUMENT && parser.depth > outerDepth)
parser.close()
return XmlSchemaAndComplicationSlotsDefinition(schema, complicationSlots, flavors)
}
}
public class ComplicationSlotStaticData(
val slotId: Int,
val accessibilityTraversalIndex: Int?,
@ComplicationSlotBoundsType val boundsType: Int,
val bounds: ComplicationSlotBounds,
val supportedTypes: List<ComplicationType>,
val defaultDataSourcePolicy: DefaultComplicationDataSourcePolicy,
val initiallyEnabled: Boolean,
val fixedComplicationDataSource: Boolean,
val nameResourceId: Int?,
val screenReaderNameResourceId: Int?,
val boundingArc: BoundingArc?
) {
companion object {
private val typesMap by lazy(LazyThreadSafetyMode.NONE) {
mapOf(
"SHORT_TEXT" to ComplicationType.SHORT_TEXT,
"LONG_TEXT" to ComplicationType.LONG_TEXT,
"RANGED_VALUE" to ComplicationType.RANGED_VALUE,
"MONOCHROMATIC_IMAGE" to ComplicationType.MONOCHROMATIC_IMAGE,
"SMALL_IMAGE" to ComplicationType.SMALL_IMAGE,
"PHOTO_IMAGE" to ComplicationType.PHOTO_IMAGE
)
}
fun inflate(
resources: Resources,
parser: XmlResourceParser,
complicationScaleX: Float,
complicationScaleY: Float
): ComplicationSlotStaticData {
require(parser.name == "ComplicationSlot") {
"Expected a UserStyleSchema node"
}
val slotId = getIntRefAttribute(resources, parser, "slotId")
require(slotId != null) {
"A ComplicationSlot must have a slotId attribute"
}
val accessibilityTraversalIndex = if (
parser.hasValue("accessibilityTraversalIndex")
) {
parser.getAttributeIntValue(
NAMESPACE_APP,
"accessibilityTraversalIndex",
0
)
} else {
null
}
require(parser.hasValue("boundsType")) {
"A ComplicationSlot must have a boundsType attribute"
}
val boundsType = when (
parser.getAttributeIntValue(NAMESPACE_APP, "boundsType", 0)
) {
0 -> ComplicationSlotBoundsType.ROUND_RECT
1 -> ComplicationSlotBoundsType.BACKGROUND
2 -> ComplicationSlotBoundsType.EDGE
else -> throw IllegalArgumentException("Unknown boundsType")
}
require(parser.hasValue("supportedTypes")) {
"A ComplicationSlot must have a supportedTypes attribute"
}
val supportedTypes =
getStringRefAttribute(resources, parser, "supportedTypes")
?.split('|') ?: throw IllegalArgumentException(
"Unable to extract the supported type(s) for ComplicationSlot $slotId"
)
val supportedTypesList = supportedTypes.map {
typesMap[it] ?: throw IllegalArgumentException(
"Unrecognised type $it for ComplicationSlot $slotId"
)
}
val defaultComplicationDataSourcePolicy = DefaultComplicationDataSourcePolicy
.inflate(resources, parser, "ComplicationSlot")
val initiallyEnabled = parser.getAttributeBooleanValue(
NAMESPACE_APP,
"initiallyEnabled",
true
)
val fixedComplicationDataSource = parser.getAttributeBooleanValue(
NAMESPACE_APP,
"fixedComplicationDataSource",
false
)
val nameResourceId =
if (parser.hasValue("name")) {
parser.getAttributeResourceValue(NAMESPACE_APP, "name", 0)
} else {
null
}
val screenReaderNameResourceId =
if (parser.hasValue("screenReaderName")) {
parser.getAttributeResourceValue(NAMESPACE_APP, "screenReaderName", 0)
} else {
null
}
val boundingArc = if (parser.hasValue("startArcAngle")) {
BoundingArc(
parser.getAttributeFloatValue(NAMESPACE_APP, "startArcAngle", 0f),
parser.getAttributeFloatValue(NAMESPACE_APP, "totalArcAngle", 0f),
parser.getAttributeFloatValue(NAMESPACE_APP, "arcThickness", 0f)
)
} else {
null
}
val bounds = ComplicationSlotBounds.inflate(
resources,
parser,
complicationScaleX,
complicationScaleY
)
require(bounds != null) {
"ComplicationSlot must have either one ComplicationSlotBounds child node or " +
"one per ComplicationType."
}
return ComplicationSlotStaticData(
slotId,
accessibilityTraversalIndex,
boundsType,
bounds,
supportedTypesList,
defaultComplicationDataSourcePolicy,
initiallyEnabled,
fixedComplicationDataSource,
nameResourceId,
screenReaderNameResourceId,
boundingArc
)
}
}
}
fun buildComplicationSlotsManager(
currentUserStyleRepository: CurrentUserStyleRepository,
complicationSlotInflationFactory: ComplicationSlotInflationFactory
): ComplicationSlotsManager {
return ComplicationSlotsManager(
complicationSlots.map {
ComplicationSlot(
it.slotId,
it.accessibilityTraversalIndex ?: it.slotId,
it.boundsType,
it.bounds,
complicationSlotInflationFactory.getCanvasComplicationFactory(it.slotId),
it.supportedTypes,
it.defaultDataSourcePolicy,
it.defaultDataSourcePolicy.systemDataSourceFallbackDefaultType,
it.initiallyEnabled,
Bundle(),
it.fixedComplicationDataSource,
when (it.boundsType) {
ComplicationSlotBoundsType.ROUND_RECT -> RoundRectComplicationTapFilter()
ComplicationSlotBoundsType.BACKGROUND -> BackgroundComplicationTapFilter()
ComplicationSlotBoundsType.EDGE ->
complicationSlotInflationFactory.getEdgeComplicationTapFilter(it.slotId)
else -> throw UnsupportedOperationException(
"Unknown boundsType ${it.boundsType}"
)
},
it.nameResourceId,
it.screenReaderNameResourceId,
it.boundingArc
)
},
currentUserStyleRepository
)
}
}
| apache-2.0 | 3f5c16fc8bcd4b1c43f0aaae455594b1 | 42.512367 | 100 | 0.550674 | 6.546518 | false | false | false | false |
androidx/androidx | paging/paging-common/src/main/kotlin/androidx/paging/SimpleChannelFlow.kt | 3 | 3641 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY)
package androidx.paging
import androidx.annotation.RestrictTo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.internal.FusibleFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
/**
* This is a simplified channelFlow implementation as a temporary measure until channel flow
* leaves experimental state.
*
* The exact same implementation is not possible due to [FusibleFlow] being an internal API. To
* get close to that implementation, internally we use a [Channel.RENDEZVOUS] channel and use a
* [buffer] ([Channel.BUFFERED]) operator on the resulting Flow. This gives us a close behavior
* where the default is buffered and any followup buffer operation will result in +1 value being
* produced.
*/
internal fun <T> simpleChannelFlow(
block: suspend SimpleProducerScope<T>.() -> Unit
): Flow<T> {
return flow {
coroutineScope {
val channel = Channel<T>(capacity = Channel.RENDEZVOUS)
val producer = launch {
try {
// run producer in a separate inner scope to ensure we wait for its children
// to finish, in case it does more launches inside.
coroutineScope {
val producerScopeImpl = SimpleProducerScopeImpl(
scope = this,
channel = channel,
)
producerScopeImpl.block()
}
channel.close()
} catch (t: Throwable) {
channel.close(t)
}
}
for (item in channel) {
emit(item)
}
// in case channel closed before producer completes, cancel the producer.
producer.cancel()
}
}.buffer(Channel.BUFFERED)
}
internal interface SimpleProducerScope<T> : CoroutineScope, SendChannel<T> {
val channel: SendChannel<T>
suspend fun awaitClose(block: () -> Unit)
}
internal class SimpleProducerScopeImpl<T>(
scope: CoroutineScope,
override val channel: SendChannel<T>,
) : SimpleProducerScope<T>, CoroutineScope by scope, SendChannel<T> by channel {
override suspend fun awaitClose(block: () -> Unit) {
try {
val job = checkNotNull(coroutineContext[Job]) {
"Internal error, context should have a job."
}
suspendCancellableCoroutine<Unit> { cont ->
job.invokeOnCompletion {
cont.resume(Unit)
}
}
} finally {
block()
}
}
} | apache-2.0 | 65b57a531fa161ce24bf0ee1675c500e | 35.787879 | 96 | 0.645976 | 4.933604 | false | false | false | false |
androidx/androidx | credentials/credentials/src/androidTest/java/androidx/credentials/CreatePublicKeyCredentialRequestPrivilegedTest.kt | 3 | 5723 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.credentials
import android.os.Bundle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
/**
* Combines with [CreatePublicKeyCredentialRequestPrivilegedFailureInputsTest] for full tests.
*/
@RunWith(AndroidJUnit4::class)
@SmallTest
class CreatePublicKeyCredentialRequestPrivilegedTest {
@Test
fun constructor_success() {
CreatePublicKeyCredentialRequestPrivileged(
"{\"hi\":{\"there\":{\"lol\":\"Value\"}}}",
"RelyingParty", "ClientDataHash"
)
}
@Test
fun constructor_setsAllowHybridToTrueByDefault() {
val createPublicKeyCredentialRequestPrivileged = CreatePublicKeyCredentialRequestPrivileged(
"JSON", "RelyingParty", "HASH"
)
val allowHybridActual = createPublicKeyCredentialRequestPrivileged.allowHybrid
assertThat(allowHybridActual).isTrue()
}
@Test
fun constructor_setsAllowHybridToFalse() {
val allowHybridExpected = false
val createPublicKeyCredentialRequestPrivileged = CreatePublicKeyCredentialRequestPrivileged(
"testJson",
"RelyingParty", "Hash", allowHybridExpected
)
val allowHybridActual = createPublicKeyCredentialRequestPrivileged.allowHybrid
assertThat(allowHybridActual).isEqualTo(allowHybridExpected)
}
@Test
fun builder_build_defaultAllowHybrid_true() {
val defaultPrivilegedRequest = CreatePublicKeyCredentialRequestPrivileged.Builder(
"{\"Data\":5}",
"RelyingParty", "HASH"
).build()
assertThat(defaultPrivilegedRequest.allowHybrid).isTrue()
}
@Test
fun builder_build_nonDefaultAllowHybrid_false() {
val allowHybridExpected = false
val createPublicKeyCredentialRequestPrivileged = CreatePublicKeyCredentialRequestPrivileged
.Builder(
"testJson",
"RelyingParty", "Hash"
).setAllowHybrid(allowHybridExpected).build()
val allowHybridActual = createPublicKeyCredentialRequestPrivileged.allowHybrid
assertThat(allowHybridActual).isEqualTo(allowHybridExpected)
}
@Test
fun getter_requestJson_success() {
val testJsonExpected = "{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
val createPublicKeyCredentialReqPriv =
CreatePublicKeyCredentialRequestPrivileged(testJsonExpected, "RelyingParty",
"HASH")
val testJsonActual = createPublicKeyCredentialReqPriv.requestJson
assertThat(testJsonActual).isEqualTo(testJsonExpected)
}
@Test
fun getter_relyingParty_success() {
val testRelyingPartyExpected = "RelyingParty"
val createPublicKeyCredentialRequestPrivileged =
CreatePublicKeyCredentialRequestPrivileged(
"{\"hi\":{\"there\":{\"lol\":\"Value\"}}}",
testRelyingPartyExpected, "X342%4dfd7&"
)
val testRelyingPartyActual = createPublicKeyCredentialRequestPrivileged.relyingParty
assertThat(testRelyingPartyActual).isEqualTo(testRelyingPartyExpected)
}
@Test
fun getter_clientDataHash_success() {
val clientDataHashExpected = "X342%4dfd7&"
val createPublicKeyCredentialRequestPrivileged =
CreatePublicKeyCredentialRequestPrivileged(
"{\"hi\":{\"there\":{\"lol\":\"Value\"}}}",
"RelyingParty", clientDataHashExpected
)
val clientDataHashActual = createPublicKeyCredentialRequestPrivileged.clientDataHash
assertThat(clientDataHashActual).isEqualTo(clientDataHashExpected)
}
@Test
fun getter_frameworkProperties_success() {
val requestJsonExpected = "{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
val relyingPartyExpected = "RelyingParty"
val clientDataHashExpected = "X342%4dfd7&"
val allowHybridExpected = false
val expectedData = Bundle()
expectedData.putString(
CreatePublicKeyCredentialRequestPrivileged.BUNDLE_KEY_REQUEST_JSON,
requestJsonExpected
)
expectedData.putString(CreatePublicKeyCredentialRequestPrivileged.BUNDLE_KEY_RELYING_PARTY,
relyingPartyExpected)
expectedData.putString(
CreatePublicKeyCredentialRequestPrivileged.BUNDLE_KEY_CLIENT_DATA_HASH,
clientDataHashExpected
)
expectedData.putBoolean(
CreatePublicKeyCredentialRequest.BUNDLE_KEY_ALLOW_HYBRID,
allowHybridExpected
)
val request = CreatePublicKeyCredentialRequestPrivileged(
requestJsonExpected,
relyingPartyExpected,
clientDataHashExpected,
allowHybridExpected
)
assertThat(request.type).isEqualTo(PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL)
assertThat(equals(request.data, expectedData)).isTrue()
assertThat(request.requireSystemProvider).isFalse()
}
} | apache-2.0 | 0d1c552aa956ee5a8d7fa2d398b94cb0 | 37.416107 | 100 | 0.690547 | 4.993892 | false | true | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/providers/InvalidBookmark.kt | 9 | 1115 | // 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.bookmark.providers
import com.intellij.ide.bookmark.Bookmark
import java.util.Objects
internal class InvalidBookmark(override val provider: LineBookmarkProvider, val url: String, val line: Int) : Bookmark {
override val attributes: Map<String, String>
get() = mapOf("url" to url, "line" to line.toString())
override fun createNode() = UrlNode(provider.project, this)
override fun canNavigate() = false
override fun canNavigateToSource() = false
override fun navigate(requestFocus: Boolean) = Unit
override fun hashCode() = Objects.hash(provider, url, line)
override fun equals(other: Any?) = other === this || other is InvalidBookmark
&& other.provider == provider
&& other.url == url
&& other.line == line
override fun toString() = "InvalidBookmark(line=$line,url=$url,provider=$provider)"
}
| apache-2.0 | 28ce2e65930cec7a342ac64ce7563210 | 43.6 | 158 | 0.669058 | 4.55102 | false | false | false | false |
GunoH/intellij-community | plugins/git4idea/tests/git4idea/ignore/RunConfigurationVcsIgnoreTest.kt | 5 | 4364 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.ignore
import com.intellij.configurationStore.saveSettings
import com.intellij.ide.impl.runBlockingUnderModalProgress
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.vcs.changes.VcsIgnoreManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.VfsTestUtil
import git4idea.repo.GitRepositoryFiles.GITIGNORE
import git4idea.test.GitSingleRepoTest
import org.assertj.core.api.Assertions.assertThat
class RunConfigurationVcsIgnoreTest : GitSingleRepoTest() {
private val configurationName = "Unnamed"
override fun isCreateDirectoryBasedProject() = true
override fun setUpProject() {
super.setUpProject()
// will create .idea directory
// setUpProject is executed in EDT
runBlockingUnderModalProgress {
saveSettings(project)
}
}
override fun setUpModule() {
myModule = createMainModule()
}
fun `test run configuration not ignored`() {
val gitIgnore = VfsTestUtil.createFile(projectRoot, GITIGNORE)
gitIgnore.write("!$configurationName")
val vcsIgnoreManager = VcsIgnoreManager.getInstance(project)
ApplicationManager.getApplication().invokeAndWait {
assertFalse(vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName))
assertFalse(vcsIgnoreManager.isDirectoryVcsIgnored("$projectPath/.idea/runConfigurations"))
}
gitIgnore.write("!$configurationName*")
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
}
fun `test run configuration ignored`() {
val gitIgnore = VfsTestUtil.createFile(projectRoot, GITIGNORE)
gitIgnore.write("$configurationName*")
ApplicationManager.getApplication().invokeAndWait {
assertThat(VcsIgnoreManager.getInstance(project).isRunConfigurationVcsIgnored(configurationName)).isTrue()
}
}
fun `test remove run configuration from ignore`() {
val gitIgnore = VfsTestUtil.createFile(projectRoot, GITIGNORE)
gitIgnore.write(".idea")
val vcsIgnoreManager = VcsIgnoreManager.getInstance(project)
ApplicationManager.getApplication().invokeAndWait {
assertThat(vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName)).isTrue()
assertThat(vcsIgnoreManager.isDirectoryVcsIgnored("$projectPath/.idea/runConfigurations")).isTrue()
vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName)
assertThat(vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName)).isFalse()
}
gitIgnore.write(".idea/")
invokeAndWaitIfNeeded { vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName) }
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
gitIgnore.write(".id*")
invokeAndWaitIfNeeded { vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName) }
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
gitIgnore.write(".id*/")
invokeAndWaitIfNeeded { vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName) }
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
gitIgnore.write("*.xml")
invokeAndWaitIfNeeded { vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName) }
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
gitIgnore.write(".idea/*.xml")
invokeAndWaitIfNeeded { vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName) }
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
gitIgnore.write("$configurationName.xml")
invokeAndWaitIfNeeded { vcsIgnoreManager.removeRunConfigurationFromVcsIgnore(configurationName) }
assertFalse(invokeAndWaitIfNeeded { vcsIgnoreManager.isRunConfigurationVcsIgnored(configurationName) })
}
}
private fun VirtualFile.write(data: String) {
runWriteActionAndWait {
setBinaryContent(data.toByteArray())
}
}
| apache-2.0 | 0f8061da7381f08a336eb2fe52366567 | 40.561905 | 120 | 0.803621 | 5.573436 | false | true | false | false |
jwren/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/GHPRDiffVirtualFile.kt | 1 | 2106 | // 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.plugins.github.pullrequest
import com.intellij.diff.impl.DiffRequestProcessor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.data.GHPRDataContextRepository
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
@Suppress("EqualsOrHashCode")
internal class GHPRDiffVirtualFile(fileManagerId: String,
project: Project,
repository: GHRepositoryCoordinates,
val pullRequest: GHPRIdentifier)
: GHPRDiffVirtualFileBase(fileManagerId, project, repository) {
override fun createProcessor(project: Project): DiffRequestProcessor {
val dataDisposable = Disposer.newDisposable()
val dataContext = GHPRDataContextRepository.getInstance(project).findContext(repository)!!
val dataProvider = dataContext.dataProviderRepository.getDataProvider(pullRequest, dataDisposable)
val diffRequestModel = dataProvider.diffRequestModel
val diffProcessor = GHPRDiffRequestChainProcessor(project, diffRequestModel)
Disposer.register(diffProcessor, dataDisposable)
return diffProcessor
}
override fun getName() = "#${pullRequest.number}.diff"
override fun getPresentableName() = GithubBundle.message("pull.request.diff.editor.title", pullRequest.number)
override fun getPath(): String = (fileSystem as GHPRVirtualFileSystem).getPath(fileManagerId, project, repository, pullRequest, true)
override fun getPresentablePath() = "${repository.toUrl()}/pulls/${pullRequest.number}.diff"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is GHPRDiffVirtualFile) return false
if (!super.equals(other)) return false
return true
}
}
| apache-2.0 | 90fbb9452adcbbca34e8f3a88688a597 | 47.976744 | 158 | 0.761633 | 5.161765 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/compiler-plugins/kotlinx-serialization/common/src/org/jetbrains/kotlin/idea/compilerPlugin/kotlinxSerialization/quickfixes/JsonRedundantDefaultQuickFix.kt | 3 | 1863 | // 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.compilerPlugin.kotlinxSerialization.quickfixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.quickfix.KotlinSingleIntentionActionFactory
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlinx.serialization.compiler.diagnostic.SerializationErrors
import org.jetbrains.kotlin.idea.compilerPlugin.kotlinxSerialization.KotlinSerializationBundle
internal class JsonRedundantDefaultQuickFix(expression: KtCallExpression) : KotlinQuickFixAction<KtCallExpression>(expression) {
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val call = element as? KtCallExpression ?: return
val callee = call.calleeExpression ?: return
call.replace(callee)
}
override fun getFamilyName(): String = text
override fun getText(): String = KotlinSerializationBundle.message("replace.with.default.json.format")
object Factory : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
if (diagnostic.factory != SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT) return null
val castedDiagnostic = SerializationErrors.JSON_FORMAT_REDUNDANT_DEFAULT.cast(diagnostic)
val element: KtCallExpression = castedDiagnostic.psiElement as? KtCallExpression ?: return null
return JsonRedundantDefaultQuickFix(element)
}
}
}
| apache-2.0 | 6d205a345a59ca942db7d52e1874423b | 50.75 | 158 | 0.782072 | 5.118132 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/java/findJavaClassUsages/JKInnerClassAllUsages.1.kt | 9 | 729 | public class KOuter : Outer() {
public inner class X(bar: String? = (this@KOuter as Outer).A().bar) : Outer.A() {
var next: Outer.A? = (this@KOuter as Outer).A()
val myBar: String? = (this@KOuter as Outer).A().bar
init {
(this@KOuter as Outer).A().bar = ""
}
fun foo(a: Outer.A) {
val aa: Outer.A = a
aa.bar = ""
}
@JvmName("getNextFun")
fun getNext(): Outer.A? {
return next
}
public override fun foo() {
super<Outer.A>.foo()
}
}
}
fun KOuter.X.bar(a: Outer.A = Outer().A()) {
}
fun Any.toA(): Outer.A? {
return if (this is Outer.A) this as Outer.A else null
}
| apache-2.0 | d745db0213d41d2161d12496ad02cb9d | 21.78125 | 85 | 0.485597 | 3.283784 | false | false | false | false |
GlobalTechnology/android-gto-support | gto-support-viewpager/src/main/kotlin/org/ccci/gto/android/common/viewpager/adapter/DataBindingPagerAdapter.kt | 2 | 1894 | package org.ccci.gto.android.common.viewpager.adapter
import android.view.ViewGroup
import androidx.annotation.UiThread
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import com.karumi.weak.weak
abstract class DataBindingPagerAdapter<B : ViewDataBinding>(lifecycleOwner: LifecycleOwner? = null) :
BaseDataBindingPagerAdapter<B, DataBindingViewHolder<B>>(lifecycleOwner) {
final override fun onCreateViewHolder(parent: ViewGroup) = DataBindingViewHolder(
onCreateViewDataBinding(parent).also {
it.lifecycleOwner = lifecycleOwner
onViewDataBindingCreated(it)
}
)
abstract fun onCreateViewDataBinding(parent: ViewGroup): B
open fun onViewDataBindingCreated(binding: B) = Unit
}
abstract class BaseDataBindingPagerAdapter<B : ViewDataBinding, VH : DataBindingViewHolder<B>>(
lifecycleOwner: LifecycleOwner? = null
) : ViewHolderPagerAdapter<VH>() {
protected val lifecycleOwner by weak(lifecycleOwner)
protected val primaryItemBinding get() = primaryItem?.binding
final override fun onBindViewHolder(holder: VH, position: Int) {
super.onBindViewHolder(holder, position)
onBindViewDataBinding(holder, holder.binding, position)
}
final override fun onUpdatePrimaryItem(old: VH?, holder: VH?) =
onUpdatePrimaryItem(old, old?.binding, holder, holder?.binding)
final override fun onViewHolderRecycled(holder: VH) {
super.onViewHolderRecycled(holder)
onViewDataBindingRecycled(holder, holder.binding)
}
@UiThread
protected open fun onBindViewDataBinding(holder: VH, binding: B, position: Int) = Unit
@UiThread
protected open fun onUpdatePrimaryItem(oldHolder: VH?, oldBinding: B?, holder: VH?, binding: B?) = Unit
@UiThread
protected open fun onViewDataBindingRecycled(holder: VH, binding: B) = Unit
}
| mit | 95c05981f953e8210ab446454bed0f14 | 39.297872 | 107 | 0.749208 | 4.85641 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveDeclarations/ui/MoveKotlinNestedClassesModel.kt | 5 | 3238 | // 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.refactoring.move.moveDeclarations.ui
import com.intellij.openapi.options.ConfigurationException
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.move.MoveCallback
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.*
import org.jetbrains.kotlin.idea.statistics.KotlinMoveRefactoringFUSCollector.MoveRefactoringDestination
import org.jetbrains.kotlin.idea.statistics.KotlinMoveRefactoringFUSCollector.MovedEntity
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtElement
internal class MoveKotlinNestedClassesModel(
val project: Project,
val openInEditorCheckBox: Boolean,
val selectedElementsToMove: List<KtClassOrObject>,
val originalClass: KtClassOrObject,
val targetClass: PsiElement?,
val moveCallback: MoveCallback?
) : Model {
private fun getCheckedTargetClass(): KtElement {
val targetClass = this.targetClass ?: throw ConfigurationException(RefactoringBundle.message("no.destination.class.specified"))
if (targetClass !is KtClassOrObject) {
throw ConfigurationException(KotlinBundle.message("text.destination.class.should.be.kotlin.class"))
}
if (originalClass === targetClass) {
throw ConfigurationException(RefactoringBundle.message("source.and.destination.classes.should.be.different"))
}
for (classOrObject in selectedElementsToMove) {
if (PsiTreeUtil.isAncestor(classOrObject, targetClass, false)) {
throw ConfigurationException(
KotlinBundle.message("text.cannot.move.inner.class.0.into.itself", classOrObject.name.toString())
)
}
}
return targetClass
}
@Throws(ConfigurationException::class)
override fun computeModelResult() = computeModelResult(throwOnConflicts = false)
@Throws(ConfigurationException::class)
override fun computeModelResult(throwOnConflicts: Boolean): ModelResultWithFUSData {
val elementsToMove = selectedElementsToMove
val target = KotlinMoveTargetForExistingElement(getCheckedTargetClass())
val delegate = MoveDeclarationsDelegate.NestedClass()
val descriptor = MoveDeclarationsDescriptor(
project,
MoveSource(elementsToMove),
target,
delegate,
searchInCommentsAndStrings = false,
searchInNonCode = false,
deleteSourceFiles = false,
moveCallback = moveCallback,
openInEditor = openInEditorCheckBox
)
val processor = MoveKotlinDeclarationsProcessor(descriptor, Mover.Default, throwOnConflicts)
return ModelResultWithFUSData(
processor,
elementsToMove.size,
MovedEntity.CLASSES,
MoveRefactoringDestination.DECLARATION
)
}
} | apache-2.0 | 9ab5c5ecf52f75b8d9464122bb28ed10 | 40.525641 | 158 | 0.73008 | 5.563574 | false | true | false | false |
smmribeiro/intellij-community | platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/WithSoftLinkEntityData.kt | 2 | 9780 | // 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:Suppress("unused")
package com.intellij.workspaceModel.storage
import com.intellij.workspaceModel.storage.impl.*
import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex
import com.intellij.workspaceModel.storage.impl.references.ManyToOne
import com.intellij.workspaceModel.storage.impl.references.MutableManyToOne
// ------------------------------ Persistent Id ---------------
data class NameId(private val name: String) : PersistentEntityId<NamedEntity>() {
override val presentableName: String
get() = name
override fun toString(): String = name
}
data class AnotherNameId(private val name: String) : PersistentEntityId<NamedEntity>() {
override val presentableName: String
get() = name
override fun toString(): String = name
}
data class ComposedId(val name: String, val link: NameId) : PersistentEntityId<ComposedIdSoftRefEntity>() {
override val presentableName: String
get() = "$name - ${link.presentableName}"
}
// ------------------------------ Entity With Persistent Id ------------------
class NamedEntityData : WorkspaceEntityData.WithCalculablePersistentId<NamedEntity>() {
lateinit var name: String
var additionalProperty: String? = null
override fun createEntity(snapshot: WorkspaceEntityStorage): NamedEntity {
return NamedEntity(name, additionalProperty).also { addMetaData(it, snapshot) }
}
override fun persistentId(): PersistentEntityId<*> = NameId(name)
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (this === other) return true
if (other !is NamedEntityData) return false
if (name != other.name) return false
if (additionalProperty != other.additionalProperty) return false
return true
}
}
class NamedEntity(val name: String, val additionalProperty: String?) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
override fun persistentId() = NameId(name)
}
class ModifiableNamedEntity : ModifiableWorkspaceEntityBase<NamedEntity>() {
var name: String by EntityDataDelegation()
var additionalProperty: String? by EntityDataDelegation()
}
fun WorkspaceEntityStorageBuilder.addNamedEntity(name: String, additionalProperty: String? = null, source: EntitySource = MySource) =
addEntity(ModifiableNamedEntity::class.java, source) {
this.name = name
this.additionalProperty = additionalProperty
}
val NamedEntity.children: Sequence<NamedChildEntity>
get() = referrers(NamedChildEntity::parent)
// ------------------------------ Child of entity with persistent id ------------------
class NamedChildEntityData : WorkspaceEntityData<NamedChildEntity>() {
lateinit var childProperty: String
override fun createEntity(snapshot: WorkspaceEntityStorage): NamedChildEntity {
return NamedChildEntity(childProperty).also { addMetaData(it, snapshot) }
}
}
class NamedChildEntity(
val childProperty: String
) : WorkspaceEntityBase() {
val parent: NamedEntity by ManyToOne.NotNull(NamedEntity::class.java)
}
class ModifiableNamedChildEntity : ModifiableWorkspaceEntityBase<NamedChildEntity>() {
var childProperty: String by EntityDataDelegation()
var parent: NamedEntity by MutableManyToOne.NotNull(NamedChildEntity::class.java, NamedEntity::class.java)
}
fun WorkspaceEntityStorageBuilder.addNamedChildEntity(parentEntity: NamedEntity,
childProperty: String = "child",
source: EntitySource = MySource) =
addEntity(ModifiableNamedChildEntity::class.java, source) {
this.parent = parentEntity
this.childProperty = childProperty
}
// ------------------------------ Entity with soft link --------------------
class WithSoftLinkEntityData : WorkspaceEntityData<WithSoftLinkEntity>(), SoftLinkable {
lateinit var link: PersistentEntityId<*>
override fun createEntity(snapshot: WorkspaceEntityStorage): WithSoftLinkEntity {
return WithSoftLinkEntity(link).also { addMetaData(it, snapshot) }
}
override fun getLinks(): Set<PersistentEntityId<*>> = setOf(link)
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
index.index(this, link)
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val previous = prev.singleOrNull()
if (previous != null) {
if (previous != link) {
index.remove(this, previous)
index.index(this, link)
}
}
else {
index.index(this, link)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>,
newLink: PersistentEntityId<*>): Boolean {
this.link = newLink
return true
}
}
class WithSoftLinkEntity(val link: PersistentEntityId<*>) : WorkspaceEntityBase()
class ModifiableWithSoftLinkEntity : ModifiableWorkspaceEntityBase<WithSoftLinkEntity>() {
var link: PersistentEntityId<*> by EntityDataDelegation()
}
fun WorkspaceEntityStorageBuilder.addWithSoftLinkEntity(link: PersistentEntityId<*>, source: EntitySource = MySource) =
addEntity(ModifiableWithSoftLinkEntity::class.java, source) {
this.link = link
}
// ------------------------- Entity with persistentId and the list of soft links ------------------
class WithListSoftLinksEntityData : SoftLinkable, WorkspaceEntityData.WithCalculablePersistentId<WithListSoftLinksEntity>() {
lateinit var name: String
lateinit var links: MutableList<NameId>
override fun getLinks(): Set<PersistentEntityId<*>> = links.toSet()
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
for (link in links) {
index.index(this, link)
}
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val mutablePreviousSet = HashSet(prev)
for (dependency in links) {
val removed = mutablePreviousSet.remove(dependency)
if (!removed) {
index.index(this, dependency)
}
}
for (removed in mutablePreviousSet) {
index.remove(this, removed)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>,
newLink: PersistentEntityId<*>): Boolean {
links.remove(oldLink)
links.add(newLink as NameId)
return true
}
override fun createEntity(snapshot: WorkspaceEntityStorage): WithListSoftLinksEntity {
return WithListSoftLinksEntity(name, links).also { addMetaData(it, snapshot) }
}
override fun persistentId() = AnotherNameId(name)
}
class WithListSoftLinksEntity(val name: String, val links: List<NameId>) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
override fun persistentId(): AnotherNameId = AnotherNameId(name)
}
class ModifiableWithListSoftLinksEntity : ModifiableWorkspaceEntityBase<WithListSoftLinksEntity>() {
var name: String by EntityDataDelegation()
var links: List<NameId> by EntityDataDelegation()
}
fun WorkspaceEntityStorageBuilder.addWithListSoftLinksEntity(name: String,
links: List<NameId>,
source: EntitySource = MySource) =
addEntity(ModifiableWithListSoftLinksEntity::class.java, source) {
this.name = name
this.links = links
}
// --------------------------- Entity with composed persistent id via soft reference ------------------
class ComposedIdSoftRefEntityData : WorkspaceEntityData.WithCalculablePersistentId<ComposedIdSoftRefEntity>(), SoftLinkable {
lateinit var name: String
lateinit var link: NameId
override fun createEntity(snapshot: WorkspaceEntityStorage): ComposedIdSoftRefEntity {
return ComposedIdSoftRefEntity(name, link).also { addMetaData(it, snapshot) }
}
override fun getLinks(): Set<PersistentEntityId<*>> = setOf(link)
override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
index.index(this, link)
}
override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) {
val previous = prev.singleOrNull()
if (previous != null) {
if (previous != link) {
index.remove(this, previous)
index.index(this, link)
}
}
else {
index.index(this, link)
}
}
override fun updateLink(oldLink: PersistentEntityId<*>,
newLink: PersistentEntityId<*>): Boolean {
if (oldLink != link) return false
this.link = newLink as NameId
return true
}
override fun persistentId() = ComposedId(name, link)
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (this === other) return true
if (other !is ComposedIdSoftRefEntityData) return false
if (name != other.name) return false
if (link != other.link) return false
return true
}
}
class ComposedIdSoftRefEntity(val name: String, val link: NameId) : WorkspaceEntityBase(), WorkspaceEntityWithPersistentId {
override fun persistentId(): ComposedId = ComposedId(name, link)
}
class ModifiableComposedIdSoftRefEntity : ModifiableWorkspaceEntityBase<ComposedIdSoftRefEntity>() {
var name: String by EntityDataDelegation()
var link: NameId by EntityDataDelegation()
}
fun WorkspaceEntityStorageBuilder.addComposedIdSoftRefEntity(name: String,
link: NameId,
source: EntitySource = MySource): ComposedIdSoftRefEntity {
return addEntity(ModifiableComposedIdSoftRefEntity::class.java, source) {
this.name = name
this.link = link
}
}
| apache-2.0 | 4039b9d34a081f3ccd387efb9bffeb23 | 34.693431 | 158 | 0.698364 | 5.494382 | false | false | false | false |
Fotoapparat/Fotoapparat | fotoapparat/src/main/java/io/fotoapparat/parameter/camera/provide/CameraParametersProvider.kt | 1 | 4381 | package io.fotoapparat.parameter.camera.provide
import io.fotoapparat.capability.Capabilities
import io.fotoapparat.configuration.CameraConfiguration
import io.fotoapparat.exception.camera.InvalidConfigurationException
import io.fotoapparat.exception.camera.UnsupportedConfigurationException
import io.fotoapparat.hardware.CameraDevice
import io.fotoapparat.parameter.Parameter
import io.fotoapparat.parameter.Resolution
import io.fotoapparat.parameter.camera.CameraParameters
import io.fotoapparat.selector.*
/**
* @return [CameraParameters] which will be used by [CameraDevice].
*/
internal fun getCameraParameters(
capabilities: Capabilities,
cameraConfiguration: CameraConfiguration
): CameraParameters {
return capabilities.run {
cameraConfiguration.run {
val selectedPictureResolution = pictureResolution selectFrom pictureResolutions
val validPreviewSizeSelector = validPreviewSizeSelector(
resolution = selectedPictureResolution,
original = previewResolution
)
CameraParameters(
flashMode = flashMode selectFrom flashModes,
focusMode = focusMode selectFrom focusModes,
jpegQuality = jpegQuality selectFrom jpegQualityRange,
exposureCompensation = exposureCompensation selectFrom exposureCompensationRange,
previewFpsRange = previewFpsRange selectFrom previewFpsRanges,
antiBandingMode = antiBandingMode selectFrom antiBandingModes,
pictureResolution = selectedPictureResolution,
previewResolution = validPreviewSizeSelector selectFrom previewResolutions,
sensorSensitivity = sensorSensitivity selectOptionalFrom sensorSensitivities
)
}
}
}
private fun validPreviewSizeSelector(
resolution: Resolution,
original: ResolutionSelector
) = firstAvailable(
filtered(
selector = aspectRatio(
aspectRatio = resolution.aspectRatio,
selector = original
),
predicate = {
it.area <= resolution.area
}
),
original
)
private infix fun <T> (Collection<T>.() -> T?)?.selectOptionalFrom(supportedParameters: Set<T>): T? =
this?.run { this(supportedParameters) }
private inline infix fun <reified T : Parameter> (Collection<T>.() -> T?).selectFrom(
supportedParameters: Set<T>
): T = this(supportedParameters)
.ensureSelected(supportedParameters)
.ensureInCollection(supportedParameters)
private infix fun QualitySelector.selectFrom(supportedParameters: IntRange): Int =
this(supportedParameters)
.ensureSelected(
supportedParameters = supportedParameters,
configurationName = "Jpeg quality"
)
.ensureInCollection(supportedParameters)
private inline fun <reified Param : Parameter> Param.ensureInCollection(
supportedParameters: Set<Param>
): Param = apply {
if (this !in supportedParameters) {
throw InvalidConfigurationException(
value = this,
klass = Param::class.java,
supportedParameters = supportedParameters
)
}
}
private inline fun <reified Param : Comparable<Param>> Param.ensureInCollection(
supportedRange: ClosedRange<Param>
): Param = apply {
if (this !in supportedRange) {
throw InvalidConfigurationException(
value = this,
klass = Param::class.java,
supportedRange = supportedRange
)
}
}
private inline fun <reified Param : Parameter> Param?.ensureSelected(
supportedParameters: Collection<Parameter>
): Param = this ?: throw UnsupportedConfigurationException(
klass = Param::class.java,
supportedParameters = supportedParameters
)
private inline fun <reified Param : Comparable<Param>> Param?.ensureSelected(
supportedParameters: ClosedRange<Param>,
configurationName: String
): Param = this ?: throw UnsupportedConfigurationException(
configurationName = configurationName,
supportedRange = supportedParameters
)
| apache-2.0 | 4080c99752977cefa7adfa19a517c40d | 36.444444 | 101 | 0.66583 | 5.756899 | false | true | false | false |
android/compose-samples | Jetsnack/app/src/main/java/com/example/jetsnack/ui/home/search/Results.kt | 1 | 8013 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetsnack.ui.home.search
import android.content.res.Configuration
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ChainStyle
import androidx.constraintlayout.compose.ConstraintLayout
import com.example.jetsnack.R
import com.example.jetsnack.model.Filter
import com.example.jetsnack.model.Snack
import com.example.jetsnack.model.snacks
import com.example.jetsnack.ui.components.FilterBar
import com.example.jetsnack.ui.components.JetsnackButton
import com.example.jetsnack.ui.components.JetsnackDivider
import com.example.jetsnack.ui.components.JetsnackSurface
import com.example.jetsnack.ui.components.SnackImage
import com.example.jetsnack.ui.theme.JetsnackTheme
import com.example.jetsnack.ui.utils.formatPrice
@Composable
fun SearchResults(
searchResults: List<Snack>,
filters: List<Filter>,
onSnackClick: (Long) -> Unit
) {
Column {
FilterBar(filters, onShowFilters = {})
Text(
text = stringResource(R.string.search_count, searchResults.size),
style = MaterialTheme.typography.h6,
color = JetsnackTheme.colors.textPrimary,
modifier = Modifier.padding(horizontal = 24.dp, vertical = 4.dp)
)
LazyColumn {
itemsIndexed(searchResults) { index, snack ->
SearchResult(snack, onSnackClick, index != 0)
}
}
}
}
@Composable
private fun SearchResult(
snack: Snack,
onSnackClick: (Long) -> Unit,
showDivider: Boolean,
modifier: Modifier = Modifier
) {
ConstraintLayout(
modifier = modifier
.fillMaxWidth()
.clickable { onSnackClick(snack.id) }
.padding(horizontal = 24.dp)
) {
val (divider, image, name, tag, priceSpacer, price, add) = createRefs()
createVerticalChain(name, tag, priceSpacer, price, chainStyle = ChainStyle.Packed)
if (showDivider) {
JetsnackDivider(
Modifier.constrainAs(divider) {
linkTo(start = parent.start, end = parent.end)
top.linkTo(parent.top)
}
)
}
SnackImage(
imageUrl = snack.imageUrl,
contentDescription = null,
modifier = Modifier
.size(100.dp)
.constrainAs(image) {
linkTo(
top = parent.top,
topMargin = 16.dp,
bottom = parent.bottom,
bottomMargin = 16.dp
)
start.linkTo(parent.start)
}
)
Text(
text = snack.name,
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textSecondary,
modifier = Modifier.constrainAs(name) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = add.start,
endMargin = 16.dp,
bias = 0f
)
}
)
Text(
text = snack.tagline,
style = MaterialTheme.typography.body1,
color = JetsnackTheme.colors.textHelp,
modifier = Modifier.constrainAs(tag) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = add.start,
endMargin = 16.dp,
bias = 0f
)
}
)
Spacer(
Modifier
.height(8.dp)
.constrainAs(priceSpacer) {
linkTo(top = tag.bottom, bottom = price.top)
}
)
Text(
text = formatPrice(snack.price),
style = MaterialTheme.typography.subtitle1,
color = JetsnackTheme.colors.textPrimary,
modifier = Modifier.constrainAs(price) {
linkTo(
start = image.end,
startMargin = 16.dp,
end = add.start,
endMargin = 16.dp,
bias = 0f
)
}
)
JetsnackButton(
onClick = { /* todo */ },
shape = CircleShape,
contentPadding = PaddingValues(0.dp),
modifier = Modifier
.size(36.dp)
.constrainAs(add) {
linkTo(top = parent.top, bottom = parent.bottom)
end.linkTo(parent.end)
}
) {
Icon(
imageVector = Icons.Outlined.Add,
contentDescription = stringResource(R.string.label_add)
)
}
}
}
@Composable
fun NoResults(
query: String,
modifier: Modifier = Modifier
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
.fillMaxSize()
.wrapContentSize()
.padding(24.dp)
) {
Image(
painterResource(R.drawable.empty_state_search),
contentDescription = null
)
Spacer(Modifier.height(24.dp))
Text(
text = stringResource(R.string.search_no_matches, query),
style = MaterialTheme.typography.subtitle1,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Spacer(Modifier.height(16.dp))
Text(
text = stringResource(R.string.search_no_matches_retry),
style = MaterialTheme.typography.body2,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
}
@Preview("default")
@Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Preview("large font", fontScale = 2f)
@Composable
private fun SearchResultPreview() {
JetsnackTheme {
JetsnackSurface {
SearchResult(
snack = snacks[0],
onSnackClick = { },
showDivider = false
)
}
}
}
| apache-2.0 | 02f383acb70207ea8f5af2eb5334b055 | 32.95339 | 90 | 0.600899 | 4.803957 | false | false | false | false |
80998062/Fank | domain/src/main/java/com/sinyuk/fanfou/domain/repo/timeline/tiled/TiledStatusDataSource.kt | 1 | 7686 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.domain.repo.timeline.tiled
import android.arch.lifecycle.MutableLiveData
import android.arch.paging.PageKeyedDataSource
import com.sinyuk.fanfou.domain.AppExecutors
import com.sinyuk.fanfou.domain.DO.PlayerExtracts
import com.sinyuk.fanfou.domain.DO.Resource
import com.sinyuk.fanfou.domain.DO.Status
import com.sinyuk.fanfou.domain.NetworkState
import com.sinyuk.fanfou.domain.TIMELINE_CONTEXT
import com.sinyuk.fanfou.domain.TIMELINE_FAVORITES
import com.sinyuk.fanfou.domain.api.RestAPI
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
/**
* Created by sinyuk on 2017/12/29.
*
* 由于statuses.context_timeline / favorites 接口不支持since_id/max_id的查询,所以只能只用分页来查询
*
*/
/**
* @param uniqueId 可以是用户id或者是msg id
*/
class TiledStatusDataSource(private val restAPI: RestAPI,
private val path: String,
private val uniqueId: String,
private val appExecutors: AppExecutors) : PageKeyedDataSource<Int, Status>() {
override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, Status>) {}
override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Status>) {
networkState.postValue(NetworkState.LOADING)
initialLoad.postValue(Resource.loading(null))
loadInitialFromNetwork(params, callback)
}
// private fun loadInitialFromLocal(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Status>) {
// appExecutors.diskIO().execute {
// localDatabase.runInTransaction {
// val statuses = localDatabase.statusDao().loadInitial(uniqueId = uniqueId, path = convertPathToFlag(path), limit = params.requestedLoadSize)
// callback.onResult(statuses, null, null)
// }
// }
// }
private fun loadInitialFromNetwork(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, Status>) {
when (path) {
TIMELINE_FAVORITES -> restAPI.fetch_favorites(id = uniqueId, count = params.requestedLoadSize, page = 1)
TIMELINE_CONTEXT -> restAPI.fetch_from_path(path = TIMELINE_CONTEXT, count = params.requestedLoadSize, page = 1, id = uniqueId)
else -> TODO()
}.enqueue(object : Callback<MutableList<Status>> {
override fun onResponse(call: Call<MutableList<Status>>?, response: Response<MutableList<Status>>) {
if (response.isSuccessful) {
val items = mapResponse(response.body())
retry = null
networkState.postValue(NetworkState.LOADED)
initialLoad.postValue(Resource.success(items))
val nextPageKey = if (items.size < params.requestedLoadSize) {
null
} else {
2
}
callback.onResult(items, null, nextPageKey)
} else {
retry = {
loadInitial(params, callback)
}
val msg = "error code: ${response.code()}"
networkState.postValue(NetworkState.error(msg))
initialLoad.postValue(Resource.error(msg, null))
}
}
override fun onFailure(call: Call<MutableList<Status>>?, t: Throwable) {
// keep a lambda for future retry
retry = {
loadInitial(params, callback)
}
// publish the error
val msg = t.message ?: "unknown error"
networkState.postValue(NetworkState.error(msg))
initialLoad.postValue(Resource.error(msg, null))
}
})
}
override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, Status>) {
networkState.postValue(NetworkState.LOADING)
loadAfterFromNetwork(params, callback)
}
@Suppress("unused")
private fun loadAfterFromLocal(params: LoadParams<Int>, callback: LoadCallback<Int, Status>) {
// appExecutors.diskIO().execute {
// localDatabase.runInTransaction {
// val statuses = localDatabase.statusDao().loadAfter(uniqueId = uniqueId, path = convertPathToFlag(path), limit = params.requestedLoadSize,
// offset = params.requestedLoadSize * params.key)
// val next = params.key + 1
// callback.onResult(statuses, next)
// }
// }
}
private fun loadAfterFromNetwork(params: LoadParams<Int>, callback: LoadCallback<Int, Status>) {
try {
val response = when (path) {
TIMELINE_FAVORITES -> restAPI.fetch_favorites(id = uniqueId, count = params.requestedLoadSize, page = params.key)
TIMELINE_CONTEXT -> restAPI.fetch_from_path(path = TIMELINE_CONTEXT, count = params.requestedLoadSize, page = params.key, id = uniqueId)
else -> TODO()
}.execute()
if (response.isSuccessful) {
val items = mapResponse(response.body())
retry = null
networkState.postValue(NetworkState.LOADED)
val nextPageKey = if (items.size < params.requestedLoadSize) {
null
} else {
params.key + 1
}
callback.onResult(items, nextPageKey)
} else {
retry = { loadAfter(params, callback) }
networkState.postValue(NetworkState.error("error code: ${response.code()}"))
}
} catch (e: IOException) {
retry = { loadAfter(params, callback) }
networkState.postValue(NetworkState.error(e.message ?: "unknown error"))
}
}
// keep a function reference for the retry event
private var retry: (() -> Any)? = null
/**
* There is no sync on the state because paging will always call loadInitial first then wait
* for it to return some success value before calling loadAfter and we don't support loadBefore
* in this example.
* <p>
* See BoundaryCallback example for a more complete example on syncing multiple network states.
*/
val networkState = MutableLiveData<NetworkState>()
val initialLoad = MutableLiveData<Resource<MutableList<Status>>>()
fun retryAllFailed() {
val prevRetry = retry
retry = null
prevRetry?.let {
appExecutors.networkIO().execute {
it.invoke()
}
}
}
fun mapResponse(response: MutableList<Status>?) = if (response == null) {
mutableListOf()
} else {
for (item in response) {
item.user?.let { item.playerExtracts = PlayerExtracts(it) }
}
response
}
} | mit | 188964db0cf7b592a0d0df4f4f2de82c | 38.123077 | 157 | 0.608154 | 4.743781 | false | false | false | false |
nelosan/yeoman-kotlin-clean | generators/app/templates/clean-architecture/data/src/main/kotlin/com/nelosan/clean/data/rest/NsConnector.kt | 1 | 1250 | package <%= appPackage %>.data.rest
import android.app.Application
import <%= appPackage %>.data.parser.Serializer
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Created by nelo on 16/2/17.
*/
class NsConnector {
var ENDPOINT = Host.getHost()
val CONNECTION_TIMEOUT: Long = 10
val application: Application
val serializer: Serializer
lateinit var adapter: Retrofit
constructor(application: Application) {
this.application = application
createApi()
serializer = Serializer()
}
fun createApi() {
var client: OkHttpClient = OkHttpClient
.Builder()
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.addInterceptor(NsInterceptor(application))
.build()
adapter = Retrofit
.Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build()
}
} | apache-2.0 | 0d7f98d8ff750f5a597528cfe9c75e5d | 25.0625 | 74 | 0.6464 | 5.208333 | false | false | false | false |
ibinti/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ChangeListUtil.kt | 5 | 1868 | /*
* Copyright 2000-2015 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.
*/
@file:JvmName("ChangeListUtil")
package com.intellij.openapi.vcs.changes
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.changes.shelf.ShelvedChangeList
private val CHANGELIST_NAME_PATTERN = "\\s\\[(.*)\\]"
private val STASH_MESSAGE_PATTERN = VcsBundle.message("stash.changes.message", ".*")
private val SYSTEM_CHANGELIST_REGEX = (STASH_MESSAGE_PATTERN + CHANGELIST_NAME_PATTERN).toRegex()
fun createSystemShelvedChangeListName(systemPrefix: String, changelistName: String): String {
return "$systemPrefix [$changelistName]"
}
private fun getOriginalName(shelvedName: String): String {
return SYSTEM_CHANGELIST_REGEX.matchEntire(shelvedName)?.groups?.get(1)?.value ?: shelvedName
}
fun getPredefinedChangeList(shelvedList: ShelvedChangeList, changeListManager: ChangeListManager): LocalChangeList? {
val defaultName = shelvedList.DESCRIPTION
return changeListManager.findChangeList(defaultName) ?:
if (shelvedList.isMarkedToDelete) changeListManager.findChangeList(getOriginalName(defaultName)) else null
}
fun getChangeListNameForUnshelve(shelvedList: ShelvedChangeList): String {
val defaultName = shelvedList.DESCRIPTION
return if (shelvedList.isMarkedToDelete) getOriginalName(defaultName) else defaultName
}
| apache-2.0 | ec70cc66476a353dc69149f0ba539803 | 41.454545 | 117 | 0.783726 | 4.284404 | false | false | false | false |
AntriKodSoft/ColorHub | app/src/main/java/cheetatech/com/colorhub/adapters/MainPageAdapter.kt | 1 | 3299 | package cheetatech.com.colorhub.adapters
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RotateDrawable
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import cheetatech.com.colorhub.R
import cheetatech.com.colorhub.Util
import cheetatech.com.colorhub.listeners.OnItemSelect
import cheetatech.com.colorhub.models.MainPageModel
/**
* Created by coderkan on 18.06.2017.
// */
class MainPageAdapter : RecyclerView.Adapter<MainPageAdapter.ViewHolder>{
private var mDataset: MutableList<MainPageModel>? = null
private var itemSelectListener : OnItemSelect
private var mContext: Context? = null
constructor(context: Context, dataset: MutableList<MainPageModel>?, itemSelectedListener : OnItemSelect ){
this.mContext = context;
this.mDataset = dataset
this.itemSelectListener = itemSelectedListener
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val layout = R.layout.main_page_item
val v: View = LayoutInflater.from(parent?.context).inflate(layout, parent, false)
return ViewHolder(v)
}
fun add(position: Int, item: MainPageModel) {
mDataset?.add(position, item)
notifyItemInserted(position)
}
fun remove(item: MainPageModel) {
val position = mDataset!!.indexOf(item)
mDataset?.removeAt(position)
notifyItemRemoved(position)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
var model = this.mDataset?.get(position)
holder?.mColorText?.text = model?.name
holder?.mColorText?.setTextColor(Color.parseColor(model?.colorCode))
var gd = holder?.mBorderLayout?.background?.current as GradientDrawable
gd.setStroke(Util.dpToPx(2), Color.parseColor(model?.colorCode))
holder.mMainColorLayout.setBackgroundColor(Color.parseColor(model?.colorCode))
var gradientDrawable = ((holder.mTriangleLayout.background as LayerDrawable).findDrawableByLayerId(R.id.triangle_shape) as RotateDrawable).drawable as GradientDrawable
with(gradientDrawable){
setColor(Color.parseColor(model?.colorCode))
setStroke(Util.dpToPx(2),Color.parseColor(model?.colorCode))
}
holder.mRelativeLayout.setOnClickListener {
this.itemSelectListener.onItemSelected(position)
}
}
override fun getItemCount(): Int {
return mDataset!!.size
}
class ViewHolder(view: View): RecyclerView.ViewHolder(view){
var mColorText = view.findViewById(R.id.text_view_page) as TextView
var mRelativeLayout = view.findViewById(R.id.relative_layout_main_page) as RelativeLayout
var mBorderLayout = view.findViewById(R.id.border_relative_layout) as RelativeLayout
var mMainColorLayout = view.findViewById(R.id.relative_layout_main_page) as RelativeLayout
var mTriangleLayout = view.findViewById(R.id.triangle_image_view) as ImageView
}
} | gpl-3.0 | 801f7fc531173033e2a126881323da92 | 37.823529 | 175 | 0.736587 | 4.410428 | false | false | false | false |
fluidsonic/jetpack-kotlin | Sources/Measurement/Time.kt | 1 | 2085 | package com.github.fluidsonic.jetpack
import java.util.Locale
public class Time : Measurement<Time, Time.Unit> {
private constructor(rawValue: Double) : super(rawValue)
public constructor(time: Time) : super(time.rawValue)
protected override val description: Description<Time, Unit>
get() = Time.description
public fun hours() =
seconds() * hoursPerSecond
public fun milliseconds() =
seconds() * millisecondsPerSecond
public fun minutes() =
seconds() * minutesPerSecond
public fun seconds() =
rawValue
override fun valueInUnit(unit: Unit) =
when (unit) {
Time.Unit.hours -> hours()
Time.Unit.milliseconds -> milliseconds()
Time.Unit.minutes -> minutes()
Time.Unit.seconds -> seconds()
}
public enum class Unit private constructor(key: String) : _StandardUnitType<Unit, Time> {
hours("hour"),
milliseconds("millisecond"),
minutes("minute"),
seconds("second");
public override val _descriptor = _StandardUnitType.Descriptor(key)
public override fun toString() =
pluralName(Locale.getDefault())
public override fun value(value: Double) =
when (this) {
hours -> hours(value)
milliseconds -> milliseconds(value)
minutes -> minutes(value)
seconds -> seconds(value)
}
}
public companion object {
private val description = Measurement.Description("Time", Unit.seconds)
private val secondsPerHour = 3600.0
private val secondsPerMinute = 60.0
private val secondsPerMillisecond = 0.001
private val hoursPerSecond = 1 / secondsPerHour
private val millisecondsPerSecond = 1 / secondsPerMillisecond
private val minutesPerSecond = 1 / secondsPerMinute
public fun hours(hours: Double) =
seconds(validatedValue(hours) * secondsPerHour)
public fun milliseconds(milliseconds: Double) =
seconds(validatedValue(milliseconds) * secondsPerMillisecond)
public fun minutes(minutes: Double) =
seconds(validatedValue(minutes) * secondsPerMinute)
public fun seconds(seconds: Double) =
Time(rawValue = validatedValue(seconds))
}
}
| mit | aaca9cdd56fdbc97efdf17270d0a45a9 | 21.180851 | 90 | 0.711271 | 3.904494 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.