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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dahlstrom-g/intellij-community | plugins/git4idea/src/git4idea/branch/GitShowDiffWithBranchPanel.kt | 2 | 3733 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package git4idea.branch
import com.intellij.dvcs.ui.CompareBranchesDiffPanel
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.impl.ChangesBrowserToolWindow.createDiffPreview
import com.intellij.openapi.vcs.impl.ChangesBrowserToolWindow.showTab
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.content.ContentFactory
import git4idea.config.GitVcsSettings
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.util.GitLocalCommitCompareInfo
import org.jetbrains.annotations.Nls
import java.awt.BorderLayout
private val LOG = logger<GitShowDiffWithBranchPanel>()
class GitShowDiffWithBranchPanel(val project: Project,
val branchName: String,
val repositories: List<GitRepository>,
val currentBranchName: String) {
private val disposable: Disposable = Disposer.newDisposable()
private val diffPanel: CompareBranchesDiffPanel
private val loadingPanel: JBLoadingPanel
init {
diffPanel = CompareBranchesDiffPanel(project, GitVcsSettings.getInstance(project), branchName, currentBranchName)
diffPanel.changesBrowser.hideViewerBorder()
diffPanel.disableControls()
diffPanel.setEmptyText("")
val changesBrowser = diffPanel.changesBrowser
val diffPreview = createDiffPreview(project, changesBrowser, disposable)
changesBrowser.setShowDiffActionPreview(diffPreview)
loadingPanel = JBLoadingPanel(BorderLayout(), disposable).apply {
startLoading()
add(diffPanel)
}
loadDiffInBackground()
}
fun showAsTab() {
val title = GitBundle.message("show.diff.between.dialog.title", branchName)
val content = ContentFactory.getInstance().createContent(loadingPanel, title, false)
content.preferredFocusableComponent = diffPanel.preferredFocusComponent
content.setDisposer(disposable)
showTab(project, content)
}
private fun loadDiffInBackground() {
ApplicationManager.getApplication().executeOnPooledThread {
val result = loadDiff()
runInEdt {
showDiff(result)
}
}
}
private fun loadDiff(): LoadingResult {
try {
val compareInfo = GitLocalCommitCompareInfo(project, branchName)
for (repository in repositories) {
compareInfo.putTotalDiff(repository, GitBranchWorker.loadTotalDiff(repository, branchName))
}
return LoadingResult.Success(compareInfo)
}
catch (e: Exception) {
LOG.warn(e)
return LoadingResult.Error(GitBundle.message("show.diff.between.dialog.could.not.load.diff.with.branch.error", branchName, e.message))
}
}
private fun showDiff(result: LoadingResult) {
if (Disposer.isDisposed(disposable)) return
loadingPanel.stopLoading()
when (result) {
is LoadingResult.Success -> {
diffPanel.setCompareInfo(result.compareInfo)
diffPanel.setEmptyText(GitBundle.message("show.diff.between.dialog.no.differences.empty.text"))
diffPanel.enableControls()
}
is LoadingResult.Error -> Messages.showErrorDialog(diffPanel, result.error)
}
}
private sealed class LoadingResult {
class Success(val compareInfo: GitLocalCommitCompareInfo) : LoadingResult()
class Error(@Nls val error: String) : LoadingResult()
}
} | apache-2.0 | 17e448f88bf70998090f6ce5697ddf37 | 35.970297 | 140 | 0.749799 | 4.56357 | false | false | false | false |
Reacto-Rx/reactorx-core | library/src/main/kotlin/org/reactorx/state/StateStore.kt | 1 | 8261 | package org.reactorx.state
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.ObservableTransformer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import io.reactivex.subjects.PublishSubject
import org.reactorx.state.model.Action
import org.reactorx.state.model.impl.Init
import org.reactorx.state.model.impl.Void
/**
* @author Filip Prochazka (@filipproch)
*/
class StateStore<T>(
private val reducer: (T, Action) -> T,
initialState: T,
private val transformers: List<ObservableTransformer<Action, Action>>,
private val middleware: List<Middleware>,
subscribeImmediately: Boolean = false,
private val errorCallback: ((Throwable) -> Unit)? = null,
/* Hack not to break build with upgrade to newer version, TODO: remove */
private val extraTransformerObservablesObtainer: ((Observable<Action>) -> Array<Observable<out org.reactorx.presenter.model.Action>>)? = null
) {
private val subject = PublishSubject.create<Action>()
var currentState: T = initialState
private set
private val preStateMiddlewareSubject = PublishSubject.create<Action>()
private val postStateMiddlewareSubject = PublishSubject.create<Action>()
private val internalSubscriptionsDisposable: CompositeDisposable = CompositeDisposable()
private val transformer = ObservableTransformer<Action, Action> { stream ->
stream.publish { sharedStream ->
var observables: List<Observable<out Action>> = transformers.map {
sharedStream.compose(it)
.doOnError { errorCallback?.invoke(it) }
}
extraTransformerObservablesObtainer?.let {
observables = observables.plus(it.invoke(sharedStream))
}
Observable.mergeDelayError(observables)
}
}
private val reduceTransformer = ObservableTransformer<Action, Pair<Action, T>> { actions ->
actions.scan(Pair(ACTION_VOID, initialState), { stateWrapper: Pair<Action, T>, action: Action ->
Pair(action, internalReducer(stateWrapper.second, action))
})
}
private val observable = subject
.compose(transformer)
.startWith(ACTION_INIT)
.doOnNext { invokePreStateMiddleware(it) }
.compose(reduceTransformer)
.doOnNext { (action, _) -> invokePostStateMiddleware(action) }
.map { (_, newState) -> newState }
.replay(1)
.autoConnect()
init {
// Initialize middleware streams
internalSubscriptionsDisposable.add(
preStateMiddlewareSubject
.compose(newMiddlewareTransformer(Middleware.PHASE_BEFORE_STATE_CHANGED))
.doOnError { errorCallback?.invoke(it) }
.subscribe(dispatch())
)
internalSubscriptionsDisposable.add(
postStateMiddlewareSubject
.compose(newMiddlewareTransformer(Middleware.PHASE_AFTER_STATE_CHANGED))
.doOnError { errorCallback?.invoke(it) }
.subscribe(dispatch())
)
// If configured, immediately accept dispatched actions (don't wait for observe() to be called)
if (subscribeImmediately) {
internalSubscriptionsDisposable.add(observable.subscribe())
}
}
private fun invokePreStateMiddleware(
action: Action
) {
preStateMiddlewareSubject.onNext(action)
}
private fun invokePostStateMiddleware(
action: Action
) {
postStateMiddlewareSubject.onNext(action)
}
private fun internalReducer(
state: T,
action: Action
): T {
currentState = reducer.invoke(state, action)
return currentState
}
private fun newMiddlewareTransformer(
phase: Int
): ObservableTransformer<Action, Action> {
return ObservableTransformer { actions ->
actions.publish { sharedStream ->
Observable.mergeDelayError(
middleware.filter { it.phase == phase }
.map { it.transformer }
.map { sharedStream.compose(it) }
)
}
}
}
fun observe(): Observable<T> = observable
fun dispatch(input: Action) {
if (internalSubscriptionsDisposable.isDisposed) {
throw RuntimeException("StateStore is disposed")
}
subject.onNext(input)
}
fun dispatch(): Consumer<Action> = Consumer { dispatch(it) }
fun dispatchAsync(
input: Action
) = Completable.create {
dispatch(input)
it.onComplete()
}
fun dispose() {
subject.onComplete()
internalSubscriptionsDisposable.dispose()
}
companion object {
val ACTION_INIT get() = Init()
val ACTION_VOID get() = Void()
}
class Builder<T>(
private val initialState: T
) {
private lateinit var reducer: (T, Action) -> T
private val transformers: MutableList<ObservableTransformer<Action, Action>> = mutableListOf()
private val middleware: MutableList<Middleware> = mutableListOf()
private var subscribeImmediately: Boolean = false
private var errorCallback: ((Throwable) -> Unit)? = null
private var extraTransformerObservablesObtainer: ((Observable<Action>) -> Array<Observable<out org.reactorx.presenter.model.Action>>)? = null
fun enableInputPasstrough(
filter: ((Action) -> Boolean)? = null
): Builder<T> {
withTransformer(ObservableTransformer { inputActions ->
if (filter == null) {
inputActions
} else {
inputActions.filter(filter)
}
})
return this
}
fun withReducer(
reducer: (T, Action) -> T
): Builder<T> {
this.reducer = reducer
return this
}
fun withTransformer(
vararg transformers: ObservableTransformer<Action, Action>
): Builder<T> {
this.transformers.addAll(transformers)
return this
}
fun withTransformers(
transformers: Collection<ObservableTransformer<Action, Action>>
): Builder<T> {
this.transformers.addAll(transformers)
return this
}
fun withMiddleware(
vararg transformers: ObservableTransformer<Action, Action>,
phase: Int = Middleware.PHASE_AFTER_STATE_CHANGED
): Builder<T> {
this.middleware.addAll(transformers.map {
Middleware(it, phase)
})
return this
}
fun withMiddlewares(
transformers: Collection<ObservableTransformer<Action, Action>>,
phase: Int = Middleware.PHASE_AFTER_STATE_CHANGED
): Builder<T> {
this.middleware.addAll(transformers.map {
Middleware(it, phase)
})
return this
}
fun subscribeImmediately(): Builder<T> {
this.subscribeImmediately = true
return this
}
fun errorCallback(
callback: (Throwable) -> Unit
): Builder<T> {
this.errorCallback = callback
return this
}
fun extraTransformerObservablesObtainer(
action: ((Observable<Action>) -> Array<Observable<out org.reactorx.presenter.model.Action>>)?
): Builder<T> {
this.extraTransformerObservablesObtainer = action
return this
}
fun build(): StateStore<T> {
return StateStore(
reducer,
initialState,
transformers,
middleware,
subscribeImmediately,
errorCallback,
extraTransformerObservablesObtainer
)
}
}
} | mit | 06edfd9b3b1d1248fa1ad3d78f334147 | 31.785714 | 149 | 0.586612 | 5.364286 | false | false | false | false |
nadraliev/DsrWeatherApp | app/src/main/java/soutvoid/com/DsrWeatherApp/interactor/forecast/ForecastRepository.kt | 1 | 2935 | package soutvoid.com.DsrWeatherApp.interactor.forecast
import com.agna.ferro.mvp.component.scope.PerApplication
import rx.Observable
import soutvoid.com.DsrWeatherApp.domain.DailyForecast
import soutvoid.com.DsrWeatherApp.domain.Forecast
import soutvoid.com.DsrWeatherApp.interactor.forecast.network.ForecastApi
import soutvoid.com.DsrWeatherApp.interactor.util.Accuracy
import soutvoid.com.DsrWeatherApp.interactor.util.Units
import java.util.*
import javax.inject.Inject
@PerApplication
class ForecastRepository @Inject constructor(val api : ForecastApi) {
fun getByCityName(query: String,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<Forecast> {
return api.getByCityName(query, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getByCityId(cityId: Int,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<Forecast> {
return api.getByCityId(cityId, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getByCoordinates(latitude: Double,
longitude: Double,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<Forecast> {
return api.getByCoordinates(latitude, longitude, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getDailyByCityName(query: String,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<DailyForecast> {
return api.getDailyByCityName(query, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getDailyByCityId(cityId: Int,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<DailyForecast> {
return api.getDailyByCityId(cityId, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
fun getDailyByCoordinates(latitude: Double,
longitude: Double,
units: Units = Units.METRIC,
accuracyType: Accuracy = Accuracy.LIKE,
lang: String = Locale.getDefault().language)
: Observable<DailyForecast> {
return api.getDailyByCoordinates(latitude, longitude, units.name.toLowerCase(), accuracyType.name.toLowerCase(), lang)
}
} | apache-2.0 | 7309c57a557755fca02ef92de7a2849c | 42.820896 | 126 | 0.630664 | 4.85124 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/adapter/ProductSliderAdapter.kt | 1 | 1694 | package com.tungnui.abccomputer.adapter
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.tungnui.abccomputer.R
import com.tungnui.abccomputer.listener.OnItemClickListener
import com.tungnui.abccomputer.models.Image
import com.tungnui.abccomputer.utils.loadGlideImg
import java.util.ArrayList
class ProductSliderAdapter(private val mContext: Context?, var images: ArrayList<Image>) : PagerAdapter() {
private val inflater: LayoutInflater
// Listener
private var mListener: OnItemClickListener? = null
init {
inflater = LayoutInflater.from(mContext)
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
override fun getCount(): Int {
return images.size
}
override fun instantiateItem(view: ViewGroup, position: Int): Any {
val imageLayout = inflater.inflate(R.layout.item_product_image_slider, view, false)
val imageView = imageLayout.findViewById<View>(R.id.image) as ImageView
imageView.loadGlideImg(images[position].src)
view.addView(imageLayout)
imageView.setOnClickListener {
if (mListener != null) {
mListener!!.onItemListener(view, position)
}
}
return imageLayout
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
fun setItemClickListener(mListener: OnItemClickListener) {
this.mListener = mListener
}
} | mit | b129823218b42938232d76ef398d1784 | 27.728814 | 107 | 0.707792 | 4.628415 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/gradle/testSources/org/jetbrains/plugins/gradle/testFramework/GradleCodeInsightTestCase.kt | 1 | 4139 | // 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.plugins.gradle.testFramework
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.openapi.externalSystem.util.runReadAction
import com.intellij.openapi.externalSystem.util.runWriteActionAndWait
import com.intellij.psi.PsiElement
import com.intellij.testFramework.runInEdtAndWait
import org.jetbrains.plugins.groovy.util.ExpressionTest
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Assertions.assertTrue
abstract class GradleCodeInsightTestCase : GradleCodeInsightBaseTestCase(), ExpressionTest {
fun testBuildscript(decorator: String, expression: String, test: () -> Unit) {
if (decorator.isEmpty()) {
testBuildscript(expression, test)
}
else {
testBuildscript("$decorator { $expression }", test)
}
}
fun testBuildscript(expression: String, test: () -> Unit) {
checkCaret(expression)
updateProjectFile(expression)
runReadAction {
test()
}
}
private fun checkCaret(expression: String) {
assertTrue("<caret>" in expression, "Please define caret position in build script.")
}
fun testHighlighting(expression: String) = testHighlighting("build.gradle", expression)
fun testHighlighting(relativePath: String, expression: String) {
val file = findOrCreateFile(relativePath, expression)
runInEdtAndWait {
codeInsightFixture.testHighlighting(true, false, true, file)
}
}
fun testCompletion(expression: String, vararg completionCandidates: String) {
checkCaret(expression)
val file = findOrCreateFile("build.gradle", expression)
runInEdtAndWait {
codeInsightFixture.configureFromExistingVirtualFile(file)
val lookup = listOf(*codeInsightFixture.completeBasic())
var startIndex = 0
for (candidate in completionCandidates) {
val newIndex = lookup.subList(startIndex, lookup.size).indexOfFirst { it.lookupString == candidate }
assertTrue(newIndex != -1, "Element '$candidate' must be in the lookup")
startIndex = newIndex + 1
}
}
}
fun testGotoDefinition(expression: String, checker: (PsiElement) -> Unit) {
checkCaret(expression)
val file = findOrCreateFile("build.gradle", expression)
runInEdtAndWait {
codeInsightFixture.configureFromExistingVirtualFile(file)
val elementAtCaret = codeInsightFixture.elementAtCaret
assertNotNull(elementAtCaret)
val elem = GotoDeclarationAction.findTargetElement(project, codeInsightFixture.editor, codeInsightFixture.caretOffset)
checker(elem!!)
}
}
fun updateProjectFile(content: String) {
val file = findOrCreateFile("build.gradle", content)
runWriteActionAndWait {
codeInsightFixture.configureFromExistingVirtualFile(file)
}
}
fun getDistributionBaseNameMethod(): String {
return when {
isGradleAtLeast("7.0") -> "getDistributionBaseName()"
else -> "getBaseName()"
}
}
fun getDistributionContainerFqn(): String {
return when {
isGradleAtLeast("3.5") -> "org.gradle.api.NamedDomainObjectContainer<org.gradle.api.distribution.Distribution>"
else -> "org.gradle.api.distribution.internal.DefaultDistributionContainer"
}
}
fun getExtraPropertiesExtensionFqn(): String {
return when {
isGradleOlderThan("5.2") -> "org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension"
else -> "org.gradle.internal.extensibility.DefaultExtraPropertiesExtension"
}
}
fun getPublishingExtensionFqn(): String {
return when {
isGradleOlderThan("4.8") -> "org.gradle.api.publish.internal.DefaultPublishingExtension"
isGradleAtLeast("5.0") -> "org.gradle.api.publish.internal.DefaultPublishingExtension"
else -> "org.gradle.api.publish.internal.DeferredConfigurablePublishingExtension"
}
}
companion object {
const val DECORATORS = """
"",
project(':'),
allprojects,
subprojects,
configure(project(':'))
"""
}
}
| apache-2.0 | 989cacc4e13458dc16b5cfc5a6c1543b | 34.681034 | 124 | 0.727229 | 4.79606 | false | true | false | false |
michaelbull/kotlin-result | kotlin-result/src/commonTest/kotlin/com/github/michaelbull/result/IterableTest.kt | 1 | 7555 | package com.github.michaelbull.result
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertSame
class IterableTest {
private sealed class IterableError {
object IterableError1 : IterableError()
object IterableError2 : IterableError()
}
class Fold {
@Test
fun returnAccumulatedValueIfOk() {
val result = listOf(20, 30, 40, 50).fold(
initial = 10,
operation = { a, b -> Ok(a + b) }
)
result as Ok
assertEquals(
expected = 150,
actual = result.value
)
}
@Test
fun returnsFirstErrorIfErr() {
val result: Result<Int, IterableError> = listOf(5, 10, 15, 20, 25).fold(
initial = 1,
operation = { a, b ->
when (b) {
(5 + 10) -> Err(IterableError.IterableError1)
(5 + 10 + 15 + 20) -> Err(IterableError.IterableError2)
else -> Ok(a * b)
}
}
)
result as Err
assertSame(
expected = IterableError.IterableError1,
actual = result.error
)
}
}
class FoldRight {
@Test
fun returnsAccumulatedValueIfOk() {
val result = listOf(2, 5, 10, 20).foldRight(
initial = 100,
operation = { a, b -> Ok(b - a) }
)
result as Ok
assertEquals(
expected = 63,
actual = result.value
)
}
@Test
fun returnsLastErrorIfErr() {
val result = listOf(2, 5, 10, 20, 40).foldRight(
initial = 38500,
operation = { a, b ->
when (b) {
(((38500 / 40) / 20) / 10) -> Err(IterableError.IterableError1)
((38500 / 40) / 20) -> Err(IterableError.IterableError2)
else -> Ok(b / a)
}
}
)
result as Err
assertSame(
expected = IterableError.IterableError2,
actual = result.error
)
}
}
class Combine {
@Test
fun returnsValuesIfAllOk() {
val values = combine(
Ok(10),
Ok(20),
Ok(30)
).get()!!
assertEquals(
expected = 3,
actual = values.size
)
assertEquals(
expected = 10,
actual = values[0]
)
assertEquals(
expected = 20,
actual = values[1]
)
assertEquals(
expected = 30,
actual = values[2]
)
}
@Test
fun returnsFirstErrorIfErr() {
val result = combine(
Ok(20),
Ok(40),
Err(IterableError.IterableError1),
Ok(60),
Err(IterableError.IterableError2),
Ok(80)
)
result as Err
assertSame(
expected = IterableError.IterableError1,
actual = result.error
)
}
}
class GetAll {
@Test
fun returnsAllValues() {
val values = getAll(
Ok("hello"),
Ok("big"),
Err(IterableError.IterableError2),
Ok("wide"),
Err(IterableError.IterableError1),
Ok("world")
)
assertEquals(
expected = 4,
actual = values.size
)
assertEquals(
expected = "hello",
actual = values[0]
)
assertEquals(
expected = "big",
actual = values[1]
)
assertEquals(
expected = "wide",
actual = values[2]
)
assertEquals(
expected = "world",
actual = values[3]
)
}
}
class GetAllErrors {
@Test
fun returnsAllErrors() {
val errors = getAllErrors(
Err(IterableError.IterableError2),
Ok("haskell"),
Err(IterableError.IterableError2),
Ok("f#"),
Err(IterableError.IterableError1),
Ok("elm"),
Err(IterableError.IterableError1),
Ok("clojure"),
Err(IterableError.IterableError2)
)
assertEquals(
expected = 5,
actual = errors.size
)
assertSame(
expected = IterableError.IterableError2,
actual = errors[0]
)
assertSame(
expected = IterableError.IterableError2,
actual = errors[1]
)
assertSame(
expected = IterableError.IterableError1,
actual = errors[2]
)
assertSame(
expected = IterableError.IterableError1,
actual = errors[3]
)
assertSame(
expected = IterableError.IterableError2,
actual = errors[4]
)
}
}
class Partition {
@Test
fun returnsPairOfValuesAndErrors() {
val pairs = partition(
Err(IterableError.IterableError2),
Ok("haskell"),
Err(IterableError.IterableError2),
Ok("f#"),
Err(IterableError.IterableError1),
Ok("elm"),
Err(IterableError.IterableError1),
Ok("clojure"),
Err(IterableError.IterableError2)
)
val values = pairs.first
assertEquals(
expected = 4,
actual = values.size
)
assertEquals(
expected = "haskell",
actual = values[0]
)
assertEquals(
expected = "f#",
actual = values[1]
)
assertEquals(
expected = "elm",
actual = values[2]
)
assertEquals(
expected = "clojure",
actual = values[3]
)
val errors = pairs.second
assertEquals(
expected = 5,
actual = errors.size
)
assertSame(
expected = IterableError.IterableError2,
actual = errors[0]
)
assertSame(
expected = IterableError.IterableError2,
actual = errors[1]
)
assertSame(
expected = IterableError.IterableError1,
actual = errors[2]
)
assertSame(
expected = IterableError.IterableError1,
actual = errors[3]
)
assertSame(
expected = IterableError.IterableError2,
actual = errors[4]
)
}
}
}
| isc | 74e7ad79d89ad23a5e4dcc190ae02fc4 | 24.183333 | 87 | 0.410854 | 5.404149 | false | false | false | false |
Gark/bassblog_kotlin | app/src/main/java/pixel/kotlin/bassblog/ui/mixes/BaseMixAdapter.kt | 1 | 4234 | package pixel.kotlin.bassblog.ui.mixes
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.squareup.picasso.Picasso
import pixel.kotlin.bassblog.R
import pixel.kotlin.bassblog.network.Mix
import java.text.DateFormat
import java.text.SimpleDateFormat
import java.util.*
abstract class BaseMixAdapter(context: Context, val callback: MixSelectCallback) : RecyclerView.Adapter<BaseMixAdapter.MixHolder>() {
interface MixSelectCallback {
fun onMixSelected(mix: Mix?)
fun onDataUpdated(showEmptyView: Boolean)
}
private val mCalendar = Calendar.getInstance()
private var fmt: DateFormat = SimpleDateFormat("MMMM yyyy", Locale.US)
private val mInflater: LayoutInflater = LayoutInflater.from(context)
private val mAllMix: ArrayList<Mix>
private val picasso: Picasso
private var mCurrentMix: Mix? = null
init {
setHasStableIds(true)
picasso = Picasso.with(context)
mAllMix = ArrayList()
}
fun updateMixList(list: List<Mix>) {
mAllMix.clear()
mAllMix.addAll(list)
handleChanges()
}
abstract fun getLayout(): Int
abstract fun needResize(): Boolean
abstract fun onFragmentDestroyed()
fun handleChanges() {
callback.onDataUpdated(mAllMix.isEmpty())
notifyDataSetChanged()
}
override fun onViewRecycled(holder: MixHolder) {
holder.onViewRecycled()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = MixHolder(mInflater.inflate(getLayout(), parent, false))
override fun onBindViewHolder(holder: MixHolder, position: Int) = holder.displayData(mAllMix[position], showHeader(position))
private fun showHeader(position: Int): Boolean {
if (position == 0) {
return true
} else {
mCalendar.timeInMillis = mAllMix[position - 1].published
val previousMonth = mCalendar.get(Calendar.MONTH)
mCalendar.timeInMillis = mAllMix[position].published
val currentMonth = mCalendar.get(Calendar.MONTH)
return currentMonth != previousMonth
}
}
override fun getItemCount(): Int = mAllMix.size
inner class MixHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val mPostTitle = itemView.findViewById(R.id.post_title) as TextView
private val mPostLabel = itemView.findViewById(R.id.post_label) as TextView
private val mHeader = itemView.findViewById(R.id.header_date) as TextView?
private val mPostImage = itemView.findViewById(R.id.mix_image) as ImageView
private val mNowPlayingImage = itemView.findViewById(R.id.now_playing) as ImageView
private val mCalendar = Calendar.getInstance()
private var mMix: Mix? = null
init {
itemView.setOnClickListener { handleClick() }
}
private fun handleClick() {
callback.onMixSelected(mMix)
}
fun displayData(mix: Mix, showHeader: Boolean) {
mMix = mix
mPostTitle.text = mix.title
mPostLabel.text = mix.label
mNowPlayingImage.visibility = if (mix == mCurrentMix) View.VISIBLE else View.GONE
mCalendar.timeInMillis = mix.published
mHeader?.let {
it.text = fmt.format(mCalendar.time)
it.visibility = if (showHeader) View.VISIBLE else View.GONE
}
val requestCreator = Picasso.with(itemView.context).load(mix.image)
if (needResize()) {
requestCreator.resizeDimen(R.dimen.image_width, R.dimen.image_height)
} else {
// requestCreator.fit()
}
requestCreator.into(mPostImage)
}
fun onViewRecycled() {
picasso.cancelRequest(mPostImage)
}
}
override fun getItemId(position: Int): Long {
return mAllMix[position].mixId
}
fun updatePlayingMix(mix: Mix?) {
mCurrentMix = mix
notifyDataSetChanged()
}
}
| agpl-3.0 | a9438a5aa481aa5f62eaafdb3442dcb2 | 31.569231 | 133 | 0.66273 | 4.494692 | false | false | false | false |
Jay-Y/yframework | yframework-android/framework/src/main/java/org/yframework/android/util/TelephonyManagerUtil.kt | 1 | 4094 | package org.yframework.android.util
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.telephony.TelephonyManager
import androidx.core.content.ContextCompat
import java.util.*
/**
* Description: TelephonyManagerUtil<br>
* Comments Name: TelephonyManagerUtil<br>
* Date: 2019-12-02 14:56<br>
* Author: ysj<br>
* EditorDate: 2019-12-02 14:56<br>
* Editor: ysj
*/
class TelephonyManagerUtil private constructor(private val tm: TelephonyManager) {
companion object {
private var INSTANCE: TelephonyManagerUtil? = null
fun with(activity: Activity): TelephonyManagerUtil {
if (INSTANCE == null) {
synchronized(this)
{
if (INSTANCE == null) {
INSTANCE = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
TelephonyManagerUtil(activity.getSystemService(TelephonyManager::class.java))
} else {
TelephonyManagerUtil(
activity.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
)
}
}
}
}
return INSTANCE!!
}
}
@SuppressLint("MissingPermission")
fun getPhoneNumber(context: Context): String? {
return if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED
) {
tm.line1Number
} else {
null
}
}
@SuppressLint("MissingPermission")
fun getSimSerialNumber(context: Context): String? {
return if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED
) {
tm.simSerialNumber
} else {
null
}
}
@SuppressLint("MissingPermission")
fun getDeviceID(context: Context): String? {
return if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED && Build.VERSION.SDK_INT < Build.VERSION_CODES.O
) {
tm.deviceId
} else {
null
}
}
@SuppressLint("MissingPermission")
fun getImei(context: Context): String? {
return if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
) {
tm.imei
} else {
null
}
}
@SuppressLint("MissingPermission")
fun getMeid(context: Context): String? {
return if (ContextCompat.checkSelfPermission(
context,
Manifest.permission.READ_PHONE_STATE
) == PackageManager.PERMISSION_GRANTED && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
) {
tm.meid
} else {
null
}
}
fun getUniquePseudoID(): String {
val deviceInfo: String = "18" +
Build.BOARD.length % 10 + Build.BRAND.length % 10 +
Build.CPU_ABI.length % 10 + Build.DEVICE.length % 10 +
Build.DISPLAY.length % 10 + Build.HOST.length % 10 +
Build.ID.length % 10 + Build.MANUFACTURER.length % 10 +
Build.MODEL.length % 10 + Build.PRODUCT.length % 10 +
Build.TAGS.length % 10 + Build.TYPE.length % 10 +
Build.USER.length % 10 // 13 位
val serial = Build.SERIAL ?: "ANDROID"
// API>=9 使用serial号
return UUID(deviceInfo.hashCode().toLong(), serial.hashCode().toLong()).toString()
}
} | apache-2.0 | 67fa9ca46afa718384116b25c2e490ce | 30.438462 | 105 | 0.564121 | 4.911058 | false | false | false | false |
tonyklawrence/kotlens | src/laws/kotlin/kotlens/laws/IsoLaws.kt | 1 | 966 | package kotlens.laws
import funk.compose
import io.kotlintest.properties.Gen
import io.kotlintest.properties.forAll
import io.kotlintest.specs.StringSpec
import kotlens.Iso
class IsoLaws : StringSpec() { init {
val iso = Iso(String::toList, { a -> a.joinToString("") })
"Round trip one way" {
forAll { s: String ->
(iso compose iso.reverse()).get(s) == s
}
}
"Round trip other way" {
forAll(Gen.list(Gen.char()), { a ->
(iso.reverse() compose iso).get(a) == a
})
}
"Modify with identity" {
forAll { s: String ->
iso.modify { a -> a }(s) == s
}
}
"Modify can compose" {
val f = { a: List<Char> -> a.filterIndexed { i, _ -> i % 3 == 2 } }
val g = { a: List<Char> -> a.filterIndexed { i, _ -> i % 5 == 0 } }
forAll { s: String ->
iso.modify(f)(iso.modify(g)(s)) == iso.modify(f compose g)(s)
}
}
}} | mit | ec149c03e63133d3d3d2b17a3385c7a5 | 24.447368 | 75 | 0.518634 | 3.437722 | false | true | false | false |
harningt/atomun-core | src/main/kotlin/us/eharning/atomun/core/utility/Hash.kt | 1 | 4443 | /*
* Copyright 2015, 2017 Thomas Harning Jr. <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package us.eharning.atomun.core.utility
import org.bouncycastle.crypto.digests.RIPEMD160Digest
import us.eharning.atomun.core.annotations.Beta
import java.security.DigestException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/**
* Utility class to perform specific necessary hash functions.
*/
@Beta
object Hash {
private const val SHA256_DIGEST_LEN = 32
/**
* Perform the double-hash of the encoded public key per Bitcoin rules.
*
* @param key
* ASN.1 encoded public key bytes.
*
* @return byte array representing the double-hashed value.
*/
@JvmStatic
fun keyHash(key: ByteArray): ByteArray {
val ph = ByteArray(20)
try {
val sha256 = MessageDigest.getInstance("SHA-256").digest(key)
val digest = RIPEMD160Digest()
digest.update(sha256, 0, sha256.size)
digest.doFinal(ph, 0)
} catch (e: NoSuchAlgorithmException) {
throw Error("Missing SHA-256", e)
}
return ph
}
/**
* Perform a double SHA-256 hash of the given input data.
*
* @param data
* byte array to process as input.
* @param offset
* offset into the byte array.
* @param len
* number of bytes to process from the byte array.
* @param result
* byte array to write results to.
* @param resultOffset
* offset into the result byte array.
* @param resultLen
* number of bytes set aside for the result byte array.
*
* @return length of digest added to buffer.
*/
@JvmStatic
fun doubleHash(data: ByteArray, offset: Int, len: Int, result: ByteArray, resultOffset: Int, resultLen: Int): Int {
try {
val digest = MessageDigest.getInstance("SHA-256")
digest.update(data, offset, len)
/* Perform first digest pass - which resets state */
digest.digest(result, resultOffset, resultLen)
/* Feed in digest data */
digest.update(result, resultOffset, resultLen)
/* Perform second digest pass */
return digest.digest(result, resultOffset, resultLen)
} catch (e: DigestException) {
throw Error("Missing SHA-256 / failed setup", e)
} catch (e: NoSuchAlgorithmException) {
throw Error("Missing SHA-256 / failed setup", e)
}
}
/**
* Perform a double SHA-256 hash of the given input data.
*
* @param data
* byte array to process as input.
* @param offset
* offset into the byte array.
* @param len
* number of bytes to process from the byte array.
*
* @return SHA-256 digest of the data used.
*/
@JvmStatic
@JvmOverloads
fun doubleHash(data: ByteArray, offset: Int = 0, len: Int = data.size): ByteArray {
val result = ByteArray(SHA256_DIGEST_LEN)
doubleHash(data, offset, len, result, 0, result.size)
return result
}
/**
* Perform a SHA-256 hash of the given input data.
*
* @param data
* byte array to process as input.
* @param offset
* offset into the byte array.
* @param len
* number of bytes to process from the byte array.
*
* @return SHA-256 digest of the data used.
*/
@JvmStatic
@JvmOverloads
fun hash(data: ByteArray, offset: Int = 0, len: Int = data.size): ByteArray {
try {
val digest = MessageDigest.getInstance("SHA-256")
digest.update(data, offset, len)
return digest.digest()
} catch (e: NoSuchAlgorithmException) {
throw Error("Missing SHA-256", e)
}
}
}
| apache-2.0 | afbe5f6dd8b3309144c4517505fcffce | 32.156716 | 119 | 0.612199 | 4.292754 | false | false | false | false |
paplorinc/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/components/service.kt | 2 | 1167 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.components
import com.intellij.openapi.components.impl.ComponentManagerImpl
import com.intellij.openapi.components.impl.stores.IComponentStore
import com.intellij.openapi.project.Project
inline fun <reified T : Any> service(): T = ServiceManager.getService(T::class.java)
inline fun <reified T : Any> serviceOrNull(): T? = ServiceManager.getService(T::class.java)
inline fun <reified T : Any> serviceIfCreated(): T? = ServiceManager.getServiceIfCreated(T::class.java)
inline fun <reified T : Any> Project.service(): T = ServiceManager.getService(this, T::class.java)
val ComponentManager.stateStore: IComponentStore
get() {
val key: Any = if (this is Project) IComponentStore::class.java else IComponentStore::class.java.name
return picoContainer.getComponentInstance(key) as IComponentStore
}
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
fun <T> ComponentManager.getComponents(baseClass: Class<T>): List<T> =
(this as ComponentManagerImpl).getComponentInstancesOfType(baseClass) | apache-2.0 | 894870491220684b21a042d058af1a0a | 47.666667 | 140 | 0.784062 | 4.123675 | false | false | false | false |
google/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/printing/JKCodeBuilder.kt | 5 | 35080 | // 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.nj2k.printing
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.printing.JKPrinterBase.ParenthesisKind
import org.jetbrains.kotlin.nj2k.symbols.getDisplayFqName
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.JKClass.ClassKind.*
import org.jetbrains.kotlin.nj2k.tree.visitors.JKVisitorWithCommentsPrinting
import org.jetbrains.kotlin.nj2k.types.JKContextType
import org.jetbrains.kotlin.nj2k.types.isAnnotationMethod
import org.jetbrains.kotlin.nj2k.types.isInterface
import org.jetbrains.kotlin.nj2k.types.isUnit
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class JKCodeBuilder(context: NewJ2kConverterContext) {
private val elementInfoStorage = context.elementsInfoStorage
private val printer = JKPrinter(context.project, context.importStorage, elementInfoStorage)
private val commentPrinter = JKCommentPrinter(printer)
fun printCodeOut(root: JKTreeElement): String {
Visitor().also { root.accept(it) }
return printer.toString().replace("\r\n", "\n")
}
private inner class Visitor : JKVisitorWithCommentsPrinting() {
override fun printLeftNonCodeElements(element: JKFormattingOwner) {
commentPrinter.printTrailingComments(element)
}
override fun printRightNonCodeElements(element: JKFormattingOwner) {
commentPrinter.printLeadingComments(element)
}
private fun renderTokenElement(tokenElement: JKTokenElement) {
printLeftNonCodeElements(tokenElement)
printer.print(tokenElement.text)
printRightNonCodeElements(tokenElement)
}
private fun renderExtraTypeParametersUpperBounds(typeParameterList: JKTypeParameterList) {
val extraTypeBounds = typeParameterList.typeParameters
.filter { it.upperBounds.size > 1 }
if (extraTypeBounds.isNotEmpty()) {
printer.print(" where ")
val typeParametersWithBounds =
extraTypeBounds.flatMap { typeParameter ->
typeParameter.upperBounds.map { bound ->
typeParameter.name to bound
}
}
printer.renderList(typeParametersWithBounds) { (name, bound) ->
name.accept(this)
printer.print(" : ")
bound.accept(this)
}
}
}
private fun renderModifiersList(modifiersList: JKModifiersListOwner) {
val hasOverrideModifier = modifiersList
.safeAs<JKOtherModifiersOwner>()
?.hasOtherModifier(OtherModifier.OVERRIDE) == true
modifiersList.forEachModifier { modifierElement ->
if (modifierElement.modifier == Modality.FINAL || modifierElement.modifier == Visibility.PUBLIC) {
if (hasOverrideModifier) {
modifierElement.accept(this)
} else {
printLeftNonCodeElements(modifierElement)
printRightNonCodeElements(modifierElement)
}
} else {
modifierElement.accept(this)
}
printer.print(" ")
}
}
override fun visitTreeElementRaw(treeElement: JKElement) {
printer.print("/* !!! Hit visitElement for element type: ${treeElement::class} !!! */")
}
override fun visitModifierElementRaw(modifierElement: JKModifierElement) {
if (modifierElement.modifier != Modality.FINAL) {
printer.print(modifierElement.modifier.text)
}
}
override fun visitTreeRootRaw(treeRoot: JKTreeRoot) {
treeRoot.element.accept(this)
}
override fun visitKtTryExpressionRaw(ktTryExpression: JKKtTryExpression) {
printer.print("try ")
ktTryExpression.tryBlock.accept(this)
ktTryExpression.catchSections.forEach { it.accept(this) }
if (ktTryExpression.finallyBlock != JKBodyStub) {
printer.print("finally ")
ktTryExpression.finallyBlock.accept(this)
}
}
override fun visitKtTryCatchSectionRaw(ktTryCatchSection: JKKtTryCatchSection) {
printer.print("catch ")
printer.par {
ktTryCatchSection.parameter.accept(this)
}
ktTryCatchSection.block.accept(this)
}
override fun visitForInStatementRaw(forInStatement: JKForInStatement) {
printer.print("for (")
forInStatement.declaration.accept(this)
printer.print(" in ")
forInStatement.iterationExpression.accept(this)
printer.print(") ")
if (forInStatement.body.isEmpty()) {
printer.print(";")
} else {
forInStatement.body.accept(this)
}
}
override fun visitKtThrowExpressionRaw(ktThrowExpression: JKKtThrowExpression) {
printer.print("throw ")
ktThrowExpression.exception.accept(this)
}
override fun visitDoWhileStatementRaw(doWhileStatement: JKDoWhileStatement) {
printer.print("do ")
doWhileStatement.body.accept(this)
printer.print(" while (")
doWhileStatement.condition.accept(this)
printer.print(")")
}
override fun visitClassAccessExpressionRaw(classAccessExpression: JKClassAccessExpression) {
printer.renderSymbol(classAccessExpression.identifier, classAccessExpression)
}
override fun visitMethodAccessExpression(methodAccessExpression: JKMethodAccessExpression) {
printer.renderSymbol(methodAccessExpression.identifier, methodAccessExpression)
}
override fun visitTypeQualifierExpression(typeQualifierExpression: JKTypeQualifierExpression) {
printer.renderType(typeQualifierExpression.type, typeQualifierExpression)
}
override fun visitFileRaw(file: JKFile) {
if (file.packageDeclaration.name.value.isNotEmpty()) {
file.packageDeclaration.accept(this)
}
file.importList.accept(this)
file.declarationList.forEach { it.accept(this) }
}
override fun visitPackageDeclarationRaw(packageDeclaration: JKPackageDeclaration) {
printer.print("package ")
val packageNameEscaped = packageDeclaration.name.value.escapedAsQualifiedName()
printer.print(packageNameEscaped)
printer.println()
}
override fun visitImportListRaw(importList: JKImportList) {
importList.imports.forEach { it.accept(this) }
}
override fun visitImportStatementRaw(importStatement: JKImportStatement) {
printer.print("import ")
val importNameEscaped =
importStatement.name.value.escapedAsQualifiedName()
printer.print(importNameEscaped)
printer.println()
}
override fun visitBreakStatementRaw(breakStatement: JKBreakStatement) {
printer.print("break")
breakStatement.label.accept(this)
}
override fun visitClassRaw(klass: JKClass) {
klass.annotationList.accept(this)
if (klass.annotationList.annotations.isNotEmpty()) {
printer.println()
}
renderModifiersList(klass)
printer.print(" ")
printer.print(klass.classKind.text)
printer.print(" ")
klass.name.accept(this)
klass.typeParameterList.accept(this)
printer.print(" ")
val primaryConstructor = klass.primaryConstructor()
primaryConstructor?.accept(this)
if (klass.inheritance.present()) {
printer.print(" : ")
klass.inheritance.accept(this)
}
renderExtraTypeParametersUpperBounds(klass.typeParameterList)
klass.classBody.accept(this)
}
override fun visitInheritanceInfoRaw(inheritanceInfo: JKInheritanceInfo) {
val thisClass = inheritanceInfo.parentOfType<JKClass>()!!
if (thisClass.classKind == INTERFACE) {
renderTypes(inheritanceInfo.extends)
return
}
inheritanceInfo.extends.singleOrNull()?.let { superTypeElement ->
superTypeElement.accept(this)
val primaryConstructor = thisClass.primaryConstructor()
val delegationCall = primaryConstructor?.delegationCall.safeAs<JKDelegationConstructorCall>()
if (delegationCall != null) {
printer.par { delegationCall.arguments.accept(this) }
} else if (!superTypeElement.type.isInterface() && (primaryConstructor != null || thisClass.isObjectOrCompanionObject)) {
printer.print("()")
}
if (inheritanceInfo.implements.isNotEmpty()) printer.print(", ")
}
renderTypes(inheritanceInfo.implements)
}
private fun renderTypes(types: List<JKTypeElement>) {
printer.renderList(types) {
it.annotationList.accept(this)
printer.renderType(it.type)
}
}
private fun renderEnumConstants(enumConstants: List<JKEnumConstant>) {
printer.renderList(enumConstants) {
it.accept(this)
}
}
private fun renderNonEnumClassDeclarations(declarations: List<JKDeclaration>) {
printer.renderList(declarations, { printer.println() }) {
it.accept(this)
}
}
override fun visitFieldRaw(field: JKField) {
field.annotationList.accept(this)
if (field.annotationList.annotations.isNotEmpty()) {
printer.println()
}
renderModifiersList(field)
printer.print(" ")
field.name.accept(this)
if (field.type.present()) {
printer.print(":")
field.type.accept(this)
}
if (field.initializer !is JKStubExpression) {
printer.print(" = ")
field.initializer.accept(this)
}
}
override fun visitEnumConstantRaw(enumConstant: JKEnumConstant) {
enumConstant.annotationList.accept(this)
enumConstant.name.accept(this)
if (enumConstant.arguments.arguments.isNotEmpty()) {
printer.par {
enumConstant.arguments.accept(this)
}
}
if (enumConstant.body.declarations.isNotEmpty()) {
enumConstant.body.accept(this)
}
}
override fun visitKtInitDeclarationRaw(ktInitDeclaration: JKKtInitDeclaration) {
if (ktInitDeclaration.block.statements.isNotEmpty()) {
printer.print("init ")
ktInitDeclaration.block.accept(this)
}
}
override fun visitIsExpressionRaw(isExpression: JKIsExpression) {
isExpression.expression.accept(this)
printer.print(" is ")
isExpression.type.accept(this)
}
override fun visitParameterRaw(parameter: JKParameter) {
renderModifiersList(parameter)
printer.print(" ")
parameter.annotationList.accept(this)
if (parameter.isVarArgs) {
printer.print("vararg ")
}
if (parameter.parent is JKKtPrimaryConstructor
&& (parameter.parent?.parent?.parent as? JKClass)?.classKind == ANNOTATION
) {
printer.print(" val ")
}
parameter.name.accept(this)
if (parameter.type.present() && parameter.type.type !is JKContextType) {
printer.print(":")
parameter.type.accept(this)
}
if (parameter.initializer !is JKStubExpression) {
printer.print(" = ")
parameter.initializer.accept(this)
}
}
override fun visitKtAnnotationArrayInitializerExpressionRaw(
ktAnnotationArrayInitializerExpression: JKKtAnnotationArrayInitializerExpression
) {
printer.print("[")
printer.renderList(ktAnnotationArrayInitializerExpression.initializers) {
it.accept(this)
}
printer.print("]")
}
override fun visitForLoopVariableRaw(forLoopVariable: JKForLoopVariable) {
forLoopVariable.annotationList.accept(this)
forLoopVariable.name.accept(this)
if (forLoopVariable.type.present() && forLoopVariable.type.type !is JKContextType) {
printer.print(": ")
forLoopVariable.type.accept(this)
}
}
override fun visitMethodRaw(method: JKMethod) {
method.annotationList.accept(this)
renderModifiersList(method)
printer.print(" fun ")
method.typeParameterList.accept(this)
elementInfoStorage.getOrCreateInfoForElement(method).let {
printer.print(it.render())
}
method.name.accept(this)
renderTokenElement(method.leftParen)
printer.renderList(method.parameters) {
it.accept(this)
}
renderTokenElement(method.rightParen)
if (!method.returnType.type.isUnit()) {
printer.print(": ")
method.returnType.accept(this)
}
renderExtraTypeParametersUpperBounds(method.typeParameterList)
method.block.accept(this)
}
override fun visitIfElseExpressionRaw(ifElseExpression: JKIfElseExpression) {
printer.print("if (")
ifElseExpression.condition.accept(this)
printer.print(")")
ifElseExpression.thenBranch.accept(this)
if (ifElseExpression.elseBranch !is JKStubExpression) {
printer.print(" else ")
ifElseExpression.elseBranch.accept(this)
}
}
override fun visitIfElseStatementRaw(ifElseStatement: JKIfElseStatement) {
printer.print("if (")
ifElseStatement.condition.accept(this)
printer.print(")")
if (ifElseStatement.thenBranch.isEmpty()) {
printer.print(";")
} else {
ifElseStatement.thenBranch.accept(this)
}
if (!ifElseStatement.elseBranch.isEmpty()) {
printer.print(" else ")
ifElseStatement.elseBranch.accept(this)
}
}
override fun visitBinaryExpressionRaw(binaryExpression: JKBinaryExpression) {
binaryExpression.left.accept(this)
printer.print(" ")
printer.print(binaryExpression.operator.token.text)
printer.print(" ")
binaryExpression.right.accept(this)
}
override fun visitTypeParameterListRaw(typeParameterList: JKTypeParameterList) {
if (typeParameterList.typeParameters.isNotEmpty()) {
printer.par(ParenthesisKind.ANGLE) {
printer.renderList(typeParameterList.typeParameters) {
it.accept(this)
}
}
}
}
override fun visitTypeParameterRaw(typeParameter: JKTypeParameter) {
typeParameter.annotationList.accept(this)
typeParameter.name.accept(this)
if (typeParameter.upperBounds.size == 1) {
printer.print(" : ")
typeParameter.upperBounds.single().accept(this)
}
}
override fun visitLiteralExpressionRaw(literalExpression: JKLiteralExpression) {
printer.print(literalExpression.literal)
}
override fun visitPrefixExpressionRaw(prefixExpression: JKPrefixExpression) {
printer.print(prefixExpression.operator.token.text)
prefixExpression.expression.accept(this)
}
override fun visitThisExpressionRaw(thisExpression: JKThisExpression) {
printer.print("this")
thisExpression.qualifierLabel.accept(this)
}
override fun visitSuperExpressionRaw(superExpression: JKSuperExpression) {
printer.print("super")
if (superExpression.superTypeQualifier != null) {
printer.par(ParenthesisKind.ANGLE) {
printer.renderSymbol(superExpression.superTypeQualifier, superExpression)
}
} else {
superExpression.outerTypeQualifier.accept(this)
}
}
override fun visitContinueStatementRaw(continueStatement: JKContinueStatement) {
printer.print("continue")
continueStatement.label.accept(this)
printer.print(" ")
}
override fun visitLabelEmptyRaw(labelEmpty: JKLabelEmpty) {}
override fun visitLabelTextRaw(labelText: JKLabelText) {
printer.print("@")
labelText.label.accept(this)
printer.print(" ")
}
override fun visitLabeledExpressionRaw(labeledExpression: JKLabeledExpression) {
for (label in labeledExpression.labels) {
label.accept(this)
printer.print("@")
}
labeledExpression.statement.accept(this)
}
override fun visitNameIdentifierRaw(nameIdentifier: JKNameIdentifier) {
printer.print(nameIdentifier.value.escaped())
}
override fun visitPostfixExpressionRaw(postfixExpression: JKPostfixExpression) {
postfixExpression.expression.accept(this)
printer.print(postfixExpression.operator.token.text)
}
override fun visitQualifiedExpressionRaw(qualifiedExpression: JKQualifiedExpression) {
qualifiedExpression.receiver.accept(this)
printer.print(".")
qualifiedExpression.selector.accept(this)
}
override fun visitArgumentListRaw(argumentList: JKArgumentList) {
printer.renderList(argumentList.arguments) { it.accept(this) }
}
override fun visitArgumentRaw(argument: JKArgument) {
argument.value.accept(this)
}
override fun visitNamedArgumentRaw(namedArgument: JKNamedArgument) {
namedArgument.name.accept(this)
printer.print(" = ")
namedArgument.value.accept(this)
}
override fun visitCallExpressionRaw(callExpression: JKCallExpression) {
printer.renderSymbol(callExpression.identifier, callExpression)
if (callExpression.identifier.isAnnotationMethod()) return
callExpression.typeArgumentList.accept(this)
printer.par {
callExpression.arguments.accept(this)
}
}
override fun visitTypeArgumentListRaw(typeArgumentList: JKTypeArgumentList) {
if (typeArgumentList.typeArguments.isNotEmpty()) {
printer.par(ParenthesisKind.ANGLE) {
printer.renderList(typeArgumentList.typeArguments) {
it.accept(this)
}
}
}
}
override fun visitParenthesizedExpressionRaw(parenthesizedExpression: JKParenthesizedExpression) {
printer.par {
parenthesizedExpression.expression.accept(this)
}
}
override fun visitDeclarationStatementRaw(declarationStatement: JKDeclarationStatement) {
printer.renderList(declarationStatement.declaredStatements, { printer.println() }) {
it.accept(this)
}
}
override fun visitTypeCastExpressionRaw(typeCastExpression: JKTypeCastExpression) {
typeCastExpression.expression.accept(this)
printer.print(" as ")
typeCastExpression.type.accept(this)
}
override fun visitWhileStatementRaw(whileStatement: JKWhileStatement) {
printer.print("while (")
whileStatement.condition.accept(this)
printer.print(")")
if (whileStatement.body.isEmpty()) {
printer.print(";")
} else {
whileStatement.body.accept(this)
}
}
override fun visitLocalVariableRaw(localVariable: JKLocalVariable) {
printer.print(" ")
localVariable.annotationList.accept(this)
renderModifiersList(localVariable)
printer.print(" ")
localVariable.name.accept(this)
if (localVariable.type.present() && localVariable.type.type != JKContextType) {
printer.print(": ")
localVariable.type.accept(this)
}
if (localVariable.initializer !is JKStubExpression) {
printer.print(" = ")
localVariable.initializer.accept(this)
}
}
override fun visitEmptyStatementRaw(emptyStatement: JKEmptyStatement) {}
override fun visitStubExpressionRaw(stubExpression: JKStubExpression) {}
override fun visitKtConvertedFromForLoopSyntheticWhileStatementRaw(
ktConvertedFromForLoopSyntheticWhileStatement: JKKtConvertedFromForLoopSyntheticWhileStatement
) {
printer.renderList(
ktConvertedFromForLoopSyntheticWhileStatement.variableDeclarations,
{ printer.println() }) {
it.accept(this)
}
printer.println()
ktConvertedFromForLoopSyntheticWhileStatement.whileStatement.accept(this)
}
override fun visitNewExpressionRaw(newExpression: JKNewExpression) {
if (newExpression.isAnonymousClass) {
printer.print("object : ")
}
printer.renderSymbol(newExpression.classSymbol, newExpression)
newExpression.typeArgumentList.accept(this)
if (!newExpression.classSymbol.isInterface() || newExpression.arguments.arguments.isNotEmpty()) {
printer.par(ParenthesisKind.ROUND) {
newExpression.arguments.accept(this)
}
}
if (newExpression.isAnonymousClass) {
newExpression.classBody.accept(this)
}
}
override fun visitKtItExpressionRaw(ktItExpression: JKKtItExpression) {
printer.print("it")
}
override fun visitClassBodyRaw(classBody: JKClassBody) {
val declarationsToPrint = classBody.declarations.filterNot { it is JKKtPrimaryConstructor }
renderTokenElement(classBody.leftBrace)
if (declarationsToPrint.isNotEmpty()) {
printer.indented {
printer.println()
val enumConstants = declarationsToPrint.filterIsInstance<JKEnumConstant>()
val otherDeclarations = declarationsToPrint.filterNot { it is JKEnumConstant }
renderEnumConstants(enumConstants)
if ((classBody.parent as? JKClass)?.classKind == ENUM
&& otherDeclarations.isNotEmpty()
) {
printer.print(";")
printer.println()
}
if (enumConstants.isNotEmpty() && otherDeclarations.isNotEmpty()) {
printer.println()
}
renderNonEnumClassDeclarations(otherDeclarations)
}
printer.println()
}
renderTokenElement(classBody.rightBrace)
}
override fun visitTypeElementRaw(typeElement: JKTypeElement) {
typeElement.annotationList.accept(this)
printer.renderType(typeElement.type, typeElement)
}
override fun visitBlockRaw(block: JKBlock) {
renderTokenElement(block.leftBrace)
if (block.statements.isNotEmpty()) {
printer.indented {
printer.println()
printer.renderList(block.statements, { printer.println() }) {
it.accept(this)
}
}
printer.println()
}
renderTokenElement(block.rightBrace)
}
override fun visitBlockStatementWithoutBracketsRaw(blockStatementWithoutBrackets: JKBlockStatementWithoutBrackets) {
printer.renderList(blockStatementWithoutBrackets.statements, { printer.println() }) {
it.accept(this)
}
}
override fun visitExpressionStatementRaw(expressionStatement: JKExpressionStatement) {
expressionStatement.expression.accept(this)
}
override fun visitReturnStatementRaw(returnStatement: JKReturnStatement) {
printer.print("return")
returnStatement.label.accept(this)
printer.print(" ")
returnStatement.expression.accept(this)
}
override fun visitFieldAccessExpressionRaw(fieldAccessExpression: JKFieldAccessExpression) {
printer.renderSymbol(fieldAccessExpression.identifier, fieldAccessExpression)
}
override fun visitPackageAccessExpressionRaw(packageAccessExpression: JKPackageAccessExpression) {
printer.renderSymbol(packageAccessExpression.identifier, packageAccessExpression)
}
override fun visitMethodReferenceExpressionRaw(methodReferenceExpression: JKMethodReferenceExpression) {
methodReferenceExpression.qualifier.accept(this)
printer.print("::")
val needFqName = methodReferenceExpression.qualifier is JKStubExpression
val displayName =
if (needFqName) methodReferenceExpression.identifier.getDisplayFqName()
else methodReferenceExpression.identifier.name
printer.print(displayName.escapedAsQualifiedName())
}
override fun visitDelegationConstructorCallRaw(delegationConstructorCall: JKDelegationConstructorCall) {
delegationConstructorCall.expression.accept(this)
printer.par {
delegationConstructorCall.arguments.accept(this)
}
}
private fun renderParameterList(parameters: List<JKParameter>) {
printer.par(ParenthesisKind.ROUND) {
printer.renderList(parameters) {
it.accept(this)
}
}
}
override fun visitConstructorRaw(constructor: JKConstructor) {
constructor.annotationList.accept(this)
if (constructor.annotationList.annotations.isNotEmpty()) {
printer.println()
}
renderModifiersList(constructor)
printer.print(" constructor")
renderParameterList(constructor.parameters)
if (constructor.delegationCall !is JKStubExpression) {
printer.print(" : ")
constructor.delegationCall.accept(this)
}
if (constructor.block.statements.isNotEmpty()) {
constructor.block.accept(this)
}
}
override fun visitKtPrimaryConstructorRaw(ktPrimaryConstructor: JKKtPrimaryConstructor) {
ktPrimaryConstructor.annotationList.accept(this)
renderModifiersList(ktPrimaryConstructor)
printer.print(" constructor ")
if (ktPrimaryConstructor.parameters.isNotEmpty()) {
renderParameterList(ktPrimaryConstructor.parameters)
} else {
printer.print("()")
}
}
override fun visitLambdaExpressionRaw(lambdaExpression: JKLambdaExpression) {
val printLambda = {
printer.par(ParenthesisKind.CURVED) {
if (lambdaExpression.statement.statements.size > 1)
printer.println()
printer.renderList(lambdaExpression.parameters) {
it.accept(this)
}
if (lambdaExpression.parameters.isNotEmpty()) {
printer.print(" -> ")
}
val statement = lambdaExpression.statement
if (statement is JKBlockStatement) {
printer.renderList(statement.block.statements, { printer.println() }) { it.accept(this) }
} else {
statement.accept(this)
}
if (lambdaExpression.statement.statements.size > 1) {
printer.println()
}
}
}
if (lambdaExpression.functionalType.present()) {
printer.renderType(lambdaExpression.functionalType.type, lambdaExpression)
printer.print(" ")
printer.par(ParenthesisKind.ROUND, printLambda)
} else {
printLambda()
}
}
override fun visitBlockStatementRaw(blockStatement: JKBlockStatement) {
blockStatement.block.accept(this)
}
override fun visitKtAssignmentStatementRaw(ktAssignmentStatement: JKKtAssignmentStatement) {
ktAssignmentStatement.field.accept(this)
printer.print(" ")
printer.print(ktAssignmentStatement.token.text)
printer.print(" ")
ktAssignmentStatement.expression.accept(this)
}
override fun visitAssignmentChainAlsoLinkRaw(assignmentChainAlsoLink: JKAssignmentChainAlsoLink) {
assignmentChainAlsoLink.receiver.accept(this)
printer.print(".also({ ")
assignmentChainAlsoLink.assignmentStatement.accept(this)
printer.print(" })")
}
override fun visitAssignmentChainLetLinkRaw(assignmentChainLetLink: JKAssignmentChainLetLink) {
assignmentChainLetLink.receiver.accept(this)
printer.print(".let({ ")
assignmentChainLetLink.assignmentStatement.accept(this)
printer.print("; ")
assignmentChainLetLink.field.accept(this)
printer.print(" })")
}
override fun visitKtWhenBlockRaw(ktWhenBlock: JKKtWhenBlock) {
printer.print("when(")
ktWhenBlock.expression.accept(this)
printer.print(")")
printer.block {
printer.renderList(ktWhenBlock.cases, { printer.println() }) {
it.accept(this)
}
}
}
override fun visitKtWhenExpression(ktWhenExpression: JKKtWhenExpression) {
visitKtWhenBlockRaw(ktWhenExpression)
}
override fun visitKtWhenStatement(ktWhenStatement: JKKtWhenStatement) {
visitKtWhenBlockRaw(ktWhenStatement)
}
override fun visitAnnotationListRaw(annotationList: JKAnnotationList) {
printer.renderList(annotationList.annotations, " ") {
it.accept(this)
}
if (annotationList.annotations.isNotEmpty()) {
printer.print(" ")
}
}
override fun visitAnnotationRaw(annotation: JKAnnotation) {
printer.print("@")
printer.renderSymbol(annotation.classSymbol, annotation)
if (annotation.arguments.isNotEmpty()) {
printer.par {
printer.renderList(annotation.arguments) { it.accept(this) }
}
}
}
override fun visitAnnotationNameParameterRaw(annotationNameParameter: JKAnnotationNameParameter) {
annotationNameParameter.name.accept(this)
printer.print(" = ")
annotationNameParameter.value.accept(this)
}
override fun visitAnnotationParameterRaw(annotationParameter: JKAnnotationParameter) {
annotationParameter.value.accept(this)
}
override fun visitClassLiteralExpressionRaw(classLiteralExpression: JKClassLiteralExpression) {
if (classLiteralExpression.literalType == JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE) {
printer.print("Void.TYPE")
} else {
printer.renderType(classLiteralExpression.classType.type, classLiteralExpression)
printer.print("::")
when (classLiteralExpression.literalType) {
JKClassLiteralExpression.ClassLiteralType.KOTLIN_CLASS -> printer.print("class")
JKClassLiteralExpression.ClassLiteralType.JAVA_CLASS -> printer.print("class.java")
JKClassLiteralExpression.ClassLiteralType.JAVA_PRIMITIVE_CLASS -> printer.print("class.javaPrimitiveType")
JKClassLiteralExpression.ClassLiteralType.JAVA_VOID_TYPE -> Unit
}
}
}
override fun visitKtWhenCaseRaw(ktWhenCase: JKKtWhenCase) {
printer.renderList(ktWhenCase.labels) {
it.accept(this)
}
printer.print(" -> ")
ktWhenCase.statement.accept(this)
}
override fun visitKtElseWhenLabelRaw(ktElseWhenLabel: JKKtElseWhenLabel) {
printer.print("else")
}
override fun visitKtValueWhenLabelRaw(ktValueWhenLabel: JKKtValueWhenLabel) {
ktValueWhenLabel.expression.accept(this)
}
override fun visitErrorStatement(errorStatement: JKErrorStatement) {
visitErrorElement(errorStatement)
}
private fun visitErrorElement(errorElement: JKErrorElement) {
val message = buildString {
append("Cannot convert element: ${errorElement.reason}")
errorElement.psi?.let { append("\nWith text:\n${it.text}") }
}
printer.print("TODO(")
printer.indented {
printer.print("\"\"\"")
printer.println()
message.split('\n').forEach { line ->
printer.print("|")
printer.print(line.replace("$", "\\$"))
printer.println()
}
printer.print("\"\"\"")
}
printer.print(").trimMargin()")
}
}
}
| apache-2.0 | 2f71a2e0768bb48a9d392877755b047c | 39 | 137 | 0.597719 | 5.847641 | false | false | false | false |
google/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/KotlinPullUpDialog.kt | 2 | 7464 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.MemberInfoChange
import com.intellij.refactoring.classMembers.MemberInfoModel
import com.intellij.refactoring.memberPullUp.PullUpProcessor
import com.intellij.refactoring.util.DocCommentPolicy
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.isCompanionMemberOf
import org.jetbrains.kotlin.idea.refactoring.isConstructorDeclaredProperty
import org.jetbrains.kotlin.idea.refactoring.isInterfaceClass
import org.jetbrains.kotlin.idea.refactoring.memberInfo.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
class KotlinPullUpDialog(
project: Project,
classOrObject: KtClassOrObject,
superClasses: List<PsiNamedElement>,
memberInfoStorage: KotlinMemberInfoStorage
) : KotlinPullUpDialogBase(
project, classOrObject, superClasses, memberInfoStorage, PULL_MEMBERS_UP
) {
init {
init()
}
private inner class MemberInfoModelImpl(
originalClass: KtClassOrObject,
superClass: PsiNamedElement?,
interfaceContainmentVerifier: (KtNamedDeclaration) -> Boolean
) : KotlinUsesAndInterfacesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
originalClass,
superClass,
false,
interfaceContainmentVerifier
) {
private var lastSuperClass: PsiNamedElement? = null
private fun KtNamedDeclaration.isConstructorParameterWithInterfaceTarget(targetClass: PsiNamedElement): Boolean {
return targetClass is KtClass && targetClass.isInterface() && isConstructorDeclaredProperty()
}
// Abstract members remain abstract
override fun isFixedAbstract(memberInfo: KotlinMemberInfo?) = true
/*
* Any non-abstract function can change abstractness.
*
* Non-abstract property with initializer or delegate is always made abstract.
* Any other non-abstract property can change abstractness.
*
* Classes do not have abstractness
*/
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
val superClass = superClass ?: return false
if (superClass is PsiClass) return false
if (superClass !is KtClass) return false
val member = memberInfo.member
if (member.hasModifier(KtTokens.INLINE_KEYWORD) ||
member.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
member.hasModifier(KtTokens.LATEINIT_KEYWORD)
) return false
if (member.isAbstractInInterface(sourceClass)) return false
if (member.isConstructorParameterWithInterfaceTarget(superClass)) return false
if (member.isCompanionMemberOf(sourceClass)) return false
if (!superClass.isInterface()) return true
return member is KtNamedFunction || (member is KtProperty && !member.mustBeAbstractInInterface()) || member is KtParameter
}
override fun isAbstractWhenDisabled(memberInfo: KotlinMemberInfo): Boolean {
val superClass = superClass
val member = memberInfo.member
if (member.isCompanionMemberOf(sourceClass)) return false
if (member.isAbstractInInterface(sourceClass)) return true
if (superClass != null && member.isConstructorParameterWithInterfaceTarget(superClass)) return true
return ((member is KtProperty || member is KtParameter) && superClass !is PsiClass)
|| (member is KtNamedFunction && superClass is PsiClass)
}
override fun isMemberEnabled(memberInfo: KotlinMemberInfo): Boolean {
val superClass = superClass ?: return false
val member = memberInfo.member
if (member.hasModifier(KtTokens.CONST_KEYWORD)) return false
if (superClass is KtClass && superClass.isInterface() &&
(member.hasModifier(KtTokens.INTERNAL_KEYWORD) || member.hasModifier(KtTokens.PROTECTED_KEYWORD))
) return false
if (superClass is PsiClass) {
if (!member.canMoveMemberToJavaClass(superClass)) return false
if (member.isCompanionMemberOf(sourceClass)) return false
}
if (memberInfo in memberInfoStorage.getDuplicatedMemberInfos(superClass)) return false
if (member in memberInfoStorage.getExtending(superClass)) return false
return true
}
override fun memberInfoChanged(event: MemberInfoChange<KtNamedDeclaration, KotlinMemberInfo>) {
super.memberInfoChanged(event)
val superClass = superClass ?: return
if (superClass != lastSuperClass) {
lastSuperClass = superClass
val isInterface = superClass is KtClass && superClass.isInterface()
event.changedMembers.forEach { it.isToAbstract = isInterface }
setSuperClass(superClass)
}
}
}
private val memberInfoStorage: KotlinMemberInfoStorage get() = myMemberInfoStorage
private val sourceClass: KtClassOrObject get() = myClass as KtClassOrObject
override fun getDimensionServiceKey() = "#" + this::class.java.name
override fun getSuperClass() = super.getSuperClass()
override fun createMemberInfoModel(): MemberInfoModel<KtNamedDeclaration, KotlinMemberInfo> =
MemberInfoModelImpl(sourceClass, preselection, getInterfaceContainmentVerifier { selectedMemberInfos })
override fun getPreselection() = mySuperClasses.firstOrNull { !it.isInterfaceClass() } ?: mySuperClasses.firstOrNull()
override fun createMemberSelectionTable(infos: MutableList<KotlinMemberInfo>) =
KotlinMemberSelectionTable(infos, null, RefactoringBundle.message("make.abstract"))
override fun isOKActionEnabled() = selectedMemberInfos.size > 0
override fun doAction() {
val selectedMembers = selectedMemberInfos
val targetClass = superClass!!
checkConflicts(project, sourceClass, targetClass, selectedMembers, { close(DialogWrapper.OK_EXIT_CODE) }) {
invokeRefactoring(createProcessor(sourceClass, targetClass, selectedMembers))
}
}
companion object {
fun createProcessor(
sourceClass: KtClassOrObject,
targetClass: PsiNamedElement,
memberInfos: List<KotlinMemberInfo>
): PullUpProcessor {
val targetPsiClass = targetClass as? PsiClass ?: (targetClass as KtClass).toLightClass()
return PullUpProcessor(
sourceClass.toLightClass() ?: error("can't build lightClass for $sourceClass"),
targetPsiClass,
memberInfos.mapNotNull { it.toJavaMemberInfo() }.toTypedArray(),
DocCommentPolicy<PsiComment>(KotlinRefactoringSettings.instance.PULL_UP_MEMBERS_JAVADOC)
)
}
}
} | apache-2.0 | 840296b643335730a901eefb28ef29c7 | 44.518293 | 158 | 0.70351 | 5.732719 | false | false | false | false |
Leifzhang/AndroidRouter | kspCompiler/src/main/java/com/kronos/ksp/compiler/KspUtils.kt | 2 | 5729 | package com.kronos.ksp.compiler
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.ClassKind.CLASS
import com.google.devtools.ksp.symbol.Origin.KOTLIN
import com.google.devtools.ksp.symbol.Visibility
import com.google.devtools.ksp.symbol.Visibility.INTERNAL
import com.google.devtools.ksp.symbol.Visibility.JAVA_PACKAGE
import com.google.devtools.ksp.symbol.Visibility.LOCAL
import com.google.devtools.ksp.symbol.Visibility.PRIVATE
import com.google.devtools.ksp.symbol.Visibility.PROTECTED
import com.google.devtools.ksp.symbol.Visibility.PUBLIC
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.KModifier
/**
*
* @Author LiABao
* @Since 2021/3/8
*
*/
internal inline fun <reified T> Resolver.getClassDeclarationByName(): KSClassDeclaration {
return getClassDeclarationByName(T::class.qualifiedName!!)
}
internal fun Resolver.getClassDeclarationByName(fqcn: String): KSClassDeclaration {
return getClassDeclarationByName(getKSNameFromString(fqcn)) ?: error("Class '$fqcn' not found.")
}
internal fun KSClassDeclaration.asType() = asType(emptyList())
internal fun KSClassDeclaration.superclass(resolver: Resolver): KSType {
return getAllSuperTypes().firstOrNull {
val decl = it.declaration
decl is KSClassDeclaration && decl.classKind == CLASS
} ?: resolver.builtIns.anyType
}
internal fun KSClassDeclaration.isKotlinClass(resolver: Resolver): Boolean {
return origin == KOTLIN ||
hasAnnotation(resolver.getClassDeclarationByName<Metadata>().asType())
}
internal fun KSAnnotated.hasAnnotation(target: KSType): Boolean {
return findAnnotationWithType(target) != null
}
internal inline fun <reified T : Annotation> KSAnnotated.findAnnotationWithType(
resolver: Resolver,
): KSAnnotation? {
return findAnnotationWithType(resolver.getClassDeclarationByName<T>().asType())
}
internal fun KSAnnotated.findAnnotationWithType(target: KSType): KSAnnotation? {
return annotations.find { it.annotationType.resolve() == target }
}
internal inline fun <reified T> KSAnnotation.getMember(name: String): T {
val matchingArg = arguments.find { it.name?.asString() == name }
?: error(
"No member name found for '$name'. All arguments: ${arguments.map { it.name?.asString() }}"
)
return when (val argValue = matchingArg.value) {
is List<*> -> {
if (argValue.isEmpty()) {
argValue as T
} else {
val first = argValue[0]
if (first is KSType) {
argValue.map { (it as KSType).toClassName() } as T
} else {
argValue as T
}
}
}
is KSType -> argValue.toClassName() as T
else -> {
argValue as? T ?: error("No value found for $name. Was ${matchingArg.value}")
}
}
}
internal fun Visibility.asKModifier(): KModifier {
return when (this) {
PUBLIC -> KModifier.PUBLIC
PRIVATE -> KModifier.PRIVATE
PROTECTED -> KModifier.PROTECTED
INTERNAL -> KModifier.INTERNAL
JAVA_PACKAGE -> KModifier.PUBLIC
LOCAL -> error("Local is unsupported")
}
}
internal fun KSAnnotation.toAnnotationSpec(resolver: Resolver): AnnotationSpec {
val element = annotationType.resolve().declaration as KSClassDeclaration
// TODO support generic annotations
val builder = AnnotationSpec.builder(element.toClassName())
for (argument in arguments) {
val member = CodeBlock.builder()
val name = argument.name!!.getShortName()
member.add("%L = ", name)
when (val value = argument.value!!) {
resolver.builtIns.arrayType -> {
// TODO("Arrays aren't supported yet")
// member.add("[⇥⇥")
// values.forEachIndexed { index, value ->
// if (index > 0) member.add(", ")
// value.accept(this, name)
// }
// member.add("⇤⇤]")
}
is KSType -> member.add("%T::class", value.toClassName())
// TODO is this the right way to handle an enum constant?
is KSName ->
member.add(
"%T.%L", ClassName.bestGuess(value.getQualifier()),
value.getShortName()
)
is KSAnnotation -> member.add("%L", value.toAnnotationSpec(resolver))
else -> member.add(memberForValue(value))
}
builder.addMember(member.build())
}
return builder.build()
}
/**
* Creates a [CodeBlock] with parameter `format` depending on the given `value` object.
* Handles a number of special cases, such as appending "f" to `Float` values, and uses
* `%L` for other types.
*/
internal fun memberForValue(value: Any) = when (value) {
is Class<*> -> CodeBlock.of("%T::class", value)
is Enum<*> -> CodeBlock.of("%T.%L", value.javaClass, value.name)
is String -> CodeBlock.of("%S", value)
is Float -> CodeBlock.of("%Lf", value)
// is Char -> CodeBlock.of("'%L'", characterLiteralWithoutSingleQuotes(value)) // TODO public?
else -> CodeBlock.of("%L", value)
}
internal inline fun KSPLogger.check(condition: Boolean, message: () -> String) {
check(condition, null, message)
}
internal inline fun KSPLogger.check(condition: Boolean, element: KSNode?, message: () -> String) {
if (!condition) {
error(message(), element)
}
} | mit | 1836e7404636d29c0e1b942de7213d10 | 35.679487 | 111 | 0.657228 | 4.317736 | false | false | false | false |
vhromada/Catalog | web/src/test/kotlin/com/github/vhromada/catalog/web/mapper/EpisodeMapperTest.kt | 1 | 1382 | package com.github.vhromada.catalog.web.mapper
import com.github.vhromada.catalog.web.CatalogWebMapperTestConfiguration
import com.github.vhromada.catalog.web.utils.EpisodeUtils
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
/**
* A class represents test for mapper for episodes.
*
* @author Vladimir Hromada
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(classes = [CatalogWebMapperTestConfiguration::class])
class EpisodeMapperTest {
/**
* Instance of [EpisodeMapper]
*/
@Autowired
private lateinit var mapper: EpisodeMapper
/**
* Test method for [EpisodeMapper.map].
*/
@Test
fun map() {
val episode = EpisodeUtils.getEpisode()
val result = mapper.map(source = episode)
EpisodeUtils.assertEpisodeDeepEquals(expected = episode, actual = result)
}
/**
* Test method for [EpisodeMapper.mapRequest].
*/
@Test
fun mapRequest() {
val episodeFO = EpisodeUtils.getEpisodeFO()
val result = mapper.mapRequest(source = episodeFO)
EpisodeUtils.assertRequestDeepEquals(expected = episodeFO, actual = result)
}
}
| mit | 82bc42c834837e1e462443709c822836 | 26.64 | 83 | 0.72576 | 4.373418 | false | true | false | false |
JetBrains/intellij-community | plugins/kotlin/kotlin.searching/base/src/org/jetbrains/kotlin/idea/base/searching/usages/handlers/KotlinFindClassUsagesHandler.kt | 1 | 7941 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.searching.usages.handlers
import com.intellij.find.findUsages.AbstractFindUsagesDialog
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.find.findUsages.JavaFindUsagesHelper
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.runReadAction
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.search.PsiElementProcessor
import com.intellij.psi.search.PsiElementProcessorAdapter
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageInfo
import com.intellij.util.FilteredQuery
import com.intellij.util.Processor
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinClassFindUsagesOptions
import org.jetbrains.kotlin.idea.base.searching.usages.KotlinFindUsagesHandlerFactory
import org.jetbrains.kotlin.idea.base.searching.usages.dialogs.KotlinFindClassUsagesDialog
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.isConstructorUsage
import org.jetbrains.kotlin.idea.findUsages.KotlinFindUsagesSupport.Companion.processCompanionObjectInternalReferences
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchOptions
import org.jetbrains.kotlin.idea.search.ideaExtensions.KotlinReferencesSearchParameters
import org.jetbrains.kotlin.idea.search.isImportUsage
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.contains
import org.jetbrains.kotlin.psi.psiUtil.effectiveDeclarations
import java.util.*
class KotlinFindClassUsagesHandler(
ktClass: KtClassOrObject,
factory: KotlinFindUsagesHandlerFactory
) : KotlinFindUsagesHandler<KtClassOrObject>(ktClass, factory) {
override fun getFindUsagesDialog(
isSingleFile: Boolean, toShowInNewTab: Boolean, mustOpenInNewTab: Boolean
): AbstractFindUsagesDialog {
return KotlinFindClassUsagesDialog(
getElement(),
project,
factory.findClassOptions,
toShowInNewTab,
mustOpenInNewTab,
isSingleFile,
this
)
}
override fun createSearcher(
element: PsiElement,
processor: Processor<in UsageInfo>,
options: FindUsagesOptions
): Searcher {
return MySearcher(element, processor, options)
}
private class MySearcher(
element: PsiElement, processor: Processor<in UsageInfo>, options: FindUsagesOptions
) : Searcher(element, processor, options) {
private val kotlinOptions = options as KotlinClassFindUsagesOptions
private val referenceProcessor = createReferenceProcessor(processor)
override fun buildTaskList(forHighlight: Boolean): Boolean {
val classOrObject = element as KtClassOrObject
if (kotlinOptions.isUsages || kotlinOptions.searchConstructorUsages) {
processClassReferencesLater(classOrObject)
}
if (kotlinOptions.isFieldsUsages || kotlinOptions.isMethodsUsages) {
processMemberReferencesLater(classOrObject)
}
if (kotlinOptions.isUsages && classOrObject is KtObjectDeclaration && classOrObject.isCompanion() && classOrObject in options.searchScope) {
if (!processCompanionObjectInternalReferences(classOrObject, referenceProcessor)) return false
}
if (kotlinOptions.searchConstructorUsages) {
classOrObject.toLightClass()?.constructors?.filterIsInstance<KtLightMethod>()?.forEach { constructor ->
val scope = constructor.useScope.intersectWith(options.searchScope)
var query = MethodReferencesSearch.search(constructor, scope, true)
if (kotlinOptions.isSkipImportStatements) {
query = FilteredQuery(query) { !it.isImportUsage() }
}
addTask { query.forEach(Processor { referenceProcessor.process(it) }) }
}
}
if (kotlinOptions.isDerivedClasses || kotlinOptions.isDerivedInterfaces) {
processInheritorsLater()
}
return true
}
private fun processInheritorsLater() {
val request = HierarchySearchRequest(element, options.searchScope, kotlinOptions.isCheckDeepInheritance)
addTask {
request.searchInheritors().forEach(
PsiElementProcessorAdapter(
PsiElementProcessor<PsiClass> { element ->
runReadAction {
if (!element.isValid) return@runReadAction false
val isInterface = element.isInterface
when {
isInterface && kotlinOptions.isDerivedInterfaces || !isInterface && kotlinOptions.isDerivedClasses ->
processUsage(processor, element.navigationElement)
else -> true
}
}
}
)
)
}
}
private fun processClassReferencesLater(classOrObject: KtClassOrObject) {
val searchParameters = KotlinReferencesSearchParameters(
classOrObject,
scope = options.searchScope,
kotlinOptions = KotlinReferencesSearchOptions(
acceptCompanionObjectMembers = true,
searchForExpectedUsages = kotlinOptions.searchExpected
)
)
var usagesQuery = ReferencesSearch.search(searchParameters)
if (kotlinOptions.isSkipImportStatements) {
usagesQuery = FilteredQuery(usagesQuery) { !it.isImportUsage() }
}
if (!kotlinOptions.searchConstructorUsages) {
usagesQuery = FilteredQuery(usagesQuery) { !it.isConstructorUsage(classOrObject) }
} else if (!options.isUsages) {
usagesQuery = FilteredQuery(usagesQuery) { it.isConstructorUsage(classOrObject) }
}
addTask { usagesQuery.forEach(referenceProcessor) }
}
private fun processMemberReferencesLater(classOrObject: KtClassOrObject) {
for (declaration in classOrObject.effectiveDeclarations()) {
if ((declaration is KtNamedFunction && kotlinOptions.isMethodsUsages) ||
((declaration is KtProperty || declaration is KtParameter) && kotlinOptions.isFieldsUsages)
) {
addTask { ReferencesSearch.search(declaration, options.searchScope).forEach(referenceProcessor) }
}
}
}
}
override fun getStringsToSearch(element: PsiElement): Collection<String> {
val psiClass = when (element) {
is PsiClass -> element
is KtClassOrObject -> getElement().toLightClass()
else -> null
} ?: return Collections.emptyList()
return JavaFindUsagesHelper.getElementNames(psiClass)
}
override fun isSearchForTextOccurrencesAvailable(psiElement: PsiElement, isSingleFile: Boolean): Boolean {
return !isSingleFile
}
override fun getFindUsagesOptions(dataContext: DataContext?): FindUsagesOptions {
return factory.findClassOptions
}
}
| apache-2.0 | b39d522a11997a6102b7fcd7b5e6704e | 44.377143 | 152 | 0.672459 | 5.84757 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/parser/token/HaskellLexerTokens.kt | 1 | 2621 | package org.jetbrains.haskell.parser.token
import org.jetbrains.haskell.parser.HaskellTokenType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.TokenType
import java.util.ArrayList
import org.jetbrains.grammar.HaskellLexerTokens
import org.jetbrains.haskell.parser.cpp.CPPTokens
/**
* Created by atsky on 3/12/14.
*/
val KEYWORDS: List<HaskellTokenType> = listOf(
HaskellLexerTokens.CASE,
HaskellLexerTokens.CLASS,
HaskellLexerTokens.DATA,
HaskellLexerTokens.DEFAULT,
HaskellLexerTokens.DERIVING,
HaskellLexerTokens.DO,
HaskellLexerTokens.ELSE,
HaskellLexerTokens.EXPORT,
HaskellLexerTokens.IF,
HaskellLexerTokens.IMPORT,
HaskellLexerTokens.IN,
HaskellLexerTokens.INFIX,
HaskellLexerTokens.INFIXL,
HaskellLexerTokens.INFIXR,
HaskellLexerTokens.INSTANCE,
HaskellLexerTokens.FORALL,
HaskellLexerTokens.FOREIGN,
HaskellLexerTokens.LET,
HaskellLexerTokens.MODULE,
HaskellLexerTokens.NEWTYPE,
HaskellLexerTokens.OF,
HaskellLexerTokens.THEN,
HaskellLexerTokens.WHERE,
HaskellLexerTokens.TYPE,
HaskellLexerTokens.SAFE,
HaskellLexerTokens.UNSAFE)
val OPERATORS: List<HaskellTokenType> = listOf<HaskellTokenType>(
HaskellLexerTokens.AT,
HaskellLexerTokens.TILDE,
HaskellLexerTokens.LAM,
HaskellLexerTokens.DARROW,
HaskellLexerTokens.BANG,
HaskellLexerTokens.RARROW,
HaskellLexerTokens.LARROW,
HaskellLexerTokens.EQUAL,
HaskellLexerTokens.COMMA,
HaskellLexerTokens.DOT,
HaskellLexerTokens.DOTDOT,
HaskellLexerTokens.DCOLON,
HaskellLexerTokens.OPAREN,
HaskellLexerTokens.CPAREN,
HaskellLexerTokens.OCURLY,
HaskellLexerTokens.CCURLY,
HaskellLexerTokens.OBRACK,
HaskellLexerTokens.CBRACK,
HaskellLexerTokens.SEMI,
HaskellLexerTokens.COLON,
HaskellLexerTokens.VBAR,
HaskellLexerTokens.UNDERSCORE)
val BLOCK_COMMENT: HaskellTokenType = HaskellTokenType("COMMENT")
val END_OF_LINE_COMMENT: HaskellTokenType = HaskellTokenType("--")
val PRAGMA: HaskellTokenType = HaskellTokenType("PRAGMA")
val NEW_LINE: HaskellTokenType = HaskellTokenType("NL")
val COMMENTS: TokenSet = TokenSet.create(
END_OF_LINE_COMMENT,
BLOCK_COMMENT,
PRAGMA,
CPPTokens.IF,
CPPTokens.ENDIF,
CPPTokens.ELSE,
CPPTokens.IFDEF)
val WHITESPACES: TokenSet = TokenSet.create(TokenType.WHITE_SPACE, NEW_LINE) | apache-2.0 | 46c5f8fd6ff57df3cfc7a32a70ced108 | 30.97561 | 76 | 0.706601 | 5.109162 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/filters/FiltersViewBindingAdapters.kt | 3 | 3233 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.filters
import android.content.res.ColorStateList
import android.graphics.Color
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.databinding.BindingAdapter
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.chip.Chip
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.widget.SpaceDecoration
@BindingAdapter("activeFilters", "viewModel", requireAll = true)
fun activeFilters(
recyclerView: RecyclerView,
filters: List<FilterChip>?,
viewModel: FiltersViewModelDelegate
) {
val filterChipAdapter: CloseableFilterChipAdapter
if (recyclerView.adapter == null) {
filterChipAdapter = CloseableFilterChipAdapter(viewModel)
recyclerView.apply {
adapter = filterChipAdapter
val space = resources.getDimensionPixelSize(R.dimen.spacing_micro)
addItemDecoration(SpaceDecoration(start = space, end = space))
}
} else {
filterChipAdapter = recyclerView.adapter as CloseableFilterChipAdapter
}
filterChipAdapter.submitList(filters ?: emptyList())
}
@BindingAdapter("showResultCount", "resultCount", requireAll = true)
fun filterHeader(textView: TextView, showResultCount: Boolean?, resultCount: Int?) {
if (showResultCount == true && resultCount != null) {
textView.text = textView.resources.getString(R.string.result_count, resultCount)
} else {
textView.setText(R.string.filters)
}
}
@BindingAdapter("filterChipOnClick", "viewModel", requireAll = true)
fun filterChipOnClick(
chip: Chip,
filterChip: FilterChip,
viewModel: FiltersViewModelDelegate
) {
chip.setOnClickListener {
viewModel.toggleFilter(filterChip.filter, !filterChip.isSelected)
}
}
@BindingAdapter("filterChipOnClose", "viewModel", requireAll = true)
fun filterChipOnClose(
chip: Chip,
filterChip: FilterChip,
viewModel: FiltersViewModelDelegate
) {
chip.setOnCloseIconClickListener {
viewModel.toggleFilter(filterChip.filter, false)
}
}
@BindingAdapter("filterChipText")
fun filterChipText(chip: Chip, filter: FilterChip) {
if (filter.textResId != 0) {
chip.setText(filter.textResId)
} else {
chip.text = filter.text
}
}
@BindingAdapter("filterChipTint")
fun filterChipTint(chip: Chip, color: Int) {
val tintColor = if (color != Color.TRANSPARENT) {
color
} else {
ContextCompat.getColor(chip.context, R.color.default_tag_color)
}
chip.chipIconTint = ColorStateList.valueOf(tintColor)
}
| apache-2.0 | 17ed1c1639c1d14a3514a43a53272809 | 32.329897 | 88 | 0.730591 | 4.287798 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/course_revenue/reducer/CourseBenefitsMonthlyReducer.kt | 1 | 3200 | package org.stepik.android.presentation.course_revenue.reducer
import org.stepik.android.domain.course_revenue.model.CourseBenefitByMonthListItem
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.State
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.Message
import org.stepik.android.presentation.course_revenue.CourseBenefitsMonthlyFeature.Action
import ru.nobird.app.core.model.concatWithPagedList
import ru.nobird.app.presentation.redux.reducer.StateReducer
import javax.inject.Inject
class CourseBenefitsMonthlyReducer
@Inject
constructor() : StateReducer<State, Message, Action> {
override fun reduce(state: State, message: Message): Pair<State, Set<Action>> =
when (message) {
is Message.FetchCourseBenefitsByMonthsSuccess -> {
when (state) {
is State.Loading -> {
val courseBenefitsMonthlyState =
if (message.courseBenefitByMonthListDataItems.isEmpty()) {
State.Empty
} else {
State.Content(message.courseBenefitByMonthListDataItems, message.courseBenefitByMonthListDataItems)
}
courseBenefitsMonthlyState to emptySet()
}
is State.Content -> {
val resultingList = state.courseBenefitByMonthListDataItems.concatWithPagedList(message.courseBenefitByMonthListDataItems)
state.copy(courseBenefitByMonthListDataItems = resultingList, courseBenefitByMonthListItems = resultingList) to emptySet()
}
else ->
null
}
}
is Message.FetchCourseBenefitsByMonthsFailure -> {
when (state) {
is State.Loading ->
State.Error to emptySet()
is State.Content ->
state to emptySet()
else ->
null
}
}
is Message.FetchCourseBenefitsByMonthNext -> {
if (state is State.Content) {
if (state.courseBenefitByMonthListDataItems.hasNext && state.courseBenefitByMonthListItems.last() !is CourseBenefitByMonthListItem.Placeholder) {
state.copy(courseBenefitByMonthListItems = state.courseBenefitByMonthListItems + CourseBenefitByMonthListItem.Placeholder) to
setOf(Action.FetchCourseBenefitsByMonths(message.courseId, state.courseBenefitByMonthListDataItems.page + 1))
} else {
null
}
} else {
null
}
}
is Message.TryAgain -> {
if (state is State.Error) {
State.Loading to setOf(Action.FetchCourseBenefitsByMonths(message.courseId))
} else {
null
}
}
} ?: state to emptySet()
} | apache-2.0 | 432e5e75d73f5802e5b93e75ece3d299 | 46.776119 | 165 | 0.572188 | 5.818182 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/backends/Shaders.kt | 1 | 10045 | package graphics.scenery.backends
import graphics.scenery.utils.LazyLogger
import org.lwjgl.util.shaderc.Shaderc
import java.util.concurrent.ConcurrentHashMap
/**
* Shaders handling class.
*
* @author Ulrik Guenther <[email protected]>
*/
sealed class Shaders() {
val logger by LazyLogger()
var stale: Boolean = false
val type: HashSet<ShaderType> = hashSetOf()
/**
* Enum to indicate whether a shader will target Vulkan or OpenGL.
*/
enum class ShaderTarget { Vulkan, OpenGL }
/**
* Abstract base class for custom shader factories.
*/
abstract class ShaderFactory : Shaders() {
/**
* Invoked by [get] to actually construct a [ShaderPackage].
*/
abstract fun construct(target: ShaderTarget, type: ShaderType): ShaderPackage
/**
* Returns a [ShaderPackage] targeting [target] (OpenGL or Vulkan), containing
* a shader of [type].
*/
override fun get(target: ShaderTarget, type: ShaderType): ShaderPackage {
return construct(target, type)
}
}
/**
* Base class for producing a shader provider that is backed by files given in
* [shaders], which are assumed to be relative to a class [clazz].
*/
open class ShadersFromFiles(val shaders: Array<String>,
val clazz: Class<*> = Renderer::class.java) : Shaders() {
init {
type.addAll(shaders.map {
val extension = it.lowercase().substringBeforeLast(".spv").substringAfterLast(".").trim()
when(extension) {
"vert" -> ShaderType.VertexShader
"frag" -> ShaderType.FragmentShader
"comp" -> ShaderType.ComputeShader
"tesc" -> ShaderType.TessellationControlShader
"tese" -> ShaderType.TessellationEvaluationShader
"geom" -> ShaderType.GeometryShader
else -> throw IllegalArgumentException(".$extension is not a valid shader file extension")
}
})
}
/**
* Returns a [ShaderPackage] targeting [target] (OpenGL or Vulkan), containing
* a shader of [type].
*/
override fun get(target: ShaderTarget, type: ShaderType): ShaderPackage {
val shaderCodePath = shaders.find { it.endsWith(type.toExtension()) || it.endsWith(type.toExtension() + ".spv") }
?: throw ShaderNotFoundException("Could not locate $type from ${shaders.joinToString(", ")}")
val spirvPath: String
val codePath: String
if (shaderCodePath.endsWith(".spv")) {
spirvPath = shaderCodePath
codePath = shaderCodePath.substringBeforeLast(".spv")
} else {
spirvPath = "$shaderCodePath.spv"
codePath = shaderCodePath
}
val cached = cache[ShaderPaths(spirvPath, codePath)]
if (cached != null) {
return cached
}
val baseClass = arrayOf(spirvPath, codePath).mapNotNull { safeFindBaseClass(arrayOf(clazz, Renderer::class.java), it) }
if (baseClass.isEmpty()) {
throw ShaderCompilationException("Shader files for $shaderCodePath ($spirvPath, $codePath) not found.")
}
val base = baseClass.first()
val pathPrefix = base.second
val spirvFromFile: ByteArray? = base.first.getResourceAsStream("$pathPrefix$spirvPath")?.readBytes()
val codeFromFile: String? = base.first.getResourceAsStream("$pathPrefix$codePath")?.bufferedReader().use { it?.readText() }
val shaderPackage = ShaderPackage(base.first,
type,
"$pathPrefix$spirvPath",
"$pathPrefix$codePath",
spirvFromFile,
codeFromFile,
SourceSPIRVPriority.SourcePriority)
val p = compile(shaderPackage, type, target, base.first)
cache.putIfAbsent(ShaderPaths(spirvPath, codePath), p)
return p
}
override fun toString(): String {
return "ShadersFromFiles: ${shaders.joinToString(",")}"
}
/**
* Data class for storing pairs of paths to SPIRV and to code path files
*/
data class ShaderPaths(val spirvPath: String, val codePath: String)
/**
* Companion object providing a cache for preventing repeated compilations.
*/
companion object {
protected val cache = ConcurrentHashMap<ShaderPaths, ShaderPackage>()
}
}
/**
* Shader provider for deriving a [ShadersFromFiles] provider just by using
* the simpleName of [clazz].
*/
class ShadersFromClassName @JvmOverloads constructor(clazz: Class<*>, shaderTypes: List<ShaderType> = listOf(ShaderType.VertexShader, ShaderType.FragmentShader)):
ShadersFromFiles(
shaderTypes
.map { it.toExtension() }.toTypedArray()
.map { "${clazz.simpleName}$it" }.toTypedArray(), clazz) {
init {
type.addAll(shaderTypes)
}
}
/**
* Abstract functions all shader providers will have to implement, for returning
* a [ShaderPackage] containing both source code and SPIRV, targeting [target],
* and being of [ShaderType] [type].
*/
abstract fun get(target: ShaderTarget, type: ShaderType): ShaderPackage
/**
* Finds the base class for a resource given by [path], and falls back to
* [Renderer] in case it is not found before. Returns null if the file cannot
* be located. The function also falls back to looking into a subdirectory "shaders/",
* if the files cannot be located within the normal neighborhood of the resources in [classes].
*/
protected fun safeFindBaseClass(classes: Array<Class<*>>, path: String): Pair<Class<*>, String>? {
logger.debug("Looking for $path in ${classes.map { it.simpleName }.joinToString(", ")}")
val streams = classes.map { clazz ->
clazz to clazz.getResourceAsStream(path)
}.filter { it.second != null }.toMutableList()
var pathPrefix = ""
if(streams.isEmpty()) {
pathPrefix = "shaders/"
}
streams.addAll(classes.map { clazz ->
clazz to clazz.getResourceAsStream("$pathPrefix$path")
}.filter { it.second != null })
if(streams.isEmpty()) {
if(classes.contains(Renderer::class.java) && !path.endsWith(".spv")) {
logger.warn("Shader path $path not found within given classes, falling back to default.")
} else {
logger.debug("Shader path $path not found within given classes, falling back to default.")
}
} else {
return streams.first().first to pathPrefix
}
return if(Renderer::class.java.getResourceAsStream(path) == null) {
if(!path.endsWith(".spv")) {
logger.warn("Shader path $path not found in class path of Renderer.")
}
null
} else {
Renderer::class.java to pathPrefix
}
}
protected fun compile(shaderPackage: ShaderPackage, type: ShaderType, target: ShaderTarget, base: Class<*>): ShaderPackage {
val sourceCode: String
val debug = System.getProperty("scenery.ShaderCompiler.Debug", "false").toBoolean()
val strict = System.getProperty("scenery.ShaderCompiler.Strict", "false").toBoolean()
val priority = if(debug) {
SourceSPIRVPriority.SourcePriority
} else {
shaderPackage.priority
}
val spirv: ByteArray = if(shaderPackage.spirv != null && priority == SourceSPIRVPriority.SPIRVPriority) {
val pair = compileFromSPIRVBytecode(shaderPackage, target)
sourceCode = pair.second
pair.first
} else if(shaderPackage.code != null && priority == SourceSPIRVPriority.SourcePriority) {
val pair = compileFromSource(shaderPackage, shaderPackage.code, type, target, base, debug, strict)
sourceCode = pair.second
pair.first
} else {
throw ShaderCompilationException("Neither code nor compiled SPIRV file found for ${shaderPackage.codePath}")
}
val p = ShaderPackage(base,
type,
shaderPackage.spirvPath,
shaderPackage.codePath,
spirv,
sourceCode,
priority)
return p
}
private fun compileFromSource(shaderPackage: ShaderPackage, code: String, type: ShaderType, target: ShaderTarget, base: Class<*>, debug: Boolean = false, strict: Boolean = false): Pair<ByteArray, String> {
logger.debug("Compiling ${shaderPackage.codePath} to SPIR-V...")
// code needs to be compiled first
val compiler = ShaderCompiler()
val bytecode = compiler.compile(code, type, target, "main", debug, strict, ShaderCompiler.OptimisationLevel.None, shaderPackage.codePath, base.simpleName)
compiler.close()
return Pair(bytecode, code)
}
private fun compileFromSPIRVBytecode(shaderPackage: ShaderPackage, target: ShaderTarget): Pair<ByteArray, String> {
val bytecode = shaderPackage.spirv ?: throw IllegalStateException("SPIRV bytecode not found")
val opcodes = shaderPackage.getSPIRVOpcodes()!!
logger.debug("Using SPIRV version, ${bytecode.size/4} opcodes")
val introspection = when (target) {
ShaderTarget.Vulkan -> {
ShaderIntrospection(opcodes, vulkanSemantics = true, version = 450)
}
ShaderTarget.OpenGL -> {
ShaderIntrospection(opcodes, vulkanSemantics = false, version = 410)
}
}
val sourceCode = introspection.compile()
return Pair(bytecode, sourceCode)
}
}
| lgpl-3.0 | 47c9802cb92766fd291c2fe2299d9118 | 38.703557 | 209 | 0.605674 | 4.822372 | false | false | false | false |
LivingDoc/livingdoc | livingdoc-repositories/src/test/kotlin/org/livingdoc/repositories/format/HtmlFormatTestData.kt | 2 | 6008 | package org.livingdoc.repositories.format
object HtmlFormatTestData {
fun getHtmlTableWithOnlyOneRow() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
</table>
</body>
</html>
""".byteInputStream()
fun getHtmlTableWithNonUniqueHeaders() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Lastname</th>
</tr>
<tr>
<td>Jill</th>
<td>Thomsen</th>
<td>35</th>
</tr>
</table>
</body>
</html>
""".byteInputStream()
fun getHtmlTableWithWrongCellCount() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</th>
<td>Thomsen</th>
</tr>
</table>
</body>
</html>
""".byteInputStream()
fun getValidHtml() =
"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>LivingDoc-HTML Parser</title>
</head>
<body>
<h1>Headline First Order</h1>
SIMPLE TEXT
<p>
PARAGRAPH CONTENT
</p>
<div>CONTENT OF THE DIV</div>
<ul>
<li>
text1
<p>
List Paragraph
</p>
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
text111
</li>
<li>text2</li>
<li>text3</li>
</ul>
<ol>
<li>text4</li>
<li>text5</li>
<li>text6</li>
</ol>
<ol type = "">
<li>text7</li>
<li>text8</li>
<li>text9</li>
</ol>
<ol type = "A">
<li>textX</li>
<li>textY</li>
<li>textZ</li>
</ol>
</body>
</html>
""".byteInputStream()
fun getHtmlWithUnorderedList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
<li>Fifth list item</li>
</ul>
</body>
</html>
""".byteInputStream()
fun getHtmlWithOrderedList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ol>
<li>First list item</li>
<li>Second list item</li>
<li>Third list item</li>
<li>Fourth list item</li>
<li>Fifth list item</li>
</ol>
</body>
</html>
""".byteInputStream()
fun getHtmlWithUnorderedListContainsOnlyOneItem() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li>First list item</li>
</ul>
</body>
</html>
""".byteInputStream()
fun getHtmlWithOrderedListContainsOnlyOneItem() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ol>
<li>First list item</li>
</ol>
</body>
</html>
""".byteInputStream()
fun getHtmlUnorderedListWithNestedUnorderedList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li>First list item</li>
<li>Second list item
<ul>
<li>First nested item</li>
</ul>
</li>
</ul>
</body>
</html>
""".byteInputStream()
fun getHtmlUnorderedListWithNestedOrderedList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ul>
<li>First list item</li>
<li>Second list item
<ol>
<li>First nested item</li>
</ol>
</li>
</ul>
</body>
</html>
""".byteInputStream()
fun getHtmlOrderedListWithNestedUnorderedList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ol>
<li>First list item</li>
<li>Second list item
<ul>
<li>First nested item</li>
</ul>
</li>
</ol>
</body>
</html>
""".byteInputStream()
fun getHtmlOrderedListWithNestedOrderedList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<ol>
<li>First list item</li>
<li>Second list item
<ol>
<li>First nested item</li>
</ol>
</li>
</ol>
</body>
</html>
""".byteInputStream()
fun getHtmlManualList() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<h2>MANUAL Test1</h2>
<ol>
<li>First list item</li>
<li>Second list item</li>
</ol>
</body>
</html>
""".byteInputStream()
fun getHtmlDescriptionText() =
"""
<!DOCTYPE html>
<html lang="en">
<body>
<p>This is a descriptive text.</p>
<ol>
<li>First list item</li>
<li>Second list item</li>
</ol>
<p>This is another descriptive text.</p>
</body>
</html>
""".byteInputStream()
}
| apache-2.0 | b76f25d08bc59dc45cf9f9668c3279d7 | 20.229682 | 55 | 0.403961 | 3.929366 | false | false | false | false |
Raizlabs/DBFlow | core/src/main/kotlin/com/dbflow5/annotation/ModelView.kt | 1 | 2090 | package com.dbflow5.annotation
import com.dbflow5.sql.Query
import kotlin.reflect.KClass
/**
* Author: andrewgrosner
* Description: Marks a class as being an SQL VIEW definition. It must extend BaseModelView and have
* a single public, static, final field that is annotated with [ModelViewQuery] and be a [Query].
*/
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)
annotation class ModelView(
/**
* @return The name of this view. Default is the class name.
*/
val name: String = "",
/**
* @return The class of the database this corresponds to.
*/
val database: KClass<*>,
/**
* @return When true, all public, package-private , non-static, and non-final fields of the reference class are considered as [com.dbflow5.annotation.Column] .
* The only required annotated field becomes The [PrimaryKey]
* or [PrimaryKey.autoincrement].
*/
val allFields: Boolean = true,
/**
* @return If true, we throw away checks for column indexing and simply assume that the cursor returns
* all our columns in order. This may provide a slight performance boost.
*/
val orderedCursorLookUp: Boolean = false,
/**
* @return When true, we reassign the corresponding Model's fields to default values when loading
* from cursor. If false, we assign values only if present in Cursor.
*/
val assignDefaultValuesFromCursor: Boolean = true,
/**
* @return The higher the number, the order by which the creation of this class gets called.
* Useful for creating ones that depend on another [ModelView].
*/
val priority: Int = 0,
/**
* @return When false, this view gets generated and associated with database, however it will not immediately
* get created upon startup. This is useful for keeping around legacy tables for migrations.
*/
val createWithDatabase: Boolean = true)
| mit | 8ba4bbfff0ef7061534200f446331d49 | 41.653061 | 167 | 0.65311 | 4.860465 | false | false | false | false |
alibaba/transmittable-thread-local | ttl2-compatible/src/test/java/com/alibaba/demo/coroutine/ttl_intergration/usage/TtlCoroutineContextDemo.kt | 2 | 2610 | package com.alibaba.demo.coroutine.ttl_intergration.usage
import com.alibaba.demo.coroutine.ttl_intergration.ttlContext
import com.alibaba.ttl.TransmittableThreadLocal
import kotlinx.coroutines.*
private val threadLocal = TransmittableThreadLocal<String?>() // declare thread-local variable
/**
* [Thread-local data - Coroutine Context and Dispatchers - Kotlin Programming Language](https://kotlinlang.org/docs/reference/coroutines/coroutine-context-and-dispatchers.html#thread-local-data)
*/
fun main(): Unit = runBlocking {
val block: suspend CoroutineScope.() -> Unit = {
println("Launch start, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
threadLocal.set("!reset!")
println("After reset, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
delay(5)
println("After yield, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
}
threadLocal.set("main")
println("======================\nEmpty Coroutine Context\n======================")
println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
launch(block = block).join()
println("Post-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
threadLocal.set("main")
println()
println("======================\nTTL Coroutine Context\n======================")
println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
launch(ttlContext(), block = block).join()
println("Post-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
threadLocal.set("main")
println()
println("======================\nDispatchers.Default Coroutine Context\n======================")
println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
launch(Dispatchers.Default, block = block).join()
println("Post-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
threadLocal.set("main")
println()
println("======================\nDispatchers.Default + TTL Coroutine Context\n======================")
println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
launch(Dispatchers.Default + ttlContext(), block = block).join()
println("Post-main, current thread: ${Thread.currentThread()}, thread local value: ${threadLocal.get()}")
}
| apache-2.0 | 468a8acb816c182db40bc05ad9426284 | 54.531915 | 195 | 0.656322 | 4.59507 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/specialBuiltins/exceptionCause.kt | 5 | 723 | class CustomException : Throwable {
constructor(message: String?, cause: Throwable?) : super(message, cause)
constructor(message: String?) : super(message, null)
constructor(cause: Throwable?) : super(cause)
constructor() : super()
}
fun box(): String {
var t = CustomException("O", Throwable("K"))
if (t.message != "O" || t.cause?.message != "K") return "fail1"
t = CustomException(Throwable("OK"))
if (t.message == null || t.message == "OK" || t.cause?.message != "OK") return "fail2"
t = CustomException("OK")
if (t.message != "OK" || t.cause != null) return "fail3"
t = CustomException()
if (t.message != null || t.cause != null) return "fail4"
return "OK"
}
| apache-2.0 | 5cd20119986748989871ebe37dd2a71e | 27.92 | 90 | 0.608575 | 3.475962 | false | false | false | false |
vimeo/vimeo-networking-java | models/src/main/java/com/vimeo/networking2/Team.kt | 1 | 1448 | package com.vimeo.networking2
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.vimeo.networking2.common.Entity
/**
* Stores information related to shared access to resources across user accounts.
*
* @param currentTeamSize The current number of team members.
* @param maximumTeamSize The maximum number of team members.
* @param teamMembership Customized information about the team, including the team name, logo image, and accent color.
* @param owner The owner of the team.
* @param userRole A translated name of the logged in user's role on the team.
* @param hasContentShared Whether or not the team has content shared with any team members yet.
* @param teamBranding Customized information about the team, including the team name, logo image, and accent color.
*/
@JsonClass(generateAdapter = true)
data class Team(
@Json(name = "current_team_size")
val currentTeamSize: Int? = null,
@Json(name = "max_team_size")
val maximumTeamSize: Int? = null,
@Json(name = "team_membership")
val teamMembership: TeamMembership? = null,
@Json(name = "owner")
val owner: User? = null,
@Json(name = "user_role")
val userRole: String? = null,
@Json(name = "has_content_shared")
val hasContentShared: Boolean? = null,
@Json(name = "team_data")
val teamBranding: TeamBranding? = null
) : Entity {
override val identifier: String? = owner?.identifier
}
| mit | 07932b1d35c601adf5103fb46de55991 | 31.909091 | 118 | 0.718923 | 3.892473 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/usageHighlighter/implicitIt.kt | 13 | 300 | fun foo(body: (Int) -> Unit) = body(1)
fun test() {
foo {
val x = <info descr="null">~it</info> + 1
val xx = <info descr="null">it</info> + 2
foo {
val y = it - 1
val yy = it - 2
}
val xxx = <info descr="null">it</info> + 3
}
} | apache-2.0 | f60979d4b7c466f0fcea25db0af25d76 | 22.153846 | 50 | 0.416667 | 3.092784 | false | true | false | false |
smmribeiro/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/UiCommandsService.kt | 1 | 1757 | package com.jetbrains.packagesearch.intellij.plugin.ui
import com.intellij.openapi.components.Service
import com.intellij.openapi.project.Project
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiStateModifier
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiStateSource
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
@Service(Service.Level.PROJECT)
internal class UiCommandsService(project: Project) : UiStateModifier, UiStateSource, CoroutineScope by project.lifecycleScope {
private val programmaticSearchQueryChannel = Channel<String>(onBufferOverflow = BufferOverflow.DROP_OLDEST)
private val programmaticTargetModulesChannel = Channel<TargetModules>(onBufferOverflow = BufferOverflow.DROP_OLDEST)
override val searchQueryFlow: Flow<String> = programmaticSearchQueryChannel.consumeAsFlow()
.shareIn(this, SharingStarted.Eagerly)
override val targetModulesFlow: Flow<TargetModules> = programmaticTargetModulesChannel.consumeAsFlow()
.shareIn(this, SharingStarted.Eagerly)
override fun setSearchQuery(query: String) {
launch { programmaticSearchQueryChannel.send(query) }
}
override fun setTargetModules(modules: TargetModules) {
launch { programmaticTargetModulesChannel.send(modules) }
}
}
| apache-2.0 | 698db2ae654b1bff2d8eeffc9173f748 | 47.805556 | 127 | 0.828116 | 4.89415 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/ScriptTemplatesFromDependenciesProvider.kt | 1 | 9393 | // 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.script
import com.intellij.ProjectTopics
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.*
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.search.FileTypeIndex
import com.intellij.psi.search.GlobalSearchScope
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionSourceAsContributor
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.loadDefinitionsFromTemplatesByPaths
import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.util.runWhenSmart
import org.jetbrains.kotlin.scripting.definitions.SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.definitions.getEnvironment
import java.io.File
import java.nio.file.Path
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import kotlin.script.experimental.host.ScriptingHostConfiguration
import kotlin.script.experimental.jvm.defaultJvmScriptingHostConfiguration
class ScriptTemplatesFromDependenciesProvider(private val project: Project) : ScriptDefinitionSourceAsContributor {
private val logger = Logger.getInstance(ScriptTemplatesFromDependenciesProvider::class.java)
override val id = "ScriptTemplatesFromDependenciesProvider"
override fun isReady(): Boolean = _definitions != null
override val definitions: Sequence<ScriptDefinition>
get() {
definitionsLock.withLock {
_definitions?.let { return it.asSequence() }
}
forceStartUpdate = false
asyncRunUpdateScriptTemplates()
return emptySequence()
}
init {
val connection = project.messageBus.connect()
connection.subscribe(
ProjectTopics.PROJECT_ROOTS,
object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
if (project.isInitialized) {
forceStartUpdate = true
asyncRunUpdateScriptTemplates()
}
}
},
)
}
private fun asyncRunUpdateScriptTemplates() {
definitionsLock.withLock {
if (!forceStartUpdate && _definitions != null) return
}
if (inProgress.compareAndSet(false, true)) {
loadScriptDefinitions()
}
}
@Volatile
private var _definitions: List<ScriptDefinition>? = null
private val definitionsLock = ReentrantLock()
private var oldTemplates: TemplatesWithCp? = null
private data class TemplatesWithCp(
val templates: List<String>,
val classpath: List<Path>,
)
private val inProgress = AtomicBoolean(false)
@Volatile
private var forceStartUpdate = false
private fun loadScriptDefinitions() {
if (project.isDefault) {
return onEarlyEnd()
}
if (logger.isDebugEnabled) {
logger.debug("async script definitions update started")
}
val task = object : Task.Backgroundable(
project, KotlinBundle.message("kotlin.script.lookup.definitions"), false
) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = true
val (templates, classpath) = project.runReadActionInSmartMode {
val files = mutableSetOf<VirtualFile>()
FileTypeIndex.processFiles(ScriptDefinitionMarkerFileType, {
indicator.checkCanceled()
files.add(it)
true
}, GlobalSearchScope.allScope(project))
getTemplateClassPath(files)
}
try {
if (!inProgress.get() || templates.isEmpty()) return onEarlyEnd()
val newTemplates = TemplatesWithCp(templates.toList(), classpath.toList())
if (!inProgress.get() || newTemplates == oldTemplates) return onEarlyEnd()
if (logger.isDebugEnabled) {
logger.debug("script templates found: $newTemplates")
}
oldTemplates = newTemplates
val hostConfiguration = ScriptingHostConfiguration(defaultJvmScriptingHostConfiguration) {
getEnvironment {
mapOf(
"projectRoot" to (project.basePath ?: project.baseDir.canonicalPath)?.let(::File),
)
}
}
val newDefinitions = loadDefinitionsFromTemplatesByPaths(
templateClassNames = newTemplates.templates,
templateClasspath = newTemplates.classpath,
baseHostConfiguration = hostConfiguration,
)
if (logger.isDebugEnabled) {
logger.debug("script definitions found: ${newDefinitions.joinToString()}")
}
val needReload = definitionsLock.withLock {
if (newDefinitions != _definitions) {
_definitions = newDefinitions
return@withLock true
}
return@withLock false
}
if (needReload) {
ScriptDefinitionsManager.getInstance(project).reloadDefinitionsBy(this@ScriptTemplatesFromDependenciesProvider)
}
} finally {
inProgress.set(false)
}
}
}
project.runWhenSmart {
ProgressManager.getInstance().runProcessWithProgressAsynchronously(
task,
BackgroundableProcessIndicator(task)
)
}
}
private fun onEarlyEnd() {
definitionsLock.withLock {
_definitions = emptyList()
}
inProgress.set(false)
}
// public for tests
fun getTemplateClassPath(files: Collection<VirtualFile>): Pair<Collection<String>, Collection<Path>> {
val rootDirToTemplates: MutableMap<VirtualFile, MutableList<VirtualFile>> = hashMapOf()
for (file in files) {
val dir = file.parent?.parent?.parent?.parent?.parent ?: continue
rootDirToTemplates.getOrPut(dir) { arrayListOf() }.add(file)
}
val templates = linkedSetOf<String>()
val classpath = linkedSetOf<Path>()
rootDirToTemplates.forEach { (root, templateFiles) ->
if (logger.isDebugEnabled) {
logger.debug("root matching SCRIPT_DEFINITION_MARKERS_PATH found: ${root.path}")
}
val orderEntriesForFile = ProjectFileIndex.getInstance(project).getOrderEntriesForFile(root)
.filter {
if (it is ModuleSourceOrderEntry) {
if (ModuleRootManager.getInstance(it.ownerModule).fileIndex.isInTestSourceContent(root)) {
return@filter false
}
it.getFiles(OrderRootType.SOURCES).contains(root)
} else {
it is LibraryOrSdkOrderEntry && it.getFiles(OrderRootType.CLASSES).contains(root)
}
}
.takeIf { it.isNotEmpty() } ?: return@forEach
for (virtualFile in templateFiles) {
templates.add(virtualFile.name.removeSuffix(SCRIPT_DEFINITION_MARKERS_EXTENSION_WITH_DOT))
}
// assuming that all libraries are placed into classes roots
// TODO: extract exact library dependencies instead of putting all module dependencies into classpath
// minimizing the classpath needed to use the template by taking cp only from modules with new templates found
// on the other hand the approach may fail if some module contains a template without proper classpath, while
// the other has properly configured classpath, so assuming that the dependencies are set correctly everywhere
for (orderEntry in orderEntriesForFile) {
for (virtualFile in OrderEnumerator.orderEntries(orderEntry.ownerModule).withoutSdk().classesRoots) {
val localVirtualFile = VfsUtil.getLocalFile(virtualFile)
localVirtualFile.fileSystem.getNioPath(localVirtualFile)?.let(classpath::add)
}
}
}
return templates to classpath
}
} | apache-2.0 | c7736a009d2d3bfe098914ad9dbb8b9f | 40.201754 | 158 | 0.620781 | 6.052191 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/audio/synth/Wave.kt | 1 | 978 | package de.fabmax.kool.modules.audio.synth
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.round
import kotlin.math.sin
/**
* @author fabmax
*/
class Wave(val tableSize: Int, generator: (Float) -> Float) {
private val table = FloatArray(tableSize)
init {
for (i in 0 until tableSize) {
table[i] = generator(i / tableSize.toFloat())
}
}
operator fun get(index: Float): Float {
return table[(index * tableSize).toInt() % tableSize]
}
companion object {
const val DEFAULT_TABLE_SIZE = 2048
val SINE = Wave(DEFAULT_TABLE_SIZE) { p -> sin(p * PI.toFloat() * 2) }
val SAW = Wave(DEFAULT_TABLE_SIZE) { p -> -2f * (p - round(p)) }
val RAMP = Wave(DEFAULT_TABLE_SIZE) { p -> 2f * (p - round(p)) }
val TRIANGLE = Wave(DEFAULT_TABLE_SIZE) { p -> 1f - 4f * abs(round(p) - p) }
val SQUARE = Wave(DEFAULT_TABLE_SIZE) { p -> if (p < 0.5f) 1f else -1f }
}
} | apache-2.0 | dc5dcf89b3454137a1bb550dcb92e771 | 27.794118 | 84 | 0.587935 | 3.144695 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/UserBookmarkFragmentViewModel.kt | 1 | 6235 | /*
* Copyright (c) 2017. Rei Matsushita
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is
* distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
* the License for the specific language governing permissions and limitations under the License.
*/
package me.rei_m.hbfavmaterial.viewmodel.widget.fragment
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.Observable
import android.databinding.ObservableArrayList
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.constant.ReadAfterFilter
import me.rei_m.hbfavmaterial.model.UserBookmarkModel
import me.rei_m.hbfavmaterial.model.UserModel
import me.rei_m.hbfavmaterial.model.entity.Bookmark
class UserBookmarkFragmentViewModel(private val userBookmarkModel: UserBookmarkModel,
userModel: UserModel,
readAfterFilter: ReadAfterFilter) : ViewModel() {
val bookmarkList: ObservableArrayList<Bookmark> = ObservableArrayList()
val hasNextPage: ObservableBoolean = ObservableBoolean(false)
val isVisibleEmpty: ObservableBoolean = ObservableBoolean(false)
val isVisibleProgress: ObservableBoolean = ObservableBoolean(false)
val isRefreshing: ObservableBoolean = ObservableBoolean(false)
val readAfterFilter: ObservableField<ReadAfterFilter> = ObservableField(readAfterFilter)
val isVisibleError: ObservableBoolean = ObservableBoolean(false)
private var hasNextPageUpdatedEventSubject = BehaviorSubject.create<Boolean>()
val hasNextPageUpdatedEvent: io.reactivex.Observable<Boolean> = hasNextPageUpdatedEventSubject
private val onItemClickEventSubject = PublishSubject.create<Bookmark>()
val onItemClickEvent: io.reactivex.Observable<Bookmark> = onItemClickEventSubject
val onRaiseGetNextPageErrorEvent = userBookmarkModel.isRaisedGetNextPageError
val onRaiseRefreshErrorEvent = userBookmarkModel.isRaisedRefreshError
private val disposable: CompositeDisposable = CompositeDisposable()
private val userId: ObservableField<String> = ObservableField("")
private val userIdChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
userBookmarkModel.getList(userId.get(), [email protected]())
}
}
private val hasNextPageChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
hasNextPageUpdatedEventSubject.onNext(hasNextPage.get())
}
}
private val readAfterFilterChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
userBookmarkModel.getList(userId.get(), [email protected]())
}
}
init {
userId.addOnPropertyChangedCallback(userIdChangedCallback)
hasNextPage.addOnPropertyChangedCallback(hasNextPageChangedCallback)
this.readAfterFilter.addOnPropertyChangedCallback(readAfterFilterChangedCallback)
disposable.addAll(userBookmarkModel.bookmarkList.subscribe {
if (it.isEmpty()) {
bookmarkList.clear()
} else {
bookmarkList.addAll(it - bookmarkList)
}
isVisibleEmpty.set(bookmarkList.isEmpty())
}, userBookmarkModel.hasNextPage.subscribe {
hasNextPage.set(it)
}, userBookmarkModel.isLoading.subscribe {
isVisibleProgress.set(it)
}, userBookmarkModel.isRefreshing.subscribe {
isRefreshing.set(it)
}, userBookmarkModel.isRaisedError.subscribe {
isVisibleError.set(it)
}, userModel.user.subscribe {
userId.set(it.id)
})
}
override fun onCleared() {
userId.removeOnPropertyChangedCallback(userIdChangedCallback)
hasNextPage.removeOnPropertyChangedCallback(hasNextPageChangedCallback)
readAfterFilter.removeOnPropertyChangedCallback(readAfterFilterChangedCallback)
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
onItemClickEventSubject.onNext(bookmarkList[position])
}
@Suppress("UNUSED_PARAMETER")
fun onScroll(listView: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) {
if (0 < totalItemCount && totalItemCount == firstVisibleItem + visibleItemCount) {
userBookmarkModel.getNextPage(userId.get())
}
}
fun onRefresh() {
userBookmarkModel.refreshList(userId.get())
}
fun onOptionItemSelected(readAfterFilter: ReadAfterFilter) {
this.readAfterFilter.set(readAfterFilter)
}
class Factory(private val userBookmarkModel: UserBookmarkModel,
private val userModel: UserModel,
var readAfterFilter: ReadAfterFilter = ReadAfterFilter.ALL) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(UserBookmarkFragmentViewModel::class.java)) {
return UserBookmarkFragmentViewModel(userBookmarkModel, userModel, readAfterFilter) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
| apache-2.0 | 29058a121c307a6f50871a421405e11e | 41.414966 | 112 | 0.732638 | 5.37037 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownDialog.kt | 1 | 4505 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pushDown
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.classMembers.*
import com.intellij.refactoring.ui.RefactoringDialog
import org.jetbrains.kotlin.idea.refactoring.KotlinRefactoringSettings
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberSelectionPanel
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinUsesDependencyMemberInfoModel
import org.jetbrains.kotlin.idea.refactoring.memberInfo.qualifiedClassNameForRendering
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtProperty
import java.awt.BorderLayout
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
class KotlinPushDownDialog(
project: Project,
private val memberInfos: List<KotlinMemberInfo>,
private val sourceClass: KtClass
) : RefactoringDialog(project, true) {
init {
title = PUSH_MEMBERS_DOWN
init()
}
private var memberInfoModel: MemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>? = null
private val selectedMemberInfos: List<KotlinMemberInfo>
get() = memberInfos.filter { it.isChecked && memberInfoModel?.isMemberEnabled(it) ?: false }
override fun getDimensionServiceKey() = "#" + this::class.java.name
override fun createNorthPanel(): JComponent? {
val gbConstraints = GridBagConstraints()
val panel = JPanel(GridBagLayout())
gbConstraints.insets = Insets(4, 0, 10, 8)
gbConstraints.weighty = 1.0
gbConstraints.weightx = 1.0
gbConstraints.gridy = 0
gbConstraints.gridwidth = GridBagConstraints.REMAINDER
gbConstraints.fill = GridBagConstraints.BOTH
gbConstraints.anchor = GridBagConstraints.WEST
panel.add(
JLabel(
RefactoringBundle.message(
"push.members.from.0.down.label",
sourceClass.qualifiedClassNameForRendering()
)
), gbConstraints
)
return panel
}
override fun createCenterPanel(): JComponent? {
val panel = JPanel(BorderLayout())
val memberSelectionPanel = KotlinMemberSelectionPanel(
RefactoringBundle.message("members.to.be.pushed.down.panel.title"),
memberInfos,
RefactoringBundle.message("keep.abstract.column.header")
)
panel.add(memberSelectionPanel, BorderLayout.CENTER)
memberInfoModel = object : DelegatingMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
ANDCombinedMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(
KotlinUsesDependencyMemberInfoModel<KtNamedDeclaration, KotlinMemberInfo>(sourceClass, null, false),
UsedByDependencyMemberInfoModel<KtNamedDeclaration, PsiNamedElement, KotlinMemberInfo>(sourceClass)
)
) {
override fun isFixedAbstract(member: KotlinMemberInfo?) = null
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
val member = memberInfo.member
if (member.hasModifier(KtTokens.INLINE_KEYWORD) ||
member.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
member.hasModifier(KtTokens.LATEINIT_KEYWORD)
) return false
return member is KtNamedFunction || member is KtProperty
}
}
memberInfoModel!!.memberInfoChanged(MemberInfoChange(memberInfos))
memberSelectionPanel.table.memberInfoModel = memberInfoModel
memberSelectionPanel.table.addMemberInfoChangeListener(memberInfoModel)
return panel
}
override fun doAction() {
if (!isOKActionEnabled) return
KotlinRefactoringSettings.instance.PUSH_DOWN_PREVIEW_USAGES = isPreviewUsages
invokeRefactoring(KotlinPushDownProcessor(project, sourceClass, selectedMemberInfos))
}
} | apache-2.0 | a9561abfb75589226278cea05a408dde | 40.722222 | 158 | 0.722974 | 5.388756 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtOverrideMembersHandler.kt | 1 | 5764 | // 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.core.overrideImplement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.analyse
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind
import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality
import org.jetbrains.kotlin.analysis.api.tokens.HackToForceAllowRunningAnalyzeOnEDT
import org.jetbrains.kotlin.analysis.api.tokens.hackyAllowRunningOnEdt
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.idea.KtIconProvider.getIcon
import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle
import org.jetbrains.kotlin.name.StandardClassIds
import org.jetbrains.kotlin.psi.KtClassOrObject
internal open class KtOverrideMembersHandler : KtGenerateMembersHandler(false) {
@OptIn(HackToForceAllowRunningAnalyzeOnEDT::class)
override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> {
return hackyAllowRunningOnEdt {
analyse(classOrObject) {
collectMembers(classOrObject)
}
}
}
fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject): List<KtClassMember> {
val classOrObjectSymbol = classOrObject.getClassOrObjectSymbol()
return getOverridableMembers(classOrObjectSymbol).map { (symbol, bodyType, containingSymbol) ->
KtClassMember(
KtClassMemberInfo(
symbol,
symbol.render(renderOption),
getIcon(symbol),
containingSymbol?.classIdIfNonLocal?.asSingleFqName()?.toString() ?: containingSymbol?.name?.asString(),
containingSymbol?.let { getIcon(it) }
),
bodyType,
preferConstructorParameter = false
)
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun KtAnalysisSession.getOverridableMembers(classOrObjectSymbol: KtClassOrObjectSymbol): List<OverrideMember> {
return buildList {
classOrObjectSymbol.getMemberScope().getCallableSymbols().forEach { symbol ->
if (!symbol.isVisibleInClass(classOrObjectSymbol)) return@forEach
val implementationStatus = symbol.getImplementationStatus(classOrObjectSymbol) ?: return@forEach
if (!implementationStatus.isOverridable) return@forEach
val intersectionSymbols = symbol.getIntersectionOverriddenSymbols()
val symbolsToProcess = if (intersectionSymbols.size <= 1) {
listOf(symbol)
} else {
val nonAbstractMembers = intersectionSymbols.filter { (it as? KtSymbolWithModality)?.modality != Modality.ABSTRACT }
// If there are non-abstract members, we only want to show override for these non-abstract members. Otherwise, show any
// abstract member to override.
nonAbstractMembers.ifEmpty {
listOf(intersectionSymbols.first())
}
}
val hasNoSuperTypesExceptAny = classOrObjectSymbol.superTypes.singleOrNull()?.isAny == true
for (symbolToProcess in symbolsToProcess) {
val originalOverriddenSymbol = symbolToProcess.originalOverriddenSymbol
val containingSymbol = originalOverriddenSymbol?.originalContainingClassForOverride
val bodyType = when {
classOrObjectSymbol.classKind == KtClassKind.INTERFACE && containingSymbol?.classIdIfNonLocal == StandardClassIds.Any -> {
if (hasNoSuperTypesExceptAny) {
// If an interface does not extends any other interfaces, FE1.0 simply skips members of `Any`. So we mimic
// the same behavior. See idea/testData/codeInsight/overrideImplement/noAnyMembersInInterface.kt
continue
} else {
BodyType.NO_BODY
}
}
(originalOverriddenSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT ->
BodyType.FROM_TEMPLATE
symbolsToProcess.size > 1 ->
BodyType.QUALIFIED_SUPER
else ->
BodyType.SUPER
}
// Ideally, we should simply create `KtClassMember` here and remove the intermediate `OverrideMember` data class. But
// that doesn't work because this callback function is holding a read lock and `symbol.render(renderOption)` requires
// the write lock.
// Hence, we store the data in an intermediate `OverrideMember` data class and do the rendering later in the `map` call.
add(OverrideMember(symbolToProcess, bodyType, containingSymbol))
}
}
}
}
private data class OverrideMember(val symbol: KtCallableSymbol, val bodyType: BodyType, val containingSymbol: KtClassOrObjectSymbol?)
override fun getChooserTitle() = KotlinIdeaCoreBundle.message("override.members.handler.title")
override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("override.members.handler.no.members.hint")
} | apache-2.0 | 003a7e3257289106256ca30a7b72ba74 | 54.970874 | 146 | 0.647467 | 5.973057 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/ext/xpoet_ext.kt | 3 | 21451 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.ext
import androidx.room.compiler.codegen.CodeLanguage
import androidx.room.compiler.codegen.VisibilityModifier
import androidx.room.compiler.codegen.XClassName
import androidx.room.compiler.codegen.XCodeBlock
import androidx.room.compiler.codegen.XFunSpec
import androidx.room.compiler.codegen.XFunSpec.Builder.Companion.apply
import androidx.room.compiler.codegen.XMemberName.Companion.companionMember
import androidx.room.compiler.codegen.XMemberName.Companion.packageMember
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.codegen.XTypeSpec
import androidx.room.compiler.codegen.asClassName
import androidx.room.compiler.codegen.asMutableClassName
import com.squareup.javapoet.ArrayTypeName
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import java.util.concurrent.Callable
import javax.lang.model.element.Modifier
import kotlin.reflect.KClass
val L = "\$L"
val T = "\$T"
val N = "\$N"
val S = "\$S"
val W = "\$W"
val KClass<*>.typeName: ClassName
get() = ClassName.get(this.java)
val KClass<*>.arrayTypeName: ArrayTypeName
get() = ArrayTypeName.of(typeName)
object SupportDbTypeNames {
val DB = XClassName.get("$SQLITE_PACKAGE.db", "SupportSQLiteDatabase")
val SQLITE_STMT = XClassName.get("$SQLITE_PACKAGE.db", "SupportSQLiteStatement")
val SQLITE_OPEN_HELPER = XClassName.get("$SQLITE_PACKAGE.db", "SupportSQLiteOpenHelper")
val SQLITE_OPEN_HELPER_CALLBACK =
XClassName.get("$SQLITE_PACKAGE.db", "SupportSQLiteOpenHelper", "Callback")
val SQLITE_OPEN_HELPER_CONFIG =
XClassName.get("$SQLITE_PACKAGE.db", "SupportSQLiteOpenHelper", "Configuration")
val QUERY = XClassName.get("$SQLITE_PACKAGE.db", "SupportSQLiteQuery")
}
object RoomTypeNames {
val STRING_UTIL = XClassName.get("$ROOM_PACKAGE.util", "StringUtil")
val ROOM_DB = XClassName.get(ROOM_PACKAGE, "RoomDatabase")
val ROOM_DB_KT = XClassName.get(ROOM_PACKAGE, "RoomDatabaseKt")
val ROOM_DB_CALLBACK = XClassName.get(ROOM_PACKAGE, "RoomDatabase", "Callback")
val ROOM_DB_CONFIG = XClassName.get(ROOM_PACKAGE, "DatabaseConfiguration")
val INSERTION_ADAPTER = XClassName.get(ROOM_PACKAGE, "EntityInsertionAdapter")
val UPSERTION_ADAPTER = XClassName.get(ROOM_PACKAGE, "EntityUpsertionAdapter")
val DELETE_OR_UPDATE_ADAPTER = XClassName.get(ROOM_PACKAGE, "EntityDeletionOrUpdateAdapter")
val SHARED_SQLITE_STMT = XClassName.get(ROOM_PACKAGE, "SharedSQLiteStatement")
val INVALIDATION_TRACKER = XClassName.get(ROOM_PACKAGE, "InvalidationTracker")
val ROOM_SQL_QUERY = XClassName.get(ROOM_PACKAGE, "RoomSQLiteQuery")
val OPEN_HELPER = XClassName.get(ROOM_PACKAGE, "RoomOpenHelper")
val OPEN_HELPER_DELEGATE = XClassName.get(ROOM_PACKAGE, "RoomOpenHelper", "Delegate")
val OPEN_HELPER_VALIDATION_RESULT =
XClassName.get(ROOM_PACKAGE, "RoomOpenHelper", "ValidationResult")
val TABLE_INFO = XClassName.get("$ROOM_PACKAGE.util", "TableInfo")
val TABLE_INFO_COLUMN = XClassName.get("$ROOM_PACKAGE.util", "TableInfo", "Column")
val TABLE_INFO_FOREIGN_KEY = XClassName.get("$ROOM_PACKAGE.util", "TableInfo", "ForeignKey")
val TABLE_INFO_INDEX =
XClassName.get("$ROOM_PACKAGE.util", "TableInfo", "Index")
val FTS_TABLE_INFO = XClassName.get("$ROOM_PACKAGE.util", "FtsTableInfo")
val VIEW_INFO = XClassName.get("$ROOM_PACKAGE.util", "ViewInfo")
val LIMIT_OFFSET_DATA_SOURCE: ClassName =
ClassName.get("$ROOM_PACKAGE.paging", "LimitOffsetDataSource")
val DB_UTIL = XClassName.get("$ROOM_PACKAGE.util", "DBUtil")
val CURSOR_UTIL = XClassName.get("$ROOM_PACKAGE.util", "CursorUtil")
val MIGRATION = XClassName.get("$ROOM_PACKAGE.migration", "Migration")
val AUTO_MIGRATION_SPEC = XClassName.get("$ROOM_PACKAGE.migration", "AutoMigrationSpec")
val UUID_UTIL = XClassName.get("$ROOM_PACKAGE.util", "UUIDUtil")
val AMBIGUOUS_COLUMN_RESOLVER = XClassName.get(ROOM_PACKAGE, "AmbiguousColumnResolver")
val RELATION_UTIL = XClassName.get("androidx.room.util", "RelationUtil")
}
object PagingTypeNames {
val DATA_SOURCE: ClassName =
ClassName.get(PAGING_PACKAGE, "DataSource")
val POSITIONAL_DATA_SOURCE: ClassName =
ClassName.get(PAGING_PACKAGE, "PositionalDataSource")
val DATA_SOURCE_FACTORY: ClassName =
ClassName.get(PAGING_PACKAGE, "DataSource", "Factory")
val PAGING_SOURCE: ClassName =
ClassName.get(PAGING_PACKAGE, "PagingSource")
val LISTENABLE_FUTURE_PAGING_SOURCE: ClassName =
ClassName.get(PAGING_PACKAGE, "ListenableFuturePagingSource")
val RX2_PAGING_SOURCE: ClassName =
ClassName.get("$PAGING_PACKAGE.rxjava2", "RxPagingSource")
val RX3_PAGING_SOURCE: ClassName =
ClassName.get("$PAGING_PACKAGE.rxjava3", "RxPagingSource")
}
object LifecyclesTypeNames {
val LIVE_DATA: ClassName = ClassName.get(LIFECYCLE_PACKAGE, "LiveData")
val COMPUTABLE_LIVE_DATA: ClassName = ClassName.get(
LIFECYCLE_PACKAGE,
"ComputableLiveData"
)
}
object AndroidTypeNames {
val CURSOR = XClassName.get("android.database", "Cursor")
val BUILD = XClassName.get("android.os", "Build")
val CANCELLATION_SIGNAL = XClassName.get("android.os", "CancellationSignal")
}
object CollectionTypeNames {
val ARRAY_MAP = XClassName.get(COLLECTION_PACKAGE, "ArrayMap")
val LONG_SPARSE_ARRAY = XClassName.get(COLLECTION_PACKAGE, "LongSparseArray")
val INT_SPARSE_ARRAY = XClassName.get(COLLECTION_PACKAGE, "SparseArrayCompat")
}
object KotlinCollectionMemberNames {
val ARRAY_OF_NULLS = XClassName.get("kotlin", "LibraryKt")
.packageMember("arrayOfNulls")
}
object CommonTypeNames {
val VOID = Void::class.asClassName()
val COLLECTION = Collection::class.asClassName()
val LIST = List::class.asClassName()
val MUTABLE_LIST = List::class.asMutableClassName()
val ARRAY_LIST = XClassName.get("java.util", "ArrayList")
val MAP = Map::class.asClassName()
val MUTABLE_MAP = Map::class.asMutableClassName()
val HASH_MAP = XClassName.get("java.util", "HashMap")
val SET = Set::class.asClassName()
val MUTABLE_SET = Set::class.asMutableClassName()
val HASH_SET = XClassName.get("java.util", "HashSet")
val STRING = String::class.asClassName()
val OPTIONAL = XClassName.get("java.util", "Optional")
val UUID = XClassName.get("java.util", "UUID")
val BYTE_BUFFER = XClassName.get("java.nio", "ByteBuffer")
val JAVA_CLASS = XClassName.get("java.lang", "Class")
}
object GuavaTypeNames {
val OPTIONAL = XClassName.get("com.google.common.base", "Optional")
val IMMUTABLE_MULTIMAP_BUILDER = XClassName.get(
"com.google.common.collect",
"ImmutableMultimap",
"Builder"
)
val IMMUTABLE_SET_MULTIMAP = XClassName.get(
"com.google.common.collect",
"ImmutableSetMultimap"
)
val IMMUTABLE_SET_MULTIMAP_BUILDER = XClassName.get(
"com.google.common.collect",
"ImmutableSetMultimap",
"Builder"
)
val IMMUTABLE_LIST_MULTIMAP = XClassName.get(
"com.google.common.collect",
"ImmutableListMultimap"
)
val IMMUTABLE_LIST_MULTIMAP_BUILDER = XClassName.get(
"com.google.common.collect",
"ImmutableListMultimap",
"Builder"
)
val IMMUTABLE_MAP = XClassName.get("com.google.common.collect", "ImmutableMap")
val IMMUTABLE_LIST = XClassName.get("com.google.common.collect", "ImmutableList")
val IMMUTABLE_LIST_BUILDER = XClassName.get(
"com.google.common.collect",
"ImmutableList",
"Builder"
)
}
object GuavaUtilConcurrentTypeNames {
val LISTENABLE_FUTURE = ClassName.get("com.google.common.util.concurrent", "ListenableFuture")
}
object RxJava2TypeNames {
val FLOWABLE = ClassName.get("io.reactivex", "Flowable")
val OBSERVABLE = ClassName.get("io.reactivex", "Observable")
val MAYBE = ClassName.get("io.reactivex", "Maybe")
val SINGLE = ClassName.get("io.reactivex", "Single")
val COMPLETABLE = ClassName.get("io.reactivex", "Completable")
}
object RxJava3TypeNames {
val FLOWABLE = ClassName.get("io.reactivex.rxjava3.core", "Flowable")
val OBSERVABLE = ClassName.get("io.reactivex.rxjava3.core", "Observable")
val MAYBE = ClassName.get("io.reactivex.rxjava3.core", "Maybe")
val SINGLE = ClassName.get("io.reactivex.rxjava3.core", "Single")
val COMPLETABLE = ClassName.get("io.reactivex.rxjava3.core", "Completable")
}
object ReactiveStreamsTypeNames {
val PUBLISHER = ClassName.get("org.reactivestreams", "Publisher")
}
object RoomGuavaTypeNames {
val GUAVA_ROOM = ClassName.get("$ROOM_PACKAGE.guava", "GuavaRoom")
}
object RoomRxJava2TypeNames {
val RX_ROOM = ClassName.get(ROOM_PACKAGE, "RxRoom")
val RX_ROOM_CREATE_FLOWABLE = "createFlowable"
val RX_ROOM_CREATE_OBSERVABLE = "createObservable"
val RX_EMPTY_RESULT_SET_EXCEPTION = ClassName.get(ROOM_PACKAGE, "EmptyResultSetException")
}
object RoomRxJava3TypeNames {
val RX_ROOM = ClassName.get("$ROOM_PACKAGE.rxjava3", "RxRoom")
val RX_ROOM_CREATE_FLOWABLE = "createFlowable"
val RX_ROOM_CREATE_OBSERVABLE = "createObservable"
val RX_EMPTY_RESULT_SET_EXCEPTION =
ClassName.get("$ROOM_PACKAGE.rxjava3", "EmptyResultSetException")
}
object RoomPagingTypeNames {
val LIMIT_OFFSET_PAGING_SOURCE: ClassName =
ClassName.get("$ROOM_PACKAGE.paging", "LimitOffsetPagingSource")
}
object RoomPagingGuavaTypeNames {
val LIMIT_OFFSET_LISTENABLE_FUTURE_PAGING_SOURCE: ClassName =
ClassName.get(
"$ROOM_PACKAGE.paging.guava",
"LimitOffsetListenableFuturePagingSource"
)
}
object RoomPagingRx2TypeNames {
val LIMIT_OFFSET_RX_PAGING_SOURCE: ClassName =
ClassName.get(
"$ROOM_PACKAGE.paging.rxjava2",
"LimitOffsetRxPagingSource"
)
}
object RoomPagingRx3TypeNames {
val LIMIT_OFFSET_RX_PAGING_SOURCE: ClassName =
ClassName.get(
"$ROOM_PACKAGE.paging.rxjava3",
"LimitOffsetRxPagingSource"
)
}
object RoomCoroutinesTypeNames {
val COROUTINES_ROOM = XClassName.get(ROOM_PACKAGE, "CoroutinesRoom")
}
object KotlinTypeNames {
val ANY = Any::class.asClassName()
val UNIT = XClassName.get("kotlin", "Unit")
val CONTINUATION = XClassName.get("kotlin.coroutines", "Continuation")
val CHANNEL = ClassName.get("kotlinx.coroutines.channels", "Channel")
val RECEIVE_CHANNEL = ClassName.get("kotlinx.coroutines.channels", "ReceiveChannel")
val SEND_CHANNEL = ClassName.get("kotlinx.coroutines.channels", "SendChannel")
val FLOW = ClassName.get("kotlinx.coroutines.flow", "Flow")
val LAZY = XClassName.get("kotlin", "Lazy")
}
object RoomMemberNames {
val DB_UTIL_QUERY = RoomTypeNames.DB_UTIL.packageMember("query")
val DB_UTIL_DROP_FTS_SYNC_TRIGGERS = RoomTypeNames.DB_UTIL.packageMember("dropFtsSyncTriggers")
val CURSOR_UTIL_GET_COLUMN_INDEX =
RoomTypeNames.CURSOR_UTIL.packageMember("getColumnIndex")
val CURSOR_UTIL_GET_COLUMN_INDEX_OR_THROW =
RoomTypeNames.CURSOR_UTIL.packageMember("getColumnIndexOrThrow")
val CURSOR_UTIL_WRAP_MAPPED_COLUMNS =
RoomTypeNames.CURSOR_UTIL.packageMember("wrapMappedColumns")
val ROOM_SQL_QUERY_ACQUIRE =
RoomTypeNames.ROOM_SQL_QUERY.companionMember("acquire", isJvmStatic = true)
val ROOM_DATABASE_WITH_TRANSACTION =
RoomTypeNames.ROOM_DB_KT.packageMember("withTransaction")
val TABLE_INFO_READ =
RoomTypeNames.TABLE_INFO.companionMember("read", isJvmStatic = true)
val FTS_TABLE_INFO_READ =
RoomTypeNames.FTS_TABLE_INFO.companionMember("read", isJvmStatic = true)
val VIEW_INFO_READ =
RoomTypeNames.VIEW_INFO.companionMember("read", isJvmStatic = true)
}
val DEFERRED_TYPES = listOf(
LifecyclesTypeNames.LIVE_DATA,
LifecyclesTypeNames.COMPUTABLE_LIVE_DATA,
RxJava2TypeNames.FLOWABLE,
RxJava2TypeNames.OBSERVABLE,
RxJava2TypeNames.MAYBE,
RxJava2TypeNames.SINGLE,
RxJava2TypeNames.COMPLETABLE,
RxJava3TypeNames.FLOWABLE,
RxJava3TypeNames.OBSERVABLE,
RxJava3TypeNames.MAYBE,
RxJava3TypeNames.SINGLE,
RxJava3TypeNames.COMPLETABLE,
GuavaUtilConcurrentTypeNames.LISTENABLE_FUTURE,
KotlinTypeNames.FLOW,
ReactiveStreamsTypeNames.PUBLISHER
)
fun XTypeName.defaultValue(): String {
return if (!isPrimitive) {
"null"
} else if (this == XTypeName.PRIMITIVE_BOOLEAN) {
"false"
} else {
"0"
}
}
fun CallableTypeSpec(
language: CodeLanguage,
parameterTypeName: XTypeName,
callBody: XFunSpec.Builder.() -> Unit
) = XTypeSpec.anonymousClassBuilder(language, "").apply {
addSuperinterface(Callable::class.asClassName().parametrizedBy(parameterTypeName))
addFunction(
XFunSpec.builder(
language = language,
name = "call",
visibility = VisibilityModifier.PUBLIC,
isOverride = true
).apply {
returns(parameterTypeName)
callBody()
}.apply(
javaMethodBuilder = {
addException(Exception::class.typeName)
},
kotlinFunctionBuilder = { }
).build()
)
}.build()
// TODO(b/127483380): Remove once XPoet is more widely adopted.
// @Deprecated("Use CallableTypeSpec, will be removed as part of XPoet migration.")
fun CallableTypeSpecBuilder(
parameterTypeName: TypeName,
callBody: MethodSpec.Builder.() -> Unit
) = TypeSpec.anonymousClassBuilder("").apply {
superclass(ParameterizedTypeName.get(Callable::class.typeName, parameterTypeName))
addMethod(
MethodSpec.methodBuilder("call").apply {
returns(parameterTypeName)
addException(Exception::class.typeName)
addModifiers(Modifier.PUBLIC)
addAnnotation(Override::class.java)
callBody()
}.build()
)
}
fun Function1TypeSpec(
language: CodeLanguage,
parameterTypeName: XTypeName,
parameterName: String,
returnTypeName: XTypeName,
callBody: XFunSpec.Builder.() -> Unit
) = XTypeSpec.anonymousClassBuilder(language, "").apply {
superclass(
Function1::class.asClassName().parametrizedBy(parameterTypeName, returnTypeName)
)
addFunction(
XFunSpec.builder(
language = language,
name = "invoke",
visibility = VisibilityModifier.PUBLIC,
isOverride = true
).apply {
addParameter(parameterTypeName, parameterName)
returns(returnTypeName)
callBody()
}.build()
)
}.build()
/**
* Generates an array literal with the given [values]
*
* Example: `ArrayLiteral(XTypeName.PRIMITIVE_INT, 1, 2, 3)`
*
* For Java will produce: `new int[] {1, 2, 3}`
*
* For Kotlin will produce: `intArrayOf(1, 2, 3)`,
*/
fun ArrayLiteral(
language: CodeLanguage,
type: XTypeName,
vararg values: Any
): XCodeBlock {
val space = when (language) {
CodeLanguage.JAVA -> "%W"
CodeLanguage.KOTLIN -> " "
}
val initExpr = when (language) {
CodeLanguage.JAVA -> XCodeBlock.of(language, "new %T[] ", type)
CodeLanguage.KOTLIN -> XCodeBlock.of(language, getArrayOfFunction(type))
}
val openingChar = when (language) {
CodeLanguage.JAVA -> "{"
CodeLanguage.KOTLIN -> "("
}
val closingChar = when (language) {
CodeLanguage.JAVA -> "}"
CodeLanguage.KOTLIN -> ")"
}
return XCodeBlock.of(
language,
"%L$openingChar%L$closingChar",
initExpr,
XCodeBlock.builder(language).apply {
val joining = Array(values.size) { i ->
XCodeBlock.of(
language,
if (type == CommonTypeNames.STRING) "%S" else "%L",
values[i]
)
}
val placeholders = joining.joinToString(separator = ",$space") { "%L" }
add(placeholders, *joining)
}.build()
)
}
/**
* Generates a 2D array literal where the value at `i`,`j` will be produced by `valueProducer.
* For example:
* ```
* DoubleArrayLiteral(XTypeName.PRIMITIVE_INT, 2, { _ -> 3 }, { i, j -> i + j })
* ```
* For Java will produce:
* ```
* new int[][] {
* {0, 1, 2},
* {1, 2, 3}
* }
* ```
* For Kotlin will produce:
* ```
* arrayOf(
* intArrayOf(0, 1, 2),
* intArrayOf(1, 2, 3)
* )
* ```
*/
fun DoubleArrayLiteral(
language: CodeLanguage,
type: XTypeName,
rowSize: Int,
columnSizeProducer: (Int) -> Int,
valueProducer: (Int, Int) -> Any
): XCodeBlock {
val space = when (language) {
CodeLanguage.JAVA -> "%W"
CodeLanguage.KOTLIN -> " "
}
val outerInit = when (language) {
CodeLanguage.JAVA -> XCodeBlock.of(language, "new %T[][] ", type)
CodeLanguage.KOTLIN -> XCodeBlock.of(language, "arrayOf")
}
val innerInit = when (language) {
CodeLanguage.JAVA -> XCodeBlock.of(language, "", type)
CodeLanguage.KOTLIN -> XCodeBlock.of(language, getArrayOfFunction(type))
}
val openingChar = when (language) {
CodeLanguage.JAVA -> "{"
CodeLanguage.KOTLIN -> "("
}
val closingChar = when (language) {
CodeLanguage.JAVA -> "}"
CodeLanguage.KOTLIN -> ")"
}
return XCodeBlock.of(
language,
"%L$openingChar%L$closingChar",
outerInit,
XCodeBlock.builder(language).apply {
val joining = Array(rowSize) { i ->
XCodeBlock.of(
language,
"%L$openingChar%L$closingChar",
innerInit,
XCodeBlock.builder(language).apply {
val joining = Array(columnSizeProducer(i)) { j ->
XCodeBlock.of(
language,
if (type == CommonTypeNames.STRING) "%S" else "%L",
valueProducer(i, j)
)
}
val placeholders = joining.joinToString(separator = ",$space") { "%L" }
add(placeholders, *joining)
}.build()
)
}
val placeholders = joining.joinToString(separator = ",$space") { "%L" }
add(placeholders, *joining)
}.build()
)
}
private fun getArrayOfFunction(type: XTypeName) = when (type) {
XTypeName.PRIMITIVE_BOOLEAN -> "booleanArrayOf"
XTypeName.PRIMITIVE_BYTE -> "byteArrayOf"
XTypeName.PRIMITIVE_SHORT -> "shortArrayOf"
XTypeName.PRIMITIVE_INT -> "intArrayOf"
XTypeName.PRIMITIVE_LONG -> "longArrayOf"
XTypeName.PRIMITIVE_CHAR -> "charArrayOf"
XTypeName.PRIMITIVE_FLOAT -> "floatArrayOf"
XTypeName.PRIMITIVE_DOUBLE -> "doubleArrayOf"
else -> "arrayOf"
}
fun getToArrayFunction(type: XTypeName) = when (type) {
XTypeName.PRIMITIVE_BOOLEAN -> "toBooleanArray()"
XTypeName.PRIMITIVE_BYTE -> "toByteArray()"
XTypeName.PRIMITIVE_SHORT -> "toShortArray()"
XTypeName.PRIMITIVE_INT -> "toIntArray()"
XTypeName.PRIMITIVE_LONG -> "toLongArray()"
XTypeName.PRIMITIVE_CHAR -> "toCharArray()"
XTypeName.PRIMITIVE_FLOAT -> "toFloatArray()"
XTypeName.PRIMITIVE_DOUBLE -> "toDoubleArray()"
else -> error("Provided type expected to be primitive. Found: $type")
}
/**
* Code of expression for [Collection.size] in Kotlin, and [java.util.Collection.size] for Java.
*/
fun CollectionsSizeExprCode(language: CodeLanguage, varName: String) = XCodeBlock.of(
language,
when (language) {
CodeLanguage.JAVA -> "%L.size()" // java.util.Collections.size()
CodeLanguage.KOTLIN -> "%L.size" // kotlin.collections.Collection.size
},
varName
)
/**
* Code of expression for [Array.size] in Kotlin, and `arr.length` for Java.
*/
fun ArraySizeExprCode(language: CodeLanguage, varName: String) = XCodeBlock.of(
language,
when (language) {
CodeLanguage.JAVA -> "%L.length" // Just `arr.length`
CodeLanguage.KOTLIN -> "%L.size" // kotlin.Array.size and primitives (e.g. IntArray)
},
varName
)
/**
* Code of expression for [Map.keys] in Kotlin, and [java.util.Map.keySet] for Java.
*/
fun MapKeySetExprCode(language: CodeLanguage, varName: String) = XCodeBlock.of(
language,
when (language) {
CodeLanguage.JAVA -> "%L.keySet()" // java.util.Map.keySet()
CodeLanguage.KOTLIN -> "%L.keys" // kotlin.collections.Map.keys
},
varName
) | apache-2.0 | ee6a87a3dba39257592510abe322ab50 | 36.17851 | 99 | 0.670085 | 4.062689 | false | false | false | false |
androidx/androidx | compose/ui/ui/src/test/kotlin/androidx/compose/ui/node/HitTestResultTest.kt | 3 | 14891 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.node
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import com.google.common.truth.Truth.assertThat
@RunWith(JUnit4::class)
class HitTestResultTest {
@Test
fun testHit() {
val hitTestResult = HitTestResult<String>()
hitTestResult.hit("Hello", true) {
hitTestResult.hit("World", true) {
assertThat(hitTestResult.hasHit()).isFalse()
}
assertThat(hitTestResult.hasHit()).isTrue()
}
assertThat(hitTestResult.hasHit()).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0f, true)).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0f, false)).isFalse()
assertThat(hitTestResult).hasSize(2)
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
hitTestResult.hit("Baz", true) {}
assertThat(hitTestResult.hasHit()).isTrue()
assertThat(hitTestResult).hasSize(1)
assertThat(hitTestResult[0]).isEqualTo("Baz")
}
@Test
fun testHitClipped() {
val hitTestResult = HitTestResult<String>()
hitTestResult.hit("Hello", false) {
hitTestResult.hit("World", false) {
assertThat(hitTestResult.hasHit()).isFalse()
}
assertThat(hitTestResult.hasHit()).isFalse()
}
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0f, true)).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0f, false)).isFalse()
assertThat(hitTestResult).hasSize(2)
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
hitTestResult.hit("Baz", false) {}
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult).hasSize(1)
assertThat(hitTestResult[0]).isEqualTo("Baz")
}
@Test
fun testHitInMinimumTouchTarget() {
val hitTestResult = HitTestResult<String>()
hitTestResult.hitInMinimumTouchTarget("Hello", 1f, true) {
hitTestResult.hitInMinimumTouchTarget("World", 2f, false) { }
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(1.5f, false)).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(2.5f, false)).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(2.5f, true)).isTrue()
}
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0.5f, true)).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(1.5f, true)).isFalse()
assertThat(hitTestResult).hasSize(2)
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
hitTestResult.hitInMinimumTouchTarget("Baz", 0.5f, false) { }
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult).hasSize(1)
assertThat(hitTestResult[0]).isEqualTo("Baz")
}
@Test
fun testHasHit() {
val hitTestResult = HitTestResult<String>()
hitTestResult.hitInMinimumTouchTarget("Hello", 1f, true) {
hitTestResult.hit("World", true) {
assertThat(hitTestResult.hasHit()).isFalse()
}
assertThat(hitTestResult.hasHit()).isTrue()
}
assertThat(hitTestResult.hasHit()).isTrue()
}
@Test
fun testEasySpeculativeHit() {
val hitTestResult = HitTestResult<String>()
hitTestResult.speculativeHit("Hello", 1f, true) {
}
assertThat(hitTestResult).hasSize(0)
hitTestResult.speculativeHit("Hello", 1f, true) {
hitTestResult.hitInMinimumTouchTarget("World", 2f, true) {}
}
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0.5f, true)).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(1.5f, true)).isFalse()
assertThat(hitTestResult).hasSize(2)
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
}
@Test
fun testSpeculativeHitWithMove() {
val hitTestResult = HitTestResult<String>()
hitTestResult.hitInMinimumTouchTarget("Foo", 1.5f, true) { }
hitTestResult.speculativeHit("Hello", 1f, true) {
}
assertThat(hitTestResult).hasSize(1)
assertThat(hitTestResult[0]).isEqualTo("Foo")
hitTestResult.speculativeHit("Hello", 1f, true) {
hitTestResult.hitInMinimumTouchTarget("World", 2f, true) {}
}
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0.5f, true)).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(1.25f, true)).isFalse()
assertThat(hitTestResult).hasSize(2)
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
}
@Test
fun testSpeculateHitWithDeepHit() {
val hitTestResult = HitTestResult<String>()
hitTestResult.hitInMinimumTouchTarget("Foo", 1.5f, true) { }
hitTestResult.speculativeHit("Hello", 2f, true) {
hitTestResult.hitInMinimumTouchTarget("World", 1f, true) {}
}
assertThat(hitTestResult.hasHit()).isFalse()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(0.5f, true)).isTrue()
assertThat(hitTestResult.isHitInMinimumTouchTargetBetter(1.25f, true)).isFalse()
assertThat(hitTestResult).hasSize(2)
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
hitTestResult.speculativeHit("Goodbye", 2f, true) {
hitTestResult.hitInMinimumTouchTarget("Cruel", 1f, true) {
hitTestResult.hit("World!", true) {}
}
}
assertThat(hitTestResult.toList()).isEqualTo(listOf("Goodbye", "Cruel", "World!"))
}
@Test
fun testClear() {
val hitTestResult = fillHitTestResult()
assertThat(hitTestResult).hasSize(5)
hitTestResult.clear()
assertThat(hitTestResult).hasSize(0)
}
@Test
fun testContains() {
val hitTestResult = fillHitTestResult()
assertThat(hitTestResult.contains("Hello")).isTrue()
assertThat(hitTestResult.contains("World")).isTrue()
assertThat(hitTestResult.contains("this")).isTrue()
assertThat(hitTestResult.contains("is")).isTrue()
assertThat(hitTestResult.contains("great")).isTrue()
assertThat(hitTestResult.contains("foo")).isFalse()
}
@Test
fun testContainsAll() {
val hitTestResult = fillHitTestResult()
assertThat(hitTestResult.containsAll(listOf("Hello", "great", "this"))).isTrue()
assertThat(hitTestResult.containsAll(listOf("Hello", "great", "foo", "this"))).isFalse()
}
@Test
fun testGet() {
val hitTestResult = fillHitTestResult()
assertThat(hitTestResult[0]).isEqualTo("Hello")
assertThat(hitTestResult[1]).isEqualTo("World")
assertThat(hitTestResult[2]).isEqualTo("this")
assertThat(hitTestResult[3]).isEqualTo("is")
assertThat(hitTestResult[4]).isEqualTo("great")
}
@Test
fun testIndexOf() {
val hitTestResult = fillHitTestResult("World")
assertThat(hitTestResult.indexOf("Hello")).isEqualTo(0)
assertThat(hitTestResult.indexOf("World")).isEqualTo(1)
assertThat(hitTestResult.indexOf("this")).isEqualTo(2)
assertThat(hitTestResult.indexOf("is")).isEqualTo(3)
assertThat(hitTestResult.indexOf("great")).isEqualTo(4)
assertThat(hitTestResult.indexOf("foo")).isEqualTo(-1)
}
@Test
fun testIsEmpty() {
val hitTestResult = fillHitTestResult()
assertThat(hitTestResult.isEmpty()).isFalse()
hitTestResult.clear()
assertThat(hitTestResult.isEmpty()).isTrue()
assertThat(HitTestResult<String>().isEmpty()).isTrue()
}
@Test
fun testIterator() {
val hitTestResult = fillHitTestResult()
assertThat(hitTestResult.toList()).isEqualTo(
listOf("Hello", "World", "this", "is", "great")
)
}
@Test
fun testLastIndexOf() {
val hitTestResult = fillHitTestResult("World")
assertThat(hitTestResult.lastIndexOf("Hello")).isEqualTo(0)
assertThat(hitTestResult.lastIndexOf("World")).isEqualTo(5)
assertThat(hitTestResult.lastIndexOf("this")).isEqualTo(2)
assertThat(hitTestResult.lastIndexOf("is")).isEqualTo(3)
assertThat(hitTestResult.lastIndexOf("great")).isEqualTo(4)
assertThat(hitTestResult.lastIndexOf("foo")).isEqualTo(-1)
}
@Test
fun testListIterator() {
val hitTestResult = fillHitTestResult()
val iterator = hitTestResult.listIterator()
val values = listOf("Hello", "World", "this", "is", "great")
values.forEachIndexed { index, value ->
assertThat(iterator.nextIndex()).isEqualTo(index)
if (index > 0) {
assertThat(iterator.previousIndex()).isEqualTo(index - 1)
}
assertThat(iterator.hasNext()).isTrue()
val hasPrevious = (index != 0)
assertThat(iterator.hasPrevious()).isEqualTo(hasPrevious)
assertThat(iterator.next()).isEqualTo(value)
}
for (index in values.lastIndex downTo 0) {
val value = values[index]
assertThat(iterator.previous()).isEqualTo(value)
}
}
@Test
fun testListIteratorWithStart() {
val hitTestResult = fillHitTestResult()
val iterator = hitTestResult.listIterator(2)
val values = listOf("Hello", "World", "this", "is", "great")
for (index in 2..values.lastIndex) {
assertThat(iterator.nextIndex()).isEqualTo(index)
if (index > 0) {
assertThat(iterator.previousIndex()).isEqualTo(index - 1)
}
assertThat(iterator.hasNext()).isTrue()
val hasPrevious = (index != 0)
assertThat(iterator.hasPrevious()).isEqualTo(hasPrevious)
assertThat(iterator.next()).isEqualTo(values[index])
}
for (index in values.lastIndex downTo 0) {
val value = values[index]
assertThat(iterator.previous()).isEqualTo(value)
}
}
@Test
fun testSubList() {
val hitTestResult = fillHitTestResult()
val subList = hitTestResult.subList(2, 4)
assertThat(subList).hasSize(2)
assertThat(subList.toList()).isEqualTo(listOf("this", "is"))
assertThat(subList.contains("this")).isTrue()
assertThat(subList.contains("foo")).isFalse()
assertThat(subList.containsAll(listOf("this", "is"))).isTrue()
assertThat(subList.containsAll(listOf("is", "this"))).isTrue()
assertThat(subList.containsAll(listOf("foo", "this"))).isFalse()
assertThat(subList[0]).isEqualTo("this")
assertThat(subList[1]).isEqualTo("is")
assertThat(subList.indexOf("is")).isEqualTo(1)
assertThat(subList.isEmpty()).isFalse()
assertThat(hitTestResult.subList(4, 4).isEmpty()).isTrue()
assertThat(subList.subList(0, 2).toList()).isEqualTo(subList.toList())
assertThat(subList.subList(0, 1)[0]).isEqualTo("this")
val listIterator1 = subList.listIterator()
assertThat(listIterator1.hasNext()).isTrue()
assertThat(listIterator1.hasPrevious()).isFalse()
assertThat(listIterator1.nextIndex()).isEqualTo(0)
assertThat(listIterator1.next()).isEqualTo("this")
assertThat(listIterator1.hasNext()).isTrue()
assertThat(listIterator1.hasPrevious()).isTrue()
assertThat(listIterator1.nextIndex()).isEqualTo(1)
assertThat(listIterator1.next()).isEqualTo("is")
assertThat(listIterator1.hasNext()).isFalse()
assertThat(listIterator1.hasPrevious()).isTrue()
assertThat(listIterator1.previousIndex()).isEqualTo(1)
assertThat(listIterator1.previous()).isEqualTo("is")
val listIterator2 = subList.listIterator(1)
assertThat(listIterator2.hasPrevious()).isTrue()
assertThat(listIterator2.hasNext()).isTrue()
assertThat(listIterator2.previousIndex()).isEqualTo(0)
assertThat(listIterator2.nextIndex()).isEqualTo(1)
assertThat(listIterator2.previous()).isEqualTo("this")
}
@Test
fun siblingHits() {
val hitTestResult = HitTestResult<String>()
hitTestResult.siblingHits {
hitTestResult.hit("Hello", true) {
hitTestResult.siblingHits {
hitTestResult.hit("World", true) {}
}
}
hitTestResult.acceptHits()
hitTestResult.hit("this", true) {
hitTestResult.siblingHits {
hitTestResult.hit("is", true) {}
}
}
hitTestResult.acceptHits()
hitTestResult.hit("great", true) {}
}
assertThat(hitTestResult.toList()).isEqualTo(
listOf(
"Hello",
"World",
"this",
"is",
"great"
)
)
}
private fun fillHitTestResult(last: String? = null): HitTestResult<String> {
val hitTestResult = HitTestResult<String>()
hitTestResult.hit("Hello", true) {
hitTestResult.hit("World", true) {
hitTestResult.hit("this", true) {
hitTestResult.hit("is", true) {
hitTestResult.hit("great", true) {
last?.let {
hitTestResult.hit(it, true) {}
}
}
}
}
}
}
return hitTestResult
}
}
| apache-2.0 | 55f9e10cc514950ca0c7500e8c450ffe | 37.084399 | 96 | 0.629575 | 4.659262 | false | true | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/stories/StoryTextPostView.kt | 1 | 7241 | package org.thoughtcrime.securesms.stories
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import androidx.annotation.ColorInt
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.graphics.ColorUtils
import androidx.core.view.doOnNextLayout
import androidx.core.view.isVisible
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.conversation.colors.ChatColors
import org.thoughtcrime.securesms.database.model.databaseprotos.StoryTextPost
import org.thoughtcrime.securesms.fonts.TextFont
import org.thoughtcrime.securesms.linkpreview.LinkPreview
import org.thoughtcrime.securesms.linkpreview.LinkPreviewViewModel
import org.thoughtcrime.securesms.mediasend.v2.text.TextAlignment
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryPostCreationState
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryScale
import org.thoughtcrime.securesms.mediasend.v2.text.TextStoryTextWatcher
import org.thoughtcrime.securesms.util.concurrent.ListenableFuture
import org.thoughtcrime.securesms.util.visible
import java.util.Locale
class StoryTextPostView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
init {
inflate(context, R.layout.stories_text_post_view, this)
}
private var textAlignment: TextAlignment? = null
private val backgroundView: ImageView = findViewById(R.id.text_story_post_background)
private val textView: StoryTextView = findViewById(R.id.text_story_post_text)
private val linkPreviewView: StoryLinkPreviewView = findViewById(R.id.text_story_post_link_preview)
private var isPlaceholder: Boolean = true
init {
TextStoryTextWatcher.install(textView)
}
fun getLinkPreviewThumbnailWidth(useLargeThumbnail: Boolean): Int {
return linkPreviewView.getThumbnailViewWidth(useLargeThumbnail)
}
fun getLinkPreviewThumbnailHeight(useLargeThumbnail: Boolean): Int {
return linkPreviewView.getThumbnailViewHeight(useLargeThumbnail)
}
fun showCloseButton() {
linkPreviewView.setCanClose(true)
}
fun hideCloseButton() {
linkPreviewView.setCanClose(false)
}
fun setTypeface(typeface: Typeface) {
textView.typeface = typeface
}
private fun setPostBackground(drawable: Drawable) {
backgroundView.setImageDrawable(drawable)
}
private fun setTextColor(@ColorInt color: Int, isPlaceholder: Boolean) {
if (isPlaceholder) {
textView.setTextColor(ColorUtils.setAlphaComponent(color, 0x99))
} else {
textView.setTextColor(color)
}
}
private fun setText(text: CharSequence, isPlaceholder: Boolean) {
this.isPlaceholder = isPlaceholder
textView.text = text
}
private fun setTextGravity(textAlignment: TextAlignment) {
textView.gravity = textAlignment.gravity
}
private fun setTextScale(scalePercent: Int) {
val scale = TextStoryScale.convertToScale(scalePercent)
textView.scaleX = scale
textView.scaleY = scale
}
private fun setTextVisible(visible: Boolean) {
textView.visible = visible
}
private fun setTextBackgroundColor(@ColorInt color: Int) {
textView.setWrappedBackgroundColor(color)
}
fun bindFromCreationState(state: TextStoryPostCreationState) {
textAlignment = state.textAlignment
setPostBackground(state.backgroundColor.chatBubbleMask)
setText(
state.body.ifEmpty {
context.getString(R.string.TextStoryPostCreationFragment__tap_to_add_text)
}.let {
if (state.textFont.isAllCaps) {
it.toString().uppercase(Locale.getDefault())
} else {
it
}
},
state.body.isEmpty()
)
setTextColor(state.textForegroundColor, state.body.isEmpty())
setTextBackgroundColor(state.textBackgroundColor)
setTextGravity(state.textAlignment)
setTextScale(state.textScale)
postAdjustLinkPreviewTranslationY()
}
fun bindFromStoryTextPost(storyTextPost: StoryTextPost) {
visible = true
linkPreviewView.visible = false
textAlignment = TextAlignment.CENTER
val font = TextFont.fromStyle(storyTextPost.style)
setPostBackground(ChatColors.forChatColor(ChatColors.Id.NotSet, storyTextPost.background).chatBubbleMask)
if (font.isAllCaps) {
setText(storyTextPost.body.uppercase(Locale.getDefault()), false)
} else {
setText(storyTextPost.body, false)
}
setTextColor(storyTextPost.textForegroundColor, false)
setTextBackgroundColor(storyTextPost.textBackgroundColor)
setTextGravity(TextAlignment.CENTER)
hideCloseButton()
postAdjustLinkPreviewTranslationY()
}
fun bindLinkPreview(linkPreview: LinkPreview?, useLargeThumbnail: Boolean, loadThumbnail: Boolean = true): ListenableFuture<Boolean> {
return linkPreviewView.bind(linkPreview, View.GONE, useLargeThumbnail, loadThumbnail)
}
fun setLinkPreviewDrawable(drawable: Drawable?, useLargeThumbnail: Boolean) {
linkPreviewView.setThumbnailDrawable(drawable, useLargeThumbnail)
}
fun bindLinkPreviewState(linkPreviewState: LinkPreviewViewModel.LinkPreviewState, hiddenVisibility: Int, useLargeThumbnail: Boolean) {
linkPreviewView.bind(linkPreviewState, hiddenVisibility, useLargeThumbnail)
}
fun postAdjustLinkPreviewTranslationY() {
setTextVisible(canDisplayText())
doOnNextLayout {
adjustLinkPreviewTranslationY()
}
}
fun setTextViewClickListener(onClickListener: OnClickListener) {
setOnClickListener(onClickListener)
}
fun setLinkPreviewCloseListener(onClickListener: OnClickListener) {
linkPreviewView.setOnCloseClickListener(onClickListener)
}
fun setLinkPreviewClickListener(onClickListener: OnClickListener?) {
linkPreviewView.setOnPreviewClickListener(onClickListener)
}
fun showPostContent() {
textView.alpha = 1f
linkPreviewView.alpha = 1f
}
fun hidePostContent() {
textView.alpha = 0f
linkPreviewView.alpha = 0f
}
private fun canDisplayText(): Boolean {
return !(linkPreviewView.isVisible && (isPlaceholder || textView.text.isEmpty()))
}
private fun adjustLinkPreviewTranslationY() {
val backgroundHeight = backgroundView.measuredHeight
val textHeight = if (canDisplayText()) textView.measuredHeight * textView.scaleY else 0f
val previewHeight = if (linkPreviewView.visible) linkPreviewView.measuredHeight else 0
val availableHeight = backgroundHeight - textHeight
if (availableHeight >= previewHeight) {
val totalContentHeight = textHeight + previewHeight
val topAndBottomMargin = backgroundHeight - totalContentHeight
val margin = topAndBottomMargin / 2f
linkPreviewView.translationY = -margin
val originPoint = textView.measuredHeight / 2f
val desiredPoint = (textHeight / 2f) + margin
textView.translationY = desiredPoint - originPoint
} else {
linkPreviewView.translationY = 0f
val originPoint = textView.measuredHeight / 2f
val desiredPoint = backgroundHeight / 2f
textView.translationY = desiredPoint - originPoint
}
}
}
| gpl-3.0 | 1d827a42031f6c14bfb4bce4c51eed34 | 31.325893 | 136 | 0.769093 | 4.830554 | false | false | false | false |
androidx/androidx | glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/translators/CompoundButtonTranslator.kt | 3 | 3065 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget.translators
import android.content.Context
import android.content.res.ColorStateList
import android.widget.RemoteViews
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.core.widget.RemoteViewsCompat.setImageViewColorFilter
import androidx.glance.appwidget.unit.CheckableColorProvider
import androidx.glance.appwidget.unit.CheckedStateSet
import androidx.glance.appwidget.unit.CheckedUncheckedColorProvider
import androidx.glance.appwidget.unit.ResourceCheckableColorProvider
import androidx.glance.appwidget.unit.resolveCheckedColor
import androidx.glance.color.isNightMode
internal val checkableColorProviderFallbackColor = Color.Black
private fun CheckedUncheckedColorProvider.toColorStateList(
context: Context,
isNightMode: Boolean
): ColorStateList {
return createCheckedColorStateList(
checked = getColor(context, isNightMode, isChecked = true),
unchecked = getColor(context, isNightMode, isChecked = false)
)
}
internal fun CheckedUncheckedColorProvider.toDayNightColorStateList(
context: Context
): DayNightColorStateList {
return DayNightColorStateList(
day = toColorStateList(context, isNightMode = false),
night = toColorStateList(context, isNightMode = true)
)
}
/**
* Creates a [ColorStateList] switching between [checked] and [unchecked] depending on the checked
* state.
*/
private fun createCheckedColorStateList(checked: Color, unchecked: Color): ColorStateList {
return ColorStateList(
arrayOf(CheckedStateSet, intArrayOf()),
intArrayOf(checked.toArgb(), unchecked.toArgb())
)
}
internal fun CheckableColorProvider.getColor(context: Context, isChecked: Boolean): Color {
return when (this) {
is CheckedUncheckedColorProvider -> getColor(context, context.isNightMode, isChecked)
is ResourceCheckableColorProvider -> {
resolveCheckedColor(context, resId, isChecked)
}
} ?: checkableColorProviderFallbackColor
}
/**
* Pair class holding two [ColorStateList]s corresponding to day and night alternatives for
* [RemoteViews] APIs that accept two [ColorStateList]s for day/night.
*/
internal data class DayNightColorStateList(val day: ColorStateList, val night: ColorStateList)
internal fun RemoteViews.setImageViewColorFilter(viewId: Int, color: Color) {
setImageViewColorFilter(viewId, color.toArgb())
} | apache-2.0 | 2e3cee29773a2746a327fe1e199ee521 | 36.851852 | 98 | 0.775204 | 4.672256 | false | false | false | false |
androidx/androidx | buildSrc/private/src/main/kotlin/androidx/build/dokka/kmpDocs/DokkaUtils.kt | 3 | 5148 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.dokka.kmpDocs
import androidx.build.getLibraryByName
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonElement
import com.google.gson.JsonPrimitive
import com.google.gson.JsonSerializationContext
import com.google.gson.JsonSerializer
import java.io.File
import java.lang.reflect.Type
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.Project
import org.gradle.api.artifacts.Configuration
import org.gradle.api.file.FileCollection
internal object DokkaUtils {
/**
* List of Dokka plugins that needs to be added to produce partial docs for a project.
*/
private val REQUIRED_PLUGIN_LIBRARIES = listOf(
"dokkaBase",
"kotlinXHtml",
"dokkaAnalysis",
"dokkaAnalysisIntellij",
"dokkaAnalysisCompiler",
"freemarker",
"dokkaAndroidDocumentation",
)
/**
* List of Dokka plugins that needs to be added to produce combined docs for a set of partial
* docs.
*/
val COMBINE_PLUGIN_LIBRARIES = listOf(
"dokkaAllModules",
"dokkaTemplating",
)
/**
* The CLI executable of Dokka.
*/
private val CLI_JAR_COORDINATES = listOf(
"dokkaCli"
)
private const val CS_ANDROID_SRC_ROOT =
"https://cs.android.com/androidx/platform/frameworks/support/+/"
/**
* Placeholder URL that use used by the first step of partial docs generation.
* This placeholder is later replaced by the HEAD sha of the repository.
* It needs to look like a URL because Dokka parses it as URL.
*/
internal const val CS_ANDROID_PLACEHOLDER = "https://__DOKKA_REPLACE_WITH_SRC_LINK__.com/"
fun createCsAndroidUrl(sha: String) = "$CS_ANDROID_SRC_ROOT$sha:"
/**
* Creates a configuration for the [project] from the given set of dokka plugin libraries.
* These libraries are defined in the Gradle Version catalog.
* @see COMBINE_PLUGIN_LIBRARIES
* @see REQUIRED_PLUGIN_LIBRARIES
*/
fun createPluginsConfiguration(
project: Project,
additionalPluginLibraries: List<String> = emptyList()
): NamedDomainObjectProvider<Configuration> {
return project.configurations.register("dokkaCliPlugins") { config ->
(REQUIRED_PLUGIN_LIBRARIES + additionalPluginLibraries).forEach {
config.dependencies.add(
project.dependencies.create(
// find the coordinates from the version catalog
project.getLibraryByName(it)
)
)
}
}
}
/**
* Creates a configuration to resolve dokka cli jar and its dependencies.
*/
internal fun createCliJarConfiguration(
project: Project
): NamedDomainObjectProvider<Configuration> {
return project.configurations.register("dokkaCliJar") { config ->
CLI_JAR_COORDINATES.forEach {
config.dependencies.add(
project.dependencies.create(
// find the coordinates from the version catalog
project.getLibraryByName(it)
)
)
}
}
}
/**
* Creates a GSON instance that can be used to serialize Dokka CLI json models.
*/
fun createGson(): Gson = GsonBuilder().setPrettyPrinting()
.registerTypeAdapter(
File::class.java, CanonicalFileSerializer()
).registerTypeAdapter(
FileCollection::class.java,
FileCollectionSerializer()
)
.create()
/**
* Serializer for Gradle's [FileCollection]
*/
private class FileCollectionSerializer : JsonSerializer<FileCollection> {
override fun serialize(
src: FileCollection,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement {
return context.serialize(src.files)
}
}
/**
* Serializer for [File] instances in the Dokka CLI model.
*
* Dokka doesn't work well with relative paths hence we use a canonical paths while setting up
* its parameters.
*/
private class CanonicalFileSerializer : JsonSerializer<File> {
override fun serialize(
src: File,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement {
return JsonPrimitive(src.canonicalPath)
}
}
} | apache-2.0 | bb3f7c32d4757603599662394e2e573a | 32.219355 | 98 | 0.642774 | 4.921606 | false | true | false | false |
GunoH/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/project/actions/MavenDependencyAnalyzerAction.kt | 6 | 3360 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.idea.maven.project.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformCoreDataKeys
import com.intellij.openapi.externalSystem.dependency.analyzer.*
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.module.Module
import com.intellij.ui.treeStructure.SimpleTree
import org.jetbrains.idea.maven.navigator.MavenProjectsStructure.*
import org.jetbrains.idea.maven.project.MavenProjectsManager
import org.jetbrains.idea.maven.utils.MavenUtil
class ViewDependencyAnalyzerAction : AbstractDependencyAnalyzerAction<MavenSimpleNode>() {
override fun getSystemId(e: AnActionEvent): ProjectSystemId = MavenUtil.SYSTEM_ID
override fun getSelectedData(e: AnActionEvent): MavenSimpleNode? {
val data = e.getData(PlatformCoreDataKeys.CONTEXT_COMPONENT)
return (data as? SimpleTree)?.selectedNode as? MavenSimpleNode
}
override fun getModule(e: AnActionEvent, selectedData: MavenSimpleNode): Module? {
val project = e.project ?: return null
val projectNode = selectedData.findNode(ProjectNode::class.java) ?: return null
val mavenProjectsManager = MavenProjectsManager.getInstance(project)
return mavenProjectsManager.findModule(projectNode.mavenProject)
}
override fun getDependencyData(e: AnActionEvent, selectedData: MavenSimpleNode): DependencyAnalyzerDependency.Data? {
return when (selectedData) {
is DependencyNode -> {
DAArtifact(
selectedData.artifact.groupId,
selectedData.artifact.artifactId,
selectedData.artifact.version
)
}
is ProjectNode -> {
DAModule(selectedData.mavenProject.displayName)
}
else -> null
}
}
override fun getDependencyScope(e: AnActionEvent, selectedData: MavenSimpleNode): String? {
if (selectedData is DependencyNode) {
return selectedData.artifact.scope
}
return null
}
}
class NavigatorDependencyAnalyzerAction : DependencyAnalyzerAction() {
private val viewAction = ViewDependencyAnalyzerAction()
override fun getSystemId(e: AnActionEvent): ProjectSystemId = MavenUtil.SYSTEM_ID
override fun isEnabledAndVisible(e: AnActionEvent) = true
override fun setSelectedState(view: DependencyAnalyzerView, e: AnActionEvent) {
viewAction.setSelectedState(view, e)
}
}
class ProjectViewDependencyAnalyzerAction : AbstractDependencyAnalyzerAction<Module>() {
override fun getSystemId(e: AnActionEvent): ProjectSystemId = MavenUtil.SYSTEM_ID
override fun getSelectedData(e: AnActionEvent): Module? {
val project = e.project ?: return null
val module = e.getData(PlatformCoreDataKeys.MODULE) ?: return null
if (MavenProjectsManager.getInstance(project).isMavenizedModule(module)) {
return module
}
return null
}
override fun getModule(e: AnActionEvent, selectedData: Module): Module {
return selectedData
}
override fun getDependencyData(e: AnActionEvent, selectedData: Module): DependencyAnalyzerDependency.Data {
return DAModule(selectedData.name)
}
override fun getDependencyScope(e: AnActionEvent, selectedData: Module) = null
}
| apache-2.0 | a35065eccc4d476f22b869fe2511aacf | 36.333333 | 158 | 0.770238 | 4.827586 | false | false | false | false |
GunoH/intellij-community | python/src/com/jetbrains/python/newProject/steps/PyAddNewEnvironmentPanel.kt | 5 | 4002 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.jetbrains.python.newProject.steps
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.ComboBox
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.UserDataHolderBase
import com.intellij.ui.SimpleListCellRenderer
import com.intellij.util.ui.FormBuilder
import com.jetbrains.python.sdk.PySdkProvider
import com.jetbrains.python.sdk.PySdkSettings
import com.jetbrains.python.sdk.add.PyAddNewCondaEnvPanel
import com.jetbrains.python.sdk.add.PyAddNewEnvPanel
import com.jetbrains.python.sdk.add.PyAddNewVirtualEnvPanel
import com.jetbrains.python.sdk.add.PyAddSdkPanel
import com.jetbrains.python.sdk.conda.PyCondaSdkCustomizer
import java.awt.BorderLayout
import java.awt.event.ItemEvent
import javax.swing.JComboBox
class PyAddNewEnvironmentPanel(existingSdks: List<Sdk>, newProjectPath: String?, preferredType: String?) : PyAddSdkPanel() {
override val panelName: String get() = com.jetbrains.python.PyBundle.message("python.add.sdk.panel.name.new.environment.using")
override val nameExtensionComponent: JComboBox<PyAddNewEnvPanel>
override var newProjectPath: String? = newProjectPath
set(value) {
field = value
for (panel in panels) {
panel.newProjectPath = newProjectPath
}
}
private val context: UserDataHolder = UserDataHolderBase()
// TODO: Introduce a method in PyAddSdkProvider or in a Python SDK Provider
private val panels = createPanels(existingSdks, newProjectPath)
var selectedPanel: PyAddNewEnvPanel = panels.find { it.envName == (preferredType ?: PySdkSettings.instance.preferredEnvironmentType) } ?: panels[0]
private val listeners = mutableListOf<Runnable>()
init {
nameExtensionComponent = ComboBox(panels.toTypedArray()).apply {
renderer = SimpleListCellRenderer.create {label, value, _ ->
label.text = value?.envName ?: return@create
label.icon = value.icon
}
selectedItem = selectedPanel
addItemListener {
if (it.stateChange == ItemEvent.SELECTED) {
val selected = it.item as? PyAddSdkPanel ?: return@addItemListener
for (panel in panels) {
val isSelected = panel == selected
panel.isVisible = isSelected
if (isSelected) {
selectedPanel = panel
}
}
for (listener in listeners) {
listener.run()
}
}
}
}
layout = BorderLayout()
val formBuilder = FormBuilder.createFormBuilder().apply {
for (panel in panels) {
addComponent(panel)
panel.isVisible = panel == selectedPanel
}
}
add(formBuilder.panel, BorderLayout.NORTH)
}
override fun getOrCreateSdk(): Sdk? {
val createdSdk = selectedPanel.getOrCreateSdk()
PySdkSettings.instance.preferredEnvironmentType = selectedPanel.envName
return createdSdk
}
override fun validateAll(): List<ValidationInfo> = selectedPanel.validateAll()
override fun addChangeListener(listener: Runnable) {
for (panel in panels) {
panel.addChangeListener(listener)
}
listeners += listener
}
private fun createPanels(existingSdks: List<Sdk>, newProjectPath: String?): List<PyAddNewEnvPanel> {
val condaPanel = PyAddNewCondaEnvPanel(null, null, existingSdks, newProjectPath)
val venvPanel = PyAddNewVirtualEnvPanel(null, null, existingSdks, newProjectPath, context)
val envPanelsFromProviders = PySdkProvider.EP_NAME.extensionList
.map { it.createNewEnvironmentPanel(null, null, existingSdks, newProjectPath, context) }
.toTypedArray()
return if (PyCondaSdkCustomizer.instance.preferCondaEnvironments) {
listOf(condaPanel, venvPanel, *envPanelsFromProviders)
}
else {
listOf(venvPanel, *envPanelsFromProviders, condaPanel)
}
}
}
| apache-2.0 | 325a74114d10b8a0d26684a42eba428d | 37.114286 | 149 | 0.729135 | 4.610599 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeVisibleFactory.kt | 4 | 2692 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities.*
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory3
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperclassesWithoutAny
object MakeVisibleFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val element = diagnostic.psiElement as? KtElement ?: return emptyList()
val usageModule = element.findModuleDescriptor()
@Suppress("UNCHECKED_CAST")
val factory = diagnostic.factory as DiagnosticFactory3<*, DeclarationDescriptor, *, DeclarationDescriptor>
val descriptor = factory.cast(diagnostic).c as? DeclarationDescriptorWithVisibility ?: return emptyList()
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor) as? KtModifierListOwner ?: return emptyList()
if (declaration.hasModifier(KtTokens.SEALED_KEYWORD) && descriptor is ClassConstructorDescriptor) return emptyList()
val module = DescriptorUtils.getContainingModule(descriptor)
val targetVisibilities = when (descriptor.visibility) {
PRIVATE, INVISIBLE_FAKE -> mutableListOf(PUBLIC).apply {
if (module == usageModule) add(INTERNAL)
val superClasses = (element.containingClass()?.descriptor as? ClassDescriptor)?.getAllSuperclassesWithoutAny()
if (superClasses?.contains(declaration.containingClass()?.descriptor) == true) add(PROTECTED)
}
else -> listOf(PUBLIC)
}
return targetVisibilities.mapNotNull { ChangeVisibilityFix.create(declaration, descriptor, it) }
}
}
| apache-2.0 | 4d641e5889edd22e3699086f7d6c3db4 | 56.276596 | 158 | 0.78529 | 5.299213 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ClassMemberConversion.kt | 2 | 2796 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.conversions
import com.intellij.psi.PsiField
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.j2k.ast.Nullability.NotNull
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.externalCodeProcessing.JKFieldDataFromJava
import org.jetbrains.kotlin.nj2k.externalCodeProcessing.JKPhysicalMethodData
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.tree.Modality.FINAL
import org.jetbrains.kotlin.nj2k.tree.Mutability.IMMUTABLE
import org.jetbrains.kotlin.nj2k.tree.Mutability.MUTABLE
import org.jetbrains.kotlin.nj2k.tree.OtherModifier.STATIC
import org.jetbrains.kotlin.nj2k.types.JKJavaArrayType
import org.jetbrains.kotlin.nj2k.types.arrayInnerType
import org.jetbrains.kotlin.nj2k.types.isStringType
import org.jetbrains.kotlin.nj2k.types.updateNullabilityRecursively
class ClassMemberConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
when (element) {
is JKMethodImpl -> element.convert()
is JKField -> element.convert()
}
return recurse(element)
}
private fun JKMethodImpl.convert() {
if (throwsList.isNotEmpty()) {
annotationList.annotations +=
throwsAnnotation(throwsList.map { it.type.updateNullabilityRecursively(NotNull) }, symbolProvider)
}
if (isMainFunctionDeclaration()) {
annotationList.annotations += jvmAnnotation("JvmStatic", symbolProvider)
parameters.single().let {
it.type.type = JKJavaArrayType(typeFactory.types.string, NotNull)
it.isVarArgs = false
}
}
psi<PsiMethod>()?.let { psiMethod ->
context.externalCodeProcessor.addMember(JKPhysicalMethodData(psiMethod))
}
}
private fun JKMethodImpl.isMainFunctionDeclaration(): Boolean {
if (name.value != "main") return false
if (!hasOtherModifier(STATIC)) return false
val parameter = parameters.singleOrNull() ?: return false
return when {
parameter.type.type.arrayInnerType()?.isStringType() == true -> true
parameter.isVarArgs && parameter.type.type.isStringType() -> true
else -> false
}
}
private fun JKField.convert() {
mutability = if (modality == FINAL) IMMUTABLE else MUTABLE
modality = FINAL
psi<PsiField>()?.let { psiField ->
context.externalCodeProcessor.addMember(JKFieldDataFromJava(psiField))
}
}
}
| apache-2.0 | f12b1cffc3725afd8c256038cb5be2f3 | 42.015385 | 158 | 0.706366 | 4.60626 | false | false | false | false |
firebase/friendlyeats-android | app/src/main/java/com/google/firebase/example/fireeats/Filters.kt | 1 | 2339 | package com.google.firebase.example.fireeats
import android.content.Context
import android.text.TextUtils
import com.google.firebase.example.fireeats.model.Restaurant
import com.google.firebase.example.fireeats.util.RestaurantUtil
import com.google.firebase.firestore.Query
/**
* Object for passing filters around.
*/
class Filters {
var category: String? = null
var city: String? = null
var price = -1
var sortBy: String? = null
var sortDirection: Query.Direction = Query.Direction.DESCENDING
fun hasCategory(): Boolean {
return !TextUtils.isEmpty(category)
}
fun hasCity(): Boolean {
return !TextUtils.isEmpty(city)
}
fun hasPrice(): Boolean {
return price > 0
}
fun hasSortBy(): Boolean {
return !TextUtils.isEmpty(sortBy)
}
fun getSearchDescription(context: Context): String {
val desc = StringBuilder()
if (category == null && city == null) {
desc.append("<b>")
desc.append(context.getString(R.string.all_restaurants))
desc.append("</b>")
}
if (category != null) {
desc.append("<b>")
desc.append(category)
desc.append("</b>")
}
if (category != null && city != null) {
desc.append(" in ")
}
if (city != null) {
desc.append("<b>")
desc.append(city)
desc.append("</b>")
}
if (price > 0) {
desc.append(" for ")
desc.append("<b>")
desc.append(RestaurantUtil.getPriceString(price))
desc.append("</b>")
}
return desc.toString()
}
fun getOrderDescription(context: Context): String {
return when (sortBy) {
Restaurant.FIELD_PRICE -> context.getString(R.string.sorted_by_price)
Restaurant.FIELD_POPULARITY -> context.getString(R.string.sorted_by_popularity)
else -> context.getString(R.string.sorted_by_rating)
}
}
companion object {
val default: Filters
get() {
val filters = Filters()
filters.sortBy = Restaurant.FIELD_AVG_RATING
filters.sortDirection = Query.Direction.DESCENDING
return filters
}
}
}
| apache-2.0 | d74b12e31a6c024db201991b4d7a091d | 24.988889 | 91 | 0.568192 | 4.42155 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/KotlinVariableNameFinder.kt | 3 | 6856 | // 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.coroutine
import com.intellij.debugger.NoDataException
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.psi.util.parents
import com.intellij.psi.util.parentsOfType
import com.intellij.util.concurrency.annotations.RequiresReadLock
import com.sun.jdi.Location
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.debugger.KotlinPositionManager
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.inline.InlineUtil
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
internal class KotlinVariableNameFinder(val debugProcess: DebugProcessImpl) {
@RequiresReadLock
fun findVisibleVariableNames(location: Location): List<String> {
val sourcePosition = location.safeSourcePosition(debugProcess) ?: return emptyList()
ProgressManager.checkCanceled()
return sourcePosition.elementAt.findVisibleVariableNames()
}
private fun PsiElement.findVisibleVariableNames(): List<String> {
val enclosingBlockExpression = findEnclosingBlockExpression() ?: return emptyList()
val blockParents = enclosingBlockExpression.parentsOfType<KtBlockExpression>()
if (blockParents.none()) {
return emptyList()
}
ProgressManager.checkCanceled()
val bindingContext = blockParents.last().analyze(BodyResolveMode.PARTIAL)
ProgressManager.checkCanceled()
val expressionToStartAnalysisFrom =
enclosingBlockExpression.findExpressionToStartAnalysisFrom(bindingContext)
if (!expressionToStartAnalysisFrom.isCoroutineContextAvailable(bindingContext)) {
return emptyList()
}
ProgressManager.checkCanceled()
val parentFunction = expressionToStartAnalysisFrom.parentOfType<KtFunction>(true)
val namesInParameterList =
parentFunction?.findVariableNamesInParameterList() ?: emptyList()
val namesVisibleInExpression = expressionToStartAnalysisFrom.findVariableNames(
bindingContext, this, blockParents
)
return namesVisibleInExpression + namesInParameterList
}
private fun KtExpression.findVariableNames(
bindingContext: BindingContext,
boundaryElement: PsiElement,
blocksToVisit: Sequence<KtBlockExpression>
): List<String> {
val names = mutableListOf<String>()
accept(object : KtTreeVisitorVoid() {
var stopTraversal = false
override fun visitBlockExpression(expression: KtBlockExpression) {
if (expression.isInlined(bindingContext) || expression in blocksToVisit) {
expression.acceptChildren(this)
}
}
override fun visitKtElement(element: KtElement) {
ProgressManager.checkCanceled()
when {
stopTraversal -> return
element.startOffset >= boundaryElement.startOffset -> {
stopTraversal = true
return
}
element is KtVariableDeclaration &&
!element.shouldBeFiltered(boundaryElement) -> {
element.name?.let { names.add(it) }
}
}
element.acceptChildren(this)
}
})
return names
}
private fun KtFunction.findVariableNamesInParameterList(): List<String> {
val parameterList = getChildOfType<KtParameterList>() ?: return emptyList()
return parameterList.parameters.mapNotNull { it.name }
}
private fun KtExpression.findExpressionToStartAnalysisFrom(bindingContext: BindingContext): KtExpression {
var lastSeenBlockExpression = this
for (parent in parents(true)) {
when (parent) {
is KtNamedFunction -> return parent
is KtBlockExpression -> {
if (!parent.isInlined(bindingContext) && parent.parent !is KtWhenEntry) {
return parent
}
lastSeenBlockExpression = parent
}
}
}
return lastSeenBlockExpression
}
private fun KtExpression.isCoroutineContextAvailable(bindingContext: BindingContext) =
isCoroutineContextAvailableFromFunction() || isCoroutineContextAvailableFromLambda(bindingContext)
private fun KtExpression.isCoroutineContextAvailableFromFunction(): Boolean {
val functionParent = parentOfType<KtFunction>(true) ?: return false
val descriptor = functionParent.descriptor as? CallableDescriptor ?: return false
return descriptor.isSuspend
}
private fun KtExpression.isCoroutineContextAvailableFromLambda(bindingContext: BindingContext): Boolean {
val type = getType(bindingContext) ?: return false
return type.isSuspendFunctionType
}
private fun PsiElement.findEnclosingBlockExpression(): KtBlockExpression? {
for (parent in parents(false)) {
when (parent) {
is KtFunction, is KtWhenEntry, is KtLambdaExpression ->
return parent.getChildOfType()
is KtBlockExpression ->
return parent
}
}
return null
}
private fun KtDeclaration.shouldBeFiltered(elementAtBreakpointPosition: PsiElement) =
if (parent is KtWhenExpression) {
parent !in elementAtBreakpointPosition.parents(false)
} else {
false
}
private fun KtBlockExpression.isInlined(bindingContext: BindingContext): Boolean {
val parentFunction = parentOfType<KtFunction>() ?: return false
return InlineUtil.isInlinedArgument(parentFunction, bindingContext, false)
}
private fun Location.safeSourcePosition(debugProcess: DebugProcessImpl) =
try {
KotlinPositionManager(debugProcess).getSourcePosition(this)
} catch (ex: NoDataException) {
null
}
}
| apache-2.0 | 10915346ba9a0a323e0a18a1567ee023 | 41.583851 | 158 | 0.685677 | 5.775906 | false | false | false | false |
GunoH/intellij-community | plugins/settings-repository/src/repositoryListEditor.kt | 2 | 4236 | // 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.settingsRepository
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.configurationStore.StateStorageManagerImpl
import com.intellij.configurationStore.reloadAppStore
import com.intellij.configurationStore.schemeManager.SchemeManagerFactoryBase
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.options.SchemeManagerFactory
import com.intellij.openapi.progress.ModalTaskOwner
import com.intellij.openapi.progress.runBlockingModal
import com.intellij.openapi.progress.runModalTask
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.Cell
import com.intellij.ui.dsl.builder.panel
import com.intellij.util.ui.ComboBoxModelEditor
import com.intellij.util.ui.ListItemEditor
import kotlinx.coroutines.ensureActive
import javax.swing.JButton
private class RepositoryItem(var url: String? = null) {
override fun toString() = url ?: ""
}
internal fun createRepositoryListEditor(icsManager: IcsManager): DialogPanel {
val editor = ComboBoxModelEditor(object : ListItemEditor<RepositoryItem> {
override fun getItemClass() = RepositoryItem::class.java
override fun clone(item: RepositoryItem, forInPlaceEditing: Boolean) = RepositoryItem(item.url)
})
lateinit var deleteButton: Cell<JButton>
return panel {
row(icsMessage("repository.editor.repository.label")) {
cell(editor.comboBox)
.comment(icsMessage("repository.editor.combobox.comment"))
deleteButton = button(IcsBundle.message("repository.editor.delete.button")) {
editor.model.selected?.let { selected ->
editor.model.remove(selected)
deleteButton.enabled(editor.model.selected != null)
}
}
}
onIsModified { editor.isModified }
onApply {
val newList = editor.apply()
if (newList.isEmpty()) {
// repo is deleted
deleteRepository(icsManager)
}
}
onReset {
val list = ArrayList<RepositoryItem>()
val upstream = icsManager.repositoryManager.getUpstream()?.let(::RepositoryItem)
upstream?.let {
list.add(it)
}
editor.reset(list)
editor.model.selectedItem = upstream
deleteButton.enabled(editor.model.selectedItem != null)
}
}
}
private fun deleteRepository(icsManager: IcsManager) {
// as two tasks, - user should be able to cancel syncing before delete and continue to delete
runBlockingModal(ModalTaskOwner.guess(), IcsBundle.message("progress.syncing.before.deleting.repository")) {
val repositoryManager = icsManager.repositoryManager
// attempt to fetch, merge and push to ensure that latest changes in the deleted user repository will be not lost
// yes, - delete repository doesn't mean "AAA, delete it, delete". It means just that user doesn't need it at this moment.
// It is user responsibility later to delete git repository or do whatever user want. Our responsibility is to not loose user changes.
if (!repositoryManager.canCommit()) {
LOG.info("Commit on repository delete skipped: repository is not committable")
return@runBlockingModal
}
catchAndLog(asWarning = true) {
val updater = repositoryManager.fetch()
ensureActive()
// ignore result, we don't need to apply it
updater.merge()
ensureActive()
if (!updater.definitelySkipPush) {
repositoryManager.push()
}
}
}
runModalTask(IcsBundle.message("progress.deleting.repository"), cancellable = false) { indicator ->
val repositoryManager = icsManager.repositoryManager
indicator.isIndeterminate = true
try {
repositoryManager.deleteRepository()
}
finally {
icsManager.isRepositoryActive = false
}
}
val store = ApplicationManager.getApplication().stateStore as ComponentStoreImpl
if (!reloadAppStore((store.storageManager as StateStorageManagerImpl).getCachedFileStorages())) {
return
}
(SchemeManagerFactory.getInstance() as SchemeManagerFactoryBase).process {
it.reload()
}
} | apache-2.0 | 2ed56a4873bf72d3cf2b7abbbacebcc1 | 35.525862 | 138 | 0.739849 | 4.819113 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/intellij/concurrent/ZCompletableBackgroundable.kt | 1 | 1184 | package zielu.intellij.concurrent
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executor
internal abstract class ZCompletableBackgroundable<T>(
project: Project?,
title: String,
canBeCancelled: Boolean = true
) : Task.Backgroundable(
project,
title,
canBeCancelled
) {
private val latch = CountDownLatch(1)
private var result: T? = null
private var error: Throwable? = null
private var cancelled: Boolean = false
protected abstract fun getResult(): T
final override fun onCancel() {
cancelled = true
latch.countDown()
}
final override fun onSuccess() {
result = getResult()
latch.countDown()
}
final override fun onThrowable(error: Throwable) {
this.error = error
latch.countDown()
}
private fun supplyAsyncResult(): T {
latch.await()
error?.apply { throw this }
return result!!
}
fun asCompletableFuture(executor: Executor): CompletableFuture<T> {
queue()
return CompletableFuture.supplyAsync({ supplyAsyncResult() }, executor)
}
}
| apache-2.0 | f7060d3332bd9658eff0e83608a34e79 | 22.68 | 75 | 0.726351 | 4.434457 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/script/AbstractScriptDefinitionsOrderTest.kt | 1 | 2035 | // 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.script
import com.intellij.codeInsight.daemon.DaemonAnalyzerTestCase
import com.intellij.testFramework.exceptionCases.AbstractExceptionCase
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.test.InTextDirectivesUtils
import org.junit.ComparisonFailure
@DaemonAnalyzerTestCase.CanChangeDocumentDuringHighlighting
abstract class AbstractScriptDefinitionsOrderTest : AbstractScriptConfigurationTest() {
fun doTest(unused: String) {
configureScriptFile(testDataFile())
assertThrows(ComparisonFailure::class.java) {
checkHighlighting(editor, false, false)
}
val definitions = InTextDirectivesUtils.findStringWithPrefixes(myFile.text, "// SCRIPT DEFINITIONS: ")
?.split(";")
?.map { it.substringBefore(":").trim() to it.substringAfter(":").trim() }
?: error("SCRIPT DEFINITIONS directive should be defined")
val allDefinitions = ScriptDefinitionsManager.getInstance(project).getAllDefinitions()
for ((definitionName, action) in definitions) {
val scriptDefinition = allDefinitions
.find { it.name == definitionName }
?: error("Unknown script definition name in SCRIPT DEFINITIONS directive: name=$definitionName, all={${allDefinitions.joinToString { it.name }}}")
when (action) {
"off" -> KotlinScriptingSettings.getInstance(project).setEnabled(scriptDefinition, false)
else -> KotlinScriptingSettings.getInstance(project).setOrder(scriptDefinition, action.toInt())
}
}
ScriptDefinitionsManager.getInstance(project).reorderScriptDefinitions()
checkHighlighting(editor, false, false)
}
} | apache-2.0 | 98ce8958456c1f121eb18d0c78e3ee5d | 48.658537 | 162 | 0.724816 | 5.383598 | false | true | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/NodeChooseTypeAction.kt | 1 | 2281 | // 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.actions
import com.intellij.ide.bookmark.Bookmark
import com.intellij.ide.bookmark.BookmarkBundle
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.popup.PopupState
internal class NodeChooseTypeAction : DumbAwareAction(BookmarkBundle.messagePointer("mnemonic.chooser.mnemonic.change.action.text")) {
private val popupState = PopupState.forPopup()
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible = false
if (popupState.isShowing) return
val manager = event.bookmarksManager ?: return
val bookmark = event.bookmarksViewFromToolWindow?.selectedNode?.value as? Bookmark ?: return
val type = manager.getType(bookmark) ?: return
if (type == BookmarkType.DEFAULT) event.presentation.text = BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.action.text")
event.presentation.isEnabledAndVisible = true
}
override fun actionPerformed(event: AnActionEvent) {
if (popupState.isRecentlyHidden) return
val manager = event.bookmarksManager ?: return
val bookmark = event.bookmarksViewFromToolWindow?.selectedNode?.value as? Bookmark ?: return
val type = manager.getType(bookmark) ?: return
val chooser = BookmarkTypeChooser(type, manager.assignedTypes) {
popupState.hidePopup()
manager.setType(bookmark, it)
}
val title = when (type) {
BookmarkType.DEFAULT -> BookmarkBundle.message("mnemonic.chooser.mnemonic.assign.popup.title")
else -> BookmarkBundle.message("mnemonic.chooser.mnemonic.change.popup.title")
}
JBPopupFactory.getInstance().createComponentPopupBuilder(chooser, chooser.buttons().first())
.setFocusable(true).setRequestFocus(true)
.setMovable(false).setResizable(false)
.setTitle(title).createPopup()
.also { popupState.prepareToShow(it) }
.showInBestPositionFor(event.dataContext)
}
init {
isEnabledInModalContext = true
}
}
| apache-2.0 | 1771a6e5f3269c76d521a00f0aa26272 | 45.55102 | 158 | 0.766331 | 4.67418 | false | false | false | false |
TimePath/launcher | src/main/kotlin/com/timepath/launcher/ui/web/WebHandler.kt | 1 | 6129 | package com.timepath.launcher.ui.web
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpHandler
import com.timepath.XMLUtils
import com.timepath.launcher.Launcher
import com.timepath.launcher.LauncherUtils
import com.timepath.util.Cache
import java.io.*
import java.net.HttpURLConnection
import java.net.URL
import java.util.Arrays
import java.util.Timer
import java.util.TimerTask
import java.util.logging.Level
import java.util.logging.Logger
import javax.xml.parsers.ParserConfigurationException
import javax.xml.transform.TransformerException
import javax.xml.transform.stream.StreamSource
class WebHandler(private val launcher: Launcher) : HttpHandler {
/**
* Current working directory
*/
private val cwd: URL?
/**
* Current working package
*/
private val cwp: String
private val cache = object : Cache<String, Page>() {
override fun fill(key: String): Page? {
if ("/" == key || "/raw" == key) {
try {
val future = System.currentTimeMillis() + (EXPIRES_INDEX * 1000).toLong()
val source = Converter.serialize(launcher.getRepositories())
val index = Converter.transform(StreamSource(getStream("/projects.xsl")), source)
val indexPage = Page(index, future)
this.put("/", indexPage)
val raw = XMLUtils.pprint(source, 4)
val rawPage = Page(raw, future)
this.put("/raw", rawPage)
return if ("/" == key) indexPage else rawPage
} catch (ex: TransformerException) {
LOG.log(Level.SEVERE, null, ex)
} catch (ex: ParserConfigurationException) {
LOG.log(Level.SEVERE, null, ex)
} catch (ex: IOException) {
LOG.log(Level.SEVERE, null, ex)
}
}
try {
val future = System.currentTimeMillis() + (EXPIRES_ALL * 1000).toLong()
val s = key.substring(1)
var `is`: InputStream? = javaClass.getResourceAsStream(cwp + s)
if (cwd != null) `is` = URL("${cwd}${s}").openStream()
if (`is` == null) throw FileNotFoundException("File not found: $key")
val data = read(`is`)
return Page(data, future)
} catch (ignored: FileNotFoundException) {
} catch (e: IOException) {
LOG.log(Level.WARNING, null, e)
}
return null
}
override fun expire(key: String, value: Page?): Page? {
return if ((LauncherUtils.DEBUG || (value != null && value.expired()))) null else value
}
}
init {
cwd = javaClass<Server>().getResource("")
cwp = ("/${javaClass.getPackage().getName().replace('.', '/')}/")
LOG.log(Level.INFO, "cwd: {0}", cwd)
LOG.log(Level.INFO, "cwp: {0}", cwp)
val task = object : TimerTask() {
override fun run() {
cache["/"]
}
}
task.run() // Ensure synchronous first call
val period = (EXPIRES_INDEX * 1000).toLong()
Timer("page-rebuild-timer", true).scheduleAtFixedRate(task, period, period)
}
private fun getStream(request: String): InputStream? {
val page = cache[request]
if (page == null) return null
return BufferedInputStream(ByteArrayInputStream(page.data))
}
override fun handle(exchange: HttpExchange) {
LOG.log(Level.INFO, "{0} {1}: {2}", arrayOf<Any>(exchange.getProtocol(), exchange.getRequestMethod(), exchange.getRequestURI()))
LOG.log(Level.FINE, "{0}", Arrays.toString(exchange.getRequestHeaders().entrySet().toTypedArray()))
if (LOG.isLoggable(Level.FINE)) {
LOG.fine(Arrays.toString(exchange.getRequestHeaders().entrySet().toTypedArray()))
}
val request = exchange.getRequestURI().toString()
if (ProxyHandler.checkProxy(exchange, request)) return
val page = cache[exchange.getRequestURI().toString()]
if (page == null) {
exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND, 0)
return
}
val headers = exchange.getResponseHeaders()
if ("/" == request) {
headers.set("Cache-Control", "max-age=$EXPIRES_INDEX")
} else {
headers.set("Cache-Control", "max-age=$EXPIRES_ALL")
}
if (request.endsWith(".css")) {
headers.set("Content-type", "text/css")
} else if (request.endsWith(".js")) {
headers.set("Content-type", "text/javascript")
} else {
headers.set("Content-type", "text/html")
}
exchange.getResponseBody().use { os ->
val bytes = page.data
if (bytes != null) {
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, bytes.size().toLong())
os.write(bytes)
}
}
}
companion object {
private val EXPIRES_ALL = 60 * 60 // Hour
private val EXPIRES_INDEX = if (LauncherUtils.DEBUG) 1 else 10
private val LOG = Logger.getLogger(javaClass<WebHandler>().getName())
/**
* Reads an InputStream to a byte array
*
* @param input The stream to read from
* @return The bytes read
* @throws IOException
*/
private fun read(input: InputStream): ByteArray {
@suppress("NAME_SHADOWING")
val input = input.buffered()
val baos = ByteArrayOutputStream(input.available())
input.copyTo(baos)
return baos.toByteArray()
}
private fun Page(data: String, expires: Long): Page {
return Page(data.toByteArray(), expires)
}
private class Page(var data: ByteArray?, var expires: Long) {
fun expired(): Boolean {
return System.currentTimeMillis() >= expires
}
}
}
}
| artistic-2.0 | 6e345502cfcc74d664191df064d5d84f | 36.371951 | 136 | 0.568282 | 4.556877 | false | false | false | false |
AlexKrupa/kotlin-koans | src/syntax/ifWhenExpressions.kt | 1 | 741 | package syntax.ifWhenExpressions
fun ifExpression(a: Int, b: Int) {
val max1 = if (a > b) a else b
val max2 = if (a > b) {
println("Choose a")
a
}
else {
println("Choose b")
b
}
}
fun whenExpression(a: Any?) {
val result = when (a) {
null -> "null"
is String -> "String"
is Any -> "Any"
else -> "Don't know"
}
}
fun whenExpression(x: Int) {
when (x) {
0, 11 -> "0 or 11"
in 1..10 -> "from 1 tail 10"
!in 12..14 -> "not from 12 tail 14"
else -> "otherwise"
}
}
fun whenWithoutArgument(x: Int) {
when {
x == 42 -> "x is 42"
x % 2 == 1 -> "x is odd"
else -> "otherwise"
}
}
| mit | c9da082ac6e60eb86c7aea4d961998da | 17.073171 | 43 | 0.453441 | 3.193966 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/projectModel-api/src/com/intellij/openapi/components/BaseState.kt | 2 | 6744 | /*
* Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.openapi.components
import com.intellij.configurationStore.properties.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.ModificationTracker
import com.intellij.util.SmartList
import com.intellij.util.xmlb.Accessor
import com.intellij.util.xmlb.PropertyAccessor
import com.intellij.util.xmlb.SerializationFilter
import com.intellij.util.xmlb.annotations.Transient
import gnu.trove.THashMap
import java.nio.charset.Charset
import java.util.concurrent.atomic.AtomicLongFieldUpdater
private val LOG = logger<BaseState>()
abstract class BaseState : SerializationFilter, ModificationTracker {
companion object {
private val MOD_COUNT_UPDATER = AtomicLongFieldUpdater.newUpdater(BaseState::class.java, "ownModificationCount")
}
private val properties: MutableList<StoredProperty> = SmartList()
@Volatile
@Transient
private var ownModificationCount: Long = 0
fun <T> property(): StoredPropertyBase<T?> {
val result = ObjectStoredProperty<T?>(null)
properties.add(result)
return result
}
/**
* Value considered as default only if all properties have default values.
* Passed instance is not used for `isDefault` check. It is just an initial value.
*/
fun <T : BaseState?> property(initialValue: T): StoredPropertyBase<T> {
val result = StateObjectStoredProperty(initialValue)
properties.add(result)
return result
}
/**
* For non-BaseState classes explicit `isDefault` must be provided, because no other way to check.
*/
fun <T> property(initialValue: T, isDefault: (value: T) -> Boolean): StoredPropertyBase<T> {
val result = object : ObjectStoredProperty<T>(initialValue) {
override fun isEqualToDefault() = isDefault(value)
}
properties.add(result)
return result
}
/**
* Collection considered as default if empty. It is *your* responsibility to call `incrementModificationCount` on collection modification.
* You cannot set value to a new collection - on set current collection is cleared and new collection is added to current.
*/
fun <E, C : MutableCollection<E>> property(initialValue: C): StoredPropertyBase<C> {
val result = CollectionStoredProperty(initialValue)
properties.add(result)
return result
}
/**
* Charset is an immutable, so, it is safe to use it as default value.
*/
fun <T : Charset> property(initialValue: T): StoredPropertyBase<T> {
val result = ObjectStoredProperty(initialValue)
properties.add(result)
return result
}
/**
* Enum is an immutable, so, it is safe to use it as default value.
*/
fun <T : Enum<*>> property(defaultValue: T): StoredPropertyBase<T> {
val result = ObjectStoredProperty(defaultValue)
properties.add(result)
return result
}
/**
* Not-null list. Initialized as SmartList.
*/
fun <T : Any> list(): StoredPropertyBase<MutableList<T>> {
val result = ListStoredProperty<T>()
properties.add(result)
@Suppress("UNCHECKED_CAST")
return result as StoredPropertyBase<MutableList<T>>
}
fun <K : Any, V: Any> property(value: MutableMap<K, V>): StoredPropertyBase<MutableMap<K, V>> {
return map(value)
}
fun <K : Any, V: Any> map(value: MutableMap<K, V> = THashMap()): StoredPropertyBase<MutableMap<K, V>> {
val result = MapStoredProperty(value)
properties.add(result)
return result
}
/**
* Empty string is always normalized to null.
*/
fun property(defaultValue: String?) = string(defaultValue)
/**
* Empty string is always normalized to null.
*/
fun string(defaultValue: String? = null): StoredPropertyBase<String?> {
val result = NormalizedStringStoredProperty(defaultValue)
properties.add(result)
return result
}
fun property(defaultValue: Int = 0): StoredPropertyBase<Int> {
val result = IntStoredProperty(defaultValue, null)
properties.add(result)
return result
}
fun property(defaultValue: Long = 0): StoredPropertyBase<Long> {
val result = LongStoredProperty(defaultValue, null)
properties.add(result)
return result
}
fun property(defaultValue: Float = 0f, valueNormalizer: ((value: Float) -> Float)? = null): StoredPropertyBase<Float> {
val result = FloatStoredProperty(defaultValue, valueNormalizer)
properties.add(result)
return result
}
fun property(defaultValue: Boolean = false): StoredPropertyBase<Boolean> {
val result = ObjectStoredProperty(defaultValue)
properties.add(result)
return result
}
// reset on load state
fun resetModificationCount() {
ownModificationCount = 0
}
protected fun incrementModificationCount() {
intIncrementModificationCount()
}
internal fun intIncrementModificationCount() {
MOD_COUNT_UPDATER.incrementAndGet(this)
}
override fun accepts(accessor: Accessor, bean: Any): Boolean {
val getterName = (accessor as? PropertyAccessor)?.getterName
for (property in properties) {
if (property.name == accessor.name || property.name == getterName) {
return !property.isEqualToDefault()
}
}
LOG.debug("Cannot find property by name: ${accessor.name}")
// do not return false - maybe accessor delegates actual set to our property
// default value in this case will be filtered by common filter (instance will be created in this case, as for non-smart state classes)
return true
}
internal fun isEqualToDefault() = properties.all { it.isEqualToDefault() }
@Transient
override fun getModificationCount(): Long {
var result = ownModificationCount
for (property in properties) {
result += property.getModificationCount()
}
return result
}
override fun equals(other: Any?) = this === other || (other is BaseState && properties == other.properties)
override fun hashCode() = properties.hashCode()
override fun toString(): String {
if (properties.isEmpty()) {
return ""
}
val builder = StringBuilder()
for (property in properties) {
builder.append(property.toString()).append(" ")
}
builder.setLength(builder.length - 1)
return builder.toString()
}
fun copyFrom(state: BaseState) {
LOG.assertTrue(state.properties.size == properties.size)
var changed = false
for ((index, property) in properties.withIndex()) {
val otherProperty = state.properties.get(index)
LOG.assertTrue(otherProperty.name == property.name)
if (property.setValue(otherProperty)) {
changed = true
}
}
if (changed) {
incrementModificationCount()
}
}
}
| apache-2.0 | 62dd00e6fa42b41cba98b4c9e7c37699 | 30.367442 | 140 | 0.707592 | 4.466225 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/execute/models/ExecutionParams.kt | 1 | 619 | package ch.rmy.android.http_shortcuts.activities.execute.models
import android.net.Uri
import ch.rmy.android.http_shortcuts.data.domains.pending_executions.ExecutionId
import ch.rmy.android.http_shortcuts.data.domains.shortcuts.ShortcutId
import ch.rmy.android.http_shortcuts.data.domains.variables.VariableKey
data class ExecutionParams(
val shortcutId: ShortcutId,
val variableValues: Map<VariableKey, String> = emptyMap(),
val executionId: ExecutionId? = null,
val tryNumber: Int = 0,
val recursionDepth: Int = 0,
val fileUris: List<Uri> = emptyList(),
val isNested: Boolean = false,
)
| mit | 9ee7f22cafefef050600854752c9e6aa | 37.6875 | 80 | 0.767367 | 3.893082 | false | false | false | false |
h31/LibraryMigration | src/main/kotlin/ru/spbstu/kspt/librarymigration/parser/parser.kt | 1 | 3559 | package ru.spbstu.kspt.librarymigration.parser
import org.antlr.v4.runtime.CharStreams
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.ParserRuleContext
import ru.spbstu.kspt.librarymigration.modelreader.LibraryModelBaseVisitor
import ru.spbstu.kspt.librarymigration.modelreader.LibraryModelLexer
import ru.spbstu.kspt.librarymigration.modelreader.LibraryModelParser
import ru.spbstu.kspt.librarymigration.prettyPrinter
import java.io.InputStream
/**
* Created by artyom on 13.07.17.
*/
class ModelParser {
fun parse(stream: InputStream): LibraryDecl {
val charStream = CharStreams.fromStream(stream)
val lexer = LibraryModelLexer(charStream)
val tokenStream = CommonTokenStream(lexer)
val parser = LibraryModelParser(tokenStream)
val start = parser.start()
return LibraryModelReader().visitStart(start)
}
fun postprocess(libraryDecl: LibraryDecl) = Postprocessor().process(libraryDecl)
}
class LibraryModelReader : LibraryModelBaseVisitor<Node>() {
override fun visitStart(ctx: LibraryModelParser.StartContext): LibraryDecl {
val libraryName = ctx.libraryName().Identifier().text
val desc = ctx.description()
val automata = desc.automatonDescription().map { visitAutomatonDescription(it) }
val typeList = desc.typesSection().single().typeDecl().map { visitTypeDecl(it) }
val converters = desc.convertersSection().single().converter().map { visitConverter(it) }
val functions = desc.funDecl().map { visitFunDecl(it) }
return LibraryDecl(name = libraryName, automata = automata, types = typeList,
converters = converters, functions = functions)
}
override fun visitAutomatonDescription(ctx: LibraryModelParser.AutomatonDescriptionContext): Automaton {
val states = ctx.stateDecl().map { visitStateDecl(it) }
val shifts = ctx.shiftDecl().map { visitShiftDecl(it) }
return Automaton(name = ctx.automatonName().text, states = states, shifts = shifts)
}
override fun visitTypeDecl(ctx: LibraryModelParser.TypeDeclContext): Type =
Type(semanticType = ctx.semanticType().text, codeType = ctx.codeType().text)
override fun visitStateDecl(ctx: LibraryModelParser.StateDeclContext): StateDecl =
StateDecl(name = ctx.stateName().text)
override fun visitShiftDecl(ctx: LibraryModelParser.ShiftDeclContext): ShiftDecl =
ShiftDecl(from = ctx.srcState().text, to = ctx.dstState().text,
functions = ctx.funName().map { it.text })
override fun visitConverter(ctx: LibraryModelParser.ConverterContext): Converter =
Converter(entity = ctx.destEntity().text, expression = ctx.converterExpression().text)
override fun visitFunDecl(ctx: LibraryModelParser.FunDeclContext): FunctionDecl {
val args = ctx.funArgs().funArg().map { visitFunArg(it) }
val actions = ctx.funProperties().map { visit(it) }.filterIsInstance<ActionDecl>()
return FunctionDecl(entity = ctx.entityName().text, name = ctx.funName().text,
args = args, actions = actions)
}
override fun visitActionDecl(ctx: LibraryModelParser.ActionDeclContext): Node {
return ActionDecl(name = ctx.actionName().text, args = ctx.Identifier().map { it.text })
}
override fun visitFunArg(ctx: LibraryModelParser.FunArgContext): FunctionArgument =
FunctionArgument(name = ctx.argName().text, type = ctx.argType().text)
}
fun main(args: Array<String>) {
} | mit | a397989bf9411fc5f229dd2d40f5f407 | 45.842105 | 108 | 0.715369 | 4.138372 | false | false | false | false |
quran/quran_android | common/recitation/src/main/java/com/quran/recitation/events/RecitationPlaybackEventPresenter.kt | 2 | 1129 | package com.quran.recitation.events
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class RecitationPlaybackEventPresenter @Inject constructor() {
private val _loadedRecitationFlow = MutableStateFlow<String?>(null)
private val _playingStateFlow = MutableStateFlow<Boolean>(false)
private val _playbackPositionFlow = MutableStateFlow<Int>(0)
val loadedRecitationFlow: StateFlow<String?> = _loadedRecitationFlow.asStateFlow()
val playingStateFlow: StateFlow<Boolean> = _playingStateFlow.asStateFlow()
val playbackPositionFlow: StateFlow<Int> = _playbackPositionFlow.asStateFlow()
fun isPlaying(): Boolean = playingStateFlow.value
fun onLoadedRecitationChange(loadedRecitation: String?) {
_loadedRecitationFlow.value = loadedRecitation
}
fun onPlayingStateChange(playingState: Boolean) {
_playingStateFlow.value = playingState
}
fun onPlaybackPositionChange(playbackPosition: Int) {
_playbackPositionFlow.value = playbackPosition
}
}
| gpl-3.0 | 0a4de41204e3a2789622ef376ab00f63 | 33.212121 | 84 | 0.805137 | 4.723849 | false | false | false | false |
hazuki0x0/YuzuBrowser | module/adblock/src/main/java/jp/hazuki/yuzubrowser/adblock/Notifications.kt | 1 | 1441 | /*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.adblock
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
const val NOTIFICATION_CHANNEL_ADBLOCK_FILTER_UPDATE = "jp.hazuki.yuzubrowser.channel.abp.update"
fun Context.registerAdBlockNotification() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val service = NotificationChannel(
NOTIFICATION_CHANNEL_ADBLOCK_FILTER_UPDATE,
getString(R.string.updating_ad_filters),
NotificationManager.IMPORTANCE_MIN)
service.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
manager.createNotificationChannels(listOf(service))
}
}
| apache-2.0 | e2b02d5c0adc80497fe97c1550ff2110 | 34.146341 | 97 | 0.750173 | 4.420245 | false | false | false | false |
kangsLee/sh8email-kotlin | app/src/main/kotlin/org/triplepy/sh8email/sh8/activities/login/di/LoginComponent.kt | 1 | 459 | package org.triplepy.sh8email.sh8.activities.login.di
import dagger.Component
import org.triplepy.sh8email.sh8.activities.login.LoginActivity
/**
* The sh8email-android Project.
* ==============================
* org.triplepy.sh8email.sh8.activities.login.di
* ==============================
* Created by igangsan on 2016. 9. 3..
*/
@Component(modules = arrayOf(LoginModule::class))
interface LoginComponent {
fun inject(activity: LoginActivity)
} | apache-2.0 | ffcb5b47f88388064be60b515e8da44e | 27.75 | 63 | 0.662309 | 3.614173 | false | false | false | false |
wiryls/HomeworkCollectionOfMYLS | 2017.AndroidApplicationDevelopment/ODES/app/src/main/java/com/myls/odes/fragment/DormFrisFragment.kt | 1 | 8543 | package com.myls.odes.fragment
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.myls.odes.R
import com.myls.odes.activity.MainActivity
import com.myls.odes.application.AnApplication
import com.myls.odes.data.UserList
import com.myls.odes.utility.Storage
import kotlinx.android.synthetic.main.fragment_dorm_fris.*
import kotlinx.android.synthetic.main.item_friend_card.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*
/**
* A simple [Fragment] subclass.
*/
class DormFrisFragment : Fragment()
{
private var holder: Holder? = null
private lateinit var saver: Storage
private lateinit var userl: UserList
private lateinit var user : UserList.User
override fun onCreateView
(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)
= inflater.inflate(R.layout.fragment_dorm_fris, container, false)!!
override fun onActivityCreated(savedInstanceState: Bundle?)
= super.onActivityCreated(savedInstanceState).also {
(activity.application as AnApplication).let {
saver = it.saver
userl = it.userlist
user = userl.list.firstOrNull()
?: return@let post(MainActivity.InvalidDataEvent("UserList is empty"))
}
with(recycler) {
adapter = FriendsRecyclerAdapter(user.dorm.fris)
layoutManager = LinearLayoutManager([email protected])
adapter = FriendsRecyclerAdapter(user.dorm.fris).apply {
onItemMovingListener = { _, _, _ ->
saver.put(userl)
}
onItemSwipingListener = { item, i ->
holder
?.snb
?.setAction(R.string.desc_undo, {
user.dorm.fris.add(i, item)
notifyItemInserted(i)
onUpdateFloatingActionButton()
})
?.show()
}
onItemSwipedListener = { item, i ->
onUpdateFloatingActionButton()
saver.put(userl)
}
onItemClickListener = { _, i ->
val args = Bundle().also {
it.putInt(DormFrisEditFragment.Contract.INDEX.name, i)
}
holder?.listener?.onReceiveFragmentAttribute(FragmentAttribute.DORM_FRED, args)
}
} .also {
ItemTouchHelper(it.ItemTouchCallback()).attachToRecyclerView(this)
}
}
}
private fun onUpdateFloatingActionButton() {
holder?.run { user.dorm.fris.let {
with(fab) {
if (it.size >= 3)
hide()
else
show()
}
with(snb) {
if (it.size >= 3)
dismiss()
}
}}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
holder = Holder(listener = context as? FragmentInteraction
?: throw RuntimeException("$context must implement ${FragmentInteraction::class.java.simpleName}"))
}
override fun onStart() {
super.onStart()
EVENT_BUS.register(this)
}
override fun onResume() {
super.onResume()
holder?.onResume()
onUpdateFloatingActionButton()
holder?.fab?.run {
setOnClickListener {
if (user.dorm.fris.size < 3)
holder?.listener?.onReceiveFragmentAttribute(FragmentAttribute.DORM_FRED)
}
}
}
override fun onPause() {
holder?.onPause()
super.onPause()
holder?.fab?.run {
setOnClickListener(null)
}
}
override fun onStop() {
EVENT_BUS.unregister(this)
super.onStop()
}
override fun onDetach() {
holder = null
super.onDetach()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onFriendEditedEvent(event: FriendEditedEvent) {
with(recycler) {
adapter.notifyDataSetChanged()
onUpdateFloatingActionButton()
}
}
data class FriendEditedEvent(val index: Int, val friend: UserList.Dorm.Friend)
private class FriendsRecyclerAdapter(private val items: MutableList<UserList.Dorm.Friend>)
: RecyclerView.Adapter<FriendsRecyclerAdapter.ViewHolder>()
{
var onItemMovingListener: ((UserList.Dorm.Friend, Int, Int) -> Unit)? = null
var onItemSwipingListener: ((UserList.Dorm.Friend, Int) -> Unit)? = null
var onItemSwipedListener: ((UserList.Dorm.Friend, Int) -> Unit)? = null
var onItemClickListener: ((UserList.Dorm.Friend, Int) -> Unit)? = null
override fun getItemCount() = items.size
override fun onCreateViewHolder(parent : ViewGroup, viewType: Int) =
ViewHolder(LayoutInflater
.from(parent.context)
.inflate(R.layout.item_friend_card, parent, false)!!)
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = items[position]
with(holder) {
stid.text = item.stid
code.text = item.code
cardview.setOnClickListener {
onItemClickListener?.invoke(items[adapterPosition], adapterPosition)
}
}
}
private fun onItemMove(src: Int, dst: Int) = true.also {
val item = items[src]
onItemMovingListener?.invoke(item, src, dst)
(minOf(src, dst)..maxOf(src, dst)).run {
if (src < dst) reversed()
else this
}.forEach {
Collections.swap(items, it, dst)
}
notifyItemMoved(src, dst)
}
private fun onItemSwiped(pos: Int) {
val item = items[pos]
onItemSwipingListener?.invoke(item, pos)
items.removeAt(pos)
notifyItemRemoved(pos)
onItemSwipedListener?.invoke(item, pos)
}
class ViewHolder(val cardview: View) : RecyclerView.ViewHolder(cardview) {
val stid = cardview.item_stid!!
val code = cardview.item_code!!
}
inner class ItemTouchCallback : ItemTouchHelper.Callback()
{
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) =
ItemTouchHelper.Callback.makeMovementFlags(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
ItemTouchHelper.START or ItemTouchHelper.END)
override fun onMove(view: RecyclerView, src: RecyclerView.ViewHolder, dst: RecyclerView.ViewHolder) =
(src.itemViewType == dst.itemViewType) && onItemMove(src.adapterPosition, dst.adapterPosition)
override fun onSwiped(holder: RecyclerView.ViewHolder, i: Int) {
onItemSwiped(holder.adapterPosition)
}
}
}
private class Holder(val listener: FragmentInteraction) {
val fml = listener.requireFrameLayout()
val snb = Snackbar.make(fml, R.string.desc_action_delete, Snackbar.LENGTH_INDEFINITE)
val fab = listener.requireFloatingActionButton()
fun onResume() {
with(fab) {
setImageResource(R.drawable.ic_add_white)
show()
}
}
fun onPause() {
with(snb) {
dismiss()
}
with(fab) {
hide()
setImageDrawable(null)
setOnClickListener(null)
isClickable = false
}
}
}
companion object {
private val TAG = DormFrisFragment::class.java.canonicalName!!
private val EVENT_BUS = EventBus.getDefault()
private fun <T> post(data: T) = EVENT_BUS.post(data)
fun create() = DormFrisFragment()
}
}
| mit | ad1237b0a9481615840f6bb7d9f69956 | 32.371094 | 116 | 0.579422 | 4.8873 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/newdata/SourceFile.kt | 1 | 7304 | package newdata
import Main
import com.github.javaparser.JavaParser
import com.github.javaparser.ast.CompilationUnit
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration
import com.github.javaparser.ast.body.ConstructorDeclaration
import com.github.javaparser.ast.body.MethodDeclaration
import com.github.javaparser.ast.body.VariableDeclarator
import common.Stopwords
import nlp.PreProcessor.Companion.regCamelCase
import nlp.PreProcessor.Companion.regHtml
import nlp.PreProcessor.Companion.regNonAlphanum
import org.tartarus.snowball.ext.englishStemmer
import tfidfDoc
import java.io.File
class SourceAnalyst(val file:File)
{
val sourceFile = SourceFile(file.path)
var parser:CompilationUnit
val stemmer = englishStemmer()
init {
parser = JavaParser.parse(file)
}
fun analysis()
{
extractClassOrInterface()
extractImports()
extractMethods()
}
fun extractImports()
{
parser.imports.forEach {
it.nameAsString.preprocessing().forEach {
sourceFile.imports.put(it)
}
}
}
fun extractMethods()
{
parser.findAll(MethodDeclaration::class.java).forEach {
//method comment
if(it.comment.isPresent)
it.comment.get().toString().preprocessing().forEach {
sourceFile.commentsMethod.put(it)
}
it.nameAsString.preprocessing().forEach {
sourceFile.nameMethod.put(it)
}
it.type.toString().preprocessing().forEach {
sourceFile.typeMethod.put(it)
}
//method parameter
it.parameters.forEach {
it.nameAsString.preprocessing().forEach {
sourceFile.nameParameter.put(it)
}
it.type.toString().preprocessing().forEach {
sourceFile.typeParameter.put(it)
}
}
// local variable
it.findAll(VariableDeclarator::class.java).forEach {
if(it.comment.isPresent)
it.comment.get().toString().preprocessing().forEach {
sourceFile.commentsVariable.put(it)
}
it.nameAsString.preprocessing().forEach {
sourceFile.nameVariable.put(it)
}
it.type.toString().preprocessing().forEach {
sourceFile.typeVariable.put(it)
}
}
}
}
fun extractClassOrInterface()
{
parser.findAll(ClassOrInterfaceDeclaration::class.java).forEach {
if(it.comment.isPresent)
it.comment.get().toString().preprocessing().forEach {
sourceFile.commentsClassOrInterface.put(it)
}
it.nameAsString.preprocessing().forEach {
sourceFile.nameClassOrInterface.put(it)
}
//constructor
it.findAll(ConstructorDeclaration::class.java).forEach {
if(it.comment.isPresent)
it.comment.get().toString().preprocessing().forEach {
sourceFile.commentsClassOrInterface.put(it)
}
it.nameAsString.preprocessing().forEach {
sourceFile.nameClassOrInterface.put(it)
}
it.parameters.forEach {
it.nameAsString.preprocessing().forEach {
sourceFile.nameParameter.put(it)
}
it.type.toString().preprocessing().forEach {
sourceFile.typeParameter.put(it)
}
}
}
// fields
it.findAll(VariableDeclarator::class.java).forEach {
if(it.comment.isPresent)
it.comment.get().toString().preprocessing().forEach {
sourceFile.commentsVariable.put(it)
}
it.nameAsString.preprocessing().forEach {
sourceFile.nameVariable.put(it)
}
it.type.toString().preprocessing().forEach {
sourceFile.typeVariable.put(it)
}
}
}
}
fun String.preprocessing() : List<String>
{
var str = regCamelCase.replace(this," ")
str = regHtml.replace(str, "")
str = com.sun.deploy.util.StringUtils.trimWhitespace(str)
return regNonAlphanum.split(str.toLowerCase()).filter { it.length > 2 && it.length < 20 && !Stopwords.instance.contains(it.toLowerCase()) }.map {
stemmer.setCurrent(it)
stemmer.stem()
stemmer.current
}
}
}
class SourceFileNode(source:SourceFile)
{
lateinit var weightMap : HashMap<String, Double>
init {
}
}
data class SourceFile (
val path:String,
val imports:CountMap = CountMap(),
val commentsClassOrInterface:CountMap = CountMap(),
val commentsMethod:CountMap = CountMap(),
val commentsVariable:CountMap = CountMap(),
val typeMethod:CountMap = CountMap(),
val typeVariable:CountMap = CountMap(),
val typeParameter:CountMap = CountMap(),
val nameClassOrInterface:CountMap = CountMap(),
val nameMethod:CountMap = CountMap(),
val nameVariable:CountMap = CountMap(),
val nameParameter:CountMap = CountMap()
)
{
fun mergeMap() : HashMap<String, Int>
{
val result : HashMap<String, Int> = hashMapOf()
excuteAll { result.increase(it) }
return result;
}
fun tfIdfMap() : HashMap<String, Double>
{
return mergeMap().tfidfDoc(Main.DF_MAP)
}
fun excuteAll(qux : (Map.Entry<String,Int>) -> Unit)
{
// imports.forEach(qux)
// commentsClassOrInterface.forEach(qux)
// commentsVariable.forEach(qux)
commentsMethod.forEach(qux)
// typeVariable.forEach(qux)
// typeParameter.forEach(qux)
typeMethod.forEach(qux)
nameMethod.forEach(qux)
// nameClassOrInterface.forEach(qux)
// nameParameter.forEach(qux)
// nameVariable.forEach(qux)
}
fun HashMap<String, Int>.increase(entry:Map.Entry<String, Int>) {
if (containsKey(entry.key))
set(entry.key, get(entry.key)!! + entry.value)
else
put(entry.key, entry.value)
}
fun getAllWords() : HashSet<String>
{
val set : HashSet<String> = hashSetOf()
set.addAll(imports.keys)
set.addAll(commentsClassOrInterface.keys)
set.addAll(commentsMethod.keys)
set.addAll(commentsVariable.keys)
set.addAll(typeMethod.keys)
set.addAll(typeVariable.keys)
set.addAll(typeParameter.keys)
set.addAll(nameClassOrInterface.keys)
set.addAll(nameMethod.keys)
set.addAll(nameMethod.keys)
set.addAll(nameParameter.keys)
return set
}
}
class CountMap : HashMap<String, Int>()
{
fun put(key:String)
{
if(containsKey(key))
set(key, get(key)!! + 1)
else
put(key, 1)
}
}
| apache-2.0 | faf5b04b653e1570a470ae97ee587d8b | 28.451613 | 153 | 0.5727 | 4.582183 | false | false | false | false |
guyca/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/TextChangeAnimator.kt | 1 | 1741 | package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.graphics.Rect
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.facebook.react.views.text.ReactTextView
import com.reactnativenavigation.parse.SharedElementTransitionOptions
import com.reactnativenavigation.utils.*
import com.shazam.android.widget.text.reflow.ReflowTextAnimatorHelper
class TextChangeAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactTextView>(from, to) {
override fun shouldAnimateProperty(fromChild: ReactTextView, toChild: ReactTextView): Boolean {
val fromXy = ViewUtils.getLocationOnScreen(from)
val toXy = ViewUtils.getLocationOnScreen(to)
return TextViewUtils.getTextSize(fromChild) != TextViewUtils.getTextSize(toChild) ||
!fromXy.equals(toXy.x, toXy.y)
}
override fun create(options: SharedElementTransitionOptions): Animator {
return ReflowTextAnimatorHelper.Builder(from as TextView, to as TextView)
.calculateDuration(false)
.setBoundsCalculator { view: View ->
val loc = IntArray(2)
view.getLocationInWindow(loc)
val x = loc[0]
val y = if (view == to) (to.layoutParams as ViewGroup.MarginLayoutParams).topMargin else loc[1]
Rect(
x,
y,
x + view.width,
y + view.height
)
}
.setTextColorGetter {
TextViewUtils.getTextColor(it)
}.buildAnimator()
}
} | mit | a32bdf0e60cd6ba82d5180dc93772e6c | 42.55 | 115 | 0.630098 | 4.988539 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/bean/Playlist.kt | 1 | 1857 | package tech.summerly.quiet.bean
import android.annotation.SuppressLint
import android.net.Uri
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import tech.summerly.quiet.module.common.bean.Music
import tech.summerly.quiet.module.common.bean.MusicType
import java.io.File
import java.io.Serializable
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/26
* desc :
*/
@SuppressLint("ParcelCreator")
@Suppress("unused")
@Parcelize
data class Playlist(
val id: Long,
val name: String,
var coverImageUrl: String?,
val musics: List<Music>,
val type: MusicType
) : Serializable, Parcelable {
val coverImageModel: Any
get() {
return coverImageUrl.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Playlist) return false
if (this.id != other.id) return false
if (this.type != other.type) return false
//check UPDATE TIME instead compare the all musics list?
if (this.musics != other.musics) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + (coverImageUrl?.hashCode() ?: 0)
result = 31 * result + musics.hashCode()
result = 31 * result + type.hashCode()
return result
}
override fun toString(): String {
return "Playlist(id=$id, title='$name',\n coverImageUrl=$coverImageUrl, \n musics=$musics, \n type=$type)"
}
fun imageUrlString(): String? {
return coverImageUrl?.let {
if (it.startsWith("http")) {
it
} else {
Uri.fromFile(File(it)).toString()
}
}
}
} | gpl-2.0 | f53bebaf606b3be53738797d3494e1a6 | 25.927536 | 114 | 0.610124 | 4.135857 | false | false | false | false |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/views/timeline/widgets/timegraph/toolbar/debugopts/DebugOptionsDialog.kt | 2 | 8643 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.views.timeline.widgets.timegraph.toolbar.debugopts
import com.efficios.jabberwocky.common.ConfigOption
import javafx.event.ActionEvent
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.control.*
import javafx.scene.control.ButtonBar.ButtonData
import javafx.scene.layout.HBox
import javafx.scene.layout.VBox
import javafx.scene.paint.Color
/**
* Dialog to configure the debug options at runtime.
*/
class DebugOptionsDialog(button: DebugOptionsButton) : Dialog<Unit>() {
companion object {
private val PADDING = Insets(20.0)
private const val SPACING = 10.0
}
private val opts = button.debugOptions
private val tabPane = TabPane(createGeneralTab(),
createLoadingOverlayTab(),
createZoomTab(),
createStateIntervalsTab(),
createTooltipTab())
init {
title = Messages.debugOptionsDialogTitle
headerText = Messages.debugOptionsDialogName
val resetToDefaultButtonType = ButtonType(Messages.resetDefaultsButtonLabel, ButtonData.LEFT)
dialogPane.buttonTypes.addAll(resetToDefaultButtonType, ButtonType.CANCEL, ButtonType.OK)
dialogPane.content = tabPane
/*
* Restore the last-selected tab (that state is saved in the button),
* and re-bind on the new dialog so that the property continues getting
* updated.
*/
tabPane.selectionModel.select(button.lastSelectedTabProperty.get())
button.lastSelectedTabProperty.bind(tabPane.selectionModel.selectedIndexProperty())
/* What to do when the dialog is closed */
setResultConverter { dialogButton ->
if (dialogButton != ButtonType.OK) return@setResultConverter
/*
* Set the debug options according to the current contents of the
* dialog.
*/
allPropertySetters.forEach(PropertySetter::save)
}
/* Define how to "Reset Defaults" button works */
dialogPane.lookupButton(resetToDefaultButtonType).addEventFilter(ActionEvent.ACTION) { e ->
/*
* This button should not close the dialog. Consuming the event here
* will prevent the dialog from closing.
*/
e.consume()
allPropertySetters.forEach {
it.option.resetToDefault()
it.load()
}
}
}
private val allPropertySetters: List<PropertySetter>
get() = tabPane.tabs
.flatMap { tab -> (tab.content as VBox).children }
.map { it as PropertySetter }
// ------------------------------------------------------------------------
// Tab classes
// ------------------------------------------------------------------------
private class DebugOptionsDialogTab(name: String?, vararg contents: Node) : Tab() {
init {
isClosable = false
text = name
VBox(*contents)
.apply {
padding = PADDING
spacing = SPACING
}
.let { content = it }
}
}
private fun createGeneralTab(): Tab =
DebugOptionsDialogTab(Messages.tabNameGeneral,
CheckBoxControl(Messages.controlPaintingEnabled, opts.isPaintingEnabled),
IntegerTextField(Messages.controlEntryPadding, opts.entryPadding),
DoubleTextField(Messages.controlRenderRangePadding, opts.renderRangePadding),
IntegerTextField(Messages.controlUIUpdateDelay, opts.uiUpdateDelay),
CheckBoxControl(Messages.controlHScrollEnabled, opts.isScrollingListenersEnabled))
private fun createLoadingOverlayTab(): Tab =
DebugOptionsDialogTab(Messages.tabNameLoadingOverlay,
CheckBoxControl(Messages.controlLoadingOverlayEnabled, opts.isLoadingOverlayEnabled),
ColorControl(Messages.controlLoadingOverlayColor, opts.loadingOverlayColor),
DoubleTextField(Messages.controlLoadingOverlayFullOpacity, opts.loadingOverlayFullOpacity),
// DoubleTextField(Messages.controlLoadingOverlayTransparentOpacity, opts.loadingOverlayTransparentOpacity),
DoubleTextField(Messages.controlLoadingOverlayFadeIn, opts.loadingOverlayFadeInDuration),
DoubleTextField(Messages.controlLoadingOverlayFadeOut, opts.loadingOverlayFadeOutDuration))
private fun createZoomTab(): Tab =
DebugOptionsDialogTab(Messages.tabNameZoom,
IntegerTextField(Messages.controlZoomAnimationDuration + " (unused)", opts.zoomAnimationDuration),
DoubleTextField(Messages.controlZoomStep, opts.zoomStep),
CheckBoxControl(Messages.controlZoomPivotOnSelection, opts.zoomPivotOnSelection),
CheckBoxControl(Messages.controlZoomPivotOnMousePosition, opts.zoomPivotOnMousePosition))
private fun createStateIntervalsTab(): Tab =
DebugOptionsDialogTab(Messages.tabNameIntervals,
DoubleTextField(Messages.controlIntervalOpacity, opts.stateIntervalOpacity)
// multi-state Paint ?
// state label Font ?
)
private fun createTooltipTab(): Tab =
DebugOptionsDialogTab(Messages.tabNameTooltips,
// Tooltip Font picker
ColorControl(Messages.controlTooltipFontColor, opts.toolTipFontFill))
// ------------------------------------------------------------------------
// Property-setting controls
// ------------------------------------------------------------------------
private interface PropertySetter {
val option: ConfigOption<*>
fun load()
fun save()
}
private class CheckBoxControl(labelText: String?, override val option: ConfigOption<Boolean>) : CheckBox(), PropertySetter {
init {
text = labelText
load()
}
override fun load() {
isSelected = option.get()
}
override fun save() {
option.set(isSelected)
}
}
private class ColorControl(labelText: String?, override val option: ConfigOption<Color>) : HBox(), PropertySetter {
private val colorPicker = ColorPicker(option.get())
init {
children.addAll(Label("$labelText:"), colorPicker)
alignment = Pos.CENTER_LEFT
spacing = SPACING
}
override fun load() {
colorPicker.value = option.get()
}
override fun save() {
colorPicker.value?.let { option.set(it) }
}
}
private abstract class TextFieldControl<T : Number> protected constructor(labelText: String?,
final override val option: ConfigOption<T>) : HBox(), PropertySetter {
protected val textField = TextField()
init {
val label = Label("$labelText:")
load()
children.addAll(label, textField)
alignment = Pos.CENTER_LEFT
spacing = SPACING
}
final override fun load() {
textField.text = option.get().toString()
}
abstract override fun save()
}
private class IntegerTextField(labelText: String?, option: ConfigOption<Int>) : TextFieldControl<Int>(labelText, option) {
override fun save() {
textField.text.toIntOrNull()
?.let { option.set(it) }
?: run {
option.resetToDefault()
load()
}
}
}
private class DoubleTextField(labelText: String?, option: ConfigOption<Double>) : TextFieldControl<Double>(labelText, option) {
override fun save() {
textField.text.toDoubleOrNull()
?.let { option.set(it) }
?: run {
option.resetToDefault()
load()
}
}
}
}
| epl-1.0 | 5e96512bd1b6194eb0791d4b65c771f9 | 35.935897 | 148 | 0.592618 | 5.442695 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/util/Rectd.kt | 1 | 1603 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.util
/**
* A rectangle using Double
*/
data class Rectd(
var left: Double,
var bottom: Double,
var right: Double,
var top: Double) {
val width
get() = right - left
val height
get() = top - bottom
constructor() : this(0.0, 0.0, 0.0, 0.0)
constructor(other: Rectd) : this(other.left, other.bottom, other.right, other.top)
fun plus(dx: Double, dy: Double, dest: Rectd = this): Rectd {
dest.left = left + dx
dest.right = right + dx
dest.top = top + dy
dest.bottom = bottom + dy
return dest
}
override fun equals(other: Any?): Boolean {
if (other !is Rectd) {
return false
}
return other.left == left && other.bottom == bottom && other.right == right && other.top == top
}
override fun toString(): String = "($left , $bottom , $right , $top)"
}
| gpl-3.0 | 058851fd174b722134283248cb41e8aa | 28.145455 | 103 | 0.648784 | 3.977667 | false | false | false | false |
afollestad/icon-request | library/src/main/java/com/afollestad/iconrequest/extensions/MiscExtensions.kt | 1 | 2656 | /*
* Licensed under Apache-2.0
*
* Designed and developed by Aidan Follestad (@afollestad)
*/
package com.afollestad.iconrequest.extensions
import android.os.Build
import android.os.Build.VERSION
import android.os.Build.VERSION_CODES
import android.text.Html
import android.text.Spanned
import com.afollestad.iconrequest.AppModel
import java.util.Locale
internal val osVersionName: String
get() {
when (Build.VERSION.SDK_INT) {
Build.VERSION_CODES.CUPCAKE -> return "Cupcake"
Build.VERSION_CODES.DONUT -> return "Donut"
Build.VERSION_CODES.ECLAIR, Build.VERSION_CODES.ECLAIR_0_1, Build.VERSION_CODES.ECLAIR_MR1 -> return "Eclair"
Build.VERSION_CODES.FROYO -> return "Froyo"
Build.VERSION_CODES.GINGERBREAD, Build.VERSION_CODES.GINGERBREAD_MR1 -> return "Gingerbread"
Build.VERSION_CODES.HONEYCOMB, Build.VERSION_CODES.HONEYCOMB_MR1, Build.VERSION_CODES.HONEYCOMB_MR2 -> return "Honeycomb"
Build.VERSION_CODES.ICE_CREAM_SANDWICH, Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1 -> return "Ice Cream Sandwich"
Build.VERSION_CODES.JELLY_BEAN, Build.VERSION_CODES.JELLY_BEAN_MR1, Build.VERSION_CODES.JELLY_BEAN_MR2 -> return "Jelly Bean"
Build.VERSION_CODES.KITKAT -> return "KitKat"
Build.VERSION_CODES.KITKAT_WATCH -> return "KitKat Watch"
Build.VERSION_CODES.LOLLIPOP, Build.VERSION_CODES.LOLLIPOP_MR1 -> return "Lollipop"
Build.VERSION_CODES.M -> return "Marshmallow"
Build.VERSION_CODES.N, Build.VERSION_CODES.N_MR1 -> return "Nougat"
Build.VERSION_CODES.O, Build.VERSION_CODES.O_MR1 -> return "Oreo"
28 -> return "P"
29 -> return "Q"
30 -> return "R"
31 -> return "S"
32 -> return "T"
33 -> return "U"
34 -> return "V"
35 -> return "W"
36 -> return "X"
37 -> return "Y"
38 -> return "Z"
else -> return "Unknown"
}
}
internal fun String.drawableName(): String {
return toLowerCase(Locale.getDefault()).replace(" ", "_")
}
internal fun List<AppModel>.transferStates(
to: MutableList<AppModel>
) {
this.filter { it.selected }
.forEach {
for (i in to.indices) {
val current = to[i]
if (it.code == current.code) {
to[i] = current.copy(selected = it.selected, requested = it.requested)
break
}
}
}
}
internal fun String.toHtml(): Spanned {
return if (VERSION.SDK_INT >= VERSION_CODES.N) {
Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY, null, null)
} else {
@Suppress("DEPRECATION")
Html.fromHtml(this)
}
}
internal fun <T> MutableList<T>.toArrayList() = java.util.ArrayList(this)
| apache-2.0 | da0cccb8b6826add8ca67f0e83716eea | 33.947368 | 131 | 0.66491 | 3.431525 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-ui/src/androidTest/kotlin/com/github/kittinunf/reactiveandroid/reactive/widget/TextViewTest.kt | 1 | 5777 | package com.github.kittinunf.reactiveandroid.reactive.widget
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.Typeface
import android.support.test.InstrumentationRegistry
import android.support.test.annotation.UiThreadTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.github.kittinunf.reactiveandroid.widget.TextViewTestActivity
import io.reactivex.Single
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TextViewTest {
@Rule
@JvmField
val activityRule = ActivityTestRule(TextViewTestActivity::class.java)
val instrumentation = InstrumentationRegistry.getInstrumentation()
lateinit var view: TextView
@Before
fun before() {
view = activityRule.activity.textView
}
@Test
@UiThreadTest
fun afterTextChanged() {
val test = view.rx.afterTextChanged().test()
val expectedText1 = "test"
val expectedText2 = "testx"
view.text = expectedText1
view.text = expectedText2
test.assertValueCount(2)
test.assertNoErrors()
assertThat(test.values()[0].s.toString(), equalTo(expectedText1))
assertThat(test.values()[1].s.toString(), equalTo(expectedText2))
}
@Test
@UiThreadTest
fun beforeTextChanged() {
val test = view.rx.beforeTextChanged().test()
val inputText1 = "h"
val inputText2 = "he"
val inputText3 = "he1"
view.text = inputText1
view.text = inputText2
view.text = inputText3
test.assertValueCount(3)
test.assertNoErrors()
assertThat(test.values()[0].s.toString(), equalTo(""))
assertThat(test.values()[0].start, equalTo(0))
assertThat(test.values()[0].count, equalTo(0))
assertThat(test.values()[0].after, equalTo(1))
assertThat(test.values()[1].s.toString(), equalTo(inputText1))
assertThat(test.values()[1].start, equalTo(0))
assertThat(test.values()[1].count, equalTo(1))
assertThat(test.values()[1].after, equalTo(2))
assertThat(test.values()[2].s.toString(), equalTo(inputText2))
assertThat(test.values()[2].start, equalTo(0))
assertThat(test.values()[2].count, equalTo(2))
assertThat(test.values()[2].after, equalTo(3))
}
@Test
@UiThreadTest
fun textChanged() {
val test = view.rx.textChanged().test()
val inputText1 = "h"
val inputText2 = "he"
val inputText3 = "he1"
view.text = inputText1
view.text = inputText2
view.text = inputText3
test.assertValueCount(4)
test.assertNoErrors()
assertThat(test.values()[0].s.toString(), equalTo(""))
assertThat(test.values()[0].start, equalTo(0))
assertThat(test.values()[0].before, equalTo(0))
assertThat(test.values()[0].count, equalTo(0))
assertThat(test.values()[1].s.toString(), equalTo(inputText1))
assertThat(test.values()[1].start, equalTo(0))
assertThat(test.values()[1].before, equalTo(0))
assertThat(test.values()[1].count, equalTo(1))
assertThat(test.values()[2].s.toString(), equalTo(inputText2))
assertThat(test.values()[2].start, equalTo(0))
assertThat(test.values()[2].before, equalTo(1))
assertThat(test.values()[2].count, equalTo(2))
assertThat(test.values()[3].s.toString(), equalTo(inputText3))
assertThat(test.values()[3].start, equalTo(0))
assertThat(test.values()[3].before, equalTo(2))
assertThat(test.values()[3].count, equalTo(3))
}
@Test
@UiThreadTest
fun editorAction() {
val test = view.rx.onEditorAction().test()
view.text = "h"
view.onEditorAction(EditorInfo.IME_ACTION_NEXT)
view.text = "he"
view.onEditorAction(EditorInfo.IME_ACTION_DONE)
test.assertValueCount(2)
test.assertNoErrors()
}
@Test
@UiThreadTest
fun text() {
val expectedText = "text"
Single.just(expectedText).subscribe(view.rx.text)
assertThat(view.text.toString(), equalTo(expectedText))
}
@Test
@UiThreadTest
fun error() {
val expectedText = "error"
Single.just(expectedText).subscribe(view.rx.error)
assertThat(view.error.toString(), equalTo(expectedText))
}
@Test
@UiThreadTest
fun hint() {
val expectedText = "hint"
Single.just(expectedText).subscribe(view.rx.hint)
assertThat(view.hint.toString(), equalTo(expectedText))
}
@Test
@UiThreadTest
fun textColor() {
val expectedColor = 20
Single.just(expectedColor).subscribe(view.rx.textColor)
assertThat(view.currentTextColor, equalTo(expectedColor))
}
@Test
@UiThreadTest
fun textColors() {
val states = arrayOf(intArrayOf(android.R.attr.state_activated), intArrayOf(-android.R.attr.state_activated))
val colors = intArrayOf(Color.parseColor("#FFFF00"), Color.BLACK)
val expectedColors = ColorStateList(states, colors)
Single.just(expectedColors).subscribe(view.rx.textColors)
assertThat(view.textColors, equalTo(expectedColors))
}
@Test
@UiThreadTest
fun typeFace() {
val expectedTypeface = Typeface.DEFAULT
Single.just(expectedTypeface).subscribe(view.rx.typeface)
assertThat(view.typeface, equalTo(expectedTypeface))
}
} | mit | bbdbc4b7e3fd58448b1d15350be831a3 | 27.89 | 117 | 0.656742 | 4.260324 | false | true | false | false |
box/box-android-share-sdk | box-share-sdk/src/test/java/com/box/androidsdk/share/sharerepo/ShareRepoTest.kt | 1 | 15244 | package com.box.androidsdk.share.sharerepo
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.box.androidsdk.content.BoxFutureTask
import com.box.androidsdk.content.models.*
import com.box.androidsdk.content.requests.*
import com.box.androidsdk.share.api.ShareController
import com.box.androidsdk.share.internal.models.BoxFeatures
import com.box.androidsdk.share.internal.models.BoxIteratorInvitees
import com.nhaarman.mockitokotlin2.*
import junit.framework.Assert.*
import org.junit.*
import org.junit.rules.TestRule
import java.lang.Exception
import java.lang.IllegalArgumentException
import java.util.*
class ShareRepoTest {
@get:Rule
var rule: TestRule = InstantTaskExecutorRule()
private val shareController: ShareController = mock()
private val mockShareItem: BoxCollaborationItem = mock()
private val mockEmailList: Array<String> = arrayOf("[email protected]", "[email protected]")
private val mockSelectedRole: BoxCollaboration.Role = BoxCollaboration.Role.EDITOR
private val mockFilter: String = "filter"
private val mockCollaboration: BoxCollaboration = mock()
private val mockBoxFile: BoxFile = mock()
private val canDownload = false
private val newAccess = BoxSharedLink.Access.COMPANY
private val newPassword = ""
private val mockGetInviteeResponseTask: BoxFutureTask<BoxIteratorInvitees> = mock()
private val mockGetInviteeResponse: BoxResponse<BoxIteratorInvitees> = mock()
private val mockFetchRolesResponseTask: BoxFutureTask<BoxCollaborationItem> = mock()
private val mockFetchRolesResponse: BoxResponse<BoxCollaborationItem> = mock()
private val mockAddCollabsResponseTask: BoxFutureTask<BoxResponseBatch> = mock()
private val mockAddCollabsResponse: BoxResponse<BoxResponseBatch> = mock()
private val mockFetchItemInfoResponseTask: BoxFutureTask<BoxItem> = mock()
private val mockFetchItemInfoResponse: BoxResponse<BoxItem> = mock()
private val mockSharedLinkResponseTask: BoxFutureTask<BoxItem> = mock()
private val mockSharedLinkResponse: BoxResponse<BoxItem> = mock()
private val mockFeatureResponseTask: BoxFutureTask<BoxFeatures> = mock()
private val mockFeatureResponse: BoxResponse<BoxFeatures> = mock()
private val mockDeleteCollaborationResponseTask: BoxFutureTask<BoxVoid> = mock()
private val mockDeleteCollaborationResponse: BoxResponse<BoxVoid> = mock()
private val mockUpdateOwnerResponseTask: BoxFutureTask<BoxVoid> = mock()
private val mockUpdateOwnerResponse: BoxResponse<BoxVoid> = mock()
private val mockUpdateCollaborationResponseTask: BoxFutureTask<BoxCollaboration> = mock()
private val mockUpdateCollaborationResponse: BoxResponse<BoxCollaboration> = mock()
private val mockFetchCollaborationResponseTask: BoxFutureTask<BoxIteratorCollaborations> = mock()
private val mockFetchCollaborationResponse: BoxResponse<BoxIteratorCollaborations> = mock()
private val mockDate: Date = mock()
private lateinit var shareRepo: ShareRepo
@Before
fun setup() {
whenever(shareController.fetchItemInfo(mockShareItem)).thenReturn(mockFetchItemInfoResponseTask)
whenever(shareController.getInvitees(mockShareItem, mockFilter)).thenReturn(mockGetInviteeResponseTask)
whenever(shareController.fetchRoles(mockShareItem)).thenReturn(mockFetchRolesResponseTask)
whenever(shareController.addCollaborations(mockShareItem, mockSelectedRole, mockEmailList)).thenReturn(mockAddCollabsResponseTask)
whenever(shareController.createDefaultSharedLink(mockShareItem)).thenReturn(mockSharedLinkResponseTask)
whenever(shareController.disableShareLink(mockShareItem)).thenReturn(mockSharedLinkResponseTask)
val mockBoxRequestsFile: BoxRequestsFile.UpdatedSharedFile = mock()
whenever(shareController.getCreatedSharedLinkRequest(mockShareItem)).thenReturn(mock())
whenever(shareController.getCreatedSharedLinkRequest(mockBoxFile)).thenReturn(mockBoxRequestsFile)
whenever(shareController.executeRequest(BoxItem::class.java, (shareController.getCreatedSharedLinkRequest(mockBoxFile) as BoxRequestsFile.UpdatedSharedFile).setCanDownload(canDownload))).thenReturn(mockSharedLinkResponseTask)
whenever(shareController.executeRequest(BoxItem::class.java, shareController.getCreatedSharedLinkRequest(mockShareItem).setAccess(newAccess))).thenReturn(mockSharedLinkResponseTask)
whenever(shareController.executeRequest(BoxItem::class.java, shareController.getCreatedSharedLinkRequest(mockShareItem).setUnsharedAt(mockDate))).thenReturn(mockSharedLinkResponseTask)
whenever(shareController.executeRequest(BoxItem::class.java, shareController.getCreatedSharedLinkRequest(mockShareItem).setRemoveUnsharedAtDate())).thenReturn(mockSharedLinkResponseTask)
whenever(shareController.executeRequest(BoxItem::class.java, shareController.getCreatedSharedLinkRequest(mockShareItem).setPassword(newPassword))).thenReturn(mockSharedLinkResponseTask)
whenever(shareController.supportedFeatures).thenReturn(mockFeatureResponseTask)
whenever(shareController.fetchCollaborations(mockShareItem)).thenReturn(mockFetchCollaborationResponseTask)
whenever(shareController.deleteCollaboration(mockCollaboration)).thenReturn(mockDeleteCollaborationResponseTask)
whenever(shareController.updateCollaboration(mockCollaboration, mockSelectedRole)).thenReturn(mockUpdateCollaborationResponseTask)
whenever(shareController.updateOwner(mockCollaboration)).thenReturn(mockUpdateOwnerResponseTask)
shareRepo = ShareRepo(shareController)
createStubs()
}
/**
* Mock callback responses.
*/
private fun createStubs() {
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxIteratorInvitees>
callback.onCompleted(mockGetInviteeResponse)
null
}.whenever(mockGetInviteeResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxIteratorInvitees>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxCollaborationItem>
callback.onCompleted(mockFetchRolesResponse)
null
}.whenever(mockFetchRolesResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxCollaborationItem>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxResponseBatch>
callback.onCompleted(mockAddCollabsResponse)
null
}.whenever(mockAddCollabsResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxResponseBatch>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxItem>
callback.onCompleted(mockFetchItemInfoResponse)
null
}.whenever(mockFetchItemInfoResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxItem>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxItem>
callback.onCompleted(mockSharedLinkResponse)
null
}.whenever(mockSharedLinkResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxItem>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxIteratorCollaborations>
callback.onCompleted(mockFetchCollaborationResponse)
null
}.whenever(mockFetchCollaborationResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxIteratorCollaborations>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxFeatures>
callback.onCompleted(mockFeatureResponse)
null
}.whenever(mockFeatureResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxFeatures>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxCollaboration>
callback.onCompleted(mockUpdateCollaborationResponse)
null
}.whenever(mockUpdateCollaborationResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxCollaboration>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxVoid>
callback.onCompleted(mockUpdateOwnerResponse)
null
}.whenever(mockUpdateOwnerResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxVoid>>())
doAnswer {
val callback = it.arguments[0] as BoxFutureTask.OnCompletedListener<BoxVoid>
callback.onCompleted(mockDeleteCollaborationResponse)
null
}.whenever(mockDeleteCollaborationResponseTask).addOnCompletedListener(any<BoxFutureTask.OnCompletedListener<BoxVoid>>())
}
@Test
fun `test fetch roles update LiveData values correctly`() {
assertNull(shareRepo.roleItem.value) //initially the LiveData should not have any value
shareRepo.fetchRolesFromRemote(mockShareItem) //get a value and update as needed
assertEquals(mockFetchRolesResponse, shareRepo.getRoleItem().value)
}
@Test
fun `test fetch invitees update LiveData values correctly`() {
assertNull(shareRepo.invitees.value) //initially the LiveData should not have any value
shareRepo.fetchInviteesFromRemote(mockShareItem, mockFilter) //get a value and update as needed
assertEquals(mockGetInviteeResponse, shareRepo.getInvitees().value)
}
@Test
fun `test invite collabs update LiveData values correctly` () {
assertNull(shareRepo.inviteCollabsBatchResponse.value) //initially the LiveData should not have any value
shareRepo.inviteCollabs(mockShareItem, mockSelectedRole, mockEmailList) //get a value and update as needed
assertEquals(mockAddCollabsResponse, shareRepo.getInviteCollabsBatchResponse().value)
}
@Test
fun `test fetch item info update LiveData values correctly` () {
assertNull(shareRepo.itemInfo.value) //initially the LiveData should not have any value
shareRepo.fetchItemInfo(mockShareItem) //get a value and update as needed
assertEquals(mockFetchItemInfoResponse, shareRepo.itemInfo.value)
}
@Test
fun `test create shared link update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.createDefaultSharedLink(mockShareItem) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test disable shared link update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.disableSharedLink(mockShareItem) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test change download permission update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.changeDownloadPermission(mockBoxFile, canDownload) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test change download permission illegal argument` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
try {
shareRepo.changeDownloadPermission(mockShareItem, canDownload)
} catch (e: Exception) {
assertTrue(e is IllegalArgumentException) //illegal argument exception should occur
}
}
@Test
fun `test change access level update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.changeAccessLevel(mockBoxFile, newAccess) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test set expiry date update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.setExpiryDate(mockBoxFile, mockDate) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test remove expiry date update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.removeExpiryDate(mockBoxFile) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test change password update LiveData values correctly` () {
assertNull(shareRepo.shareLinkedItem.value) //initially the LiveData should not have any value
shareRepo.changePassword(mockShareItem, newPassword) //get a value and update as needed
assertEquals(mockSharedLinkResponse, shareRepo.shareLinkedItem.value)
}
@Test
fun `test fetch features update LiveData values correctly` () {
assertNull(shareRepo.supportFeatures.value) //initially the LiveData should not have any value
shareRepo.fetchSupportedFeatures() //get a value and update as needed
assertEquals(mockFeatureResponse, shareRepo.supportFeatures.value)
}
@Test
fun `test fetch collaborations update LiveData values correctly` () {
assertNull(shareRepo.collaborations.value) //initially the LiveData should not have any value
shareRepo.fetchCollaborations(mockShareItem) //get a value and update as needed
assertEquals(mockFetchCollaborationResponse, shareRepo.collaborations.value)
}
@Test
fun `test update collaborations update LiveData values correctly` () {
assertNull(shareRepo.updateCollaboration.value) //initially the LiveData should not have any value
shareRepo.updateCollaboration(mockCollaboration, mockSelectedRole) //get a value and update as needed
assertEquals(mockUpdateCollaborationResponse, shareRepo.updateCollaboration.value)
}
@Test
fun `test update owner update LiveData values correctly` () {
assertNull(shareRepo.updateOwner.value) //initially the LiveData should not have any value
shareRepo.updateOwner(mockCollaboration) //get a value and update as needed
assertEquals(mockUpdateOwnerResponse, shareRepo.updateOwner.value)
}
@Test
fun `test delete collaboration update LiveData values correctly` () {
assertNull(shareRepo.deleteCollaboration.value) //initially the LiveData should not have any value
shareRepo.deleteCollaboration(mockCollaboration) //get a value and update as needed
assertEquals(mockDeleteCollaborationResponse, shareRepo.deleteCollaboration.value)
}
} | apache-2.0 | 71a364fcf85f5a50a616ec9089d0ff1c | 48.983607 | 233 | 0.761152 | 4.822525 | false | true | false | false |
thaleslima/GuideApp | app/src/main/java/com/guideapp/data/local/GuideProvider.kt | 1 | 4990 | package com.guideapp.data.local
import android.annotation.TargetApi
import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import android.util.Log
class GuideProvider : ContentProvider() {
private var mOpenHelper: GuideDbHelper? = null
override fun onCreate(): Boolean {
mOpenHelper = GuideDbHelper(context)
return true
}
override fun bulkInsert(uri: Uri, values: Array<ContentValues>): Int {
var rowsInserted = 0
mOpenHelper?.writableDatabase?.let { db ->
Log.d(TAG, "bulkInsert: " + uri)
when (URI_MATCHER.match(uri)) {
CODE_LOCAL -> {
db.beginTransaction()
try {
db.delete(GuideContract.LocalEntry.TABLE_NAME, null, null)
values.map { db.insert(GuideContract.LocalEntry.TABLE_NAME, null, it) }.filter { it != -1L }.forEach { rowsInserted++ }
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
if (rowsInserted > 0) {
context?.contentResolver?.notifyChange(uri, null)
Log.d(TAG, "notifyChange: " + uri)
}
return rowsInserted
}
else -> return super.bulkInsert(uri, values)
}
}
return rowsInserted
}
override fun query(uri: Uri, projection: Array<String>?, selection: String?,
selectionArgs: Array<String>?, sortOrder: String?): Cursor? {
Log.d(TAG, "query: " + uri)
val cursor: Cursor?
when (URI_MATCHER.match(uri)) {
CODE_LOCAL -> {
cursor = mOpenHelper?.readableDatabase?.query(
GuideContract.LocalEntry.TABLE_NAME,
projection,
selection,
selectionArgs, null, null,
sortOrder)
}
CODE_LOCAL_WITH_ID -> {
val id = uri.pathSegments[1]
cursor = mOpenHelper?.readableDatabase?.query(
GuideContract.LocalEntry.TABLE_NAME,
projection,
GuideContract.LocalEntry._ID + " = ?",
arrayOf(id), null, null, null)
}
else -> throw UnsupportedOperationException("Unknown uri: " + uri)
}
cursor?.setNotificationUri(context?.contentResolver, uri)
return cursor
}
override fun getType(uri: Uri): String? {
throw RuntimeException("We are not implementing getType.")
}
override fun insert(uri: Uri, values: ContentValues?): Uri? {
throw RuntimeException("We are not implementing insert.")
}
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int {
var selection1 = selection
val numRowsDeleted: Int?
if (null == selection1) selection1 = "1"
when (URI_MATCHER.match(uri)) {
CODE_LOCAL -> numRowsDeleted = mOpenHelper?.writableDatabase?.delete(
GuideContract.LocalEntry.TABLE_NAME,
selection1,
selectionArgs)
else -> throw UnsupportedOperationException("Unknown uri: " + uri)
}
context?.contentResolver?.notifyChange(uri, null)
return numRowsDeleted ?: 0
}
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int {
val numRowsDeleted: Int?
when (URI_MATCHER.match(uri)) {
CODE_LOCAL_WITH_ID -> {
val id = uri.pathSegments[1]
numRowsDeleted = mOpenHelper?.writableDatabase?.update(
GuideContract.LocalEntry.TABLE_NAME,
values,
GuideContract.LocalEntry._ID + " = ?",
arrayOf(id))
}
else -> throw UnsupportedOperationException("Unknown uri: " + uri)
}
return numRowsDeleted ?: 0
}
@TargetApi(11)
override fun shutdown() {
mOpenHelper?.close()
super.shutdown()
}
companion object {
val CODE_LOCAL = 100
val CODE_LOCAL_WITH_ID = 101
private val TAG = GuideProvider::class.java.name
private val URI_MATCHER = buildUriMatcher()
fun buildUriMatcher(): UriMatcher {
val matcher = UriMatcher(UriMatcher.NO_MATCH)
val authority = GuideContract.CONTENT_AUTHORITY
matcher.addURI(authority, GuideContract.PATH_LOCAL, CODE_LOCAL)
matcher.addURI(authority, GuideContract.PATH_LOCAL + "/#", CODE_LOCAL_WITH_ID)
return matcher
}
}
}
| apache-2.0 | a941a7348bf95e74a99c701e53ded947 | 34.140845 | 143 | 0.548898 | 5.060852 | false | false | false | false |
Cardstock/Cardstock | src/test/kotlin/xyz/cardstock/cardstock/commands/CommandRegistrarSpec.kt | 1 | 3246 | /*
* 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 xyz.cardstock.cardstock.commands
import org.jetbrains.spek.api.Spek
import xyz.cardstock.cardstock.implementations.commands.NoOpDummyCommand
import xyz.cardstock.cardstock.implementations.commands.TestCommand
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertTrue
class CommandRegistrarSpec : Spek({
given("a standard command registrar") {
val commandRegistrar = CommandRegistrar()
val command = TestCommand()
on("registering a command") {
commandRegistrar.registerCommand(command)
it("should have one command") {
assertEquals(1, commandRegistrar.all().size)
}
it("should return the same command if queried by name") {
assertTrue(command === commandRegistrar[command.name])
}
it("should return the same command if queried by alias") {
assertTrue(command === commandRegistrar[command.aliases[0]])
}
it("should return the same command if queried by name with different case") {
assertTrue(command === commandRegistrar[command.name.toUpperCase()])
}
it("should return the same command if queried by alias with different case") {
assertTrue(command === commandRegistrar[command.aliases[0].toUpperCase()])
}
}
on("registering the same command again") {
it("should throw an IllegalStateException") {
assertFailsWith(IllegalStateException::class) {
commandRegistrar.registerCommand(command)
}
}
}
on("registering a command with a clashing alias") {
it("should throw an IllegalStateException") {
assertFailsWith(IllegalStateException::class) {
commandRegistrar.registerCommand(NoOpDummyCommand("something", arrayOf("spec")))
}
}
}
}
// TODO: Merge this with the above `given`. This cannot be done because Spek is broken. It runs all `on` blocks
// at once, then it runs all `it` blocks. This breaks functionality involving state.
given("a command registrar with one command") {
val commandRegistrar = CommandRegistrar()
val command = TestCommand()
commandRegistrar.registerCommand(command)
on("unregistering the same command") {
commandRegistrar.unregisterCommand(command)
it("should have zero commands") {
assertEquals(0, commandRegistrar.all().size)
}
it("should return null if queried by name") {
assertNull(commandRegistrar[command.name])
}
it("should return null if queried by alias") {
assertNull(commandRegistrar[command.aliases[0]])
assertNull(commandRegistrar.getCommandByAlias(command.aliases[0]))
}
}
}
})
| mpl-2.0 | 2eb30560e2ccdfd9281e9f70f377a252 | 43.465753 | 115 | 0.626001 | 5.177033 | false | true | false | false |
Nagarajj/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/ScheduledAction.kt | 1 | 1795 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.util.concurrent.Executors.newSingleThreadScheduledExecutor
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit.SECONDS
/**
* Encapsulates an action that runs regularly. Used by queue implementation for
* checking for unacknowledged messages and re-delivering them.
*
* The function passed to [action] is called on a regular cycle by a single
* dedicated thread.
*/
class ScheduledAction(
private val action: () -> Unit,
initialDelay: Long = 10,
delay: Long = 10,
unit: TimeUnit = SECONDS
) : Closeable {
private val executor = newSingleThreadScheduledExecutor()
private val watcher = executor
.scheduleWithFixedDelay({
try {
action.invoke()
} catch(e: Exception) {
// this really indicates a code issue but if it's not caught here it
// will kill the scheduled action.
log.error("Uncaught exception in scheduled action", e)
}
}, initialDelay, delay, unit)
private val log = LoggerFactory.getLogger(javaClass)
override fun close() {
watcher.cancel(false)
executor.shutdown()
}
}
| apache-2.0 | a2c7bd252262763353fdb431a599202d | 30.491228 | 79 | 0.725905 | 4.314904 | false | false | false | false |
jean79/yested_fw | src/commonMain/kotlin/net/yested/core/properties/properties.kt | 1 | 15438 | package net.yested.core.properties
import net.yested.core.utils.SortSpecification
import net.yested.core.utils.Tuple4
import net.yested.core.utils.Tuple5
import net.yested.core.utils.Tuple6
import kotlinx.coroutines.*
interface Disposable {
fun dispose()
}
private interface PropertyChangeListener<in T> {
fun onNext(value: T)
}
/** A Property that can be subscribed to. The T value should be immutable or else its changes won't be detected. */
interface ReadOnlyProperty<out T> {
fun get():T
fun onNext(handler: (T)->Unit):Disposable
}
private val nullProperty: ReadOnlyProperty<Any?> = object : ReadOnlyProperty<Any?> {
val emptyDisposable: Disposable = object : Disposable {
override fun dispose() {}
}
override fun get(): Any? = null
override fun onNext(handler: (Any?) -> Unit): Disposable {
handler(null)
return emptyDisposable
}
}
@Suppress("UNCHECKED_CAST")
fun <T> nullProperty(): ReadOnlyProperty<T?> = nullProperty as ReadOnlyProperty<T>
/** A mutable Property that can be subscribed to. The T value should be immutable or else its changes won't be detected. */
class Property<T>(initialValue: T): ReadOnlyProperty<T> {
private var value : T = initialValue
private val listeners = mutableSetOf<PropertyChangeListener<T>>()
fun set(newValue: T) {
if (newValue != value) {
value = newValue
listeners.forEach { it.onNext(value) }
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (!(other is Property<*>)) return false
return value == other.value
}
override fun hashCode(): Int {
return value?.hashCode() ?: 0
}
override fun get() = value
override fun onNext(handler: (T)->Unit):Disposable {
val listener = object : PropertyChangeListener<T> {
override fun onNext(value: T) {
handler(value)
}
}
listeners.add(listener)
handler(value)
return object : Disposable {
override fun dispose() {
listeners.remove(listener)
}
}
}
/** Useful for ensuring that listeners are disposed correctly. */
val listenerCount: Int get() = listeners.size
}
fun <IN, OUT> ReadOnlyProperty<IN>.map(transform: (IN)->OUT): ReadOnlyProperty<OUT> {
return mapAsDefault(transform)
}
/**
* Map a property to a modifiable property.
* The resulting property can be modified directly which will have no effect on the original property.
* If the original property changes, it will get a new value using transform, losing any direct modifications made.
*/
fun <IN, OUT> ReadOnlyProperty<IN>.mapAsDefault(transform: (IN)->OUT): Property<OUT> {
val property = Property(transform(this.get()))
this.onNext {
property.set(transform(it))
}
return property
}
fun <IN, OUT> ReadOnlyProperty<IN>.flatMap(transform: (IN)->ReadOnlyProperty<OUT>): ReadOnlyProperty<OUT> {
val initialProperty = transform(this.get())
val result = Property(initialProperty.get())
var disposable = initialProperty.onChange { _, value -> result.set(value) }
this.onChange { _, value ->
disposable.dispose()
disposable = transform(value).onNext { result.set(it) }
}
return result
}
fun <IN, OUT> ReadOnlyProperty<IN>.flatMapOrNull(transform: (IN)->ReadOnlyProperty<OUT?>?): ReadOnlyProperty<OUT?> {
return flatMap<IN,OUT?> { transform(it) ?: nullProperty() }
}
fun <IN, OUT> ReadOnlyProperty<IN?>.flatMapIfNotNull(transform: (IN)->ReadOnlyProperty<OUT?>?): ReadOnlyProperty<OUT?> {
return flatMapOrNull<IN?,OUT?> { it?.let(transform) }
}
fun <IN, OUT> ReadOnlyProperty<IN?>.mapIfNotNull(default: OUT? = null, transform: (IN)->OUT?): ReadOnlyProperty<OUT?> {
return map { it?.let { transform(it) } ?: default }
}
/**
* Returns a Property that is updated asynchronously from this Property.
* Only the latest value is guaranteed to be propagated.
* This is useful for deferring work that doesn't need to happen right away,
* and to avoid redoing work that could be done once by waiting.
*/
fun <T> ReadOnlyProperty<T>.async(): ReadOnlyProperty<T> {
val result = Property(get())
onNext {
GlobalScope.launch { // launch new coroutine in background and continue
result.set(get())
}
}
return result
}
/**
* Executes an operation each time the property value changes. The operation is not called immediately.
* @param operation an operation that takes the old and the new values, in that order.
*/
fun <T> ReadOnlyProperty<T>.onChange(operation: (T, T)->Unit): Disposable {
var firstTime = true
var oldValue = get()
return onNext { newValue ->
if (firstTime) {
firstTime = false
} else {
val oldValueToUse = oldValue
oldValue = newValue
operation(oldValueToUse, newValue)
}
}
}
/**
* Collects values for this property into a collected result.
* The resulting Property's onNext is called each time another value is collected.
* The collector function has access to the collected result so far and the next value.
* The collected result is null the first time the collector function is run.
* This can be useful when reducing or accumulating data or conditionally reusing what was previously mapped.
*/
fun <OUT, IN> ReadOnlyProperty<IN>.collect(collector: (OUT?, IN)->OUT): ReadOnlyProperty<OUT> {
return collectAsDefault(collector)
}
/** Same as [collect] but return a modifiable Property like [mapAsDefault]. */
fun <OUT, IN> ReadOnlyProperty<IN>.collectAsDefault(collector: (OUT?, IN)->OUT): Property<OUT> {
val collected = Property(collector(null, this.get()))
var firstTime = true
this.onNext { if (firstTime) { firstTime = false } else collected.set(collector(collected.get(), it)) }
return collected
}
/** Maps two properties together to calculate a single result. */
fun <T,T2,OUT> ReadOnlyProperty<T>.mapWith(property2: ReadOnlyProperty<T2>, transform: (T,T2)->OUT): ReadOnlyProperty<OUT> {
var value1 = this.get()
var value2 = property2.get()
val result = Property(transform(value1, value2))
this.onNext {
value1 = it
result.set(transform(value1, value2))
}
property2.onNext {
value2 = it
result.set(transform(value1, value2))
}
return result
}
/** Maps three properties together to calculate a single result. */
fun <T,T2,T3,OUT> ReadOnlyProperty<T>.mapWith(property2: ReadOnlyProperty<T2>, property3: ReadOnlyProperty<T3>,
transform: (T,T2,T3)->OUT): ReadOnlyProperty<OUT> {
var value1 = this.get()
var value2 = property2.get()
var value3 = property3.get()
val result = Property(transform(value1, value2, value3))
this.onNext {
value1 = it
result.set(transform(value1, value2, value3))
}
property2.onNext {
value2 = it
result.set(transform(value1, value2, value3))
}
property3.onNext {
value3 = it
result.set(transform(value1, value2, value3))
}
return result
}
/**
* Map a Property to another Property and vice-versa.
* This is useful when either property can be modified and the other property should reflect the change,
* but it should not circle back to again update the property that was modified.
*/
fun <IN, OUT> Property<IN>.bind(transform: (IN)->OUT, reverse: (OUT)->IN): Property<OUT> {
var updating = false
val transformedProperty = Property(transform(this.get()))
this.onNext {
if (!updating) {
transformedProperty.set(transform(it))
}
}
transformedProperty.onNext {
updating = true
try { this.set(reverse(it)) }
finally { updating = false }
}
return transformedProperty
}
/**
* Map a Property to two Properties and vice-versa.
* This is useful when either property can be modified and the other property should reflect the change,
* but it should not circle back to again update the property that was modified.
*/
fun <IN, OUT1, OUT2> Property<IN>.bindParts(transform1: (IN)->OUT1, transform2: (IN)->OUT2, reverse: (OUT1, OUT2)->IN): Pair<Property<OUT1>, Property<OUT2>> {
var updating = false
val transformedProperty1 = Property(transform1(this.get()))
val transformedProperty2 = Property(transform2(this.get()))
this.onNext {
if (!updating) {
transformedProperty1.set(transform1(it))
transformedProperty2.set(transform2(it))
}
}
transformedProperty1.onNext {
updating = true
try { this.set(reverse(it, transformedProperty2.get())) }
finally { updating = false }
}
transformedProperty2.onNext {
updating = true
try { this.set(reverse(transformedProperty1.get(), it)) }
finally { updating = false }
}
return Pair(transformedProperty1, transformedProperty2)
}
fun ReadOnlyProperty<Boolean>.not() = this.map { !it }
/** Zips two properties together into a Pair. */
fun <T,T2> ReadOnlyProperty<T>.zip(property2: ReadOnlyProperty<T2>): ReadOnlyProperty<Pair<T,T2>> {
var value1 = this.get()
var value2 = property2.get()
val combined = Property(Pair(value1, value2))
this.onNext {
value1 = it
combined.set(Pair(value1, value2))
}
property2.onNext {
value2 = it
combined.set(Pair(value1, value2))
}
return combined
}
/** Zips three properties together into a Triple. */
fun <T,T2,T3> ReadOnlyProperty<T>.zip(property2: ReadOnlyProperty<T2>, property3: ReadOnlyProperty<T3>): ReadOnlyProperty<Triple<T,T2,T3>> {
var value1 = this.get()
var value2 = property2.get()
var value3 = property3.get()
val combined = Property(Triple(value1, value2, value3))
this.onNext {
value1 = it
combined.set(Triple(value1, value2, value3))
}
property2.onNext {
value2 = it
combined.set(Triple(value1, value2, value3))
}
property3.onNext {
value3 = it
combined.set(Triple(value1, value2, value3))
}
return combined
}
/** Zips four properties together into a Tuple4. */
fun <T,T2,T3,T4> ReadOnlyProperty<T>.zip(property2: ReadOnlyProperty<T2>, property3: ReadOnlyProperty<T3>, property4: ReadOnlyProperty<T4>): ReadOnlyProperty<Tuple4<T, T2, T3, T4>> {
var value1 = this.get()
var value2 = property2.get()
var value3 = property3.get()
var value4 = property4.get()
val combined = Property(Tuple4(value1, value2, value3, value4))
this.onNext {
value1 = it
combined.set(Tuple4(value1, value2, value3, value4))
}
property2.onNext {
value2 = it
combined.set(Tuple4(value1, value2, value3, value4))
}
property3.onNext {
value3 = it
combined.set(Tuple4(value1, value2, value3, value4))
}
property4.onNext {
value4 = it
combined.set(Tuple4(value1, value2, value3, value4))
}
return combined
}
/** Zips five properties together into a Tuple5. */
fun <T,T2,T3,T4,T5> ReadOnlyProperty<T>.zip(property2: ReadOnlyProperty<T2>, property3: ReadOnlyProperty<T3>, property4: ReadOnlyProperty<T4>, property5: ReadOnlyProperty<T5>): ReadOnlyProperty<Tuple5<T, T2, T3, T4, T5>> {
var value1 = this.get()
var value2 = property2.get()
var value3 = property3.get()
var value4 = property4.get()
var value5 = property5.get()
val combined = Property(Tuple5(value1, value2, value3, value4, value5))
this.onNext {
value1 = it
combined.set(Tuple5(value1, value2, value3, value4, value5))
}
property2.onNext {
value2 = it
combined.set(Tuple5(value1, value2, value3, value4, value5))
}
property3.onNext {
value3 = it
combined.set(Tuple5(value1, value2, value3, value4, value5))
}
property4.onNext {
value4 = it
combined.set(Tuple5(value1, value2, value3, value4, value5))
}
property5.onNext {
value5 = it
combined.set(Tuple5(value1, value2, value3, value4, value5))
}
return combined
}
/** Zips six properties together into a Tuple6. */
fun <T,T2,T3,T4,T5,T6> ReadOnlyProperty<T>.zip(property2: ReadOnlyProperty<T2>, property3: ReadOnlyProperty<T3>, property4: ReadOnlyProperty<T4>, property5: ReadOnlyProperty<T5>, property6: ReadOnlyProperty<T6>): ReadOnlyProperty<Tuple6<T, T2, T3, T4, T5, T6>> {
var value1 = this.get()
var value2 = property2.get()
var value3 = property3.get()
var value4 = property4.get()
var value5 = property5.get()
var value6 = property6.get()
val combined = Property(Tuple6(value1, value2, value3, value4, value5, value6))
this.onNext {
value1 = it
combined.set(Tuple6(value1, value2, value3, value4, value5, value6))
}
property2.onNext {
value2 = it
combined.set(Tuple6(value1, value2, value3, value4, value5, value6))
}
property3.onNext {
value3 = it
combined.set(Tuple6(value1, value2, value3, value4, value5, value6))
}
property4.onNext {
value4 = it
combined.set(Tuple6(value1, value2, value3, value4, value5, value6))
}
property5.onNext {
value5 = it
combined.set(Tuple6(value1, value2, value3, value4, value5, value6))
}
property6.onNext {
value6 = it
combined.set(Tuple6(value1, value2, value3, value4, value5, value6))
}
return combined
}
/**
* Combines two properties into another one that pairs them together.
* @deprecated use [zip] which has the exact same behavior.
*/
fun <V1, V2> ReadOnlyProperty<V1>.combineLatest(other: ReadOnlyProperty<V2>): ReadOnlyProperty<Pair<V1,V2>> {
return zip(other)
}
infix fun <T> ReadOnlyProperty<T>.debug(render: (T)->String):ReadOnlyProperty<T> {
this.onNext { println(render(it)) }
return this
}
fun <T> T.toProperty() = Property(this)
fun <T> Property<T>.modify(f: (T) -> T) { set(f(get())) }
fun <T> Property<List<T>>.modifyList(operation: (ArrayList<T>) -> Unit) {
modify { list ->
val newList = ArrayList(list)
operation(newList)
newList
}
}
fun <T> Property<List<T>>.clear() { modifyList { it.clear() } }
fun <T> Property<List<T>>.removeAt(index: Int) { modifyList { it.removeAt(index) } }
fun <T> Property<List<T>>.add(item: T) { modifyList { it.add(item) } }
fun <T> Property<List<T>>.remove(item: T) { modifyList { it.remove(item) } }
fun <T> ReadOnlyProperty<Iterable<T>?>.sortedWith(sortSpecification: ReadOnlyProperty<SortSpecification<T>?>): ReadOnlyProperty<Iterable<T>?> {
return sortedWith(sortSpecification.map { it?.fullComparator })
}
fun <T> ReadOnlyProperty<Iterable<T>?>.sortedWith(comparator: ReadOnlyProperty<Comparator<in T>?>): ReadOnlyProperty<Iterable<T>?> {
return mapWith(comparator) { toSort, _comparator ->
if (_comparator == null || toSort == null) {
toSort
} else {
toSort.sortedWith(_comparator)
}
}
}
fun <T> ReadOnlyProperty<List<T>>.sortedWith(comparator: ReadOnlyProperty<Comparator<in T>?>): ReadOnlyProperty<List<T>> {
return mapWith(comparator) { toSort, _comparator ->
if (_comparator == null) toSort else toSort.sortedWith(_comparator)
}
}
| mit | 8dc0677d0e479b22246c2b65cc7754e3 | 33.927602 | 262 | 0.657663 | 3.769043 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/main/kotlin/fr/cph/chicago/core/activity/AlertActivity.kt | 1 | 3970 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.core.activity
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import fr.cph.chicago.R
import fr.cph.chicago.core.adapter.AlertRouteAdapter
import fr.cph.chicago.databinding.ActivityAlertBinding
import fr.cph.chicago.service.AlertService
import fr.cph.chicago.util.Util
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import org.apache.commons.lang3.StringUtils
import timber.log.Timber
class AlertActivity : AppCompatActivity() {
companion object {
private val alertService = AlertService
private val util = Util
}
private lateinit var binding: ActivityAlertBinding
private lateinit var routeId: String
private lateinit var title: String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!this.isFinishing) {
binding = ActivityAlertBinding.inflate(layoutInflater)
setContentView(binding.root)
routeId = intent.getStringExtra("routeId") ?: StringUtils.EMPTY
title = intent.getStringExtra("title") ?: StringUtils.EMPTY
binding.scrollView.setOnRefreshListener { this.refreshData() }
setToolBar()
refreshData()
}
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
routeId = savedInstanceState.getString("routeId") ?: StringUtils.EMPTY
title = savedInstanceState.getString("title") ?: StringUtils.EMPTY
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
if (::routeId.isInitialized) savedInstanceState.putString("routeId", routeId)
if (::title.isInitialized) savedInstanceState.putString("title", title)
super.onSaveInstanceState(savedInstanceState)
}
private fun setToolBar() {
val toolbar = binding.included.toolbar
toolbar.inflateMenu(R.menu.main)
toolbar.setOnMenuItemClickListener {
binding.scrollView.isRefreshing = true
refreshData()
false
}
toolbar.elevation = 4f
toolbar.title = title
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp)
toolbar.setOnClickListener { finish() }
}
@SuppressLint("CheckResult")
private fun refreshData() {
alertService.routeAlertForId(routeId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ routeAlertsDTOS ->
val ada = AlertRouteAdapter(routeAlertsDTOS)
binding.listView.adapter = ada
if (routeAlertsDTOS.isEmpty()) {
util.showSnackBar(view = binding.listView, text = [email protected](R.string.message_no_alerts))
}
hideAnimation()
},
{ error ->
Timber.e(error, "Error while refreshing data")
util.showOopsSomethingWentWrong(binding.listView)
hideAnimation()
})
}
private fun hideAnimation() {
if (binding.scrollView.isRefreshing) {
binding.scrollView.isRefreshing = false
}
}
}
| apache-2.0 | f08c0d107153c52840dc259c57a9f048 | 35.090909 | 131 | 0.667758 | 4.993711 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/engine/selection/SelectedPlaybackEngineTypeAccess.kt | 2 | 1235 | package com.lasthopesoftware.bluewater.client.playback.engine.selection
import com.lasthopesoftware.bluewater.client.playback.engine.selection.defaults.LookupDefaultPlaybackEngine
import com.lasthopesoftware.bluewater.settings.repository.access.HoldApplicationSettings
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
class SelectedPlaybackEngineTypeAccess
(
private val applicationSettings: HoldApplicationSettings,
private val defaultPlaybackEngineLookup: LookupDefaultPlaybackEngine
) : LookupSelectedPlaybackEngineType {
private val engineTypes by lazy { PlaybackEngineType.values() }
override fun promiseSelectedPlaybackEngineType(): Promise<PlaybackEngineType> =
applicationSettings
.promiseApplicationSettings()
.eventually { s ->
engineTypes.firstOrNull { e -> e.name == s.playbackEngineTypeName }
?.toPromise()
?: defaultPlaybackEngineLookup.promiseDefaultEngineType()
.eventually { t ->
s.playbackEngineTypeName = t.name
applicationSettings
.promiseUpdatedSettings(s)
.then { ns ->
engineTypes.first { e -> e.name == ns.playbackEngineTypeName }
}
}
}
}
| lgpl-3.0 | 4544982324e7ab1e37649bd2bbf33530 | 38.83871 | 107 | 0.778947 | 4.843137 | false | false | false | false |
FurhatRobotics/example-skills | OpenAIChat/src/main/kotlin/furhatos/app/openaichat/flow/main/greeting.kt | 1 | 2211 | package furhatos.app.openaichat.flow
import furhatos.app.openaichat.flow.chatbot.MainChat
import furhatos.app.openaichat.setting.Persona
import furhatos.app.openaichat.setting.hostPersona
import furhatos.app.openaichat.setting.personas
import furhatos.flow.kotlin.*
import furhatos.records.Location
val Greeting = state(Parent) {
onEntry {
furhat.attend(users.userClosestToPosition(Location(0.0, 0.0, 0.5)))
askForAnything("Hi there")
furhat.say("I was recently introduced to the A I GPT3 from open A I.")
if (furhat.askYN("Have you heard about GPT3?") == true) {
furhat.say("Good, let's try it out")
} else {
furhat.say("GPT3 is a so-called language model, developed by OpenAI. It can be used to generate any text, for example a conversation, based on the description of a character. ")
if (furhat.askYN("Are you ready to try it out?") == true) {
} else {
furhat.say("Okay, maybe another time then")
goto(Idle)
}
}
goto(ChoosePersona())
}
}
var currentPersona: Persona = hostPersona
fun ChoosePersona() = state(Parent) {
val personasWithAvailableVoice = personas.filter { it.voice.first().isAvailable }
val selectedPersonas = personasWithAvailableVoice.take(3)
fun FlowControlRunner.presentPersonas() {
furhat.say("You can choose to speak to one of these characters:")
for (persona in selectedPersonas) {
//activate(persona)
delay(300)
furhat.say(persona.fullDesc)
delay(300)
}
//activate(hostPersona)
reentry()
}
onEntry {
presentPersonas()
}
onReentry {
furhat.ask("Who would you like to talk to?")
}
onResponse("can you present them again", "could you repeat") {
presentPersonas()
}
for (persona in personas) {
onResponse(persona.intent) {
furhat.say("Okay, I will let you talk to ${persona.name}.")
furhat.say("When you want to end the conversation, just say goodbye.")
currentPersona = persona
goto(MainChat)
}
}
} | mit | d8a58ddbe8be9e6b9f9ab755bbc06cf3 | 31.057971 | 189 | 0.626413 | 3.948214 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/fragment/onboarding/OnboardingSecondFragment.kt | 1 | 2973 | /* 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 org.mozilla.focus.fragment.onboarding
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.transition.TransitionInflater
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import mozilla.telemetry.glean.private.NoExtras
import org.mozilla.focus.GleanMetrics.Onboarding
import org.mozilla.focus.R
import org.mozilla.focus.ext.requireComponents
import org.mozilla.focus.ui.theme.FocusTheme
class OnboardingSecondFragment : Fragment() {
private lateinit var onboardingInteractor: OnboardingInteractor
private var activityResultLauncher: ActivityResultLauncher<Intent> = registerForActivityResult(
ActivityResultContracts.StartActivityForResult(),
) {
onboardingInteractor.onActivityResultImplementation(it)
}
override fun onAttach(context: Context) {
super.onAttach(context)
val transition =
TransitionInflater.from(context).inflateTransition(R.transition.firstrun_exit)
exitTransition = transition
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
onboardingInteractor = DefaultOnboardingInteractor(
DefaultOnboardingController(
onboardingStorage = OnboardingStorage(requireContext()),
appStore = requireComponents.appStore,
context = requireActivity(),
selectedTabId = requireComponents.store.state.selectedTabId,
),
)
return ComposeView(requireContext()).apply {
setContent {
FocusTheme {
OnBoardingSecondScreenCompose(
setAsDefaultBrowser = {
Onboarding.defaultBrowserButton.record(NoExtras())
onboardingInteractor.onMakeFocusDefaultBrowserButtonClicked(activityResultLauncher)
},
skipScreen = {
Onboarding.skipButton.record(NoExtras())
onboardingInteractor.onFinishOnBoarding()
},
onCloseButtonClick = {
Onboarding.secondScreenCloseButton.record(NoExtras())
onboardingInteractor.onFinishOnBoarding()
},
)
}
}
isTransitionGroup = true
}
}
}
| mpl-2.0 | 523bf99f06db68f9bf2573040453865b | 38.64 | 111 | 0.652203 | 5.784047 | false | false | false | false |
shaeberling/euler | kotlin/src/com/s13g/aoc/aoc2020/Day8.kt | 1 | 1918 | package com.s13g.aoc.aoc2020
import com.s13g.aoc.Result
import com.s13g.aoc.Solver
/**
* --- Day 8: Handheld Halting ---
* https://adventofcode.com/2020/day/8
*/
class Day8 : Solver {
override fun solve(lines: List<String>): Result {
val input = lines.map { it.split(" ") }.map { Instr(it[0], it[1].toInt()) }
return Result("${runA(VM(input))}", "${runB(input)}")
}
private fun runA(vm: VM): Int {
while (vm.step()) if (vm.hasLooped()) return vm.acc
error("No loop detected")
}
private fun runB(program: List<Instr>): Int {
for (x in program.indices) {
// Clone the list.
val variant = program.toMutableList()
// Swap the instruction if it matches.
if (variant[x].cmd == "jmp") variant[x] = Instr("nop", variant[x].value)
else if (variant[x].cmd == "nop") variant[x] = Instr("jmp", variant[x].value)
// Create a Vm an run it until it either ends or loops.
val vm = VM(variant)
while (vm.step() && !vm.hasLooped());
// If the program has ended normally, we found the fix!
if (vm.hasEnded()) return vm.acc
}
error("Could not find a solution for Part B")
}
private class VM(val program: List<Instr>) {
var acc = 0
var pc = 0
private val history = mutableSetOf<Int>()
/** Returns whether the program is still running. False if it has finished. */
fun step(): Boolean {
history.add(pc)
when (program[pc].cmd) {
"nop" -> pc++
"acc" -> {
acc += program[pc].value; pc++
}
"jmp" -> pc += program[pc].value
}
return !hasEnded()
}
/** Whether the instruction to be executed has already been executed before. */
fun hasLooped() = history.contains(pc)
/** Whether this program has terminated normally .*/
fun hasEnded() = pc >= program.size
}
private data class Instr(val cmd: String, val value: Int)
} | apache-2.0 | 63c659c2c4a1f6630775aba4ca010985 | 27.220588 | 83 | 0.595933 | 3.493625 | false | false | false | false |
JavaEden/OrchidCore | languageExtensions/OrchidWritersBlocks/src/main/kotlin/com/eden/orchid/writersblocks/tags/YoutubeTag.kt | 1 | 1705 | package com.eden.orchid.writersblocks.tags
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.compilers.TemplateTag
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import java.time.format.DateTimeParseException
import javax.inject.Inject
@Description("Embed a YouTube video in your page.", name = "YouTube")
class YoutubeTag
@Inject
constructor(
) : TemplateTag("youtube", TemplateTag.Type.Simple, true) {
@Option
@Description("The Youtube video Id.")
lateinit var id: String
@Option
@Description("The start time of the video, in MM:SS format.")
lateinit var start: String
@Option @StringDefault("560")
@Description("The width of the embedded video.")
lateinit var width: String
@Option @StringDefault("315")
@Description("The height of the embedded video.")
lateinit var height: String
override fun parameters(): Array<String> {
return arrayOf("id", "start")
}
public fun getStartSeconds(): Int {
if(start.isNotBlank() && start.contains(":")) {
try {
val time = start.split(":")
if(time.size == 2) {
return (Integer.parseInt(time[0]) * (60)) + (Integer.parseInt(time[1]))
}
else if(time.size == 3) {
return (Integer.parseInt(time[0]) * (60*60)) + (Integer.parseInt(time[1]) * (60)) + (Integer.parseInt(time[2]))
}
} catch (e: DateTimeParseException) {
Clog.e(e.message, e)
}
}
return 0
}
}
| mit | 64f2b9dbca7259a9c0baa7ab5d5115b4 | 30 | 131 | 0.622874 | 4.158537 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/database/models/guild/starboard/StarboardEntry.kt | 1 | 820 | package me.mrkirby153.KirBot.database.models.guild.starboard
import com.mrkirby153.bfs.model.Model
import com.mrkirby153.bfs.model.annotations.AutoIncrementing
import com.mrkirby153.bfs.model.annotations.Column
import com.mrkirby153.bfs.model.annotations.Table
import com.mrkirby153.bfs.model.annotations.Timestamps
import com.mrkirby153.bfs.model.enhancers.TimestampEnhancer
import java.sql.Timestamp
@Table("starboard")
@Timestamps
class StarboardEntry : Model() {
var id = ""
@Column("star_count")
var count = 0L
var hidden = false
@Column("starboard_mid")
var starboardMid: String? = null
@TimestampEnhancer.CreatedAt
@Column("created_at")
var createdAt: Timestamp? = null
@TimestampEnhancer.UpdatedAt
@Column("updated_at")
var updatedAt: Timestamp? = null
} | mit | 5844bc3aa11e86c52b5efb978130b68c | 23.147059 | 60 | 0.75122 | 3.744292 | false | false | false | false |
sedovalx/xodus-entity-browser | entity-browser-app/src/main/kotlin/com/lehvolk/xodus/web/JerseyConfiguration.kt | 1 | 2691 | package com.lehvolk.xodus.web
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.lehvolk.xodus.web.search.SearchQueryException
import javax.ws.rs.ClientErrorException
import javax.ws.rs.InternalServerErrorException
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.ext.ContextResolver
import javax.ws.rs.ext.ExceptionMapper
import javax.ws.rs.ext.Provider
interface WithMessage {
val msg: String
}
class EntityNotFoundException(cause: Throwable, val typeId: Int, val entityId: Long) : RuntimeException(cause), WithMessage {
override val msg: String = "Error getting entity by type '$typeId' and id='$entityId'"
}
class InvalidFieldException(cause: Throwable, val fieldName: String, val fieldValue: String) : RuntimeException(cause), WithMessage {
override val msg: String = "invalid value of property '$fieldName': '$fieldValue'"
}
class XodusRestServerException(cause: Throwable) : InternalServerErrorException(cause), WithMessage {
override val msg = "Internal server error. Getting " +
cause.javaClass.name + ": " +
cause.message + ". Check server log for more details."
}
class XodusRestClientException(cause: Throwable) : RuntimeException(cause), WithMessage {
override val msg = cause.message ?: "UFO error"
}
abstract class AbstractMapper<T> : ExceptionMapper<T>
where T : WithMessage, T : Throwable {
abstract val status: Response.Status
override fun toResponse(exception: T): Response? {
val vo = ServerError(exception.msg)
return Response.status(status).type(MediaType.APPLICATION_JSON).entity(vo).build()
}
}
@Provider
class ServerExceptionMapper : AbstractMapper<XodusRestServerException>() {
override val status: Response.Status
get() = Response.Status.INTERNAL_SERVER_ERROR
}
@Provider
class EntityExceptionMapper : AbstractMapper<EntityNotFoundException>() {
override val status: Response.Status
get() = Response.Status.NOT_FOUND
}
@Provider
class ValidationErrorMapper : AbstractMapper<InvalidFieldException>() {
override val status: Response.Status
get() = Response.Status.BAD_REQUEST
}
@Provider
class JacksonConfigurator : ContextResolver<ObjectMapper> {
val mapper: ObjectMapper = ObjectMapper().apply {
this.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
override fun getContext(type: Class<*>): ObjectMapper {
return mapper
}
}
@Provider
class ClientExceptionMapper : AbstractMapper<XodusRestClientException>() {
override val status = Response.Status.BAD_REQUEST
} | apache-2.0 | d1a90e2e7e7805f73aca5291f5c206b9 | 28.911111 | 133 | 0.749164 | 4.237795 | false | false | false | false |
google/ksp | integration-tests/src/test/resources/psi-cache/test-processor/src/main/kotlin/TestProcessor.kt | 1 | 1319 | import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.validate
class TestProcessor(
val codeGenerator: CodeGenerator,
val logger: KSPLogger
) : SymbolProcessor {
var rounds = 0
override fun process(resolver: Resolver): List<KSAnnotated> {
rounds++
val syms = resolver.getSymbolsWithAnnotation("com.example.Anno").toList()
syms.forEach {
val v = it.validate()
if (rounds == 2 && v == false) {
logger.error("validation failed: $it")
}
}
if (rounds == 1) {
codeGenerator.createNewFile(Dependencies(true), "com.example", "Foo1").use {
it.write("package com.example\n\ninterface Foo1\n".toByteArray())
}
codeGenerator.createNewFile(Dependencies(true), "com.example", "Foo2", "java").use {
it.write("package com.example;\n\npublic interface Foo2{}\n".toByteArray())
}
return syms.toList()
}
return emptyList()
}
}
class TestProcessorProvider : SymbolProcessorProvider {
override fun create(environment: SymbolProcessorEnvironment): SymbolProcessor {
return TestProcessor(environment.codeGenerator, environment.logger)
}
}
| apache-2.0 | 9ca67533abc06b78282ab6d50022364d | 31.975 | 96 | 0.623958 | 4.564014 | false | true | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/util/HtmlCssResource.kt | 1 | 2592 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.util
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.project.Project
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.md.nav.settings.MdRenderingProfile
import com.vladsch.plugin.util.ifElse
import java.util.*
open class HtmlCssResource(
override val providerInfo: HtmlCssResourceProvider.Info // provider info
, val darkCss: String // resource path for dark scheme stylesheet
, val lightCss: String // resource path for light scheme stylesheet
, val layoutCss: String? // resource path for layout stylesheet, optional
) : HtmlResource() {
open val darkCssUrl: String = resourceFileUrl(darkCss, javaClass)
open val lightCssUrl: String = resourceFileUrl(lightCss, javaClass)
open val layoutCssUrl: String? = if (layoutCss == null) null else resourceFileUrl(layoutCss, javaClass)
open fun darkCssUrl(parentDir: String): String {
return resourceFileUrl(darkCss, javaClass)
}
open fun lightCssUrl(parentDir: String): String {
return resourceFileUrl(lightCss, javaClass)
}
open fun layoutCssUrl(parentDir: String): String? {
return if (layoutCss == null) null else resourceFileUrl(layoutCss, javaClass)
}
open val isByScript: Boolean
get() {
val parentInfo = HtmlCssResourceProvider.getFromId(providerInfo.providerId)?.HAS_PARENT ?: true
return parentInfo
}
override fun injectHtmlResource(
project: Project,
applicationSettings: MdApplicationSettings,
renderingProfile: MdRenderingProfile,
injections: ArrayList<InjectHtmlResource?>,
forHtmlExport: Boolean,
dataContext: DataContext
) {
val isDarkTheme = renderingProfile.cssSettings.isDarkTheme
injectCssUrl(injections, true, false, isByScript,
getInjectionUrl(
project,
isDarkTheme.ifElse(darkCssUrl, lightCssUrl),
isDarkTheme.ifElse(darkCss, lightCss),
renderingProfile,
forHtmlExport,
dataContext
)
)
injectCssUrl(injections, true, true, isByScript, getInjectionUrl(project, layoutCssUrl, layoutCss, renderingProfile, forHtmlExport, dataContext))
}
}
| apache-2.0 | dd88b7c722a5afe4ba2d3a6ec19dbdc7 | 41.491803 | 177 | 0.68287 | 4.782288 | false | false | false | false |
jaymell/ip-mapper | src/main/kotlin/com/jaymell/ipmapper/JsonController.kt | 1 | 1286 | package com.jaymell.ipmapper
import com.mongodb.MongoClient
import mu.KLogging
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
@Controller
class JsonController {
companion object : KLogging()
@Autowired
private lateinit var mongo: MongoClient
val dbName = "logger"
val colName = "logs"
@RequestMapping("/json", method = [RequestMethod.GET])
fun handleRequest(@RequestParam(value = "gte", required = false) gteParam: Long?,
@RequestParam(value = "lte", required = false) lteParam: Long?): StreamingResponseBody {
val template = MongoTemplate(mongo, dbName)
return StreamingResponseBody { out ->
queryMongoByDate(template, colName, lteParam, gteParam)
.forEach {
out.write("${com.mongodb.util.JSON.serialize(it)}\n".toByteArray())
}
}
}
} | gpl-3.0 | af159cad802d8142bd3df5921c3f3837 | 33.783784 | 110 | 0.710731 | 4.710623 | false | false | false | false |
android/privacy-sandbox-samples | PrivacySandboxKotlin/client-app/src/main/java/com/example/client/MainActivity.kt | 1 | 11625 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.client
import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.sdksandbox.LoadSdkException
import android.app.sdksandbox.RequestSurfacePackageException
import android.app.sdksandbox.SandboxedSdk
import android.app.sdksandbox.SdkSandboxManager
import android.app.sdksandbox.SdkSandboxManager.EXTRA_DISPLAY_ID
import android.app.sdksandbox.SdkSandboxManager.EXTRA_HEIGHT_IN_PIXELS
import android.app.sdksandbox.SdkSandboxManager.EXTRA_HOST_TOKEN
import android.app.sdksandbox.SdkSandboxManager.EXTRA_SURFACE_PACKAGE
import android.app.sdksandbox.SdkSandboxManager.EXTRA_WIDTH_IN_PIXELS
import android.app.sdksandbox.SdkSandboxManager.SdkSandboxProcessDeathCallback
import android.content.DialogInterface
import android.os.*
import android.text.InputType
import android.util.Log
import android.view.SurfaceControlViewHost.SurfacePackage
import android.view.SurfaceView
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.example.exampleaidllibrary.ISdkApi
import com.example.privacysandbox.client.R
@SuppressLint("NewApi")
class MainActivity : AppCompatActivity() {
/**
* Button to load the SDK to the sandbox.
*/
private lateinit var mLoadSdkButton: Button
/**
* Button to request a SurfacePackage from sandbox which remotely render a webview.
*/
private lateinit var mRequestWebViewButton: Button
/**
* Button to create a file inside sandbox.
*/
private lateinit var mCreateFileButton: Button
/**
* An instance of SdkSandboxManager which contains APIs to communicate with the sandbox.
*/
private lateinit var mSdkSandboxManager: SdkSandboxManager
/**
* The SurfaceView which will be used by the client app to show the SurfacePackage
* going to be rendered by the sandbox.
*/
private lateinit var mClientView: SurfaceView
/**
* This object is going to be set when SDK is successfully loaded. It is a wrapper for the
* public SDK API Binder object defined by SDK by implementing the AIDL file from
* example-aidl-library module.
*/
private lateinit var mSandboxedSdk : SandboxedSdk
private var mSdkLoaded = false
@RequiresApi(api = 33)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mSdkSandboxManager = applicationContext.getSystemService(
SdkSandboxManager::class.java
)
mClientView = findViewById(R.id.rendered_view)
mClientView.setZOrderOnTop(true)
mLoadSdkButton = findViewById(R.id.load_sdk_button)
mRequestWebViewButton = findViewById(R.id.request_webview_button)
mCreateFileButton = findViewById(R.id.create_file_button)
registerLoadCodeProviderButton()
registerRequestWebViewButton()
registerCreateFileButton()
}
/**
* Register the callback action after once mLoadSdkButton got clicked.
*/
@RequiresApi(api = 33)
private fun registerLoadCodeProviderButton() {
mLoadSdkButton.setOnClickListener { _: View? ->
// Register for sandbox death event.
mSdkSandboxManager.addSdkSandboxProcessDeathCallback(
{ obj: Runnable -> obj.run() }, SdkSandboxProcessDeathCallbackImpl())
log("Attempting to load sandbox SDK")
val callback = LoadSdkCallbackImpl()
mSdkSandboxManager.loadSdk(
SDK_NAME, Bundle(), { obj: Runnable -> obj.run() }, callback
)
}
}
/**
* Register the callback action after once mRequestWebViewButton got clicked.
*/
@RequiresApi(api = 33)
private fun registerRequestWebViewButton() {
mRequestWebViewButton.setOnClickListener {
if (!mSdkLoaded) {
makeToast("Please load the SDK first!")
return@setOnClickListener
}
log("Getting SurfacePackage.")
Handler(Looper.getMainLooper()).post {
val params = Bundle()
params.putInt(EXTRA_WIDTH_IN_PIXELS, mClientView.getWidth())
params.putInt(EXTRA_HEIGHT_IN_PIXELS, mClientView.getHeight())
params.putInt(EXTRA_DISPLAY_ID, getDisplay()?.getDisplayId()!!)
params.putBinder(EXTRA_HOST_TOKEN, mClientView.getHostToken())
mSdkSandboxManager.requestSurfacePackage(
SDK_NAME, params, { obj: Runnable -> obj.run() }, RequestSurfacePackageCallbackImpl())
}
}
}
/**
* Register the callback action after once mCreateFileButton got clicked.
*/
@RequiresApi(api = 33)
private fun registerCreateFileButton() {
mCreateFileButton.setOnClickListener { _ ->
if (!mSdkLoaded) {
makeToast("Please load the SDK first!")
return@setOnClickListener
}
log("Creating file inside sandbox.")
// Show dialog to collect the size of storage
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
builder.setTitle("Set size in MB")
val input = EditText(this)
input.setInputType(InputType.TYPE_CLASS_NUMBER)
builder.setView(input)
builder.setPositiveButton("Create", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
var sizeInMb = -1
try {
sizeInMb = Integer.parseInt(input.getText().toString())
} catch (ignore: Exception) {
}
if (sizeInMb <= 0) {
makeToast("Please provide positive integer value")
return
}
val binder: IBinder? = mSandboxedSdk.getInterface()
val sdkApi = ISdkApi.Stub.asInterface(binder)
try {
val response: String = sdkApi.createFile(sizeInMb)
makeToast(response)
} catch (e: RemoteException) {
throw RuntimeException(e)
}
}
})
builder.setNegativeButton("Cancel", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
dialog.cancel()
}
})
builder.show()
}
}
/**
* A callback for tracking events regarding loading an SDK.
*/
@RequiresApi(api = 33)
private inner class LoadSdkCallbackImpl() : OutcomeReceiver<SandboxedSdk, LoadSdkException> {
/**
* This notifies client application that the requested SDK is successfully loaded.
*
* @param sandboxedSdk a [SandboxedSdk] is returned from the sandbox to the app.
*/
@SuppressLint("Override")
override fun onResult(sandboxedSdk: SandboxedSdk) {
log("SDK is loaded")
makeToast("Loaded successfully!")
mSdkLoaded = true
mSandboxedSdk = sandboxedSdk;
}
/**
* This notifies client application that the requested Sdk failed to be loaded.
*
* @param error a [LoadSdkException] containing the details of failing to load the
* SDK.
*/
@SuppressLint("Override")
override fun onError(error: LoadSdkException) {
log("onLoadSdkFailure(" + error.getLoadSdkErrorCode().toString() + "): " + error.message)
makeToast("Load SDK Failed! " + error.message)
}
}
/**
* A callback for tracking Sdk Sandbox process death event.
*/
@RequiresApi(api = 33)
private inner class SdkSandboxProcessDeathCallbackImpl() : SdkSandboxProcessDeathCallback {
/**
* Notifies the client application that the SDK sandbox has died. The sandbox could die for
* various reasons, for example, due to memory pressure on the system, or a crash in the
* sandbox.
*
* The system will automatically restart the sandbox process if it died due to a crash.
* However, the state of the sandbox will be lost - so any SDKs that were loaded previously
* would have to be loaded again, using [SdkSandboxManager.loadSdk] to continue using them.
*/
@SuppressLint("Override")
override fun onSdkSandboxDied() {
makeToast("Sdk Sandbox process died")
}
}
/**
* A callback for tracking a request for a surface package from an SDK.
*/
@RequiresApi(api = 33)
private inner class RequestSurfacePackageCallbackImpl() :
OutcomeReceiver<Bundle?, RequestSurfacePackageException?> {
/**
* This notifies client application that [SurfacePackage]
* is ready to remote render view from the SDK.
*
* @param response a [Bundle] which should contain the key EXTRA_SURFACE_PACKAGE with
* a value of [SurfacePackage] response.
*/
@SuppressLint("Override")
override fun onResult(response: Bundle) {
log("Surface package ready")
makeToast("Surface Package Rendered!")
Handler(Looper.getMainLooper()).post {
log("Setting surface package in the client view")
val surfacePackage: SurfacePackage? = response.getParcelable(
EXTRA_SURFACE_PACKAGE, SurfacePackage::class.java)
mClientView.setChildSurfacePackage(surfacePackage!!)
mClientView.setVisibility(View.VISIBLE)
}
}
/**
* This notifies client application that requesting [SurfacePackage] has failed.
*
* @param error a [RequestSurfacePackageException] containing the details of failing
* to request the surface package.
*/
@SuppressLint("Override")
override fun onError(error: RequestSurfacePackageException) {
log("onSurfacePackageError" + error.getRequestSurfacePackageErrorCode()
.toString() + "): "
+ error.message)
makeToast("Surface Package Failed! " + error.message)
}
}
private fun makeToast(message: String) {
runOnUiThread { Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() }
}
private fun log(message: String) {
Log.e(TAG, message)
}
companion object {
private const val TAG = "SandboxClient"
/**
* Name of the SDK to be loaded.
*/
private const val SDK_NAME = "com.example.privacysandbox.provider"
}
}
| apache-2.0 | 0c974faa5742e9abdb61f333f6c0092b | 37.75 | 106 | 0.637677 | 4.913356 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsReassignImmutableInspection.kt | 4 | 1365 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import org.rust.ide.annotator.fixes.AddMutableFix
import org.rust.lang.core.psi.RsBinaryExpr
import org.rust.lang.core.psi.RsExpr
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.AssignmentOp
import org.rust.lang.core.psi.ext.operatorType
import org.rust.lang.core.types.isMutable
class RsReassignImmutableInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : RsVisitor() {
override fun visitBinaryExpr(expr: RsBinaryExpr) {
if (expr.isAssignBinaryExpr() && !expr.left.isMutable) {
registerProblem(holder, expr, expr.left)
}
}
}
private fun registerProblem(holder: ProblemsHolder, expr: RsExpr, nameExpr: RsExpr) {
val fix = AddMutableFix.createIfCompatible(nameExpr).let { if (it == null) emptyArray() else arrayOf(it) }
holder.registerProblem(expr, "Re-assignment of immutable variable [E0384]", *fix)
}
}
private fun RsExpr?.isAssignBinaryExpr(): Boolean {
val op = this as? RsBinaryExpr ?: return false
return op.operatorType is AssignmentOp
}
| mit | 2ce7946e5a8064ecdc1a2d47f134c0d3 | 34.921053 | 114 | 0.70989 | 4.099099 | false | false | false | false |
TheFallOfRapture/Morph | src/main/kotlin/com/morph/engine/graphics/shaders/PresetUniforms.kt | 2 | 11228 | package com.morph.engine.graphics.shaders
import com.morph.engine.core.Camera
import com.morph.engine.graphics.Color
import com.morph.engine.graphics.Framebuffer
import com.morph.engine.graphics.Texture
import com.morph.engine.graphics.components.Emitter
import com.morph.engine.graphics.components.RenderData
import com.morph.engine.graphics.components.light.Light
import com.morph.engine.graphics.components.light.SceneLight
import com.morph.engine.math.Matrix4f
import com.morph.engine.physics.components.Transform
class BasicTexturedShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diffuse", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
setUniformMatrix4fv("mvp", camera.modelViewProjection * mvp)
setUniform1i("diffuse", 0)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
}
class GUIShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diffuse", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
setUniformMatrix4fv("mvp", screen * mvp)
setUniform1i("diffuse", 0)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
}
class GUITextShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diffuse", shader)
addUniform("diffuseColor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
setUniformMatrix4fv("mvp", screen * mvp)
setUniform1i("diffuse", 0)
setUniform3f("diffuseColor", data.tint)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
}
class GUITintShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diffuse", shader)
addUniform("diffuseColor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
setUniformMatrix4fv("mvp", screen * mvp)
setUniform1i("diffuse", 0)
setUniform4f("diffuseColor", data.tint)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
}
class GUITintTransitionShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diff1: Texture
private lateinit var diff2: Texture
private lateinit var diffuseColor: Color
private var lerpFactor: Float = 0f
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diff1", shader)
addUniform("diff2", shader)
addUniform("diffuseColor", shader)
addUniform("lerpFactor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
this.mvp = t.transformationMatrix
this.diff1 = data.getTexture(0)
this.diff2 = data.getTexture(1)
this.diffuseColor = data.tint
this.lerpFactor = data.lerpFactor
setUniformMatrix4fv("mvp", screen * mvp)
setUniform1i("diff1", 0)
setUniform1i("diff2", 1)
setUniform4f("diffuseColor", diffuseColor)
setUniform1f("lerpFactor", lerpFactor)
diff1.bind(0)
diff2.bind(1)
}
override fun unbind(t: Transform, data: RenderData) {
diff1.unbind()
diff2.unbind()
}
}
class GUITransitionShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diff1: Texture
private lateinit var diff2: Texture
private var lerpFactor: Float = 0f
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diff1", shader)
addUniform("diff2", shader)
addUniform("lerpFactor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
this.mvp = t.transformationMatrix
this.diff1 = data.getTexture(0)
this.diff2 = data.getTexture(1)
this.lerpFactor = data.lerpFactor
setUniformMatrix4fv("mvp", screen * mvp)
setUniform1i("diff1", 0)
setUniform1i("diff2", 1)
setUniform1f("lerpFactor", lerpFactor)
diff1.bind(0)
diff2.bind(1)
}
override fun unbind(t: Transform, data: RenderData) {
diff1.unbind()
diff2.unbind()
}
}
class TextShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diffuse", shader)
addUniform("diffuseColor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
setUniformMatrix4fv("mvp", camera.modelViewProjection * mvp)
setUniform1i("diffuse", 0)
setUniform3f("diffuseColor", data.tint)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
}
class TintShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diffuse", shader)
addUniform("diffuseColor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
setUniformMatrix4fv("mvp", camera.modelViewProjection * mvp)
setUniform1i("diffuse", 0)
setUniform4f("diffuseColor", data.tint)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
}
class TransitionShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diff1: Texture
private lateinit var diff2: Texture
private var lerpFactor: Float = 0f
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("diff1", shader)
addUniform("diff2", shader)
addUniform("lerpFactor", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
this.mvp = t.transformationMatrix
this.diff1 = data.getTexture(0)
this.diff2 = data.getTexture(1)
this.lerpFactor = data.lerpFactor
setUniformMatrix4fv("mvp", camera.modelViewProjection * mvp)
setUniform1i("diff1", 0)
setUniform1i("diff2", 1)
setUniform1f("lerpFactor", lerpFactor)
diff1.bind(0)
diff2.bind(1)
}
override fun unbind(t: Transform, data: RenderData) {
diff1.unbind()
diff2.unbind()
}
}
class BasicLightShaderUniforms : Uniforms() {
private lateinit var mvp: Matrix4f
private lateinit var diffuse: Texture
private var normal: Texture? = null
override fun defineUniforms(shader: Int) {
addUniform("mvp", shader)
addUniform("world", shader)
addUniform("diffuse", shader)
addUniform("normal", shader)
addUniform("diffuseColor", shader)
addUniform("lightPosition", shader)
for (i in 0..9) {
addUniform("lights[$i].brightness", shader)
addUniform("lights[$i].color", shader)
addUniform("lights[$i].position", shader)
}
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
mvp = t.transformationMatrix
diffuse = data.getTexture(0)
normal = data.getTexture(1)
setUniformMatrix4fv("mvp", camera.modelViewProjection * mvp)
setUniformMatrix4fv("world", camera.transformationMatrix * mvp)
setUniform1i("diffuse", 0)
setUniform1i("normal", 1)
setUniform4f("diffuseColor", data.tint)
lights.take(10).mapIndexed { index, light ->
setUniform1f("lights[$index].brightness", light.brightness)
setUniform3f("lights[$index].color", light.color)
if (light is SceneLight) setUniform3f("lights[$index].position", camera.transformationMatrix * light.localPosition)
}
diffuse.bind(0)
normal?.bind(1)
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
normal?.unbind()
}
}
class InstancedShaderUniforms : Uniforms() {
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("diffuse", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
diffuse = data.getTexture(0)
setUniform1i("diffuse", 0)
diffuse.bind()
}
fun setUniforms(emitter : Emitter) {
diffuse = emitter.texture
setUniform1i("diffuse", 0)
diffuse.bind()
}
override fun unbind(t: Transform, data: RenderData) {
diffuse.unbind()
}
fun unbind() {
diffuse.unbind()
}
}
class FramebufferShaderUniforms : Uniforms() {
private lateinit var diffuse: Texture
override fun defineUniforms(shader: Int) {
addUniform("diffuse", shader)
}
override fun setUniforms(t: Transform, data: RenderData, camera: Camera, screen: Matrix4f, lights: List<Light>) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun unbind(t: Transform, data: RenderData) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun setUniforms(framebuffer : Framebuffer) {
setUniform1i("diffuse", 0)
framebuffer.bindTexture(0)
}
fun unbind(framebuffer : Framebuffer) {
framebuffer.unbindTextures()
}
}
| mit | c10e9580e5b018f4541e5d0ddfedabc3 | 29.101877 | 127 | 0.654079 | 4.141645 | false | false | false | false |
camdenorrb/KPortals | src/main/kotlin/me/camdenorrb/kportals/position/Position.kt | 1 | 1533 | package me.camdenorrb.kportals.position
//import com.sk89q.worldedit.math.BlockVector3
/**
* Created by camdenorrb on 3/20/17.
*/
// TODO: Just use vectors like a normal huemin, maybe with type alias
/*
data class Position(val x: Double = 0.0, val y: Double = 0.0, val z: Double = 0.0, val yaw: Float = 0.0F, val pitch: Float = 0.0F, val worldName: String = "world") {
constructor(x: Int = 0, y: Int = 0, z: Int = 0, worldName: String = "world") : this(x.toDouble(), y.toDouble(), z.toDouble(), worldName = worldName)
constructor(loc: Location) : this(loc.x, loc.y, loc.z, loc.yaw, loc.pitch, loc.world!!.name)
constructor(vec: BlockVector3, worldName: String = "world") : this(vec.x, vec.y, vec.z, worldName = worldName)
operator fun rangeTo(other: Position) = PositionProgression(this, other)
fun getWorld() = Bukkit.getWorld(worldName)!!
fun round() = Position(floor(x), floor(y), floor(z))
fun equalCords(pos2: Position): Boolean = x == pos2.x && z == pos2.z && y == pos2.y
fun toLocation(world: World): Location = Location(world, x, y, z, yaw, pitch)
fun toLocation(): Location = KPortals.instance.server.getWorld(worldName)?.let { toLocation(it) } ?: error("Couldn't convert pos to loc")
fun randomSafePos(radius: Int): Position {
val randomX = (x - (Random.nextInt(radius * 2) - radius)).toInt()
val randomZ = (z - (Random.nextInt(radius * 2) - radius)).toInt()
val randomY = getWorld().getHighestBlockYAt(randomX, randomZ)
return Position(randomX, randomY, randomZ, worldName)
}
}*/ | mit | 74babdf4d1a4c9787a411e4ab2692c23 | 34.674419 | 165 | 0.680365 | 3.09697 | false | false | false | false |
requery/requery | requery-android/src/main/java/io/requery/android/QueryRecyclerAdapter.kt | 1 | 6228 | /*
* Copyright 2018 requery.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.requery.android
import android.database.Cursor
import android.os.Handler
import androidx.recyclerview.widget.RecyclerView
import io.requery.meta.EntityModel
import io.requery.meta.Type
import io.requery.proxy.EntityProxy
import io.requery.query.Result
import io.requery.sql.EntityDataStore
import io.requery.sql.ResultSetIterator
import io.requery.util.function.Function
import java.io.Closeable
import java.sql.SQLException
import java.util.concurrent.Callable
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
/**
* An implementation of [android.support.v7.widget.RecyclerView.Adapter] specifically for
* displaying items from a [EntityDataStore] query. To use extend this class and implement
* [.performQuery] and [.onBindViewHolder].
*
* @param <E> entity element type
* @param <VH> view holder type
*
* @author Nikhil Purushe
*/
abstract class QueryRecyclerAdapter<E, VH : RecyclerView.ViewHolder>
@JvmOverloads protected constructor(type: Type<E>? = null) : RecyclerView.Adapter<VH>(), Closeable {
private val handler: Handler
private val proxyProvider: Function<E, EntityProxy<E>>?
private var createdExecutor: Boolean = false
private var executor: ExecutorService? = null
private var queryFuture: Future<Result<E>>? = null
/**
* @return the underlying iterator being used or null if none
*/
protected var iterator: ResultSetIterator<E>? = null
/**
* Creates a new adapter instance.
*
* @param model database entity model
* @param type entity class type
*/
protected constructor(model: EntityModel, type: Class<E>) : this(model.typeOf<E>(type))
init {
setHasStableIds(true)
proxyProvider = type?.proxyProvider
handler = Handler()
}
/**
* Call this to clean up the underlying result.
*/
override fun close() {
queryFuture?.cancel(true)
iterator?.close()
iterator = null
setExecutor(null)
}
/**
* Sets the [Executor] used for running the query off the main thread.
*
* @param executor ExecutorService to use for the background query.
*/
fun setExecutor(executor: ExecutorService?) {
if (createdExecutor && this.executor != null) {
this.executor!!.shutdown()
}
this.executor = executor
}
/**
* Sets the results the adapter should display.
*
* @param iterator result set iterator
*/
fun setResult(iterator: ResultSetIterator<E>) {
if (this.iterator != null) {
this.iterator!!.close()
}
this.iterator = iterator
notifyDataSetChanged()
}
/**
* Schedules the query to be run in the background. After completion
* [.setResult] will be called to update the contents of the adapter.
* Note if an [Executor] was not specified one will be created automatically to run the
* query.
*/
fun queryAsync() {
if (this.executor == null) {
this.executor = Executors.newSingleThreadExecutor()
createdExecutor = true
}
if (queryFuture != null && !queryFuture!!.isDone) {
queryFuture!!.cancel(true)
}
queryFuture = executor!!.submit(Callable {
val result = performQuery()
// main work happens here
val iterator = result.iterator() as ResultSetIterator<E>
handler.post { setResult(iterator) }
result
})
}
/**
* Implement this method with your query operation. Note this method is executed on a
* background thread not the main thread.
*
* @see .setExecutor
* @return query result set
*/
abstract fun performQuery(): Result<E>
override fun onBindViewHolder(holder: VH, position: Int) {
val item = iterator!!.get(position)
onBindViewHolder(item, holder, position)
}
/**
* Called to display the data at the specified position for the given item. The item is
* retrieved from the result iterator.
*
* @param item entity element to bind to the view
* @param holder view holder to be updated
* @param position position index of the view
*/
abstract fun onBindViewHolder(item: E?, holder: VH, position: Int)
override fun getItemId(position: Int): Long {
val item = iterator!!.get(position) ?: throw IllegalStateException()
var key: Any? = null
if (proxyProvider != null) {
val proxy = proxyProvider.apply(item)
key = proxy.key()
}
return (if (key == null) item.hashCode() else key.hashCode()).toLong()
}
override fun getItemCount(): Int {
if (iterator == null) {
return 0
}
try {
val cursor = iterator!!.unwrap(Cursor::class.java)
return cursor.count
} catch (e: SQLException) {
throw RuntimeException(e)
}
}
override fun getItemViewType(position: Int): Int {
val item = iterator!!.get(position)
return getItemViewType(item)
}
/**
* Return the view type of the item.
*
* @param item being checked
* @return integer identifying the type of the view
*/
protected fun getItemViewType(item: E?): Int {
return 0
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
close()
setExecutor(null)
}
}
| apache-2.0 | 6b190610ae6b3e0c6461beaecc3ed81d | 29.985075 | 100 | 0.649326 | 4.545985 | false | false | false | false |
daneko/android-inapp-library | library/src/main/kotlin/com/github/daneko/android/iab/Util.kt | 1 | 1238 | package com.github.daneko.android.iab
import com.github.daneko.android.iab.exception.IabResponseException
import com.github.daneko.android.iab.model.GooglePlayResponse
import fj.data.Validation
import rx.Observable
internal fun <E : Throwable, T> fromValidation(valid: Validation<E, T>): Observable<T> =
Observable.create<T> { subs ->
valid.validation(
{ e -> subs.onError(e) },
{ s ->
subs.onNext(s)
subs.onCompleted()
}
)
}
internal fun checkGooglePlayResponse(
response: GooglePlayResponse,
cause: Exception = Exception()): Observable<GooglePlayResponse> =
if (!response.isSuccess) {
val message = """not success response
response: code:${response.code} / desc:${response.description}
response Bundle: $response
"""
Observable.error<GooglePlayResponse>(IabResponseException(response, message, cause))
} else {
Observable.just(response)
}
internal fun <A, E, B> fj.data.Validation<E, A>.failMap(f: (E) -> B): fj.data.Validation<B, A> =
fj.data.Validation.validation(toEither().left().map { f(it) })
| mit | 4effc8f29b17f25d0cc126f66de39139 | 36.515152 | 96 | 0.610662 | 4.072368 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/api/AppRxAdapterFactory.kt | 1 | 3682 | package lt.vilnius.tvarkau.api
import com.google.gson.JsonParseException
import io.reactivex.Single
import io.reactivex.functions.Function
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.HttpException
import retrofit2.Retrofit
import timber.log.Timber
import java.lang.reflect.Type
class AppRxAdapterFactory(
private val factory: CallAdapter.Factory
) : CallAdapter.Factory() {
@Suppress("UNCHECKED_CAST")
override fun get(returnType: Type, annotations: Array<out Annotation>, retrofit: Retrofit): CallAdapter<*, *>? {
val original = factory.get(returnType, annotations, retrofit) ?: return null
return CallAdapterDecorator(original as CallAdapter<Any, *>)
}
private inner class CallAdapterDecorator(val decorated: CallAdapter<Any, *>) : CallAdapter<Any, Any> {
override fun responseType() = decorated.responseType()
override fun adapt(call: Call<Any>): Any {
val orig = decorated.adapt(call)!!
return when (orig) {
is Single<*> -> wrapSingle(orig)
else -> throw IllegalArgumentException("Unsupported type of call " + orig.toString())
}
}
private fun wrapSingle(orig: Single<*>): Single<BaseResponse> {
return orig
.cast(BaseResponse::class.java)
.onErrorResumeNext(mapHttpExceptionToBaseResponse())
.flatMap(throwOnApiError())
.doOnError { processError(it) }
}
private fun mapHttpExceptionToBaseResponse(): (Throwable) -> Single<out BaseResponse> {
return {
if (it is HttpException) {
try {
val response = ApiError.extractBaseResponse(it)
if (response.isStatusOk) {
throw it
}
Single.just(response)
} catch (e: Exception) {
Single.error<BaseResponse>(ApiError.of(e))
}
} else {
Single.error<BaseResponse>(ApiError(it))
}
}
}
private fun processError(error: Throwable) {
val apiError = ApiError.of(error)
logError(apiError)
}
private fun throwOnApiError(): Function<BaseResponse, Single<BaseResponse>> {
return Function { response ->
if (response.isStatusOk) {
Single.just(response)
} else {
Single.error(ApiError(response))
}
}
}
private fun logError(error: ApiError) {
when (error.errorType) {
ApiError.ErrorType.SERVER -> {
val response = error.retrofitResponse!!
Timber.e(
error,
"[${response.raw().request().url()}] " +
"Server error: ${response.code()}, " +
"Reason: ${response.message()}"
)
}
ApiError.ErrorType.VALIDATION -> error.validationErrors.forEach { validationError ->
Timber.e(error, validationError.toString())
}
ApiError.ErrorType.API -> {
Timber.e(error, error.message)
}
ApiError.ErrorType.SYSTEM -> {
if (error.cause is JsonParseException) {
Timber.e(error.message, error)
}
}
}
}
}
}
| mit | 66d804132ceddb4840c4f03aef7da569 | 35.455446 | 116 | 0.521456 | 5.454815 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/ui/reblog/ReblogViewModel.kt | 1 | 1177 | package com.nutrition.express.ui.reblog
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.nutrition.express.model.api.repo.ReblogRepo
import java.util.*
class ReblogViewModel : ViewModel() {
private val reblogRepo = ReblogRepo(viewModelScope.coroutineContext)
private val _reblogData = MutableLiveData<ReblogRequest>()
val reblogResult = _reblogData.switchMap {
val hashMap = HashMap<String, String>(4)
hashMap["type"] = it.blogType
hashMap["id"] = it.blogId
hashMap["reblog_key"] = it.blogkey
if (!it.comment.isNullOrEmpty()) {
hashMap["comment"] = it.comment
}
reblogRepo.reblogPost(it.blogName, hashMap)
}
fun reblog(blogName: String, blogId: String, blogkey: String, blogType: String, comment: String?) {
_reblogData.value = ReblogRequest(blogName, blogId, blogkey, blogType, comment)
}
data class ReblogRequest(val blogName: String, val blogId: String, val blogkey: String,
val blogType: String, val comment: String?)
} | apache-2.0 | 0544d6fb83a57c9cbbd5902d19f21028 | 38.266667 | 103 | 0.700085 | 4.327206 | false | false | false | false |
Aidanvii7/Toolbox | delegates-observable-lifecycle/src/main/java/com/aidanvii/toolbox/delegates/observable/lifecycle/LifecycleDecorator.kt | 1 | 2020 | package com.aidanvii.toolbox.delegates.observable.lifecycle
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.aidanvii.toolbox.arch.lifecycle.DefaultLifecycleObserver
import com.aidanvii.toolbox.delegates.observable.AfterChange
import com.aidanvii.toolbox.delegates.observable.ObservableProperty
abstract class LifecycleDecorator<ST, TT>(
private val decorated: ObservableProperty<ST, TT>,
lifecycle: Lifecycle
) : ObservableProperty<ST, TT> by decorated, DefaultLifecycleObserver {
protected var latestValue: TT? = null
init {
lifecycle.addObserver(this)
decorated.afterChangeObservers += { property, oldValue, newValue ->
latestValue = newValue
afterChangeObservers.forEach { it(property, oldValue, newValue) }
}
}
override val afterChangeObservers = mutableSetOf<AfterChange<TT>>()
override fun onCreate(owner: LifecycleOwner) = onLifeCycleEvent(
state = owner.lifecycle.currentState,
event = Lifecycle.Event.ON_CREATE
)
override fun onResume(owner: LifecycleOwner) = onLifeCycleEvent(
state = owner.lifecycle.currentState,
event = Lifecycle.Event.ON_RESUME
)
override fun onStart(owner: LifecycleOwner) = onLifeCycleEvent(
state = owner.lifecycle.currentState,
event = Lifecycle.Event.ON_START
)
override fun onPause(owner: LifecycleOwner) = onLifeCycleEvent(
state = owner.lifecycle.currentState,
event = Lifecycle.Event.ON_PAUSE
)
override fun onStop(owner: LifecycleOwner) = onLifeCycleEvent(
state = owner.lifecycle.currentState,
event = Lifecycle.Event.ON_STOP
)
override fun onDestroy(owner: LifecycleOwner) = onLifeCycleEvent(
state = owner.lifecycle.currentState,
event = Lifecycle.Event.ON_DESTROY
).also {
owner.lifecycle.removeObserver(this)
}
abstract fun onLifeCycleEvent(state: Lifecycle.State, event: Lifecycle.Event)
} | apache-2.0 | 2a97e9f48c92bb0508878885eff1d567 | 33.254237 | 81 | 0.719802 | 4.821002 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/bus_stop_ref/AddBusStopRef.kt | 1 | 1599 | package de.westnordost.streetcomplete.quests.bus_stop_ref
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.quest.NoCountriesExcept
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
class AddBusStopRef : OsmFilterQuestType<BusStopRefAnswer>() {
override val elementFilter = """
nodes with
(
(public_transport = platform and ~bus|trolleybus|tram ~ yes)
or
(highway = bus_stop and public_transport != stop_position)
)
and !ref and noref != yes and ref:signed != no
"""
override val enabledInCountries = NoCountriesExcept("US", "CA", "JE")
override val commitMessage = "Determine bus/tram stop ref"
override val wikiLink = "Tag:public_transport=platform"
override val icon = R.drawable.ic_quest_bus_stop_name
override val questTypeAchievements = listOf(PEDESTRIAN)
override fun getTitle(tags: Map<String, String>) =
if (tags["tram"] == "yes")
R.string.quest_tramStopRef_title
else
R.string.quest_busStopRef_title
override fun createForm() = AddBusStopRefForm()
override fun applyAnswerTo(answer: BusStopRefAnswer, changes: StringMapChangesBuilder) {
when(answer) {
is NoBusStopRef -> changes.add("ref:signed", "no")
is BusStopRef -> changes.add("ref", answer.ref)
}
}
}
| gpl-3.0 | a3ddb0f445ac26c72d79645eabdb9cb1 | 37.071429 | 92 | 0.697936 | 4.241379 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/main/java/org/wordpress/android/fluxc/example/ui/customer/search/WooCustomersListItemDataSource.kt | 2 | 5089 | package org.wordpress.android.fluxc.example.ui.customer.search
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.example.MainExampleActivity
import org.wordpress.android.fluxc.generated.ListActionBuilder
import org.wordpress.android.fluxc.model.LocalOrRemoteId.RemoteId
import org.wordpress.android.fluxc.model.customer.WCCustomerListDescriptor
import org.wordpress.android.fluxc.model.customer.WCCustomerModel
import org.wordpress.android.fluxc.model.list.datasource.ListItemDataSourceInterface
import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooResult
import org.wordpress.android.fluxc.store.ListStore.FetchedListItemsPayload
import org.wordpress.android.fluxc.store.ListStore.ListError
import org.wordpress.android.fluxc.store.ListStore.ListErrorType.GENERIC_ERROR
import org.wordpress.android.fluxc.store.WCCustomerStore
import javax.inject.Inject
const val PAGE_SIZE = 15
class WooCustomersListItemDataSource @Inject constructor(
private val store: WCCustomerStore,
private val dispatcher: Dispatcher,
private val activity: MainExampleActivity
) : ListItemDataSourceInterface<WCCustomerListDescriptor, Long, CustomerListItemType> {
private val coroutineScope = CoroutineScope(Dispatchers.Main)
override fun getItemsAndFetchIfNecessary(
listDescriptor: WCCustomerListDescriptor,
itemIdentifiers: List<Long>
): List<CustomerListItemType> {
val storedCustomers = store.getCustomerByRemoteIds(listDescriptor.site, itemIdentifiers)
coroutineScope.launch {
val remoteIdToFetch = itemIdentifiers - storedCustomers.map { it.remoteCustomerId }
if (remoteIdToFetch.isEmpty()) return@launch
val payload = store.fetchCustomersByIdsAndCache(
site = listDescriptor.site,
pageSize = PAGE_SIZE,
remoteCustomerIds = remoteIdToFetch
)
if (payload.error == null) {
val listTypeIdentifier = WCCustomerListDescriptor.calculateTypeIdentifier(listDescriptor.site.id)
dispatcher.dispatch(ListActionBuilder.newListDataInvalidatedAction(listTypeIdentifier))
}
}
return itemIdentifiers.map { remoteId ->
val customer = storedCustomers.firstOrNull { it.remoteCustomerId == remoteId }
if (customer == null) {
CustomerListItemType.LoadingItem(remoteId)
} else {
CustomerListItemType.CustomerItem(
remoteCustomerId = customer.remoteCustomerId,
firstName = customer.firstName,
lastName = customer.lastName,
email = customer.email,
role = customer.role
)
}
}
}
override fun getItemIdentifiers(
listDescriptor: WCCustomerListDescriptor,
remoteItemIds: List<RemoteId>,
isListFullyFetched: Boolean
): List<Long> = remoteItemIds.map { it.value }
override fun fetchList(listDescriptor: WCCustomerListDescriptor, offset: Long) {
coroutineScope.launch {
activity.prependToLog("Fetching customers with offset $offset")
val payload = store.fetchCustomers(
offset = offset,
pageSize = PAGE_SIZE,
site = listDescriptor.site,
searchQuery = listDescriptor.searchQuery,
email = listDescriptor.email,
role = listDescriptor.role,
remoteCustomerIds = listDescriptor.remoteCustomerIds,
excludedCustomerIds = listDescriptor.excludedCustomerIds
)
when {
payload.isError -> {
activity.prependToLog("couldn't fetch customers ${payload.error}")
}
payload.model.isNullOrEmpty() -> {
activity.prependToLog("Customers list is empty")
}
else -> {
activity.prependToLog("Fetched ${payload.model!!.size} customers")
}
}
dispatchEventWhenFetched(listDescriptor, payload, offset)
}
}
private fun dispatchEventWhenFetched(
listDescriptor: WCCustomerListDescriptor,
payload: WooResult<List<WCCustomerModel>>,
offset: Long
) {
dispatcher.dispatch(ListActionBuilder.newFetchedListItemsAction(FetchedListItemsPayload(
listDescriptor = listDescriptor,
remoteItemIds = payload.model?.map { it.remoteCustomerId } ?: emptyList(),
loadedMore = offset > 0,
canLoadMore = payload.model?.size == PAGE_SIZE,
error = payload.error?.let { fetchError ->
ListError(type = GENERIC_ERROR, message = fetchError.message)
}
)))
}
}
| gpl-2.0 | daabbc5bf5ad85ce42d3137d3e4b5aca | 43.252174 | 113 | 0.652191 | 5.356842 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/GameCollectionItemFragment.kt | 1 | 18757 | package com.boardgamegeek.ui
import android.content.Context
import android.os.Bundle
import android.view.*
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.os.bundleOf
import androidx.core.view.children
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentGameCollectionItemBinding
import com.boardgamegeek.entities.CollectionItemEntity
import com.boardgamegeek.entities.Status
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract.Collection
import com.boardgamegeek.provider.BggContract.Companion.INVALID_ID
import com.boardgamegeek.ui.dialog.EditCollectionTextDialogFragment
import com.boardgamegeek.ui.dialog.PrivateInfoDialogFragment
import com.boardgamegeek.ui.viewmodel.GameCollectionItemViewModel
import com.boardgamegeek.ui.widget.TextEditorView
class GameCollectionItemFragment : Fragment() {
private var _binding: FragmentGameCollectionItemBinding? = null
private val binding get() = _binding!!
private var gameId = INVALID_ID
private var collectionId = INVALID_ID
private var internalId = INVALID_ID.toLong()
private var isInEditMode = false
private var isDirty = false
private val viewModel by activityViewModels<GameCollectionItemViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
gameId = arguments?.getInt(KEY_GAME_ID, INVALID_ID) ?: INVALID_ID
collectionId = arguments?.getInt(KEY_COLLECTION_ID, INVALID_ID) ?: INVALID_ID
}
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentGameCollectionItemBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
listOf(
binding.wantToBuyView,
binding.preorderedView,
binding.ownView,
binding.wantToPlayView,
binding.previouslyOwnedView,
binding.wantInTradeView,
binding.forTradeView,
binding.wishlistView
).forEach {
it.setOnCheckedChangeListener { view, _ ->
if (view.isVisible && isInEditMode) {
if (view === binding.wishlistView) {
binding.wishlistPriorityView.isEnabled = binding.wishlistView.isChecked
}
updateStatuses()
}
}
}
binding.wishlistPriorityView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (binding.wishlistPriorityView.isVisible && binding.wishlistPriorityView.isEnabled && binding.wishlistView.isChecked && isInEditMode) {
updateStatuses()
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
binding.wishlistPriorityView.adapter = WishlistPriorityAdapter(requireContext())
binding.commentView.setOnClickListener {
onTextEditorClick(binding.commentView, Collection.Columns.COMMENT, Collection.Columns.COMMENT_DIRTY_TIMESTAMP)
}
binding.privateInfoCommentView.setOnClickListener {
onTextEditorClick(binding.privateInfoCommentView, Collection.Columns.PRIVATE_INFO_COMMENT, Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP)
}
binding.wishlistCommentView.setOnClickListener {
onTextEditorClick(binding.wishlistCommentView, Collection.Columns.WISHLIST_COMMENT, Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP)
}
binding.conditionView.setOnClickListener {
onTextEditorClick(binding.conditionView, Collection.Columns.CONDITION, Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP)
}
binding.wantPartsView.setOnClickListener {
onTextEditorClick(binding.wantPartsView, Collection.Columns.WANTPARTS_LIST, Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP)
}
binding.hasPartsView.setOnClickListener {
onTextEditorClick(binding.hasPartsView, Collection.Columns.HASPARTS_LIST, Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP)
}
binding.privateInfoEditContainer.setOnClickListener {
val privateInfoDialogFragment = PrivateInfoDialogFragment.newInstance(
binding.editPrivateInfoView.getTag(R.id.priceCurrencyView).toString(),
binding.editPrivateInfoView.getTag(R.id.priceView) as? Double,
binding.editPrivateInfoView.getTag(R.id.currentValueCurrencyView).toString(),
binding.editPrivateInfoView.getTag(R.id.currentValueView) as? Double,
binding.editPrivateInfoView.getTag(R.id.quantityView) as? Int,
binding.editPrivateInfoView.getTag(R.id.acquisitionDateView) as? Long,
binding.editPrivateInfoView.getTag(R.id.acquiredFromView).toString(),
binding.editPrivateInfoView.getTag(R.id.inventoryLocationView).toString()
)
this.showAndSurvive(privateInfoDialogFragment)
}
viewModel.isEditMode.observe(viewLifecycleOwner) {
isInEditMode = it
bindVisibility()
}
viewModel.swatch.observe(viewLifecycleOwner) {
it?.let { swatch ->
listOf(binding.privateInfoHeader, binding.wishlistHeader, binding.tradeHeader, binding.privateInfoHintView).forEach { view ->
view.setTextColor(swatch.rgb)
}
listOf(
binding.commentView,
binding.privateInfoCommentView,
binding.wishlistCommentView,
binding.conditionView,
binding.wantPartsView,
binding.hasPartsView
).forEach { view ->
view.setHeaderColor(swatch)
}
}
}
viewModel.item.observe(viewLifecycleOwner) {
it?.let { (status, data, message) ->
when (status) {
Status.REFRESHING -> binding.progressView.show()
Status.ERROR -> {
showError(message)
binding.progressView.hide()
}
Status.SUCCESS -> {
internalId = data?.internalId ?: INVALID_ID.toLong()
isDirty = data?.isDirty ?: false
if (data != null) {
updateUi(data)
} else {
showError(getString(R.string.invalid_collection_status))
}
binding.progressView.hide()
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun showError(message: String) {
binding.invalidStatusView.text = message
binding.invalidStatusView.isVisible = true
binding.mainContainer.isVisible = false
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.game_collection_fragment, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
menu.findItem(R.id.menu_discard).isVisible = !isInEditMode && isDirty
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_discard -> {
requireActivity().createDiscardDialog(R.string.collection_item, R.string.keep, isNew = false, finishActivity = false) {
viewModel.reset()
}.show()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun bindVisibility() {
// show edit containers only when in edit mode
listOf(
binding.statusEditContainer,
binding.privateInfoEditContainer,
binding.wishlistEditContainer,
binding.tradeEditContainer
).forEach { view ->
view.isVisible = isInEditMode
}
binding.personalRatingView.enableEditMode(isInEditMode)
binding.commentView.enableEditMode(isInEditMode)
binding.privateInfoCommentView.enableEditMode(isInEditMode)
binding.wishlistCommentView.enableEditMode(isInEditMode)
binding.conditionView.enableEditMode(isInEditMode)
binding.wantPartsView.enableEditMode(isInEditMode)
binding.hasPartsView.enableEditMode(isInEditMode)
listOf(binding.statusView, binding.viewPrivateInfoView, binding.wishlistStatusView, binding.tradeStatusView).forEach { view ->
view.isVisible = if (isInEditMode) false else getVisibleTag(view)
}
val readonlyContainers = listOf(binding.mainContainer, binding.privateInfoContainer, binding.wishlistContainer, binding.tradeContainer)
readonlyContainers.forEach { view -> setVisibilityByChildren(view) }
//binding.invalidStatusView.isVisible = readonlyContainers.none { it.isVisible }
}
private fun updateStatuses() {
val statuses = listOf(
binding.wantToBuyView,
binding.preorderedView,
binding.ownView,
binding.wantToPlayView,
binding.previouslyOwnedView,
binding.wantInTradeView,
binding.forTradeView,
binding.wishlistView
).filter {
it.isChecked
}.filterNot {
(it.tag as? String).isNullOrBlank()
}.map {
it.tag as String
}
val wishlistPriority = if (binding.wishlistView.isChecked) binding.wishlistPriorityView.selectedItemPosition + 1 else 0
viewModel.updateStatuses(statuses, wishlistPriority)
}
private fun onTextEditorClick(view: TextEditorView, textColumn: String, timestampColumn: String) {
// TODO refactor to use view model, not direct data access
showAndSurvive(
EditCollectionTextDialogFragment.newInstance(
view.headerText,
view.contentText,
textColumn,
timestampColumn
)
)
}
private fun updateUi(item: CollectionItemEntity) {
bindMainContainer(item)
bindWishlist(item)
bindTrade(item)
bindPrivateInfo(item)
bindFooter(item)
bindVisibility()
}
private fun bindMainContainer(item: CollectionItemEntity) {
// view
val statusDescription = getStatusDescription(item)
binding.statusView.setTextOrHide(statusDescription)
setVisibleTag(binding.statusView, statusDescription.isNotEmpty())
// edit
binding.wantToBuyView.isChecked = item.wantToBuy
binding.preorderedView.isChecked = item.preOrdered
binding.ownView.isChecked = item.own
binding.wantToPlayView.isChecked = item.wantToPlay
binding.previouslyOwnedView.isChecked = item.previouslyOwned
// both
binding.personalRatingView.setContent(item.rating, item.ratingDirtyTimestamp, gameId, collectionId, item.internalId)
binding.commentView.setContent(item.comment, item.commentDirtyTimestamp)
}
private fun bindWishlist(item: CollectionItemEntity) {
// view
if (item.wishList) {
binding.wishlistStatusView.setTextOrHide(item.wishListPriority.asWishListPriority(context))
} else {
binding.wishlistStatusView.visibility = View.GONE
}
setVisibleTag(binding.wishlistStatusView, item.wishList)
// edit
if (item.wishList) {
binding.wishlistPriorityView.setSelection(item.wishListPriority.coerceIn(1..5) - 1)
}
binding.wishlistPriorityView.isEnabled = item.wishList
binding.wishlistView.isChecked = item.wishList
binding.wishlistCommentView.setContent(item.wishListComment, item.wishListDirtyTimestamp)
}
private fun bindTrade(item: CollectionItemEntity) {
// view
val statusDescriptions = mutableListOf<String>()
if (item.forTrade) statusDescriptions += getString(R.string.collection_status_for_trade)
if (item.wantInTrade) statusDescriptions += getString(R.string.collection_status_want_in_trade)
binding.tradeStatusView.setTextOrHide(statusDescriptions.formatList())
setVisibleTag(binding.tradeStatusView, item.forTrade || item.wantInTrade)
// edit
binding.wantInTradeView.isChecked = item.wantInTrade
binding.forTradeView.isChecked = item.forTrade
// both
binding.conditionView.setContent(item.conditionText, item.tradeConditionDirtyTimestamp)
binding.wantPartsView.setContent(item.wantPartsList, item.wantPartsDirtyTimestamp)
binding.hasPartsView.setContent(item.hasPartsList, item.hasPartsDirtyTimestamp)
}
private fun bindPrivateInfo(item: CollectionItemEntity) {
// view
binding.viewPrivateInfoView.setTextOrHide(item.getPrivateInfo(requireContext()))
setVisibleTag(binding.viewPrivateInfoView, hasPrivateInfo(item))
// edit
binding.privateInfoHintView.isVisible = !hasPrivateInfo(item)
binding.editPrivateInfoView.isVisible = hasPrivateInfo(item)
binding.editPrivateInfoView.text = item.getPrivateInfo(requireContext())
binding.editPrivateInfoView.setTag(R.id.priceCurrencyView, item.pricePaidCurrency)
binding.editPrivateInfoView.setTag(R.id.priceView, item.pricePaid)
binding.editPrivateInfoView.setTag(R.id.currentValueCurrencyView, item.currentValueCurrency)
binding.editPrivateInfoView.setTag(R.id.currentValueView, item.currentValue)
binding.editPrivateInfoView.setTag(R.id.quantityView, item.quantity)
binding.editPrivateInfoView.setTag(R.id.acquisitionDateView, item.acquisitionDate)
binding.editPrivateInfoView.setTag(R.id.acquiredFromView, item.acquiredFrom)
binding.editPrivateInfoView.setTag(R.id.inventoryLocationView, item.inventoryLocation)
// both
binding.privateInfoCommentView.setContent(item.privateComment, item.privateInfoDirtyTimestamp)
}
private fun bindFooter(item: CollectionItemEntity) {
binding.lastModifiedView.timestamp = when {
item.dirtyTimestamp > 0 -> item.dirtyTimestamp
item.statusDirtyTimestamp > 0 -> item.statusDirtyTimestamp
else -> item.lastModifiedDate
}
binding.updatedView.timestamp = item.syncTimestamp
binding.idView.text = item.collectionId.toString()
}
private fun getStatusDescription(item: CollectionItemEntity): String {
val statusDescriptions = mutableListOf<String>()
if (item.own) statusDescriptions += getString(R.string.collection_status_own)
if (item.previouslyOwned) statusDescriptions += getString(R.string.collection_status_prev_owned)
if (item.wantToBuy) statusDescriptions += getString(R.string.collection_status_want_to_buy)
if (item.wantToPlay) statusDescriptions += getString(R.string.collection_status_want_to_play)
if (item.preOrdered) statusDescriptions += getString(R.string.collection_status_preordered)
return if (statusDescriptions.isEmpty() && item.numberOfPlays > 0) {
getString(R.string.played)
} else statusDescriptions.formatList()
}
private class WishlistPriorityAdapter(context: Context) : ArrayAdapter<String?>(
context,
android.R.layout.simple_spinner_item,
context.resources.getStringArray(R.array.wishlist_priority_finite)
) {
init {
setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
}
}
private fun setVisibilityByChildren(view: ViewGroup) {
view.children.forEach { child ->
if (setVisibilityByChild(view, child)) return
}
view.visibility = View.GONE
}
companion object {
private const val KEY_GAME_ID = "GAME_ID"
private const val KEY_COLLECTION_ID = "COLLECTION_ID"
fun newInstance(gameId: Int, collectionId: Int): GameCollectionItemFragment {
return GameCollectionItemFragment().apply {
arguments = bundleOf(
KEY_GAME_ID to gameId,
KEY_COLLECTION_ID to collectionId,
)
}
}
private fun setVisibleTag(view: View, isVisible: Boolean) {
view.setTag(R.id.visibility, isVisible)
}
private fun getVisibleTag(view: View): Boolean {
return view.getTag(R.id.visibility) as? Boolean ?: false
}
fun hasPrivateInfo(item: CollectionItemEntity): Boolean {
return item.quantity > 1 ||
item.acquisitionDate > 0L ||
item.acquiredFrom.isNotEmpty() ||
item.pricePaid > 0.0 ||
item.currentValue > 0.0 ||
item.inventoryLocation.isNotEmpty()
}
private fun setVisibilityByChild(view: ViewGroup, child: View): Boolean {
if (child is ViewGroup) {
val tag = child.getTag() as? String?
if (tag != null && tag == "container") {
child.children.forEach { grandchild ->
if (setVisibilityByChild(view, grandchild)) return true
}
} else {
if (setVisibilityByChildView(view, child)) return true
}
} else {
if (setVisibilityByChildView(view, child)) return true
}
return false
}
/** Show the view if the child is visible. **/
private fun setVisibilityByChildView(view: View, child: View): Boolean {
val tag = child.tag as? String?
if (tag != null && tag == "header") return false
if (child.visibility == View.VISIBLE) {
view.visibility = View.VISIBLE
return true
}
return false
}
}
}
| gpl-3.0 | ba493f36b785485a5fdc5ca48084b999 | 42.722611 | 153 | 0.652556 | 4.952997 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/data/value/CachedBooleanValueConstructor.kt | 1 | 1006 | /*
* 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.value
import org.spongepowered.api.data.value.Value
internal class CachedBooleanValueConstructor(
private val original: ValueConstructor<Value<Boolean>, Boolean>
) : ValueConstructor<Value<Boolean>, Boolean> {
private val immutableValueTrue = this.original.getImmutable(true)
private val immutableValueFalse = this.original.getImmutable(false)
override fun getMutable(element: Boolean) = this.original.getMutable(element)
override fun getImmutable(element: Boolean) = getRawImmutable(element)
override fun getRawImmutable(element: Boolean) = if (element) this.immutableValueTrue else this.immutableValueFalse
}
| mit | 6bf073517ca2651c79d61f4b972e5cb0 | 39.24 | 119 | 0.764414 | 4.157025 | false | false | false | false |
devmil/PaperLaunch | app/src/main/java/de/devmil/paperlaunch/view/widgets/VerticalTextView.kt | 1 | 2147 | /*
* Copyright 2015 Devmil Solutions
*
* 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 de.devmil.paperlaunch.view.widgets
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.Gravity
import android.widget.TextView
class VerticalTextView : TextView {
private var topDown: Boolean = false
constructor(context: Context) : super(context) {
construct()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
construct()
}
private fun construct() {
val gravity = gravity
topDown = if (Gravity.isVertical(gravity) && gravity and Gravity.VERTICAL_GRAVITY_MASK == Gravity.BOTTOM) {
setGravity(gravity and Gravity.HORIZONTAL_GRAVITY_MASK or Gravity.TOP)
false
} else
true
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec)
setMeasuredDimension(measuredHeight, measuredWidth)
}
override fun setFrame(l: Int, t: Int, r: Int, b: Int): Boolean {
return super.setFrame(l, t, l + (b - t), t + (r - l))
}
override fun draw(canvas: Canvas) {
if (topDown) {
canvas.translate(height.toFloat(), 0f)
canvas.rotate(90f)
} else {
canvas.translate(0f, width.toFloat())
canvas.rotate(-90f)
}
@Suppress("DEPRECATION")
canvas.clipRect(0f, 0f, width.toFloat(), height.toFloat(), android.graphics.Region.Op.REPLACE)
super.draw(canvas)
}
} | apache-2.0 | e3a3996137dd9864472b4b780a49c341 | 32.046154 | 115 | 0.66884 | 4.251485 | false | false | false | false |
SimonVT/cathode | trakt-api/src/main/java/net/simonvt/cathode/api/entity/Episode.kt | 1 | 1010 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.api.entity
data class Episode(
var season: Int? = null,
var number: Int? = null,
var title: String? = null,
var ids: Ids,
var number_abs: Int? = null,
var overview: String? = null,
var first_aired: IsoTime? = null,
var updated_at: IsoTime? = null,
var rating: Float? = null,
var votes: Int? = null,
var available_translations: List<String>? = null
)
| apache-2.0 | f0d8b25f87f59f9a3e3656e09e41bac0 | 31.580645 | 75 | 0.707921 | 3.713235 | false | false | false | false |
jamieadkins95/Roach | data/src/main/java/com/jamieadkins/gwent/data/update/repository/PatchRepositoryImpl.kt | 1 | 2107 | package com.jamieadkins.gwent.data.update.repository
import com.google.firebase.firestore.EventListener
import com.google.firebase.firestore.FirebaseFirestore
import com.jamieadkins.gwent.data.BuildConfig
import com.jamieadkins.gwent.domain.patch.GwentPatch
import com.jamieadkins.gwent.domain.patch.PatchRepository
import io.reactivex.Observable
import io.reactivex.Single
import timber.log.Timber
import javax.inject.Inject
class PatchRepositoryImpl @Inject constructor(
private val firestore: FirebaseFirestore
) : PatchRepository {
override fun getLatestRoachPatch(): Single<String> {
val patchRef = firestore.collection("patch").document(BuildConfig.CARD_DATA_VERSION)
return Single.create<String> { emitter ->
patchRef.get()
.addOnSuccessListener { document ->
val patch = document.data?.get("patch")
if (patch != null) {
emitter.onSuccess(patch.toString())
} else {
emitter.onError(NullPointerException("patch is null"))
}
}
.addOnFailureListener { exception -> emitter.onError(exception) }
}
.doOnError { Timber.e(it) }
}
override fun getLatestGwentPatch(): Observable<GwentPatch> {
return Observable.create { emitter ->
val patchRef = firestore.collection("patch").document("latestGwentPatch")
val listenerRegistration = patchRef
.addSnapshotListener(EventListener { snapshot, e ->
if (e != null) {
Timber.e(e)
emitter.onError(e)
return@EventListener
}
val patch = GwentPatch(
snapshot?.getString("name") ?: "",
snapshot?.getBoolean("upToDate") ?: false
)
emitter.onNext(patch)
})
emitter.setCancellable { listenerRegistration.remove() }
}
}
} | apache-2.0 | 0f63bb10f7f89d12ecba7f39df2e6392 | 36.642857 | 92 | 0.581395 | 5.361323 | false | true | false | false |
brayvqz/ejercicios_kotlin | descuento_sueldo/main.kt | 1 | 766 | package descuento_sueldo
import java.util.*
/**
* Created by brayan on 16/04/2017.
*/
fun main(args: Array<String>) {
var scan = Scanner(System.`in`)
println("Digite su sueldo : ")
var sueldo = scan.nextDouble()
descuento(sueldo)
}
fun descuento(sueldo:Double = 0.0){
var desc:Double = 0.0
var pago:Double = 0.0
if (sueldo<=1000){
desc = 0.10
pago = sueldo - (sueldo * desc)
}else if(sueldo>1000 && sueldo<=2000){
desc = 0.05
pago = sueldo - (sueldo * desc)
}else if(sueldo>2000){
desc = 0.03
pago = sueldo - (sueldo * desc)
}
println("Su sueldo es : \n${sueldo}")
println("El descuento a realizar es : \n${desc}")
println("Su sueldo final es : \n${pago}")
} | mit | 8b42131924e143bf3f94d77bc1fdeab9 | 22.242424 | 53 | 0.574413 | 2.765343 | false | false | false | false |
FHannes/intellij-community | platform/script-debugger/backend/src/org/jetbrains/debugger/sourcemap/SourceMap.kt | 3 | 3634 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger.sourcemap
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.Url
// sources - is not originally specified, but canonicalized/normalized
interface SourceMap {
val outFile: String?
/**
* note: Nested map returns only parent sources
*/
val sources: Array<Url>
val generatedMappings: Mappings
val hasNameMappings: Boolean
val sourceResolver: SourceResolver
fun findSourceMappings(sourceIndex: Int): Mappings
fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int
fun findSourceMappings(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Mappings? {
val sourceIndex = findSourceIndex(sourceUrls, sourceFile, resolver, localFileUrlOnly)
return if (sourceIndex >= 0) findSourceMappings(sourceIndex) else null
}
fun getSourceLineByRawLocation(rawLine: Int, rawColumn: Int) = generatedMappings.get(rawLine, rawColumn)?.sourceLine ?: -1
fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean): Int
fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean
fun processSourceMappingsInLine(sourceUrls: List<Url>, sourceLine: Int, mappingProcessor: MappingsProcessorInLine, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Boolean {
val sourceIndex = findSourceIndex(sourceUrls, sourceFile, resolver, localFileUrlOnly)
return sourceIndex >= 0 && processSourceMappingsInLine(sourceIndex, sourceLine, mappingProcessor)
}
}
class OneLevelSourceMap(override val outFile: String?,
override val generatedMappings: Mappings,
internal val sourceIndexToMappings: Array<MappingList?>,
override val sourceResolver: SourceResolver,
override val hasNameMappings: Boolean) : SourceMap {
override val sources: Array<Url>
get() = sourceResolver.canonicalizedUrls
override fun findSourceIndex(sourceUrls: List<Url>, sourceFile: VirtualFile?, resolver: Lazy<SourceFileResolver?>?, localFileUrlOnly: Boolean): Int {
val index = sourceResolver.findSourceIndex(sourceUrls, sourceFile, localFileUrlOnly)
if (index == -1 && resolver != null) {
return resolver.value?.let { sourceResolver.findSourceIndex(sourceFile, it) } ?: -1
}
return index
}
// returns SourceMappingList
override fun findSourceMappings(sourceIndex: Int) = sourceIndexToMappings.get(sourceIndex)!!
override fun findSourceIndex(sourceFile: VirtualFile, localFileUrlOnly: Boolean) = sourceResolver.findSourceIndexByFile(sourceFile, localFileUrlOnly)
override fun processSourceMappingsInLine(sourceIndex: Int, sourceLine: Int, mappingProcessor: MappingsProcessorInLine): Boolean {
return findSourceMappings(sourceIndex).processMappingsInLine(sourceLine, mappingProcessor)
}
} | apache-2.0 | d17660a9ad68bc1e1fca56a3dde6db9a | 44.4375 | 218 | 0.760594 | 4.890983 | false | false | false | false |
TeamAmaze/AmazeFileManager | app/src/test/java/com/amaze/filemanager/database/models/utilities/SmbEntryTest.kt | 1 | 2595 | /*
* Copyright (C) 2014-2022 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.database.models.utilities
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
/**
* Test [SmbEntry] model.
*/
@Suppress("StringLiteralDuplication")
class SmbEntryTest {
/**
* Test [SmbEntry.equals] for equality.
*/
@Test
fun testEquals() {
val a = SmbEntry("SMB connection 1", "smb://root:[email protected]/root")
val b = SmbEntry("SMB connection 1", "smb://root:[email protected]/root")
assertEquals(a, b)
assertEquals(a.hashCode(), b.hashCode())
}
/**
* Test [SmbEntry.equals] for inequality by name.
*/
@Test
fun testNameNotEquals() {
val a = SmbEntry("SMB connection 1", "smb://root:[email protected]/root")
val b = SmbEntry("SMB connection 2", "smb://root:[email protected]/root")
assertNotEquals(a, b)
assertNotEquals(a.hashCode(), b.hashCode())
}
/**
* Test [SmbEntry.equals] for inequality by path.
*/
@Test
fun testPathNotEquals() {
val a = SmbEntry("SMB connection 1", "smb://root:[email protected]/root")
val b = SmbEntry("SMB connection 1", "smb://root:[email protected]/toor")
assertNotEquals(a, b)
assertNotEquals(a.hashCode(), b.hashCode())
}
/**
* Test [SmbEntry.equals] for inequality with other class.
*/
@Test
fun testForeignClassNotEquals() {
val a = SmbEntry("SMB connection 1", "smb://root:[email protected]/root")
val b = Bookmark("SMB connection 1", "smb://root:[email protected]/root")
assertNotEquals(a, b)
assertNotEquals(a.hashCode(), b.hashCode())
}
}
| gpl-3.0 | cf8e1fd9b6b721fe8ccb3fb140ae6888 | 33.144737 | 107 | 0.656262 | 3.665254 | false | true | false | false |
EricssonResearch/scott-eu | lyo-services/lib-common/src/main/kotlin/eu/scott/warehouse/domains/trs/TrsServerAnnouncement.kt | 1 | 2338 | package eu.scott.warehouse.domains.trs
import eu.scott.warehouse.domains.pddl.PrimitiveType
import org.eclipse.lyo.oslc4j.core.annotation.*
import org.eclipse.lyo.oslc4j.core.model.Link
import org.eclipse.lyo.oslc4j.core.model.Occurs
import org.eclipse.lyo.oslc4j.core.model.ValueType
import java.net.URI
// TODO I would love just to have @OslcNamespace mandatory and have the rest inferred
@OslcNamespace(TrsXConstants.NS)
@OslcName("TrsServerAnnouncement")
@OslcResourceShape(describes = [(TrsXConstants.NS + "TrsServerAnnouncement")])
class TrsServerAnnouncement() : PrimitiveType() {
var trsUri: Link = Link()
@OslcName("trs_uri")
@OslcPropertyDefinition(TrsXConstants.NS + "trs_uri")
@OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.Resource)
get
var adaptorId: String = ""
@OslcName("adaptor_id") @OslcPropertyDefinition(TrsXConstants.NS + "adaptor_id")
@OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.String)
// @OslcReadOnly(false)
get
var isLeaving: Boolean = false
// TODO can we make only name mandatory? and infer the NS from @OslcNamespace
@OslcName("is_leaving")
@OslcPropertyDefinition(TrsXConstants.NS + "is_leaving")
// @OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.Boolean)
// @OslcReadOnly(false)
get
var kind: String = ""
@OslcName("kind")
@OslcPropertyDefinition(TrsXConstants.NS + "kind")
// @OslcOccurs(Occurs.ExactlyOne)
@OslcValueType(ValueType.String)
get
var lwtTopic: String = ""
@OslcName("lwt_topic") @OslcPropertyDefinition(TrsXConstants.NS + "lwt_topic") @OslcOccurs(
Occurs.ZeroOrOne) @OslcValueType(ValueType.String) get
@JvmOverloads constructor(twinId: String, kind: String = TrsXConstants.TYPE_TWIN, trsUri: URI,
lwtTopic: String, isLeaving: Boolean = false) : this() {
this.trsUri = Link(trsUri)
this.kind = kind
this.adaptorId = twinId
this.isLeaving = isLeaving
this.lwtTopic = lwtTopic
}
override fun toString(): String {
return "TrsServerAnnouncement(id=${adaptorId}, kind=${kind}, trsURI=${trsUri}, lwtTopic=${lwtTopic}, isLeaving=${isLeaving})"
}
}
| apache-2.0 | 5efe08d27560624e6b6308a813a1aedb | 36.111111 | 133 | 0.67237 | 3.443299 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/misc/TableDataFile.kt | 1 | 2066 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// 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/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.modelFeatures.misc
import com.google.common.collect.Table
import org.droidmate.misc.withExtension
import java.nio.file.Files
import java.nio.file.Path
class TableDataFile<R, C, V>(val table: Table<R, C, V>,
private val file: Path) {
fun write() {
Files.write(file, tableString.toByteArray())
}
fun writeOutPlot(resourceDir: Path) {
plot(file.toAbsolutePath().toString(), plotFile.toAbsolutePath().toString(), resourceDir)
}
private val tableString: String by lazy {
val headerRowString = table.columnKeySet().joinToString(separator = "\t")
val dataRowsStrings: List<String> = table.rowMap().map {
val rowValues = it.value.values
rowValues.joinToString(separator = "\t")
}
val tableString = headerRowString + System.lineSeparator() + dataRowsStrings.joinToString(separator = System.lineSeparator())
tableString
}
private val plotFile = file.withExtension("pdf")
override fun toString(): String {
return file.toString()
}
}
| gpl-3.0 | 05a8f92aeffd16702fd623f995d422a8 | 31.28125 | 127 | 0.732817 | 3.912879 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.