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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/data/LanternDataProviderBuilderBase.kt | 1 | 15843 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.data
import org.lanternpowered.server.data.value.ValueFactory
import org.spongepowered.api.data.DataHolder
import org.spongepowered.api.data.DataTransactionResult
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.value.Value
import org.spongepowered.api.util.Direction
internal abstract class LanternDataProviderBuilderBase<V : Value<E>, E : Any>(private val key: Key<V>) {
protected var allowAsyncAccess: (DataHolder.() -> Boolean)? = null
protected var supportedByHandler: (DataHolder.() -> Boolean)? = null
protected var removeHandler: (DataHolder.Mutable.() -> DataTransactionResult)? = null
protected var removeFastHandler: (DataHolder.Mutable.() -> Boolean)? = null
protected var offerValueHandler: (DataHolder.Mutable.(value: V) -> DataTransactionResult)? = null
protected var offerValueFastHandler: (DataHolder.Mutable.(value: V) -> Boolean)? = null
protected var offerHandler: (DataHolder.Mutable.(element: E) -> DataTransactionResult)? = null
protected var offerFastHandler: (DataHolder.Mutable.(element: E) -> Boolean)? = null
protected var getHandler: (DataHolder.() -> E?)? = null
protected var getDirectionalHandler: (DataHolder.(direction: Direction) -> E?)? = null
protected var getValueHandler: (DataHolder.() -> V?)? = null
protected var getValueDirectionalHandler: (DataHolder.(direction: Direction) -> V?)? = null
protected var withHandler: (DataHolder.Immutable<*>.(element: E) -> DataHolder.Immutable<*>?)? = null
protected var withValueHandler: (DataHolder.Immutable<*>.(value: V) -> DataHolder.Immutable<*>?)? = null
protected var withoutHandler: (DataHolder.Immutable<*>.() -> DataHolder.Immutable<*>?)? = null
fun build(): LanternDataProvider<V, E> {
val supportedTester = this.supportedByHandler ?: { true }
// Generate missing offer handlers, if none is specified,
// offering will always fail
var offerValueHandler = this.offerValueHandler
var offerValueFastHandler = this.offerValueFastHandler
var offerHandler = this.offerHandler
var offerFastHandler = this.offerFastHandler
if (offerValueHandler == null) {
offerValueHandler = when {
this.offerHandler != null -> offerValueFromOffer(this.key, offerHandler!!)
this.offerValueFastHandler != null -> offerValueFromOfferValueFast(this.key, offerValueFastHandler!!)
this.offerFastHandler != null -> offerValueFromOfferFast(this.key, offerFastHandler!!)
else -> offerValueFromFail(this.key)
}
}
if (offerValueFastHandler != null) {
offerValueFastHandler = when {
this.offerValueHandler != null -> offerValueFastFromOfferValue(this.key, offerValueHandler)
this.offerFastHandler != null -> offerValueFastFromOfferFast(this.key, offerFastHandler!!)
this.offerHandler != null -> offerValueFastFromOffer(this.key, offerHandler!!)
else -> offerValueFastFromFail(this.key)
}
}
offerValueFastHandler!! // Uhm, why is this needed?
if (offerHandler != null) {
offerHandler = when {
this.offerValueHandler != null -> offerFromOfferValue(this.key, offerValueHandler)
this.offerFastHandler != null -> offerFromOfferFast(this.key, offerFastHandler!!)
this.offerValueFastHandler != null -> offerFromOfferValueFast(this.key, offerValueFastHandler)
else -> offerFromFail(this.key)
}
}
offerHandler!! // Uhm, why is this needed?
if (offerFastHandler == null) {
offerFastHandler = when {
this.offerHandler != null -> offerFastFromOffer(this.key, offerHandler)
this.offerValueFastHandler != null -> offerFastFromOfferValueFast(this.key, offerValueFastHandler)
this.offerValueHandler != null -> offerFastFromOfferValue(this.key, offerValueHandler)
else -> offerFastFromFail(this.key)
}
}
// Generate missing remove handlers, defaults
// to fail always
// With the exception to optional values, if no
// remove handler is found, it will try to offer
// empty optionals.
var removeHandler = this.removeHandler
var removeFastHandler = this.removeFastHandler
if (removeHandler == null) {
if (removeFastHandler != null) {
removeHandler = removeFromRemoveFast(this.key, removeFastHandler)
} else {
// Default to non removable
removeHandler = failRemoveHandler
removeFastHandler = failRemoveFastHandler
}
}
if (removeFastHandler == null) {
removeFastHandler = removeFastFromRemove(this.key, removeHandler)
}
// Generate missing get handlers, at least
// one must be specified
val originalGetHandler = this.getHandler
val originalGetValueHandler = this.getValueHandler
val originalGetDirectionalHandler = this.getDirectionalHandler
val originalGetValueDirectionalHandler = this.getValueDirectionalHandler
val isDirectional = originalGetDirectionalHandler != null || originalGetValueDirectionalHandler != null
var getHandler = originalGetHandler
var getValueHandler = originalGetValueHandler
var getDirectionalHandler = originalGetDirectionalHandler
var getValueDirectionalHandler = originalGetValueDirectionalHandler
if (getHandler == null) {
getHandler = when {
originalGetValueHandler != null -> getFromGetValue(this.key, originalGetValueHandler)
originalGetDirectionalHandler != null -> getFromGetDirectional(this.key, originalGetDirectionalHandler)
else -> {
checkNotNull(originalGetValueDirectionalHandler) { "At least one get handler must be set" }
getFromGetValueDirectional(this.key, originalGetValueDirectionalHandler)
}
}
}
if (getValueHandler == null) {
getValueHandler = when {
originalGetHandler != null -> getValueFromGet(this.key, originalGetHandler)
originalGetValueDirectionalHandler != null -> getValueFromGetValueDirectional(this.key, originalGetValueDirectionalHandler)
else -> {
checkNotNull(originalGetDirectionalHandler) { "At least one get handler must be set" }
getValueFromGetDirectional(this.key, originalGetDirectionalHandler)
}
}
}
if (isDirectional) {
if (getDirectionalHandler == null) {
originalGetValueDirectionalHandler!!
getDirectionalHandler = getDirectionalFromGetValueDirectional(this.key, originalGetValueDirectionalHandler)
} else if (getValueDirectionalHandler == null) {
originalGetDirectionalHandler!!
getValueDirectionalHandler = getValueDirectionalFromGetDirectional(this.key, originalGetDirectionalHandler)
}
}
// Generate missing with handlers
var withHandler = this.withHandler
var withValueHandler = this.withValueHandler
if (withHandler == null) {
if (withValueHandler != null) {
withHandler = withFromWithValue(this.key, withValueHandler)
} else {
withHandler = { null }
withValueHandler = { null }
}
} else {
withValueHandler = withValueFromWith(this.key, withHandler)
}
val withoutHandler = this.withoutHandler ?: { null }
val allowAsyncAccess = this.allowAsyncAccess ?: { false }
if (isDirectional) {
getDirectionalHandler!!
getValueDirectionalHandler!!
return LanternDirectionalDataProvider(this.key, allowAsyncAccess, supportedTester, removeHandler, removeFastHandler,
offerValueHandler, offerValueFastHandler, offerHandler, offerFastHandler, getHandler, getValueHandler,
getDirectionalHandler, getValueDirectionalHandler, withHandler, withValueHandler, withoutHandler)
}
return LanternDataProvider(this.key, allowAsyncAccess, supportedTester, removeHandler, removeFastHandler,
offerValueHandler, offerValueFastHandler, offerHandler, offerFastHandler, getHandler, getValueHandler, withHandler,
withValueHandler, withoutHandler)
}
private fun <H> withValueFromWith(key: Key<V>, handler: H.(element: E) -> H?): H.(value: V) -> H? {
return { value ->
handler(value.get())
}
}
private fun <H> withFromWithValue(key: Key<V>, handler: H.(value: V) -> H?): H.(element: E) -> H? {
return { element ->
handler(ValueFactory.mutableOf(key, element))
}
}
private fun <H> getDirectionalFromGetValueDirectional(key: Key<V>, handler: H.(direction: Direction) -> V?): H.(direction: Direction) -> E? {
return { direction -> handler(direction)?.get() }
}
private fun <H> getValueDirectionalFromGetDirectional(key: Key<V>, handler: H.(direction: Direction) -> E?): H.(direction: Direction) -> V? {
return { direction ->
val element = handler(direction)
if (element != null) ValueFactory.mutableOf(key, element) else null
}
}
private fun <H> getFromGetValue(key: Key<V>, handler: H.() -> V?): H.() -> E? {
return { handler()?.get() }
}
private fun <H> getFromGetDirectional(key: Key<V>, handler: H.(direction: Direction) -> E?): H.() -> E? {
return { handler(Direction.NONE) }
}
private fun <H> getFromGetValueDirectional(key: Key<V>, handler: H.(direction: Direction) -> V?): H.() -> E? {
return { handler(Direction.NONE)?.get() }
}
private fun <H> getValueFromGet(key: Key<V>, handler: H.() -> E?): H.() -> V? {
return {
val element = handler()
if (element != null) ValueFactory.mutableOf(key, element) else null
}
}
private fun <H> getValueFromGetValueDirectional(key: Key<V>, handler: H.(direction: Direction) -> V?): H.() -> V? {
return { handler(Direction.NONE) }
}
private fun <H> getValueFromGetDirectional(key: Key<V>, handler: H.(direction: Direction) -> E?): H.() -> V? {
return {
val element = handler(Direction.NONE)
if (element != null) ValueFactory.mutableOf(key, element) else null
}
}
private fun <H> offerFromFail(key: Key<V>): H.(value: E) -> DataTransactionResult {
return { value -> DataTransactionResult.failResult(ValueFactory.immutableOf(key, value).asImmutable()) }
}
private fun <H> offerFromOfferValueFast(key: Key<V>, handler: H.(value: V) -> Boolean): H.(value: E) -> DataTransactionResult {
return { element ->
val value = ValueFactory.immutableOf(key, element)
if (handler(value)) {
DataTransactionResult.successResult(value.asImmutable())
} else {
DataTransactionResult.failResult(value.asImmutable())
}
}
}
private fun <H> offerFromOfferFast(key: Key<V>, handler: H.(value: E) -> Boolean): H.(value: E) -> DataTransactionResult {
return { element ->
val value = org.lanternpowered.server.data.value.ValueFactory.immutableOf(key, element).asImmutable()
if (handler(element)) {
DataTransactionResult.successResult(value)
} else {
DataTransactionResult.failResult(value)
}
}
}
private fun <H> offerFromOfferValue(key: Key<V>, handler: H.(value: V) -> DataTransactionResult): H.(value: E) -> DataTransactionResult {
return { value -> handler(ValueFactory.mutableOf(key, value)) }
}
private fun <H> offerValueFastFromFail(key: Key<V>): H.(value: V) -> Boolean {
return { false }
}
private fun <H> offerValueFastFromOffer(key: Key<V>, handler: H.(value: E) -> DataTransactionResult): H.(value: V) -> Boolean {
return { value -> handler(value.get()).isSuccessful }
}
private fun <H> offerValueFastFromOfferFast(key: Key<V>, handler: H.(value: E) -> Boolean): H.(value: V) -> Boolean {
return { value -> handler(value.get()) }
}
private fun <H> offerValueFastFromOfferValue(key: Key<V>, handler: H.(value: V) -> DataTransactionResult): H.(value: V) -> Boolean {
return { value -> handler(value).isSuccessful }
}
private fun <H> offerFastFromFail(key: Key<V>): H.(value: E) -> Boolean {
return { false }
}
private fun <H> offerFastFromOfferValue(key: Key<V>, handler: H.(value: V) -> DataTransactionResult): H.(value: E) -> Boolean {
return { value -> handler(ValueFactory.mutableOf(key, value)).isSuccessful }
}
private fun <H> offerFastFromOfferValueFast(key: Key<V>, handler: H.(value: V) -> Boolean): H.(value: E) -> Boolean {
return { value -> handler(ValueFactory.mutableOf(key, value)) }
}
private fun <H> offerFastFromOffer(key: Key<V>, handler: H.(element: E) -> DataTransactionResult): H.(value: E) -> Boolean {
return { value -> handler(value).isSuccessful }
}
private fun <H> offerValueFromFail(key: Key<V>): H.(value: V) -> DataTransactionResult {
return { value -> DataTransactionResult.failResult(value.asImmutable()) }
}
private fun <H> offerValueFromOfferFast(key: Key<V>, handler: H.(element: E) -> Boolean): H.(value: V) -> DataTransactionResult {
return { value ->
if (handler(value.get())) {
DataTransactionResult.successResult(value.asImmutable())
} else {
DataTransactionResult.failResult(value.asImmutable())
}
}
}
private fun <H> offerValueFromOffer(key: Key<V>, handler: H.(element: E) -> DataTransactionResult): H.(value: V) -> DataTransactionResult {
return { value -> handler(value.get()) }
}
private fun <H> offerValueFromOfferValueFast(key: Key<V>, handler: H.(value: V) -> Boolean): H.(value: V) -> DataTransactionResult {
return { value ->
if (handler(value)) {
DataTransactionResult.successResult(value.asImmutable())
} else {
DataTransactionResult.failResult(value.asImmutable())
}
}
}
private fun <H> removeFromRemoveFast(key: Key<V>, handler: H.() -> Boolean): H.() -> DataTransactionResult {
return {
if (handler()) {
DataTransactionResult.successNoData()
} else {
DataTransactionResult.failNoData()
}
}
}
private fun <H> removeFastFromRemove(key: Key<V>, handler: H.() -> DataTransactionResult): H.() -> Boolean {
return { handler(this).isSuccessful }
}
companion object {
val alwaysAsyncAccess: DataHolder.() -> Boolean = { true }
val failRemoveHandler: DataHolder.() -> DataTransactionResult = { DataTransactionResult.failNoData() }
val failRemoveFastHandler: DataHolder.() -> Boolean = { false }
}
}
| mit | 9e6f7074f8b928f4d01aa1faea5f1322 | 44.525862 | 145 | 0.632519 | 4.520114 | false | false | false | false |
googleapis/gapic-generator-kotlin | example-api-cloud-clients/src/main/kotlin/example/Language.kt | 1 | 1498 | /*
* Copyright 2018 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 example
import com.google.cloud.language.v1.Document
import com.google.cloud.language.v1.LanguageServiceClient
import com.google.cloud.language.v1.document
import kotlinx.coroutines.runBlocking
/**
* Simple example of calling the Natural Language API with a generated Kotlin gRPC client.
*
* Run this example using your service account as follows:
*
* ```
* $ GOOGLE_APPLICATION_CREDENTIALS=<path_to_your_service_account.json> ./gradlew run --language
* ```
*/
fun languageExample() = runBlocking {
// create a client
val client = LanguageServiceClient.fromEnvironment()
// call the API
val result = client.analyzeSentiment(document {
content = "Let's see what this API can do. It's great! Right?"
type = Document.Type.PLAIN_TEXT
})
// print the result
println("The response was: $result")
// shutdown
client.shutdownChannel()
}
| apache-2.0 | a6e98fb56c6fa09ca09c95f11b04cf26 | 30.208333 | 96 | 0.721629 | 4.126722 | false | false | false | false |
hellenxu/AndroidAdvanced | CrashCases/app/src/main/java/six/ca/crashcases/fragment/biz/ContentAdapter.kt | 1 | 5170 | package six.ca.crashcases.fragment.biz
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import six.ca.crashcases.fragment.biz.summary.SummaryFragment
import six.ca.crashcases.fragment.core.ItemFragment
import six.ca.crashcases.fragment.data.AccountType
/**
* @author hellenxu
* @date 2020-10-02
* Copyright 2020 Six. All rights reserved.
*/
class ContentAdapter(
activity: FragmentActivity
) : FragmentStateAdapter(activity) {
private val tabs: MutableList<String> = mutableListOf()
private val ids: MutableList<Long> = mutableListOf()
private var currentTab: String = TAB_SUMMARY
private var currentAccountType: AccountType = AccountType.GUEST
val currentIndex: Int
get() {
return tabs.indexOf(currentTab)
}
// init {
// println("xxl-init00: $accountType")
// initData(accountType)
// }
fun updateCurrentTab(position: Int) {
currentTab = tabs[position]
}
fun updateCurrentTab(tab: String) {
if (tab in tabs) {
currentTab = tab
}
}
fun initData(accountType: AccountType) {
// fragments.clear()
// fragments.addAll(
// when (accountType) {
// AccountType.VIP -> vipFragments()
// AccountType.STANDARD -> standardFragments()
// AccountType.GUEST -> guestFragments()
// }
// )
currentAccountType = accountType
tabs.clear()
tabs.addAll(
when (accountType) {
AccountType.VIP -> vipTabs()
AccountType.STANDARD -> standardTabs()
AccountType.GUEST -> guestTabs()
}
)
ids.clear()
ids.addAll(
when (accountType) {
AccountType.VIP -> vipIds()
AccountType.STANDARD -> standardIds()
AccountType.GUEST -> guestIds()
}
)
notifyDataSetChanged()
}
override fun getItemCount(): Int {
return tabs.size
}
override fun createFragment(position: Int): Fragment {
return createTargetFrag(position)
}
// need to override getItemId() and containsItem(), as mFragments in FragmentStateAdapter
// is used itemId as the key to save fragments
// mFragments.put(itemId, fragment);
override fun getItemId(position: Int): Long {
return ids[position]
}
override fun containsItem(itemId: Long): Boolean {
return ids.contains(itemId)
}
private fun createTargetFrag(position: Int): ItemFragment {
val tab = tabs[position]
return when (currentAccountType) {
AccountType.VIP -> vipFragment(tab)
AccountType.STANDARD -> standardFragment(tab)
AccountType.GUEST -> guestFragment(tab)
}
}
private fun vipFragment(tab: String): ItemFragment {
return when (tab) {
TAB_FOOD -> FoodFragment()
TAB_READING -> ReadingFragment()
TAB_TRAVEL -> TravelFragment()
TAB_WORKOUT -> WorkOutFragment()
else -> SummaryFragment()
}
}
private fun vipTabs(): List<String> {
return listOf(
TAB_SUMMARY,
TAB_FOOD,
TAB_READING,
TAB_TRAVEL,
TAB_WORKOUT
)
}
private fun vipIds(): List<Long> {
return listOf(
ID_DEFAULT + 1,
ID_DEFAULT + 2,
ID_DEFAULT + 3,
ID_DEFAULT + 4,
ID_DEFAULT + 5
)
}
private fun standardFragment(tab: String): ItemFragment {
return when (tab) {
TAB_FOOD -> FoodFragment()
TAB_READING -> ReadingFragment()
TAB_TRAVEL -> TravelFragment()
else -> SummaryFragment()
}
}
private fun standardTabs(): List<String> {
return listOf(
TAB_SUMMARY,
TAB_FOOD,
TAB_READING,
TAB_TRAVEL
)
}
private fun standardIds(): List<Long> {
return listOf(
ID_DEFAULT + 6,
ID_DEFAULT + 7,
ID_DEFAULT + 8,
ID_DEFAULT + 9
)
}
private fun guestFragment(tab: String): ItemFragment {
return when (tab) {
TAB_FOOD -> FoodFragment()
TAB_TRAVEL -> TravelFragment()
else -> SummaryFragment()
}
}
private fun guestTabs(): List<String> {
return listOf(
TAB_SUMMARY,
TAB_FOOD,
TAB_TRAVEL
)
}
private fun guestIds(): List<Long> {
return listOf(
ID_DEFAULT + 10,
ID_DEFAULT + 11,
ID_DEFAULT + 12
)
}
companion object {
private const val TAB_SUMMARY = "summary"
const val TAB_FOOD = "food"
private const val TAB_READING = "reading"
private const val TAB_TRAVEL = "travel"
private const val TAB_WORKOUT = "workout"
private const val ID_DEFAULT = 0X00L
}
} | apache-2.0 | ece28e6cfdf3a4d8d7c78d9a0878aab9 | 25.116162 | 93 | 0.558801 | 4.649281 | false | false | false | false |
android/animation-samples | Motion/app/src/main/java/com/example/android/motion/demo/Transitions.kt | 1 | 3116 | /*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.motion.demo
import androidx.transition.ChangeBounds
import androidx.transition.Fade
import androidx.transition.Transition
import androidx.transition.TransitionSet
/**
* Creates a transition like [androidx.transition.AutoTransition], but customized to be more
* true to Material Design.
*
* Fade through involves one element fading out completely before a new one fades in. These
* transitions can be applied to text, icons, and other elements that don't perfectly overlap.
* This technique lets the background show through during a transition, and it can provide
* continuity between screens when paired with a shared transformation.
*
* See
* [Expressing continuity](https://material.io/design/motion/understanding-motion.html#expressing-continuity)
* for the detail of fade through.
*/
fun fadeThrough(): Transition {
return transitionTogether {
interpolator = FAST_OUT_SLOW_IN
this += ChangeBounds()
this += transitionSequential {
addTransition(Fade(Fade.OUT))
addTransition(Fade(Fade.IN))
}
}
}
inline fun transitionTogether(crossinline body: TransitionSet.() -> Unit): TransitionSet {
return TransitionSet().apply {
ordering = TransitionSet.ORDERING_TOGETHER
body()
}
}
inline fun transitionSequential(
crossinline body: SequentialTransitionSet.() -> Unit
): SequentialTransitionSet {
return SequentialTransitionSet().apply(body)
}
inline fun TransitionSet.forEach(action: (transition: Transition) -> Unit) {
for (i in 0 until transitionCount) {
action(getTransitionAt(i) ?: throw IndexOutOfBoundsException())
}
}
inline fun TransitionSet.forEachIndexed(action: (index: Int, transition: Transition) -> Unit) {
for (i in 0 until transitionCount) {
action(i, getTransitionAt(i) ?: throw IndexOutOfBoundsException())
}
}
operator fun TransitionSet.iterator() = object : MutableIterator<Transition> {
private var index = 0
override fun hasNext() = index < transitionCount
override fun next() =
getTransitionAt(index++) ?: throw IndexOutOfBoundsException()
override fun remove() {
removeTransition(getTransitionAt(--index) ?: throw IndexOutOfBoundsException())
}
}
operator fun TransitionSet.plusAssign(transition: Transition) {
addTransition(transition)
}
operator fun TransitionSet.get(i: Int): Transition {
return getTransitionAt(i) ?: throw IndexOutOfBoundsException()
}
| apache-2.0 | e8df29e787ec55107564916f1f2b8aa7 | 32.505376 | 109 | 0.729461 | 4.555556 | false | false | false | false |
dlew/android-architecture-counter-sample | app/src/main/java/net/danlew/counter/ui/CounterAdapter.kt | 1 | 2497 | package net.danlew.counter.ui
import android.content.Context
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.ViewGroup
import com.jakewharton.rxrelay2.PublishRelay
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import net.danlew.counter.data.Counter
import net.danlew.counter.data.CounterChange
class CounterAdapter(private val context: Context) : RecyclerView.Adapter<CounterViewHolder>() {
private var data: List<Counter> = emptyList()
private val changes = PublishRelay.create<CounterChange>()
private val listener = object : CounterViewHolder.Listener {
override fun onCounterChange(counterChange: CounterChange) = changes.accept(counterChange)
}
init {
setHasStableIds(true)
}
fun changes(): Observable<CounterChange> = changes.hide()
fun bind(source: Flowable<List<Counter>>): Disposable {
data class DataWithDiff(val counters: List<Counter>, val diff: DiffUtil.DiffResult?)
return source
.scan(DataWithDiff(emptyList(), null)) { (old), new ->
DataWithDiff(new, DiffUtil.calculateDiff(DiffCallback(old, new)))
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
data = it.counters
if (it.diff != null) {
it.diff.dispatchUpdatesTo(this)
}
else {
notifyDataSetChanged()
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CounterViewHolder(context, parent)
override fun onBindViewHolder(holder: CounterViewHolder, position: Int) = holder.bind(data[position], listener)
override fun onViewDetachedFromWindow(holder: CounterViewHolder) = holder.detach()
override fun getItemCount() = data.size
override fun getItemId(position: Int) = data[position].id
fun getPosition(itemId: Long) = data.indexOfFirst { it.id == itemId }
private class DiffCallback(private val old: List<Counter>, private val new: List<Counter>) : DiffUtil.Callback() {
override fun getOldListSize() = old.size
override fun getNewListSize() = new.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int)
= old[oldItemPosition].id == new[newItemPosition].id
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int)
= old[oldItemPosition] == new[newItemPosition]
}
} | apache-2.0 | 2fd42f2a6368912bab0a0e143ea20a02 | 33.219178 | 116 | 0.728875 | 4.515371 | false | false | false | false |
hotpodata/Blockelganger | app/src/main/java/com/hotpodata/blockelganger/fragment/DialogHowToPlayFragment.kt | 1 | 2840 | package com.hotpodata.blockelganger.fragment
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import com.hotpodata.blockelganger.R
import kotlinx.android.synthetic.main.fragment_dialog_how_to_play.*
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import timber.log.Timber
import java.util.concurrent.TimeUnit
/**
* Created by jdrotos on 12/28/15.
*/
class DialogHowToPlayFragment : DialogFragment() {
public interface IDialogHowToPlayListener {
fun onHelpDialogDismissed()
}
var dialogLisetner: IDialogHowToPlayListener? = null
var timerSub: Subscription? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
dialogLisetner = context as? IDialogHowToPlayListener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog? {
val dialog = super.onCreateDialog(savedInstanceState)
// request a window without the title
dialog.window.requestFeature(Window.FEATURE_NO_TITLE)
dialog.setCanceledOnTouchOutside(true)
return dialog
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.fragment_dialog_how_to_play, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn_got_it.setOnClickListener {
Timber.d("Calling dismiss()")
dismiss()
}
step_one_video.setZOrderOnTop(true)
}
override fun onResume() {
super.onResume()
val uriPath = "android.resource://" + getActivity().getPackageName() + "/" + R.raw.blockelganger_how_to_play_step1
val uri = Uri.parse(uriPath)
step_one_video.setVideoURI(uri)
step_one_video.setOnCompletionListener(MediaPlayer.OnCompletionListener {
timerSub = Observable.timer(3, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
if (isResumed && isAdded) {
step_one_video.start()
}
}
})
step_one_video.start()
}
override fun onPause() {
super.onPause()
timerSub?.unsubscribe()
step_one_video.stopPlayback()
}
override fun onDismiss(dialog: DialogInterface) {
super.onDismiss(dialog)
Timber.d("OnDismissListener firing!")
dialogLisetner?.onHelpDialogDismissed()
}
} | apache-2.0 | 194ce962580694595e8605d809362959 | 31.284091 | 122 | 0.695423 | 4.529506 | false | false | false | false |
CineCor/CinecorAndroid | app/src/main/java/com/cinecor/android/data/source/remote/CinecorRemoteDataSource.kt | 1 | 1514 | package com.cinecor.android.data.source.remote
import com.cinecor.android.data.model.Cinema
import com.cinecor.android.data.model.Movie
import com.cinecor.android.data.source.CinecorDataSource
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.FirebaseDatabase
import durdinapps.rxfirebase2.DataSnapshotMapper
import durdinapps.rxfirebase2.RxFirebaseAuth
import durdinapps.rxfirebase2.RxFirebaseDatabase
import io.reactivex.Flowable
import javax.inject.Inject
class CinecorRemoteDataSource
@Inject constructor(private val firebaseAuth: FirebaseAuth, private val database: FirebaseDatabase)
: CinecorDataSource {
private var cinemas = RxFirebaseAuth.signInAnonymously(firebaseAuth).toFlowable().flatMap {
RxFirebaseDatabase.observeValueEvent(database.getReference("cinemas"), DataSnapshotMapper.listOf<Cinema>(Cinema::class.java))
}
override fun getCinemas(): Flowable<List<Cinema>> =
cinemas
override fun getCinema(id: Int): Flowable<Cinema> =
cinemas.map { it.find { it.id == id } }
override fun getMoviesFromCinema(id: Int): Flowable<List<Movie>> =
cinemas.map { it.find { it.id == id }?.movies }
override fun getMovieFromCinema(cinemaId: Int, movieId: Int): Flowable<Movie> =
cinemas.map { it.find { it.id == cinemaId }?.movies?.find { it.id == movieId } }
override fun saveCinemas(cinemas: List<Cinema>) {} // Not needed here
override fun deleteCinemas() {} // Not needed here
}
| gpl-3.0 | 724d3395726d2b43975e98f59bf46f6c | 39.918919 | 133 | 0.747688 | 3.953003 | false | false | false | false |
arturbosch/detekt | detekt-rules-naming/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/naming/ClassNamingSpec.kt | 1 | 1888 | package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.test.assertThat
import io.gitlab.arturbosch.detekt.test.compileAndLint
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class ClassNamingSpec : Spek({
describe("different naming conventions inside classes") {
it("should detect no violations class with numbers") {
val code = """
class MyClassWithNumbers5
"""
assertThat(ClassNaming().compileAndLint(code)).isEmpty()
}
it("should detect no violations") {
val code = """
class NamingConventions {
}
"""
assertThat(ClassNaming().compileAndLint(code)).isEmpty()
}
it("should detect no violations with class using backticks") {
val code = """
class `NamingConventions`
"""
assertThat(ClassNaming().compileAndLint(code)).isEmpty()
}
it("should detect because it have a _") {
val code = """
class _NamingConventions
"""
assertThat(ClassNaming().compileAndLint(code))
.hasSize(1)
.hasTextLocations(6 to 24)
}
it("should detect because it have starts with lowercase") {
val code = """
class namingConventions {}
"""
assertThat(ClassNaming().compileAndLint(code))
.hasSize(1)
.hasTextLocations(6 to 23)
}
it("should ignore the issue by alias suppression") {
val code = """
@Suppress("ClassName")
class namingConventions {}
"""
assertThat(ClassNaming().compileAndLint(code)).isEmpty()
}
}
})
| apache-2.0 | a72af637cd8a137c8af6977c5daa2d4c | 28.046154 | 70 | 0.54714 | 5.409742 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/recording/NotificationRecordingCleanupJob.kt | 1 | 1722 | package net.nemerosa.ontrack.extension.notifications.recording
import net.nemerosa.ontrack.extension.notifications.NotificationsJobs
import net.nemerosa.ontrack.job.*
import net.nemerosa.ontrack.job.orchestrator.JobOrchestratorSupplier
import net.nemerosa.ontrack.model.settings.CachedSettingsService
import org.springframework.stereotype.Component
import java.util.stream.Stream
@Component
class NotificationRecordingCleanupJob(
private val cachedSettingsService: CachedSettingsService,
private val notificationRecordingService: NotificationRecordingService,
) : JobOrchestratorSupplier {
override fun collectJobRegistrations(): Stream<JobRegistration> = listOf(
createNotificationRecordingCleanupJobRegistration()
).stream()
private fun createNotificationRecordingCleanupJobRegistration() = JobRegistration(
job = createNotificationRecordingCleanupJob(),
schedule = Schedule.everySeconds(cachedSettingsService.getCachedSettings(NotificationRecordingSettings::class.java).cleanupIntervalSeconds),
)
private fun createNotificationRecordingCleanupJob() = object : Job {
override fun getKey(): JobKey =
NotificationsJobs.category
.getType("recording-cleanup").withName("Notification recordings cleanup")
.getKey("main")
override fun getTask() = JobRun {
val settings = cachedSettingsService.getCachedSettings(NotificationRecordingSettings::class.java)
notificationRecordingService.clear(settings.retentionSeconds)
}
override fun getDescription(): String =
"Cleanup of notification recordings"
override fun isDisabled(): Boolean = false
}
} | mit | 54ed035e725784a34cd3c9c337f13f0d | 40.02381 | 148 | 0.763066 | 5.572816 | false | false | false | false |
wiltonlazary/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/BridgesBuilding.kt | 1 | 11986 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.ClassLoweringPass
import org.jetbrains.kotlin.backend.common.DeclarationContainerLoweringPass
import org.jetbrains.kotlin.backend.common.ir.simpleFunctions
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.lower.irBlockBody
import org.jetbrains.kotlin.backend.common.lower.irIfThen
import org.jetbrains.kotlin.backend.konan.Context
import org.jetbrains.kotlin.backend.konan.descriptors.*
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.declarations.impl.IrFunctionImpl
import org.jetbrains.kotlin.ir.declarations.impl.IrValueParameterImpl
import org.jetbrains.kotlin.ir.descriptors.WrappedSimpleFunctionDescriptor
import org.jetbrains.kotlin.ir.descriptors.WrappedValueParameterDescriptor
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.*
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol
import org.jetbrains.kotlin.ir.symbols.impl.IrSimpleFunctionSymbolImpl
import org.jetbrains.kotlin.ir.symbols.impl.IrValueParameterSymbolImpl
import org.jetbrains.kotlin.ir.types.IrType
import org.jetbrains.kotlin.ir.types.isNullableAny
import org.jetbrains.kotlin.ir.util.transformFlat
import org.jetbrains.kotlin.ir.visitors.IrElementTransformerVoid
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.load.java.BuiltinMethodsWithSpecialGenericSignature
internal class WorkersBridgesBuilding(val context: Context) : DeclarationContainerLoweringPass, IrElementTransformerVoid() {
val symbols = context.ir.symbols
lateinit var runtimeJobFunction: IrSimpleFunction
override fun lower(irDeclarationContainer: IrDeclarationContainer) {
irDeclarationContainer.declarations.transformFlat {
listOf(it) + buildWorkerBridges(it).also { bridges ->
// `buildWorkerBridges` builds bridges for all declarations inside `it` and nested declarations,
// so some bridges get incorrect parent. Fix it:
bridges.forEach { bridge -> bridge.parent = irDeclarationContainer }
}
}
}
private fun buildWorkerBridges(declaration: IrDeclaration): List<IrFunction> {
val bridges = mutableListOf<IrFunction>()
declaration.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitCall(expression: IrCall): IrExpression {
expression.transformChildrenVoid(this)
if (expression.symbol != symbols.executeImpl)
return expression
val job = expression.getValueArgument(3) as IrFunctionReference
val jobFunction = (job.symbol as IrSimpleFunctionSymbol).owner
if (!::runtimeJobFunction.isInitialized) {
val arg = jobFunction.valueParameters[0]
val startOffset = jobFunction.startOffset
val endOffset = jobFunction.endOffset
runtimeJobFunction = WrappedSimpleFunctionDescriptor().let {
IrFunctionImpl(
startOffset, endOffset,
IrDeclarationOrigin.DEFINED,
IrSimpleFunctionSymbolImpl(it),
jobFunction.name,
jobFunction.visibility,
jobFunction.modality,
isInline = false,
isExternal = false,
isTailrec = false,
isSuspend = false,
returnType = context.irBuiltIns.anyNType,
isExpect = false,
isFakeOverride = false,
isOperator = false,
isInfix = false
).apply {
it.bind(this)
}
}
runtimeJobFunction.valueParameters += WrappedValueParameterDescriptor().let {
IrValueParameterImpl(
startOffset, endOffset,
IrDeclarationOrigin.DEFINED,
IrValueParameterSymbolImpl(it),
arg.name,
arg.index,
type = context.irBuiltIns.anyNType,
varargElementType = null,
isCrossinline = arg.isCrossinline,
isNoinline = arg.isNoinline
).apply { it.bind(this) }
}
}
val overriddenJobDescriptor = OverriddenFunctionInfo(jobFunction, runtimeJobFunction)
if (!overriddenJobDescriptor.needBridge) return expression
val bridge = context.buildBridge(
startOffset = job.startOffset,
endOffset = job.endOffset,
overriddenFunction = overriddenJobDescriptor,
targetSymbol = jobFunction.symbol)
bridges += bridge
expression.putValueArgument(3, IrFunctionReferenceImpl(
startOffset = job.startOffset,
endOffset = job.endOffset,
type = job.type,
symbol = bridge.symbol,
typeArgumentsCount = 0,
reflectionTarget = null)
)
return expression
}
})
return bridges
}
}
internal class BridgesBuilding(val context: Context) : ClassLoweringPass {
override fun lower(irClass: IrClass) {
val builtBridges = mutableSetOf<IrSimpleFunction>()
irClass.simpleFunctions()
.forEach { function ->
function.allOverriddenFunctions
.map { OverriddenFunctionInfo(function, it) }
.filter { !it.bridgeDirections.allNotNeeded() }
.filter { it.canBeCalledVirtually }
.filter { !it.inheritsBridge }
.distinctBy { it.bridgeDirections }
.forEach {
buildBridge(it, irClass)
builtBridges += it.function
}
}
irClass.transformChildrenVoid(object: IrElementTransformerVoid() {
override fun visitFunction(declaration: IrFunction): IrStatement {
declaration.transformChildrenVoid(this)
val body = declaration.body ?: return declaration
val descriptor = declaration.descriptor
val typeSafeBarrierDescription = BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(descriptor)
if (typeSafeBarrierDescription == null || builtBridges.contains(declaration))
return declaration
val irBuilder = context.createIrBuilder(declaration.symbol, declaration.startOffset, declaration.endOffset)
declaration.body = irBuilder.irBlockBody(declaration) {
buildTypeSafeBarrier(declaration, declaration, typeSafeBarrierDescription)
(body as IrBlockBody).statements.forEach { +it }
}
return declaration
}
})
}
private fun buildBridge(overriddenFunction: OverriddenFunctionInfo, irClass: IrClass) {
irClass.declarations.add(context.buildBridge(
startOffset = irClass.startOffset,
endOffset = irClass.endOffset,
overriddenFunction = overriddenFunction,
targetSymbol = overriddenFunction.function.symbol,
superQualifierSymbol = irClass.symbol)
)
}
}
internal class DECLARATION_ORIGIN_BRIDGE_METHOD(val bridgeTarget: IrFunction) : IrDeclarationOrigin {
override fun toString(): String {
return "BRIDGE_METHOD(target=${bridgeTarget.descriptor})"
}
}
internal val IrFunction.bridgeTarget: IrFunction?
get() = (origin as? DECLARATION_ORIGIN_BRIDGE_METHOD)?.bridgeTarget
private fun IrBuilderWithScope.returnIfBadType(value: IrExpression,
type: IrType,
returnValueOnFail: IrExpression)
= irIfThen(irNotIs(value, type), irReturn(returnValueOnFail))
private fun IrBuilderWithScope.irConst(value: Any?) = when (value) {
null -> irNull()
is Int -> irInt(value)
is Boolean -> if (value) irTrue() else irFalse()
else -> TODO()
}
private fun IrBlockBodyBuilder.buildTypeSafeBarrier(function: IrFunction,
originalFunction: IrFunction,
typeSafeBarrierDescription: BuiltinMethodsWithSpecialGenericSignature.TypeSafeBarrierDescription) {
val valueParameters = function.valueParameters
val originalValueParameters = originalFunction.valueParameters
for (i in valueParameters.indices) {
if (!typeSafeBarrierDescription.checkParameter(i))
continue
val type = originalValueParameters[i].type
if (!type.isNullableAny()) {
+returnIfBadType(irGet(valueParameters[i]), type,
if (typeSafeBarrierDescription == BuiltinMethodsWithSpecialGenericSignature.TypeSafeBarrierDescription.MAP_GET_OR_DEFAULT)
irGet(valueParameters[2])
else irConst(typeSafeBarrierDescription.defaultValue)
)
}
}
}
private fun Context.buildBridge(startOffset: Int, endOffset: Int,
overriddenFunction: OverriddenFunctionInfo, targetSymbol: IrSimpleFunctionSymbol,
superQualifierSymbol: IrClassSymbol? = null): IrFunction {
val bridge = specialDeclarationsFactory.getBridge(overriddenFunction)
if (bridge.modality == Modality.ABSTRACT) {
return bridge
}
val irBuilder = createIrBuilder(bridge.symbol, startOffset, endOffset)
bridge.body = irBuilder.irBlockBody(bridge) {
val typeSafeBarrierDescription = BuiltinMethodsWithSpecialGenericSignature.getDefaultValueForOverriddenBuiltinFunction(overriddenFunction.overriddenFunction.descriptor)
typeSafeBarrierDescription?.let { buildTypeSafeBarrier(bridge, overriddenFunction.function, it) }
val delegatingCall = IrCallImpl(
startOffset,
endOffset,
targetSymbol.owner.returnType,
targetSymbol,
superQualifierSymbol = superQualifierSymbol /* Call non-virtually */
).apply {
bridge.dispatchReceiverParameter?.let {
dispatchReceiver = irGet(it)
}
bridge.extensionReceiverParameter?.let {
extensionReceiver = irGet(it)
}
bridge.valueParameters.forEachIndexed { index, parameter ->
this.putValueArgument(index, irGet(parameter))
}
}
+irReturn(delegatingCall)
}
return bridge
} | apache-2.0 | 19bf36c96217a0acb893715483704da5 | 46.007843 | 176 | 0.607542 | 5.846829 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsAnonymousParameterInspection.kt | 1 | 1173 | package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.rust.ide.inspections.fixes.SubstituteTextFix
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsFunctionRole
import org.rust.lang.core.psi.ext.parentOfType
import org.rust.lang.core.psi.ext.role
class RsAnonymousParameterInspection : RsLocalInspectionTool() {
override fun getDisplayName(): String = "Anonymous function parameter"
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor = object : RsVisitor() {
override fun visitValueParameter(o: RsValueParameter) {
if (o.pat != null) return
val fn = o.parentOfType<RsFunction>() ?: return
if (o.parentOfType<RsPath>() != null) return
if (fn.role == RsFunctionRole.TRAIT_METHOD) {
holder.registerProblem(o,
"Anonymous functions parameters are deprecated (RFC 1685)",
SubstituteTextFix(fn.containingFile, o.textRange, "_: ${o.text}", "Add dummy parameter name")
)
}
}
}
}
| mit | cb57c07e7e25201a4cfb273a759ae476 | 42.444444 | 118 | 0.681159 | 4.460076 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/types/infer/Declarations.kt | 1 | 6460 | package org.rust.lang.core.types.infer
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.findIteratorItemType
import org.rust.lang.core.types.ty.*
import org.rust.lang.core.types.type
fun inferDeclarationType(decl: RsNamedElement): Ty {
return when (decl) {
is RsStructItem -> TyStruct(decl)
is RsEnumItem -> TyEnum(decl)
is RsEnumVariant -> TyEnum(decl.parentEnum)
is RsTypeAlias -> {
val t = decl.typeReference?.type ?: TyUnknown
(t as? TyStructOrEnumBase)
?.aliasTypeArguments(decl.typeParameters.map(::TyTypeParameter)) ?: t
}
is RsFunction -> deviseFunctionType(decl)
is RsTraitItem -> TyTraitObject(decl)
is RsConstant -> decl.typeReference?.type ?: TyUnknown
is RsSelfParameter -> deviseSelfType(decl)
is RsPatBinding -> {
val pattern = decl.topLevelPattern
val parent = pattern.parent
val patternType = when (parent) {
is RsLetDecl ->
// use type ascription, if present or fallback to the type of the initializer expression
parent.typeReference?.type ?: parent.expr?.type
is RsValueParameter -> parent.typeReference?.type ?: inferTypeForLambdaParameter(parent)
is RsCondition -> parent.expr.type
is RsMatchArm -> parent.parentOfType<RsMatchExpr>()?.expr?.type
is RsForExpr -> findIteratorItemType(decl.project, parent.expr?.type ?: TyUnknown)
else -> null
} ?: TyUnknown
inferPatternBindingType(decl, pattern, patternType)
}
is RsTypeParameter -> TyTypeParameter(decl)
else -> TyUnknown
}
}
private val RsCallExpr.declaration: RsFunction?
get() = (expr as? RsPathExpr)?.path?.reference?.resolve() as? RsFunction
private val RsMethodCallExpr.declaration: RsFunction?
get() = reference.resolve() as? RsFunction
private val RsTypeParamBounds.boundTraitRefs: Collection<RsTraitRef>
get() = polyboundList.mapNotNull { it.bound.traitRef }
fun inferTypeForLambdaExpr(lambdaExpr: RsLambdaExpr): Collection<RsTraitRef> {
val parent = lambdaExpr.parent as? RsValueArgumentList ?: return emptyList()
val callExpr = parent.parent
val typeOfFunction = when (callExpr) {
is RsCallExpr -> callExpr.declaration ?: return emptyList()
is RsMethodCallExpr -> callExpr.declaration ?: return emptyList()
else -> return emptyList()
}
val pos = parent.exprList.indexOf(lambdaExpr)
val typeReference = typeOfFunction.valueParameterList
?.valueParameterList
?.get(pos)
?.typeReference ?: return emptyList()
var result = emptyList<RsTraitRef>()
typeOfFunction.typeParameterList
?.typeParameterList
?.filter { it.identifier.text == typeReference.text }
?.forEach {
result += it.typeParamBounds?.boundTraitRefs ?: emptyList()
}
typeOfFunction.whereClause
?.wherePredList
?.filter { it.typeReference?.text == typeReference.text }
?.forEach {
result += it.typeParamBounds?.boundTraitRefs ?: emptyList()
}
return result
}
fun inferTypeForLambdaParameter(parameter: RsValueParameter): Ty {
val lambda = parameter.parentOfType<RsLambdaExpr>() ?: return TyUnknown
val parameterPos = lambda.valueParameterList.valueParameterList.indexOf(parameter)
val bounds = inferTypeForLambdaExpr(lambda)
return bounds.asSequence()
.mapNotNull { it.path.valueParameterList?.valueParameterList?.get(parameterPos) }
.firstOrNull()
.let { it?.typeReference?.type ?: TyUnknown }
}
fun inferTypeReferenceType(ref: RsTypeReference): Ty {
return when (ref) {
is RsTupleType -> {
val single = ref.typeReferenceList.singleOrNull()
if (single != null && ref.rparen.getPrevNonCommentSibling()?.elementType != RsElementTypes.COMMA) {
return inferTypeReferenceType(single)
}
if (ref.typeReferenceList.isEmpty()) {
return TyUnit
}
TyTuple(ref.typeReferenceList.map(::inferTypeReferenceType))
}
is RsBaseType -> {
val path = ref.path ?: return TyUnknown
val primitiveType = TyPrimitive.fromPath(path)
if (primitiveType != null) return primitiveType
val target = ref.path?.reference?.resolve() as? RsNamedElement
?: return TyUnknown
val typeArguments = path.typeArgumentList?.typeReferenceList.orEmpty()
inferDeclarationType(target)
.applyTypeArguments(typeArguments.map { it.type })
}
is RsRefLikeType -> {
val base = ref.typeReference ?: return TyUnknown
val mutable = ref.isMut
if (ref.isRef) {
TyReference(inferTypeReferenceType(base), mutable)
} else {
if (ref.isPointer) { //Raw pointers
TyPointer(inferTypeReferenceType(base), mutable)
} else {
TyUnknown
}
}
}
is RsArrayType -> {
val componentType = ref.typeReference?.type ?: TyUnknown
val size = ref.arraySize
if (size == null) {
TySlice(componentType)
} else {
TyArray(componentType, size)
}
}
else -> TyUnknown
}
}
/**
* Devises type for the given (implicit) self-argument
*/
private fun deviseSelfType(self: RsSelfParameter): Ty {
val impl = self.parentOfType<RsImplItem>()
var Self: Ty = if (impl != null) {
impl.typeReference?.type ?: return TyUnknown
} else {
val trait = self.parentOfType<RsTraitItem>()
?: return TyUnknown
TyTypeParameter(trait)
}
if (self.isRef) {
Self = TyReference(Self, mutable = self.isMut)
}
return Self
}
private fun deviseFunctionType(fn: RsFunction): TyFunction {
val paramTypes = mutableListOf<Ty>()
val self = fn.selfParameter
if (self != null) {
paramTypes += deviseSelfType(self)
}
paramTypes += fn.valueParameters.map { it.typeReference?.type ?: TyUnknown }
return TyFunction(paramTypes, fn.returnType)
}
| mit | 1feb463f89be07aa5e3494e0700c6dc0 | 33.179894 | 111 | 0.621981 | 4.893939 | false | false | false | false |
groupdocs-comparison/GroupDocs.Comparison-for-Java | Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/model/TreeResponse.kt | 3 | 223 | package com.groupdocs.ui.model
data class FileDescriptionEntity(
val guid: String? = null,
val name: String? = null,
val docType: String? = null,
val directory: Boolean? = null,
val size: Long? = null
) | mit | a358d816a8148bf56b5635a6189d5916 | 23.888889 | 35 | 0.663677 | 3.539683 | false | false | false | false |
is00hcw/anko | dsl/src/org/jetbrains/android/anko/render/SqlParserHelperRenderer.kt | 5 | 2039 | /*
* Copyright 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.
*/
package org.jetbrains.android.anko.render
import org.jetbrains.android.anko.config.AnkoConfiguration
import org.jetbrains.android.anko.config.AnkoFile
import org.jetbrains.android.anko.config.ConfigurationOption
import org.jetbrains.android.anko.generator.GenerationState
import org.jetbrains.android.anko.utils.buffer
class SqlParserHelperRenderer(config: AnkoConfiguration) : Renderer(config) {
override val renderIf: Array<ConfigurationOption> = arrayOf(AnkoFile.SQL_PARSER_HELPERS)
override fun processElements(state: GenerationState) = StringBuilder {
for (i in 1..22) {
val types = (1..i).map { "T$it" }.joinToString(", ")
val args = (1..i).map { "columns[${it - 1}] as T$it" }.joinToString(", ")
append(buffer {
line("public fun <$types, R> rowParser(parser: ($types) -> R): RowParser<R> {")
line("return object : RowParser<R> {")
line("override fun parseRow(columns: Array<Any>): R {")
line("if (columns.size() != $i)")
val s = if (i == 1) "" else "s"
indent.line("throw SQLiteException(\"Invalid row: $i column$s required\")")
line("@suppress(\"UNCHECKED_CAST\")")
line("return parser($args)")
line("}")
line("}")
line("}")
nl()
}.toString())
}
}.toString()
} | apache-2.0 | d196e6b708121912cf4d64b4c956fe9d | 39 | 95 | 0.62874 | 4.256785 | false | true | false | false |
Ztiany/Repository | Kotlin/Kotlin-github/app/src/main/java/com/bennyhuo/github/view/RepoDetailActivity.kt | 2 | 8522 | package com.bennyhuo.github.view
import android.os.Bundle
import com.apollographql.apollo.rx.RxApollo
import com.bennyhuo.experimental.coroutines.awaitOrError
import com.bennyhuo.experimental.coroutines.launchUI
import com.bennyhuo.github.R
import com.bennyhuo.github.network.GraphQLService
import com.bennyhuo.github.network.apolloClient
import com.bennyhuo.github.network.entities.Repository
import com.bennyhuo.github.network.graphql.entities.RepositoryIssueCountQuery
import com.bennyhuo.github.network.services.ActivityService
import com.bennyhuo.github.network.services.RepositoryService
import com.bennyhuo.github.utils.*
import com.bennyhuo.github.view.common.BaseDetailSwipeFinishableActivity
import com.bennyhuo.tieguanyin.annotations.ActivityBuilder
import com.bennyhuo.tieguanyin.annotations.Required
import kotlinx.android.synthetic.main.activity_repo_details.*
import kotlinx.android.synthetic.main.app_bar_details.*
import retrofit2.Response
import rx.Subscriber
@ActivityBuilder
class RepoDetailActivity: BaseDetailSwipeFinishableActivity() {
@Required
lateinit var repository: Repository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_repo_details)
setSupportActionBar(toolBar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
initDetails()
reloadDetails()
}
private fun initDetails(){
avatarView.loadWithGlide(repository.owner.avatar_url, repository.owner.login.first())
collapsingToolbar.title = repository.name
descriptionView.markdownText = getString(R.string.repo_description_template,
repository.owner.login,
repository.owner.html_url,
repository.name,
repository.html_url,
repository.owner.login,
repository.owner.html_url,
githubTimeToDate(repository.created_at).view())
bodyView.text = repository.description
detailContainer.alpha = 0f
stars.checkEvent = { isChecked ->
if(isChecked){
ActivityService.unstar(repository.owner.login, repository.name)
.map { false }
} else {
ActivityService.star(repository.owner.login, repository.name)
.map { true }
}.doOnNext { reloadDetails(true) }
}
watches.checkEvent = { isChecked ->
if(isChecked){
ActivityService.unwatch(repository.owner.login, repository.name)
.map { false }
} else {
ActivityService.watch(repository.owner.login, repository.name)
.map { true }
}.doOnNext { reloadDetails(true) }
}
ActivityService.isStarred(repository.owner.login, repository.name)
.onErrorReturn {
if(it is retrofit2.HttpException){
it.response() as Response<Any>
} else {
throw it
}
}
.subscribeIgnoreError {
stars.isChecked = it.isSuccessful
}
// ActivityService.isWatched(repository.owner.login, repository.name)
// .subscribeIgnoreError {
// watches.isChecked = it.subscribed
// }
// launchUI {
// try {
// watches.isChecked = ActivityService.isWatchedDeferred(repository.owner.login, repository.name).await().subscribed
// } catch (e: Exception) {
// e.printStackTrace()
// }
// }
// launchUI {
// val (subscriptionResponse, error) = ActivityService.isWatchedDeferred(repository.owner.login, repository.name).awaitOrError()
// error?.printStackTrace() ?: run {
// watches.isChecked = subscriptionResponse!!.subscribed
// }
// }
launchUI {
val (subscriptionResponse, error) = ActivityService.isWatchedDeferred(repository.owner.login, repository.name).awaitOrError()
error?.printStackTrace() ?: run {
watches.isChecked = subscriptionResponse.subscribed
}
}
}
private fun reloadDetails(forceNetwork: Boolean = false){
RepositoryService.getRepository(repository.owner.login, repository.name, forceNetwork)
.subscribe(object: Subscriber<Repository>(){
override fun onStart() {
super.onStart()
loadingView.animate().alpha(1f).start()
}
override fun onNext(t: Repository) {
repository = t
owner.content = repository.owner.login
stars.content = repository.stargazers_count.toString()
watches.content = repository.subscribers_count.toString()
forks.content = repository.forks_count.toString()
//issues.content = repository.open_issues_count.toString()
loadingView.animate().alpha(0f).start()
detailContainer.animate().alpha(1f).start()
}
override fun onCompleted() = Unit
override fun onError(e: Throwable) {
loadingView.animate().alpha(0f).start()
e.printStackTrace()
}
})
val watcher = apolloClient.query(RepositoryIssueCountQuery(repository.name, repository.owner.login)).watcher()
RxApollo.from(watcher)
// .subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe {
// it.data()?.let{
// issues.content = "open: ${it.repository()?.openIssues()?.totalCount()?: 0} closed: ${it.repository()?.closedIssues()?.totalCount()?: 0}"
// }
// }
// GraphQLService.repositoryIssueCount(repository.owner.login, repository.name)
// .subscribeIgnoreError {
// data ->
// issues.content = "open: ${data.repository()?.openIssues()?.totalCount()?: 0} closed: ${data.repository()?.closedIssues()?.totalCount()?: 0}"
// }
launchUI {
val (data, error) = GraphQLService.repositoryIssueCount3(repository.owner.login, repository.name).awaitOrError()
error?.printStackTrace()?: kotlin.run {
issues.content = "open: ${data.repository()?.openIssues()?.totalCount()?: 0} closed: ${data.repository()?.closedIssues()?.totalCount()?: 0}"
}
}
// GraphQLService.repositoryIssueCount2(repository.owner.login, repository.name)
// .enqueue(object : ApolloCall.Callback<RepositoryIssueCountQuery.Data>(){
// override fun onFailure(e: ApolloException) {
// e.printStackTrace()
// }
//
// override fun onResponse(response: com.apollographql.apollo.api.Response<Data>) {
// runOnUiThread {
// response.data()?.let{
// issues.content = "open: ${it.repository()?.openIssues()?.totalCount()?: 0} closed: ${it.repository()?.closedIssues()?.totalCount()?: 0}"
// }
// }
// }
//
// })
// apolloClient.query(RepositoryIssueCountQuery(repository.name, repository.owner.login))
// .enqueue(object : ApolloCall.Callback<RepositoryIssueCountQuery.Data>(){
// override fun onFailure(e: ApolloException) {
// e.printStackTrace()
// }
//
// override fun onResponse(response: com.apollographql.apollo.api.Response<Data>) {
// runOnUiThread {
// response.data()?.let{
// issues.content = "open: ${it.repository()?.openIssues()?.totalCount()?: 0} closed: ${it.repository()?.closedIssues()?.totalCount()?: 0}"
// }
// }
// }
//
// })
}
} | apache-2.0 | ad83fbb1c25e9f9bfa9b99e017770398 | 40.173913 | 170 | 0.564304 | 5.045589 | false | false | false | false |
chromeos/vulkanphotobooth | app/src/main/java/dev/hadrosaur/vulkanphotobooth/CameraUtils.kt | 1 | 9964 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.hadrosaur.vulkanphotobooth
import android.graphics.ImageFormat
import android.graphics.Rect
import android.hardware.camera2.*
import android.hardware.camera2.CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE
import android.os.Build
import android.view.Surface
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.FIXED_FOCUS_DISTANCE
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.allCameraParams
import dev.hadrosaur.vulkanphotobooth.MainActivity.Companion.logd
import dev.hadrosaur.vulkanphotobooth.cameracontroller.Camera2CaptureSessionCallback
import dev.hadrosaur.vulkanphotobooth.cameracontroller.Camera2DeviceStateCallback
import java.util.*
/** The focus mechanism to request for captures */
enum class FocusMode(private val mode: String) {
/** Auto-focus */
AUTO("Auto"),
/** Continous auto-focus */
CONTINUOUS("Continuous"),
/** For fixed-focus lenses */
FIXED("Fixed")
}
/**
* For all the cameras associated with the device, populate the CameraParams values and add them to
* the companion object for the activity.
*/
fun initializeCameras(activity: MainActivity) {
val manager = activity.getSystemService(AppCompatActivity.CAMERA_SERVICE) as CameraManager
try {
val numCameras = manager.cameraIdList.size
for (cameraId in manager.cameraIdList) {
val tempCameraParams = CameraParams().apply {
logd("Camera " + cameraId + " of " + numCameras)
// Get camera characteristics and capabilities
val cameraChars = manager.getCameraCharacteristics(cameraId)
val cameraCapabilities =
cameraChars.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES)
?: IntArray(0)
// Multi-camera?
for (capability in cameraCapabilities) {
if (capability ==
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA) {
hasMulti = true
} else if (capability ==
CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR) {
hasManualControl = true
}
}
id = cameraId
isOpen = false
hasFlash = cameraChars.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) ?: false
isFront = CameraCharacteristics.LENS_FACING_FRONT ==
cameraChars.get(CameraCharacteristics.LENS_FACING)
isExternal = (Build.VERSION.SDK_INT >= 23 &&
CameraCharacteristics.LENS_FACING_EXTERNAL ==
cameraChars.get(CameraCharacteristics.LENS_FACING))
characteristics = cameraChars
orientation = cameraChars.get(CameraCharacteristics.SENSOR_ORIENTATION) ?: 0
focalLengths =
cameraChars.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
?: FloatArray(0)
smallestFocalLength = smallestFocalLength(focalLengths)
minDeltaFromNormal = focalLengthMinDeltaFromNormal(focalLengths)
apertures = cameraChars.get(CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES)
?: FloatArray(0)
largestAperture = largestAperture(apertures)
minFocusDistance =
cameraChars.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE)
?: MainActivity.FIXED_FOCUS_DISTANCE
hasAF = minFocusDistance != FIXED_FOCUS_DISTANCE // If camera is fixed focus, no AF
isLegacy = cameraChars.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL) ==
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY;
val activeSensorRect: Rect = cameraChars.get(SENSOR_INFO_ACTIVE_ARRAY_SIZE)
?: Rect(0, 0, 640, 480)
megapixels = (activeSensorRect.width() * activeSensorRect.height()) / 1000000
// Set up camera2 callbacks
camera2DeviceStateCallback =
Camera2DeviceStateCallback(this, activity)
camera2CaptureSessionCallback =
Camera2CaptureSessionCallback(activity, this)
previewSurfaceView = activity.surface_mirror
if (Build.VERSION.SDK_INT >= 28) {
physicalCameras = cameraChars.physicalCameraIds
}
// Get Camera2 and CameraX image capture sizes
val map =
characteristics?.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP)
if (map != null) {
cam2MaxSize = Collections.max(
Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
CompareSizesByArea()
)
cam2MinSize = Collections.min(
Arrays.asList(*map.getOutputSizes(ImageFormat.JPEG)),
CompareSizesByArea()
)
}
}
allCameraParams.put(cameraId, tempCameraParams)
} // For all camera devices
} catch (accessError: CameraAccessException) {
accessError.printStackTrace()
}
}
/** Adds automatic flash to the given CaptureRequest.Builder */
fun setAutoFlash(params: CameraParams, requestBuilder: CaptureRequest.Builder?) {
try {
if (params.hasFlash) {
requestBuilder?.set(
CaptureRequest.CONTROL_AE_MODE,
CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
// Force flash always on
// requestBuilder?.set(CaptureRequest.CONTROL_AE_MODE,
// CaptureRequest.CONTROL_AE_MODE_ON_ALWAYS_FLASH)
}
} catch (e: Exception) {
// Do nothing
}
}
/**
* Configure the ImageReader
*
* Note: format is currently overridden to PRIVATE in native for speed
*
* If device is a Chromebox, assume it can handle 1920x1080 and has enough memory for a large buffer
*/
fun setupImageReader(activity: MainActivity, params: CameraParams) {
val useLargest = true
val size = if (useLargest)
params.cam2MaxSize
else
params.cam2MinSize
if (activity.isChromebox()) {
createPreviewImageReader(
1920, 1080,
ImageFormat.YUV_420_888, 20
)
} else {
createPreviewImageReader(size.width, size.height,
ImageFormat.YUV_420_888, 10)
}
}
/** Finds the smallest focal length in the given array, useful for finding the widest angle lens */
fun smallestFocalLength(focalLengths: FloatArray): Float = focalLengths.min()
?: MainActivity.INVALID_FOCAL_LENGTH
/** Finds the largest aperture in the array of focal lengths */
fun largestAperture(apertures: FloatArray): Float = apertures.max()
?: MainActivity.NO_APERTURE
/** Finds the most "normal" focal length in the array of focal lengths */
fun focalLengthMinDeltaFromNormal(focalLengths: FloatArray): Float =
focalLengths.minBy { Math.abs(it - MainActivity.NORMAL_FOCAL_LENGTH) }
?: Float.MAX_VALUE
/**
* Return the "best" camera's CameraParams
*
* Best in order of preference: first external camera, first front camera, fallback to first camera
*/
fun chooseBestCamera(allCameraParams: HashMap<String, CameraParams>) : CameraParams {
if (allCameraParams.isEmpty()) {
return CameraParams()
}
var bestParams = allCameraParams.entries.iterator().next().value // Start with the first camera
for (cameraParams in allCameraParams) {
// Is external?
if (cameraParams.value.isExternal) {
bestParams = cameraParams.value
break
}
// If we have not found a front camera and this one is a front-facing
if (!bestParams.isFront && cameraParams.value.isFront) {
bestParams = cameraParams.value
}
}
return bestParams
}
/**
* Get degrees (multiple of 90) that output camera image is rotated from "up" relative to screen display
*/
fun getCameraImageRotation(activity: MainActivity, params: CameraParams) : Int {
var rotation = 0
if (true) { // front-facing
rotation = (params.orientation + getDisplayRotation(activity)) % 360;
rotation = (360 - rotation) % 360; // make front-facing like a mirror
} else { // back-facing
rotation = (params.orientation - getDisplayRotation(activity) + 360) % 360;
}
return rotation
}
/**
* Get current display rotation
*/
fun getDisplayRotation(activity: MainActivity) : Int {
return when(activity.windowManager.defaultDisplay.rotation) {
Surface.ROTATION_0 -> 0
Surface.ROTATION_90 -> 90
Surface.ROTATION_180 -> 180
Surface.ROTATION_270 -> 270
else -> 0
}
}
/**
* Native call to create the desired ImageReader
*
* The reader should be created in Native to avoid costly image copies across JNI
*/
external fun createPreviewImageReader(width: Int, height: Int, format: Int, maxImages: Int)
| apache-2.0 | 54a8bc9156a3cba7342a4d24d0532866 | 37.323077 | 104 | 0.643717 | 4.753817 | false | false | false | false |
matejdro/WearMusicCenter | wear/src/main/java/com/matejdro/wearmusiccenter/watch/view/CircularVolumeBar.kt | 1 | 2753 | package com.matejdro.wearmusiccenter.watch.view
import kotlin.math.max
import kotlin.math.min
class CircularVolumeBar : android.view.View {
private val foregroundPaint: android.graphics.Paint = android.graphics.Paint()
private val backgroundPaint: android.graphics.Paint
private val circleBounds = android.graphics.RectF()
constructor(context: android.content.Context?) : this(context, null)
constructor(context: android.content.Context?, attrs: android.util.AttributeSet?) : this(context, attrs, 0)
constructor(context: android.content.Context?, attrs: android.util.AttributeSet?, defStyleAttr: Int) : this(context, attrs, defStyleAttr, 0)
constructor(context: android.content.Context?, attrs: android.util.AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes)
init {
foregroundPaint.style = android.graphics.Paint.Style.STROKE
foregroundPaint.strokeWidth = resources.getDimension(com.matejdro.wearmusiccenter.R.dimen.music_screen_volume_bar_width)
foregroundPaint.strokeCap = android.graphics.Paint.Cap.ROUND
foregroundPaint.color = resources.getColor(com.matejdro.wearmusiccenter.R.color.music_screen_volume_bar_foreground_color, null)
foregroundPaint.isAntiAlias = true
backgroundPaint = android.graphics.Paint(foregroundPaint)
backgroundPaint.color = resources.getColor(com.matejdro.wearmusiccenter.R.color.music_screen_volume_bar_background_color, null)
}
var volume = 0.5f
set(value) {
field = value
invalidate()
}
fun incrementVolume(change : Float) {
updateVolume(min(1f, max(0f, volume + change)))
}
private fun updateVolume(newVolume : Float) {
volume = newVolume
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val viewSize = min(measuredWidth, measuredHeight).toFloat()
val circleStroke = foregroundPaint.strokeWidth / 2
val circleSize = viewSize - foregroundPaint.strokeWidth
val horizontalMargin = measuredWidth - viewSize
val verticalMargin = measuredHeight - viewSize
circleBounds.left = circleStroke + horizontalMargin / 2
circleBounds.top = circleStroke + verticalMargin / 2
circleBounds.right = circleBounds.left + circleSize
circleBounds.bottom = circleBounds.top + circleSize
}
override fun onDraw(canvas: android.graphics.Canvas?) {
super.onDraw(canvas)
canvas?.drawArc(circleBounds, 0f, 360f, false, backgroundPaint)
canvas?.drawArc(circleBounds, -90f, volume * 360f, false, foregroundPaint)
}
}
| gpl-3.0 | c85396a798ac64383ef58f5ba568b17c | 40.712121 | 173 | 0.719215 | 4.53542 | false | false | false | false |
simia-tech/epd-kotlin | src/test/kotlin/com/anyaku/test/Tools.kt | 1 | 789 | package com.anyaku.test
import java.util.HashMap
import java.util.ArrayList
[ suppress("UNCHECKED_CAST") ]
fun asMap<K, V>(vararg arguments: Any?): MutableMap<K, V> {
val result = HashMap<K, V>()
val iterator = arguments.iterator()
while (iterator.hasNext()) {
val key = iterator.next() as K
val value = iterator.next() as V
result.put(key, value)
}
return result
}
fun asList<T>(vararg arguments: T): MutableList<T> {
val result = ArrayList<T>()
for (item in arguments) {
result.add(item)
}
return result
}
fun asByteArray(vararg arguments: Byte): ByteArray {
val result = ByteArray(arguments.size)
for (index in 0..arguments.size - 1) {
result.set(index, arguments[index])
}
return result
}
| lgpl-3.0 | a0f9c5638b1bc62e39ac5af71e468acc | 23.65625 | 59 | 0.636248 | 3.635945 | false | false | false | false |
AndroidX/androidx | core/core-ktx/src/main/java/androidx/core/util/SparseIntArray.kt | 3 | 3629 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE") // Aliases to public API.
package androidx.core.util
import android.util.SparseIntArray
/** Returns the number of key/value pairs in the collection. */
public inline val SparseIntArray.size: Int get() = size()
/** Returns true if the collection contains [key]. */
public inline operator fun SparseIntArray.contains(key: Int): Boolean = indexOfKey(key) >= 0
/** Allows the use of the index operator for storing values in the collection. */
public inline operator fun SparseIntArray.set(key: Int, value: Int): Unit = put(key, value)
/** Creates a new collection by adding or replacing entries from [other]. */
public operator fun SparseIntArray.plus(other: SparseIntArray): SparseIntArray {
val new = SparseIntArray(size() + other.size())
new.putAll(this)
new.putAll(other)
return new
}
/** Returns true if the collection contains [key]. */
public inline fun SparseIntArray.containsKey(key: Int): Boolean = indexOfKey(key) >= 0
/** Returns true if the collection contains [value]. */
public inline fun SparseIntArray.containsValue(value: Int): Boolean = indexOfValue(value) >= 0
/** Return the value corresponding to [key], or [defaultValue] when not present. */
public inline fun SparseIntArray.getOrDefault(key: Int, defaultValue: Int): Int =
get(key, defaultValue)
/** Return the value corresponding to [key], or from [defaultValue] when not present. */
public inline fun SparseIntArray.getOrElse(key: Int, defaultValue: () -> Int): Int =
indexOfKey(key).let { if (it >= 0) valueAt(it) else defaultValue() }
/** Return true when the collection contains no elements. */
public inline fun SparseIntArray.isEmpty(): Boolean = size() == 0
/** Return true when the collection contains elements. */
public inline fun SparseIntArray.isNotEmpty(): Boolean = size() != 0
/** Removes the entry for [key] only if it is mapped to [value]. */
public fun SparseIntArray.remove(key: Int, value: Int): Boolean {
val index = indexOfKey(key)
if (index >= 0 && value == valueAt(index)) {
removeAt(index)
return true
}
return false
}
/** Update this collection by adding or replacing entries from [other]. */
public fun SparseIntArray.putAll(other: SparseIntArray): Unit = other.forEach(::put)
/** Performs the given [action] for each key/value entry. */
public inline fun SparseIntArray.forEach(action: (key: Int, value: Int) -> Unit) {
for (index in 0 until size()) {
action(keyAt(index), valueAt(index))
}
}
/** Return an iterator over the collection's keys. */
public fun SparseIntArray.keyIterator(): IntIterator = object : IntIterator() {
var index = 0
override fun hasNext() = index < size()
override fun nextInt() = keyAt(index++)
}
/** Return an iterator over the collection's values. */
public fun SparseIntArray.valueIterator(): IntIterator = object : IntIterator() {
var index = 0
override fun hasNext() = index < size()
override fun nextInt() = valueAt(index++)
}
| apache-2.0 | 4f81f3d778bc4c8b4e525c12baf637f7 | 38.445652 | 94 | 0.710113 | 4.195376 | false | false | false | false |
satamas/fortran-plugin | src/main/kotlin/org/jetbrains/fortran/lang/FortranIncludeHelpers.kt | 1 | 3931 | package org.jetbrains.fortran.lang
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Ref
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceHelper
import com.intellij.psi.search.SpecificNameItemProcessor
import com.intellij.util.SmartList
fun resolveIncludedFile(
context: VirtualFile?,
includePath: String?,
project: Project
): VirtualFile? {
if (context == null || !context.isValid) return null
val pathElements = includePath?.split('/') ?: return null
val item = FileReferenceHelper.getPsiFileSystemItem(PsiManager.getInstance(project), context)
val first = pathElements.first()
var file = findAbsoluteFile(includePath, first)
if(file != null) return file
if (item != null && item.parent != null) {
val firstSegmentElements = findChild(item.parent, first)
file = findFile(firstSegmentElements, pathElements)
}
return file
}
private fun findAbsoluteFile(path: String, first: String): VirtualFile? {
if (first.isEmpty() || FileUtil.isWindowsAbsolutePath(path)) {
val file = LocalFileSystem.getInstance().findFileByPath(path)
return if (file == null || file.isDirectory) null else file
}
return null
}
private fun findFile(firstSegmentElements: List<PsiFileSystemItem>,
pathElements: List<String>): VirtualFile? {
return firstSegmentElements.asSequence()
.map { if (pathElements.size != 1) find(it, pathElements, 1) else it as? PsiFile }
.map { it?.virtualFile }
.filterNotNull()
.firstOrNull()
}
private fun find(root: PsiFileSystemItem?, pathElements: List<String>, cur: Int): PsiFile? {
if (root == null || cur >= pathElements.size) return null
val name = pathElements[cur]
if (name.isEmpty()) {
return find(root, pathElements, cur + 1)
}
for (item in findChild(root, name)) {
if (cur == pathElements.size - 1) {
if (item is PsiFile) return item
} else {
val element = find(item, pathElements, cur + 1)
if (element != null) {
return element
}
}
}
return null
}
private fun findChild(parent: PsiFileSystemItem?, childName: String): List<PsiFileSystemItem> {
if (parent == null || !parent.isValid) return emptyList()
return when (childName) {
".." -> {
val vFile = parent.virtualFile ?: return emptyList()
val vParent = vFile.parent ?: return emptyList()
val directory = parent.manager.findDirectory(vParent)
if (directory != null) listOf(directory) else emptyList()
}
"." -> listOf(parent)
else -> {
if (parent !is PsiDirectory) {
val result = SmartList<PsiFileSystemItem>()
parent.processChildren(object : SpecificNameItemProcessor(childName) {
override fun execute(element: PsiFileSystemItem): Boolean {
result.add(element)
return true
}
})
result
} else {
// special-case optimization: iterating over directories and getting file names is expensive
findInDir((parent as PsiDirectory?)!!, childName)
}
}
}
}
private fun findInDir(dir: PsiDirectory, childName: String): List<PsiFileSystemItem> {
val found: PsiFileSystemItem? = dir.findFile(childName) ?: dir.findSubdirectory(childName)
return if (found != null) listOf(found) else emptyList()
} | apache-2.0 | 7dd7ce973d64ad9c4903cdc51d2a2d4f | 35.747664 | 108 | 0.64233 | 4.619271 | false | false | false | false |
ioc1778/incubator | incubator-cache/src/test/java/com/riaektiv/cache/ignite/IgniteCacheTest.kt | 2 | 1379 | package com.riaektiv.cache.ignite
import org.apache.ignite.Ignite
import org.apache.ignite.Ignition
import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi
import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder
import org.junit.Test
import kotlin.test.assertEquals
/**
* Coding With Passion Since 1991
* Created: 2/22/2017, 6:14 PM Eastern Time
* @author Sergey Chuykov
*/
class IgniteCacheTest {
fun ipFinder(set: TcpDiscoveryVmIpFinder.() -> Unit): TcpDiscoveryVmIpFinder {
val finder = TcpDiscoveryVmIpFinder()
finder.set()
return finder
}
fun Ignite.setIpFinderAddresses(addresses: List<String>) {
(this.configuration().discoverySpi as TcpDiscoverySpi).ipFinder =
ipFinder {
setAddresses(addresses)
}
}
@Test
fun test() {
val ignite = Ignition.start("example-ignite.xml")
//val ignite = Ignition.start()
//ignite.setIpFinderAddresses(listOf("127.0.0.1"))
val cache = ignite.createCache<Long, String>(this.javaClass.simpleName)
val NUM = 8L
for (key in 0L..NUM) {
cache.put(key, key.toString());
}
for (key in 0L..NUM) {
val value = cache.get(key)
assertEquals(key.toString(), value)
}
ignite.close()
}
} | bsd-3-clause | a9739dc37fa895591cce1be8c96c506e | 24.090909 | 82 | 0.631617 | 3.873596 | false | true | false | false |
oehf/ipf | modules/hl7-kotlin/src/test/kotlin/org/openehealth/ipf/modules/hl7/kotlin/SegmentTest.kt | 1 | 6413 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openehealth.ipf.modules.hl7.kotlin
import ca.uhn.hl7v2.DefaultHapiContext
import ca.uhn.hl7v2.model.Composite
import ca.uhn.hl7v2.model.Message
import ca.uhn.hl7v2.model.Primitive
import ca.uhn.hl7v2.model.Segment
import ca.uhn.hl7v2.model.v22.message.ADT_A01
import ca.uhn.hl7v2.model.v22.segment.NK1
import ca.uhn.hl7v2.parser.EncodingCharacters
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
/**
* @author Christian Ohr
*/
class SegmentTest {
val context = DefaultHapiContext()
private val msg1: ADT_A01 = loadHl7(context, "/msg-01.hl7")
private val msg2: Message = loadHl7(context, "/msg-02.hl7")
private val msg3: Message = loadHl7(context, "/msg-03.hl7")
private val nk1 = msg1.nK1!!
val msh = msg1.msh!!
private val evn = msg3["EVN"] as Segment
val pid = msg3["PID"] as Segment
private val pv1 = msg1.pV1!!
private val pv2 = msg1.pV2!!
@Test
fun testInvokeMethod() {
// invoke method on adapter
assertEquals(2, nk1.count(5))
// invoke method on target
assertEquals(13, nk1.numFields())
}
@Test
fun testGet() {
// property access on target
assertEquals("NK1", nk1.name)
}
@Test
fun testSet() {
val msg = msg1.copy()
msh[3] = "SAP-XXX"
assertEquals("SAP-ISH", msg.msh[3].value)
msg.msh.from(msh)
assertEquals("SAP-XXX", msg.msh[3].value)
msg.msh[3] = "SAP-ISH"
msg["MSH"] = msh
assertEquals("SAP-XXX", msg.msh[3].value)
}
@Test
fun testSetRepetitiveSegment() {
val msg = msg2.copy()
val nte4 = msg2["PATIENT_RESULT"]["ORDER_OBSERVATION",1]["OBSERVATION",1]["NTE",4]
val nte3: Segment = msg2["PATIENT_RESULT"]["ORDER_OBSERVATION",1]["OBSERVATION",1]["NTE",3] as Segment
assertTrue(nte3[3].value!!.startsWith("MICROALBUMINURIA"))
assertTrue(nte4[3].value!!.startsWith("CLINICAL ALBUMINURIA"))
msg["PATIENT_RESULT"]["ORDER_OBSERVATION",1]["OBSERVATION",1]["NTE", 4] = nte3
assertTrue(msg["PATIENT_RESULT"]["ORDER_OBSERVATION",1]["OBSERVATION",1]["NTE", 4][3].value!!.startsWith("MICROALBUMINURIA"))
}
@Test
fun testPrimitiveGetAt() {
// field with value
assertTrue(msh[3] is Primitive)
assertEquals("SAP-ISH", msh[3].value)
// field without value
assertTrue(msh[6] is Primitive)
assertTrue(msh[6].empty)
}
@Test
fun testSettingObx5Type() {
// create a new OBX segment from scratch
val obx = msg2["PATIENT_RESULT"]["ORDER_OBSERVATION"].nrp("OBSERVATION")["OBX"]
// before OBX-5 type has been set, it should be impossible
// to set this field using IPF DSL
try {
obx[5](0)[1] = "T57000"
obx[5](0)[2] = "GALLBLADDER"
obx[5](0)[3] = "SNM"
fail()
} catch (e: Exception) {
}
// set OBX-5 type and prove that this field is now accessible in default manner
obx.setObx5Type("CE")
obx[5](0)[1] = "T57000"
obx[5](0)[2] = "GALLBLADDER"
obx[5](0)[3] = "SNM"
val obxString = msg2.parser.doEncode(obx as Segment, EncodingCharacters('|', "^~\\&"))
assertEquals("OBX||CE|||T57000^GALLBLADDER^SNM", obxString)
}
@Test
fun testCompositeGetAt() {
assertTrue(nk1[4] is Composite)
assertTrue(nk1[4][4] is Primitive)
assertEquals("NW", nk1[4][4].value)
assertTrue(nk1[4][2] is Primitive)
assertTrue(nk1[4][2].empty)
assertTrue(nk1[4][2].value == null)
}
@Test
fun testRepetitionGetAt() {
assertEquals(2, nk1.count(5))
assertEquals("333-4444", nk1[5](0).value)
assertEquals("333-4444", nk1[5, 0].value)
assertEquals("333-5555", nk1[5](1).value)
assertEquals("333-5555", nk1[5, 1].value)
assertEquals("333-4444,333-5555", nk1[5]().joinToString(","))
}
@Test
fun testPrimitiveSetAt() {
assertTrue(msh[5] is Primitive)
assertTrue(msh[5].empty)
// assign value from string
msh[5] = "abc"
assertTrue(msh[5] is Primitive)
assertEquals("abc", msh[5].value)
// assign value from primitive adapter
msh[5] = nk1[4][4]
assertTrue(msh[5] is Primitive)
assertEquals("NW", msh[5].value)
}
@Test
fun testCompositeSetAt() {
val nk1Copy = msg1.copy().getNK1(0)
nk1Copy[4][4] = "XY"
assertEquals("NW", nk1[4][4].value)
nk1[4] = nk1Copy[4]
assertEquals("XY", nk1[4][4].value)
}
@Test
fun testComponentSetAt() {
nk1[4][2] = "blah"
assertEquals("blah", nk1[4][2].value)
}
@Test
fun testCompositeCreate() {
assertTrue(evn[7][1].empty)
assertTrue(evn[7][2].empty)
evn[7][1] = 'X'
evn[7][2] = 'Y'
assertEquals("X", evn[7][1].value)
assertEquals("Y", evn[7][2].value)
}
@Test
fun testNrp() {
nk1.nrp(5).from("333-6666")
assertEquals(3, nk1.count(5))
assertEquals("333-4444", nk1[5](0).value)
assertEquals("333-5555", nk1[5](1).value)
assertEquals("333-6666", nk1[5](2).value)
}
@Test
fun testZeroCardinality() {
assertEquals(0, pid.getMaxCardinality(5))
assertTrue(pid[5](0)[1][2] is Primitive)
assertTrue(pid[5](0)[1][2].empty)
pid[5](0)[1][2] = "van"
assertEquals("van", pid[5](0)[1][2].value)
}
@Test
fun testIsEmpty() {
assertTrue(pv2.empty)
assertFalse(pv1.empty)
}
@Test
fun testMakeSegment() {
val nk1 = newSegment("NK1", msg1)
assertTrue(nk1 is NK1)
}
} | apache-2.0 | 4da6655d363b49fcc763d997f8ef6b48 | 29.254717 | 133 | 0.595041 | 3.151351 | false | true | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/config/io/ConfigurationExceptionSpec.kt | 1 | 4012 | /*
Copyright 2017-2020 Charles Korn.
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 batect.config.io
import batect.testutils.given
import batect.testutils.on
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object ConfigurationExceptionSpec : Spek({
describe("a configuration exception") {
describe("formatting") {
given("an exception with just a message") {
val exception = ConfigurationException("This is the error message")
on("converting to a string") {
it("returns just the message") {
assertThat(exception.toString(), equalTo("This is the error message"))
}
}
}
given("an exception with a message and a cause") {
val cause = RuntimeException("Something went wrong")
val exception = ConfigurationException("This is the error message", null, null, null, cause)
on("converting to a string") {
it("returns the message and details of the cause") {
assertThat(exception.toString(), equalTo("This is the error message"))
}
}
}
given("an exception with a message and a file name") {
val exception = ConfigurationException("This is the error message", "source.txt", null, null, null)
on("converting to a string") {
it("returns the message and the file name") {
assertThat(exception.toString(), equalTo("source.txt: This is the error message"))
}
}
}
given("an exception with a message, a file name and a line number") {
val exception = ConfigurationException("This is the error message", "source.txt", 12, null, null)
on("converting to a string") {
it("returns the message, the file name and the line number") {
assertThat(exception.toString(), equalTo("source.txt (line 12): This is the error message"))
}
}
}
given("an exception with a message, a file name, a line number and a column") {
val exception = ConfigurationException("This is the error message", "source.txt", 12, 54, null)
on("converting to a string") {
it("returns the message, the file name, the line number and the column") {
assertThat(exception.toString(), equalTo("source.txt (line 12, column 54): This is the error message"))
}
}
}
given("an exception with a message, a file name, a line number, a column and a cause") {
val cause = RuntimeException("Something went wrong")
val exception = ConfigurationException("This is the error message", "source.txt", 12, 54, cause)
on("converting to a string") {
it("returns the message, the file name, the line number, the column and the cause") {
assertThat(exception.toString(), equalTo("source.txt (line 12, column 54): This is the error message"))
}
}
}
}
}
})
| apache-2.0 | b4623bebb12061937d09421b02ba59b7 | 42.608696 | 127 | 0.581256 | 5.217165 | false | true | false | false |
pbreault/adb-idea | src/main/kotlin/com/developerphil/adbidea/adb/AdbFacade.kt | 1 | 3056 | package com.developerphil.adbidea.adb
import com.developerphil.adbidea.ObjectGraph
import com.developerphil.adbidea.adb.DeviceResult.SuccessfulDeviceResult
import com.developerphil.adbidea.adb.command.*
import com.developerphil.adbidea.adb.command.SvcCommand.MOBILE
import com.developerphil.adbidea.adb.command.SvcCommand.WIFI
import com.developerphil.adbidea.ui.NotificationHelper
import com.google.common.util.concurrent.ThreadFactoryBuilder
import com.intellij.openapi.project.Project
import java.util.concurrent.Executors
object AdbFacade {
private val EXECUTOR = Executors.newCachedThreadPool(ThreadFactoryBuilder().setNameFormat("AdbIdea-%d").build())
fun uninstall(project: Project) = executeOnDevice(project, UninstallCommand())
fun kill(project: Project) = executeOnDevice(project, KillCommand())
fun grantPermissions(project: Project) = executeOnDevice(project, GrantPermissionsCommand())
fun revokePermissions(project: Project) = executeOnDevice(project, RevokePermissionsCommand())
fun revokePermissionsAndRestart(project: Project) = executeOnDevice(project, RevokePermissionsAndRestartCommand())
fun startDefaultActivity(project: Project) = executeOnDevice(project, StartDefaultActivityCommand(false))
fun startDefaultActivityWithDebugger(project: Project) = executeOnDevice(project, StartDefaultActivityCommand(true))
fun restartDefaultActivity(project: Project) = executeOnDevice(project, RestartPackageCommand())
fun restartDefaultActivityWithDebugger(project: Project) =
executeOnDevice(project, CommandList(KillCommand(), StartDefaultActivityCommand(true)))
fun clearData(project: Project) = executeOnDevice(project, ClearDataCommand())
fun clearDataAndRestart(project: Project) = executeOnDevice(project, ClearDataAndRestartCommand())
fun clearDataAndRestartWithDebugger(project: Project) =
executeOnDevice(project, ClearDataAndRestartWithDebuggerCommand())
fun enableWifi(project: Project) = executeOnDevice(project, ToggleSvcCommand(WIFI, true))
fun disableWifi(project: Project) = executeOnDevice(project, ToggleSvcCommand(WIFI, false))
fun enableMobile(project: Project) = executeOnDevice(project, ToggleSvcCommand(MOBILE, true))
fun disableMobile(project: Project) = executeOnDevice(project, ToggleSvcCommand(MOBILE, false))
private fun executeOnDevice(project: Project, runnable: Command) {
if (AdbUtil.isGradleSyncInProgress(project)) {
NotificationHelper.error("Gradle sync is in progress")
return
}
when (val result = project.getComponent(ObjectGraph::class.java).deviceResultFetcher.fetch()) {
is SuccessfulDeviceResult -> {
result.devices.forEach { device ->
EXECUTOR.submit { runnable.run(project, device, result.facet, result.packageName) }
}
}
is DeviceResult.Cancelled -> Unit
is DeviceResult.DeviceNotFound, null -> NotificationHelper.error("No device found")
}
}
}
| apache-2.0 | b150c819ea0d9cce404957f98c7b7fe6 | 56.660377 | 120 | 0.764071 | 4.789969 | false | false | false | false |
pedroSG94/rtmp-rtsp-stream-client-java | rtsp/src/main/java/com/pedro/rtsp/rtsp/RtspSender.kt | 1 | 7312 | /*
* Copyright (C) 2021 pedroSG94.
*
* 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.pedro.rtsp.rtsp
import android.media.MediaCodec
import android.util.Log
import com.pedro.rtsp.rtcp.BaseSenderReport
import com.pedro.rtsp.rtp.packets.*
import com.pedro.rtsp.rtp.sockets.BaseRtpSocket
import com.pedro.rtsp.rtp.sockets.RtpSocketTcp
import com.pedro.rtsp.utils.BitrateManager
import com.pedro.rtsp.utils.ConnectCheckerRtsp
import com.pedro.rtsp.utils.RtpConstants
import java.io.IOException
import java.io.OutputStream
import java.nio.ByteBuffer
import java.util.*
import java.util.concurrent.*
/**
* Created by pedro on 7/11/18.
*/
open class RtspSender(private val connectCheckerRtsp: ConnectCheckerRtsp) : VideoPacketCallback, AudioPacketCallback {
private var videoPacket: BasePacket? = null
private var aacPacket: AacPacket? = null
private var rtpSocket: BaseRtpSocket? = null
private var baseSenderReport: BaseSenderReport? = null
@Volatile
private var running = false
@Volatile
private var rtpFrameBlockingQueue: BlockingQueue<RtpFrame> = LinkedBlockingQueue(defaultCacheSize)
private var thread: ExecutorService? = null
private var audioFramesSent: Long = 0
private var videoFramesSent: Long = 0
var droppedAudioFrames: Long = 0
private set
var droppedVideoFrames: Long = 0
private set
private val bitrateManager: BitrateManager = BitrateManager(connectCheckerRtsp)
private var isEnableLogs = true
companion object {
private const val TAG = "RtspSender"
}
@Throws(IOException::class)
fun setSocketsInfo(protocol: Protocol, videoSourcePorts: IntArray, audioSourcePorts: IntArray) {
rtpSocket = BaseRtpSocket.getInstance(protocol, videoSourcePorts[0], audioSourcePorts[0])
baseSenderReport = BaseSenderReport.getInstance(protocol, videoSourcePorts[1], audioSourcePorts[1])
}
fun setVideoInfo(sps: ByteArray, pps: ByteArray, vps: ByteArray?) {
videoPacket = if (vps == null) H264Packet(sps, pps, this) else H265Packet(sps, pps, vps, this)
}
fun setAudioInfo(sampleRate: Int) {
aacPacket = AacPacket(sampleRate, this)
}
/**
* @return number of packets
*/
private val defaultCacheSize: Int
get() = 10 * 1024 * 1024 / RtpConstants.MTU
@Throws(IOException::class)
fun setDataStream(outputStream: OutputStream, host: String) {
rtpSocket?.setDataStream(outputStream, host)
baseSenderReport?.setDataStream(outputStream, host)
}
fun setVideoPorts(rtpPort: Int, rtcpPort: Int) {
videoPacket?.setPorts(rtpPort, rtcpPort)
}
fun setAudioPorts(rtpPort: Int, rtcpPort: Int) {
aacPacket?.setPorts(rtpPort, rtcpPort)
}
fun sendVideoFrame(h264Buffer: ByteBuffer, info: MediaCodec.BufferInfo) {
if (running) videoPacket?.createAndSendPacket(h264Buffer, info)
}
fun sendAudioFrame(aacBuffer: ByteBuffer, info: MediaCodec.BufferInfo) {
if (running) aacPacket?.createAndSendPacket(aacBuffer, info)
}
override fun onVideoFrameCreated(rtpFrame: RtpFrame) {
try {
rtpFrameBlockingQueue.add(rtpFrame)
} catch (e: IllegalStateException) {
Log.i(TAG, "Video frame discarded")
droppedVideoFrames++
}
}
override fun onAudioFrameCreated(rtpFrame: RtpFrame) {
try {
rtpFrameBlockingQueue.add(rtpFrame)
} catch (e: IllegalStateException) {
Log.i(TAG, "Audio frame discarded")
droppedAudioFrames++
}
}
fun start() {
thread = Executors.newSingleThreadExecutor()
running = true
thread?.execute post@{
val ssrcVideo = Random().nextInt().toLong()
val ssrcAudio = Random().nextInt().toLong()
baseSenderReport?.setSSRC(ssrcVideo, ssrcAudio)
videoPacket?.setSSRC(ssrcVideo)
aacPacket?.setSSRC(ssrcAudio)
val isTcp = rtpSocket is RtpSocketTcp
while (!Thread.interrupted() && running) {
try {
val rtpFrame = rtpFrameBlockingQueue.poll(1, TimeUnit.SECONDS)
if (rtpFrame == null) {
Log.i(TAG, "Skipping iteration, frame null")
continue
}
rtpSocket?.sendFrame(rtpFrame, isEnableLogs)
//bytes to bits (4 is tcp header length)
val packetSize = if (isTcp) rtpFrame.length + 4 else rtpFrame.length
bitrateManager.calculateBitrate(packetSize * 8.toLong())
if (rtpFrame.isVideoFrame()) {
videoFramesSent++
} else {
audioFramesSent++
}
if (baseSenderReport?.update(rtpFrame, isEnableLogs) == true) {
//bytes to bits (4 is tcp header length)
val reportSize = if (isTcp) baseSenderReport?.PACKET_LENGTH ?: (0 + 4) else baseSenderReport?.PACKET_LENGTH ?: 0
bitrateManager.calculateBitrate(reportSize * 8.toLong())
}
} catch (e: Exception) {
//InterruptedException is only when you disconnect manually, you don't need report it.
if (e !is InterruptedException && running) {
connectCheckerRtsp.onConnectionFailedRtsp("Error send packet, " + e.message)
Log.e(TAG, "send error: ", e)
}
return@post
}
}
}
}
fun stop() {
running = false
thread?.shutdownNow()
try {
thread?.awaitTermination(100, TimeUnit.MILLISECONDS)
} catch (e: InterruptedException) { }
thread = null
rtpFrameBlockingQueue.clear()
baseSenderReport?.reset()
baseSenderReport?.close()
rtpSocket?.close()
aacPacket?.reset()
videoPacket?.reset()
resetSentAudioFrames()
resetSentVideoFrames()
resetDroppedAudioFrames()
resetDroppedVideoFrames()
}
fun hasCongestion(): Boolean {
val size = rtpFrameBlockingQueue.size.toFloat()
val remaining = rtpFrameBlockingQueue.remainingCapacity().toFloat()
val capacity = size + remaining
return size >= capacity * 0.2f //more than 20% queue used. You could have congestion
}
fun resizeCache(newSize: Int) {
if (newSize < rtpFrameBlockingQueue.size - rtpFrameBlockingQueue.remainingCapacity()) {
throw RuntimeException("Can't fit current cache inside new cache size")
}
val tempQueue: BlockingQueue<RtpFrame> = LinkedBlockingQueue(newSize)
rtpFrameBlockingQueue.drainTo(tempQueue)
rtpFrameBlockingQueue = tempQueue
}
fun getCacheSize(): Int {
return rtpFrameBlockingQueue.size
}
fun getSentAudioFrames(): Long {
return audioFramesSent
}
fun getSentVideoFrames(): Long {
return videoFramesSent
}
fun resetSentAudioFrames() {
audioFramesSent = 0
}
fun resetSentVideoFrames() {
videoFramesSent = 0
}
fun resetDroppedAudioFrames() {
droppedAudioFrames = 0
}
fun resetDroppedVideoFrames() {
droppedVideoFrames = 0
}
fun setLogs(enable: Boolean) {
isEnableLogs = enable
}
} | apache-2.0 | fd1c7c84b8761028201eb030fb25cf61 | 30.521552 | 124 | 0.699261 | 4.053215 | false | false | false | false |
bibaev/stream-debugger-plugin | src/main/java/com/intellij/debugger/streams/trace/dsl/impl/DslImpl.kt | 1 | 3995 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.streams.trace.dsl.impl
import com.intellij.debugger.streams.trace.dsl.*
import com.intellij.debugger.streams.trace.impl.handler.type.GenericType
import com.intellij.debugger.streams.wrapper.IntermediateStreamCall
/**
* @author Vitaliy.Bibaev
*/
class DslImpl(private val statementFactory: StatementFactory) : Dsl {
override val nullExpression: Expression = TextExpression("null")
override val thisExpression: Expression = TextExpression("this")
override val types: Types = statementFactory.types
override fun variable(type: GenericType, name: String): Variable = statementFactory.createVariable(type, name)
override fun code(init: CodeContext.() -> Unit): String {
val fragment = MyContext()
fragment.init()
return fragment.toCode(0)
}
override fun block(init: CodeContext.() -> Unit): CodeBlock {
val fragment = MyContext()
fragment.init()
return fragment
}
override fun array(elementType: GenericType, name: String): ArrayVariable = statementFactory.createArrayVariable(elementType, name)
override fun newArray(elementType: GenericType, vararg args: Expression): Expression =
statementFactory.createNewArrayExpression(elementType, args)
override fun newSizedArray(elementType: GenericType, size: Expression): Expression =
statementFactory.createNewSizedArray(elementType, size)
override fun map(keyType: GenericType, valueType: GenericType, name: String): MapVariable =
statementFactory.createMapVariable(keyType, valueType, name, false)
override fun list(elementType: GenericType, name: String): ListVariable =
statementFactory.createListVariable(elementType, name)
override fun newList(elementType: GenericType, vararg args: Expression): Expression =
statementFactory.createNewListExpression(elementType, *args)
override fun linkedMap(keyType: GenericType, valueType: GenericType, name: String): MapVariable =
statementFactory.createMapVariable(keyType, valueType, name, true)
override fun lambda(argName: String, init: LambdaBody.(Expression) -> Unit): Lambda {
val lambdaBody = statementFactory.createEmptyLambdaBody(argName)
lambdaBody.init(argName.expr)
return statementFactory.createLambda(argName, lambdaBody)
}
override fun declaration(variable: Variable, init: Expression, isMutable: Boolean): VariableDeclaration =
statementFactory.createVariableDeclaration(variable, init, isMutable)
override fun timeDeclaration(): VariableDeclaration = statementFactory.createTimeVariableDeclaration()
override fun currentTime(): Expression = statementFactory.currentTimeExpression()
override fun updateTime(): Expression = statementFactory.updateCurrentTimeExpression()
override fun createPeekCall(elementsType: GenericType, lambda: String): IntermediateStreamCall =
statementFactory.createPeekCall(elementsType, lambda)
override fun Expression.and(right: Expression): Expression = statementFactory.and(this, right)
override fun Expression.equals(right: Expression): Expression = statementFactory.equals(this, right)
override fun Expression.same(right: Expression): Expression = statementFactory.same(this, right)
override fun Expression.not(): Expression = statementFactory.not(this)
private inner class MyContext : CodeContext, Dsl by DslImpl@ this, CodeBlock by statementFactory.createEmptyCompositeCodeBlock()
} | apache-2.0 | 4a8fb610e1da0ccfe103d6ef10172188 | 41.967742 | 133 | 0.781227 | 4.750297 | false | false | false | false |
percolate/percolate-java-sdk | api/src/test/java/com/percolate/sdk/api/request/monitoring/flagging/FlaggingRequestTest.kt | 1 | 1540 | package com.percolate.sdk.api.request.monitoring.flagging
import com.percolate.sdk.api.BaseApiTest
import com.percolate.sdk.dto.Flag
import org.junit.Assert
import org.junit.Test
class FlaggingRequestTest : BaseApiTest() {
@Test
fun testList() {
val flags = percolateApi
.flags()
.list(FlaggingListParams())
.execute()
.body();
val data = flags?.data
Assert.assertNotNull(data)
Assert.assertEquals(5, data!!.size.toLong())
}
@Test
fun testGet() {
val singleFlag = percolateApi
.flags()
.get(FlaggingGetParams("123"))
.execute()
.body();
Assert.assertNotNull(singleFlag?.data?.id)
}
@Test
fun testCreate() {
val singleFlag = percolateApi
.flags()
.create(Flag())
.execute()
.body();
Assert.assertNotNull(singleFlag?.data?.id)
}
@Test
fun testUpdate() {
val singleFlag = percolateApi
.flags()
.update(Flag().apply { id= 123L })
.execute()
.body();
Assert.assertNotNull(singleFlag?.data?.id)
}
@Test
fun testDelete() {
val responseBody = percolateApi
.flags()
.delete(FlaggingDeleteParams("123"))
.execute()
.body();
Assert.assertNotNull(responseBody)
}
} | bsd-3-clause | 7fe370f78c9f4a35838d7011a3a9c893 | 22.348485 | 57 | 0.507143 | 4.597015 | false | true | false | false |
minecraft-dev/MinecraftDev | src/main/kotlin/translations/identification/TranslationInstance.kt | 1 | 13053 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2022 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.translations.identification
import com.demonwav.mcdev.platform.mcp.util.McpConstants
import com.demonwav.mcdev.translations.TranslationConstants
import com.demonwav.mcdev.util.MemberReference
import com.intellij.psi.PsiElement
data class TranslationInstance(
val foldingElement: PsiElement?,
val foldStart: Int,
val referenceElement: PsiElement?,
val key: Key,
val text: String?,
val formattingError: FormattingError? = null,
val superfluousVarargStart: Int = -1
) {
data class Key(val prefix: String, val infix: String, val suffix: String) {
val full = (prefix + infix + suffix).trim()
}
companion object {
enum class FormattingError {
MISSING, SUPERFLUOUS
}
val translationFunctions = listOf(
TranslationFunction(
MemberReference(
TranslationConstants.FORMAT,
"(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
TranslationConstants.I18N_CLIENT_CLASS
),
0,
formatting = true,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.GET,
"(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
TranslationConstants.I18N_CLIENT_LANG_CLASS
),
0,
formatting = true,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.EXISTS,
"(Ljava/lang/String;)Z",
TranslationConstants.I18N_CLIENT_LANG_CLASS
),
0,
formatting = false,
obfuscatedName = true,
foldParameters = TranslationFunction.FoldingScope.PARAMETERS
),
TranslationFunction(
MemberReference(
TranslationConstants.TRANSLATE_TO_LOCAL,
"(Ljava/lang/String;)Ljava/lang/String;",
TranslationConstants.I18N_COMMON_CLASS
),
0,
formatting = false,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.TRANSLATE_TO_LOCAL_FORMATTED,
"(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;",
TranslationConstants.I18N_COMMON_CLASS
),
0,
formatting = true,
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;[Ljava/lang/Object;)V",
TranslationConstants.TRANSLATION_COMPONENT_CLASS
),
0,
formatting = true,
foldParameters = TranslationFunction.FoldingScope.PARAMETERS
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;)V",
TranslationConstants.TRANSLATABLE_COMPONENT
),
0,
formatting = false,
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;[Ljava/lang/Object;)V",
TranslationConstants.TRANSLATABLE_COMPONENT
),
0,
formatting = true,
),
TranslationFunction(
MemberReference(
TranslationConstants.CREATE_COMPONENT_TRANSLATION,
"(Lnet/minecraft/commands/CommandSource;Ljava/lang/String;" +
"[Ljava/lang/Object;)Lnet/minecraft/network/chat/BaseComponent;",
TranslationConstants.TEXT_COMPONENT_HELPER
),
1,
formatting = true,
foldParameters = TranslationFunction.FoldingScope.PARAMETERS,
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;[Ljava/lang/Object;)V",
TranslationConstants.COMMAND_EXCEPTION_CLASS
),
0,
formatting = true,
foldParameters = TranslationFunction.FoldingScope.PARAMETERS
),
TranslationFunction(
MemberReference(
TranslationConstants.SET_BLOCK_NAME,
"(Ljava/lang/String;)Lnet/minecraft/block/Block;",
McpConstants.BLOCK
),
0,
formatting = false,
setter = true,
foldParameters = TranslationFunction.FoldingScope.PARAMETERS,
prefix = "tile.",
suffix = ".name",
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.SET_ITEM_NAME,
"(Ljava/lang/String;)Lnet/minecraft/item/Item;",
McpConstants.ITEM
),
0,
formatting = false,
setter = true,
foldParameters = TranslationFunction.FoldingScope.PARAMETERS,
prefix = "item.",
suffix = ".name",
obfuscatedName = true
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
2,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lcom/mojang/blaze3d/platform/InputConstants\$Type;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lcom/mojang/blaze3d/platform/InputConstants\$Type;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
3,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Type;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Type;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
4,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Key;Ljava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Key;Ljava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
3,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lnet/minecraftforge/client/settings/KeyModifier;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Type;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lnet/minecraftforge/client/settings/KeyModifier;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Type;ILjava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
5,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lnet/minecraftforge/client/settings/KeyModifier;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Key;Ljava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.CONSTRUCTOR,
"(Ljava/lang/String;Lnet/minecraftforge/client/settings/IKeyConflictContext;" +
"Lnet/minecraftforge/client/settings/KeyModifier;" +
"Lcom/mojang/blaze3d/platform/InputConstants\$Key;Ljava/lang/String;)V",
TranslationConstants.KEY_MAPPING
),
4,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER
),
TranslationFunction(
MemberReference(
TranslationConstants.INPUT_CONSTANTS_KEY_GET_KEY,
"(Ljava/lang/String;)Lcom/mojang/blaze3d/platform/InputConstants\$Key;",
TranslationConstants.INPUT_CONSTANTS_KEY
),
0,
formatting = false,
foldParameters = TranslationFunction.FoldingScope.PARAMETER,
obfuscatedName = true
),
)
fun find(element: PsiElement): TranslationInstance? =
TranslationIdentifier.INSTANCES
.firstOrNull { it.elementClass().isAssignableFrom(element.javaClass) }
?.identifyUnsafe(element)
}
}
| mit | 1586256eb6e26a07b80286cc871c5d7d | 40.438095 | 113 | 0.522562 | 6.236503 | false | false | false | false |
vitorsalgado/android-boilerplate | buildSrc/src/main/kotlin/Versions.kt | 1 | 1376 | object Versions {
val kotlin = "1.3.20"
// support
val testCore = "1.1.0"
val constraintLayout = "1.1.2"
val orchestrator = "1.1.0"
val navigation = "1.0.0-alpha04"
//
val design = "1.0.0-rc01"
val androidx = "1.0.0"
//
// test dependencies
val junit = "4.12"
val junit5 = "5.2.0"
val hamcrest = "1.3"
val testButler = "1.4.0"
val robolectric = "3.8"
val espresso = "3.1.0-alpha1"
val mockito = "2.23.0"
val requestmatcher = "2.2.0"
val jsonpathassert = "2.2.0"
// main dependencies
val okhttp = "3.11.0"
val retrofit = "2.4.0"
val play_services = "16.0.1"
val firebase_core = "16.0.4"
val firebase_messaging = "17.3.4"
val firebase_remote_config = "16.1.0"
val gson = "2.8.5"
val fresco = "1.9.0"
val rxAndroid = "2.0.2"
val rxJava = "2.1.16"
val sqlbrite = "3.1.0"
val licensesDialog = "1.8.3"
val crashlytics = "2.9.5"
val traceur = "1.0.1"
val dagger = "2.16"
val fabric = "1.27.1"
val rootbeer = "0.0.7"
val google_services = "4.2.0"
val owasp_dependency_check = "3.2.1"
val sonar = "2.6.1"
val timber = "4.7.1"
val facebook_sdk = "4.33.0"
// architecture components
val arch = "1.1.1"
// utils
val leakCanary = "1.6.2"
val stetho = "1.5.0"
val jacoco = "0.8.1"
val coveralls = "2.8.2"
val ktlint = "0.24.0"
val detekt = "1.0.0.RC7"
val spotless = "3.14.0"
}
| apache-2.0 | 322438be2b943a96d087105c207cdfa6 | 21.557377 | 39 | 0.585756 | 2.388889 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/extensions/RecyclerViewExtensions.kt | 1 | 2815 | @file:Suppress("unused")
package com.commonsense.android.kotlin.views.extensions
import android.support.v7.widget.RecyclerView
import com.commonsense.android.kotlin.base.*
import com.commonsense.android.kotlin.base.extensions.collections.*
/**
* Setup this recycler view with an adapter and a layout manager
* @receiver RecyclerView
* @param adapter RecyclerView.Adapter<*> the adapter to use
* @param layoutManager RecyclerView.LayoutManager the layoutmanager to use
*/
fun RecyclerView.setup(adapter: RecyclerView.Adapter<*>,
layoutManager: RecyclerView.LayoutManager) {
this.adapter = adapter
this.layoutManager = layoutManager
}
/**
* adds an onscroll listener that calls the given action when we have scrolled past the first item in the adapter
* @receiver RecyclerView
* @param action FunctionUnit<Boolean>
* @return RecyclerView.OnScrollListener
*/
inline fun RecyclerView.addOnScrollWhenPastFirstItem(crossinline action: FunctionUnit<Boolean>): RecyclerView.OnScrollListener {
val listener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val isFirstVisible = recyclerView.findViewHolderForLayoutPosition(0) == null
action(isFirstVisible)
}
}
addOnScrollListener(listener)
return listener
}
/**
* Calls notify range changed on the given range.
* There are no validation whenever the range exists or not.
* uses the range.start and the range.length as the item count.
* @receiver RecyclerView.Adapter<*>
* @param range IntRange
*/
@Suppress("NOTHING_TO_INLINE")
inline fun RecyclerView.Adapter<*>.notifyItemRangeChanged(range: IntRange) {
notifyItemRangeChanged(range.first, range.length)
}
/**
* Scrolls this recycler view to the top.
* @receiver RecyclerView
* @param shouldScrollSmooth Boolean whenever this should be performed smoothly (animated) or instantly; if true then it will be smoothly
*/
fun RecyclerView.scrollToTop(shouldScrollSmooth: Boolean = true) {
if (shouldScrollSmooth) {
smoothScrollToPosition(0)
} else {
layoutManager?.scrollToPosition(0)
}
}
/**
* Scrolls this recycler view to the bottom.
* @receiver RecyclerView
* @param shouldScrollSmooth Boolean whenever this should be performed smoothly (animated) or instantly; if true then it will be smoothly
*/
fun RecyclerView.scrollToBottom(shouldScrollSmooth: Boolean = true) {
val lastPositionPlus1 = maxOf(adapter?.itemCount ?: 0, 1) // [1 -> ??]
val lastPosition = lastPositionPlus1 - 1 //go into bounds
if (shouldScrollSmooth) {
smoothScrollToPosition(lastPosition)
} else {
layoutManager?.scrollToPosition(lastPosition)
}
}
| mit | f4d497fae4579885c6e21575c4ef18d4 | 35.089744 | 137 | 0.736767 | 4.599673 | false | false | false | false |
bastman/kotlin-spring-jpa-examples | src/main/kotlin/com/example/demo/api/realestate/handler/common/request/queryDsl.kt | 1 | 2238 | package com.example.demo.api.realestate.handler.common.request
import com.example.demo.api.common.BadRequestException
import com.example.demo.api.realestate.domain.jpa.entities.PropertyType
import java.time.Instant
import java.util.*
object QueryDslOperation {
const val ASC = "asc"
const val DESC = "desc"
const val LIKE = "like"
const val EQ = "eq"
const val GOE = "goe"
const val LOE = "loe"
}
object QueryDslRequestParser {
fun asInstant(fieldValue: String, fieldExpression: String): Instant {
return try {
Instant.parse(fieldValue)
} catch (all: Exception) {
throw BadRequestException(
"Failed to parse field.value"
+ " provided by field.expression=$fieldExpression"
+ " as Instant!"
+ " reason=${all.message} !"
+ " example=$INSTANT_EXAMPLE"
)
}
}
fun asUUID(fieldValue: String, fieldExpression: String): UUID {
return try {
UUID.fromString(fieldValue)
} catch (all: Exception) {
throw BadRequestException(
"Failed to parse field.value"
+ " provided by field.expression=$fieldExpression"
+ " as UUID!"
+ " reason=${all.message} !"
+ " example=$UUID_EXAMPLE"
)
}
}
fun asPropertyType(fieldValue: String, fieldExpression: String): PropertyType {
return try {
PropertyType.valueOf(fieldValue)
} catch (all: Exception) {
throw BadRequestException(
"Failed to parse field.value"
+ " provided by field.expression=$fieldExpression"
+ " as PropertyType!"
+ " reason=${all.message} !"
+ " examples=$PROPERTY_TYPES_ALLOWED"
)
}
}
private val INSTANT_EXAMPLE = Instant.ofEpochSecond(1501595115)
private val UUID_EXAMPLE = UUID.randomUUID()
private val PROPERTY_TYPES_ALLOWED = PropertyType.values()
}
| mit | 2b7176395cbd6368b14c10a5cbd2656e | 34.52381 | 83 | 0.537087 | 4.918681 | false | false | false | false |
tasomaniac/OpenLinkWith | data/src/main/kotlin/com/tasomaniac/openwith/data/PreferredApp.kt | 1 | 605 | package com.tasomaniac.openwith.data
import android.content.ComponentName
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "openwith",
indices = [(Index("host", unique = true))]
)
data class PreferredApp(
@PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") val id: Int = 0,
val host: String,
val component: String,
val preferred: Boolean
) {
val componentName: ComponentName
@Ignore get() = ComponentName.unflattenFromString(component)!!
}
| apache-2.0 | 50c1c5cdf3e1f930eacfe7798b702cbf | 25.304348 | 79 | 0.730579 | 4.087838 | false | false | false | false |
Polidea/RxAndroidBle | sample-kotlin/src/main/kotlin/com/polidea/rxandroidble2/samplekotlin/example1a_background_scanning/BackgroundScanActivity.kt | 1 | 3534 | package com.polidea.rxandroidble2.samplekotlin.example1a_background_scanning
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.polidea.rxandroidble2.exceptions.BleScanException
import com.polidea.rxandroidble2.samplekotlin.R
import com.polidea.rxandroidble2.samplekotlin.SampleApplication
import com.polidea.rxandroidble2.samplekotlin.util.isLocationPermissionGranted
import com.polidea.rxandroidble2.samplekotlin.util.requestLocationPermission
import com.polidea.rxandroidble2.samplekotlin.util.showError
import com.polidea.rxandroidble2.samplekotlin.util.showSnackbarShort
import com.polidea.rxandroidble2.scan.ScanFilter
import com.polidea.rxandroidble2.scan.ScanSettings
import kotlinx.android.synthetic.main.activity_example1a.scan_start_btn
import kotlinx.android.synthetic.main.activity_example1a.scan_stop_btn
class BackgroundScanActivity : AppCompatActivity() {
companion object {
fun newInstance(context: Context) = Intent(context, BackgroundScanActivity::class.java)
}
private val rxBleClient = SampleApplication.rxBleClient
private lateinit var callbackIntent: PendingIntent
private var hasClickedScan = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_example1a)
callbackIntent = ScanReceiver.newPendingIntent(this)
scan_start_btn.setOnClickListener { onScanStartClick() }
scan_stop_btn.setOnClickListener { onScanStopClick() }
}
private fun onScanStartClick() {
if (rxBleClient.isScanRuntimePermissionGranted) {
scanBleDeviceInBackground()
} else {
hasClickedScan = true
requestLocationPermission(rxBleClient)
}
}
private fun scanBleDeviceInBackground() {
if (Build.VERSION.SDK_INT >= 26 /* Build.VERSION_CODES.O */) {
try {
val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.build()
val scanFilter = ScanFilter.Builder()
// .setDeviceAddress("5C:31:3E:BF:F7:34")
// add custom filters if needed
.build()
rxBleClient.backgroundScanner.scanBleDeviceInBackground(callbackIntent, scanSettings, scanFilter)
} catch (scanException: BleScanException) {
Log.e("BackgroundScanActivity", "Failed to start background scan", scanException)
showError(scanException)
}
} else {
showSnackbarShort("Background scanning requires at least API 26")
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (isLocationPermissionGranted(requestCode, grantResults) && hasClickedScan) {
hasClickedScan = false
scanBleDeviceInBackground()
}
}
private fun onScanStopClick() {
if (Build.VERSION.SDK_INT >= 26 /* Build.VERSION_CODES.O */) {
rxBleClient.backgroundScanner.stopBackgroundBleScan(callbackIntent)
} else {
showSnackbarShort("Background scanning requires at least API 26")
}
}
}
| apache-2.0 | bc84da748e65fdafce834838e181396b | 38.266667 | 115 | 0.703735 | 4.808163 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/models/responses/BulkTaskScoringData.kt | 1 | 893 | package com.habitrpg.android.habitica.models.responses
import com.google.gson.annotations.SerializedName
import com.habitrpg.android.habitica.models.user.Buffs
import com.habitrpg.android.habitica.models.user.Training
import com.habitrpg.shared.habitica.models.responses.TaskDirectionData
class BulkTaskScoringData {
@SerializedName("con")
var constitution: Int? = null
@SerializedName("str")
var strength: Int? = null
@SerializedName("per")
var per: Int? = null
@SerializedName("int")
var intelligence: Int? = null
var training: Training? = null
var buffs: Buffs? = null
var points: Int? = null
var lvl: Int? = null
@SerializedName("class")
var habitClass: String? = null
var gp: Double? = null
var exp: Double? = null
var mp: Double? = null
var hp: Double? = null
var tasks: List<TaskDirectionData> = listOf()
}
| gpl-3.0 | 64d9516895a306d9e3606b5c0beba066 | 29.793103 | 70 | 0.701008 | 3.865801 | false | false | false | false |
campos20/tnoodle | cloudscrambles/src/main/kotlin/org/worldcubeassociation/tnoodle/server/cloudscrambles/GoogleServerEnvironmentConfig.kt | 1 | 1206 | package org.worldcubeassociation.tnoodle.server.cloudscrambles
import org.worldcubeassociation.tnoodle.server.ServerEnvironmentConfig
import org.worldcubeassociation.tnoodle.server.util.WebServerUtils.DEVEL_VERSION
import org.worldcubeassociation.tnoodle.server.util.WebServerUtils.callerClass
import java.io.File
import java.io.File.separator
object GoogleServerEnvironmentConfig : ServerEnvironmentConfig {
private val CONFIG_FILE = javaClass.getResourceAsStream("/version.tnoodle")
private val CONFIG_DATA = CONFIG_FILE?.reader()?.readLines() ?: listOf()
val JAVA_HOME = System.getProperty("java.home")
val FONT_CONFIG_NAME = "fontconfig.Prodimage.properties"
val FONT_CONFIG = ("$JAVA_HOME${separator}lib${separator}$FONT_CONFIG_NAME")
val FONT_CONFIG_PROPERTY = "sun.awt.fontconfig"
override val projectName: String
get() = CONFIG_DATA.getOrNull(0)
?: callerClass?.simpleName!!
override val projectVersion: String
get() = CONFIG_DATA.getOrNull(1)
?: DEVEL_VERSION
fun overrideFontConfig() {
if (File(FONT_CONFIG).exists()) {
System.setProperty(FONT_CONFIG_PROPERTY, FONT_CONFIG)
}
}
}
| gpl-3.0 | 579550a9cc086c4771d4f963d0cfa267 | 35.545455 | 80 | 0.728027 | 4.246479 | false | true | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/network/AndroidCookieJar.kt | 1 | 1957 | package eu.kanade.tachiyomi.network
import android.content.Context
import android.os.Build
import android.webkit.CookieManager
import android.webkit.CookieSyncManager
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
class AndroidCookieJar(context: Context) : CookieJar {
private val manager = CookieManager.getInstance()
private val syncManager by lazy { CookieSyncManager.createInstance(context) }
init {
// Init sync manager when using anything below L
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
syncManager
}
}
override fun saveFromResponse(url: HttpUrl, cookies: MutableList<Cookie>) {
val urlString = url.toString()
for (cookie in cookies) {
manager.setCookie(urlString, cookie.toString())
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
syncManager.sync()
}
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
return get(url)
}
fun get(url: HttpUrl): List<Cookie> {
val cookies = manager.getCookie(url.toString())
return if (cookies != null && !cookies.isEmpty()) {
cookies.split(";").mapNotNull { Cookie.parse(url, it) }
} else {
emptyList()
}
}
fun remove(url: HttpUrl) {
val urlString = url.toString()
val cookies = manager.getCookie(urlString) ?: return
cookies.split(";")
.map { it.substringBefore("=") }
.onEach { manager.setCookie(urlString, "$it=;Max-Age=-1") }
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
syncManager.sync()
}
}
fun removeAll() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
manager.removeAllCookies {}
} else {
manager.removeAllCookie()
syncManager.sync()
}
}
}
| apache-2.0 | c85e6216f6889cccad1a0bcf069084f2 | 26.56338 | 81 | 0.611139 | 4.378076 | false | false | false | false |
devromik/poly | src/test/kotlin/net/devromik/poly/PairwiseSumTest.kt | 1 | 1752 | package net.devromik.poly
import com.carrotsearch.hppc.IntArrayList
import com.carrotsearch.hppc.IntArrayList.from
import org.junit.Test
import org.junit.Assert.*
/**
* @author Shulnyaev Roman
*/
class PairwiseSumTest {
@Test fun canCalculatePairwiseSumOfTwoNonNegativeIntegerArrays() {
var a1 = IntArrayList()
var a2 = IntArrayList()
assertEquals(IntArrayList(), pairwiseSumOfNonNegativeArrays(a1, a2))
/* ****************************** */
a1 = from(1)
a2 = IntArrayList()
assertEquals(IntArrayList(), pairwiseSumOfNonNegativeArrays(a1, a2))
// ****************************** //
a1 = IntArrayList()
a2 = from(1)
assertEquals(IntArrayList(), pairwiseSumOfNonNegativeArrays(a1, a2))
// ****************************** //
a1 = from(0)
a2 = from(0)
assertEquals(from(0), pairwiseSumOfNonNegativeArrays(a1, a2))
// ****************************** //
a1 = from(0)
a2 = from(0, 1)
assertEquals(from(0, 1), pairwiseSumOfNonNegativeArrays(a1, a2))
// ****************************** //
a1 = from(1, 0)
a2 = from(0)
assertEquals(from(0, 1), pairwiseSumOfNonNegativeArrays(a1, a2))
// ****************************** //
a1 = from(0, 1, 2, 3)
a2 = from(4, 5)
assertEquals(from(4, 5, 6, 7, 8), pairwiseSumOfNonNegativeArrays(a1, a2))
// ****************************** //
a1 = from(7, 0, 1, 2, 3, 1, 7, 8)
a2 = from(4, 5, 9, 3, 3, 5, 7, 1)
assertEquals(
from(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17),
pairwiseSumOfNonNegativeArrays(a1, a2))
}
} | mit | 14b7eaf781f9efded7acd5d1b656106e | 24.042857 | 81 | 0.492009 | 3.568228 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/domain/category/interactor/CreateCategoryWithName.kt | 1 | 1693 | package eu.kanade.domain.category.interactor
import eu.kanade.domain.category.model.Category
import eu.kanade.domain.category.model.anyWithName
import eu.kanade.domain.category.repository.CategoryRepository
import eu.kanade.domain.library.service.LibraryPreferences
import eu.kanade.tachiyomi.util.lang.withNonCancellableContext
import eu.kanade.tachiyomi.util.system.logcat
import logcat.LogPriority
class CreateCategoryWithName(
private val categoryRepository: CategoryRepository,
private val preferences: LibraryPreferences,
) {
private val initialFlags: Long
get() {
val sort = preferences.librarySortingMode().get()
return preferences.libraryDisplayMode().get().flag or
sort.type.flag or
sort.direction.flag
}
suspend fun await(name: String): Result = withNonCancellableContext {
val categories = categoryRepository.getAll()
if (categories.anyWithName(name)) {
return@withNonCancellableContext Result.NameAlreadyExistsError
}
val nextOrder = categories.maxOfOrNull { it.order }?.plus(1) ?: 0
val newCategory = Category(
id = 0,
name = name,
order = nextOrder,
flags = initialFlags,
)
try {
categoryRepository.insert(newCategory)
Result.Success
} catch (e: Exception) {
logcat(LogPriority.ERROR, e)
Result.InternalError(e)
}
}
sealed class Result {
object Success : Result()
object NameAlreadyExistsError : Result()
data class InternalError(val error: Throwable) : Result()
}
}
| apache-2.0 | 2446fbbe9a57a51ad6b1774a315d1fe1 | 31.557692 | 74 | 0.660366 | 4.837143 | false | false | false | false |
abigpotostew/easypolitics | db/src/test/kotlin/bz/bracken/stewart/db/AssertAllFound.kt | 1 | 1497 | package bz.bracken.stewart.db
import org.junit.Assert.assertTrue
/**
* when using comparator, the expected collection could be mocked objects that would fail
* referential "===" equality but may pass with the comparison function.
*/
class AssertAllFound<T>(val expected: Collection<T>,
val failIfNotExact: Boolean = false,
val comparator: (T.(T) -> Boolean)? = null) {
val queue: MutableCollection<T> = expected.toMutableList()
fun foundElement(el: T) {
if (containsElement(el)) {
if (comparator != null) {
queue.remove(findComparableElement(el))
}
else {
queue.remove(el)
}
}
else {
assertTrue("Unexpected element found: $el", !failIfNotExact)
}
}
private fun findComparableElement(el: T): T? {
if (comparator != null) {
val comp: T.(T) -> Boolean = comparator
for (item in queue) {
if (item.comp(el)) {
return item
}
}
}
return null
}
private fun containsElement(el: T): Boolean {
if (comparator != null) {
val found = findComparableElement(el)
return found != null
}
else {
return queue.contains(el)
}
}
fun assertAllFound() {
assertTrue(
"All elements were not found, ${queue.size} out of ${expected.size} remaining!! - $queue",
queue.isEmpty())
}
} | apache-2.0 | 174dae97ffd95e9f023f1a4488476770 | 25.75 | 103 | 0.553774 | 4.33913 | false | false | false | false |
dempe/pinterest-java | src/main/java/com/chrisdempewolf/pinterest/methods/user/UserEndPointURIBuilder.kt | 1 | 943 | package com.chrisdempewolf.pinterest.methods.user
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils.isNotBlank
import org.apache.http.client.utils.URIBuilder
import java.net.URI
import java.net.URISyntaxException
object UserEndPointURIBuilder {
private const val BASE_URL = "https://api.pinterest.com/v1/me/"
@JvmStatic
@Throws(URISyntaxException::class)
fun buildURI(accessToken: String, fields: String? = null, path: String? = null, query: String? = null): URI {
val uriBuilder = URIBuilder(BASE_URL).setParameter("access_token", accessToken)
if (isNotBlank(fields)) {
uriBuilder.setParameter("fields", fields)
}
if (isNotBlank(path)) {
uriBuilder.setPath(uriBuilder.path + path)
}
if (isNotBlank(query)) {
uriBuilder.setParameter("query", query)
}
return uriBuilder.build()
}
} | mit | 393e5c7e0eb0bd6cc7a36275d09ace67 | 31.551724 | 113 | 0.680806 | 4.135965 | false | false | false | false |
KotlinNLP/SimpleDNN | src/test/kotlin/core/attention/scaleddot/ScaledDotAttentionParametersSpec.kt | 1 | 3433 | /* Copyright 2020-present Simone Cangialosi. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.attention.scaleddot
import com.kotlinnlp.simplednn.core.functionalities.initializers.RandomInitializer
import com.kotlinnlp.simplednn.core.functionalities.randomgenerators.RandomGenerator
import com.kotlinnlp.simplednn.core.layers.models.attention.scaleddot.ScaledDotAttentionLayerParameters
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.whenever
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class ScaledDotAttentionParametersSpec : Spek({
describe("ScaledDotAttentionParameters") {
context("initialization") {
val randomGenerator = mock<RandomGenerator>()
var i = 0.0
whenever(randomGenerator.next()).thenAnswer { i++ }
val params = ScaledDotAttentionLayerParameters(
inputSize = 2,
attentionSize = 3,
outputSize = 2,
weightsInitializer = RandomInitializer(randomGenerator),
biasesInitializer = RandomInitializer(randomGenerator))
it("should have the queries weights with the expected initialized values") {
assertTrue {
params.queries.weights.values.equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(0.0, 3.0),
doubleArrayOf(1.0, 4.0),
doubleArrayOf(2.0, 5.0)
)),
tolerance = 1.0e-06
)
}
}
it("should have the keys weights with the expected initialized values") {
assertTrue {
params.keys.weights.values.equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(6.0, 9.0),
doubleArrayOf(7.0, 10.0),
doubleArrayOf(8.0, 11.0)
)),
tolerance = 1.0e-06
)
}
}
it("should have the values weights with the expected initialized values") {
assertTrue {
params.values.weights.values.equals(
DenseNDArrayFactory.arrayOf(listOf(
doubleArrayOf(12.0, 14.0),
doubleArrayOf(13.0, 15.0)
)),
tolerance = 1.0e-06
)
}
}
it("should have the queries biases with the expected initialized values") {
assertTrue {
params.queries.biases.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(16.0, 17.0, 18.0)),
tolerance = 1.0e-06)
}
}
it("should have the keys biases with the expected initialized values") {
assertTrue {
params.keys.biases.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(19.0, 20.0, 21.0)),
tolerance = 1.0e-06)
}
}
it("should have the values biases with the expected initialized values") {
assertTrue {
params.values.biases.values.equals(
DenseNDArrayFactory.arrayOf(doubleArrayOf(22.0, 23.0)),
tolerance = 1.0e-06)
}
}
}
}
})
| mpl-2.0 | cc2f391fe5c49f5c4c97ac02aaba4ec2 | 32.330097 | 103 | 0.622488 | 4.55305 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/viewmodel/mlp/ModalLayoutPickerViewModel.kt | 1 | 6908 | package org.wordpress.android.viewmodel.mlp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.wordpress.android.BuildConfig
import org.wordpress.android.R.string
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.generated.SiteActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.SiteStore
import org.wordpress.android.fluxc.store.SiteStore.FetchBlockLayoutsPayload
import org.wordpress.android.fluxc.store.SiteStore.OnBlockLayoutsFetched
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.layoutpicker.LayoutModel
import org.wordpress.android.ui.layoutpicker.LayoutPickerUiState.Content
import org.wordpress.android.ui.layoutpicker.LayoutPickerUiState.Error
import org.wordpress.android.ui.layoutpicker.LayoutPickerUiState.Loading
import org.wordpress.android.ui.layoutpicker.LayoutPickerViewModel
import org.wordpress.android.ui.mlp.ModalLayoutPickerDimensionProvider
import org.wordpress.android.ui.layoutpicker.toLayoutCategories
import org.wordpress.android.ui.layoutpicker.toLayoutModels
import org.wordpress.android.ui.mlp.ModalLayoutPickerTracker
import org.wordpress.android.ui.mlp.SupportedBlocksProvider
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.util.DisplayUtilsWrapper
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.SiteUtils
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.SingleLiveEvent
import javax.inject.Inject
import javax.inject.Named
/**
* Implements the Modal Layout Picker view model
*/
class ModalLayoutPickerViewModel @Inject constructor(
private val dispatcher: Dispatcher,
private val siteStore: SiteStore,
private val selectedSiteRepository: SelectedSiteRepository,
private val supportedBlocksProvider: SupportedBlocksProvider,
private val thumbDimensionProvider: ModalLayoutPickerDimensionProvider,
private val displayUtilsWrapper: DisplayUtilsWrapper,
override val networkUtils: NetworkUtilsWrapper,
private val analyticsTracker: ModalLayoutPickerTracker,
@Named(BG_THREAD) override val bgDispatcher: CoroutineDispatcher,
@Named(UI_THREAD) override val mainDispatcher: CoroutineDispatcher
) : LayoutPickerViewModel(mainDispatcher, bgDispatcher, networkUtils, analyticsTracker) {
/**
* Tracks the Modal Layout Picker visibility state
*/
private val _isModalLayoutPickerShowing = MutableLiveData<Event<Boolean>>()
val isModalLayoutPickerShowing: LiveData<Event<Boolean>> = _isModalLayoutPickerShowing
/**
* Create new page event
*/
private val _onCreateNewPageRequested = SingleLiveEvent<PageRequest.Create>()
val onCreateNewPageRequested: LiveData<PageRequest.Create> = _onCreateNewPageRequested
private val site: SiteModel? by lazy {
siteStore.getSiteByLocalId(selectedSiteRepository.getSelectedSiteLocalId(true))
}
override val useCachedData: Boolean = true
override val shouldUseMobileThumbnail = false
override val selectedLayout: LayoutModel?
get() = (uiState.value as? Content)?.let { state ->
state.selectedLayoutSlug?.let { slug ->
site?.let { site ->
siteStore.getBlockLayout(site, slug)
}
}?.let { LayoutModel(it) }
}
sealed class PageRequest(val template: String?) {
open class Create(template: String?, val title: String) : PageRequest(template)
object Blank : Create(null, "")
class Preview(template: String?, val content: String, val site: SiteModel, val demoUrl: String?) : PageRequest(
template
)
}
init {
dispatcher.register(this)
}
override fun onCleared() {
dispatcher.unregister(this)
super.onCleared()
}
override fun fetchLayouts(preferCache: Boolean) {
val selectedSite = site
if (!networkUtils.isNetworkAvailable() || selectedSite == null) {
setErrorState()
return
}
if (!preferCache) {
updateUiState(Loading)
}
launch {
val payload = FetchBlockLayoutsPayload(
selectedSite,
supportedBlocksProvider.fromAssets().supported,
thumbDimensionProvider.previewWidth.toFloat(),
thumbDimensionProvider.previewHeight.toFloat(),
thumbDimensionProvider.scale.toFloat(),
BuildConfig.DEBUG,
preferCache
)
dispatcher.dispatch(SiteActionBuilder.newFetchBlockLayoutsAction(payload))
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onBlockLayoutsFetched(event: OnBlockLayoutsFetched) {
if (event.isError) {
setErrorState()
} else {
handleResponse(
(event.layouts ?: listOf()).toLayoutModels(),
(event.categories ?: listOf()).toLayoutCategories()
)
}
}
private fun setErrorState() {
if (networkUtils.isNetworkAvailable()) {
updateUiState(Error(string.mlp_error_title, string.mlp_error_subtitle))
} else {
updateUiState(Error(string.mlp_network_error_title, string.mlp_network_error_subtitle))
}
}
/**
* Checks if the Modal Layout Picker can be shown
* at this point the only requirement is to have the block editor enabled
* @return true if the Modal Layout Picker can be shown
*/
fun canShowModalLayoutPicker() = SiteUtils.isBlockEditorDefaultForNewPost(site)
/**
* Triggers the create page flow and shows the MLP
*/
fun createPageFlowTriggered() {
_isModalLayoutPickerShowing.value = Event(true)
initializePreviewMode(displayUtilsWrapper.isTablet())
fetchLayouts()
}
/**
* Dismisses the MLP
*/
fun dismiss() {
_isModalLayoutPickerShowing.postValue(Event(false))
updateUiState(Content())
}
/**
* Create page tapped
*/
fun onCreatePageClicked() {
createPage()
dismiss()
}
override fun onPreviewChooseTapped() {
super.onPreviewChooseTapped()
onCreatePageClicked()
}
/**
* Triggers the creation of a new page
*/
private fun createPage() {
selectedLayout?.let { layout ->
_onCreateNewPageRequested.value = PageRequest.Create(layout.slug, layout.title)
return
}
_onCreateNewPageRequested.value = PageRequest.Blank
}
}
| gpl-2.0 | a46409488f3f023d7ffdca2352733cff | 35.941176 | 119 | 0.702519 | 4.840925 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/quickstart/QuickStartTracker.kt | 1 | 3836 | package org.wordpress.android.ui.quickstart
import org.wordpress.android.analytics.AnalyticsTracker.Stat
import org.wordpress.android.analytics.AnalyticsTracker.Stat.QUICK_START_TYPE_CUSTOMIZE_DISMISSED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.QUICK_START_TYPE_CUSTOMIZE_VIEWED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.QUICK_START_TYPE_GET_TO_KNOW_APP_DISMISSED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.QUICK_START_TYPE_GET_TO_KNOW_APP_VIEWED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.QUICK_START_TYPE_GROW_DISMISSED
import org.wordpress.android.analytics.AnalyticsTracker.Stat.QUICK_START_TYPE_GROW_VIEWED
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType
import org.wordpress.android.ui.mysite.MySiteCardAndItem
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Type.QUICK_START_CARD
import org.wordpress.android.ui.mysite.SelectedSiteRepository
import org.wordpress.android.ui.mysite.tabs.MySiteTabType
import org.wordpress.android.ui.prefs.AppPrefsWrapper
import org.wordpress.android.ui.quickstart.QuickStartType.NewSiteQuickStartType
import org.wordpress.android.util.analytics.AnalyticsTrackerWrapper
import javax.inject.Inject
class QuickStartTracker @Inject constructor(
private val analyticsTrackerWrapper: AnalyticsTrackerWrapper,
private val appPrefsWrapper: AppPrefsWrapper,
private val selectedSiteRepository: SelectedSiteRepository
) {
private val cardsShownTracked = mutableListOf<Pair<MySiteCardAndItem.Type, Map<String, String>>>()
@JvmOverloads
fun track(stat: Stat, properties: Map<String, Any?>? = null) {
val props = HashMap<String, Any?>()
properties?.let { props.putAll(it) }
props[SITE_TYPE] = getLastSelectedQuickStartType().trackingLabel
analyticsTrackerWrapper.track(stat, props)
}
fun trackShown(itemType: MySiteCardAndItem.Type, tabType: MySiteTabType) {
if (itemType == QUICK_START_CARD) {
val props = mapOf(
TAB to tabType.trackingLabel,
SITE_TYPE to getLastSelectedQuickStartType().trackingLabel
)
val cardsShownTrackedPair = Pair(itemType, props)
if (!cardsShownTracked.contains(cardsShownTrackedPair)) {
cardsShownTracked.add(cardsShownTrackedPair)
analyticsTrackerWrapper.track(Stat.QUICK_START_CARD_SHOWN, props)
}
}
}
fun trackQuickStartListViewed(tasksType: QuickStartTaskType) {
when (tasksType) {
QuickStartTaskType.CUSTOMIZE -> track(QUICK_START_TYPE_CUSTOMIZE_VIEWED)
QuickStartTaskType.GROW -> track(QUICK_START_TYPE_GROW_VIEWED)
QuickStartTaskType.GET_TO_KNOW_APP -> track(QUICK_START_TYPE_GET_TO_KNOW_APP_VIEWED)
QuickStartTaskType.UNKNOWN -> Unit // Do Nothing
}
}
fun trackQuickStartListDismissed(tasksType: QuickStartTaskType) {
when (tasksType) {
QuickStartTaskType.CUSTOMIZE -> track(QUICK_START_TYPE_CUSTOMIZE_DISMISSED)
QuickStartTaskType.GROW -> track(QUICK_START_TYPE_GROW_DISMISSED)
QuickStartTaskType.GET_TO_KNOW_APP -> track(QUICK_START_TYPE_GET_TO_KNOW_APP_DISMISSED)
QuickStartTaskType.UNKNOWN -> Unit // Do Nothing
}
}
fun resetShown() {
cardsShownTracked.clear()
}
private fun getLastSelectedQuickStartType(): QuickStartType {
return selectedSiteRepository.getSelectedSite()?.let {
val siteLocalId = it.id.toLong()
appPrefsWrapper.getLastSelectedQuickStartTypeForSite(siteLocalId)
} ?: NewSiteQuickStartType
}
companion object {
private const val SITE_TYPE = "site_type"
private const val TAB = "tab"
}
}
| gpl-2.0 | 9b726dafd5eacf28f0fc9a362e82f699 | 45.780488 | 103 | 0.731491 | 4.528926 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/jetpackoverlay/JetpackFeatureFullScreenOverlayFragment.kt | 1 | 7963 | package org.wordpress.android.ui.jetpackoverlay
import android.content.res.Resources
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.fragment.app.activityViewModels
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import dagger.hilt.android.AndroidEntryPoint
import org.wordpress.android.databinding.JetpackFeatureRemovalOverlayBinding
import org.wordpress.android.ui.ActivityLauncherWrapper
import org.wordpress.android.ui.ActivityLauncherWrapper.Companion.JETPACK_PACKAGE_NAME
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureOverlayActions.DismissDialog
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureOverlayActions.ForwardToJetpack
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureOverlayActions.OpenPlayStore
import org.wordpress.android.ui.jetpackoverlay.JetpackFeatureRemovalOverlayUtil.JetpackFeatureOverlayScreenType
import org.wordpress.android.ui.sitecreation.misc.SiteCreationSource
import org.wordpress.android.ui.sitecreation.misc.SiteCreationSource.UNSPECIFIED
import org.wordpress.android.util.RtlUtils
import org.wordpress.android.util.extensions.exhaustive
import org.wordpress.android.util.extensions.setVisible
import javax.inject.Inject
@AndroidEntryPoint
class JetpackFeatureFullScreenOverlayFragment : BottomSheetDialogFragment() {
@Inject lateinit var activityLauncherWrapper: ActivityLauncherWrapper
private val viewModel: JetpackFeatureFullScreenOverlayViewModel by activityViewModels()
private var _binding: JetpackFeatureRemovalOverlayBinding? = null
private val binding get() = _binding ?: throw NullPointerException("_binding cannot be null")
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = JetpackFeatureRemovalOverlayBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.init(
getSiteScreen(),
getIfSiteCreationOverlay(),
getIfDeepLinkOverlay(),
getSiteCreationSource(),
RtlUtils.isRtl(view.context)
)
binding.setupObservers()
(dialog as? BottomSheetDialog)?.apply {
setOnShowListener {
val bottomSheet: FrameLayout = dialog?.findViewById(
com.google.android.material.R.id.design_bottom_sheet
) ?: return@setOnShowListener
val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)
bottomSheetBehavior.setMaxWidth(ViewGroup.LayoutParams.MATCH_PARENT)
bottomSheetBehavior.isDraggable = false
if (bottomSheet.layoutParams != null) {
showFullScreenBottomSheet(bottomSheet)
}
expandBottomSheet(bottomSheetBehavior)
}
}
}
private fun showFullScreenBottomSheet(bottomSheet: FrameLayout) {
val layoutParams = bottomSheet.layoutParams
layoutParams.height = Resources.getSystem().displayMetrics.heightPixels
bottomSheet.layoutParams = layoutParams
}
private fun expandBottomSheet(bottomSheetBehavior: BottomSheetBehavior<FrameLayout>) {
bottomSheetBehavior.skipCollapsed = true
bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
private fun getSiteScreen() =
arguments?.getSerializable(OVERLAY_SCREEN_TYPE) as JetpackFeatureOverlayScreenType?
private fun getIfSiteCreationOverlay() =
arguments?.getSerializable(IS_SITE_CREATION_OVERLAY) as Boolean
private fun getIfDeepLinkOverlay() =
arguments?.getSerializable(IS_DEEP_LINK_OVERLAY) as Boolean
private fun getSiteCreationSource() =
arguments?.getSerializable(SITE_CREATION_OVERLAY_SOURCE) as SiteCreationSource
private fun JetpackFeatureRemovalOverlayBinding.setupObservers() {
viewModel.uiState.observe(viewLifecycleOwner) {
renderUiState(it)
}
viewModel.action.observe(viewLifecycleOwner) { action ->
when (action) {
is OpenPlayStore -> {
dismiss()
activity?.let {
activityLauncherWrapper.openPlayStoreLink(it, JETPACK_PACKAGE_NAME)
}
}
is DismissDialog -> {
dismiss()
}
is ForwardToJetpack -> {
dismiss()
}
}.exhaustive
}
}
private fun JetpackFeatureRemovalOverlayBinding.renderUiState(
jetpackPoweredOverlayUIState: JetpackFeatureOverlayUIState
) {
updateVisibility(jetpackPoweredOverlayUIState.componentVisibility)
updateContent(jetpackPoweredOverlayUIState.overlayContent)
setClickListener(jetpackPoweredOverlayUIState.componentVisibility.secondaryButton)
}
private fun JetpackFeatureRemovalOverlayBinding.setClickListener(secondaryButtonVisible: Boolean) {
primaryButton.setOnClickListener {
viewModel.openJetpackAppDownloadLink()
}
closeButton.setOnClickListener { viewModel.closeBottomSheet() }
if (secondaryButtonVisible) secondaryButton.setOnClickListener { viewModel.continueToFeature() }
}
private fun JetpackFeatureRemovalOverlayBinding.updateVisibility(
componentVisibility: JetpackFeatureOverlayComponentVisibility
) {
componentVisibility.let {
illustrationView.setVisible(it.illustration)
title.setVisible(it.title)
caption.setVisible(it.caption)
primaryButton.setVisible(it.primaryButton)
secondaryButton.setVisible(it.secondaryButton)
}
}
private fun JetpackFeatureRemovalOverlayBinding.updateContent(overlayContent: JetpackFeatureOverlayContent) {
overlayContent.let {
illustrationView.setAnimation(it.illustration)
illustrationView.playAnimation()
title.text = getString(it.title)
caption.text = getString(it.caption)
primaryButton.text = getString(it.primaryButtonText)
it.secondaryButtonText?.let { secondaryButton.text = getString(it) }
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
const val TAG = "JETPACK_POWERED_OVERLAY_FULL_SCREEN_FRAGMENT"
private const val OVERLAY_SCREEN_TYPE = "KEY_JETPACK_OVERLAY_SCREEN"
private const val IS_SITE_CREATION_OVERLAY = "KEY_IS_SITE_CREATION_OVERLAY"
private const val IS_DEEP_LINK_OVERLAY = "KEY_IS_DEEP_LINK_OVERLAY"
private const val SITE_CREATION_OVERLAY_SOURCE = "KEY_SITE_CREATION_OVERLAY_SOURCE"
@JvmStatic fun newInstance(
jetpackFeatureOverlayScreenType: JetpackFeatureOverlayScreenType? = null,
isSiteCreationOverlay: Boolean = false,
isDeepLinkOverlay: Boolean = false,
siteCreationSource: SiteCreationSource? = UNSPECIFIED
) = JetpackFeatureFullScreenOverlayFragment().apply {
arguments = Bundle().apply {
putSerializable(OVERLAY_SCREEN_TYPE, jetpackFeatureOverlayScreenType)
putBoolean(IS_SITE_CREATION_OVERLAY, isSiteCreationOverlay)
putBoolean(IS_DEEP_LINK_OVERLAY, isDeepLinkOverlay)
putSerializable(SITE_CREATION_OVERLAY_SOURCE, siteCreationSource)
}
}
}
}
| gpl-2.0 | c9576239b6b38dfb1558f4c813c30011 | 42.513661 | 113 | 0.70589 | 5.398644 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/evaluation/src/org/jetbrains/kotlin/idea/debugger/evaluate/KotlinSuspendFunctionWrapper.kt | 1 | 4937 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.evaluate
import com.intellij.debugger.engine.evaluation.EvaluateException
import com.intellij.psi.PsiElement
import com.intellij.psi.util.descendantsOfType
import com.intellij.psi.util.parentsOfType
import org.jetbrains.kotlin.backend.common.descriptors.isSuspend
import org.jetbrains.kotlin.builtins.isSuspendFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.calls.checkers.COROUTINE_CONTEXT_FQ_NAME
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
internal class KotlinSuspendFunctionWrapper(
val bindingContext: BindingContext,
val executionContext: ExecutionContext,
val psiContext: PsiElement?,
isCoroutineScopeAvailable: Boolean
) : KotlinExpressionWrapper {
private val coroutineContextKeyword =
if (isCoroutineScopeAvailable)
COROUTINE_CONTEXT_FQ_NAME.shortName().asString()
else
COROUTINE_CONTEXT_FQ_NAME.asString()
override fun createWrappedExpressionText(expressionText: String): String {
checkIfKotlinxCoroutinesIsAvailable()
val isCoroutineContextAvailable = runReadAction {
psiContext.isCoroutineContextAvailable()
}
return wrapInRunBlocking(expressionText, isCoroutineContextAvailable)
}
override fun isApplicable(expression: KtExpression) = expression.containsSuspendFunctionCall(bindingContext)
private fun wrapInRunBlocking(expressionText: String, isCoroutineContextAvailable: Boolean) =
buildString {
append("kotlinx.coroutines.runBlocking")
if (isCoroutineContextAvailable) {
append("""
(
@kotlin.OptIn(kotlin.ExperimentalStdlibApi::class)
$coroutineContextKeyword.minusKey(kotlinx.coroutines.CoroutineDispatcher)
)
""".trimIndent())
}
append(" {\n\t")
append(expressionText)
append("\n}")
}
private fun KtExpression.containsSuspendFunctionCall(bindingContext: BindingContext): Boolean {
return runReadAction {
descendantsOfType<KtCallExpression>().any { callExpression ->
val resolvedCall = callExpression.getResolvedCall(bindingContext)
resolvedCall != null
&& resolvedCall.resultingDescriptor.isSuspend
&& !callExpression.parentsOfType<KtLambdaExpression>().isCoroutineContextAvailableFromLambda(bindingContext)
}
}
}
private fun PsiElement?.isCoroutineContextAvailable() =
if (this == null) {
false
} else {
parentsOfType<KtNamedFunction>().isCoroutineContextAvailableFromFunction() ||
parentsOfType<KtLambdaExpression>().isCoroutineContextAvailableFromLambda()
}
private fun Sequence<KtNamedFunction>.isCoroutineContextAvailableFromFunction(): Boolean {
for (item in this) {
val descriptor = item.descriptor as? CallableDescriptor ?: continue
if (descriptor.isSuspend) {
return true
}
}
return false
}
private fun Sequence<KtLambdaExpression>.isCoroutineContextAvailableFromLambda(
bindingContext: BindingContext
): Boolean {
for (item in this) {
val type = item.getType(bindingContext) ?: continue
if (type.isSuspendFunctionType) {
return true
}
}
return false
}
private fun Sequence<KtLambdaExpression>.isCoroutineContextAvailableFromLambda() =
if (none()) {
false
} else {
val bindingContext = last().analyze(BodyResolveMode.PARTIAL)
isCoroutineContextAvailableFromLambda(bindingContext)
}
private fun checkIfKotlinxCoroutinesIsAvailable() {
val debugProcess = executionContext.debugProcess
val evaluationContext = executionContext.evaluationContext
try {
debugProcess.findClass(evaluationContext, "kotlinx.coroutines.BuildersKt", evaluationContext.classLoader)
} catch (ex: EvaluateException) {
evaluationException(KotlinDebuggerEvaluationBundle.message("error.failed.to.wrap.suspend.function"))
}
}
}
| apache-2.0 | 981e957f63bd5706628ddeab753b65da | 40.141667 | 158 | 0.692728 | 5.661697 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/KtType.kt | 2 | 4258 | // 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.workspaceModel.codegen.deft.model
import org.jetbrains.deft.annotations.Child
import com.intellij.workspaceModel.codegen.deft.*
class KtType(
val classifierRange: SrcRange,
val args: List<KtType> = listOf(),
val optional: Boolean = false,
annotations: List<KtAnnotation> = listOf()
) {
val annotations: KtAnnotations = KtAnnotations().also { it.list.addAll(annotations) }
val classifier: String get() = classifierRange.text.replace(" ", "")
override fun toString(): String =
(if (annotations.list.isEmpty()) "" else annotations.list.joinToString(" ") + " ") +
if (args.isEmpty()) classifier
else "$classifier<${args.joinToString(", ")}>"
fun build(scope: KtScope, diagnostics: Diagnostics, annotations: KtAnnotations = KtAnnotations(), keepUnknownFields: Boolean): ValueType<*>? {
val childAnnotation = this.annotations.byName[Child::class.java.simpleName]
?: annotations.byName[Child::class.java.simpleName]
val result = when (classifier) {
"String" -> TString
"Int" -> TInt
"Boolean" -> TBoolean
"List" -> {
if (optional) {
diagnostics.add(classifierRange, "Nullable lists are not supported")
null
} else {
val target = args.singleOrNull()
if (target == null) diagnostics.add(classifierRange, "List should have 1 type argument: $this")
val elementType = target?.build(scope, diagnostics, annotations, keepUnknownFields)
if (elementType != null) TList(elementType) else null
}
}
"Set" -> {
if (optional) {
diagnostics.add(classifierRange, "Nullable sets are not supported")
null
} else {
val target = args.singleOrNull()
if (target == null) diagnostics.add(classifierRange, "Set should have 1 type argument: $this")
val elementType = target?.build(scope, diagnostics, annotations, keepUnknownFields)
if (elementType == null) {
null
} else if (elementType is TRef<*>) {
diagnostics.add(classifierRange, "Set of references is not supported")
null
} else {
TSet(elementType)
}
}
}
"Map" -> {
if (args.size != 2) {
diagnostics.add(classifierRange, "Map should have 2 type arguments: $this")
null
}
else {
val (k, v) = args
val kt = k.build(scope, diagnostics, annotations, keepUnknownFields)
val vt = v.build(scope, diagnostics, annotations, keepUnknownFields)
if (kt != null && vt != null) TMap(kt, vt) else null
}
}
else -> {
val ktInterface = scope.resolve(classifier)?.ktInterface
if (ktInterface?.kind == null && classifier !in listOf("VirtualFileUrl", "EntitySource", "PersistentEntityId") && !keepUnknownFields) {
diagnostics.add(classifierRange, "Unsupported type: $this. " +
"Supported: String, Int, Boolean, List, Set, Map, Serializable, subtypes of Obj")
null
}
else {
var kind = if (classifier in listOf("VirtualFileUrl", "PersistentEntityId")) WsEntityInterface() else ktInterface?.kind
if (kind == null && keepUnknownFields) {
kind = WsUnknownType
}
kind?.buildValueType(ktInterface, diagnostics, this, childAnnotation)
}
}
}
if (result == null) return null
if (childAnnotation != null && result !is TRef) {
diagnostics.add(childAnnotation.name, "@Child allowed only on references")
}
return if (optional) TOptional(result) else result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as KtType
if (args != other.args) return false
if (classifier != other.classifier) return false
return true
}
override fun hashCode(): Int {
var result = args.hashCode()
result = 31 * result + classifier.hashCode()
return result
}
} | apache-2.0 | eac6d446eb419e423f37da9413f7c04c | 37.026786 | 144 | 0.617191 | 4.50582 | false | false | false | false |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/adapters/LyricsAdapter.kt | 1 | 3297 | package com.kelsos.mbrc.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import butterknife.BindView
import butterknife.ButterKnife
import com.kelsos.mbrc.R
class LyricsAdapter(private var data: List<String> = emptyList()) :
RecyclerView.Adapter<LyricsAdapter.ViewHolder>() {
/**
* Called when RecyclerView needs a new [ViewHolder] of the given type to represent
* an item.
*
*
* This new ViewHolder should be constructed with a new View that can represent the items
* of the given type. You can either create a new View manually or inflate it from an XML
* layout file.
*
*
* The new ViewHolder will be used to display items of the adapter using
* [.onBindViewHolder]. Since it will be re-used to display different
* items in the data set, it is a good idea to cache references to sub views of the View to
* avoid unnecessary [View.findViewById] calls.
* @param parent The ViewGroup into which the new View will be added after it is bound to
* * an adapter position.
* *
* @param viewType The view type of the new View.
* *
* @return A new ViewHolder that holds a View of the given view type.
* *
* @see .getItemViewType
* @see .onBindViewHolder
*/
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.ui_list_lyrics_item, parent, false)
return ViewHolder(view)
}
/**
* Called by RecyclerView to display the data at the specified position. This method
* should update the contents of the [ViewHolder.itemView] to reflect the item at
* the given position.
*
*
* Note that unlike [android.widget.ListView], RecyclerView will not call this
* method again if the position of the item changes in the data set unless the item itself
* is invalidated or the new position cannot be determined. For this reason, you should only
* use the `position` parameter while acquiring the related data item inside this
* method and should not keep a copy of it. If you need the position of an item later on
* (e.g. in a click listener), use [ViewHolder.getPosition] which will have the
* updated position.
* @param holder The ViewHolder which should be updated to represent the contents of the
* * item at the given position in the data set.
* *
* @param position The position of the item within the adapter's data set.
*/
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val str = data[position]
holder.title.text = str
}
fun updateLyrics(lyrics: List<String>) {
this.data = lyrics
notifyDataSetChanged()
}
/**
* Returns the total number of items in the data set hold by the adapter.
* @return The total number of items in this adapter.
*/
override fun getItemCount(): Int {
return data.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
@BindView(android.R.id.text1)
lateinit var title: TextView
init {
ButterKnife.bind(this, itemView)
}
}
fun clear() {
if (data.isNotEmpty()) {
data = emptyList()
}
}
}
| gpl-3.0 | fc7dab0eeb3176622ebc8934bc206f8a | 32.642857 | 94 | 0.70913 | 4.309804 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/serializers/FarebotJsonFormat.kt | 1 | 9583 | /*
* FarebotJsonFormat.kt
*
* Copyright 2019 Google
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.serializers
import au.id.micolous.metrodroid.card.Card
import au.id.micolous.metrodroid.card.cepas.CEPASApplication
import au.id.micolous.metrodroid.card.classic.ClassicCard
import au.id.micolous.metrodroid.card.classic.ClassicSector
import au.id.micolous.metrodroid.card.classic.ClassicSectorRaw
import au.id.micolous.metrodroid.card.desfire.DesfireApplication
import au.id.micolous.metrodroid.card.desfire.DesfireCard
import au.id.micolous.metrodroid.card.desfire.files.RawDesfireFile
import au.id.micolous.metrodroid.card.felica.FelicaBlock
import au.id.micolous.metrodroid.card.felica.FelicaCard
import au.id.micolous.metrodroid.card.felica.FelicaService
import au.id.micolous.metrodroid.card.felica.FelicaSystem
import au.id.micolous.metrodroid.card.iso7816.ISO7816ApplicationCapsule
import au.id.micolous.metrodroid.card.iso7816.ISO7816Card
import au.id.micolous.metrodroid.card.ultralight.UltralightCard
import au.id.micolous.metrodroid.card.ultralight.UltralightPage
import au.id.micolous.metrodroid.time.MetroTimeZone
import au.id.micolous.metrodroid.time.TimestampFull
import au.id.micolous.metrodroid.util.ImmutableByteArray
import au.id.micolous.metrodroid.util.decodeBase64
import au.id.micolous.metrodroid.util.readToString
import kotlinx.io.InputStream
import kotlinx.serialization.*
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonConfiguration
import kotlinx.serialization.json.JsonElement
abstract class CardImporterString : CardImporter {
override fun readCard(stream: InputStream): Card? =
readCardList(stream.readToString()).firstOrNull()
override fun readCard(input: String): Card? =
readCardList(input).firstOrNull()
override fun readCards(stream: InputStream) =
readCardList(stream.readToString()).iterator()
override fun readCards(s: String): Iterator<Card> =
readCardList(s).iterator()
abstract fun readCardList(input: String): List<Card>
}
object FarebotJsonFormat : CardImporterString() {
override fun readCardList(input: String): List<Card> =
CardSerializer.jsonPlainStable.parse(FarebotCards.serializer(), input).convert()
fun readCards(input: JsonElement): List<Card> =
CardSerializer.jsonPlainStable.fromJson(FarebotCards.serializer(), input).convert()
}
object AutoJsonFormat : CardImporterString() {
override fun readCardList(input: String): List<Card> =
readCards(CardSerializer.jsonPlainStable.parseJson(input), input)
fun readCards(input: JsonElement, plain: String): List<Card> =
if (input.jsonObject.containsKey("cards") &&
!input.jsonObject.containsKey("scannedAt") &&
!input.jsonObject.containsKey("tagId"))
FarebotJsonFormat.readCards(input)
else
// Kotlin 1.3.40 has trouble parsing polymorphs in an abstract tree
listOf(JsonKotlinFormat.readCard(plain))
}
@Serializable
data class FarebotDataWrapper(val data: String)
@Serializable
data class FarebotDesfireError(val type: Int, val message: String)
@Serializable
data class FarebotDesfireFile(
val fileId: Int,
val fileSettings: FarebotDataWrapper,
val fileData: String? = null,
val error: FarebotDesfireError? = null) {
fun convert() = RawDesfireFile(
data = fileData?.let { ImmutableByteArray.fromBase64(it) },
settings = ImmutableByteArray.fromBase64(fileSettings.data),
error = error?.message, isUnauthorized = error?.type == 1)
}
@Serializable
data class FarebotDesfireApplication(
val appId: Int,
val files: List<FarebotDesfireFile>) {
fun convert() = DesfireApplication(files = files.map {it.fileId to it.convert() }.toMap())
}
@Serializable
data class FarebotUltralightPage(val index: Int, val data: String) {
fun convert() = UltralightPage(ImmutableByteArray.fromBase64(data))
}
@Serializable
data class FarebotClassicBlock(val index: Int, val data: String) {
fun convert() = ImmutableByteArray.fromBase64(data)
}
@Serializable
data class FarebotClassicSector(
val type: String,
val index: Int,
val blocks: List<FarebotClassicBlock>?,
val errorMessage: String? = null) {
fun convert() = ClassicSectorRaw(
blocks = blocks.orEmpty().sortedBy {it.index}.map { it.convert() },
error = when (type) {
"data" -> null
"unauthorized" -> "Unauthorized"
else -> errorMessage
},
isUnauthorized = type == "unauthorized"
)
}
@Serializable
data class FarebotFelicaBlock(
val address: Int,
val data: String
) {
fun convert() = FelicaBlock(ImmutableByteArray.fromBase64(data))
}
@Serializable
data class FarebotFelicaService(
val serviceCode: Int,
val blocks: List<FarebotFelicaBlock>
) {
fun convert() = FelicaService(blocks = blocks.sortedBy { it.address }.map { it.convert() })
}
@Serializable
data class FarebotFelicaSystem(
val code: Int,
val services: List<FarebotFelicaService>
) {
fun convert() = FelicaSystem(services = services.map {it.serviceCode to it.convert()}.toMap())
}
@Serializable
data class FarebotCepasPurse(
val id: Int,
val data: String? = null,
val errorMessage: String? = null
) {
fun convert() = ImmutableByteArray.fromBase64(data ?: "")
}
@Serializable
data class FarebotCepasHistory(
val id: Int,
val data: String? = null,
val errorMessage: String? = null
) {
fun convert() = ImmutableByteArray.fromBase64(data ?: "")
}
@Serializable
data class FarebotFelicaIdm(
val cardIdentification: List<Int>,
val manufactureCode: List<Int>
)
@Serializable
data class FarebotFelicaPmm(
val icCode: List<Int>,
val maximumResponseTime: List<Int>
)
@Serializable
data class FarebotCard(
// Common
val tagId: String, val scannedAt: Long, val cardType: String,
// Desfire
val manufacturingData: FarebotDataWrapper? = null,
val applications: List<FarebotDesfireApplication>? = null,
// Ultralight
val ultralightType: Int? = null,
val pages: List<FarebotUltralightPage>? = null,
// Classic
val sectors: List<FarebotClassicSector>? = null,
// Felica
val idm: FarebotFelicaIdm? = null,
val pmm: FarebotFelicaPmm? = null,
val systems: List<FarebotFelicaSystem>? = null,
// CEPAS
val purses: List<FarebotCepasPurse>? = null,
val histories: List<FarebotCepasHistory>? = null
) {
fun convertScannedAt() = TimestampFull(timeInMillis = scannedAt,
tz = MetroTimeZone.UNKNOWN)
fun convert() = when(cardType) {
"MifareDesfire" -> Card(
tagId = ImmutableByteArray.fromBase64(tagId),
scannedAt = convertScannedAt(),
mifareDesfire = DesfireCard(
manufacturingData = ImmutableByteArray.fromBase64(manufacturingData?.data ?: ""),
applications = applications.orEmpty().map { it.appId to it.convert() }.toMap())
)
"MifareUltralight" -> Card(
tagId = ImmutableByteArray.fromBase64(tagId),
scannedAt = convertScannedAt(),
mifareUltralight = UltralightCard(
pages = pages.orEmpty().sortedBy { it.index }.map { it.convert() })
)
"MifareClassic" -> Card(
tagId = ImmutableByteArray.fromBase64(tagId),
scannedAt = convertScannedAt(),
mifareClassic = ClassicCard(
sectors = sectors.orEmpty().sortedBy {it.index}.
map { ClassicSector.create(it.convert()) })
)
"FeliCa" -> Card(
tagId = ImmutableByteArray.fromBase64(tagId),
scannedAt = convertScannedAt(),
felica = FelicaCard(
// TODO: convert pMm
pMm = null,
systems = systems.orEmpty().map { it.code to it.convert() }.toMap())
)
"CEPAS" -> Card(
tagId = ImmutableByteArray.fromBase64(tagId),
scannedAt = convertScannedAt(),
iso7816 = ISO7816Card(
applications = listOf(CEPASApplication(
generic = ISO7816ApplicationCapsule(),
purses = purses.orEmpty().filter { it.data != null }.map { it.id to it.convert() }.toMap(),
histories = histories.orEmpty().filter { it.data != null }.map { it.id to it.convert() }.toMap()
))
)
)
else -> throw IllegalArgumentException("Unknown card $cardType")
}
}
@Serializable
class FarebotCards(val cards: List<FarebotCard>,
val versionCode: Int? = null,
val versionName: String? = null) {
fun convert() = cards.map { it.convert() }
}
| gpl-3.0 | 12997761a243eebd056b1aa7ce1d94d3 | 34.624535 | 120 | 0.678493 | 4.045167 | false | false | false | false |
android/nowinandroid | feature/settings/src/main/java/com/google/samples/apps/nowinandroid/feature/settings/SettingsViewModel.kt | 1 | 3312 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.feature.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.samples.apps.nowinandroid.core.data.repository.UserDataRepository
import com.google.samples.apps.nowinandroid.core.model.data.DarkThemeConfig
import com.google.samples.apps.nowinandroid.core.model.data.ThemeBrand
import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Loading
import com.google.samples.apps.nowinandroid.feature.settings.SettingsUiState.Success
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
@HiltViewModel
class SettingsViewModel @Inject constructor(
private val userDataRepository: UserDataRepository,
) : ViewModel() {
val settingsUiState: StateFlow<SettingsUiState> =
userDataRepository.userDataStream
.map { userData ->
Success(
settings = UserEditableSettings(
brand = userData.themeBrand,
darkThemeConfig = userData.darkThemeConfig
)
)
}
.stateIn(
scope = viewModelScope,
// Starting eagerly means the user data is ready when the SettingsDialog is laid out
// for the first time. Without this, due to b/221643630 the layout is done using the
// "Loading" text, then replaced with the user editable fields once loaded, however,
// the layout height doesn't change meaning all the fields are squashed into a small
// scrollable column.
// TODO: Change to SharingStarted.WhileSubscribed(5_000) when b/221643630 is fixed
started = SharingStarted.Eagerly,
initialValue = Loading
)
fun updateThemeBrand(themeBrand: ThemeBrand) {
viewModelScope.launch {
userDataRepository.setThemeBrand(themeBrand)
}
}
fun updateDarkThemeConfig(darkThemeConfig: DarkThemeConfig) {
viewModelScope.launch {
userDataRepository.setDarkThemeConfig(darkThemeConfig)
}
}
}
/**
* Represents the settings which the user can edit within the app.
*/
data class UserEditableSettings(val brand: ThemeBrand, val darkThemeConfig: DarkThemeConfig)
sealed interface SettingsUiState {
object Loading : SettingsUiState
data class Success(val settings: UserEditableSettings) : SettingsUiState
}
| apache-2.0 | 869004e8fb36507b58c5667eccbe5e6e | 39.888889 | 100 | 0.710447 | 4.856305 | false | true | false | false |
Mystery00/JanYoShare | app/src/main/java/com/janyo/janyoshare/handler/ErrorHandler.kt | 1 | 1107 | package com.janyo.janyoshare.handler
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.os.Message
import android.widget.Toast
import com.janyo.janyoshare.R
import com.janyo.janyoshare.service.ReceiveFileService
import com.janyo.janyoshare.service.SendFileService
class ErrorHandler(private var context: Context) : Handler()
{
override fun handleMessage(msg: Message)
{
when (msg.what)
{
UNKNOWN_ERROR -> Toast.makeText(context, R.string.hint_transfer_file_unknown_error, Toast.LENGTH_SHORT)
.show()
FILE_EXISTS -> Toast.makeText(context, R.string.hint_transfer_file_exists, Toast.LENGTH_SHORT)
.show()
FILE_NOT_EXISTS -> Toast.makeText(context, R.string.hint_transfer_file_not_exists, Toast.LENGTH_SHORT)
.show()
}
val sendIntent = Intent(context, SendFileService::class.java)
val receiveIntent = Intent(context, ReceiveFileService::class.java)
context.stopService(sendIntent)
context.stopService(receiveIntent)
}
companion object
{
val UNKNOWN_ERROR = 0
val FILE_EXISTS = 1
val FILE_NOT_EXISTS = 2
}
} | gpl-3.0 | 991bf43274479497db4a81fcc919fbbc | 28.945946 | 106 | 0.762421 | 3.448598 | false | false | false | false |
aedans/Quartz | compiler/src/main/kotlin/io/quartz/analyze/type/Subst.kt | 1 | 1073 | package io.quartz.analyze.type
import io.quartz.env.*
import io.quartz.tree.ir.*
import io.quartz.tree.util.Name
typealias Subst = Map<Name, TypeI>
val emptySubst: Subst = emptyMap()
infix fun <A, B> Map<A, B>.union(map: Map<A, B>) = map + this
infix fun Subst.compose(subst: Subst): Subst = (subst union this).mapValues { apply(it.value, this) }
fun apply(scheme: SchemeI, subst: Subst): SchemeI = run {
val substP = scheme.foralls.fold(subst) { a, b -> a - b }
SchemeI(scheme.foralls, scheme.constraints, apply(scheme.type, substP))
}
fun apply(type: TypeI, subst: Subst): TypeI = when (type) {
is TypeI.Const -> type
is TypeI.Var -> subst.getOrDefault(type.name, type)
is TypeI.Apply -> TypeI.Apply(apply(type.t1, subst), apply(type.t2, subst))
}
fun apply(env: Env, subst: Subst): Env = env.mapTypes { _, it ->
it?.map { apply(it, subst) }
}
val TypeI.freeTypeVariables: Set<Name> get() = when (this) {
is TypeI.Const -> emptySet()
is TypeI.Var -> setOf(name)
is TypeI.Apply -> t1.freeTypeVariables + t2.freeTypeVariables
}
| mit | f2be78233335827af2556a16802dfd91 | 30.558824 | 101 | 0.67288 | 2.892183 | false | false | false | false |
himikof/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsDocAndAttributeOwner.kt | 1 | 3387 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.psi.NavigatablePsiElement
import org.rust.lang.core.psi.RsAttr
import org.rust.lang.core.psi.RsInnerAttr
import org.rust.lang.core.psi.RsMetaItem
import org.rust.lang.core.psi.RsOuterAttr
interface RsDocAndAttributeOwner : RsCompositeElement, NavigatablePsiElement
interface RsInnerAttributeOwner : RsDocAndAttributeOwner {
/**
* Outer attributes are always children of the owning node.
* In contrast, inner attributes can be either direct
* children or grandchildren.
*/
val innerAttrList: List<RsInnerAttr>
}
/**
* An element with attached outer attributes and documentation comments.
* Such elements should use left edge binder to properly wrap preceding comments.
*
* Fun fact: in Rust, documentation comments are a syntactic sugar for attribute syntax.
*
* ```
* /// docs
* fn foo() {}
* ```
*
* is equivalent to
*
* ```
* #[doc="docs"]
* fn foo() {}
* ```
*/
interface RsOuterAttributeOwner : RsDocAndAttributeOwner {
val outerAttrList: List<RsOuterAttr>
}
/**
* Find the first outer attribute with the given identifier.
*/
fun RsOuterAttributeOwner.findOuterAttr(name: String): RsOuterAttr? =
outerAttrList.find { it.metaItem.referenceName == name }
/**
* Get sequence of all item's inner and outer attributes.
* Inner attributes take precedence, so they must go first.
*/
val RsDocAndAttributeOwner.allAttributes: Sequence<RsAttr>
get() = Sequence { (this as? RsInnerAttributeOwner)?.innerAttrList.orEmpty().iterator() } +
Sequence { (this as? RsOuterAttributeOwner)?.outerAttrList.orEmpty().iterator() }
/**
* Returns [QueryAttributes] for given PSI element.
*/
val RsDocAndAttributeOwner.queryAttributes: QueryAttributes
get() = QueryAttributes(allAttributes)
/**
* Allows for easy querying [RsDocAndAttributeOwner] for specific attributes.
*
* **Do not instantiate directly**, use [RsDocAndAttributeOwner.queryAttributes] instead.
*/
class QueryAttributes(private val attributes: Sequence<RsAttr>) {
fun hasCfgAttr(): Boolean = hasAttribute("cfg")
fun hasAttribute(attributeName: String) = metaItems.any { it.referenceName == attributeName }
fun hasAtomAttribute(attributeName: String): Boolean {
val attr = attrByName(attributeName)
return attr != null && (!attr.hasEq && attr.metaItemArgs == null)
}
fun hasAttributeWithArg(attributeName: String, arg: String): Boolean {
val attr = attrByName(attributeName) ?: return false
val args = attr.metaItemArgs ?: return false
return args.metaItemList.any { it.referenceName == arg }
}
fun lookupStringValueForKey(key: String): String? =
metaItems
.filter { it.referenceName == key }
.mapNotNull { it.value }
.singleOrNull()
val langAttribute: String?
get() = getStringAttribute("lang")
val deriveAttribute: RsMetaItem?
get() = attrByName("derive")
fun getStringAttribute(attributeName: String): String? = attrByName(attributeName)?.value
val metaItems: Sequence<RsMetaItem>
get() = attributes.mapNotNull { it.metaItem }
private fun attrByName(name: String) = metaItems.find { it.referenceName == name }
}
| mit | 3fb5b01707354e452b4c7781af2069d3 | 30.361111 | 97 | 0.705639 | 4.120438 | false | false | false | false |
pdvrieze/kotlinsql | sql/src/generators/kotlin/kotlinsql/builder/generate_statements.kt | 1 | 5591 | /*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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.
*/
/**
* Created by pdvrieze on 04/04/16.
*/
package kotlinsql.builder
import java.io.Writer
@Suppress("unused")
class GenerateStatementsKt {
fun doGenerate(output: Writer, input: Any) {
val count = input as Int
output.apply {
appendCopyright()
appendLine()
appendLine("package io.github.pdvrieze.kotlinsql.dml.impl")
appendLine()
appendLine("import io.github.pdvrieze.kotlinsql.ddl.Column")
appendLine("import io.github.pdvrieze.kotlinsql.ddl.IColumnType")
appendLine("import io.github.pdvrieze.kotlinsql.dml.Select1")
appendLine("import io.github.pdvrieze.kotlinsql.dml.WhereClause")
appendLine("import java.sql.SQLException")
for (n in 1..count) {
appendLine()
append("class _Statement$n<")
(1..n).joinToString(",\n ") { m -> "T$m:Any, S$m:IColumnType<T$m,S$m,C$m>, C$m: Column<T$m, S$m, C$m>" }
.apply { append(this) }
append(">(${if (n == 1) "" else "override val "}select:_Select$n<")
(1..n).joinTo(this, ",") { m -> "T$m,S$m,C$m" }
appendLine(">, where:WhereClause):")
append(" ")
when (n) {
1 -> appendLine("_Statement1Base<T1,S1,C1>(select,where),")
else -> appendLine("_StatementBase(where),")
}
append(" Select$n<")
(1..n).joinTo(this, ",") { m -> "T$m,S$m,C$m" }
appendLine("> {")
if (n > 1) {
appendLine()
append(" data class Result<")
(1..n).joinTo(this) { "out T$it" }
append(">(")
(1..n).joinTo(this) { "val col$it:T$it?" }
appendLine(")")
}
/*
appendLine()
append(" override fun execute(connection:MonadicDBConnection<*>, block: (")
(1..n).joinToString(",") { m -> "T$m?" }.apply { append(this) }
appendLine(")->Unit):Boolean {")
appendLine(" return executeHelper(connection, block) { rs, block2 ->")
append(" block2(")
(1..n).joinToString(",\n${" ".repeat(13)}") { m -> "select.col$m.type.fromResultSet(rs, $m)" }
.apply { append(this) }
// if (n==1) {
// append("select.col1.type.fromResultSet(rs, 1)")
// } else {
// }
appendLine(')')
appendLine(" }")
appendLine(" }")
if (n > 1) {
appendLine()
appendLine(" @NonMonadicApi")
append(" override fun getSingle(connection:MonadicDBConnection<*>)")
append(" = getSingle(connection) { ")
(1..n).joinTo(this, ",") { "p$it" }
append(" -> Result(")
(1..n).joinTo(this, ",") { "p$it" }
appendLine(")}")
appendLine()
appendLine(" @NonMonadicApi")
append(" override fun <R> getSingle(connection:MonadicDBConnection<*>, factory:")
appendFactorySignature(n)
appendLine("):R? {")
appendLine(" return connection.prepareStatement(toSQL()) {")
appendLine(" setParams(this)")
appendLine(" execute { rs ->")
appendLine(" if (rs.next()) {")
appendLine(" if (!rs.isLast) throw SQLException(\"Multiple results found, where only one or none expected\")")
append(" factory(")
(1..n).joinTo(this, ",\n${" ".repeat(18)}") { m -> "select.col$m.type.fromResultSet(rs, $m)" }
appendLine(")")
appendLine(" } else null ")
appendLine(" }")
appendLine(" }")
appendLine(" }")
}
appendLine()
if (n == 1) {
appendLine(" override fun getList(connection: MonadicDBConnection<*>): List<T1?> {")
appendLine(" val result=mutableListOf<T1?>()")
append(" execute(connection) { ")
(1..n).joinToString { "p$it" }.apply { append(this) }
append(" -> result.add(")
(1..n).joinToString { "p$it" }.apply { append(this) }
appendLine(") }")
} else {
append(" override fun <R> getList(connection: MonadicDBConnection<*>, factory:")
appendFactorySignature(n)
appendLine("): List<R> {")
appendLine(" val result=mutableListOf<R>()")
append(" execute(connection) { ")
(1..n).joinToString { "p$it" }.apply { append(this) }
append(" -> result.add(factory(")
(1..n).joinToString { "p$it" }.apply { append(this) }
appendLine(")) }")
}
appendLine(" return result")
appendLine(" }")
*/
appendLine()
appendLine("}")
}
}
}
}
internal fun Appendable.appendFactorySignature(n: Int) {
append("(")
(1..n).joinToString(",") { "T$it?" }.apply { append(this) }
append(")->R")
}
| apache-2.0 | 9c91eb0a90bf0d5908edbe3da2298ee6 | 35.070968 | 129 | 0.540869 | 3.929023 | false | false | false | false |
AsamK/TextSecure | qr/lib/src/main/java/org/signal/qr/QrProcessor.kt | 1 | 2121 | package org.signal.qr
import androidx.camera.core.ImageProxy
import com.google.zxing.BinaryBitmap
import com.google.zxing.ChecksumException
import com.google.zxing.DecodeHintType
import com.google.zxing.FormatException
import com.google.zxing.LuminanceSource
import com.google.zxing.NotFoundException
import com.google.zxing.PlanarYUVLuminanceSource
import com.google.zxing.Result
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.qrcode.QRCodeReader
import org.signal.core.util.logging.Log
/**
* Wraps [QRCodeReader] for use from API19 or API21+.
*/
class QrProcessor {
private val reader = QRCodeReader()
private var previousHeight = 0
private var previousWidth = 0
fun getScannedData(proxy: ImageProxy): String? {
return getScannedData(ImageProxyLuminanceSource(proxy))
}
fun getScannedData(
data: ByteArray,
width: Int,
height: Int
): String? {
return getScannedData(PlanarYUVLuminanceSource(data, width, height, 0, 0, width, height, false))
}
private fun getScannedData(source: LuminanceSource): String? {
try {
if (source.width != previousWidth || source.height != previousHeight) {
Log.i(TAG, "Processing ${source.width} x ${source.height} image")
previousWidth = source.width
previousHeight = source.height
}
val bitmap = BinaryBitmap(HybridBinarizer(source))
val result: Result? = reader.decode(bitmap, mapOf(DecodeHintType.TRY_HARDER to true, DecodeHintType.CHARACTER_SET to "ISO-8859-1"))
if (result != null) {
return result.text
}
} catch (e: NullPointerException) {
Log.w(TAG, "Random null", e)
} catch (e: ChecksumException) {
Log.w(TAG, "QR code read and decoded, but checksum failed", e)
} catch (e: FormatException) {
Log.w(TAG, "Thrown when a barcode was successfully detected, but some aspect of the content did not conform to the barcodes format rules.", e)
} catch (e: NotFoundException) {
// Thanks ZXing...
}
return null
}
companion object {
private val TAG = Log.tag(QrProcessor::class.java)
}
}
| gpl-3.0 | 96c6286abb75663cc07d29ca6930680c | 30.656716 | 148 | 0.7124 | 3.807899 | false | false | false | false |
ktorio/ktor | ktor-io/common/test/io/ktor/utils/io/VerifyingPoolBase.kt | 1 | 1477 | package io.ktor.utils.io
import io.ktor.utils.io.pool.*
import kotlin.test.*
internal expect fun identityHashCode(instance: Any): Int
expect class VerifyingObjectPool<T : Any>(delegate: ObjectPool<T>) : VerifyingPoolBase<T>
abstract class VerifyingPoolBase<T : Any> constructor(private val delegate: ObjectPool<T>) : ObjectPool<T> by delegate {
protected abstract val allocated: MutableSet<IdentityWrapper<T>>
val used: Int
get() = allocated.size
final override fun borrow(): T {
val instance = delegate.borrow()
if (!allocated.add(IdentityWrapper(instance))) {
throw AssertionError("Instance $instance has been provided by the pool twice")
}
return instance
}
final override fun recycle(instance: T) {
if (!allocated.remove(IdentityWrapper(instance))) {
throw AssertionError(
"Instance $instance hasn't been borrowed but tried to recycle (possibly double recycle)"
)
}
delegate.recycle(instance)
}
fun assertEmpty() {
assertEquals(0, allocated.size, "There are remaining unreleased buffers, ")
}
protected class IdentityWrapper<T : Any>(private val instance: T) {
override fun equals(other: Any?): Boolean {
if (other !is IdentityWrapper<*>) return false
return other.instance === this.instance
}
override fun hashCode() = identityHashCode(instance)
}
}
| apache-2.0 | c436f0d197115597b7c6193e6a0dce2b | 31.822222 | 120 | 0.655383 | 4.530675 | false | false | false | false |
roylanceMichael/yaclib | core/src/main/java/org/roylance/yaclib/core/services/java/server/JettyGradleBuilder.kt | 1 | 4266 | package org.roylance.yaclib.core.services.java.server
import org.roylance.common.service.IBuilder
import org.roylance.yaclib.YaclibModel
import org.roylance.yaclib.core.enums.CommonTokens
import org.roylance.yaclib.core.utilities.GradleUtilities
import org.roylance.yaclib.core.utilities.JavaUtilities
class JettyGradleBuilder(
private val projectInformation: YaclibModel.ProjectInformation) : IBuilder<YaclibModel.File> {
private val InitialTemplate = """${CommonTokens.AutoGeneratedAlteringOkay}
import org.roylance.yaclib.YaclibPackageTask;
buildscript {
ext.kotlin_version = "$${JavaUtilities.KotlinName}"
repositories {
jcenter()
mavenCentral()
maven { url '${JavaUtilities.DefaultRepository}'}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$${JavaUtilities.KotlinName}"
classpath "org.roylance:yaclib.core:$${JavaUtilities.YaclibVersionName}"
}
}
group "$${JavaUtilities.GroupName}"
version "$${JavaUtilities.MajorName}.$${JavaUtilities.MinorName}"
apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'application'
sourceCompatibility = 1.8
mainClassName="${projectInformation.mainDependency.group}.Main"
repositories {
mavenCentral()
maven { url '${JavaUtilities.DefaultRepository}'}
${GradleUtilities.buildRepository(projectInformation.mainDependency.mavenRepository)}
}
sourceSets {
main {
java.srcDirs = ['src/main/java',
'../${projectInformation.mainDependency.name}/src/main/java',
'../${projectInformation.mainDependency.name}client/src/main/java']
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '${YaclibStatics.JUnitVersion}'
compile "org.eclipse.jetty:jetty-server:$${JavaUtilities.JettyServerName}"
compile "org.eclipse.jetty:jetty-servlet:$${JavaUtilities.JettyServerName}"
compile "org.eclipse.jetty:jetty-webapp:$${JavaUtilities.JettyServerName}"
compile "org.glassfish.jersey.core:jersey-server:$${JavaUtilities.JerseyMediaName}"
compile "org.glassfish.jersey.containers:jersey-container-servlet-core:$${JavaUtilities.JerseyMediaName}"
compile "org.glassfish.jersey.containers:jersey-container-servlet:$${JavaUtilities.JerseyMediaName}"
compile "org.glassfish.jersey.media:jersey-media-multipart:$${JavaUtilities.JerseyMediaName}"
compile "org.apache.httpcomponents:httpclient:$${JavaUtilities.HttpComponentsName}"
compile "com.squareup.retrofit2:retrofit:${'$'}${JavaUtilities.RetrofitName}"
compile "org.roylance:roylance.common:${'$'}${'{'}YaclibStatics.RoylanceCommonVersion${'}'}"
${buildDependencies()}
}
task packageApp(type: YaclibPackageTask) {
appName = rootProject.name
serverVersion = "$${JavaUtilities.MajorName}.$${JavaUtilities.MinorName}"
maintainerInfo = "${projectInformation.mainDependency.authorName}"
serverPort = "$${JavaUtilities.ServerPortName}".toInteger()
}
packageApp.dependsOn(installDist)
"""
override fun build(): YaclibModel.File {
val returnFile = YaclibModel.File.newBuilder()
.setFileToWrite(InitialTemplate.trim())
.setFileExtension(YaclibModel.FileExtension.GRADLE_EXT)
.setFileName("build")
.setFullDirectoryLocation("")
.setFileUpdateType(YaclibModel.FileUpdateType.WRITE_IF_NOT_EXISTS)
.build()
return returnFile
}
private fun buildDependencies(): String {
val workspace = StringBuilder()
projectInformation.thirdPartyDependenciesList
.filter { it.type == YaclibModel.DependencyType.JAVA }
.forEach { dependency ->
workspace.append(
""" compile "${dependency.group}:${dependency.name}:$${JavaUtilities.buildPackageVariableName(
dependency)}"
""")
}
// todo: verify we don't need this
// projectInformation.controllers.controllerDependenciesList.forEach { controllerDependency ->
// workspace.append(
// """ compile "${controllerDependency.dependency.group}:${controllerDependency.dependency.name}${CommonTokens.ClientSuffix}:$${JavaUtilities.buildPackageVariableName(
// controllerDependency.dependency)}"
//""")
// }
return workspace.toString()
}
} | mit | e250136a9bb4923d3dfb7921c30baca3 | 36.104348 | 179 | 0.723394 | 4.495258 | false | false | false | false |
ktorio/ktor | ktor-io/common/src/io/ktor/utils/io/bits/MemoryPrimitives.kt | 1 | 5425 | @file:Suppress("NOTHING_TO_INLINE")
package io.ktor.utils.io.bits
/**
* Read short signed 16bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadShortAt(offset: Int): Short
/**
* Read short signed 16bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadShortAt(offset: Long): Short
/**
* Write short signed 16bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeShortAt(offset: Int, value: Short)
/**
* Write short signed 16bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeShortAt(offset: Long, value: Short)
/**
* Read short unsigned 16bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.loadUShortAt(offset: Int): UShort = loadShortAt(offset).toUShort()
/**
* Read short unsigned 16bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.loadUShortAt(offset: Long): UShort = loadShortAt(offset).toUShort()
/**
* Write short unsigned 16bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.storeUShortAt(offset: Int, value: UShort): Unit = storeShortAt(offset, value.toShort())
/**
* Write short unsigned 16bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.storeUShortAt(offset: Long, value: UShort): Unit = storeShortAt(offset, value.toShort())
/**
* Read regular signed 32bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadIntAt(offset: Int): Int
/**
* Read regular signed 32bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadIntAt(offset: Long): Int
/**
* Write regular signed 32bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeIntAt(offset: Int, value: Int)
/**
* Write regular signed 32bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeIntAt(offset: Long, value: Int)
/**
* Read regular unsigned 32bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.loadUIntAt(offset: Int): UInt = loadIntAt(offset).toUInt()
/**
* Read regular unsigned 32bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.loadUIntAt(offset: Long): UInt = loadIntAt(offset).toUInt()
/**
* Write regular unsigned 32bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.storeUIntAt(offset: Int, value: UInt): Unit = storeIntAt(offset, value.toInt())
/**
* Write regular unsigned 32bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.storeUIntAt(offset: Long, value: UInt): Unit = storeIntAt(offset, value.toInt())
/**
* Read short signed 64bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadLongAt(offset: Int): Long
/**
* Read short signed 64bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadLongAt(offset: Long): Long
/**
* Write short signed 64bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeLongAt(offset: Int, value: Long)
/**
* write short signed 64bit integer in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeLongAt(offset: Long, value: Long)
/**
* Read short signed 64bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.loadULongAt(offset: Int): ULong = loadLongAt(offset).toULong()
/**
* Read short signed 64bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.loadULongAt(offset: Long): ULong = loadLongAt(offset).toULong()
/**
* Write short signed 64bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.storeULongAt(offset: Int, value: ULong): Unit = storeLongAt(offset, value.toLong())
/**
* Write short signed 64bit integer in the network byte order (Big Endian)
*/
public inline fun Memory.storeULongAt(offset: Long, value: ULong): Unit = storeLongAt(offset, value.toLong())
/**
* Read short signed 32bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadFloatAt(offset: Int): Float
/**
* Read short signed 32bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadFloatAt(offset: Long): Float
/**
* Write short signed 32bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeFloatAt(offset: Int, value: Float)
/**
* Write short signed 32bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeFloatAt(offset: Long, value: Float)
/**
* Read short signed 64bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadDoubleAt(offset: Int): Double
/**
* Read short signed 64bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.loadDoubleAt(offset: Long): Double
/**
* Write short signed 64bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeDoubleAt(offset: Int, value: Double)
/**
* Write short signed 64bit floating point number in the network byte order (Big Endian)
*/
public expect inline fun Memory.storeDoubleAt(offset: Long, value: Double)
| apache-2.0 | 6e548b58d3635d70cb6ba90225936ccf | 32.282209 | 113 | 0.744147 | 3.825811 | false | false | false | false |
RayBa82/DVBViewerController | dvbViewerController/src/main/java/org/dvbviewer/controller/ui/base/AbstractRemote.kt | 1 | 1884 | /*
* Copyright © 2013 dvbviewer-controller 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 org.dvbviewer.controller.ui.base
import android.content.Context
import android.view.View
import android.view.View.OnClickListener
import androidx.fragment.app.Fragment
/**
* The Class Remote.
*
* @author RayBa
* @date 07.04.2013
*/
abstract class AbstractRemote : Fragment(), OnClickListener {
protected var remoteButtonClickListener: OnRemoteButtonClickListener? = null
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is OnRemoteButtonClickListener) {
remoteButtonClickListener = context
} else if (parentFragment is OnRemoteButtonClickListener) {
remoteButtonClickListener = parentFragment as OnRemoteButtonClickListener?
}
}
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
override fun onClick(v: View) {
val command = getCommand(v)
if (remoteButtonClickListener != null) {
remoteButtonClickListener!!.OnRemoteButtonClick(command)
}
}
abstract fun getCommand(v: View): String
// Container Activity or Fragment must implement this interface
interface OnRemoteButtonClickListener {
fun OnRemoteButtonClick(action: String)
}
}
| apache-2.0 | 6f8f906924a425742f03bd44db1d1f24 | 29.868852 | 86 | 0.715879 | 4.637931 | false | false | false | false |
meik99/CoffeeList | app/src/main/java/rynkbit/tk/coffeelist/ui/admin/customer/ManageCustomerAdapter.kt | 1 | 3254 | package rynkbit.tk.coffeelist.ui.admin.customer
import android.text.Editable
import android.text.TextWatcher
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 androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.RecyclerView
import rynkbit.tk.coffeelist.R
import rynkbit.tk.coffeelist.contract.entity.Customer
import rynkbit.tk.coffeelist.ui.entity.UICustomer
import java.text.NumberFormat
import java.util.*
class ManageCustomerAdapter() : RecyclerView.Adapter<ManageCustomerAdapter.ViewHolder>() {
private val customers: MutableList<UICustomer> = mutableListOf()
var onRemoveCustomer: ((customer: UICustomer) -> Unit)? = null
var onClearBalance: ((customer: UICustomer) -> Unit)? = null
var onUpdateCustomer: ((customer: UICustomer) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val viewHolder = ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.edit_customer, parent, false)
)
return viewHolder
}
override fun getItemCount(): Int = customers.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val customer = customers[position]
holder.apply {
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
println(s)
onUpdateCustomer?.apply {
this(UICustomer(customer.id, s.toString(), customer.balance))
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
}
txtCustomerId.text = customer.id.toString()
txtCustomerBalance.text = NumberFormat
.getCurrencyInstance(Locale.getDefault())
.format(customer.balance)
editCustomerName.setText(customer.name)
editCustomerName.addTextChangedListener(textWatcher)
btnRemoveCustomer.setOnClickListener {
onRemoveCustomer?.apply { this(customer) }
}
btnClearBalance.setOnClickListener {
onClearBalance?.apply { this(customer) }
}
}
}
fun updateCustomers(customerList: List<UICustomer>) {
customers.clear()
customers.addAll(customerList)
notifyDataSetChanged()
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txtCustomerId: TextView = itemView.findViewById(R.id.txtCustomerId)
val txtCustomerBalance: TextView = itemView.findViewById(R.id.txtCustomerBalance)
val editCustomerName: EditText = itemView.findViewById(R.id.editCustomerName)
val btnRemoveCustomer: Button = itemView.findViewById(R.id.btnRemoveCustomer)
val btnClearBalance: Button = itemView.findViewById(R.id.btnClearBalance)
}
} | mit | 32410db9fa62b0ae5a541e94e43ac74e | 37.294118 | 102 | 0.664106 | 4.900602 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/test/java/org/hisp/dhis/android/core/event/EventServiceShould.kt | 1 | 7399 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.event
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.whenever
import org.hisp.dhis.android.core.arch.helpers.AccessHelper
import org.hisp.dhis.android.core.category.CategoryOptionComboService
import org.hisp.dhis.android.core.common.BaseIdentifiableObject
import org.hisp.dhis.android.core.enrollment.Enrollment
import org.hisp.dhis.android.core.enrollment.EnrollmentCollectionRepository
import org.hisp.dhis.android.core.enrollment.internal.EnrollmentServiceImpl
import org.hisp.dhis.android.core.event.internal.EventDateUtils
import org.hisp.dhis.android.core.event.internal.EventServiceImpl
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitService
import org.hisp.dhis.android.core.program.Program
import org.hisp.dhis.android.core.program.ProgramCollectionRepository
import org.hisp.dhis.android.core.program.ProgramStage
import org.hisp.dhis.android.core.program.ProgramStageCollectionRepository
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito
class EventServiceShould {
private val eventUid: String = "eventUid"
private val attributeOptionComboUid = "attOptionComboUid"
private val readDataAccess = AccessHelper.createForDataWrite(false)
private val writeDataAccess = AccessHelper.createForDataWrite(true)
private val enrollment: Enrollment = mock()
private val event: Event = mock()
private val program: Program = mock()
private val programStage: ProgramStage = mock()
private val enrollmentRepository: EnrollmentCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val eventRepository: EventCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programRepository: ProgramCollectionRepository = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val programStageRepository: ProgramStageCollectionRepository =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val enrollmentService: EnrollmentServiceImpl = mock()
private val organisationUnitService: OrganisationUnitService = mock()
private val categoryOptionComboService: CategoryOptionComboService =
mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS)
private val eventDateUtils: EventDateUtils = mock()
private val eventService: EventService = EventServiceImpl(
enrollmentRepository, eventRepository, programRepository, programStageRepository,
enrollmentService, organisationUnitService, categoryOptionComboService, eventDateUtils
)
private val firstJanuary = BaseIdentifiableObject.DATE_FORMAT.parse("2020-01-01T00:00:00.000")
@Before
fun setUp() {
whenever(eventRepository.uid(any()).blockingGet()) doReturn event
whenever(enrollmentRepository.uid(any()).blockingGet()) doReturn enrollment
whenever(programRepository.uid(any()).blockingGet()) doReturn program
whenever(programStageRepository.uid(any()).blockingGet()) doReturn programStage
whenever(event.uid()) doReturn eventUid
whenever(event.eventDate()) doReturn firstJanuary
}
@Test
fun `Should return true if program and program stage have write access`() {
whenever(program.access()) doReturn writeDataAccess
whenever(programStage.access()) doReturn writeDataAccess
assertTrue(eventService.blockingHasDataWriteAccess(event.uid()))
}
@Test
fun `Should return false if program stage has not write access`() {
whenever(program.access()) doReturn writeDataAccess
whenever(programStage.access()) doReturn readDataAccess
assertFalse(eventService.blockingHasDataWriteAccess(event.uid()))
}
@Test
fun `Should return true if programStage has write access and program has not write access`() {
whenever(program.access()) doReturn readDataAccess
whenever(programStage.access()) doReturn writeDataAccess
assertTrue(eventService.blockingHasDataWriteAccess(event.uid()))
}
@Test
fun `Should return true if has access to categoryCombo or attribute option combo is null`() {
whenever(event.attributeOptionCombo()) doReturn attributeOptionComboUid
whenever(categoryOptionComboService.blockingHasAccess(attributeOptionComboUid, firstJanuary)) doReturn true
assertTrue(eventService.blockingHasCategoryComboAccess(event))
whenever(event.attributeOptionCombo()) doReturn null
whenever(categoryOptionComboService.blockingHasAccess(attributeOptionComboUid, firstJanuary)) doReturn false
assertTrue(eventService.blockingHasCategoryComboAccess(event))
}
@Test
fun `Should return false if has not access to categoryCombo`() {
whenever(event.attributeOptionCombo()) doReturn attributeOptionComboUid
whenever(categoryOptionComboService.blockingHasAccess(attributeOptionComboUid, firstJanuary)) doReturn false
assertFalse(eventService.blockingHasCategoryComboAccess(event))
}
@Test
fun `Should return no data write access edition status`() {
whenever(event.attributeOptionCombo()) doReturn attributeOptionComboUid
whenever(categoryOptionComboService.blockingHasAccess(attributeOptionComboUid, firstJanuary)) doReturn false
val status = eventService.blockingGetEditableStatus(event.uid())
assertThat(status is EventEditableStatus.NonEditable).isTrue()
assertThat((status as EventEditableStatus.NonEditable).reason)
.isEquivalentAccordingToCompareTo(EventNonEditableReason.NO_DATA_WRITE_ACCESS)
}
}
| bsd-3-clause | 489e7bb4e06aaaa08b94d6a04d3bca77 | 48.993243 | 119 | 0.779024 | 5.012873 | false | false | false | false |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/fileresource/FileResourceRoutine.kt | 1 | 5724 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.fileresource
import dagger.Reusable
import io.reactivex.Completable
import java.io.File
import java.util.Calendar
import java.util.Date
import javax.inject.Inject
import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableDataObjectStore
import org.hisp.dhis.android.core.common.ValueType
import org.hisp.dhis.android.core.dataelement.DataElement
import org.hisp.dhis.android.core.dataelement.DataElementCollectionRepository
import org.hisp.dhis.android.core.datavalue.DataValue
import org.hisp.dhis.android.core.datavalue.DataValueCollectionRepository
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeCollectionRepository
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValue
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValueCollectionRepository
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValue
import org.hisp.dhis.android.core.trackedentity.TrackedEntityDataValueCollectionRepository
@Reusable
internal class FileResourceRoutine @Inject constructor(
private val dataValueCollectionRepository: DataValueCollectionRepository,
private val dataElementCollectionRepository: DataElementCollectionRepository,
private val fileResourceCollectionRepository: FileResourceCollectionRepository,
private val trackedEntityAttributeCollectionRepository: TrackedEntityAttributeCollectionRepository,
private val trackedEntityDataValueCollectionRepository: TrackedEntityDataValueCollectionRepository,
private val fileResourceStore: IdentifiableDataObjectStore<FileResource>,
private val trackedEntityAttributeValueCollectionRepository: TrackedEntityAttributeValueCollectionRepository
) {
fun deleteOutdatedFileResources(after: Date? = null): Completable {
return Completable.fromCallable {
blockingDeleteOutdatedFileResources(after)
}
}
@SuppressWarnings("MagicNumber")
fun blockingDeleteOutdatedFileResources(after: Date? = null) {
val dataElementsUids = dataElementCollectionRepository
.byValueType().`in`(ValueType.FILE_RESOURCE, ValueType.IMAGE)
.blockingGet().map(DataElement::uid)
val trackedEntityAttributesUids = trackedEntityAttributeCollectionRepository
.byValueType().`in`(ValueType.FILE_RESOURCE, ValueType.IMAGE)
.blockingGet().map(TrackedEntityAttribute::uid)
val trackedEntityDataValues = trackedEntityDataValueCollectionRepository
.byDataElement().`in`(dataElementsUids)
.blockingGet()
val trackedEntityAttributeValues = trackedEntityAttributeValueCollectionRepository
.byTrackedEntityAttribute().`in`(trackedEntityAttributesUids)
.blockingGet()
val dataValues = dataValueCollectionRepository
.byDataElementUid().`in`(dataElementsUids)
.blockingGet()
val fileResourceUids = dataValues.map(DataValue::value) +
trackedEntityAttributeValues.map(TrackedEntityAttributeValue::value) +
trackedEntityDataValues.map(TrackedEntityDataValue::value)
val calendar = Calendar.getInstance().apply {
add(Calendar.HOUR_OF_DAY, -2)
}
val fileResources = fileResourceCollectionRepository
.byUid().notIn(fileResourceUids)
.byDomain().eq(FileResourceDomain.DATA_VALUE)
.byLastUpdated().before(after ?: calendar.time)
.blockingGet()
blockingDeleteFileResources(fileResources)
}
private fun blockingDeleteFileResources(fileResources: List<FileResource>) {
fileResources.forEach { fileResource ->
fileResource.uid()?.let { uid ->
fileResourceStore.deleteIfExists(uid)
fileResource.path()?.let { path ->
deleteFile(path)
}
}
}
}
private fun deleteFile(path: String) {
runCatching {
val file = File(path)
file.delete()
}
}
}
| bsd-3-clause | b3728638b9b76ac861488e6ad4464feb | 46.305785 | 112 | 0.752096 | 5.309833 | false | false | false | false |
Reacto-Rx/reactorx-core | library/src/test/java/org/reactorx/util/TestTranslator.kt | 1 | 640 | package org.reactorx.util
import cz.filipproch.reactor.base.translator.ReactorTranslator
import cz.filipproch.reactor.base.view.UiEvent
/**
* @author Filip Prochazka (@filipproch)
*/
class TestTranslator : ReactorTranslator() {
var onCreatedCalled = false
var onDestroyedCalled = false
val receivedEvents = mutableListOf<UiEvent>()
override fun onCreated() {
onCreatedCalled = true
reactTo {
subscribe {
receivedEvents.add(it)
}
}
}
override fun onBeforeDestroyed() {
super.onBeforeDestroyed()
onDestroyedCalled = true
}
} | mit | 5f246964aa0acebf8bf8f5d11613d064 | 19.677419 | 62 | 0.646875 | 4.740741 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/bst_level_order_traversal/BstLevelOrderTraversal.kt | 1 | 1394 | package katas.kotlin.leetcode.bst_level_order_traversal
import katas.kotlin.leetcode.TreeNode
import datsok.shouldEqual
import org.junit.Test
import java.util.*
import kotlin.collections.ArrayList
/**
* https://leetcode.com/problems/binary-tree-level-order-traversal/
*/
class BstLevelOrderTraversal {
@Test fun `level order traversal`() {
TreeNode(1).levelOrder() shouldEqual listOf(listOf(1))
TreeNode(1, TreeNode(0), TreeNode(2)).levelOrder() shouldEqual listOf(listOf(1), listOf(0, 2))
TreeNode(3,
TreeNode(9),
TreeNode(20, TreeNode(15), TreeNode(7))
).levelOrder() shouldEqual listOf(listOf(3), listOf(9, 20), listOf(15, 7))
}
private fun TreeNode.levelOrder(): List<List<Int>> {
var q1 = LinkedList<TreeNode>()
var q2 = LinkedList<TreeNode>()
q1.addFirst(this)
val result = ArrayList<List<Int>>()
while (q1.isNotEmpty()) {
val subResult = ArrayList<Int>()
do {
val node = q1.removeLast()
if (node.left != null) q2.addFirst(node.left)
if (node.right != null) q2.addFirst(node.right)
subResult.add(node.value)
} while (q1.isNotEmpty())
result.add(subResult)
val tmp = q1
q1 = q2
q2 = tmp
}
return result
}
}
| unlicense | f8beb5d6976133ad7196907512ea6323 | 31.418605 | 102 | 0.58967 | 3.91573 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantWithInspection.kt | 1 | 5260 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.inspections.UnusedLambdaExpressionBodyInspection.Companion.replaceBlockExpressionWithLambdaBody
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RedundantWithInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
callExpressionVisitor(fun(callExpression) {
val callee = callExpression.calleeExpression ?: return
if (callee.text != "with") return
val valueArguments = callExpression.valueArguments
if (valueArguments.size != 2) return
val receiver = valueArguments[0].getArgumentExpression() ?: return
val lambda = valueArguments[1].lambdaExpression() ?: return
val lambdaBody = lambda.bodyExpression ?: return
val context = callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (lambdaBody.statements.size > 1 && callExpression.isUsedAsExpression(context)) return
if (callExpression.getResolvedCall(context)?.resultingDescriptor?.fqNameSafe != FqName("kotlin.with")) return
val lambdaDescriptor = context[BindingContext.FUNCTION, lambda.functionLiteral] ?: return
var used = false
lambda.functionLiteral.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (used) return
element.acceptChildren(this)
if (element is KtReturnExpression && element.getLabelName() == "with") {
used = true
return
}
if (isUsageOfDescriptor(lambdaDescriptor, element, context)) {
used = true
}
}
})
if (!used) {
val quickfix = when (receiver) {
is KtSimpleNameExpression, is KtStringTemplateExpression, is KtConstantExpression -> RemoveRedundantWithFix()
else -> null
}
holder.registerProblem(
callee,
KotlinBundle.message("inspection.redundant.with.display.name"),
quickfix
)
}
})
}
private fun KtValueArgument.lambdaExpression(): KtLambdaExpression? =
(this as? KtLambdaArgument)?.getLambdaExpression() ?: this.getArgumentExpression() as? KtLambdaExpression
private class RemoveRedundantWithFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.redundant.with.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val callExpression = descriptor.psiElement.parent as? KtCallExpression ?: return
val lambdaExpression = callExpression.valueArguments.getOrNull(1)?.lambdaExpression() ?: return
val lambdaBody = lambdaExpression.bodyExpression ?: return
val declaration = callExpression.getStrictParentOfType<KtDeclarationWithBody>()
val replaced = if (declaration?.equalsToken != null && KtPsiUtil.deparenthesize(declaration.bodyExpression) == callExpression) {
val singleReturnedExpression = (lambdaBody.statements.singleOrNull() as? KtReturnExpression)?.returnedExpression
if (singleReturnedExpression != null) {
callExpression.replaced(singleReturnedExpression)
} else {
declaration.replaceBlockExpressionWithLambdaBody(lambdaBody)
declaration.bodyExpression
}
} else {
val result = lambdaBody.allChildren.takeUnless { it.isEmpty }?.let { range ->
callExpression.parent.addRangeAfter(range.first, range.last, callExpression)
}
callExpression.delete()
result
}
if (replaced != null) {
replaced.findExistingEditor()?.moveCaret(replaced.startOffset)
}
}
}
| apache-2.0 | 67d14cc104336fab7048dc27ad54019f | 46.818182 | 136 | 0.687643 | 5.748634 | false | false | false | false |
cdietze/klay | tripleklay/tripleklay-demo/src/main/kotlin/tripleklay/demo/core/util/ColorsDemo.kt | 1 | 2392 | package tripleklay.demo.core.util
import tripleklay.demo.core.DemoScreen
import tripleklay.ui.*
import tripleklay.ui.layout.AxisLayout
import tripleklay.ui.layout.TableLayout
import tripleklay.util.Colors
class ColorsDemo : DemoScreen() {
override fun name(): String {
return "Colors"
}
override fun title(): String {
return "Util: Colors"
}
override fun createIface(root: Root): Group {
return Group(AxisLayout.vertical(), Style.HALIGN.center).add(
Group(TableLayout(TableLayout.COL.fixed().alignRight(),
TableLayout.COL.fixed().alignLeft()).gaps(1, 5)).add(
Label("White"), createLabel(Colors.WHITE),
Label("Light Gray"), createLabel(Colors.LIGHT_GRAY),
Label("Gray"), createLabel(Colors.GRAY),
Label("Dark Gray"), createLabel(Colors.DARK_GRAY),
Label("Black"), createLabel(Colors.BLACK),
Label("Red"), createLabel(Colors.RED),
Label("Pink"), createLabel(Colors.PINK),
Label("Orange"), createLabel(Colors.ORANGE),
Label("Yellow"), createLabel(Colors.YELLOW),
Label("Green"), createLabel(Colors.GREEN),
Label("Magenta"), createLabel(Colors.MAGENTA),
Label("Cyan"), createLabel(Colors.CYAN),
Label("Blue"), createLabel(Colors.BLUE)))
}
protected fun createLabel(baseColor: Int): Label {
return Label(createSampler(baseColor))
}
protected fun createSampler(baseColor: Int): Icon {
val size = 16f
val canvas = graphics().createCanvas(size * 17f, size)
var lighter = baseColor
for (ii in 0..8) {
canvas.setFillColor(lighter)
canvas.fillRect((size * (ii + 8)), 0f, size, size)
lighter = Colors.brighter(lighter)
}
var darker = baseColor
for (ii in 0..7) {
canvas.setFillColor(darker)
canvas.fillRect((size * (7 - ii)), 0f, size, size)
darker = Colors.darker(darker)
}
canvas.setStrokeColor(Colors.BLACK)
canvas.strokeRect((size * 8), 0f, (size - 1), (size - 1))
return Icons.image(canvas.toTexture())
}
}
| apache-2.0 | a78704c367318b5cb611eed7c540c729 | 38.213115 | 77 | 0.560619 | 4.591171 | false | false | false | false |
MGaetan89/ShowsRage | app/src/main/kotlin/com/mgaetan89/showsrage/model/ShowsStat.kt | 1 | 595 | package com.mgaetan89.showsrage.model
import com.google.gson.annotations.SerializedName
import io.realm.RealmObject
open class ShowsStat : RealmObject() {
@SerializedName("ep_downloaded")
open var episodesDownloaded: Int = 0
@SerializedName("ep_snatched")
open var episodesSnatched: Int = 0
@SerializedName("ep_total")
open var episodesTotal: Int = 0
@SerializedName("shows_active")
open var showsActive: Int = 0
@SerializedName("shows_total")
open var showsTotal: Int = 0
val episodesMissing: Int
get() = this.episodesTotal - (this.episodesDownloaded + this.episodesSnatched)
}
| apache-2.0 | 212034bdb3189fbc800ff85fb12e947a | 28.75 | 80 | 0.766387 | 3.584337 | false | false | false | false |
zbeboy/ISY | src/main/java/top/zbeboy/isy/service/common/DesServiceImpl.kt | 1 | 3142 | package top.zbeboy.isy.service.common
import org.apache.commons.codec.binary.Base64
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import top.zbeboy.isy.config.ISYProperties
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.DESKeySpec
/**
* Created by zbeboy 2017-12-31 .
**/
@Service("desService")
open class DesServiceImpl : DesService {
val DES = "DES"
@Autowired
open lateinit var isyProperties: ISYProperties
override fun encrypt(data: String): String {
val bt = encrypt(data.toByteArray(Charsets.UTF_8), isyProperties.getSecurity().desDefaultKey!!.toByteArray(Charsets.UTF_8))
return Base64.encodeBase64String(bt)
}
override fun decrypt(data: String?): String? {
if (data == null)
return null
val buf = Base64.decodeBase64(data)
val bt = decrypt(buf, isyProperties.getSecurity().desDefaultKey!!.toByteArray(Charsets.UTF_8))
return String(bt, Charsets.UTF_8)
}
override fun encrypt(data: String, key: String): String {
val bt = encrypt(data.toByteArray(Charsets.UTF_8), key.toByteArray(Charsets.UTF_8))
return Base64.encodeBase64String(bt)
}
override fun decrypt(data: String?, key: String): String? {
if (data == null)
return null
val buf = Base64.decodeBase64(data)
val bt = decrypt(buf, key.toByteArray(Charsets.UTF_8))
return String(bt, Charsets.UTF_8)
}
/**
* Description 根据键值进行加密
*
* @param data
* @param key
*/
private fun encrypt(data: ByteArray, key: ByteArray): ByteArray {
// 生成一个可信任的随机数源
val sr = SecureRandom()
// 从原始密钥数据创建DESKeySpec对象
val dks = DESKeySpec(key)
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
val keyFactory = SecretKeyFactory.getInstance(DES)
val securekey = keyFactory.generateSecret(dks)
// Cipher对象实际完成加密操作
val cipher = Cipher.getInstance(DES)
// 用密钥初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr)
return cipher.doFinal(data)
}
/**
* Description 根据键值进行解密
*
* @param data
* @param key
*/
private fun decrypt(data: ByteArray, key: ByteArray): ByteArray {
// 生成一个可信任的随机数源
val sr = SecureRandom()
// 从原始密钥数据创建DESKeySpec对象
val dks = DESKeySpec(key)
// 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象
val keyFactory = SecretKeyFactory.getInstance(DES)
val securekey = keyFactory.generateSecret(dks)
// Cipher对象实际完成解密操作
val cipher = Cipher.getInstance(DES)
// 用密钥初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr)
return cipher.doFinal(data)
}
} | mit | 451ae0ea977551bd89635c33f1d6436e | 27.425743 | 131 | 0.658188 | 3.821571 | false | false | false | false |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/statistic/statistics/MessagePicker.kt | 1 | 5524 | package simyukkuri.gameobject.yukkuri.statistic.statistics
import messageutil.MessageCollection
import simyukkuri.gameobject.yukkuri.statistic.YukkuriStats
import simyukkuri.randomElement
/** メッセージを取り出すためのクラス. */
class MessagePicker(private val messageCollection: MessageCollection) {
lateinit var self: YukkuriStats
val findsFood: String?
get() = messageCollection["findsFood"]?.get(self.messageCondition)?.randomElement()
val wantsFood: String?
get() = messageCollection["wantsFood"]?.get(self.messageCondition)?.randomElement()
val sexuallyExcited: String?
get() = messageCollection["sexuallyExcited"]?.get(self.messageCondition)?.randomElement()
val relaxed: String?
get() = messageCollection["relaxed"]?.get(self.messageCondition)?.randomElement()
val furifuri: String?
get() = messageCollection["furifuri"]?.get(self.messageCondition)?.randomElement()
val wakesUp: String?
get() = messageCollection["wakesUp"]?.get(self.messageCondition)?.randomElement()
val sleeping: String?
get() = messageCollection["sleeping"]?.get(self.messageCondition)?.randomElement()
val screams: String?
get() = messageCollection["screams"]?.get(self.messageCondition)?.randomElement()
val scared: String?
get() = messageCollection["scared"]?.get(self.messageCondition)?.randomElement()
val scaredAtRaper: String?
get() = messageCollection["scaredAtRaper"]?.get(self.messageCondition)?.randomElement()
val alarmed: String?
get() = messageCollection["alarmed"]?.get(self.messageCondition)?.randomElement()
val killedInstantly: String?
get() = messageCollection["killedInstantly"]?.get(self.messageCondition)?.randomElement()
val dies: String?
get() = messageCollection["dies"]?.get(self.messageCondition)?.randomElement()
val eating: String?
get() = messageCollection["eating"]?.get(self.messageCondition)?.randomElement()
val eatingPoo: String?
get() = messageCollection["eatingPoo"]?.get(self.messageCondition)?.randomElement()
val hasEatenBitter: String?
get() = messageCollection["hasEatenBitter"]?.get(self.messageCondition)?.randomElement()
val getsFull: String?
get() = messageCollection["getsFull"]?.get(self.messageCondition)?.randomElement()
val takesSweets: String?
get() = messageCollection["takesSweets"]?.get(self.messageCondition)?.randomElement()
val hasSukkiried: String?
get() = messageCollection["hasSukkiried"]?.get(self.messageCondition)?.randomElement()
val born: String?
get() = messageCollection["born"]?.get(self.messageCondition)?.randomElement()
val startsToPoop: String?
get() = messageCollection["startsToPoop"]?.get(self.messageCondition)?.randomElement()
val needsToPoop: String?
get() = messageCollection["needsToPoop"]?.get(self.messageCondition)?.randomElement()
val hasPooped: String?
get() = messageCollection["hasPooped"]?.get(self.messageCondition)?.randomElement()
val leaksPoo: String?
get() = messageCollection["leaksPoo"]?.get(self.messageCondition)?.randomElement()
val surisuri: String?
get() = messageCollection["surisuri"]?.get(self.messageCondition)?.randomElement()
val peropero: String?
get() = messageCollection["peropero"]?.get(self.messageCondition)?.randomElement()
val bearing: String?
get() = messageCollection["bearing"]?.get(self.messageCondition)?.randomElement()
val greetsBabyAfterBearing: String?
get() = messageCollection["greetsBabyAfterBearing"]?.get(self.messageCondition)?.randomElement()
val lamentsForAbortingBaby: String?
get() = messageCollection["lamentsForAbortingBaby"]?.get(self.messageCondition)?.randomElement()
val complainsAboutPoo: String?
get() = messageCollection["complainsAboutPoo"]?.get(self.messageCondition)?.randomElement()
val hungry: String?
get() = messageCollection["hungry"]?.get(self.messageCondition)?.randomElement()
val losesOkazari: String?
get() = messageCollection["losesOkazari"]?.get(self.messageCondition)?.randomElement()
val despisesYukkuriHavingNoOkazari: String?
get() = messageCollection["despisesYukkuriHavingNoOkazari"]?.get(self.messageCondition)?.randomElement()
val saysLikeFlying: String?
get() = messageCollection["saysLikeFlying"]?.get(self.messageCondition)?.randomElement()
val childDies: String?
get() = messageCollection["childDies"]?.get(self.messageCondition)?.randomElement()
val partnerDies: String?
get() = messageCollection["partnerDies"]?.get(self.messageCondition)?.randomElement()
val elderSisterDies: String?
get() = messageCollection["elderSisterDies"]?.get(self.messageCondition)?.randomElement()
val youngerSisterDies: String?
get() = messageCollection["youngerSisterDies"]?.get(self.messageCondition)?.randomElement()
val blockedByWall: String?
get() = messageCollection["blockedByWall"]?.get(self.messageCondition)?.randomElement()
val getsTreasure: String?
get() = messageCollection["getsTreasure"]?.get(self.messageCondition)?.randomElement()
val treasureTaken: String?
get() = messageCollection["treasureTaken"]?.get(self.messageCondition)?.randomElement()
val nobinobi: String?
get() = messageCollection["nobinobi"]?.get(self.messageCondition)?.randomElement()
} | apache-2.0 | ad6bba37b01429ff620b70ae8d7c14f0 | 57.43617 | 112 | 0.715768 | 4.13243 | false | false | false | false |
syncloud/android | syncloud/src/main/java/org/syncloud/android/SyncloudApplication.kt | 1 | 3455 | package org.syncloud.android
import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import androidx.preference.PreferenceManager
import org.acra.ACRA
import org.acra.BuildConfig
import org.acra.ReportField
import org.acra.annotation.AcraCore
import org.acra.annotation.AcraDialog
import org.acra.data.StringFormat
import org.apache.log4j.Logger
import org.syncloud.android.ConfigureLog4J.configure
import org.syncloud.android.core.common.WebService
import org.syncloud.android.core.common.http.HttpClient
import org.syncloud.android.core.redirect.IUserService
import org.syncloud.android.core.redirect.RedirectService
import org.syncloud.android.core.redirect.UserCachedService
import org.syncloud.android.core.redirect.UserStorage
import java.io.File
@SuppressLint("NonConstantResourceId")
@AcraDialog(
resText = R.string.crash_dialog_text,
resIcon = R.drawable.ic_launcher,
resTitle = R.string.crash_dialog_title
)
@AcraCore(
buildConfigClass = BuildConfig::class,
reportContent = [ReportField.APP_VERSION_CODE, ReportField.ANDROID_VERSION, ReportField.PHONE_MODEL, ReportField.STACK_TRACE, ReportField.LOGCAT],
logcatArguments = ["-t", "500", "-v", "long", "*:D"],
logcatFilterByPid = false,
reportSenderFactoryClasses = [AcraLogEmailerFactory::class],
reportFormat = StringFormat.KEY_VALUE_LIST
)
class SyncloudApplication : Application() {
private lateinit var _userStorage: UserStorage
lateinit var preferences: Preferences
lateinit var userServiceCached: IUserService
@Suppress("DEPRECATION")
fun isWifiConnected(): Boolean {
val connMgr = applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?
connMgr ?: return false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val network: Network = connMgr.activeNetwork ?: return false
val capabilities = connMgr.getNetworkCapabilities(network)
return capabilities != null && capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} else {
val networkInfo = connMgr.activeNetworkInfo ?: return false
return networkInfo.isConnected && networkInfo.type == ConnectivityManager.TYPE_WIFI
}
}
override fun onCreate() {
configure()
val logger = Logger.getLogger(SyncloudApplication::class.java)
logger.info("Starting Syncloud App")
super.onCreate()
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
PreferenceManager.setDefaultValues(this, R.xml.preferences, false)
preferences = Preferences(sharedPreferences)
_userStorage = UserStorage(File(applicationContext.filesDir, "user.json"))
userServiceCached = webServiceAuthWithFileBackedCache()
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(base)
ACRA.init(this)
}
private fun webServiceAuthWithFileBackedCache(): UserCachedService {
val redirectService = RedirectService(preferences.mainDomain, WebService(HttpClient()))
return UserCachedService(redirectService, _userStorage)
}
fun reportError() = ACRA.getErrorReporter().handleSilentException(null)
} | gpl-3.0 | ee079e3204c00e14e47dda0a86c244ef | 40.638554 | 154 | 0.74848 | 4.552042 | false | true | false | false |
paplorinc/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/CreateMethodAction.kt | 6 | 6309 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupEditor
import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils.setupMethodBody
import com.intellij.codeInsight.daemon.impl.quickfix.GuessTypeParameters
import com.intellij.codeInsight.template.Template
import com.intellij.codeInsight.template.TemplateBuilder
import com.intellij.codeInsight.template.TemplateBuilderImpl
import com.intellij.codeInsight.template.TemplateEditingAdapter
import com.intellij.lang.java.request.CreateMethodFromJavaUsageRequest
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.*
import com.intellij.openapi.command.WriteCommandAction.runWriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil.setModifierProperty
/**
* @param abstract whether this action creates a method with explicit abstract modifier
*/
internal class CreateMethodAction(
targetClass: PsiClass,
override val request: CreateMethodRequest,
private val abstract: Boolean
) : CreateMemberAction(targetClass, request), JvmGroupIntentionAction {
override fun getActionGroup(): JvmActionGroup = if (abstract) CreateAbstractMethodActionGroup else CreateMethodActionGroup
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
return super.isAvailable(project, editor, file) && PsiNameHelper.getInstance(project).isIdentifier(request.methodName)
}
override fun getRenderData() = JvmActionGroup.RenderData { request.methodName }
override fun getFamilyName(): String = message("create.method.from.usage.family")
override fun getText(): String {
val what = request.methodName
val where = getNameForClass(target, false)
return if (abstract) {
message("create.abstract.method.from.usage.full.text", what, where)
}
else {
message("create.method.from.usage.full.text", what, where)
}
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
JavaMethodRenderer(project, abstract, target, request).doMagic()
}
}
private class JavaMethodRenderer(
val project: Project,
val abstract: Boolean,
val targetClass: PsiClass,
val request: CreateMethodRequest
) {
val factory = JavaPsiFacade.getElementFactory(project)!!
val requestedModifiers = request.modifiers
val javaUsage = request as? CreateMethodFromJavaUsageRequest
val withoutBody = abstract || targetClass.isInterface && JvmModifier.STATIC !in requestedModifiers
fun doMagic() {
var method = renderMethod()
method = insertMethod(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val builder = setupTemplate(method)
method = forcePsiPostprocessAndRestoreElement(method) ?: return
val template = builder.buildInlineTemplate()
startTemplate(method, template)
}
private fun renderMethod(): PsiMethod {
val method = factory.createMethod(request.methodName, PsiType.VOID)
val modifiersToRender = requestedModifiers.toMutableList()
if (targetClass.isInterface) {
modifiersToRender -= (visibilityModifiers + JvmModifier.ABSTRACT)
}
else if (abstract) {
if (modifiersToRender.remove(JvmModifier.PRIVATE)) {
modifiersToRender += JvmModifier.PROTECTED
}
modifiersToRender += JvmModifier.ABSTRACT
}
for (modifier in modifiersToRender) {
setModifierProperty(method, modifier.toPsiModifier(), true)
}
for (annotation in request.annotations) {
method.modifierList.addAnnotation(annotation.qualifiedName)
}
if (withoutBody) method.body?.delete()
return method
}
private fun insertMethod(method: PsiMethod): PsiMethod {
val anchor = javaUsage?.getAnchor(targetClass)
val inserted = if (anchor == null) {
targetClass.add(method)
}
else {
targetClass.addAfter(method, anchor)
}
return inserted as PsiMethod
}
private fun setupTemplate(method: PsiMethod): TemplateBuilderImpl {
val builder = TemplateBuilderImpl(method)
createTemplateContext(builder).run {
setupTypeElement(method.returnTypeElement, request.returnType)
setupParameters(method, request.expectedParameters)
}
builder.setEndVariableAfter(method.body ?: method)
return builder
}
private fun createTemplateContext(builder: TemplateBuilder): TemplateContext {
val substitutor = request.targetSubstitutor.toPsiSubstitutor(project)
val guesser = GuessTypeParameters(project, factory, builder, substitutor)
return TemplateContext(project, factory, targetClass, builder, guesser, javaUsage?.context)
}
private fun startTemplate(method: PsiMethod, template: Template) {
val targetFile = targetClass.containingFile
val newEditor = positionCursor(project, targetFile, method) ?: return
val templateListener = if (withoutBody) null else MyMethodBodyListener(project, newEditor, targetFile)
CreateFromUsageBaseFix.startTemplate(newEditor, template, project, templateListener, null)
}
}
private class MyMethodBodyListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() {
override fun templateFinished(template: Template, brokenOff: Boolean) {
if (brokenOff) return
runWriteCommandAction(project) {
PsiDocumentManager.getInstance(project).commitDocument(editor.document)
val offset = editor.caretModel.offset
PsiTreeUtil.findElementOfClassAtOffset(file, offset - 1, PsiMethod::class.java, false)?.let { method ->
setupMethodBody(method)
setupEditor(method, editor)
}
}
}
}
| apache-2.0 | ad2f484876d273506a8d5b8e956842ae | 38.93038 | 140 | 0.772706 | 4.81971 | false | false | false | false |
paplorinc/intellij-community | uast/uast-tests/src/org/jetbrains/uast/test/common/IndentedPrintingVisitor.kt | 1 | 1063 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.common
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import kotlin.reflect.KClass
abstract class IndentedPrintingVisitor(val shouldIndent: (PsiElement) -> Boolean) : PsiElementVisitor() {
constructor(vararg kClasses: KClass<*>) : this({ psi -> kClasses.any { it.isInstance(psi) } })
private val builder = StringBuilder()
var level = 0
private set
override fun visitElement(element: PsiElement) {
val charSequence = render(element)
if (charSequence != null) {
builder.append(" ".repeat(level))
builder.append(charSequence)
builder.appendln()
}
val shouldIndent = shouldIndent(element)
if (shouldIndent) level++
element.acceptChildren(this)
if (shouldIndent) level--
}
protected abstract fun render(element: PsiElement): CharSequence?
val result: String
get() = builder.toString()
} | apache-2.0 | b572573a735e1a817b7e52d1b606276a | 30.294118 | 140 | 0.720602 | 4.269076 | false | false | false | false |
PlanBase/PdfLayoutMgr2 | src/main/java/com/planbase/pdf/lm2/lineWrapping/LineWrapped.kt | 1 | 5707 | // Copyright 2017 PlanBase Inc.
//
// This file is part of PdfLayoutMgr2
//
// PdfLayoutMgr 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.
//
// PdfLayoutMgr 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 PdfLayoutMgr. If not, see <https://www.gnu.org/licenses/agpl-3.0.en.html>.
//
// If you wish to use this code with proprietary software,
// contact PlanBase Inc. <https://planbase.com> to purchase a commercial license.
package com.planbase.pdf.lm2.lineWrapping
import com.planbase.pdf.lm2.attributes.DimAndPageNums
import com.planbase.pdf.lm2.pages.RenderTarget
import com.planbase.pdf.lm2.utils.Dim
import com.planbase.pdf.lm2.utils.Coord
/**
Represents a fixed-size item. Classes implementing this interface should be immutable.
*/
interface LineWrapped {
/** These are the dim *without/before* page-breaking adjustments. */
val dim: Dim
// fun width(): Double = width
// fun totalHeight(): Double = heightAboveBase + depthBelowBase
/** Height above the baseline of this line */
val ascent: Double
/** Depth below the baseline of this line */
// val descentAndLeading: Double
// Removed because it entirely duplicated dim.height.
// Was "Total vertical height this line, both above and below the baseline"
// val lineHeight: Double
/**
* Sends the underlying object to PDFBox to be drawn.
*
* @param lp RenderTarget is the SinglePage or PageGrouping to draw to. This will contain the paper size,
* orientation, and body area which are necessary in order to calculate page breaking
* @param topLeft is the offset where this item starts.
* @param reallyRender render if true. Otherwise, just measure without drawing anything. This may be a little
* awkward for the end-user, but it lets us use exactly the same logic for measuring as for drawing which
* prevents bugs and there's a version of this method without this parameter.
* @param justifyWidth the width of the line - non-zero if items should be alignd "justified" to stretch to both
* sides of the width.
* @return the adjusted Dim which may include extra (vertical) spacing required to nudge some items onto the next
* page so they don't end up in the margin or off the page.
*/
// TODO: Add preventWidows: Boolean after reallyRender.
fun render(lp: RenderTarget, topLeft: Coord, reallyRender: Boolean, justifyWidth: Double): DimAndPageNums
/**
* Sends the underlying object to PDFBox to be drawn.
*
* @param lp RenderTarget is the SinglePage or PageGrouping to draw to. This will contain the paper size,
* orientation, and body area which are necessary in order to calculate page breaking
* @param topLeft is the offset where this item starts.
* @param reallyRender render if true. Otherwise, just measure without drawing anything. This may be a little
* awkward for the end-user, but it lets us use exactly the same logic for measuring as for drawing which
* prevents bugs and there's a version of this method without this parameter.
* @return the adjusted Dim which may include extra (vertical) spacing required to nudge some items onto the next
* page so they don't end up in the margin or off the page.
*/
// TODO: Is this necessary or helpful?
@JvmDefault
fun render(lp: RenderTarget, topLeft: Coord, reallyRender:Boolean): DimAndPageNums =
render(lp, topLeft, reallyRender, 0.0)
/**
* Sends the underlying object to PDFBox to be drawn. Use the other render() method with reallyRender=false
* for an exact measurement after page breaking without actually drawing anything.
*
* @param lp RenderTarget is the SinglePage or PageGrouping to draw to. This will contain the paper size,
* orientation, and body area which are necessary in order to calculate page breaking
* @param topLeft is the offset where this item starts.
* @return the adjusted Dim which may include extra (vertical) spacing required to nudge some items onto the next
* page so they don't end up in the margin or off the page.
*/
// TODO: Is this necessary or helpful?
@JvmDefault
fun render(lp: RenderTarget, topLeft: Coord): DimAndPageNums = render(lp, topLeft, true)
// companion object {
//
// fun preWrappedLineWrapper(item: LineWrapped) = object : LineWrapper {
// private var hasMore = true
// override fun hasMore(): Boolean = hasMore
//
// override fun getSomething(maxWidth: Double): ConTerm {
// hasMore = false
// return Continuing(item)
// }
//
// override fun getIfFits(remainingWidth: Double): ConTermNone =
// if (hasMore && (item.dim.width <= remainingWidth)) {
// hasMore = false
// Continuing(item)
// } else {
// None
// }
// }
// }
/**
* For a composite line, returns the items on the line. For a single-item line, just returns a single-item list
* containing `this`.
*/
@JvmDefault
fun items():List<LineWrapped> = listOf(this)
}
| agpl-3.0 | b09f24eea120a06da06764dfea821bca | 45.778689 | 117 | 0.686525 | 4.469068 | false | false | false | false |
google/intellij-community | plugins/github/src/org/jetbrains/plugins/github/extensions/GHProtectedBranchRulesLoader.kt | 1 | 3793 | // 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 org.jetbrains.plugins.github.extensions
import git4idea.remote.hosting.findKnownRepositories
import com.intellij.concurrency.SensitiveProgressWrapper
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.util.PatternUtil
import git4idea.config.GitSharedSettings
import git4idea.fetch.GitFetchHandler
import git4idea.repo.GitRemote
import git4idea.repo.GitRepository
import org.jetbrains.plugins.github.api.GHGQLRequests
import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager
import org.jetbrains.plugins.github.api.util.SimpleGHGQLPagesLoader
import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.util.GHHostedRepositoriesManager
import org.jetbrains.plugins.github.util.GithubProjectSettings
private val LOG = logger<GHProtectedBranchRulesLoader>()
internal class GHProtectedBranchRulesLoader : GitFetchHandler {
override fun doAfterSuccessfulFetch(project: Project, fetches: Map<GitRepository, List<GitRemote>>, indicator: ProgressIndicator) {
try {
loadProtectionRules(indicator, fetches, project)
}
catch (e: Exception) {
if (e is ProcessCanceledException) {
throw e
}
LOG.info("Error occurred while trying to load branch protection rules", e)
}
}
private fun loadProtectionRules(indicator: ProgressIndicator,
fetches: Map<GitRepository, List<GitRemote>>,
project: Project) {
val authenticationManager = GithubAuthenticationManager.getInstance()
if (!GitSharedSettings.getInstance(project).isSynchronizeBranchProtectionRules || !authenticationManager.hasAccounts()) {
runInEdt {
project.service<GithubProjectSettings>().branchProtectionPatterns = arrayListOf()
}
return
}
indicator.text = GithubBundle.message("progress.text.loading.protected.branches")
val branchProtectionPatterns = mutableSetOf<String>()
for ((repository, remotes) in fetches) {
indicator.checkCanceled()
for (remote in remotes) {
indicator.checkCanceled()
val repositoryMapping =
project.service<GHHostedRepositoriesManager>().findKnownRepositories(repository)
.find { it.remote.remote == remote }
?: continue
val serverPath = repositoryMapping.repository.serverPath
val defaultAccount = authenticationManager.getDefaultAccount(repository.project)
val account =
if (defaultAccount != null
&& defaultAccount.server.equals(serverPath, true)) {
defaultAccount
}
else {
authenticationManager.getAccounts().find {
it.server.equals(serverPath, true)
}
} ?: continue
val requestExecutor = GithubApiRequestExecutorManager.getInstance().getExecutor(account)
SimpleGHGQLPagesLoader(requestExecutor, { GHGQLRequests.Repo.getProtectionRules(repositoryMapping.repository) })
.loadAll(SensitiveProgressWrapper((indicator)))
.forEach { rule -> branchProtectionPatterns.add(PatternUtil.convertToRegex(rule.pattern)) }
}
}
runInEdt {
project.service<GithubProjectSettings>().branchProtectionPatterns = branchProtectionPatterns.toMutableList()
}
}
}
| apache-2.0 | b94dfef5c4992c3e3e9601fc2d76ba89 | 40.228261 | 140 | 0.741366 | 5.091275 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/view/course_content/ui/adapter/decorators/CourseContentTimelineDecorator.kt | 2 | 1268 | package org.stepik.android.view.course_content.ui.adapter.decorators
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
class CourseContentTimelineDecorator : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val adapterPosition = parent.getChildAdapterPosition(view)
if (adapterPosition + 1 == parent.adapter?.itemCount) {
outRect.right += calculateRightOffset(parent)
}
}
private fun calculateRightOffset(parent: RecyclerView): Int {
val layoutManager = parent.layoutManager ?: return 0
val adapter = parent.adapter ?: return 0
var offset = 0
var position = adapter.itemCount - 1
while (position >= 0) {
val width = layoutManager.findViewByPosition(position)?.width ?: 0
if (offset + width > parent.width) {
break
} else {
offset += width
}
position--
}
// if we fill whole width we don't need scroll decoration
return if (position < 0) 0 else parent.width - offset - parent.paddingLeft - parent.paddingRight
}
} | apache-2.0 | 2b39fa0361e8f1ba2e07d502992c2c1d | 35.257143 | 109 | 0.647476 | 4.992126 | false | false | false | false |
fluidsonic/fluid-json | coding/sources-jvm/codecs/basic/NonRecursiveJsonDecoderCodec.kt | 1 | 1244 | package io.fluidsonic.json
internal abstract class NonRecursiveJsonDecoderCodec<Value : Any> : AbstractJsonDecoderCodec<Value, JsonCodingContext>() {
private val expectedFirstToken = when (decodableType.rawClass) {
Collection::class,
Iterable::class,
List::class,
Sequence::class,
Set::class ->
JsonToken.listStart
Map::class ->
JsonToken.mapStart
else -> error("Cannot decode $decodableType")
}
@Suppress("UNCHECKED_CAST")
override fun JsonDecoder<JsonCodingContext>.decode(valueType: JsonCodingType<Value>): Value {
if (nextToken != expectedFirstToken) {
throw JsonException.Schema(
message = "Cannot decode $nextToken as $valueType",
offset = offset,
path = path
)
}
val value = JsonParser.default.parseValueOrNull(this, withTermination = false)
return when {
Sequence::class.java.isAssignableFrom(valueType.rawClass.java) -> (value as Iterable<*>).asSequence() as Value
Set::class.java.isAssignableFrom(valueType.rawClass.java) -> (value as Iterable<*>).toSet() as Value
else -> value as Value
}
}
companion object {
inline fun <reified Value : Any> create(): JsonDecoderCodec<Value, JsonCodingContext> =
object : NonRecursiveJsonDecoderCodec<Value>() {}
}
}
| apache-2.0 | f62dc9454e88e999a0fdd0593a2beddd | 26.043478 | 122 | 0.723473 | 3.92429 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ui/colorpicker/ColorPipetteButton.kt | 1 | 1629 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.colorpicker
import java.awt.Color
import javax.swing.JButton
class ColorPipetteButton(private val colorPickerModel: ColorPickerModel, private val pipette: ColorPipette) : JButton() {
init {
isRolloverEnabled = true
icon = pipette.icon
rolloverIcon = pipette.rolloverIcon
pressedIcon = pipette.pressedIcon
addActionListener { pipette.pick(MyCallback(colorPickerModel)) }
}
private inner class MyCallback(val model: ColorPickerModel): ColorPipette.Callback {
private val originalColor = model.color
override fun picked(pickedColor: Color) {
model.setColor(pickedColor, this@ColorPipetteButton)
model.firePipettePicked(pickedColor)
}
override fun update(updatedColor: Color) {
model.setColor(updatedColor, this@ColorPipetteButton)
model.firePipetteUpdated(updatedColor)
}
override fun cancel() {
model.setColor(originalColor, this@ColorPipetteButton)
model.firePipetteCancelled()
}
}
}
| apache-2.0 | bcc2c7c1cd63504f8355d7c11c6fa6ff | 30.326923 | 121 | 0.740331 | 4.332447 | false | false | false | false |
allotria/intellij-community | platform/statistics/devkit/src/com/intellij/internal/statistic/toolwindow/StatisticsGroupHyperlinkInfo.kt | 3 | 2798 | // 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.internal.statistic.toolwindow
import com.intellij.execution.filters.HyperlinkInfo
import com.intellij.execution.filters.OpenFileHyperlinkInfo
import com.intellij.ide.DataManager
import com.intellij.internal.statistic.StatisticsBundle
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.WindowManager
import com.intellij.ui.awt.RelativePoint
internal class StatisticsGroupHyperlinkInfo(private val groupId: String,
private val eventId: String,
private val eventData: String,
private val file: VirtualFile,
private val lineNumber: Int) : HyperlinkInfo {
override fun navigate(project: Project) {
val actions = StatisticsLogGroupActionsProvider.EP_NAME.extensionList
.filter { getPluginInfo(it.javaClass).isDevelopedByJetBrains() }
.flatMap { it.getActions(groupId, eventId, eventData) }
if (actions.isEmpty()) {
OpenFileHyperlinkInfo(project, file, lineNumber).navigate(project)
}
else {
val group = DefaultActionGroup()
group.addAll(actions)
group.add(OpenGroupScheme(project, file, lineNumber))
showPopup(project, group)
}
}
private fun showPopup(project: Project?, actionGroup: ActionGroup) {
DataManager.getInstance().dataContextFromFocusAsync.onSuccess { dataContext ->
val popup = JBPopupFactory.getInstance().createActionGroupPopup(null, actionGroup, dataContext,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, true)
val frame = WindowManager.getInstance().getFrame(project)
if (frame != null) {
val mousePosition = frame.mousePosition
if (mousePosition != null) {
popup.show(RelativePoint(frame, mousePosition))
}
}
}
}
class OpenGroupScheme(private val project: Project, private val file: VirtualFile, private val lineNumber: Int)
: AnAction(StatisticsBundle.message("stats.navigate.to.group.scheme")) {
override fun actionPerformed(e: AnActionEvent) {
OpenFileHyperlinkInfo(project, file, lineNumber).navigate(project)
}
}
} | apache-2.0 | ef57366332367d6e1ecda32a4895e694 | 46.440678 | 140 | 0.704074 | 5.041441 | false | false | false | false |
tsagi/JekyllForAndroid | app/src/main/java/gr/tsagi/jekyllforandroid/app/activities/LoginActivity.kt | 2 | 7826 | package gr.tsagi.jekyllforandroid.app.activities
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ImageButton
import android.widget.TextView
import android.widget.Toast
import com.jchanghong.R
import gr.tsagi.jekyllforandroid.app.utils.FetchPostsTask
import gr.tsagi.jekyllforandroid.app.utils.GetAccessToken
import gr.tsagi.jekyllforandroid.app.utils.JekyllRepo
import org.eclipse.egit.github.core.client.GitHubClient
import org.eclipse.egit.github.core.service.UserService
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
class LoginActivity : BaseActivity() {
//Change the Scope as you need
lateinit internal var web: WebView
lateinit internal var auth: ImageButton
lateinit internal var settings: SharedPreferences
lateinit internal var logview: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
logview = findViewById(R.id.log) as TextView
logview.text = "login......."
settings = getSharedPreferences(
"gr.tsagi.jekyllforandroid", Context.MODE_PRIVATE)
auth = findViewById(R.id.fab) as ImageButton
auth.setOnClickListener(object : View.OnClickListener {
lateinit internal var auth_dialog: Dialog
override fun onClick(arg0: View) {
// TODO Auto-generated method stub
auth_dialog = Dialog(this@LoginActivity)
auth_dialog.setContentView(R.layout.auth_dialog)
web = auth_dialog.findViewById<View>(R.id.webv) as WebView
web.settings.javaScriptEnabled = true
web.loadUrl("$OAUTH_URL?redirect_uri=$REDIRECT_URI&response_type=code&client_id=$CLIENT_ID&scope=$OAUTH_SCOPE")
web.webViewClient = object : WebViewClient() {
internal var authComplete = false
internal var resultIntent = Intent()
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
// super.onPageStarted(view, url, favicon)
}
lateinit internal var authCode: String
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
if (url.contains("?code=") && authComplete != true) {
val uri = Uri.parse(url)
authCode = uri.getQueryParameter("code")
Log.i("", "CODE : " + authCode)
authComplete = true
resultIntent.putExtra("code", authCode)
[email protected](Activity.RESULT_OK, resultIntent)
setResult(Activity.RESULT_CANCELED, resultIntent)
val edit = settings.edit()
edit.putString("Code", authCode)
edit.commit()
auth_dialog.dismiss()
TokenGet().execute()
} else if (url.contains("error=access_denied")) {
Log.i("", "ACCESS_DENIED_HERE")
resultIntent.putExtra("code", authCode)
authComplete = true
setResult(Activity.RESULT_CANCELED, resultIntent)
Toast.makeText(applicationContext, "Error Occured", Toast.LENGTH_SHORT).show()
auth_dialog.dismiss()
}
}
}
auth_dialog.show()
auth_dialog.setTitle("Authorize Jekyll for Android")
auth_dialog.setCancelable(true)
}
})
}
override val layoutResource: Int
get() = R.layout.activity_login
private inner class TokenGet : AsyncTask<String, String, JSONObject>() {
private var pDialog: ProgressDialog? = null
lateinit internal var Code: String
override fun onPreExecute() {
super.onPreExecute()
pDialog = ProgressDialog(this@LoginActivity)
pDialog!!.setMessage("Contacting Github ...")
pDialog!!.isIndeterminate = false
pDialog!!.setCancelable(true)
Code = settings.getString("Code", "")
pDialog!!.show()
}
override fun doInBackground(vararg args: String): JSONObject {
val jParser = GetAccessToken()
return jParser.gettoken(TOKEN_URL, Code, CLIENT_ID, CLIENT_SECRET, REDIRECT_URI,
GRANT_TYPE)
}
@SuppressLint("ObsoleteSdkInt")
override fun onPostExecute(json: JSONObject?) {
pDialog!!.dismiss()
if (json != null) {
try {
val tok = json.getString("access_token")
Log.d("Token Access", tok)
//TODO: React to touch
val editor = settings.edit()
editor.putString("user_status", tok)
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
editor.apply()
} else {
editor.commit()
}
UserGet().execute()
} catch (e: JSONException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
} else {
Toast.makeText(applicationContext, "Network Error", Toast.LENGTH_SHORT).show()
pDialog!!.dismiss()
}
}
}
private inner class UserGet : AsyncTask<Void, Void, Void>() {
internal var user = ""
override fun doInBackground(vararg args: Void): Void? {
val client = GitHubClient()
client.setOAuth2Token(settings.getString("user_status", ""))
val uService = UserService(client)
try {
val us = uService.user
user = us.login
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
override fun onPostExecute(aVoid: Void?) {
Log.d("LoginUser", settings.getString("user_status", ""))
val uRepo = JekyllRepo()
val repo = uRepo.getName(user)
val editor = settings.edit()
editor.putString("user_login", user)
editor.putString("user_repo", repo)
editor.commit()
val fetchPostsTask = FetchPostsTask(this@LoginActivity, logview)
fetchPostsTask.execute()
// finish();
}
}
companion object {
private val CLIENT_ID = "1569f7710e0b37bb066c"
//Use your own client id
private val CLIENT_SECRET = "f28ab3c713d44d4cc582c09fa7afe38e5e6024b4"
//Use your own client secret
private val REDIRECT_URI = "http://localhost"
private val GRANT_TYPE = "auth_code"
private val TOKEN_URL = "https://github.com/login/oauth/access_token"
private val OAUTH_URL = "https://github.com/login/oauth/authorize"
private val OAUTH_SCOPE = "user%2Crepo"
}
}
| gpl-2.0 | b89a407fec8a9bd2f19dd14395a20126 | 38.928571 | 127 | 0.569895 | 4.978372 | false | false | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/browser/bookmark/BookmarkRecyclerViewAdapter.kt | 1 | 1795 | package acr.browser.lightning.browser.bookmark
import acr.browser.lightning.R
import acr.browser.lightning.browser.image.ImageLoader
import acr.browser.lightning.database.Bookmark
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
/**
* An adapter that creates the views for bookmark list items and binds the bookmark data to them.
*
* @param onClick Invoked when the cell is clicked.
* @param onLongClick Invoked when the cell is long pressed.
* @param imageLoader The image loader needed to load favicons.
*/
class BookmarkRecyclerViewAdapter(
private val onClick: (Int) -> Unit,
private val onLongClick: (Int) -> Unit,
private val imageLoader: ImageLoader
) : ListAdapter<Bookmark, BookmarkViewHolder>(
object : DiffUtil.ItemCallback<Bookmark>() {
override fun areItemsTheSame(oldItem: Bookmark, newItem: Bookmark): Boolean =
oldItem == newItem
override fun areContentsTheSame(oldItem: Bookmark, newItem: Bookmark): Boolean =
oldItem == newItem
}
) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookmarkViewHolder {
val inflater = LayoutInflater.from(parent.context)
val itemView = inflater.inflate(R.layout.bookmark_list_item, parent, false)
return BookmarkViewHolder(
itemView,
onItemLongClickListener = onLongClick,
onItemClickListener = onClick
)
}
override fun onBindViewHolder(holder: BookmarkViewHolder, position: Int) {
val viewModel = getItem(position)
holder.binding.textBookmark.text = viewModel.title
imageLoader.loadImage(holder.binding.faviconBookmark, viewModel)
}
}
| mpl-2.0 | 1cb6981d25b2f2a15069ad15c286d0a1 | 36.395833 | 97 | 0.729248 | 4.917808 | false | false | false | false |
chiuki/espresso-samples | rotate-screen/app/src/main/java/com/sqisland/espresso/rotate_screen/MainActivity.kt | 1 | 907 | package com.sqisland.espresso.rotate_screen
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private var count = 0
private lateinit var countView: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
countView = findViewById(R.id.count)
savedInstanceState?.let {
count = it.getInt(KEY_COUNT, 0)
}
updateCount()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt(KEY_COUNT, count)
}
fun increment(v: View) {
count += 1
updateCount()
}
private fun updateCount() {
countView.text = count.toString()
}
companion object {
private const val KEY_COUNT = "count"
}
} | apache-2.0 | d4560dcbaaa5772e6c9c7d2ad194348c | 21.146341 | 54 | 0.718853 | 4.238318 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/util/Tuples.kt | 2 | 2811 | /*
* 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 kotlin
/**
* Represents a generic pair of two values.
*
* There is no meaning attached to values in this class, it can be used for any purpose.
* Pair exhibits value semantics, i.e. two pairs are equal if both components are equal.
*
* An example of decomposing it into values:
* @sample samples.misc.Tuples.pairDestructuring
*
* @param A type of the first value.
* @param B type of the second value.
* @property first First value.
* @property second Second value.
* @constructor Creates a new instance of Pair.
*/
public data class Pair<out A, out B>(
public val first: A,
public val second: B
) {
/**
* Returns string representation of the [Pair] including its [first] and [second] values.
*/
public override fun toString(): String = "($first, $second)"
}
/**
* Creates a tuple of type [Pair] from this and [that].
*
* This can be useful for creating [Map] literals with less noise, for example:
* @sample samples.collections.Maps.Instantiation.mapFromPairs
*/
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
/**
* Converts this pair into a list.
*/
public fun <T> Pair<T, T>.toList(): List<T> = listOf(first, second)
/**
* Represents a triad of values
*
* There is no meaning attached to values in this class, it can be used for any purpose.
* Triple exhibits value semantics, i.e. two triples are equal if all three components are equal.
* An example of decomposing it into values:
* @sample samples.misc.Tuples.tripleDestructuring
*
* @param A type of the first value.
* @param B type of the second value.
* @param C type of the third value.
* @property first First value.
* @property second Second value.
* @property third Third value.
*/
public data class Triple<out A, out B, out C>(
public val first: A,
public val second: B,
public val third: C
) {
/**
* Returns string representation of the [Triple] including its [first], [second] and [third] values.
*/
public override fun toString(): String = "($first, $second, $third)"
}
/**
* Converts this triple into a list.
*/
public fun <T> Triple<T, T, T>.toList(): List<T> = listOf(first, second, third)
| apache-2.0 | 910fae517607bdac8a75370d1fca0a7e | 30.943182 | 104 | 0.688367 | 3.743009 | false | false | false | false |
alvarlagerlof/temadagar-android | app/src/main/java/com/alvarlagerlof/temadagarapp/FCM/FirebaseInstanceIDService.kt | 1 | 1430 | package com.alvarlagerlof.temadagarapp.FCM
import android.util.Log
import com.alvarlagerlof.temadagarapp.Vars
import com.google.firebase.iid.FirebaseInstanceId
import com.google.firebase.iid.FirebaseInstanceIdService
/**
* Created by alvar on 2016-08-14.
*/
class FirebaseInstanceIDService : FirebaseInstanceIdService() {
override fun onTokenRefresh() {
//Getting registration token
val refreshedToken = FirebaseInstanceId.getInstance().token
//Displaying token on logcat
Log.d(TAG, "Refreshed token: " + refreshedToken!!)
// Subscribe to topics
val preferences = android.preference.PreferenceManager.getDefaultSharedPreferences(this)
val notificationsToday = preferences.getBoolean(Vars.NOTIFICATIONS_TODAY, false)
val notificationsComing = preferences.getBoolean(Vars.NOTIFICATIONS_COMING, false)
val notificationsNew = preferences.getBoolean(Vars.NOTIFICATIONS_NEW, false)
if (notificationsToday) {
//FirebaseMessaging.getInstance().subscribeToTopic(Vars.TOPIC_TODAY)
}
if (notificationsComing) {
//FirebaseMessaging.getInstance().subscribeToTopic(Vars.TOPIC_COMING)
}
if (notificationsNew) {
//FirebaseMessaging.getInstance().subscribeToTopic(Vars.TOPIC_NEW)
}
}
companion object {
private val TAG = "MyFirebaseIIDService"
}
}
| mit | fd6c1a242a90baf92f019d33dd6171ab | 27.6 | 96 | 0.705594 | 4.65798 | false | false | false | false |
AndroidX/androidx | activity/activity-lint/src/main/java/androidx/activity/lint/ActivityResultFragmentVersionDetector.kt | 3 | 8725 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.activity.lint
import com.android.builder.model.AndroidLibrary
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Detector.UastScanner
import com.android.tools.lint.detector.api.GradleContext
import com.android.tools.lint.detector.api.GradleScanner
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Location
import com.android.tools.lint.detector.api.Project
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UElement
import java.util.EnumSet
import kotlin.reflect.full.memberFunctions
import kotlin.reflect.full.memberProperties
import kotlin.reflect.jvm.isAccessible
class ActivityResultFragmentVersionDetector : Detector(), UastScanner, GradleScanner {
companion object {
const val FRAGMENT_VERSION = "1.3.0"
val ISSUE = Issue.create(
id = "InvalidFragmentVersionForActivityResult",
briefDescription = "Update to Fragment $FRAGMENT_VERSION to use ActivityResult APIs",
explanation = """In order to use the ActivityResult APIs you must upgrade your \
Fragment version to $FRAGMENT_VERSION. Previous versions of FragmentActivity \
failed to call super.onRequestPermissionsResult() and used invalid request codes""",
category = Category.CORRECTNESS,
severity = Severity.FATAL,
implementation = Implementation(
ActivityResultFragmentVersionDetector::class.java,
EnumSet.of(Scope.JAVA_FILE, Scope.GRADLE_FILE),
Scope.JAVA_FILE_SCOPE,
Scope.GRADLE_SCOPE
)
).addMoreInfo(
"https://developer.android.com/training/permissions/requesting#make-the-request"
)
}
var locations = ArrayList<Location>()
lateinit var expression: UCallExpression
private var checkedImplementationDependencies = false
override fun getApplicableUastTypes(): List<Class<out UElement>>? {
return listOf(UCallExpression::class.java)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return object : UElementHandler() {
override fun visitCallExpression(node: UCallExpression) {
if (node.methodIdentifier?.name != "registerForActivityResult") {
return
}
expression = node
locations.add(context.getLocation(node))
}
}
}
override fun checkDslPropertyAssignment(
context: GradleContext,
property: String,
value: String,
parent: String,
parentParent: String?,
valueCookie: Any,
statementCookie: Any
) {
if (locations.isEmpty()) {
return
}
if (property == "api") {
// always check api dependencies
reportIssue(value, context)
} else if (!checkedImplementationDependencies) {
val project = context.project
if (useNewLintVersion(project)) {
checkWithNewLintVersion(project, context)
} else {
checkWithOldLintVersion(project, context)
}
}
}
private fun useNewLintVersion(project: Project): Boolean {
project::class.memberFunctions.forEach { function ->
if (function.name == "getBuildVariant") {
return true
}
}
return false
}
private fun checkWithNewLintVersion(project: Project, context: GradleContext) {
val buildVariant = callFunctionWithReflection(project, "getBuildVariant")
val mainArtifact = getMemberWithReflection(buildVariant, "mainArtifact")
val dependencies = getMemberWithReflection(mainArtifact, "dependencies")
val all = callFunctionWithReflection(dependencies, "getAll")
(all as ArrayList<*>).forEach { lmLibrary ->
lmLibrary::class.memberProperties.forEach { libraryMembers ->
if (libraryMembers.name == "resolvedCoordinates") {
libraryMembers.isAccessible = true
reportIssue(libraryMembers.call(lmLibrary).toString(), context, false)
}
}
}
}
private fun checkWithOldLintVersion(project: Project, context: GradleContext) {
lateinit var explicitLibraries: Collection<AndroidLibrary>
val currentVariant = callFunctionWithReflection(project, "getCurrentVariant")
val mainArtifact = callFunctionWithReflection(currentVariant, "getMainArtifact")
val dependencies = callFunctionWithReflection(mainArtifact, "getDependencies")
@Suppress("UNCHECKED_CAST")
explicitLibraries =
callFunctionWithReflection(dependencies, "getLibraries") as Collection<AndroidLibrary>
// collect all of the library dependencies
val allLibraries = HashSet<AndroidLibrary>()
addIndirectAndroidLibraries(explicitLibraries, allLibraries)
// check all of the dependencies
allLibraries.forEach {
val resolvedCoords = it.resolvedCoordinates
val groupId = resolvedCoords.groupId
val artifactId = resolvedCoords.artifactId
val version = resolvedCoords.version
reportIssue("$groupId:$artifactId:$version", context, false)
}
}
private fun callFunctionWithReflection(caller: Any, functionName: String): Any {
caller::class.memberFunctions.forEach { function ->
if (function.name == functionName) {
function.isAccessible = true
return function.call(caller)!!
}
}
return Unit
}
private fun getMemberWithReflection(caller: Any, memberName: String): Any {
caller::class.memberProperties.forEach { member ->
if (member.name == memberName) {
member.getter.isAccessible = true
return member.getter.call(caller)!!
}
}
return Unit
}
private fun addIndirectAndroidLibraries(
libraries: Collection<AndroidLibrary>,
result: MutableSet<AndroidLibrary>
) {
for (library in libraries) {
if (!result.contains(library)) {
result.add(library)
addIndirectAndroidLibraries(library.libraryDependencies, result)
}
}
}
private fun reportIssue(
value: String,
context: GradleContext,
removeQuotes: Boolean = true
) {
val library = if (removeQuotes) {
getStringLiteralValue(value)
} else {
value
}
if (library.isNotEmpty()) {
val currentVersion = library.substringAfter("androidx.fragment:fragment:")
.substringBeforeLast("-")
if (library != currentVersion && currentVersion < FRAGMENT_VERSION) {
locations.forEach { location ->
context.report(
ISSUE, expression, location,
"Upgrade Fragment version to at least $FRAGMENT_VERSION."
)
}
}
}
}
/**
* Extracts the string value from the DSL value by removing surrounding quotes.
*
* Returns an empty string if [value] is not a string literal.
*/
private fun getStringLiteralValue(value: String): String {
if (value.length > 2 && (
value.startsWith("'") && value.endsWith("'") ||
value.startsWith("\"") && value.endsWith("\"")
)
) {
return value.substring(1, value.length - 1)
}
return ""
}
}
| apache-2.0 | 9cb4af1635cb225692e641be829d98a6 | 37.436123 | 100 | 0.639542 | 5.114302 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/ui/tree/GroupListProvider.kt | 9 | 1471 | // 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.ui.tree
import com.intellij.ide.bookmark.BookmarkBundle.message
import com.intellij.ide.bookmark.BookmarksListProvider
import com.intellij.ide.bookmark.ui.GroupRenameDialog
import com.intellij.ide.util.treeView.AbstractTreeNode
import com.intellij.openapi.project.Project
import javax.swing.JComponent
internal class GroupListProvider(private val project: Project) : BookmarksListProvider {
override fun getWeight() = Int.MAX_VALUE
override fun getProject() = project
override fun createNode(): AbstractTreeNode<*>? = null
override fun getEditActionText() = message("bookmark.group.rename.action.text")
override fun canEdit(selection: Any) = selection is GroupNode
override fun performEdit(selection: Any, parent: JComponent) {
val node = selection as? GroupNode ?: return
val group = node.value ?: return
val manager = node.bookmarksManager ?: return
GroupRenameDialog(project, parent, manager, group).showAndGetGroup()
}
override fun getDeleteActionText() = message("bookmark.group.delete.action.text")
override fun canDelete(selection: List<*>) = selection.all { it is GroupNode }
override fun performDelete(selection: List<*>, parent: JComponent) = selection.forEach {
val node = it as? GroupNode
node?.value?.remove()
}
}
| apache-2.0 | 2d24aa77a2f18fbe8994851e0bca02f8 | 44.96875 | 158 | 0.768865 | 4.377976 | false | false | false | false |
kpi-ua/ecampus-client-android | app/src/main/java/com/goldenpiedevs/schedule/app/core/api/teachers/TeachersManager.kt | 1 | 2041 | package com.goldenpiedevs.schedule.app.core.api.teachers
import android.content.Context
import com.goldenpiedevs.schedule.app.core.dao.group.DaoGroupModel
import com.goldenpiedevs.schedule.app.core.dao.timetable.DaoTeacherModel
import com.goldenpiedevs.schedule.app.core.utils.util.isNetworkAvailable
import io.realm.Realm
import io.realm.RealmList
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
class TeachersManager(private val context: Context, private val teachersService: TeachersService) {
fun loadTeachers(groupId: Int) {
if (!context.isNetworkAvailable()) {
return
}
GlobalScope.launch {
[email protected](groupId)
}
}
fun loadTeachersAsync(groupId: Int): Deferred<Boolean> = GlobalScope.async {
val response = teachersService.getTeachers(groupId).await()
if (response.isSuccessful) {
val realm = Realm.getDefaultInstance()
val group = DaoGroupModel.getGroup(groupId)
response.body()?.data?.let {
val list = RealmList<DaoTeacherModel>().apply {
addAll(response.body()?.data!!)
}
list.onEach { newTeacher ->
DaoTeacherModel.getTeacher(newTeacher.teacherId)?.let { managedTeacher ->
newTeacher.hasLoadedSchedule = managedTeacher.hasLoadedSchedule
}
}
realm.executeTransaction { r ->
r.copyToRealmOrUpdate(list)
group?.let {
r.copyToRealmOrUpdate(
it.apply {
teachers = list
})
}
}
if (!realm.isClosed)
realm.close()
}
}
return@async response.isSuccessful
}
} | apache-2.0 | 80bcb5c21be1cea7b7f6ec76b6dadf78 | 31.412698 | 99 | 0.584027 | 5.301299 | false | false | false | false |
tensorflow/examples | lite/examples/gesture_classification/android/app/src/main/java/org/tensorflow/lite/examples/gestureclassification/fragments/PermissionsFragment.kt | 1 | 2830 | /*
* Copyright 2022 The TensorFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.tensorflow.lite.examples.gestureclassification.fragments
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import org.tensorflow.lite.examples.gestureclassification.R
private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA)
class PermissionsFragment : Fragment() {
private val requestPermissionLauncher =
registerForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show()
navigateToCamera()
} else {
Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
when {
ContextCompat.checkSelfPermission(
requireContext(),
Manifest.permission.CAMERA
) == PackageManager.PERMISSION_GRANTED -> {
navigateToCamera()
}
else -> {
requestPermissionLauncher.launch(
Manifest.permission.CAMERA
)
}
}
}
private fun navigateToCamera() {
lifecycleScope.launchWhenStarted {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsToCamera()
)
}
}
companion object {
/** Convenience method used to check if all permissions required by this app are granted */
fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
}
}
| apache-2.0 | 47eefdf69ccc138bc3a525aeb1738d7a | 34.822785 | 99 | 0.678799 | 5.299625 | false | false | false | false |
Flank/flank | flank-scripts/src/main/kotlin/flank/scripts/data/github/objects/GitHubUpdateIssue.kt | 1 | 505 | package flank.scripts.data.github.objects
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class GitHubUpdateIssueRequest(
val title: String = "",
val body: String = "",
val state: IssueState = IssueState.OPEN,
val milestone: Int? = null,
val labels: List<String> = emptyList(),
val assignees: List<String> = emptyList()
)
@Serializable
enum class IssueState {
@SerialName("open") OPEN,
@SerialName("closed") CLOSED
}
| apache-2.0 | bfdfaa9325c6bd874aaae40383a65699 | 24.25 | 45 | 0.718812 | 4.105691 | false | false | false | false |
fabmax/kool | kool-physics/src/jvmMain/kotlin/de/fabmax/kool/physics/character/CharacterControllerManager.kt | 1 | 1686 | package de.fabmax.kool.physics.character
import de.fabmax.kool.math.toRad
import de.fabmax.kool.physics.Physics
import de.fabmax.kool.physics.PhysicsWorld
import physx.PxTopLevelFunctions
import physx.character.PxCapsuleClimbingModeEnum
import physx.character.PxCapsuleControllerDesc
import physx.character.PxControllerManager
import physx.character.PxControllerNonWalkableModeEnum
import kotlin.math.cos
actual class CharacterControllerManager actual constructor(world: PhysicsWorld) : CommonCharacterControllerManager(world) {
private val pxManager: PxControllerManager
init {
Physics.checkIsLoaded()
pxManager = PxTopLevelFunctions.CreateControllerManager(world.pxScene)
}
override fun doCreateController(): JvmCharacterController {
// create controller with default configuration
val hitCallback = ControllerHitListener(world)
val behaviorCallback = ControllerBahaviorCallback(world)
val desc = PxCapsuleControllerDesc()
desc.height = 1f
desc.radius = 0.3f
desc.climbingMode = PxCapsuleClimbingModeEnum.eEASY
desc.nonWalkableMode = PxControllerNonWalkableModeEnum.ePREVENT_CLIMBING
desc.slopeLimit = cos(50f.toRad())
desc.material = Physics.defaultMaterial.pxMaterial
desc.contactOffset = 0.1f
desc.reportCallback = hitCallback
desc.behaviorCallback = behaviorCallback
val pxCharacter = pxManager.createController(desc)
desc.destroy()
return JvmCharacterController(pxCharacter, hitCallback, behaviorCallback, this, world)
}
override fun release() {
super.release()
pxManager.release()
}
} | apache-2.0 | 40745580c753b83788289b1783c08a07 | 36.488889 | 123 | 0.752076 | 4.606557 | false | false | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/viewmodels/ThreadViewModelTest.kt | 1 | 30899 | package com.kickstarter.viewmodels
import android.content.Intent
import android.util.Pair
import com.kickstarter.KSRobolectricTestCase
import com.kickstarter.libs.Environment
import com.kickstarter.libs.MockCurrentUser
import com.kickstarter.libs.utils.EventName
import com.kickstarter.mock.factories.AvatarFactory
import com.kickstarter.mock.factories.CommentCardDataFactory
import com.kickstarter.mock.factories.CommentEnvelopeFactory
import com.kickstarter.mock.factories.CommentFactory
import com.kickstarter.mock.factories.ProjectFactory
import com.kickstarter.mock.factories.UserFactory
import com.kickstarter.mock.services.MockApolloClient
import com.kickstarter.models.Comment
import com.kickstarter.services.apiresponses.commentresponse.CommentEnvelope
import com.kickstarter.ui.IntentKey
import com.kickstarter.ui.data.CommentCardData
import com.kickstarter.ui.views.CommentCardStatus
import com.kickstarter.ui.views.CommentComposerStatus
import org.joda.time.DateTime
import org.junit.Test
import rx.Observable
import rx.observers.TestSubscriber
import rx.schedulers.TestScheduler
import rx.subjects.BehaviorSubject
import java.io.IOException
import java.util.concurrent.TimeUnit
class ThreadViewModelTest : KSRobolectricTestCase() {
private lateinit var vm: ThreadViewModel.ViewModel
private val getComment = TestSubscriber<CommentCardData>()
private val focusCompose = TestSubscriber<Boolean>()
private val onReplies = TestSubscriber<Pair<List<CommentCardData>, Boolean>>()
private val replyComposerStatus = TestSubscriber<CommentComposerStatus>()
private val showReplyComposer = TestSubscriber<Boolean>()
private val loadMoreReplies = TestSubscriber<Void>()
private val openCommentGuideLines = TestSubscriber<Void>()
private val refresh = TestSubscriber<Void>()
private val hasPendingComments = TestSubscriber<Boolean>()
private val closeThreadActivity = TestSubscriber<Void>()
private fun setUpEnvironment() {
setUpEnvironment(environment())
}
private fun setUpEnvironment(environment: Environment) {
this.vm = ThreadViewModel.ViewModel(environment)
this.vm.getRootComment().subscribe(getComment)
this.vm.shouldFocusOnCompose().subscribe(focusCompose)
this.vm.onCommentReplies().subscribe(onReplies)
this.vm.loadMoreReplies().subscribe(loadMoreReplies)
this.vm.refresh().subscribe(refresh)
}
@Test
fun testGetRootComment() {
setUpEnvironment()
val commentCardData = CommentCardDataFactory.commentCardData()
this.vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, commentCardData))
getComment.assertValue(commentCardData)
this.vm.intent(Intent().putExtra("Some other Key", commentCardData))
getComment.assertValue(commentCardData)
}
@Test
fun testShouldFocusCompose() {
setUpEnvironment()
this.vm.intent(Intent().putExtra(IntentKey.REPLY_EXPAND, false))
focusCompose.assertValue(false)
this.vm.intent(Intent().putExtra("Some other Key", false))
focusCompose.assertValues(false)
this.vm.intent(Intent().putExtra(IntentKey.REPLY_EXPAND, true))
focusCompose.assertValues(false, true)
}
@Test
fun testThreadViewModel_setCurrentUserAvatar() {
val userAvatar = AvatarFactory.avatar()
val currentUser = UserFactory.user().toBuilder().id(111).avatar(
userAvatar
).build()
val project = ProjectFactory.project()
.toBuilder()
.isBacking(false)
.build()
val vm = ThreadViewModel.ViewModel(
environment().toBuilder().currentUser(MockCurrentUser(currentUser)).build()
)
val currentUserAvatar = TestSubscriber<String?>()
vm.outputs.currentUserAvatar().subscribe(currentUserAvatar)
// Start the view model with a project.
vm.intent(Intent().putExtra(IntentKey.PROJECT, project))
// set user avatar with small url
currentUserAvatar.assertValue(userAvatar.small())
}
@Test
fun testThreadViewModel_whenUserLoggedInAndBacking_shouldShowEnabledComposer() {
val vm = ThreadViewModel.ViewModel(
environment().toBuilder().currentUser(MockCurrentUser(UserFactory.user())).build()
)
vm.outputs.replyComposerStatus().subscribe(replyComposerStatus)
vm.outputs.showReplyComposer().subscribe(showReplyComposer)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardDataBacked()))
// The comment composer should be shown to backer and enabled to write comments
replyComposerStatus.assertValue(CommentComposerStatus.ENABLED)
showReplyComposer.assertValues(true, true)
}
@Test
fun testThreadViewModel_whenUserIsLoggedOut_composerShouldBeGone() {
val vm = ThreadViewModel.ViewModel(environment().toBuilder().build())
vm.outputs.replyComposerStatus().subscribe(replyComposerStatus)
vm.outputs.showReplyComposer().subscribe(showReplyComposer)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
// The comment composer should be hidden and disabled to write comments as no user logged-in
showReplyComposer.assertValue(false)
replyComposerStatus.assertValue(CommentComposerStatus.GONE)
}
@Test
fun testThreadViewModel_whenUserIsLoggedInNotBacking_shouldShowDisabledComposer() {
val vm = ThreadViewModel.ViewModel(
environment().toBuilder().currentUser(MockCurrentUser(UserFactory.user())).build()
)
vm.outputs.replyComposerStatus().subscribe(replyComposerStatus)
vm.outputs.showReplyComposer().subscribe(showReplyComposer)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
// The comment composer should show but in disabled state
replyComposerStatus.assertValue(CommentComposerStatus.DISABLED)
showReplyComposer.assertValues(true, true)
}
@Test
fun testThreadViewModel_whenUserIsCreator_shouldShowEnabledComposer() {
val currentUser = UserFactory.user().toBuilder().id(1234).build()
val project = ProjectFactory.project()
.toBuilder()
.creator(currentUser)
.isBacking(false)
.build()
val vm = ThreadViewModel.ViewModel(
environment().toBuilder().currentUser(MockCurrentUser(currentUser)).build()
)
vm.outputs.replyComposerStatus().subscribe(replyComposerStatus)
vm.outputs.showReplyComposer().subscribe(showReplyComposer)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardDataBacked()))
// The comment composer enabled to write comments for creator
showReplyComposer.assertValues(true, true)
replyComposerStatus.assertValues(CommentComposerStatus.ENABLED)
}
@Test
fun testThreadViewModel_enableCommentComposer_notBackingNotCreator() {
val creator = UserFactory.creator().toBuilder().id(222).build()
val currentUser = UserFactory.user().toBuilder().id(111).build()
val project = ProjectFactory.project()
.toBuilder()
.creator(creator)
.isBacking(false)
.build()
val vm = ThreadViewModel.ViewModel(
environment().toBuilder().currentUser(MockCurrentUser(currentUser)).build()
)
vm.outputs.replyComposerStatus().subscribe(replyComposerStatus)
vm.outputs.showReplyComposer().subscribe(showReplyComposer)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
// Comment composer should be disabled and shown the disabled msg if not backing and not creator.
showReplyComposer.assertValues(true, true)
replyComposerStatus.assertValue(CommentComposerStatus.DISABLED)
}
@Test
fun testLoadCommentReplies_Successful() {
val createdAt = DateTime.now()
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.just(CommentEnvelopeFactory.repliesCommentsEnvelope(createdAt = createdAt))
}
})
.build()
setUpEnvironment(env)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
this.onReplies.assertValueCount(2)
}
@Test
fun testLoadCommentReplies_Error() {
val createdAt = DateTime.now()
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.error(IOException())
}
})
.build()
setUpEnvironment(env)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
this.onReplies.assertValueCount(0)
vm.reloadRepliesPage()
this.refresh.assertValueCount(1)
}
@Test
fun testLoadCommentReplies_pagination() {
val createdAt = DateTime.now()
val replies = CommentEnvelopeFactory.repliesCommentsEnvelopeHasPrevious(createdAt = createdAt)
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.just(replies)
}
})
.build()
setUpEnvironment(env)
val onReplies = BehaviorSubject.create<Pair<List<CommentCardData>, Boolean>>()
this.vm.onCommentReplies().subscribe(onReplies)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
val onRepliesResult = onReplies.value
assertEquals(replies.comments?.size, onRepliesResult?.first?.size)
assertEquals(true, onRepliesResult?.second)
vm.inputs.reloadRepliesPage()
this.loadMoreReplies.assertValueCount(1)
}
@Test
fun testThreadsViewModel_openCommentGuidelinesLink() {
setUpEnvironment()
this.vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
// Start the view model with an update.
vm.outputs.showCommentGuideLinesLink().subscribe(openCommentGuideLines)
// post a comment
vm.inputs.onShowGuideLinesLinkClicked()
openCommentGuideLines.assertValueCount(1)
}
@Test
fun testComments_UpdateCommentStateAfterPost() {
val currentUser = UserFactory.user()
.toBuilder()
.id(1)
.build()
val comment1 = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(1).body("comment1").build()
val comment2 = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(2).body("comment2").build()
val newPostedComment = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(3).body("comment3").build()
val commentEnvelope = CommentEnvelopeFactory.commentsEnvelope().toBuilder()
.comments(listOf(comment1, comment2))
.build()
val testScheduler = TestScheduler()
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.just(commentEnvelope)
}
})
.currentUser(MockCurrentUser(currentUser))
.scheduler(testScheduler)
.build()
val commentCardData1 = CommentCardData.builder()
.comment(comment1)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val commentCardData2 = CommentCardData.builder()
.comment(comment2)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val commentCardData3 = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.TRYING_TO_POST.commentCardStatus)
.build()
val commentCardData3Updated = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val vm = ThreadViewModel.ViewModel(env)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
vm.outputs.onCommentReplies().subscribe(onReplies)
onReplies.assertValueCount(1)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 2)
assertTrue(newList[0].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData2.commentCardState)
}
// - New posted comment with status "TRYING_TO_POST"
vm.inputs.insertNewReplyToList(newPostedComment.body(), DateTime.now())
testScheduler.advanceTimeBy(3, TimeUnit.SECONDS)
onReplies.assertValueCount(2)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
// - Check the status of the newly posted comment has been updated to "COMMENT_FOR_LOGIN_BACKED_USERS"
vm.inputs.refreshCommentCardInCaseSuccessPosted(newPostedComment, 0)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
onReplies.assertValueCount(3)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3Updated.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3Updated.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
segmentTrack.assertValues(EventName.PAGE_VIEWED.eventName, EventName.CTA_CLICKED.eventName)
}
@Test
fun testComments_UpdateCommentStateAfterPostFailed() {
val currentUser = UserFactory.user()
.toBuilder()
.id(1)
.build()
val comment1 = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(1).body("comment1").build()
val comment2 = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(2).body("comment2").build()
val newPostedComment = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(3).body("comment3").build()
val commentEnvelope = CommentEnvelopeFactory.commentsEnvelope().toBuilder()
.comments(listOf(comment1, comment2))
.build()
val testScheduler = TestScheduler()
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.just(commentEnvelope)
}
})
.currentUser(MockCurrentUser(currentUser))
.scheduler(testScheduler)
.build()
val commentCardData1 = CommentCardData.builder()
.comment(comment1)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val commentCardData2 = CommentCardData.builder()
.comment(comment2)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val commentCardData3 = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.TRYING_TO_POST.commentCardStatus)
.build()
val commentCardData3Failed = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.FAILED_TO_SEND_COMMENT.commentCardStatus)
.build()
val commentCardData3Updated = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val vm = ThreadViewModel.ViewModel(env)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
vm.outputs.onCommentReplies().subscribe(onReplies)
onReplies.assertValueCount(1)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 2)
assertTrue(newList[0].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData2.commentCardState)
}
// - New posted comment with status "TRYING_TO_POST"
vm.inputs.insertNewReplyToList(newPostedComment.body(), DateTime.now())
testScheduler.advanceTimeBy(3, TimeUnit.SECONDS)
onReplies.assertValueCount(2)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
// - Check the status of the newly posted comment has been updated to "FAILED_TO_SEND_COMMENT"
vm.inputs.refreshCommentCardInCaseFailedPosted(newPostedComment, 0)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
onReplies.assertValueCount(3)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3Failed.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3Failed.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
// - Check the status of the newly posted comment has been updated to "COMMENT_FOR_LOGIN_BACKED_USERS"
vm.inputs.refreshCommentCardInCaseSuccessPosted(newPostedComment, 0)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3Updated.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3Updated.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
segmentTrack.assertValues(EventName.PAGE_VIEWED.eventName, EventName.CTA_CLICKED.eventName)
}
@Test
fun backButtonPressed_whenEmits_shouldEmitToCloseActivityStream() {
setUpEnvironment()
vm.outputs.closeThreadActivity().subscribe(closeThreadActivity)
vm.inputs.backPressed()
closeThreadActivity.assertValueCount(1)
}
@Test
fun testReplies_BackWithPendingComment() {
val currentUser = UserFactory.user()
.toBuilder()
.id(1)
.build()
val comment1 = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(1).body("comment1").build()
val comment2 = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(2).body("comment2").build()
val newPostedComment = CommentFactory.commentToPostWithUser(currentUser).toBuilder().id(3).body("comment3").build()
val commentEnvelope = CommentEnvelopeFactory.commentsEnvelope().toBuilder()
.comments(listOf(comment1, comment2))
.build()
val testScheduler = TestScheduler()
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.just(commentEnvelope)
}
})
.currentUser(MockCurrentUser(currentUser))
.scheduler(testScheduler)
.build()
val commentCardData1 = CommentCardData.builder()
.comment(comment1)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val commentCardData2 = CommentCardData.builder()
.comment(comment2)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val commentCardData3 = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.TRYING_TO_POST.commentCardStatus)
.build()
val commentCardData3Failed = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.FAILED_TO_SEND_COMMENT.commentCardStatus)
.build()
val commentCardData3Updated = CommentCardData.builder()
.comment(newPostedComment)
.commentCardState(CommentCardStatus.COMMENT_FOR_LOGIN_BACKED_USERS.commentCardStatus)
.build()
val vm = ThreadViewModel.ViewModel(env)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
vm.outputs.onCommentReplies().subscribe(onReplies)
vm.outputs.onCommentReplies().subscribe()
vm.outputs.hasPendingComments().subscribe(hasPendingComments)
onReplies.assertValueCount(1)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 2)
assertTrue(newList[0].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData2.commentCardState)
}
vm.inputs.checkIfThereAnyPendingComments()
this.hasPendingComments.assertValue(false)
// - New posted comment with status "TRYING_TO_POST"
vm.inputs.insertNewReplyToList(newPostedComment.body(), DateTime.now())
testScheduler.advanceTimeBy(3, TimeUnit.SECONDS)
onReplies.assertValueCount(2)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
vm.inputs.checkIfThereAnyPendingComments()
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
this.hasPendingComments.assertValues(false, true)
// - Check the status of the newly posted comment
vm.inputs.refreshCommentCardInCaseFailedPosted(newPostedComment, 0)
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
onReplies.assertValueCount(3)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList.size == 3)
assertTrue(newList[0].comment?.body() == commentCardData3Failed.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData3Failed.commentCardState)
assertTrue(newList[1].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[1].commentCardState == commentCardData1.commentCardState)
assertTrue(newList[2].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[2].commentCardState == commentCardData2.commentCardState)
}
// - Check Pull to refresh
vm.inputs.checkIfThereAnyPendingComments()
testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)
this.hasPendingComments.assertValues(false, true, true)
}
@Test
fun testComments_onShowCanceledPledgeComment() {
val currentUser = UserFactory.user()
.toBuilder()
.id(1)
.build()
val comment1 = CommentFactory.commentWithCanceledPledgeAuthor(currentUser).toBuilder().id(1).body("comment1").build()
val commentEnvelope = CommentEnvelopeFactory.commentsEnvelope().toBuilder()
.comments(listOf(comment1))
.build()
val testScheduler = TestScheduler()
val env = environment().toBuilder()
.apolloClient(object : MockApolloClient() {
override fun getRepliesForComment(
comment: Comment,
cursor: String?,
pageSize: Int
): Observable<CommentEnvelope> {
return Observable.just(commentEnvelope)
}
})
.currentUser(MockCurrentUser(currentUser))
.scheduler(testScheduler)
.build()
val commentCardData1 = CommentCardData.builder()
.comment(comment1)
.commentCardState(CommentCardStatus.CANCELED_PLEDGE_MESSAGE.commentCardStatus)
.build()
val commentCardData2 = CommentCardData.builder()
.comment(comment1)
.commentCardState(CommentCardStatus.CANCELED_PLEDGE_COMMENT.commentCardStatus)
.build()
val vm = ThreadViewModel.ViewModel(env)
// Start the view model with a backed project and comment.
vm.intent(Intent().putExtra(IntentKey.COMMENT_CARD_DATA, CommentCardDataFactory.commentCardData()))
vm.outputs.onCommentReplies().subscribe(onReplies)
onReplies.assertValueCount(1)
vm.outputs.onCommentReplies().take(0).subscribe {
val newList = it.first
assertTrue(newList[0].comment?.body() == commentCardData1.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData1.commentCardState)
}
vm.inputs.onShowCanceledPledgeComment(comment1)
vm.outputs.onCommentReplies().take(1).subscribe {
val newList = it.first
assertTrue(newList[0].comment?.body() == commentCardData2.comment?.body())
assertTrue(newList[0].commentCardState == commentCardData2.commentCardState)
}
}
}
| apache-2.0 | d6f7556000023278f6f2f7a86967f5b3 | 42.27591 | 125 | 0.668048 | 4.851468 | false | true | false | false |
kivensolo/UiUsingListView | app-playerdemo/src/main/java/com/kingz/playerdemo/extractor/AMExtractor.kt | 1 | 1793 | package com.kingz.playerdemo.extractor
import android.media.MediaExtractor
import android.media.MediaFormat
import android.util.Log
/**
* author:ZekeWang
* date:2021/4/16
* description: Android MediaExtractor音视频的Exractor
*/
class AMExtractor(playUrl: String) {
private val TAG: String = "PlayerDemoActivity"
lateinit var mMediaExtractor: MediaExtractor
var videoTrackId: Int = 0
var audioTrackId: Int = 0
var videoFormat: MediaFormat? = null
var audioFormat: MediaFormat? = null
init {
Log.i(TAG, "Init AMExtractor with file:$playUrl")
try {
mMediaExtractor = MediaExtractor()
mMediaExtractor.setDataSource(playUrl)
} catch (e: Exception) {
e.printStackTrace()
}
// 遍历轨道
for (idx in 0 until mMediaExtractor.trackCount) {
// 获取指定track的MediaFormat
val mediaFormat = mMediaExtractor.getTrackFormat(idx)
val mime = mediaFormat.getString(MediaFormat.KEY_MIME)
if (mime.startsWith("video/")) {
Log.w(TAG, "Find video track, MIME=$mime ; " +
"MediaFormat=$mediaFormat; ")
videoTrackId = idx
videoFormat = mediaFormat
} else if (mime.startsWith("audio")) {
Log.w(TAG, "Find Audio track, MIME=$mime ; " +
"MediaFormat=$mediaFormat; ")
audioTrackId = idx
audioFormat = mediaFormat
}
}
}
/**
* 选择指定轨道
* 由Decoder对象在Config之前调用
*/
fun selectTrack(trackId: Int) {
mMediaExtractor.selectTrack(trackId)
}
fun release(){
mMediaExtractor.release()
}
} | gpl-2.0 | 8a8133b4beef73f3b33e3bf186843df3 | 28.389831 | 66 | 0.587421 | 4.489637 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/util/utils.kt | 2 | 3160 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.fir.low.level.api.util
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressManager
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.declarations.FirDeclaration
import org.jetbrains.kotlin.fir.diagnostics.FirDiagnosticHolder
import org.jetbrains.kotlin.fir.psi
import org.jetbrains.kotlin.fir.render
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.util.getElementTextInContext
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtObjectLiteralExpression
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.Lock
internal inline fun <T> executeOrReturnDefaultValueOnPCE(defaultValue: T, action: () -> T): T =
try {
action()
} catch (e: ProcessCanceledException) {
defaultValue
}
internal inline fun <T : Any> executeWithoutPCE(crossinline action: () -> T): T {
var result: T? = null
ProgressManager.getInstance().executeNonCancelableSection { result = action() }
return result!!
}
internal inline fun <T> Lock.lockWithPCECheck(lockingIntervalMs: Long, action: () -> T): T {
var needToRun = true
var result: T? = null
while (needToRun) {
checkCanceled()
if (tryLock(lockingIntervalMs, TimeUnit.MILLISECONDS)) {
try {
needToRun = false
result = action()
} finally {
unlock()
}
}
}
return result!!
}
@Suppress("NOTHING_TO_INLINE")
internal inline fun checkCanceled() {
ProgressManager.checkCanceled()
}
internal val FirElement.isErrorElement
get() = this is FirDiagnosticHolder
internal val FirDeclaration.ktDeclaration: KtDeclaration
get() {
val psi = psi
?: error("PSI element was not found for${render()}")
return when (psi) {
is KtDeclaration -> psi
is KtObjectLiteralExpression -> psi.objectDeclaration
else -> error(
"""
FirDeclaration.psi (${this::class.simpleName}) should be KtDeclaration but was ${psi::class.simpleName}
${(psi as? KtElement)?.getElementTextInContext() ?: psi.text}
${render()}
""".trimIndent()
)
}
}
internal val FirDeclaration.containingKtFileIfAny: KtFile?
get() = psi?.containingFile as? KtFile
internal fun IdeaModuleInfo.collectTransitiveDependenciesWithSelf(): List<IdeaModuleInfo> {
val result = mutableSetOf<IdeaModuleInfo>()
fun collect(module: IdeaModuleInfo) {
if (module in result) return
result += module
module.dependencies().forEach(::collect)
}
collect(this)
return result.toList()
} | apache-2.0 | a52375cdcbfa1274210e933cae4f62b2 | 32.62766 | 122 | 0.676582 | 4.54023 | false | false | false | false |
kivensolo/UiUsingListView | module-Demo/src/main/java/com/zeke/demo/draw/paint/Paint2BitmapShaderView.kt | 1 | 1366 | package com.zeke.demo.draw.paint
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import com.zeke.demo.R
import com.zeke.demo.base.BasePracticeView
import com.zeke.demo.model.CardItemConst
/**
* author: King.Z <br>
* date: 2020/3/15 14:27 <br>
* description: <br>
* 展示BitmapShader着色器的效果;
* 其实也就是用 Bitmap 的像素来作为图形或文字的填充.
*/
class Paint2BitmapShaderView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : BasePracticeView(context, attrs, defStyleAttr) {
var bitmap: Bitmap = BitmapFactory.decodeResource(resources, R.drawable.bg10)
private var shader: BitmapShader = BitmapShader(bitmap, // 用来做模板的 Bitmap 对象
Shader.TileMode.CLAMP, // 横向的 TileMode
Shader.TileMode.CLAMP) // 纵向的 TileMode
override fun onDraw(canvas: Canvas) {
// 练习内容:使用 BitmapShader 方法画自定义效果的Bitmap
super.onDraw(canvas)
paint.shader = shader
// 只画出circle范围内的Bitmap图像(bitmap为原尺寸大小),效果和Canvas.drawBitmap()一样
canvas.drawCircle(550f, 300f, 250f, paint)
}
override fun getViewHeight(): Int {
return CardItemConst.LARGE_HEIGHT
}
} | gpl-2.0 | 10c6c601f5ea6df34f17e535bcc76ef9 | 32.583333 | 81 | 0.701987 | 3.422096 | false | false | false | false |
googlearchive/android-FingerprintDialog | kotlinApp/app/src/main/java/com/example/android/fingerprintdialog/FingerprintUiHelper.kt | 3 | 3914 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License
*/
package com.example.android.fingerprintdialog
import android.hardware.fingerprint.FingerprintManager
import android.os.CancellationSignal
import android.widget.ImageView
import android.widget.TextView
/**
* Small helper class to manage text/icon around fingerprint authentication UI.
*/
class FingerprintUiHelper
/**
* Constructor for [FingerprintUiHelper].
*/
internal constructor(private val fingerprintMgr: FingerprintManager,
private val icon: ImageView,
private val errorTextView: TextView,
private val callback: Callback
) : FingerprintManager.AuthenticationCallback() {
private var cancellationSignal: CancellationSignal? = null
private var selfCancelled = false
val isFingerprintAuthAvailable: Boolean
get() = fingerprintMgr.isHardwareDetected && fingerprintMgr.hasEnrolledFingerprints()
private val resetErrorTextRunnable = Runnable {
icon.setImageResource(R.drawable.ic_fp_40px)
errorTextView.run {
setTextColor(errorTextView.resources.getColor(R.color.hint_color, null))
text = errorTextView.resources.getString(R.string.fingerprint_hint)
}
}
fun startListening(cryptoObject: FingerprintManager.CryptoObject) {
if (!isFingerprintAuthAvailable) return
cancellationSignal = CancellationSignal()
selfCancelled = false
fingerprintMgr.authenticate(cryptoObject, cancellationSignal, 0, this, null)
icon.setImageResource(R.drawable.ic_fp_40px)
}
fun stopListening() {
cancellationSignal?.also {
selfCancelled = true
it.cancel()
}
cancellationSignal = null
}
override fun onAuthenticationError(errMsgId: Int, errString: CharSequence) {
if (!selfCancelled) {
showError(errString)
icon.postDelayed({ callback.onError() }, ERROR_TIMEOUT_MILLIS)
}
}
override fun onAuthenticationHelp(helpMsgId: Int, helpString: CharSequence) =
showError(helpString)
override fun onAuthenticationFailed() =
showError(icon.resources.getString(R.string.fingerprint_not_recognized))
override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
errorTextView.run {
removeCallbacks(resetErrorTextRunnable)
setTextColor(errorTextView.resources.getColor(R.color.success_color, null))
text = errorTextView.resources.getString(R.string.fingerprint_success)
}
icon.run {
setImageResource(R.drawable.ic_fingerprint_success)
postDelayed({ callback.onAuthenticated() }, SUCCESS_DELAY_MILLIS)
}
}
private fun showError(error: CharSequence) {
icon.setImageResource(R.drawable.ic_fingerprint_error)
errorTextView.run {
text = error
setTextColor(errorTextView.resources.getColor(R.color.warning_color, null))
removeCallbacks(resetErrorTextRunnable)
postDelayed(resetErrorTextRunnable, ERROR_TIMEOUT_MILLIS)
}
}
interface Callback {
fun onAuthenticated()
fun onError()
}
companion object {
val ERROR_TIMEOUT_MILLIS: Long = 1600
val SUCCESS_DELAY_MILLIS: Long = 1300
}
}
| apache-2.0 | 0a82bd1128ac8a6ae02284919b63ea4a | 33.946429 | 93 | 0.698263 | 4.886392 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/core/frontendIndependentPsiUtils.kt | 1 | 1167 | // 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.core
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtParenthesizedExpression
import org.jetbrains.kotlin.psi.KtPsiUtil
inline fun <reified T : PsiElement> PsiElement.replaced(newElement: T): T {
if (this == newElement) return newElement
val result = replace(newElement)
return result as? T ?: (result as KtParenthesizedExpression).expression as T
}
fun KtExpression.dropEnclosingParenthesesIfPossible(): KtExpression {
val innermostExpression = this
var current = innermostExpression
while (true) {
val parent = current.parent as? KtParenthesizedExpression ?: break
if (!KtPsiUtil.areParenthesesUseless(parent)) break
current = parent
}
return current.replaced(innermostExpression)
}
//todo make inline
@Suppress("UNCHECKED_CAST")
fun <T : PsiElement> T.copied(): T = copy() as T
fun String.unquote(): String = KtPsiUtil.unquoteIdentifier(this)
| apache-2.0 | 9255c5e6ca38c17c522807d610ba5e73 | 35.46875 | 158 | 0.75407 | 4.33829 | false | false | false | false |
jwren/intellij-community | uast/uast-java/src/org/jetbrains/uast/java/generate/JavaUastCodeGenerationPlugin.kt | 3 | 22057 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.uast.java.generate
import com.intellij.codeInsight.BlockUtils
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.lang.jvm.JvmModifier
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
import com.intellij.psi.codeStyle.JavaCodeStyleManager
import com.intellij.psi.codeStyle.VariableKind
import com.intellij.psi.impl.PsiDiamondTypeUtil
import com.intellij.psi.impl.source.tree.CompositeElement
import com.intellij.psi.impl.source.tree.ElementType
import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl
import com.intellij.psi.util.PsiTypesUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.util.elementType
import com.intellij.psi.util.siblings
import com.intellij.util.castSafelyTo
import com.siyeh.ig.psiutils.ParenthesesUtils
import org.jetbrains.uast.*
import org.jetbrains.uast.generate.UParameterInfo
import org.jetbrains.uast.generate.UastCodeGenerationPlugin
import org.jetbrains.uast.generate.UastElementFactory
import org.jetbrains.uast.java.*
internal class JavaUastCodeGenerationPlugin : UastCodeGenerationPlugin {
override fun getElementFactory(project: Project): UastElementFactory = JavaUastElementFactory(project)
override val language: Language
get() = JavaLanguage.INSTANCE
private fun cleanupMethodCall(methodCall: PsiMethodCallExpression): PsiMethodCallExpression {
if (methodCall.typeArguments.isNotEmpty()) {
val resolved = methodCall.resolveMethod() ?: return methodCall
if (methodCall.typeArguments.size == resolved.typeParameters.size &&
PsiDiamondTypeUtil.areTypeArgumentsRedundant(
methodCall.typeArguments,
methodCall,
false,
resolved,
resolved.typeParameters
)
) {
val emptyTypeArgumentsMethodCall = JavaPsiFacade.getElementFactory(methodCall.project)
.createExpressionFromText("foo()", null) as PsiMethodCallExpression
methodCall.typeArgumentList.replace(emptyTypeArgumentsMethodCall.typeArgumentList)
}
}
return JavaCodeStyleManager.getInstance(methodCall.project).shortenClassReferences(methodCall) as PsiMethodCallExpression
}
private fun adjustChainStyleToMethodCalls(oldPsi: PsiElement, newPsi: PsiElement) {
if (oldPsi is PsiMethodCallExpression && newPsi is PsiMethodCallExpression &&
oldPsi.methodExpression.qualifierExpression != null && newPsi.methodExpression.qualifier != null) {
if (oldPsi.methodExpression.children.getOrNull(1) is PsiWhiteSpace &&
newPsi.methodExpression.children.getOrNull(1) !is PsiWhiteSpace
) {
newPsi.methodExpression.addAfter(oldPsi.methodExpression.children[1], newPsi.methodExpression.children[0])
}
}
}
override fun <T : UElement> replace(oldElement: UElement, newElement: T, elementType: Class<T>): T? {
val oldPsi = oldElement.sourcePsi ?: return null
val newPsi = newElement.sourcePsi ?: return null
adjustChainStyleToMethodCalls(oldPsi, newPsi)
val factory = JavaPsiFacade.getElementFactory(oldPsi.project)
val updOldPsi = when {
(newPsi is PsiBlockStatement || newPsi is PsiCodeBlock) && oldPsi.parent is PsiExpressionStatement -> oldPsi.parent
else -> oldPsi
}
val updNewPsi = when {
updOldPsi is PsiStatement && newPsi is PsiExpression -> factory.createExpressionStatement(newPsi) ?: return null
updOldPsi is PsiCodeBlock && newPsi is PsiBlockStatement -> newPsi.codeBlock
else -> newPsi
}
return when (val replaced = updOldPsi.replace(updNewPsi)) {
is PsiExpressionStatement -> replaced.expression.toUElementOfExpectedTypes(elementType)
is PsiMethodCallExpression -> cleanupMethodCall(replaced).toUElementOfExpectedTypes(elementType)
is PsiMethodReferenceExpression -> {
JavaCodeStyleManager.getInstance(replaced.project).shortenClassReferences(replaced).toUElementOfExpectedTypes(elementType)
}
else -> replaced.toUElementOfExpectedTypes(elementType)
}
}
override fun bindToElement(reference: UReferenceExpression, element: PsiElement): PsiElement? {
val sourceReference = reference.sourcePsi ?: return null
if (sourceReference !is PsiReference) return null
return sourceReference.bindToElement(element)
}
override fun shortenReference(reference: UReferenceExpression): UReferenceExpression? {
val sourceReference = reference.sourcePsi ?: return null
val styleManager = JavaCodeStyleManager.getInstance(sourceReference.project)
return styleManager.shortenClassReferences(sourceReference).toUElementOfType()
}
}
private fun PsiElementFactory.createExpressionStatement(expression: PsiExpression): PsiStatement? {
val statement = createStatementFromText("x;", null) as? PsiExpressionStatement ?: return null
statement.expression.replace(expression)
return statement
}
class JavaUastElementFactory(private val project: Project) : UastElementFactory {
private val psiFactory: PsiElementFactory = JavaPsiFacade.getElementFactory(project)
override fun createQualifiedReference(qualifiedName: String, context: PsiElement?): UQualifiedReferenceExpression? {
return psiFactory.createExpressionFromText(qualifiedName, context)
.castSafelyTo<PsiReferenceExpression>()
?.let { JavaUQualifiedReferenceExpression(it, null) }
}
override fun createIfExpression(condition: UExpression,
thenBranch: UExpression,
elseBranch: UExpression?,
context: PsiElement?): UIfExpression? {
val conditionPsi = condition.sourcePsi ?: return null
val thenBranchPsi = thenBranch.sourcePsi ?: return null
val ifStatement = psiFactory.createStatementFromText("if (a) b else c", null) as? PsiIfStatement ?: return null
ifStatement.condition?.replace(conditionPsi)
ifStatement.thenBranch?.replace(thenBranchPsi.branchStatement ?: return null)
elseBranch?.sourcePsi?.branchStatement?.let { ifStatement.elseBranch?.replace(it) } ?: ifStatement.elseBranch?.delete()
return JavaUIfExpression(ifStatement, null)
}
override fun createCallExpression(receiver: UExpression?,
methodName: String,
parameters: List<UExpression>,
expectedReturnType: PsiType?,
kind: UastCallKind,
context: PsiElement?): UCallExpression? {
if (kind != UastCallKind.METHOD_CALL) return null
val methodCall = psiFactory.createExpressionFromText(
createCallExpressionTemplateRespectingChainStyle(receiver), context
) as? PsiMethodCallExpression ?: return null
val methodIdentifier = psiFactory.createIdentifier(methodName)
if (receiver != null) {
methodCall.methodExpression.qualifierExpression?.replace(receiver.sourcePsi!!)
}
methodCall.methodExpression.referenceNameElement?.replace(methodIdentifier)
for (parameter in parameters) {
methodCall.argumentList.add(parameter.sourcePsi!!)
}
return if (expectedReturnType == null)
methodCall.toUElementOfType()
else
MethodCallUpgradeHelper(project, methodCall, expectedReturnType).tryUpgradeToExpectedType()
?.let { JavaUCallExpression(it, null) }
}
private fun createCallExpressionTemplateRespectingChainStyle(receiver: UExpression?): String {
if (receiver == null) return "a()"
val siblings = receiver.sourcePsi?.siblings(withSelf = false) ?: return "a.b()"
(siblings.firstOrNull() as? PsiWhiteSpace)?.let { whitespace ->
return "a${whitespace.text}.b()"
}
if (siblings.firstOrNull()?.elementType == ElementType.DOT) {
(siblings.elementAt(2) as? PsiWhiteSpace)?.let { whitespace ->
return "a.${whitespace.text}b()"
}
}
return "a.b()"
}
override fun createCallableReferenceExpression(
receiver: UExpression?,
methodName: String,
context: PsiElement?
): UCallableReferenceExpression? {
val receiverSource = receiver?.sourcePsi
requireNotNull(receiverSource) { "Receiver should not be null for Java callable references." }
val callableExpression = psiFactory.createExpressionFromText("${receiverSource.text}::$methodName", context)
if (callableExpression !is PsiMethodReferenceExpression) return null
return JavaUCallableReferenceExpression(callableExpression, null)
}
override fun createStringLiteralExpression(text: String, context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText(StringUtil.wrapWithDoubleQuote(text), context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
override fun createLongConstantExpression(long: Long, context: PsiElement?): UExpression? {
return when (val literalExpr = psiFactory.createExpressionFromText(long.toString() + "L", context)) {
is PsiLiteralExpressionImpl -> JavaULiteralExpression(literalExpr, null)
is PsiPrefixExpression -> JavaUPrefixExpression(literalExpr, null)
else -> null
}
}
override fun createNullLiteral(context: PsiElement?): ULiteralExpression? {
val literalExpr = psiFactory.createExpressionFromText("null", context)
if (literalExpr !is PsiLiteralExpressionImpl) return null
return JavaULiteralExpression(literalExpr, null)
}
private class MethodCallUpgradeHelper(val project: Project, val methodCall: PsiMethodCallExpression, val expectedReturnType: PsiType) {
lateinit var resultType: PsiType
fun tryUpgradeToExpectedType(): PsiMethodCallExpression? {
resultType = methodCall.type ?: return null
if (expectedReturnType.isAssignableFrom(resultType)) return methodCall
if (!(resultType eqResolved expectedReturnType))
return null
return methodCall.methodExpression.qualifierExpression?.let { tryPickUpTypeParameters() }
}
private fun tryPickUpTypeParameters(): PsiMethodCallExpression? {
val expectedTypeTypeParameters = expectedReturnType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val resultTypeTypeParameters = resultType.castSafelyTo<PsiClassType>()?.parameters ?: return null
val notEqualTypeParametersIndices = expectedTypeTypeParameters
.zip(resultTypeTypeParameters)
.withIndex()
.filterNot { (_, pair) -> PsiTypesUtil.compareTypes(pair.first, pair.second, false) }
.map { (i, _) -> i }
val resolvedMethod = methodCall.resolveMethod() ?: return null
val methodReturnTypeTypeParameters = (resolvedMethod.returnType.castSafelyTo<PsiClassType>())?.parameters ?: return null
val methodDefinitionTypeParameters = resolvedMethod.typeParameters
val methodDefinitionToReturnTypeParametersMapping = methodDefinitionTypeParameters.map {
it to methodReturnTypeTypeParameters.indexOfFirst { param -> it.name == param.canonicalText }
}
.filter { it.second != -1 }
.toMap()
val notMatchedTypesParametersNames = notEqualTypeParametersIndices
.map { methodReturnTypeTypeParameters[it].canonicalText }
.toSet()
val callTypeParametersSubstitutor = methodCall.resolveMethodGenerics().substitutor
val newParametersList = mutableListOf<PsiType>()
for (parameter in methodDefinitionTypeParameters) {
if (parameter.name in notMatchedTypesParametersNames) {
newParametersList += expectedTypeTypeParameters[methodDefinitionToReturnTypeParametersMapping[parameter] ?: return null]
}
else {
newParametersList += callTypeParametersSubstitutor.substitute(parameter) ?: return null
}
}
return buildMethodCallFromNewTypeParameters(newParametersList)
}
private fun buildMethodCallFromNewTypeParameters(newParametersList: List<PsiType>): PsiMethodCallExpression? {
val factory = JavaPsiFacade.getElementFactory(project)
val expr = factory.createExpressionFromText(buildString {
append("a.<")
newParametersList.joinTo(this) { "T" }
append(">b()")
}, null) as? PsiMethodCallExpression ?: return null
for ((i, param) in newParametersList.withIndex()) {
val typeElement = factory.createTypeElement(param)
expr.typeArgumentList.typeParameterElements[i].replace(typeElement)
}
methodCall.typeArgumentList.replace(expr.typeArgumentList)
if (methodCall.type?.let { expectedReturnType.isAssignableFrom(it) } != true)
return null
return methodCall
}
infix fun PsiType.eqResolved(other: PsiType): Boolean {
val resolvedThis = this.castSafelyTo<PsiClassType>()?.resolve() ?: return false
val resolvedOther = other.castSafelyTo<PsiClassType>()?.resolve() ?: return false
return PsiManager.getInstance(project).areElementsEquivalent(resolvedThis, resolvedOther)
}
}
override fun createDeclarationExpression(declarations: List<UDeclaration>, context: PsiElement?): UDeclarationsExpression {
return JavaUDeclarationsExpression(null, declarations)
}
override fun createReturnExpresion(expression: UExpression?,
inLambda: Boolean,
context: PsiElement?): UReturnExpression? {
val returnStatement = psiFactory.createStatementFromText("return ;", null) as? PsiReturnStatement ?: return null
expression?.sourcePsi?.node?.let { (returnStatement as CompositeElement).addChild(it, returnStatement.lastChild.node) }
return JavaUReturnExpression(returnStatement, null)
}
private fun PsiVariable.setMutability(immutable: Boolean) {
if (immutable && !this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, true)
}
if (!immutable && this.hasModifier(JvmModifier.FINAL)) {
PsiUtil.setModifierProperty(this, PsiModifier.FINAL, false)
}
}
override fun createLocalVariable(suggestedName: String?,
type: PsiType?,
initializer: UExpression,
immutable: Boolean,
context: PsiElement?): ULocalVariable? {
val initializerPsi = initializer.sourcePsi as? PsiExpression ?: return null
val name = createNameFromSuggested(
suggestedName,
VariableKind.LOCAL_VARIABLE,
type,
initializer = initializerPsi,
context = initializerPsi
) ?: return null
val variable = (type ?: initializer.getExpressionType())?.let { variableType ->
psiFactory.createVariableDeclarationStatement(
name,
variableType,
initializerPsi,
initializerPsi.context
).declaredElements.firstOrNull() as? PsiLocalVariable
} ?: return null
variable.setMutability(immutable)
return JavaULocalVariable(variable, null)
}
override fun createBlockExpression(expressions: List<UExpression>, context: PsiElement?): UBlockExpression? {
val blockStatement = BlockUtils.createBlockStatement(project)
for (expression in expressions) {
if (expression is JavaUDeclarationsExpression) {
for (declaration in expression.declarations) {
if (declaration.sourcePsi is PsiLocalVariable) {
blockStatement.codeBlock.add(declaration.sourcePsi?.parent as? PsiDeclarationStatement ?: return null)
}
}
continue
}
expression.sourcePsi?.let { psi ->
psi as? PsiStatement ?: (psi as? PsiExpression)?.let { psiFactory.createExpressionStatement(it) }
}?.let { blockStatement.codeBlock.add(it) } ?: return null
}
return JavaUBlockExpression(blockStatement, null)
}
override fun createLambdaExpression(parameters: List<UParameterInfo>, body: UExpression, context: PsiElement?): ULambdaExpression? {
//TODO: smart handling cases, when parameters types should exist in code
val lambda = psiFactory.createExpressionFromText(
buildString {
parameters.joinTo(this, separator = ",", prefix = "(", postfix = ")") { "x x" }
append("->{}")
},
null
) as? PsiLambdaExpression ?: return null
val needsType = parameters.all { it.type != null }
lambda.parameterList.parameters.forEachIndexed { i, parameter ->
parameters[i].also { parameterInfo ->
val name = createNameFromSuggested(
parameterInfo.suggestedName,
VariableKind.PARAMETER,
parameterInfo.type,
context = body.sourcePsi
) ?: return null
parameter.nameIdentifier?.replace(psiFactory.createIdentifier(name))
if (needsType) {
parameter.typeElement?.replace(psiFactory.createTypeElement(parameterInfo.type!!))
}
else {
parameter.removeTypeElement()
}
}
}
if (lambda.parameterList.parametersCount == 1) {
lambda.parameterList.parameters[0].removeTypeElement()
lambda.parameterList.firstChild.delete()
lambda.parameterList.lastChild.delete()
}
val normalizedBody = when (val bodyPsi = body.sourcePsi) {
is PsiExpression -> bodyPsi
is PsiCodeBlock -> normalizeBlockForLambda(bodyPsi)
is PsiBlockStatement -> normalizeBlockForLambda(bodyPsi.codeBlock)
else -> return null
}
lambda.body?.replace(normalizedBody) ?: return null
return JavaULambdaExpression(lambda, null)
}
private fun normalizeBlockForLambda(block: PsiCodeBlock): PsiElement =
block
.takeIf { block.statementCount == 1 }
?.let { block.statements[0] as? PsiReturnStatement }
?.returnValue
?: block
override fun createParenthesizedExpression(expression: UExpression, context: PsiElement?): UParenthesizedExpression? {
val parenthesizedExpression = psiFactory.createExpressionFromText("()", null) as? PsiParenthesizedExpression ?: return null
parenthesizedExpression.children.getOrNull(1)?.replace(expression.sourcePsi ?: return null) ?: return null
return JavaUParenthesizedExpression(parenthesizedExpression, null)
}
override fun createSimpleReference(name: String, context: PsiElement?): USimpleNameReferenceExpression {
val reference = psiFactory.createExpressionFromText(name, null)
return JavaUSimpleNameReferenceExpression(reference, name, null)
}
override fun createSimpleReference(variable: UVariable, context: PsiElement?): USimpleNameReferenceExpression? {
return createSimpleReference(variable.name ?: return null, context)
}
override fun createBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UBinaryExpression? {
val leftPsi = leftOperand.sourcePsi ?: return null
val rightPsi = rightOperand.sourcePsi ?: return null
val operatorSymbol = when (operator) {
UastBinaryOperator.LOGICAL_AND -> "&&"
UastBinaryOperator.PLUS -> "+"
else -> return null
}
val psiBinaryExpression = psiFactory.createExpressionFromText("a $operatorSymbol b", null) as? PsiBinaryExpression
?: return null
psiBinaryExpression.lOperand.replace(leftPsi)
psiBinaryExpression.rOperand?.replace(rightPsi)
return JavaUBinaryExpression(psiBinaryExpression, null)
}
override fun createFlatBinaryExpression(leftOperand: UExpression,
rightOperand: UExpression,
operator: UastBinaryOperator,
context: PsiElement?): UPolyadicExpression? {
val binaryExpression = createBinaryExpression(leftOperand, rightOperand, operator, context) ?: return null
val binarySourcePsi = binaryExpression.sourcePsi as? PsiBinaryExpression ?: return null
val dummyParent = psiFactory.createStatementFromText("a;", null)
dummyParent.firstChild.replace(binarySourcePsi)
ParenthesesUtils.removeParentheses(dummyParent.firstChild as PsiExpression, false)
return when (val result = dummyParent.firstChild) {
is PsiBinaryExpression -> JavaUBinaryExpression(result, null)
is PsiPolyadicExpression -> JavaUPolyadicExpression(result, null)
else -> error("Unexpected type " + result.javaClass)
}
}
private val PsiElement.branchStatement: PsiStatement?
get() = when (this) {
is PsiExpression -> JavaPsiFacade.getElementFactory(project).createExpressionStatement(this)
is PsiCodeBlock -> BlockUtils.createBlockStatement(project).also { it.codeBlock.replace(this) }
is PsiStatement -> this
else -> null
}
private fun PsiVariable.removeTypeElement() {
this.typeElement?.delete()
if (this.children.getOrNull(1) !is PsiIdentifier) {
this.children.getOrNull(1)?.delete()
}
}
private fun createNameFromSuggested(suggestedName: String?,
variableKind: VariableKind,
type: PsiType? = null,
initializer: PsiExpression? = null,
context: PsiElement? = null): String? {
val codeStyleManager = JavaCodeStyleManager.getInstance(project)
val name = suggestedName ?: codeStyleManager.generateVariableName(type, initializer, variableKind) ?: return null
return codeStyleManager.suggestUniqueVariableName(name, context, false)
}
private fun JavaCodeStyleManager.generateVariableName(type: PsiType?, initializer: PsiExpression?, kind: VariableKind) =
suggestVariableName(kind, null, initializer, type).names.firstOrNull()
} | apache-2.0 | 41bc8a896d03737253c76c89e6d5af34 | 42.852883 | 137 | 0.714014 | 5.586879 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/export/remote/FolderRemoteDatabase.kt | 1 | 5860 | package com.maubis.scarlet.base.export.remote
import android.content.Context
import android.os.Environment
import com.maubis.scarlet.base.core.folder.IFolderContainer
import com.maubis.scarlet.base.core.note.INoteContainer
import com.maubis.scarlet.base.core.note.NoteState
import com.maubis.scarlet.base.core.tag.ITagContainer
import com.maubis.scarlet.base.database.remote.IRemoteDatabase
import com.maubis.scarlet.base.database.remote.IRemoteDatabaseUtils
import com.maubis.scarlet.base.export.data.ExportableFolder
import com.maubis.scarlet.base.export.data.ExportableNote
import com.maubis.scarlet.base.export.data.ExportableTag
import com.maubis.scarlet.base.export.support.sFolderSyncBackupLocked
import com.maubis.scarlet.base.export.support.sFolderSyncPath
import java.io.File
import java.lang.ref.WeakReference
class FolderRemoteDatabase(val weakContext: WeakReference<Context>) : IRemoteDatabase {
private var isValidController: Boolean = true
private var rootFolder: File? = null
private var notesRemoteFolder: RemoteFolder<ExportableNote>? = null
private var tagsRemoteFolder: RemoteFolder<ExportableTag>? = null
private var foldersRemoteFolder: RemoteFolder<ExportableFolder>? = null
private var remoteImagesFolder: RemoteImagesFolder? = null
override fun init(userId: String) {}
fun init(onNotesInit: () -> Unit = {}, onTagsInit: () -> Unit = {}, onFoldersInit: () -> Unit = {}) {
isValidController = true
rootFolder = File(Environment.getExternalStorageDirectory(), sFolderSyncPath)
val notesFolder = File(rootFolder, "notes")
notesRemoteFolder = RemoteFolder(
notesFolder,
ExportableNote::class.java,
{ it -> onRemoteInsert(it) },
{ it -> onRemoteRemove(ExportableNote(it, "", 0L, 0L, 0, NoteState.DEFAULT.name, "", emptyMap(), "")) },
onNotesInit)
tagsRemoteFolder = RemoteFolder(
File(rootFolder, "tags"),
ExportableTag::class.java,
{ it -> onRemoteInsert(it) },
{ it -> onRemoteRemove(ExportableTag(it, "")) },
onTagsInit)
foldersRemoteFolder = RemoteFolder(
File(rootFolder, "folders"),
ExportableFolder::class.java,
{ it -> onRemoteInsert(it) },
{ it -> onRemoteRemove(ExportableFolder(it, "", 0L, 0L, 0)) },
onFoldersInit)
val context = weakContext.get()
if (context !== null) {
remoteImagesFolder = RemoteImagesFolder(context, File(notesFolder, "images"))
}
}
override fun reset() {
isValidController = false
notesRemoteFolder = null
tagsRemoteFolder = null
foldersRemoteFolder = null
remoteImagesFolder = null
}
override fun logout() {
reset()
}
override fun deleteEverything() {
if (!isValidController) {
return
}
notesRemoteFolder?.deleteEverything()
tagsRemoteFolder?.deleteEverything()
foldersRemoteFolder?.deleteEverything()
remoteImagesFolder?.deleteEverything()
}
override fun insert(note: INoteContainer) {
if (!isValidController || note !is ExportableNote) {
return
}
if (note.locked() && sFolderSyncBackupLocked) {
notesRemoteFolder?.lock(note.uuid())
}
notesRemoteFolder?.insert(note.uuid(), note)
remoteImagesFolder?.onInsert(note)
}
override fun insert(tag: ITagContainer) {
if (!isValidController || tag !is ExportableTag) {
return
}
tagsRemoteFolder?.insert(tag.uuid(), tag)
}
override fun insert(folder: IFolderContainer) {
if (!isValidController || folder !is ExportableFolder) {
return
}
foldersRemoteFolder?.insert(folder.uuid(), folder)
}
override fun remove(note: INoteContainer) {
if (!isValidController || note !is ExportableNote) {
return
}
notesRemoteFolder?.delete(note.uuid())
remoteImagesFolder?.onRemove(note.uuid())
}
override fun remove(tag: ITagContainer) {
if (!isValidController || tag !is ExportableTag) {
return
}
tagsRemoteFolder?.delete(tag.uuid())
}
override fun remove(folder: IFolderContainer) {
if (!isValidController || folder !is ExportableFolder) {
return
}
foldersRemoteFolder?.delete(folder.uuid())
}
override fun onRemoteInsert(note: INoteContainer) {
if (!isValidController || note !is ExportableNote) {
return
}
val context = weakContext.get()
if (context === null) {
return
}
IRemoteDatabaseUtils.onRemoteInsert(context, note)
remoteImagesFolder?.onRemoteInsert(note)
}
override fun onRemoteRemove(note: INoteContainer) {
if (!isValidController || note !is ExportableNote) {
return
}
val context = weakContext.get()
if (context === null) {
return
}
IRemoteDatabaseUtils.onRemoteRemove(context, note)
}
override fun onRemoteInsert(tag: ITagContainer) {
if (!isValidController || tag !is ExportableTag) {
return
}
val context = weakContext.get()
if (context === null) {
return
}
IRemoteDatabaseUtils.onRemoteInsert(context, tag)
}
override fun onRemoteRemove(tag: ITagContainer) {
if (!isValidController || tag !is ExportableTag) {
return
}
val context = weakContext.get()
if (context === null) {
return
}
IRemoteDatabaseUtils.onRemoteRemove(context, tag)
}
override fun onRemoteInsert(folder: IFolderContainer) {
if (!isValidController || folder !is ExportableFolder) {
return
}
val context = weakContext.get()
if (context === null) {
return
}
IRemoteDatabaseUtils.onRemoteInsert(context, folder)
}
override fun onRemoteRemove(folder: IFolderContainer) {
if (!isValidController || folder !is ExportableFolder) {
return
}
val context = weakContext.get()
if (context === null) {
return
}
IRemoteDatabaseUtils.onRemoteRemove(context, folder)
}
} | gpl-3.0 | a13440f72c32ed8e198428fdb31d2377 | 28.014851 | 110 | 0.692491 | 4.038594 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/localEscapeAnalysis/arraysFieldWrite.kt | 4 | 1784 | /*
* Copyright 2010-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.
*/
class ArraysConstructor {
private val memberArray: IntArray
constructor(int1: Int, int2: Int) {
memberArray = IntArray(2)
set(int1, int2)
}
fun set(int1: Int, int2: Int) {
memberArray[0] = int1
memberArray[1] = int2
}
fun log() {
println("Array (constructor init):")
println("Size: ${memberArray.size}")
println("Contents: ${memberArray.contentToString()}")
}
}
class ArraysDefault {
private val memberArray = IntArray(2)
constructor(int1: Int, int2: Int) {
set(int1, int2)
}
fun set(int1: Int, int2: Int) {
memberArray[0] = int1
memberArray[1] = int2
}
fun log() {
println("Array (default value init):")
println("Size: ${memberArray.size}")
println("Contents: ${memberArray.contentToString()}")
}
}
class ArraysInitBlock {
private val memberArray : IntArray
init {
memberArray = IntArray(2)
}
constructor(int1: Int, int2: Int) {
set(int1, int2)
}
fun set(int1: Int, int2: Int) {
memberArray[0] = int1
memberArray[1] = int2
}
fun log() {
println("Array (init block):")
println("Size: ${memberArray.size}")
println("Contents: ${memberArray.contentToString()}")
}
}
fun main() {
val array1 = (::ArraysConstructor)(1, 2)
array1.log()
array1.set( 3, 4)
array1.log()
val array2 = (::ArraysDefault)(1, 2)
array2.log()
array2.set( 3, 4)
array2.log()
val array3 = (::ArraysInitBlock)(1, 2)
array3.log()
array3.set( 3, 4)
array3.log()
} | apache-2.0 | e59784c98f3bdf88d5edd91fdd07dd43 | 23.452055 | 101 | 0.577915 | 3.450677 | false | false | false | false |
androidx/androidx | annotation/annotation/src/commonMain/kotlin/androidx/annotation/StringDef.kt | 3 | 1823 | /*
* Copyright (C) 2014 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.annotation
/**
* Denotes that the annotated String element, represents a logical
* type and that its value should be one of the explicitly named constants.
*
* Example:
* ```
* @Retention(SOURCE)
* @StringDef({
* POWER_SERVICE,
* WINDOW_SERVICE,
* LAYOUT_INFLATER_SERVICE
* })
* public @interface ServiceName {}
* public static final String POWER_SERVICE = "power";
* public static final String WINDOW_SERVICE = "window";
* public static final String LAYOUT_INFLATER_SERVICE = "layout_inflater";
* ...
* public abstract Object getSystemService(@ServiceName String name);
* ```
*/
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.ANNOTATION_CLASS)
public annotation class StringDef(
/** Defines the allowed constants for this element */
vararg val value: String = [],
/**
* Whether any other values are allowed. Normally this is
* not the case, but this allows you to specify a set of
* expected constants, which helps code completion in the IDE
* and documentation generation and so on, but without
* flagging compilation warnings if other values are specified.
*/
val open: Boolean = false
) | apache-2.0 | 569ab0b8116c55fbd9995cec6a646466 | 34.764706 | 75 | 0.715853 | 4.361244 | false | false | false | false |
nimakro/tornadofx | src/main/java/tornadofx/Dialogs.kt | 1 | 4761 | package tornadofx
import javafx.scene.control.Alert
import javafx.scene.control.ButtonType
import javafx.scene.control.Dialog
import javafx.stage.DirectoryChooser
import javafx.stage.FileChooser
import javafx.stage.Stage
import javafx.stage.Window
import tornadofx.FileChooserMode.*
import java.io.File
/**
* Show a confirmation dialog and execute the given action if confirmButton is clicked. The button types
* of the confirmButton and cancelButton are configurable.
*/
inline fun confirm(header: String, content: String = "", confirmButton: ButtonType = ButtonType.OK, cancelButton: ButtonType = ButtonType.CANCEL, owner: Window? = null, title: String? = null, actionFn: () -> Unit) {
alert(Alert.AlertType.CONFIRMATION, header, content, confirmButton, cancelButton, owner = owner, title = title) {
if (it == confirmButton) actionFn()
}
}
/**
* Show an alert dialog of the given type with the given header and content.
* You can override the default buttons for the alert type and supply an optional
* function that will run when a button is clicked. The function runs in the scope
* of the alert dialog and is passed the button that was clicked.
*
* You can optionally pass an owner window parameter.
*/
inline fun alert(type: Alert.AlertType,
header: String,
content: String? = null,
vararg buttons: ButtonType,
owner: Window? = null,
title: String? = null,
actionFn: Alert.(ButtonType) -> Unit = {}): Alert {
val alert = Alert(type, content ?: "", *buttons)
title?.let { alert.title = it }
alert.headerText = header
owner?.also { alert.initOwner(it) }
val buttonClicked = alert.showAndWait()
if (buttonClicked.isPresent) {
alert.actionFn(buttonClicked.get())
}
return alert
}
inline fun warning(header: String, content: String? = null, vararg buttons: ButtonType, owner: Window? = null, title: String? = null, actionFn: Alert.(ButtonType) -> Unit = {}) =
alert(Alert.AlertType.WARNING, header, content, *buttons, owner = owner, title = title, actionFn = actionFn)
inline fun error(header: String, content: String? = null, vararg buttons: ButtonType, owner: Window? = null, title: String? = null, actionFn: Alert.(ButtonType) -> Unit = {}) =
alert(Alert.AlertType.ERROR, header, content, *buttons, owner = owner, title = title, actionFn = actionFn)
inline fun information(header: String, content: String? = null, vararg buttons: ButtonType, owner: Window? = null, title: String? = null, actionFn: Alert.(ButtonType) -> Unit = {}) =
alert(Alert.AlertType.INFORMATION, header, content, *buttons, owner = owner, title = title, actionFn = actionFn)
inline fun confirmation(header: String, content: String? = null, vararg buttons: ButtonType, owner: Window? = null, title: String? = null, actionFn: Alert.(ButtonType) -> Unit = {}) =
alert(Alert.AlertType.CONFIRMATION, header, content, *buttons, owner = owner, title = title, actionFn = actionFn)
enum class FileChooserMode { None, Single, Multi, Save }
/**
* Ask the user to select one or more files from a file chooser dialog. The mode will dictate how the dialog works,
* by allowing single selection, multi selection or save functionality. The file dialog will only allow files
* that match one of the given ExtensionFilters.
*
* This function blocks until the user has made a selection, and can optionally block a specified owner Window.
*
* If the user cancels, the returnedfile list will be empty.
*/
fun chooseFile(title: String? = null, filters: Array<FileChooser.ExtensionFilter>, mode: FileChooserMode = Single, owner: Window? = null, op: FileChooser.() -> Unit = {}): List<File> {
val chooser = FileChooser()
if (title != null) chooser.title = title
chooser.extensionFilters.addAll(filters)
op(chooser)
return when (mode) {
Single -> {
val result = chooser.showOpenDialog(owner)
if (result == null) emptyList() else listOf(result)
}
Multi -> chooser.showOpenMultipleDialog(owner) ?: emptyList()
Save -> {
val result = chooser.showSaveDialog(owner)
if (result == null) emptyList() else listOf(result)
}
else -> emptyList()
}
}
fun chooseDirectory(title: String? = null, initialDirectory: File? = null, owner: Window? = null, op: DirectoryChooser.() -> Unit = {}): File? {
val chooser = DirectoryChooser()
if (title != null) chooser.title = title
if (initialDirectory != null) chooser.initialDirectory = initialDirectory
op(chooser)
return chooser.showDialog(owner)
}
fun Dialog<*>.toFront() = (dialogPane.scene.window as? Stage)?.toFront() | apache-2.0 | 726815c563e852ef6799ccab99e41a43 | 46.62 | 215 | 0.687671 | 4.187335 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/symbols/KtFirPropertyGetterSymbol.kt | 2 | 3615 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.fir.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.impl.FirDefaultPropertyAccessor
import org.jetbrains.kotlin.idea.fir.findPsi
import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState
import org.jetbrains.kotlin.idea.frontend.api.ValidityToken
import org.jetbrains.kotlin.idea.frontend.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.containsAnnotation
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.getAnnotationClassIds
import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.annotations.toAnnotationsList
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.cached
import org.jetbrains.kotlin.idea.frontend.api.fir.utils.firRef
import org.jetbrains.kotlin.idea.frontend.api.symbols.KtPropertyGetterSymbol
import org.jetbrains.kotlin.idea.frontend.api.symbols.markers.*
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtPsiBasedSymbolPointer
import org.jetbrains.kotlin.idea.frontend.api.symbols.pointers.KtSymbolPointer
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.idea.frontend.api.types.KtType
internal class KtFirPropertyGetterSymbol(
fir: FirPropertyAccessor,
resolveState: FirModuleResolveState,
override val token: ValidityToken,
private val builder: KtSymbolByFirBuilder,
) : KtPropertyGetterSymbol(), KtFirSymbol<FirPropertyAccessor> {
init {
require(fir.isGetter)
}
override val firRef = firRef(fir, resolveState)
override val psi: PsiElement? by firRef.withFirAndCache { fir -> fir.findPsi(fir.session) }
override val isDefault: Boolean get() = firRef.withFir { it is FirDefaultPropertyAccessor }
override val isInline: Boolean get() = firRef.withFir { it.isInline }
override val isOverride: Boolean get() = firRef.withFir { it.isOverride }
override val hasBody: Boolean get() = firRef.withFir { it.body != null }
override val symbolKind: KtSymbolKind
get() = firRef.withFir { fir ->
when (fir.symbol.callableId.classId) {
null -> KtSymbolKind.TOP_LEVEL
else -> KtSymbolKind.MEMBER
}
}
override val annotatedType: KtTypeAndAnnotations by cached {
firRef.returnTypeAndAnnotations(FirResolvePhase.IMPLICIT_TYPES_BODY_RESOLVE, builder)
}
override val modality: KtCommonSymbolModality get() = firRef.withFir(FirResolvePhase.STATUS) { it.modality.getSymbolModality() }
override val visibility: KtSymbolVisibility get() = firRef.withFir(FirResolvePhase.STATUS) { it.visibility.getSymbolVisibility() }
override val annotations: List<KtAnnotationCall> by cached { firRef.toAnnotationsList() }
override fun containsAnnotation(classId: ClassId): Boolean = firRef.containsAnnotation(classId)
override val annotationClassIds: Collection<ClassId> by cached { firRef.getAnnotationClassIds() }
override val dispatchType: KtType? by cached {
firRef.dispatchReceiverTypeAndAnnotations(builder)
}
override fun createPointer(): KtSymbolPointer<KtPropertyGetterSymbol> {
KtPsiBasedSymbolPointer.createForSymbolFromSource(this)?.let { return it }
TODO("Creating pointers for getters from library is not supported yet")
}
} | apache-2.0 | a13a7d2e0fdb4c2546b6d14b3bd408ae | 49.929577 | 134 | 0.77455 | 4.581749 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.