content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.moviereel.di.qualifiers
import kotlin.annotation.Retention
import kotlin.annotation.AnnotationRetention.RUNTIME
import javax.inject.Qualifier
/**
* @author lusinabrian on 27/03/17
*/
@Qualifier
@Retention(RUNTIME)
annotation class DatabaseInfo
| app/src/main/kotlin/com/moviereel/di/qualifiers/DatabaseInfo.kt | 819998700 |
package de.westnordost.streetcomplete.data.elementfilter.filters
import de.westnordost.streetcomplete.data.meta.toCheckDateString
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.ktx.toLocalDate
import java.time.Instant
import java.time.LocalDate
abstract class CompareElementAge(private val dateFilter: DateFilter) : ElementFilter {
val date: LocalDate get() = dateFilter.date
override fun toOverpassQLString() =
"(if: date(timestamp()) " + operator + " date('" + date.toCheckDateString() + "'))"
override fun toString() = toOverpassQLString()
override fun matches(obj: Element?): Boolean {
val timestampEdited = obj?.timestampEdited ?: return false
return compareTo(Instant.ofEpochMilli(timestampEdited).toLocalDate())
}
abstract fun compareTo(tagValue: LocalDate): Boolean
abstract val operator: String
}
| app/src/main/java/de/westnordost/streetcomplete/data/elementfilter/filters/CompareElementAge.kt | 3641563158 |
package de.westnordost.streetcomplete.data.elementfilter.filters
import de.westnordost.streetcomplete.data.elementfilter.dateDaysAgo
import de.westnordost.streetcomplete.data.elementfilter.matches
import de.westnordost.streetcomplete.data.meta.toCheckDateString
import org.junit.Assert.*
import org.junit.Test
class TagNewerThanTest {
private val oldDate = dateDaysAgo(101f)
private val newDate = dateDaysAgo(99f)
val c = TagNewerThan("opening_hours", RelativeDate(-100f))
@Test fun `does not match old element with tag`() {
assertFalse(c.matches(mapOf("opening_hours" to "tag"), oldDate))
}
@Test fun `matches new element with tag`() {
assertTrue(c.matches(mapOf("opening_hours" to "tag"), newDate))
}
@Test fun `matches old element with tag and new check_date`() {
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"opening_hours:check_date" to newDate.toCheckDateString()
), oldDate))
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"check_date:opening_hours" to newDate.toCheckDateString()
), oldDate))
}
@Test fun `matches old element with tag and new lastcheck`() {
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"opening_hours:lastcheck" to newDate.toCheckDateString()
), oldDate))
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"lastcheck:opening_hours" to newDate.toCheckDateString()
), oldDate))
}
@Test fun `matches old element with tag and new last_checked`() {
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"opening_hours:last_checked" to newDate.toCheckDateString()
), oldDate))
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"last_checked:opening_hours" to newDate.toCheckDateString()
), oldDate))
}
@Test fun `matches old element with tag and different check date tags of which only one is new`() {
assertTrue(c.matches(mapOf(
"opening_hours" to "tag",
"opening_hours:last_checked" to oldDate.toCheckDateString(),
"opening_hours:lastcheck" to newDate.toCheckDateString(),
"opening_hours:check_date" to oldDate.toCheckDateString(),
"last_checked:opening_hours" to oldDate.toCheckDateString(),
"lastcheck:opening_hours" to oldDate.toCheckDateString(),
"check_date:opening_hours" to oldDate.toCheckDateString()
), oldDate))
}
@Test fun `to string`() {
val date = dateDaysAgo(100f).toCheckDateString()
assertEquals(
"(if: date(timestamp()) > date('$date') || " +
"date(t['opening_hours:check_date']) > date('$date') || " +
"date(t['check_date:opening_hours']) > date('$date') || " +
"date(t['opening_hours:lastcheck']) > date('$date') || " +
"date(t['lastcheck:opening_hours']) > date('$date') || " +
"date(t['opening_hours:last_checked']) > date('$date') || " +
"date(t['last_checked:opening_hours']) > date('$date'))",
c.toOverpassQLString()
)
}
} | app/src/test/java/de/westnordost/streetcomplete/data/elementfilter/filters/TagNewerThanTest.kt | 71061225 |
package org.wordpress.android.fluxc.ditests
import dagger.Module
import dagger.Provides
import dagger.multibindings.IntoSet
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Response
import javax.inject.Named
@Module
class TestInterceptorModule {
@Provides @IntoSet @Named("interceptors")
fun provideDummyInterceptor(): Interceptor = DummyInterceptor
@Provides @IntoSet @Named("network-interceptors")
fun provideDummyNetworkInterceptor(): Interceptor = DummyNetworkInterceptor
}
object DummyInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
return Response.Builder().build()
}
}
object DummyNetworkInterceptor : Interceptor {
override fun intercept(chain: Chain): Response {
return Response.Builder().build()
}
}
| example/src/androidTest/java/org/wordpress/android/fluxc/ditests/TestInterceptorModule.kt | 4001614473 |
package com.github.pavlospt
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.github.pavlospt.misc.IssuesInfo
import com.github.pavlospt.misc.LithoLintConstants
import com.github.pavlospt.utils.PsiUtils
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiModifier
import org.jetbrains.uast.UAnnotation
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.UNamedExpression
import org.jetbrains.uast.visitor.AbstractUastVisitor
class LithoLintIssuesDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes(): List<Class<out UElement>> {
return listOf<Class<out UElement>>(UClass::class.java)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return object : UElementHandler() {
override fun visitClass(node: UClass) {
node.accept(LithoVisitor(context))
}
override fun visitMethod(node: UMethod) {
node.accept(LithoVisitor(context))
}
}
}
internal class LithoVisitor(private val context: JavaContext?) : AbstractUastVisitor() {
private val INVALID_POSITION = -1
override fun visitClass(node: UClass): Boolean {
detectAnnotatedClassNameIssue(context, node)
return super.visitClass(node)
}
override fun visitMethod(node: UMethod): Boolean {
detectMethodVisibilityIssue(node)
detectComponentContextNameIssue(node)
detectOptionalPropOrderIssue(node)
detectPossibleResourceTypesIssue(node)
return super.visitMethod(node)
}
// Detect annotated class name issue
private fun detectAnnotatedClassNameIssue(context: JavaContext?, uClass: UClass) {
if (!PsiUtils.hasAnnotations(uClass.modifierList)) return
val annotations = uClass.modifierList?.annotations ?: return
annotations.forEach {
val worthCheckingClass = LithoLintConstants.LAYOUT_SPEC_ANNOTATION == it.qualifiedName
val psiClassName = uClass.name ?: return@forEach
val notSuggestedName = LithoLintConstants.SUGGESTED_LAYOUT_COMPONENT_SPEC_NAME_FORMAT !in psiClassName
val shouldReportClass = worthCheckingClass && notSuggestedName
if (shouldReportClass) {
context?.report(IssuesInfo.LAYOUT_SPEC_NAME_ISSUE, it,
context.getLocation(uClass.psi.nameIdentifier as PsiElement),
IssuesInfo.LAYOUT_SPEC_CLASS_NAME_ISSUE_DESC)
}
}
}
// Detect possible resource types issue
private fun detectPossibleResourceTypesIssue(uMethod: UMethod) {
if (!worthCheckingMethod(uMethod)) return
val parametersList = uMethod.uastParameters
for (parameter in parametersList) {
if (parameter.type.canonicalText
!in LithoLintConstants.POSSIBLE_RESOURCE_PARAMETER_TYPES) continue
val annotations = parameter.annotations
annotations.filter {
LithoLintConstants.PROP_PARAMETER_ANNOTATION == it.qualifiedName
}.forEach {
context?.report(IssuesInfo.POSSIBLE_RESOURCE_TYPE_ISSUE, parameter as UElement,
context.getLocation(parameter as UElement),
IssuesInfo.POSSIBLE_RESOURCE_TYPE_ISSUE_DESC)
}
}
}
// Detect wrong props order issue
private fun detectOptionalPropOrderIssue(uMethod: UMethod) {
if (!worthCheckingMethod(uMethod)) return
val parametersList = uMethod.uastParameters
var indexOfFirstRequiredProp = INVALID_POSITION
var indexOfFirstOptionalProp = INVALID_POSITION
for (i in parametersList.indices) {
val parameter = parametersList[i]
if (!PsiUtils.hasAnnotations(parameter.modifierList)) continue
val annotations = parameter.annotations
val propAnnotation: UAnnotation = annotations.find {
LithoLintConstants.PROP_PARAMETER_ANNOTATION == it.qualifiedName
} ?: continue
val annotationParameters: List<UNamedExpression> = propAnnotation.attributeValues
if (annotationParameters.isEmpty()) {
indexOfFirstRequiredProp = assignPositionIfInvalid(indexOfFirstRequiredProp, i)
} else {
for (psiNameValuePair in annotationParameters) {
if (LithoLintConstants.OPTIONAL_PROP_ATTRIBUTE_NAME == psiNameValuePair.name) {
indexOfFirstOptionalProp = assignPositionIfInvalid(indexOfFirstOptionalProp, i)
} else {
indexOfFirstRequiredProp = assignPositionIfInvalid(indexOfFirstRequiredProp, i)
}
}
}
if (indexOfFirstOptionalProp != INVALID_POSITION
&& indexOfFirstRequiredProp != INVALID_POSITION
&& indexOfFirstOptionalProp < indexOfFirstRequiredProp) {
val psiParameter = parametersList[indexOfFirstOptionalProp]
context?.report(IssuesInfo.OPTIONAL_PROP_BEFORE_REQUIRED_ISSUE, psiParameter as UElement,
context.getLocation(psiParameter.psi.nameIdentifier as PsiElement),
IssuesInfo.OPTIONAL_PROP_BEFORE_REQUIRED_ISSUE_DESC)
break
}
}
}
// Detect component context name issue
private fun detectComponentContextNameIssue(uMethod: UMethod) {
if (!worthCheckingMethod(uMethod)) return
val parameters = uMethod.uastParameters
for (parameter in parameters) {
if (parameter.type
.canonicalText == LithoLintConstants.COMPONENT_CONTEXT_CLASS_NAME) {
val shouldReportParameter = LithoLintConstants.COMPONENT_CONTEXT_DESIRABLE_PARAMETER_NAME != parameter.name
if (shouldReportParameter) {
val lintFix = LintFix.create().replace().text(parameter.name).with("c").build()
context?.report(IssuesInfo.COMPONENT_CONTEXT_NAME_ISSUE_ISSUE, parameter as UElement,
context.getLocation(parameter.psi.nameIdentifier as PsiElement),
IssuesInfo.COMPONENT_CONTEXT_NAME_ISSUE_DESC, lintFix)
}
}
}
}
// Detect method visibility issue
private fun detectMethodVisibilityIssue(uMethod: UMethod) {
if (!PsiUtils.hasAnnotations(uMethod.modifierList)) return
val annotations = uMethod.annotations
for (annotation in annotations) {
val worthCheckingMethod = LithoLintConstants.ALL_METHOD_ANNOTATIONS
.contains(annotation.qualifiedName)
val notSuggestedVisibility = !uMethod.modifierList.hasModifierProperty(
PsiModifier.PACKAGE_LOCAL)
val missesStaticModifier = !uMethod.modifierList.hasExplicitModifier(PsiModifier.STATIC)
val shouldReportMethodVisibility = worthCheckingMethod && notSuggestedVisibility
val shouldReportMissingStaticModifier = worthCheckingMethod && missesStaticModifier
if (shouldReportMethodVisibility) {
context?.report(IssuesInfo.ANNOTATED_METHOD_VISIBILITY_ISSUE, uMethod as UElement,
context.getLocation(uMethod.psi.nameIdentifier as PsiElement),
IssuesInfo.ANNOTATED_METHOD_VISIBILITY_ISSUE_DESC)
}
if (shouldReportMissingStaticModifier) {
context?.report(IssuesInfo.MISSING_STATIC_MODIFIER_ISSUE, uMethod as UElement,
context.getLocation(uMethod.psi.nameIdentifier as PsiElement),
IssuesInfo.MISSING_STATIC_MODIFIER_ISSUE_DESC)
}
}
}
// Utility method
private fun worthCheckingMethod(uMethod: UMethod): Boolean {
if (!PsiUtils.hasAnnotations(uMethod.modifierList)) return false
val annotations = uMethod.annotations
var worthCheckingMethod = false
for (annotation in annotations) {
worthCheckingMethod = LithoLintConstants.ALL_METHOD_ANNOTATIONS
.contains(annotation.qualifiedName)
if (worthCheckingMethod) break
}
return worthCheckingMethod && PsiUtils.hasParameters(uMethod)
}
// Utility method
private fun assignPositionIfInvalid(assignable: Int, position: Int): Int {
return if (assignable == INVALID_POSITION) position else assignable
}
}
}
| litho-lint-detector/src/main/java/com/github/pavlospt/LithoLintIssuesDetector.kt | 1817425092 |
package gargoyle.ct.ui
import java.net.URL
interface CTIconProvider {
val bigIcon: URL?
val mediumIcon: URL?
val smallIcon: URL?
}
| app/src/main/kotlin/gargoyle/ct/ui/CTIconProvider.kt | 2082849392 |
package gargoyle.ct.config.convert.impl
import gargoyle.ct.config.CTConfig
import gargoyle.ct.config.CTConfigs
import gargoyle.ct.config.convert.CTUnitConverter
import gargoyle.ct.util.log.Log
import java.util.concurrent.TimeUnit
class CTConfigsConverter : CTUnitConverter<CTConfigs> {
private val configConverter: CTUnitConverter<CTConfig> = CTConfigConverter()
private val configsDataConverter = CTConfigsDataConverter()
override fun format(unit: TimeUnit, data: CTConfigs): String =
configsDataConverter.format(unit, data.getConfigs().map { configConverter.format(unit, it) }.toTypedArray())
override fun parse(data: String): CTConfigs =
CTConfigs(configsDataConverter.parse(data).filter { it.isNotEmpty() }.mapNotNull {
try {
configConverter.parse(it)
} catch (ex: IllegalArgumentException) {
Log.error("skip invalid convert line: $it")
null
}
})
}
| app/src/main/kotlin/gargoyle/ct/config/convert/impl/CTConfigsConverter.kt | 4167332266 |
package io.josephtran.showstowatch.show_form
import android.content.Context
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import io.josephtran.showstowatch.R
import io.josephtran.showstowatch.api.STWShow
import kotlinx.android.synthetic.main.activity_show_form.*
import kotlinx.android.synthetic.main.fragment_show_form.*
abstract class ShowFormFragment : Fragment(), ShowFormView {
private var listener: ShowFormFragmentListener? = null
interface ShowFormFragmentListener {
fun onFormInteracted(show: STWShow)
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View?
= inflater!!.inflate(R.layout.fragment_show_form, container, false)
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
activity.show_form_toolbar_btn.text = getFormButtonText()
activity.show_form_toolbar_btn.setOnClickListener {
val show = constructShow()
if (show != null)
handleShow(show)
}
}
/**
* Gets the text used for the form button.
*
* @return the text used for the form button
*/
abstract protected fun getFormButtonText(): String
/**
* Handle the {@code STWShow} constructed from the form.
*
* @param stwShow the constructed {@code STWShow} from the form
*/
abstract protected fun handleShow(stwShow: STWShow)
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = activity as ShowFormFragmentListener?
} catch (e: ClassCastException) {
throw ClassCastException(activity.toString()
+ " must implement ShowFormFragmentListener")
}
}
/**
* Populates the form with the given {@code STWShow}.
*
* @param stwShow the {@code STWShow} to populate the form with
*/
protected fun populateForm(stwShow: STWShow) {
show_form_title_edit.setText(stwShow.title)
show_form_season_edit.setText(stwShow.season.toString())
show_form_episode_edit.setText(stwShow.episode.toString())
show_form_abandoned.isChecked = stwShow.abandoned
show_form_completed.isChecked = stwShow.completed
}
protected open fun constructShow(): STWShow? {
if (!fieldsValid())
return null
return STWShow(
id = null,
title = show_form_title_edit.text.toString(),
season = show_form_season_edit.text.toString().toInt(),
episode = show_form_episode_edit.text.toString().toInt(),
abandoned = show_form_abandoned.isChecked,
completed = show_form_completed.isChecked
)
}
private fun fieldsValid(): Boolean {
var message = ""
if (show_form_title_edit.text.isNullOrEmpty()) {
message = "Title required."
} else if (show_form_season_edit.text.isNullOrEmpty()) {
message = "Season required."
} else if (show_form_episode_edit.text.isNullOrEmpty()) {
message = "Episode required."
}
if (!message.isNullOrEmpty()) {
showErrorMessage(message)
return false
}
return true
}
private fun showMessage(message: String, color: String) {
if (view != null)
Snackbar.make(view!!,
Html.fromHtml("<font color=\"$color\">$message</font>"),
Snackbar.LENGTH_SHORT).show()
}
override fun showMessage(message: String) {
showMessage(message, "white")
}
override fun showErrorMessage(errorMessage: String) {
showMessage(errorMessage, "red")
}
override fun onShowHandled(show: STWShow) {
if (listener != null)
listener!!.onFormInteracted(show)
}
} | app/src/main/java/io/josephtran/showstowatch/show_form/ShowFormFragment.kt | 4077205832 |
package rxjava2
import io.reactivex.Observable
import java.util.*
import java.util.concurrent.Callable
import java.util.stream.Collectors
// scan和reduce都是把上一次操作的结果做为参数传递给第二次Observable使用
// 区别就在subscribe()是否被频繁调用. 见下面日志即知
fun main() {
Observable.range(0, 6)
.scan(12) { a, b ->
println(" szw a = $a, b = $b")
a + b
}
.subscribe { println(" $it") }
Observable.range(0, 6)
.reduce(12) { a, b ->
println("==> a = $a, b = $b")
a + b
}
.subscribe { v -> println("==> ${v}") }
}
/*
result:
12
szw a = 12, b = 0
12
szw a = 12, b = 1
13
szw a = 13, b = 2
15
szw a = 15, b = 3
18
szw a = 18, b = 4
22
szw a = 22, b = 5
27
==> a = 12, b = 0
==> a = 12, b = 1
==> a = 13, b = 2
==> a = 15, b = 3
==> a = 18, b = 4
==> a = 22, b = 5
==> 27
*/ | Advanced_kb/src/rxjava2/Scan_Reduce_Diff.kt | 2289726906 |
package com.budilov
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestHandler
import com.amazonaws.services.lambda.runtime.events.S3Event
import com.budilov.db.ESPictureService
import com.budilov.pojo.PictureItem
import com.budilov.rekognition.RekognitionService
import java.net.URLDecoder
/**
* Created by Vladimir Budilov
*
* This Lambda function is invoked by S3 whenever an object is added to an S3 bucket.
*/
class AddPhotoLambda : RequestHandler<S3Event, String> {
private val rekognition = RekognitionService()
private val esService = ESPictureService()
/**
* 1. Get the s3 bucket and object name in question
* 2. Clean the object name
* 3. Run the RekognitionService service to get the labels
* 4. Save the bucket/object & labels into ElasticSearch
*/
override fun handleRequest(s3event: S3Event, context: Context): String {
val record = s3event.records.first()
val logger = context.logger
val srcBucket = record.s3.bucket.name
// Object key may have spaces or unicode non-ASCII characters.
val srcKeyEncoded = record.s3.`object`.key
.replace('+', ' ')
val srcKey = URLDecoder.decode(srcKeyEncoded, "UTF-8")
logger.log("bucket: ${srcBucket}, key: $srcKey")
// Get the cognito id from the object name (it's a prefix)...hacky, don't judge
val cognitoId = srcKey.split("/")[1]
logger.log("Cognito ID: $cognitoId")
val labels = rekognition.getLabels(srcBucket, srcKey)
if (labels.isNotEmpty()) {
val picture = PictureItem(srcKeyEncoded.hashCode().toString(), srcBucket + Properties._BUCKET_URL + "/" + srcKey, labels, null)
logger.log("Saving picture: $picture")
// Save the picture to ElasticSearch
esService.add(cognitoId, picture)
} else {
logger.log("No labels returned. Not saving to ES")
//todo: create an actionable event to replay the flow
}
return "Ok"
}
} | src/main/kotlin/com/budilov/AddPhotoLambda.kt | 2317518543 |
package voice.app.mvp
import android.os.Bundle
import android.view.View
import androidx.viewbinding.ViewBinding
import com.bluelinelabs.conductor.Controller
import voice.common.checkMainThread
import voice.common.conductor.InflateBinding
import voice.common.conductor.ViewBindingController
/**
* Base controller that provides a convenient way for binding a view to a presenter
*/
abstract class MvpController<V : Any, out P, B : ViewBinding>(
inflateBinding: InflateBinding<B>,
args: Bundle = Bundle(),
) : ViewBindingController<B>(args, inflateBinding) where P : Presenter<V> {
private var internalPresenter: P? = null
val presenter: P
get() {
checkMainThread()
check(!isDestroyed) { "Must not call presenter when destroyed!" }
if (internalPresenter == null) {
internalPresenter = createPresenter()
}
return internalPresenter!!
}
init {
addLifecycleListener(
object : LifecycleListener() {
override fun onRestoreInstanceState(controller: Controller, savedInstanceState: Bundle) {
presenter.onRestore(savedInstanceState)
}
override fun postAttach(controller: Controller, view: View) {
presenter.attach(provideView())
}
override fun preDetach(controller: Controller, view: View) {
presenter.detach()
}
override fun onSaveInstanceState(controller: Controller, outState: Bundle) {
presenter.onSave(outState)
}
override fun postDestroy(controller: Controller) {
internalPresenter = null
}
},
)
}
@Suppress("UNCHECKED_CAST")
open fun provideView(): V = this as V
abstract fun createPresenter(): P
}
| app/src/main/kotlin/voice/app/mvp/MvpController.kt | 989700935 |
package com.github.ykrank.androidtools.widget.glide.downsamplestrategy
import com.bumptech.glide.load.resource.bitmap.DownsampleStrategy
/**
* A DownsampleStrategy for choose min scale.
* Created by ykrank on 2017/6/4.
*/
class MultiDownSampleStrategy(vararg strategy: DownsampleStrategy) : DownsampleStrategy() {
val strateies: List<DownsampleStrategy> = strategy.toList()
override fun getScaleFactor(sourceWidth: Int, sourceHeight: Int, requestedWidth: Int, requestedHeight: Int): Float {
return strateies.map { it.getScaleFactor(sourceWidth, sourceHeight, requestedWidth, requestedHeight) }
.sorted()
.first()
}
override fun getSampleSizeRounding(sourceWidth: Int, sourceHeight: Int, requestedWidth: Int, requestedHeight: Int): SampleSizeRounding {
return if (strateies.any { it.getSampleSizeRounding(sourceWidth, sourceHeight, requestedWidth, requestedHeight) == SampleSizeRounding.QUALITY })
SampleSizeRounding.QUALITY
else SampleSizeRounding.MEMORY
}
} | library/src/main/java/com/github/ykrank/androidtools/widget/glide/downsamplestrategy/MultiDownSampleStrategy.kt | 4114154778 |
package me.ykrank.s1next.view.event
import me.ykrank.s1next.data.api.app.model.AppPost
import me.ykrank.s1next.data.api.app.model.AppThread
data class EditAppPostEvent(val post: AppPost, val thread: AppThread)
| app/src/main/java/me/ykrank/s1next/view/event/EditAppPostEvent.kt | 2916655797 |
package org.rliz.cfm.recorder.mbs.service
import org.rliz.cfm.recorder.common.exception.MbsLookupFailedException
import org.rliz.cfm.recorder.mbs.api.MbsIdentifiedPlaybackDto
import org.rliz.cfm.recorder.mbs.api.MbsIdentifiedPlaybackRes
import org.rliz.cfm.recorder.mbs.api.MbsRecordingViewListRes
import org.rliz.cfm.recorder.mbs.api.MbsReleaseGroupViewListRes
import org.springframework.beans.factory.annotation.Value
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
import org.springframework.web.client.RestTemplate
import org.springframework.web.util.UriComponentsBuilder
import java.util.UUID
import java.util.concurrent.CompletableFuture
@Service
class MbsService {
@Value("\${cfm.mbs.url}")
lateinit var mbsUrl: String
@Async
fun getRecordingView(ids: List<UUID>): CompletableFuture<MbsRecordingViewListRes> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v1", "recordings")
.let { uriBuilder ->
ids.forEach { uriBuilder.queryParam("id", it) }
CompletableFuture.completedFuture(
RestTemplate().getForObject(
uriBuilder.build().toUri(),
MbsRecordingViewListRes::class.java
)
)
}
@Async
fun getReleaseGroupView(ids: List<UUID>): CompletableFuture<MbsReleaseGroupViewListRes> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v2", "release-groups")
.let { uriBuilder ->
ids.forEach { uriBuilder.queryParam("id", it) }
CompletableFuture.completedFuture(
RestTemplate().getForObject(
uriBuilder.build().toUri(),
MbsReleaseGroupViewListRes::class.java
)
)
}
@Async
fun identifyPlayback(recordingTitle: String, releaseTitle: String, artists: List<String>):
CompletableFuture<MbsIdentifiedPlaybackDto> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v1", "playbacks", "identify")
.queryParam("title", recordingTitle)
.queryParam("release", releaseTitle)
.apply {
artists.forEach { queryParam("artist", it) }
}
.build()
.toUri()
.let { uri ->
val future = CompletableFuture<MbsIdentifiedPlaybackDto>()
try {
future.complete(
RestTemplate().getForObject(
uri,
MbsIdentifiedPlaybackRes::class.java
)!!.toDto()
)
} catch (e: Exception) {
future.completeExceptionally(MbsLookupFailedException(e))
}
future
}
@Async
fun identifyPlayback(
artist: String,
release: String,
recording: String,
length: Long
): CompletableFuture<IdentifiedPlayback> =
UriComponentsBuilder.fromHttpUrl(mbsUrl)
.pathSegment("mbs", "v2", "playbacks", "best")
.queryParam("artist", artist)
.queryParam("release", release)
.queryParam("recording", recording)
.queryParam("length", length)
.build()
.encode()
.toUri()
.let { uri ->
val future = CompletableFuture<IdentifiedPlayback>()
try {
future.complete(
RestTemplate().getForObject(uri, IdentifiedPlayback::class.java)
)
} catch (e: Exception) {
future.completeExceptionally(MbsLookupFailedException(e))
}
future
}
}
| server/recorder/src/main/kotlin/org/rliz/cfm/recorder/mbs/service/MbsService.kt | 660943910 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XValueChildrenList
import com.intellij.xdebugger.frame.XValueGroup
import org.jetbrains.concurrency.done
import org.jetbrains.concurrency.rejected
import org.jetbrains.concurrency.thenAsyncAccept
class ScopeVariablesGroup(val scope: Scope, parentContext: VariableContext, callFrame: CallFrame?) : XValueGroup(scope.createScopeNodeName()) {
private val context = createVariableContext(scope, parentContext, callFrame)
private val callFrame = if (scope.type == ScopeType.LOCAL) callFrame else null
override fun isAutoExpand() = scope.type == ScopeType.LOCAL || scope.type == ScopeType.CATCH
override fun getComment(): String? {
val className = scope.description
return if ("Object" == className) null else className
}
override fun computeChildren(node: XCompositeNode) {
val promise = processScopeVariables(scope, node, context, callFrame == null)
if (callFrame == null) {
return
}
promise
.done(node) {
context.memberFilter
.thenAsyncAccept(node) {
if (it.hasNameMappings()) {
it.sourceNameToRaw(RECEIVER_NAME)?.let {
return@thenAsyncAccept callFrame.evaluateContext.evaluate(it)
.done(node) {
VariableImpl(RECEIVER_NAME, it.value, null)
node.addChildren(XValueChildrenList.singleton(VariableView(VariableImpl(RECEIVER_NAME, it.value, null), context)), true)
}
}
}
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
.rejected(node) {
context.viewSupport.computeReceiverVariable(context, callFrame, node)
}
}
}
}
fun createAndAddScopeList(node: XCompositeNode, scopes: List<Scope>, context: VariableContext, callFrame: CallFrame?) {
val list = XValueChildrenList(scopes.size)
for (scope in scopes) {
list.addTopGroup(ScopeVariablesGroup(scope, context, callFrame))
}
node.addChildren(list, true)
}
fun createVariableContext(scope: Scope, parentContext: VariableContext, callFrame: CallFrame?): VariableContext {
if (callFrame == null || scope.type == ScopeType.LIBRARY) {
// functions scopes - we can watch variables only from global scope
return ParentlessVariableContext(parentContext, scope, scope.type == ScopeType.GLOBAL)
}
else {
return VariableContextWrapper(parentContext, scope)
}
}
private class ParentlessVariableContext(parentContext: VariableContext, scope: Scope, private val watchableAsEvaluationExpression: Boolean) : VariableContextWrapper(parentContext, scope) {
override fun watchableAsEvaluationExpression() = watchableAsEvaluationExpression
}
private fun Scope.createScopeNodeName(): String {
when (type) {
ScopeType.GLOBAL -> return XDebuggerBundle.message("scope.global")
ScopeType.LOCAL -> return XDebuggerBundle.message("scope.local")
ScopeType.WITH -> return XDebuggerBundle.message("scope.with")
ScopeType.CLOSURE -> return XDebuggerBundle.message("scope.closure")
ScopeType.CATCH -> return XDebuggerBundle.message("scope.catch")
ScopeType.LIBRARY -> return XDebuggerBundle.message("scope.library")
ScopeType.INSTANCE -> return XDebuggerBundle.message("scope.instance")
ScopeType.CLASS -> return XDebuggerBundle.message("scope.class")
ScopeType.BLOCK -> return XDebuggerBundle.message("scope.block")
ScopeType.SCRIPT -> return XDebuggerBundle.message("scope.script")
ScopeType.UNKNOWN -> return XDebuggerBundle.message("scope.unknown")
else -> throw IllegalArgumentException(type.name)
}
} | platform/script-debugger/debugger-ui/src/ScopeVariablesGroup.kt | 1509396609 |
package io.casey.musikcube.remote.ui.tracks.fragment
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
import io.casey.musikcube.remote.R
import io.casey.musikcube.remote.service.playback.impl.remote.Metadata
import io.casey.musikcube.remote.service.websocket.model.IMetadataProxy
import io.casey.musikcube.remote.service.websocket.model.ITrack
import io.casey.musikcube.remote.service.websocket.model.ITrackListQueryFactory
import io.casey.musikcube.remote.ui.shared.activity.IFilterable
import io.casey.musikcube.remote.ui.shared.activity.IMenuProvider
import io.casey.musikcube.remote.ui.shared.activity.ITitleProvider
import io.casey.musikcube.remote.ui.shared.activity.ITransportObserver
import io.casey.musikcube.remote.ui.shared.constant.Shared
import io.casey.musikcube.remote.ui.shared.extension.*
import io.casey.musikcube.remote.ui.shared.fragment.BaseFragment
import io.casey.musikcube.remote.ui.shared.mixin.ItemContextMenuMixin
import io.casey.musikcube.remote.ui.shared.mixin.MetadataProxyMixin
import io.casey.musikcube.remote.ui.shared.mixin.PlaybackMixin
import io.casey.musikcube.remote.ui.shared.model.DefaultSlidingWindow
import io.casey.musikcube.remote.ui.shared.model.ITrackListSlidingWindow
import io.casey.musikcube.remote.ui.shared.view.EmptyListView
import io.casey.musikcube.remote.ui.tracks.activity.EditPlaylistActivity
import io.casey.musikcube.remote.ui.tracks.activity.TrackListActivity
import io.casey.musikcube.remote.ui.tracks.adapter.TrackListAdapter
import io.casey.musikcube.remote.ui.tracks.constant.Track
import io.casey.musikcube.remote.util.Debouncer
import io.reactivex.Observable
import io.reactivex.rxkotlin.subscribeBy
class TrackListFragment: BaseFragment(), IFilterable, ITitleProvider, ITransportObserver, IMenuProvider {
private lateinit var tracks: DefaultSlidingWindow
private lateinit var emptyView: EmptyListView
private lateinit var adapter: TrackListAdapter
private lateinit var queryFactory: ITrackListQueryFactory
private lateinit var data: MetadataProxyMixin
private lateinit var playback: PlaybackMixin
private var categoryType: String = ""
private var categoryId: Long = 0
private var titleId = R.string.songs_title
private var categoryValue: String = ""
private var lastFilter = ""
override fun onCreate(savedInstanceState: Bundle?) {
component.inject(this)
data = mixin(MetadataProxyMixin())
playback = mixin(PlaybackMixin())
extras.run {
categoryType = getString(Track.Extra.CATEGORY_TYPE, "")
categoryId = getLong(Track.Extra.SELECTED_ID, 0)
categoryValue = getString(Track.Extra.CATEGORY_VALUE, "")
titleId = getInt(Track.Extra.TITLE_ID, titleId)
}
/* needs to come after we extract categoryType -- otherwise menuListener
may get resolved to `null` */
mixin(ItemContextMenuMixin(appCompatActivity, menuListener, this))
queryFactory = createCategoryQueryFactory(categoryType, categoryId)
super.onCreate(savedInstanceState)
}
override fun onPause() {
super.onPause()
tracks.pause()
}
override fun onResume() {
tracks.resume() /* needs to happen first */
super.onResume()
requeryIfViewingOfflineCache()
}
override fun onInitObservables() {
disposables.add(data.provider.observeState().subscribeBy(
onNext = { states ->
val shouldRequery =
states.first === IMetadataProxy.State.Connected ||
(states.first === IMetadataProxy.State.Disconnected && isOfflineTracks)
if (shouldRequery) {
filterDebouncer.cancel()
tracks.requery()
}
else {
emptyView.update(states.first, adapter.itemCount)
}
},
onError = {
}))
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(this.getLayoutId(), container, false).apply {
val recyclerView = findViewById<FastScrollRecyclerView>(R.id.recycler_view)
tracks = DefaultSlidingWindow(recyclerView, data.provider, queryFactory)
adapter = TrackListAdapter(tracks, eventListener, playback, prefs)
setupDefaultRecyclerView(recyclerView, adapter)
emptyView = findViewById(R.id.empty_list_view)
emptyView.let {
it.capability = if (isOfflineTracks) EmptyListView.Capability.OfflineOk else EmptyListView.Capability.OnlineOnly
it.emptyMessage = emptyMessage
it.alternateView = recyclerView
}
tracks.setOnMetadataLoadedListener(slidingWindowListener)
}
private val editPlaylistLauncher = launcher { result ->
val data = result.data
if (result.resultCode == AppCompatActivity.RESULT_OK && data != null) {
val playlistName = data.getStringExtra(EditPlaylistActivity.EXTRA_PLAYLIST_NAME) ?: ""
val playlistId = data.getLongExtra(EditPlaylistActivity.EXTRA_PLAYLIST_ID, -1L)
if (categoryType != Metadata.Category.PLAYLISTS || playlistId != this.categoryId) {
showSnackbar(
appCompatActivity.findViewById(android.R.id.content),
getString(R.string.playlist_edit_save_success, playlistName),
buttonText = getString(R.string.button_view),
buttonCb = {
startActivity(TrackListActivity.getStartIntent(
appCompatActivity, Metadata.Category.PLAYLISTS, playlistId, playlistName))
})
}
}
}
override val title: String
get() = getTitleOverride(getString(titleId))
override val addFilterToToolbar: Boolean
get() = false
override fun setFilter(filter: String) {
lastFilter = filter
filterDebouncer.call()
}
override fun createOptionsMenu(menu: Menu): Boolean {
when (Metadata.Category.PLAYLISTS == categoryType) {
true -> appCompatActivity.menuInflater.inflate(R.menu.view_playlist_menu, menu)
false -> addFilterAction(menu, this)
}
return true
}
override fun optionsItemSelected(menuItem: MenuItem): Boolean =
when (menuItem.itemId == R.id.action_edit) {
true -> {
editPlaylistLauncher.launch(
EditPlaylistActivity.getStartIntent(
appCompatActivity,
categoryValue,
categoryId))
true
}
else -> false
}
override fun onTransportChanged() {
adapter.notifyDataSetChanged()
}
private val filterDebouncer = object : Debouncer<String>(350) {
override fun onDebounced(last: String?) {
if (!paused) {
tracks.requery()
}
}
}
private val emptyMessage: String
get() {
if (isOfflineTracks) {
return getString(R.string.empty_no_offline_tracks_message)
}
return getString(R.string.empty_no_items_format, getString(R.string.browse_type_tracks))
}
private val isOfflineTracks: Boolean
get() = Metadata.Category.OFFLINE == categoryType
private fun requeryIfViewingOfflineCache() {
if (isOfflineTracks) {
tracks.requery()
}
}
private fun createCategoryQueryFactory(categoryType: String?, categoryId: Long): ITrackListQueryFactory {
if (isValidCategory(categoryType, categoryId)) {
/* tracks for a specified category (album, artists, genres, etc */
return object : ITrackListQueryFactory {
override fun count(): Observable<Int> =
data.provider.getTrackCountByCategory(categoryType ?: "", categoryId, lastFilter)
override fun page(offset: Int, limit: Int): Observable<List<ITrack>> =
data.provider.getTracksByCategory(categoryType ?: "", categoryId, limit, offset, lastFilter)
override fun offline(): Boolean =
Metadata.Category.OFFLINE == categoryType
}
}
else {
/* all tracks */
return object : ITrackListQueryFactory {
override fun count(): Observable<Int> =
data.provider.getTrackCount(lastFilter)
override fun page(offset: Int, limit: Int): Observable<List<ITrack>> =
data.provider.getTracks(limit, offset, lastFilter)
override fun offline(): Boolean =
Metadata.Category.OFFLINE == categoryType
}
}
}
private val slidingWindowListener = object : ITrackListSlidingWindow.OnMetadataLoadedListener {
override fun onReloaded(count: Int) =
emptyView.update(data.provider.state, count)
override fun onMetadataLoaded(offset: Int, count: Int) {}
}
private val menuListener: ItemContextMenuMixin.EventListener?
get() {
if (categoryType == Metadata.Category.PLAYLISTS) {
return object: ItemContextMenuMixin.EventListener () {
override fun onPlaylistUpdated(id: Long, name: String) {
tracks.requery()
}
}
}
return null
}
private val eventListener = object: TrackListAdapter.EventListener {
override fun onItemClick(view: View, track: ITrack, position: Int) {
if (isValidCategory(categoryType, categoryId)) {
playback.service.play(categoryType, categoryId, position, lastFilter)
}
else {
playback.service.playAll(position, lastFilter)
}
}
override fun onActionItemClick(view: View, track: ITrack, position: Int) {
val mixin = mixin(ItemContextMenuMixin::class.java)!!
if (categoryType == Metadata.Category.PLAYLISTS) {
mixin.showForPlaylistTrack(track, position, categoryId, categoryValue, view)
}
else {
mixin.showForTrack(track, view)
}
}
}
companion object {
const val TAG = "TrackListFragment"
fun arguments(context: Context,
categoryType: String = "",
categoryId: Long = 0,
categoryValue: String = ""): Bundle = Bundle().apply {
putLong(Track.Extra.SELECTED_ID, categoryId)
putString(Track.Extra.CATEGORY_TYPE, categoryType)
putString(Track.Extra.CATEGORY_VALUE, categoryValue)
if (categoryValue.isNotEmpty()) {
putString(
Shared.Extra.TITLE_OVERRIDE,
context.getString(R.string.songs_from_category, categoryValue))
}
}
fun create(intent: Intent?): TrackListFragment =
create(intent?.extras?.getBundle(Track.Extra.FRAGMENT_ARGUMENTS) ?: Bundle())
fun create(arguments: Bundle = Bundle()): TrackListFragment =
TrackListFragment().apply {
this.arguments = arguments
}
private fun isValidCategory(categoryType: String?, categoryId: Long): Boolean =
categoryType != null && categoryType.isNotEmpty() && categoryId != -1L
}
} | src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/tracks/fragment/TrackListFragment.kt | 2678615905 |
/*
Copyright 2016 StepStone Services
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.stepstone.stepper.sample
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.view.View
class CustomPageTransformerActivity : AbstractStepperActivity() {
override val layoutResId: Int
get() = R.layout.activity_default_dots
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
stepperLayout.setPageTransformer(CrossFadePageTransformer())
}
private class CrossFadePageTransformer : ViewPager.PageTransformer {
override fun transformPage(view: View, position: Float) {
if (position <= -1.0f || position >= 1.0f) {
view.translationX = view.width * position
view.alpha = 0.0f
} else if (position == 0.0f) {
view.translationX = view.width * position
view.alpha = 1.0f
} else {
// position is between -1.0F & 0.0F OR 0.0F & 1.0F
view.translationX = view.width * -position
view.alpha = 1.0f - Math.abs(position)
}
}
}
}
| sample/src/main/java/com/stepstone/stepper/sample/CustomPageTransformerActivity.kt | 3862642196 |
package cc.aoeiuv020.panovel.local
import cc.aoeiuv020.anull.notNull
import cc.aoeiuv020.log.debug
import cc.aoeiuv020.log.error
import cc.aoeiuv020.regex.pick
import cc.aoeiuv020.string.divide
import cc.aoeiuv020.string.lastDivide
import nl.siegmann.epublib.domain.Author
import nl.siegmann.epublib.domain.Book
import nl.siegmann.epublib.domain.Resource
import nl.siegmann.epublib.epub.EpubWriter
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
/**
* TODO: 其他阅读器无法识别,
*
* Created by AoEiuV020 on 2018.06.19-22:53:24.
*/
class EpubExporter(
private val file: File
) : LocalNovelExporter {
private val imagePattern = "^!\\[img\\]\\((.*)\\)$"
private val logger: Logger = LoggerFactory.getLogger(this.javaClass.simpleName)
override fun export(info: LocalNovelInfo, contentProvider: ContentProvider, progressCallback: (Int, Int) -> Unit) {
val book = Book()
val indent = " "
val chapters = info.chapters
val total = chapters.size
progressCallback(0, total)
book.metadata.apply {
addPublisher("PaNovel")
language = "zh"
info.author?.also {
try {
val (first, last) = it.divide(' ')
val firstName = first.trim()
val lastName = last.trim()
addAuthor(Author(firstName, lastName))
logger.debug { "添加作者<$firstName $lastName>" }
} catch (e: Exception) {
addAuthor(Author(it))
logger.debug { "添加作者<$it>" }
}
}
info.name?.also {
addTitle(it)
logger.debug { "添加标题<$it>" }
}
info.introduction?.let { intro ->
try {
intro.split('\n').map(String::trim).filter(String::isNotEmpty)
.takeIf(List<*>::isNotEmpty)
?.fold(Element("div")) { div, it ->
// 没考虑简介有图片的情况,
div.appendElement("p")
.text("$indent$it")
}
} catch (e: Exception) {
// 按理说不会有失败,
logger.error(e) { "导出简介失败," }
null
}
}?.also { div ->
addDescription(div.outerHtml())
}
}
info.image?.let {
try {
val url = contentProvider.getImage(it)
// info.image或者url中一般有图片文件名,
// 但不可控,万一就出现重名的呢,
val fileName = try {
it.lastDivide('/').second
} catch (_: Exception) {
try {
url.toString().lastDivide('/').second
} catch (_: Exception) {
// 失败填充默认jpg一般没问题,
"cover.jpg"
}
}
val resource = url.openStream().use { input ->
Resource(input, fileName)
}
logger.debug {
"添加封面<$url, ${resource.href}>"
}
book.coverImage = resource
} catch (e: Exception) {
// 任何失败就不添加封面了,
logger.error(e) { "导出封面失败" }
}
}
var imageIndex = 0
chapters.forEachIndexed { index, chapter ->
progressCallback(index, total)
val content = contentProvider.getNovelContent(chapter)
// 空章节不导出,
if (content.isEmpty()) return@forEachIndexed
val name = chapter.name
val fileName = "chapter$index.html"
val root = Document.createShell(("file://$OPS_PATH/$fileName"))
root.title(name)
val div = root.body().appendElement("div")
.text("")
// 如果第一行不是章节名,就添加一行章节名,
// 正常正文应该是不包括章节名的,也就是会调用这个的,
if (content.firstOrNull() != name) {
div.appendElement("h2")
.text(name)
}
content.forEach { line ->
val extra = try {
line.pick(imagePattern).first()
} catch (_: Exception) {
// 不是图片就直接保存p标签,
div.appendElement("p")
.text("$indent$line")
return@forEach
}
try {
val url = contentProvider.getImage(extra)
// 如果打开图片输入流返回空,直接抛异常到下面的catch打印普通文本,
logger.debug { "adding image: $url" }
val resource = contentProvider.openImage(url).notNull().use { input ->
val suffix = try {
// 从url中拿文件后辍,
url.toString().lastDivide('.').second
} catch (e: Exception) {
// 失败填充默认jpg一般没问题,
"jpg"
}
Resource(input, "image${imageIndex++}.$suffix")
}
book.addResource(resource)
div.appendElement("p")
.appendElement("img")
.attr("src", resource.href)
// jsoup没有内容的标签不封闭,以防万一加上text就封闭了,
.text("")
} catch (e: Exception) {
logger.error(e) { "导出图片<$extra>出错," }
div.appendElement("p")
.text("$indent[image]")
}
}
val bytes = (root.outerHtml()).toByteArray(Charsets.UTF_8)
val resource = Resource(bytes, fileName)
book.addSection(name, resource)
// 这个guide不知道是否重要,
if (index == 0) {
book.guide.coverPage = resource
}
}
// EpubWriter不带缓冲,加个缓冲,不确定有多大效果,
// 这里use多余,write里面close了,
file.outputStream().buffered().use { output ->
EpubWriter().write(book, output)
}
progressCallback(total, total)
}
companion object {
const val OPS_PATH = "OEBPS"
}
} | local/src/main/java/cc/aoeiuv020/panovel/local/EpubExpoter.kt | 693377649 |
package com.example.alexeyglushkov.cachemanager.clients
import com.example.alexeyglushkov.cachemanager.clients.Cache.CacheMode
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ScopeCacheAdapter(private val cache: Cache, private val scope: CoroutineScope) : ScopeCache {
override var cacheMode: CacheMode
get() = cache.cacheMode
set(value) {
cache.cacheMode = value
}
override suspend fun putValue(key: String, value: Any) {
scope.async {
cache.putValue(key, value)
}.await()
}
override suspend fun <T> getCachedValue(cacheKey: String): T? {
return scope.async {
cache.getCachedValue<T>(cacheKey)
}.await()
}
} | storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/clients/ScopeCacheAdapter.kt | 2787604881 |
package com.example.alexeyglushkov.taskmanager.providers
import androidx.annotation.WorkerThread
import com.example.alexeyglushkov.taskmanager.task.Task
import com.example.alexeyglushkov.taskmanager.pool.TaskPool
/**
* Created by alexeyglushkov on 30.12.14.
*/
// Obligation: a provider defines in which order tasks should be executed
// Obligation: a provider must remove a task from the pool in the takeTopTask method
// Restriction: a provider ignores a task in addTask if the task is not ready to start
// Obligation: a provider changes the status of a task to Task.Status.Waiting in addTask
interface TaskProvider : TaskPool {
// TODO: maybe delete it and force to pass in a constructor
var taskProviderId: String
// TODO: implement it
// priority is used to determine the order of accessing to the providers int a TaskManager
// it affects tasks order if the tasks have the same priority
var priority: Int
var taskFilter: TaskFilter?
@WorkerThread fun getTopTask(): Task?
@WorkerThread fun takeTopTask(): Task?
interface TaskFilter {
fun getFilteredTaskTypes(): List<Int>
fun isFiltered(task: Task): Boolean {
return getFilteredTaskTypes().contains(task.taskType)
}
}
}
| taskmanager/src/main/java/com/example/alexeyglushkov/taskmanager/providers/TaskProvider.kt | 3774607823 |
/* The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.examples.kotlin
import org.neuroph.core.NeuralNetwork
import org.neuroph.core.learning.SupervisedTrainingElement
import org.neuroph.core.learning.TrainingSet
import org.neuroph.nnet.Kohonen
import org.neuroph.nnet.learning.BackPropagation
import java.io.*
import java.util.*
object TestKohonen {
@JvmStatic
var inputSize = 8
@JvmStatic
var outputSize = 1
@JvmStatic
var network: NeuralNetwork? = null
@JvmStatic
var trainingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var testingSet: TrainingSet<SupervisedTrainingElement>? = null
@JvmStatic
var layers = arrayOf(8, 8, 1)
@JvmStatic
fun loadNetwork() {
network = NeuralNetwork.load("D:/GitHub/Neuroph-Intellij-Plugin/TestKohonen.nnet")
}
@JvmStatic
fun trainNetwork() {
val list = ArrayList<Int>()
for (layer in layers) {
list.add(layer)
}
network = Kohonen(inputSize, outputSize)
trainingSet = TrainingSet<SupervisedTrainingElement>(inputSize, outputSize)
trainingSet = TrainingSet.createFromFile("D:/GitHub/NeuralNetworkTest/Classroom Occupation Data.csv", inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val learningRule = BackPropagation()
(network as NeuralNetwork).learningRule = learningRule
(network as NeuralNetwork).learn(trainingSet)
(network as NeuralNetwork).save("D:/GitHub/Neuroph-Intellij-Plugin/TestKohonen.nnet")
}
@JvmStatic
fun testNetwork() {
var input = ""
val fromKeyboard = BufferedReader(InputStreamReader(System.`in`))
val testValues = ArrayList<Double>()
var testValuesDouble: DoubleArray
do {
try {
println("Enter test values or \"\": ")
input = fromKeyboard.readLine()
if (input == "") {
break
}
input = input.replace(" ", "")
val stringVals = input.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
testValues.clear()
for (`val` in stringVals) {
testValues.add(java.lang.Double.parseDouble(`val`))
}
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
} catch (nfe: NumberFormatException) {
nfe.printStackTrace(System.err)
}
testValuesDouble = DoubleArray(testValues.size)
for (t in testValuesDouble.indices) {
testValuesDouble[t] = testValues[t].toDouble()
}
network?.setInput(*testValuesDouble)
network?.calculate()
} while (input != "")
}
@JvmStatic
fun testNetworkAuto(setPath: String) {
var total: Double = 0.0
val list = ArrayList<Int>()
val outputLine = ArrayList<String>()
for (layer in layers) {
list.add(layer)
}
testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>?
val count: Int = testingSet?.elements()?.size!!
var averageDeviance = 0.0
var resultString = ""
try {
val file = File("Results " + setPath)
val fw = FileWriter(file)
val bw = BufferedWriter(fw)
for (i in 0..testingSet?.elements()?.size!! - 1) {
val expected: Double
val calculated: Double
network?.setInput(*testingSet?.elementAt(i)!!.input)
network?.calculate()
calculated = network?.output!![0]
expected = testingSet?.elementAt(i)?.idealArray!![0]
println("Calculated Output: " + calculated)
println("Expected Output: " + expected)
println("Deviance: " + (calculated - expected))
averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected))
total += network?.output!![0]
resultString = ""
for (cols in 0..testingSet?.elementAt(i)?.inputArray?.size!! - 1) {
resultString += testingSet?.elementAt(i)?.inputArray!![cols].toString() + ", "
}
for (t in 0..network?.output!!.size - 1) {
resultString += network?.output!![t].toString() + ", "
}
resultString = resultString.substring(0, resultString.length - 2)
resultString += ""
bw.write(resultString)
bw.flush()
println()
println("Average: " + (total / count).toString())
println("Average Deviance % : " + (averageDeviance / count * 100).toString())
bw.flush()
bw.close()
}
} catch (ex: IOException) {
ex.printStackTrace()
}
}
}
| neuroph-plugin/src/com/thomas/needham/neurophidea/examples/kotlin/TestKohonen.kt | 915377567 |
package org.tvheadend.data.source
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.tvheadend.data.db.AppRoomDatabase
import org.tvheadend.data.entity.Channel
import org.tvheadend.data.entity.ChannelEntity
import org.tvheadend.data.entity.EpgChannel
import timber.log.Timber
import java.util.*
class ChannelDataSource(private val db: AppRoomDatabase) : DataSourceInterface<Channel> {
private val ioScope = CoroutineScope(Dispatchers.IO)
override fun addItem(item: Channel) {
ioScope.launch { db.channelDao.insert(ChannelEntity.from(item)) }
}
fun addItems(items: List<Channel>) {
ioScope.launch { db.channelDao.insert(ArrayList(items.map { ChannelEntity.from(it) })) }
}
override fun updateItem(item: Channel) {
ioScope.launch { db.channelDao.update(ChannelEntity.from(item)) }
}
override fun removeItem(item: Channel) {
ioScope.launch { db.channelDao.delete(ChannelEntity.from(item)) }
}
fun removeItemById(id: Int) {
ioScope.launch { db.channelDao.deleteById(id) }
}
override fun getLiveDataItemCount(): LiveData<Int> {
return db.channelDao.itemCount
}
override fun getLiveDataItems(): LiveData<List<Channel>> {
return MutableLiveData()
}
override fun getLiveDataItemById(id: Any): LiveData<Channel> {
return MutableLiveData()
}
override fun getItemById(id: Any): Channel? {
var channel: Channel?
runBlocking(Dispatchers.IO) {
channel = db.channelDao.loadChannelByIdSync(id as Int)?.toChannel()
}
return channel
}
fun getChannels(sortOrder: Int = 0): List<Channel> {
val channels = ArrayList<Channel>()
runBlocking(Dispatchers.IO) {
channels.addAll(db.channelDao.loadAllChannelsSync(sortOrder).map { it.toChannel() })
}
return channels
}
override fun getItems(): List<Channel> {
return getChannels()
}
fun getItemByIdWithPrograms(id: Int, selectedTime: Long): Channel? {
var channel: Channel?
runBlocking(Dispatchers.IO) {
channel = db.channelDao.loadChannelByIdWithProgramsSync(id, selectedTime)?.toChannel()
}
return channel
}
fun getAllEpgChannels(channelSortOrder: Int, tagIds: List<Int>): LiveData<List<EpgChannel>> {
Timber.d("Loading epg channels with sort order $channelSortOrder and ${tagIds.size} tags")
return if (tagIds.isEmpty()) {
Transformations.map(db.channelDao.loadAllEpgChannels(channelSortOrder)) { entities ->
entities.map { it.toEpgChannel() }
}
} else {
Transformations.map(db.channelDao.loadAllEpgChannelsByTag(channelSortOrder, tagIds)) { entities ->
entities.map { it.toEpgChannel() }
}
}
}
fun getAllChannelsByTime(selectedTime: Long, channelSortOrder: Int, tagIds: List<Int>): LiveData<List<Channel>> {
Timber.d("Loading channels from time $selectedTime with sort order $channelSortOrder and ${tagIds.size} tags")
return if (tagIds.isEmpty()) {
Transformations.map(db.channelDao.loadAllChannelsByTime(selectedTime, channelSortOrder)) { entities ->
entities.map { it.toChannel() }
}
} else {
Transformations.map(db.channelDao.loadAllChannelsByTimeAndTag(selectedTime, channelSortOrder, tagIds)) { entities ->
entities.map { it.toChannel() }
}
}
}
}
| data/src/main/java/org/tvheadend/data/source/ChannelDataSource.kt | 2979319487 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package sample.gitchurn
import kotlinx.cinterop.*
import libgit2.*
class GitCommit(val repository: GitRepository, val commit: CPointer<git_commit>) {
fun close() = git_commit_free(commit)
val summary: String get() = git_commit_summary(commit)!!.toKString()
val time: git_time_t get() = git_commit_time(commit)
val tree: GitTree get() = memScoped {
val treePtr = allocPointerTo<git_tree>()
git_commit_tree(treePtr.ptr, commit).errorCheck()
GitTree(repository, treePtr.value!!)
}
val parents: List<GitCommit> get() = memScoped {
val count = git_commit_parentcount(commit).toInt()
val result = ArrayList<GitCommit>(count)
for (index in 0..count - 1) {
val commitPtr = allocPointerTo<git_commit>()
git_commit_parent(commitPtr.ptr, commit, index.toUInt()).errorCheck()
result.add(GitCommit(repository, commitPtr.value!!))
}
result
}
} | samples/gitchurn/src/gitChurnMain/kotlin/GitCommit.kt | 2688635991 |
package net.nemerosa.ontrack.extension.notifications.webhooks
import net.nemerosa.ontrack.model.annotations.APIDescription
import net.nemerosa.ontrack.model.annotations.APILabel
import net.nemerosa.ontrack.model.annotations.getPropertyDescription
import net.nemerosa.ontrack.model.annotations.getPropertyLabel
import net.nemerosa.ontrack.model.form.*
import net.nemerosa.ontrack.model.structure.ServiceConfiguration
import net.nemerosa.ontrack.model.structure.ServiceConfigurationSource
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/extension/notifications/webhook")
class WebhookController(
private val webhookAdminService: WebhookAdminService,
private val webhookExecutionService: WebhookExecutionService,
private val webhookAuthenticatorRegistry: WebhookAuthenticatorRegistry,
) {
@GetMapping("create")
fun newWebhookForm(): Form = webhookForm(null)
@PostMapping("{name}/ping")
fun pingWebhook(@PathVariable name: String) {
val webhook = webhookAdminService.findWebhookByName(name)
?: throw WebhookNotFoundException(name)
val payload = WebhookPingPayloadData.pingPayload("Webhook $name ping")
webhookExecutionService.send(webhook, payload)
}
private fun webhookForm(webhook: Webhook?): Form = Form.create()
.textField(WebhookForm::name, webhook?.name)
.yesNoField(WebhookForm::enabled, webhook?.enabled ?: true)
.urlField(WebhookForm::url, webhook?.url)
.intField(WebhookForm::timeoutSeconds, webhook?.timeout?.toSeconds()?.toInt() ?: 60)
.with(
ServiceConfigurator.of(WebhookForm::authentication.name)
.label(getPropertyLabel(WebhookForm::authentication))
.help(getPropertyDescription(WebhookForm::authentication))
.sources(
webhookAuthenticatorRegistry.authenticators.map { authenticator ->
ServiceConfigurationSource(
authenticator.type,
authenticator.displayName,
authenticator.getForm(null)
)
}
)
.value(
webhook?.authentication?.run {
ServiceConfiguration(type, config)
}
)
)
data class WebhookForm(
@APIDescription("Webhook unique name")
@APILabel("Name")
val name: String,
@APIDescription("Webhook enabled or not")
@APILabel("Enabled")
val enabled: Boolean,
@APIDescription("Webhook endpoint")
@APILabel("URL")
val url: String,
@APIDescription("Webhook execution timeout (in seconds)")
@APILabel("Timeout")
val timeoutSeconds: Int,
@APIDescription("Webhook authentication")
@APILabel("Authentication")
val authentication: WebhookAuthentication,
)
} | ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/webhooks/WebhookController.kt | 2471995600 |
/*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.owncloud.android.db.ProviderMeta.ProviderTableMeta
@Entity(tableName = ProviderTableMeta.UPLOADS_TABLE_NAME)
data class UploadEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = ProviderTableMeta._ID)
val id: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_LOCAL_PATH)
val localPath: String?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_REMOTE_PATH)
val remotePath: String?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_ACCOUNT_NAME)
val accountName: String?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_FILE_SIZE)
val fileSize: Long?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_STATUS)
val status: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_LOCAL_BEHAVIOUR)
val localBehaviour: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_UPLOAD_TIME)
val uploadTime: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_NAME_COLLISION_POLICY)
val nameCollisionPolicy: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_IS_CREATE_REMOTE_FOLDER)
val isCreateRemoteFolder: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_UPLOAD_END_TIMESTAMP)
val uploadEndTimestamp: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_LAST_RESULT)
val lastResult: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_IS_WHILE_CHARGING_ONLY)
val isWhileChargingOnly: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_IS_WIFI_ONLY)
val isWifiOnly: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_CREATED_BY)
val createdBy: Int?,
@ColumnInfo(name = ProviderTableMeta.UPLOADS_FOLDER_UNLOCK_TOKEN)
val folderUnlockToken: String?
)
| app/src/main/java/com/nextcloud/client/database/entity/UploadEntity.kt | 534497452 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.google.gson.JsonSyntaxException
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.diagnostic.Logger
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.*
class LogEventRecordRequest(val product : String, val user: String, val records: List<LogEventRecord>) {
companion object {
private const val RECORD_SIZE = 1000 * 1000 // 1000KB
private val LOG = Logger.getInstance(LogEventRecordRequest::class.java)
fun create(file: File, filter: LogEventFilter): LogEventRecordRequest? {
try {
return create(file, ApplicationInfo.getInstance().build.productCode, PermanentInstallationID.get(), RECORD_SIZE, filter)
}
catch (e: Exception) {
LOG.warn("Failed reading event log file", e)
return null
}
}
fun create(file: File, product: String, user: String, maxRecordSize: Int, filter: LogEventFilter): LogEventRecordRequest? {
try {
val records = ArrayList<LogEventRecord>()
BufferedReader(FileReader(file.path)).use { reader ->
val sizeEstimator = LogEventRecordSizeEstimator(product, user)
var events = ArrayList<LogEvent>()
var line = fillNextBatch(reader, reader.readLine(), events, sizeEstimator, maxRecordSize, filter)
while (!events.isEmpty()) {
records.add(LogEventRecord(events))
events = ArrayList()
line = fillNextBatch(reader, line, events, sizeEstimator, maxRecordSize, filter)
}
}
return LogEventRecordRequest(product, user, records)
}
catch (e: JsonSyntaxException) {
LOG.warn(e)
}
catch (e: IOException) {
LOG.warn(e)
}
return null
}
private fun fillNextBatch(reader: BufferedReader,
firstLine: String?,
events: MutableList<LogEvent>,
estimator: LogEventRecordSizeEstimator,
maxRecordSize: Int,
filter: LogEventFilter) : String? {
var recordSize = 0
var line = firstLine
while (line != null && recordSize + estimator.estimate(line) < maxRecordSize) {
val event = LogEventSerializer.fromString(line)
if (event != null && filter.accepts(event)) {
recordSize += estimator.estimate(line)
events.add(event)
}
line = reader.readLine()
}
return line
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecordRequest
if (product != other.product) return false
if (user != other.user) return false
if (records != other.records) return false
return true
}
override fun hashCode(): Int {
var result = product.hashCode()
result = 31 * result + user.hashCode()
result = 31 * result + records.hashCode()
return result
}
}
class LogEventRecord(val events: List<LogEvent>) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as LogEventRecord
if (events != other.events) return false
return true
}
override fun hashCode(): Int {
return events.hashCode()
}
}
class LogEventRecordSizeEstimator(product : String, user: String) {
private val formatAdditionalSize = product.length + user.length + 2
fun estimate(line: String) : Int {
return line.length + formatAdditionalSize
}
} | platform/platform-impl/src/com/intellij/internal/statistic/eventLog/LogEventRecordRequest.kt | 1360300308 |
/*
*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2021 Tobias Kaminsky
* Copyright (C) 2021 Nextcloud GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.nextcloud.sso
import com.nextcloud.android.sso.InputStreamBinder
import com.nextcloud.android.sso.QueryParam
import org.junit.Assert.assertEquals
import org.junit.Test
class InputStreamBinderTest {
@Test
fun convertMapToNVP() {
val source = mutableMapOf<String, String>()
source["quality"] = "1024p"
source["someOtherParameter"] = "parameterValue"
source["duplicate"] = "1"
source["duplicate"] = "2" // this overwrites previous parameter
val output = InputStreamBinder.convertMapToNVP(source)
assertEquals(source.size, output.size)
assertEquals("1024p", output[0].value)
assertEquals("parameterValue", output[1].value)
assertEquals("2", output[2].value)
}
@Test
fun convertListToNVP() {
val source = mutableListOf<QueryParam>()
source.add(QueryParam("quality", "1024p"))
source.add(QueryParam("someOtherParameter", "parameterValue"))
source.add(QueryParam("duplicate", "1"))
source.add(QueryParam("duplicate", "2")) // here we can have same parameter multiple times
val output = InputStreamBinder.convertListToNVP(source)
assertEquals(source.size, output.size)
assertEquals("1024p", output[0].value)
assertEquals("parameterValue", output[1].value)
assertEquals("1", output[2].value)
assertEquals("2", output[3].value)
}
}
| app/src/androidTest/java/com/nextcloud/sso/InputStreamBinderTest.kt | 3554659860 |
package com.ethan.and.ui.main
import android.animation.ObjectAnimator
import android.content.*
import android.graphics.drawable.RotateDrawable
import android.net.NetworkInfo
import android.net.wifi.WifiInfo
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.Message
import android.preference.PreferenceManager
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.bumptech.glide.Glide
import com.common.componentes.activity.ImmersiveFragmentActivity
import com.flybd.sharebox.Constants
import com.flybd.sharebox.PreferenceInfo
import com.flybd.sharebox.R
import com.ethan.and.getMainApplication
import com.flybd.sharebox.presenter.MainActivityDelegate
import com.ethan.and.service.MainService
import com.ethan.and.ui.fragment.SplashFragment
import com.flybd.sharebox.util.admob.AdmobCallback
import com.flybd.sharebox.util.admob.AdmobManager
import org.ecjtu.easyserver.IAidlInterface
import org.ecjtu.easyserver.server.DeviceInfo
import org.ecjtu.easyserver.server.impl.service.EasyServerService
import org.ecjtu.easyserver.server.util.cache.ServerInfoParcelableHelper
class MainActivity : ImmersiveFragmentActivity(), MainContract.View {
companion object {
private const val TAG = "MainActivity"
private const val MSG_SERVICE_STARTED = 0x10
const val MSG_START_SERVER = 0x11
const val MSG_STOP_SERVER = 0x14
private const val MSG_LOADING_SERVER = 0x12
const val MSG_CLOSE_APP = -1
const val DEBUG = true
private const val CLOSE_TIME = 3 * 1000
}
private var mDelegate: MainActivityDelegate? = null
private var mAnimator: ObjectAnimator? = null
private var mReceiver: WifiApReceiver? = null
var refreshing = true
private var mService: IAidlInterface? = null
private var mAdManager: AdmobManager? = null
private var mMainService: MainService? = null
private lateinit var presenter: MainContract.Presenter
private var lastBackPressTime = -1L
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// loadSplash()
setContentView(R.layout.activity_main)
var toolbar = findViewById<View>(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
mDelegate = MainActivityDelegate(this)
var drawer = findViewById<View>(R.id.drawer_view)
if (isNavigationBarShow(this)) {
drawer.setPadding(drawer.paddingLeft, drawer.paddingTop, drawer.paddingRight,
drawer.paddingBottom + getNavigationBarHeight(this))
val recyclerView = mDelegate?.getRecyclerView()
recyclerView?.setPadding(recyclerView.paddingLeft, recyclerView.paddingTop, recyclerView.paddingRight,
recyclerView.paddingBottom + getNavigationBarHeight(this))
}
// ad
initAd()
mReceiver = WifiApReceiver()
var filter = IntentFilter()
filter.addAction(mReceiver?.ACTION_WIFI_AP_CHANGED)
filter.addAction(mReceiver?.WIFI_STATE_CHANGED_ACTION)
filter.addAction(mReceiver?.NETWORK_STATE_CHANGED_ACTION)
filter.addAction(mReceiver?.CONNECTIVITY_ACTION)
filter.addAction(org.ecjtu.easyserver.server.Constants.ACTION_CLOSE_SERVER)
filter.addAction(org.ecjtu.easyserver.server.Constants.ACTION_UPDATE_SERVER)
registerReceiver(mReceiver, filter)
presenter = MainPresenter()
}
override fun onResume() {
super.onResume()
presenter.takeView(this)
getMainApplication().closeActivitiesByIndex(1)
var name = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)
(findViewById<View>(R.id.text_name) as TextView).setText(name)
//resume service
val intent = Intent(this, MainService::class.java)
startService(intent)
bindService(intent, mMainServiceConnection, Context.BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
}
override fun onPause() {
super.onPause()
presenter.dropView()
}
override fun onDestroy() {
refreshing = false
mDelegate?.onDestroy()
getHandler()?.removeMessages(MSG_LOADING_SERVER)
unregisterReceiver(mReceiver)
try {
unbindService(mServiceConnection)
} catch (ignore: java.lang.Exception) {
}
try {
unbindService(mMainServiceConnection)
} catch (ignore: java.lang.Exception) {
}
// release main process
System.exit(0)
Glide.get(this).clearMemory()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main_activity, menu)
var item = menu!!.findItem(R.id.refresh)
var rotateDrawable = item.icon as RotateDrawable
mAnimator = ObjectAnimator.ofInt(rotateDrawable, "level", 0, 10000) as ObjectAnimator?
mAnimator?.setRepeatMode(ObjectAnimator.RESTART)
mAnimator?.repeatCount = ObjectAnimator.INFINITE
mAnimator?.setDuration(1000)
mAnimator?.start()
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.refresh -> {
if (mAnimator?.isRunning == true) {
refreshing = false
mAnimator?.cancel()
} else {
refreshing = true
mAnimator?.start()
}
}
}
var result = mDelegate?.onOptionsItemSelected(item) ?: false
if (result) {
return result
}
return super.onOptionsItemSelected(item)
}
private inner class WifiApReceiver : BroadcastReceiver() {
val WIFI_AP_STATE_DISABLING = 10
val WIFI_AP_STATE_DISABLED = 11
val WIFI_AP_STATE_ENABLING = 12
val WIFI_AP_STATE_ENABLED = 13
val WIFI_AP_STATE_FAILED = 14
val WIFI_STATE_ENABLED = 3
val WIFI_STATE_DISABLED = 1
val EXTRA_WIFI_AP_STATE = "wifi_state"
val EXTRA_WIFI_STATE = "wifi_state"
val ACTION_WIFI_AP_CHANGED = "android.net.wifi.WIFI_AP_STATE_CHANGED"
val WIFI_STATE_CHANGED_ACTION = "android.net.wifi.WIFI_STATE_CHANGED"
val NETWORK_STATE_CHANGED_ACTION = "android.net.wifi.STATE_CHANGE"
val CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE"
val EXTRA_WIFI_INFO = "wifiInfo"
val EXTRA_NETWORK_INFO = "networkInfo"
val TYPE_MOBILE = 0
override fun onReceive(context: Context, intent: Intent) {
val state = intent.getIntExtra(EXTRA_WIFI_AP_STATE, -1)
val action = intent.action
if (action == ACTION_WIFI_AP_CHANGED) {
when (state) {
WIFI_AP_STATE_ENABLED -> {
if (mDelegate?.checkCurrentNetwork(null) ?: false) {
if (mService != null) {
getHandler()?.obtainMessage(MSG_START_SERVER)?.sendToTarget()
} else {
startServerService()
}
}
var s = ""
when (state) {
WIFI_AP_STATE_DISABLED -> s = "WIFI_AP_STATE_DISABLED"
WIFI_AP_STATE_DISABLING -> s = "WIFI_AP_STATE_DISABLING"
WIFI_AP_STATE_ENABLED -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_ENABLING -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_FAILED -> s = "WIFI_AP_STATE_FAILED"
}
Log.i("WifiApReceiver", "ap " + s)
}
WIFI_AP_STATE_DISABLED -> {
getHandler()?.obtainMessage(MSG_STOP_SERVER)?.sendToTarget()
mDelegate?.checkCurrentNetwork(null)
}
else -> {
var s = ""
when (state) {
WIFI_AP_STATE_DISABLED -> s = "WIFI_AP_STATE_DISABLED"
WIFI_AP_STATE_DISABLING -> s = "WIFI_AP_STATE_DISABLING"
WIFI_AP_STATE_ENABLED -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_ENABLING -> s = "WIFI_AP_STATE_ENABLED"
WIFI_AP_STATE_FAILED -> s = "WIFI_AP_STATE_FAILED"
}
Log.i("WifiApReceiver", "ap " + s)
}
}
} else if (action == WIFI_STATE_CHANGED_ACTION) { // wifi 连接上时,有可能不会回调
val localState = intent.getIntExtra(EXTRA_WIFI_STATE, -1)
when (localState) {
WIFI_STATE_ENABLED -> {
if (mDelegate?.checkCurrentNetwork(null) ?: false) {
if (mService != null) {
getHandler()?.obtainMessage(MSG_START_SERVER)?.sendToTarget()
} else {
startServerService()
}
}
}
WIFI_STATE_DISABLED -> {
getHandler()?.obtainMessage(MSG_STOP_SERVER)?.sendToTarget()
mDelegate?.checkCurrentNetwork(null)
}
}
} else if (action.equals(NETWORK_STATE_CHANGED_ACTION)) {
var wifiInfo = intent.getParcelableExtra<WifiInfo>(EXTRA_WIFI_INFO)
Log.i("WifiApReceiver", "WifiInfo " + wifiInfo?.toString() ?: "null")
if (wifiInfo != null) {
if (wifiInfo.bssid != null && !wifiInfo.bssid.equals("<none>")) // is a bug in ui
mDelegate?.checkCurrentNetwork(wifiInfo)
}
} else if (action.equals(CONNECTIVITY_ACTION)) {
var info = intent.getParcelableExtra<NetworkInfo>(EXTRA_NETWORK_INFO)
Log.i("WifiApReceiver", "NetworkInfo " + info?.toString() ?: "null")
if (info != null && info.type == TYPE_MOBILE && (info.state == NetworkInfo.State.CONNECTED ||
info.state == NetworkInfo.State.DISCONNECTED)) {
mDelegate?.checkCurrentNetwork(null)
} else if (info != null && (info.state == NetworkInfo.State.CONNECTED)) {
if (mDelegate?.checkCurrentNetwork(null) == true) {
startServerService()
}
}
} else if (action == org.ecjtu.easyserver.server.Constants.ACTION_CLOSE_SERVER) {
getHandler()?.sendEmptyMessage(MSG_CLOSE_APP)
} else if (action == org.ecjtu.easyserver.server.Constants.ACTION_UPDATE_SERVER) {
val pref = PreferenceManager.getDefaultSharedPreferences(this@MainActivity)
val name = pref.getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)
val hostIP = pref.getString(org.ecjtu.easyserver.server.Constants.PREF_KEY_HOST_IP, "")
val port = pref.getInt(org.ecjtu.easyserver.server.Constants.PREF_KEY_HOST_PORT, 0)
if (!TextUtils.isEmpty(hostIP)) {
registerServerInfo(hostIP, port, name, mutableMapOf())
val deviceInfo = getMainApplication().getSavedInstance().get(Constants.KEY_INFO_OBJECT) as DeviceInfo
val helper = ServerInfoParcelableHelper([email protected])
helper.put(Constants.KEY_INFO_OBJECT, deviceInfo)
val intent = EasyServerService.getSetupServerIntent(this@MainActivity, Constants.KEY_INFO_OBJECT)
[email protected](intent)
getHandler()?.removeMessages(MSG_LOADING_SERVER)
getHandler()?.sendEmptyMessage(MSG_START_SERVER)
}
runOnUiThread { mDelegate?.doSearch() }
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
mDelegate?.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private val mServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
Log.e(TAG, "onServiceDisconnected " + name.toString()) // 子进程服务挂掉后会被回调
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
Log.e(TAG, "onServiceConnected " + name.toString())
mService = IAidlInterface.Stub.asInterface(service)
getHandler()?.obtainMessage(MSG_SERVICE_STARTED)?.sendToTarget()
}
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
when (msg.what) {
MSG_SERVICE_STARTED -> {
if (mDelegate?.checkCurrentNetwork(null) ?: false) {
getHandler()?.obtainMessage(MSG_START_SERVER)?.sendToTarget()
}
}
MSG_START_SERVER -> {
if (mService == null) return
var flag = false
if (mService?.isServerAlive() == false && getHandler()?.hasMessages(MSG_LOADING_SERVER) == false) {
flag = true
Log.e(TAG, "isServerAlive false,start server")
var intent = EasyServerService.getApIntent(this)
startService(intent)
getHandler()?.sendEmptyMessageDelayed(MSG_LOADING_SERVER, Int.MAX_VALUE.toLong())
} else if (getHandler()?.hasMessages(MSG_LOADING_SERVER) == false) {
// PreferenceManager.getDefaultSharedPreferences(this).edit().remove(Constants.PREF_SERVER_PORT).apply()
}
if (!flag && mDelegate != null) {
var name = PreferenceManager.getDefaultSharedPreferences(this).getString(PreferenceInfo.PREF_DEVICE_NAME, Build.MODEL)
if (mService != null && mService!!.ip != null && mService!!.port != 0) {
val deviceInfo = getMainApplication().getSavedInstance().get(Constants.KEY_INFO_OBJECT) as DeviceInfo?
deviceInfo?.let {
registerServerInfo(mService!!.ip, mService!!.port, name,
deviceInfo.fileMap)
}
}
runOnUiThread { mDelegate?.doSearch() }
}
}
MSG_STOP_SERVER -> {
stopServerService()
}
MSG_CLOSE_APP -> {
try {
unbindService(mServiceConnection)
unbindService(mMainServiceConnection)
} catch (e: java.lang.Exception) {
} finally {
stopService(Intent(this, EasyServerService::class.java))
stopService(Intent(this, MainService::class.java))
getMainApplication().closeApp()
}
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
mDelegate?.onActivityResult(requestCode, resultCode, data)
}
fun registerServerInfo(hostIP: String, port: Int, name: String, mutableMap: MutableMap<String, List<String>>) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(Constants.PREF_SERVER_PORT, port).apply()
val deviceInfo = getMainApplication().getSavedInstance().get(Constants.KEY_INFO_OBJECT) as DeviceInfo
deviceInfo.apply {
this.name = name
this.ip = hostIP
this.port = port
this.icon = "/API/Icon"
this.fileMap = mutableMap
this.updateTime = System.currentTimeMillis()
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (!DEBUG) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
this.moveTaskToBack(true)
return true
}
}
return super.onKeyDown(keyCode, event)
}
override fun onBackPressed() {
if (lastBackPressTime < 0) {
lastBackPressTime = System.currentTimeMillis()
return
}
if (System.currentTimeMillis() - lastBackPressTime < CLOSE_TIME) {
super.onBackPressed()
}
}
private fun initAd() {
mAdManager = AdmobManager(this)
mAdManager?.loadInterstitialAd(getString(R.string.admob_ad_02), object : AdmobCallback {
override fun onLoaded() {
mAdManager?.getLatestInterstitialAd()?.show()
}
override fun onError() {
mAdManager?.loadInterstitialAd(getString(R.string.admob_ad_02), this)
}
override fun onOpened() {
}
override fun onClosed() {
mAdManager = null
}
})
}
private fun loadSplash() {
val intent = ImmersiveFragmentActivity.newInstance(this, SplashFragment::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NO_ANIMATION
startActivity(intent)
}
private val mMainServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName?) {
mMainService = null
}
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
mMainService = (service as MainService.MainServiceBinder).service
//start server
startServerService()
}
}
fun getMainService(): MainService? {
return mMainService
}
fun getServerService(): IAidlInterface? {
return mService
}
fun stopServerService() {
Log.i(TAG, "stopServerService")
if (mService == null) return
try {
unbindService(mServiceConnection)
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
stopService(Intent(this, EasyServerService::class.java))
mService = null
}
}
fun startServerService() {
Log.i(TAG, "startServerService")
if (mService == null) {
var intent = Intent(this@MainActivity, EasyServerService::class.java)
startService(intent)
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
}
}
}
| share/src/main/java/com/ethan/and/ui/main/MainActivity.kt | 1318438854 |
package domain
import domain.Direction
/**
* Created by quangio.
*/
data class OutsideRequests (val fromFloor: Int, val direction: Direction) | src/main/java/domain/OutsideRequests.kt | 3352819739 |
package ru.churchtools.deskbible.data.cache
interface Cache<T> {
fun getOrNull(key: String): T?
fun getOrDefault(key: String, defaultValue: T): T
fun put(key: String, value: T)
} | bible/src/main/java/ru/churchtools/deskbible/data/cache/Cache.kt | 1789259715 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.nbt.tags
import java.io.DataOutputStream
import java.text.DecimalFormat
import java.text.NumberFormat
import java.util.Locale
class TagDouble(override val value: Double) : NbtValueTag<Double>(Double::class.java) {
override val payloadSize = 8
override val typeId = NbtTypeId.DOUBLE
override fun write(stream: DataOutputStream) {
stream.writeDouble(value)
}
override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString()
override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState): StringBuilder {
return sb.append(FORMATTER.format(value))
}
companion object {
val FORMATTER = (NumberFormat.getInstance(Locale.ROOT) as DecimalFormat).apply {
minimumFractionDigits = 1 // Default NBTT double format always uses a fraction, like in Kotlin
maximumFractionDigits = 20 // Should be more than enough, but let's use 20 just in case
groupingSize = 0 // Disables thousands separator
}
}
}
| src/main/kotlin/nbt/tags/TagDouble.kt | 1517357518 |
/*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.github.mauricio.async.db.column
object DoubleEncoderDecoder : ColumnEncoderDecoder {
override fun decode(value: String): Double = value.toDouble()
}
| db-async-common/src/main/kotlin/com/github/mauricio/async/db/column/DoubleEncoderDecoder.kt | 668896124 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.handlers
import com.demonwav.mcdev.platform.mixin.handlers.injectionPoint.InsnResolutionInfo
import com.demonwav.mcdev.platform.mixin.util.FieldTargetMember
import com.demonwav.mcdev.platform.mixin.util.MethodTargetMember
import com.demonwav.mcdev.platform.mixin.util.findSourceElement
import com.demonwav.mcdev.platform.mixin.util.findSourceField
import com.intellij.psi.PsiAnnotation
import com.intellij.psi.PsiElement
import org.objectweb.asm.tree.ClassNode
interface MixinMemberAnnotationHandler : MixinAnnotationHandler {
override fun isUnresolved(annotation: PsiAnnotation, targetClass: ClassNode): InsnResolutionInfo.Failure? {
return if (resolveTarget(annotation, targetClass).isEmpty()) {
InsnResolutionInfo.Failure()
} else {
null
}
}
override fun resolveForNavigation(annotation: PsiAnnotation, targetClass: ClassNode): List<PsiElement> {
val targets = resolveTarget(annotation, targetClass)
return targets.mapNotNull {
when (it) {
is FieldTargetMember ->
it.classAndField.field.findSourceField(
it.classAndField.clazz,
annotation.project,
annotation.resolveScope,
canDecompile = true
)
is MethodTargetMember ->
it.classAndMethod.method.findSourceElement(
it.classAndMethod.clazz,
annotation.project,
annotation.resolveScope,
canDecompile = true
)
}
}
}
}
| src/main/kotlin/platform/mixin/handlers/MixinMemberAnnotationHandler.kt | 3367543000 |
/*
* Copyright (C) 2017-2022 Alexey Rochev <[email protected]>
*
* This file is part of Tremotesf.
*
* Tremotesf is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Tremotesf is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.equeim.tremotesf.ui.torrentslistfragment
import android.content.Context
import android.widget.AutoCompleteTextView
import org.equeim.tremotesf.R
import org.equeim.tremotesf.torrentfile.rpc.Torrent
import org.equeim.tremotesf.rpc.GlobalRpc
import org.equeim.tremotesf.common.AlphanumericComparator
import org.equeim.tremotesf.ui.utils.AutoCompleteTextViewDynamicAdapter
class TrackersViewAdapter(
private val context: Context,
textView: AutoCompleteTextView
) : AutoCompleteTextViewDynamicAdapter(textView) {
private val trackersMap = mutableMapOf<String, Int>()
val trackers = mutableListOf<String>()
private val comparator = AlphanumericComparator()
private var trackerFilter = ""
override fun getItem(position: Int): String {
if (position == 0) {
return context.getString(R.string.torrents_all, GlobalRpc.torrents.value.size)
}
val tracker = trackers[position - 1]
val torrents = trackersMap[tracker]
return context.getString(R.string.trackers_spinner_text, tracker, torrents)
}
override fun getCount(): Int {
return trackers.size + 1
}
override fun getCurrentItem(): CharSequence {
return getItem(trackers.indexOf(trackerFilter) + 1)
}
fun getTrackerFilter(position: Int): String {
return if (position == 0) {
""
} else {
trackers[position - 1]
}
}
fun update(torrents: List<Torrent>, trackerFilter: String) {
this.trackerFilter = trackerFilter
trackersMap.clear()
for (torrent in torrents) {
for (tracker in torrent.trackerSites) {
trackersMap[tracker] = trackersMap.getOrElse(tracker) { 0 } + 1
}
}
trackers.clear()
trackers.addAll(trackersMap.keys.sortedWith(comparator))
notifyDataSetChanged()
}
} | app/src/main/kotlin/org/equeim/tremotesf/ui/torrentslistfragment/TrackersViewAdapter.kt | 2843834018 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.materialstudies.reply.ui.home
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import com.materialstudies.reply.data.Email
import com.materialstudies.reply.data.EmailDiffCallback
import com.materialstudies.reply.databinding.EmailItemLayoutBinding
/**
* Simple adapter to display Email's in MainActivity.
*/
class EmailAdapter(
private val listener: EmailAdapterListener
) : ListAdapter<Email, EmailViewHolder>(EmailDiffCallback) {
interface EmailAdapterListener {
fun onEmailClicked(cardView: View, email: Email)
fun onEmailLongPressed(email: Email): Boolean
fun onEmailStarChanged(email: Email, newValue: Boolean)
fun onEmailArchived(email: Email)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EmailViewHolder {
return EmailViewHolder(
EmailItemLayoutBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
),
listener
)
}
override fun onBindViewHolder(holder: EmailViewHolder, position: Int) {
holder.bind(getItem(position))
}
} | Reply/app/src/main/java/com/materialstudies/reply/ui/home/EmailAdapter.kt | 2142345535 |
package de.xikolo.controllers.dialogs
import android.annotation.SuppressLint
import android.app.Dialog
import android.content.DialogInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.Html
import android.text.InputType
import android.text.TextWatcher
import android.util.Patterns
import android.view.KeyEvent
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.content.ContextCompat
import butterknife.BindView
import com.yatatsu.autobundle.AutoBundleField
import de.xikolo.App
import de.xikolo.R
import de.xikolo.config.Feature
import de.xikolo.controllers.dialogs.base.ViewModelDialogFragment
import de.xikolo.managers.UserManager
import de.xikolo.models.TicketTopic
import de.xikolo.models.dao.CourseDao
import de.xikolo.utils.extensions.getString
import de.xikolo.utils.extensions.isOnline
import de.xikolo.utils.extensions.showToast
import de.xikolo.viewmodels.helpdesk.TicketViewModel
class CreateTicketDialog : ViewModelDialogFragment<TicketViewModel>(), HelpdeskTopicDialog.HelpdeskTopicListener, ConfirmCancelDialog.ConfirmCancelListener {
companion object {
@JvmField
val TAG: String = CreateTicketDialog::class.java.simpleName
}
@AutoBundleField(required = false)
var courseId: String? = null
@BindView(R.id.ticketContent)
lateinit var messageEditText: EditText
@BindView(R.id.textInputLayoutEmail)
lateinit var emailContainer: ViewGroup
@BindView(R.id.ticketEmail)
lateinit var emailEditText: EditText
@BindView(R.id.ticketTitle)
lateinit var titleEditText: EditText
@BindView(R.id.ticketTopic)
lateinit var ticketTopicEditText: EditText
@BindView(R.id.ticketInfoText)
lateinit var ticketInfoText: TextView
@BindView(R.id.infoCard)
lateinit var infoCard: ViewGroup
@BindView(R.id.infoCardText)
lateinit var infoCardText: TextView
private var topic: TicketTopic = TicketTopic.NONE
override val layoutResource = R.layout.dialog_helpdesk_create_ticket
override fun createViewModel(): TicketViewModel {
return TicketViewModel()
}
@SuppressLint("SetTextI18n")
override fun onDialogViewCreated(view: View, savedInstanceState: Bundle?) {
super.onDialogViewCreated(view, savedInstanceState)
if (!context.isOnline) {
showToast(R.string.toast_no_network)
dialog?.cancel()
return
}
networkStateHelper.enableSwipeRefresh(false)
if (courseId == null) {
changeTopic(false)
} else {
ticketTopicEditText.setText(CourseDao.Unmanaged.find(courseId)?.title)
topic = TicketTopic.COURSE
}
if (UserManager.isAuthorized) {
emailContainer.visibility = View.GONE
ticketInfoText.text = getString(R.string.helpdesk_info_text_logged_in)
}
if (Feature.enabled("url_faq")) {
var text = getString(R.string.helpdesk_info_text_faq) +
" " + getString(R.string.helpdesk_info_text_forum)
var html = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(text)
}
infoCardText.text = html
infoCard.setOnClickListener {
activity?.let {
CustomTabsIntent.Builder()
.setToolbarColor(ContextCompat.getColor(
App.instance,
R.color.apptheme_primary
))
.build()
.launchUrl(it, Uri.parse(it.getString("url_faq")))
}
}
} else {
infoCardText.text = getString(R.string.helpdesk_info_text_forum)
}
//listeners for wrong entries in EditTexts after focusing another view
titleEditText.setOnFocusChangeListener { _, b ->
if (titleEditText.text.isEmpty() && !b) {
titleEditText.error = getString(R.string.helpdesk_title_error)
}
setPositiveButton()
}
messageEditText.setOnFocusChangeListener { _, b ->
if (messageEditText.text.isEmpty() && !b) {
messageEditText.error = getString(R.string.helpdesk_message_error)
}
setPositiveButton()
}
emailEditText.setOnFocusChangeListener { _, b ->
if ((!Patterns.EMAIL_ADDRESS.matcher(emailEditText.text).matches() || emailEditText.text.isEmpty()) &&
emailContainer.visibility != View.GONE && !b) {
emailEditText.error = getString(R.string.helpdesk_email_error)
}
}
//listeners for positive button to change while typing
val textWatcher = object : TextWatcher {
override fun afterTextChanged(p0: Editable?) {}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
setPositiveButton()
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
}
messageEditText.addTextChangedListener(textWatcher)
emailEditText.addTextChangedListener(textWatcher)
titleEditText.addTextChangedListener(textWatcher)
ticketTopicEditText.addTextChangedListener(textWatcher)
ticketTopicEditText.setOnClickListener {
changeTopic(true)
}
ticketTopicEditText.inputType = InputType.TYPE_NULL
showContent()
}
override fun onResume() {
super.onResume()
(dialog as? AlertDialog)?.apply {
getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener {
cancel(this)
}
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
if (context.isOnline) {
viewModel.send(titleEditText.text.toString(), messageEditText.text.toString(), topic, emailEditText.text.toString(), courseId)
dialog?.dismiss()
} else {
showToast(R.string.toast_no_network)
}
}
}
//needed for initial disabling of positive button
setPositiveButton()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return AlertDialog.Builder(requireActivity())
.setNegativeButton(R.string.dialog_negative) { _: DialogInterface, _: Int ->
//see onResume
}
.setPositiveButton(R.string.dialog_send) { _: DialogInterface, _: Int ->
//see onResume
}
.setView(dialogView)
.setTitle(R.string.helpdesk_dialog_header)
.setOnCancelListener { dialog: DialogInterface ->
cancel(dialog)
}
.setOnKeyListener { dialog, keyCode, keyEvent ->
if (keyEvent.action == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
cancel(dialog)
return@setOnKeyListener true
}
false
}
.create()
}
private fun cancel(dialog: DialogInterface) {
if (atLeastOneFieldHasInput) {
confirmCancel()
} else {
dialog.dismiss()
}
}
private fun changeTopic(isChange: Boolean) {
val dialog = HelpdeskTopicDialogAutoBundle.builder().fromTicketDialog(isChange).build()
dialog.listener = this
dialog.show(fragmentManager!!, HelpdeskTopicDialog.TAG)
}
override fun onTopicChosen(title: String?, topic: TicketTopic, courseId: String?) {
this.courseId = courseId
this.topic = topic
ticketTopicEditText.setText(title)
}
fun setPositiveButton() {
(dialog as AlertDialog).getButton(AlertDialog.BUTTON_POSITIVE)?.isEnabled = allFieldsHaveInput
}
override fun closeTicketDialog() {
dialog?.dismiss()
}
override fun onConfirmCancel() {
closeTicketDialog()
}
private val atLeastOneFieldHasInput: Boolean
get() =
(titleEditText.text.isNotEmpty() ||
messageEditText.text.isNotEmpty() ||
emailEditText.text.isNotEmpty())
private val allFieldsHaveInput: Boolean
get() = titleEditText.text.isNotEmpty() &&
messageEditText.text.isNotEmpty() &&
ticketTopicEditText.text.isNotEmpty() &&
((emailEditText.text.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(emailEditText.text).matches()) ||
emailContainer.visibility == View.GONE) && topic !== TicketTopic.NONE
private fun confirmCancel() {
val dialog = ConfirmCancelDialog()
dialog.listener = this
dialog.show(fragmentManager!!, ConfirmCancelDialog.TAG)
}
}
| app/src/main/java/de/xikolo/controllers/dialogs/CreateTicketDialog.kt | 364872760 |
package com.soywiz.korge.service.storage
import com.soywiz.kds.*
import com.soywiz.korge.view.*
/** Cross-platform way of synchronously storing small data */
expect class NativeStorage(views: Views) : IStorage {
fun keys(): List<String>
override fun set(key: String, value: String)
override fun getOrNull(key: String): String?
override fun remove(key: String)
override fun removeAll()
}
fun NativeStorage.toMap() = keys().associateWith { getOrNull(it) }
val Views.storage: NativeStorage by Extra.PropertyThis<Views, NativeStorage> { NativeStorage(this) }
val ViewsContainer.storage: NativeStorage get() = this.views.storage
| korge/src/commonMain/kotlin/com/soywiz/korge/service/storage/NativeStorage.kt | 2409014508 |
/*
* This file is part of git-as-svn. It is subject to the license terms
* in the LICENSE file found in the top-level directory of this distribution
* and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn,
* including this file, may be copied, modified, propagated, or distributed
* except according to the terms contained in the LICENSE file.
*/
package svnserver.repository.git.path.matcher.name
import svnserver.repository.git.path.NameMatcher
/**
* Simple matcher for mask with only one asterisk.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class SimpleMatcher constructor(private val prefix: String, private val suffix: String, private val dirOnly: Boolean) : NameMatcher {
override fun isMatch(name: String, isDir: Boolean): Boolean {
return (!dirOnly || isDir) && (name.length >= prefix.length + suffix.length) && name.startsWith(prefix) && name.endsWith(suffix)
}
override val isRecursive: Boolean
get() {
return false
}
override val svnMask: String
get() {
return "$prefix*$suffix"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val that: SimpleMatcher = other as SimpleMatcher
return ((dirOnly == that.dirOnly)
&& ((prefix == that.prefix))
&& (suffix == that.suffix))
}
override fun hashCode(): Int {
var result: Int = prefix.hashCode()
result = 31 * result + suffix.hashCode()
result = 31 * result + (if (dirOnly) 1 else 0)
return result
}
override fun toString(): String {
return prefix + "*" + suffix + (if (dirOnly) "/" else "")
}
}
| src/main/kotlin/svnserver/repository/git/path/matcher/name/SimpleMatcher.kt | 3380017747 |
package co.nums.intellij.aem.htl.inspections
import co.nums.intellij.aem.htl.HtlAnnotatorTestBase
class DisallowedHtlAttributeBlockQuickFixTest : HtlAnnotatorTestBase() {
// change attribute
fun testChangeStyleAttributeCaretAtBeginning() = checkQuickFix(
"Change 'data-sly-attribute.style' to 'style'",
"""<div <caret>data-sly-attribute.style="any"></div>""",
"""<div <caret>style="any"></div>""")
fun testChangeStyleAttributeCaretInMiddle() = checkQuickFix(
"Change 'data-sly-attribute.style' to 'style'",
"""<div data-sly-<caret>attribute.style="any"></div>""",
"""<div <caret>style="any"></div>""")
fun testChangeStyleAttributeCaretAtEnd() = checkQuickFix(
"Change 'data-sly-attribute.style' to 'style'",
"""<div data-sly-attribute.style<caret>="any"></div>""",
"""<div style<caret>="any"></div>""")
fun testChangeOnClickDashedAttributeCaretAtBeginning() = checkQuickFix(
"Change 'data-sly-attribute.on-click' to 'on-click'",
"""<div <caret>data-sly-attribute.on-click="any"></div>""",
"""<div <caret>on-click="any"></div>""")
fun testChangeOnClickDashedAttributeCaretInMiddle() = checkQuickFix(
"Change 'data-sly-attribute.on-click' to 'on-click'",
"""<div data-sly-<caret>attribute.on-click="any"></div>""",
"""<div <caret>on-click="any"></div>""")
fun testChangeOnClickDashedAttributeCaretAtEnd() = checkQuickFix(
"Change 'data-sly-attribute.on-click' to 'on-click'",
"""<div data-sly-attribute.on-click<caret>="any"></div>""",
"""<div on-click<caret>="any"></div>""")
// remove attribute
fun testRemoveStyleAttributeCaretAtBeginning() = checkQuickFix(
"Remove 'data-sly-attribute.style'",
"""<div <caret>data-sly-attribute.style="any"></div>""",
"""<div <caret>></div>""")
fun testRemoveStyleAttributeCaretInMiddle() = checkQuickFix(
"Remove 'data-sly-attribute.style'",
"""<div data-sly-<caret>attribute.style="any"></div>""",
"""<div <caret>></div>""")
fun testRemoveStyleAttributeCaretAtEnd() = checkQuickFix(
"Remove 'data-sly-attribute.style'",
"""<div data-sly-attribute.style<caret>="any"></div>""",
"""<div <caret>></div>""")
fun testRemoveOnClickDashedAttributeCaretAtBeginning() = checkQuickFix(
"Remove 'data-sly-attribute.on-click'",
"""<div <caret>data-sly-attribute.on-click="any"></div>""",
"""<div <caret>></div>""")
fun testRemoveOnClickDashedAttributeCaretInMiddle() = checkQuickFix(
"Remove 'data-sly-attribute.on-click'",
"""<div data-sly-<caret>attribute.on-click="any"></div>""",
"""<div <caret>></div>""")
fun testRemoveOnClickDashedAttributeCaretAtEnd() = checkQuickFix(
"Remove 'data-sly-attribute.on-click'",
"""<div data-sly-attribute.on-click<caret>="any"></div>""",
"""<div <caret>></div>""")
}
| src/test/kotlin/co/nums/intellij/aem/htl/inspections/DisallowedHtlAttributeBlockQuickFixTest.kt | 4200470756 |
package ru.dageev.compiler.bytecodegeneration.expression
import jdk.internal.org.objectweb.asm.MethodVisitor
import jdk.internal.org.objectweb.asm.Opcodes
import ru.dageev.compiler.domain.node.expression.VariableReference
import ru.dageev.compiler.domain.scope.Scope
/**
* Created by dageev
* on 11/27/16.
*/
class FieldReferenceGenerator(val scope: Scope, val methodVisitor: MethodVisitor) {
fun generate(localVariableReference: VariableReference.LocalVariableReference) {
val index = scope.localVariables.indexOf(localVariableReference.localVariable.name)
methodVisitor.visitVarInsn(localVariableReference.localVariable.type.getLoadVariableOpcode(), index)
}
fun generate(fieldReference: VariableReference.FieldReference) {
methodVisitor.visitVarInsn(Opcodes.ALOAD, 0)
methodVisitor.visitFieldInsn(Opcodes.GETFIELD, fieldReference.field.ownerType.getInternalName(), fieldReference.field.name, fieldReference.field.type.getDescriptor())
}
} | src/main/kotlin/ru/dageev/compiler/bytecodegeneration/expression/FieldReferenceGenerator.kt | 486848238 |
/*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.test.request.internal
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.panpf.sketch.datasource.DataFrom.MEMORY
import com.github.panpf.sketch.request.DownloadData
import com.github.panpf.sketch.request.DownloadRequest
import com.github.panpf.sketch.request.DownloadResult
import com.github.panpf.sketch.request.Listener
import com.github.panpf.sketch.request.internal.CombinedListener
import com.github.panpf.sketch.test.utils.getTestContext
import com.github.panpf.sketch.util.UnknownException
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class CombinedListenerTest {
@Test
fun test() {
val listenerCallbackList = mutableListOf<String>()
Assert.assertEquals(listOf<String>(), listenerCallbackList)
val listener1 =
object : Listener<DownloadRequest, DownloadResult.Success, DownloadResult.Error> {
override fun onStart(request: DownloadRequest) {
super.onStart(request)
listenerCallbackList.add("onStart1")
}
override fun onSuccess(request: DownloadRequest, result: DownloadResult.Success) {
super.onSuccess(request, result)
listenerCallbackList.add("onSuccess1")
}
override fun onError(request: DownloadRequest, result: DownloadResult.Error) {
super.onError(request, result)
listenerCallbackList.add("onError1")
}
override fun onCancel(request: DownloadRequest) {
super.onCancel(request)
listenerCallbackList.add("onCancel1")
}
}
val listener2 =
object : Listener<DownloadRequest, DownloadResult.Success, DownloadResult.Error> {
override fun onStart(request: DownloadRequest) {
super.onStart(request)
listenerCallbackList.add("onStart2")
}
override fun onSuccess(request: DownloadRequest, result: DownloadResult.Success) {
super.onSuccess(request, result)
listenerCallbackList.add("onSuccess2")
}
override fun onError(request: DownloadRequest, result: DownloadResult.Error) {
super.onError(request, result)
listenerCallbackList.add("onError2")
}
override fun onCancel(request: DownloadRequest) {
super.onCancel(request)
listenerCallbackList.add("onCancel2")
}
}
val context = getTestContext()
val request = DownloadRequest(context, "http://sample.com/sample.jpeg")
val combinedListener = CombinedListener(listener1, listener2)
Assert.assertSame(listener1, combinedListener.fromProviderListener)
Assert.assertSame(listener2, combinedListener.fromBuilderListener)
combinedListener.onStart(request)
Assert.assertEquals(listOf("onStart1", "onStart2"), listenerCallbackList)
combinedListener.onError(request, DownloadResult.Error(request, UnknownException("")))
Assert.assertEquals(
listOf("onStart1", "onStart2", "onError1", "onError2"),
listenerCallbackList
)
combinedListener.onCancel(request)
Assert.assertEquals(
listOf(
"onStart1",
"onStart2",
"onError1",
"onError2",
"onCancel1",
"onCancel2"
), listenerCallbackList
)
combinedListener.onSuccess(
request,
DownloadResult.Success(request, DownloadData(byteArrayOf(), MEMORY))
)
Assert.assertEquals(
listOf(
"onStart1",
"onStart2",
"onError1",
"onError2",
"onCancel1",
"onCancel2",
"onSuccess1",
"onSuccess2"
), listenerCallbackList
)
}
} | sketch/src/androidTest/java/com/github/panpf/sketch/test/request/internal/CombinedListenerTest.kt | 2066029275 |
package de.saschahlusiak.freebloks.model
import java.io.Serializable
data class Turn(val player: Int, val shape: Shape, val orientation: Orientation, val y: Int, val x: Int) : Serializable {
constructor(from: Turn): this(from.player, from.shape, from.orientation, from.y, from.x)
constructor(player: Int, shape: Int, y: Int, x: Int, orientation: Orientation) : this(player, Shape.get(shape), orientation, y, x)
val shapeNumber = shape.number
companion object {
private const val serialVersionUID = 1L
}
} | game/src/main/java/de/saschahlusiak/freebloks/model/Turn.kt | 861502714 |
package com.icapps.niddler.ui.form.components
interface StackTraceComponent : UIComponent {
fun setStackTrace(stackTrace: List<String>?)
} | niddler-ui/src/main/kotlin/com/icapps/niddler/ui/form/components/StackTraceComponent.kt | 3276404215 |
package de.cineaste.android.activity
import android.app.ActivityOptions
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Pair
import android.view.Menu
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import com.google.gson.JsonParser
import de.cineaste.android.R
import de.cineaste.android.listener.ItemClickListener
import de.cineaste.android.network.NetworkCallback
import de.cineaste.android.network.NetworkResponse
import de.cineaste.android.util.DateAwareGson
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.lang.reflect.Type
abstract class AbstractSearchActivity : AppCompatActivity(), ItemClickListener {
internal val gson = DateAwareGson.gson
internal lateinit var recyclerView: RecyclerView
internal lateinit var progressBar: ProgressBar
private lateinit var searchView: SearchView
private var searchText: String? = null
protected abstract val layout: Int
protected abstract val listAdapter: RecyclerView.Adapter<*>
protected abstract val listType: Type
val networkCallback: NetworkCallback
get() = object : NetworkCallback {
override fun onFailure() {
GlobalScope.launch(Main) { showNetworkError() }
}
override fun onSuccess(response: NetworkResponse) {
val responseObject = JsonParser.parseReader(response.responseReader).asJsonObject
val json = responseObject.get("results").toString()
val listType = listType
GlobalScope.launch(Main) { getRunnable(json, listType).run() }
}
}
protected abstract fun getIntentForDetailActivity(itemId: Long): Intent
protected abstract fun initAdapter()
protected abstract fun getSuggestions()
protected abstract fun searchRequest(searchQuery: String)
protected abstract fun getRunnable(json: String, listType: Type): Runnable
override fun onItemClickListener(itemId: Long, views: Array<View>) {
val intent = getIntentForDetailActivity(itemId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val options = ActivityOptions.makeSceneTransitionAnimation(
this,
Pair.create(views[0], "card"),
Pair.create(views[1], "poster")
)
this.startActivity(intent, options.toBundle())
} else {
this.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout)
initToolbar()
if (savedInstanceState != null) {
searchText = savedInstanceState.getString("query", "").replace("+", " ")
}
progressBar = findViewById(R.id.progressBar)
recyclerView = findViewById(R.id.search_recycler_view)
val layoutManager = LinearLayoutManager(this)
val divider = ContextCompat.getDrawable(recyclerView.context, R.drawable.divider)
val itemDecor = DividerItemDecoration(
recyclerView.context,
layoutManager.orientation
)
divider?.let {
itemDecor.setDrawable(it)
}
recyclerView.addItemDecoration(itemDecor)
initAdapter()
recyclerView.itemAnimator = DefaultItemAnimator()
recyclerView.layoutManager = layoutManager
recyclerView.adapter = listAdapter
progressBar.visibility = View.VISIBLE
getSuggestions()
}
private fun initToolbar() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val actionBar = supportActionBar
actionBar?.setDisplayHomeAsUpEnabled(true)
}
public override fun onSaveInstanceState(outState: Bundle) {
if (!TextUtils.isEmpty(searchText)) {
outState.putString("query", searchText)
}
super.onSaveInstanceState(outState)
}
public override fun onPause() {
super.onPause()
val outState = Bundle()
outState.putString("query", searchText)
onSaveInstanceState(outState)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val menuInflater = menuInflater
menuInflater.inflate(R.menu.search_menu, menu)
val searchItem = menu.findItem(R.id.action_search)
if (searchItem != null) {
searchView = searchItem.actionView as SearchView
searchView.isFocusable = true
searchView.isIconified = false
searchView.requestFocusFromTouch()
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
return false
}
override fun onQueryTextChange(query: String): Boolean {
var myQuery = query
if (myQuery.isNotEmpty()) {
myQuery = myQuery.replace(" ", "+")
progressBar.visibility = View.VISIBLE
scheduleSearchRequest(myQuery)
searchText = myQuery
} else {
getSuggestions()
}
return false
}
})
if (!TextUtils.isEmpty(searchText))
searchView.setQuery(searchText, false)
}
return super.onCreateOptionsMenu(menu)
}
private fun scheduleSearchRequest(query: String) {
searchView.removeCallbacks(getSearchRunnable(query))
searchView.postDelayed(getSearchRunnable(query), 500)
}
private fun getSearchRunnable(searchQuery: String): Runnable {
return Runnable { searchRequest(searchQuery) }
}
private fun showNetworkError() {
val snackBar = Snackbar
.make(recyclerView, R.string.noInternet, Snackbar.LENGTH_LONG)
snackBar.show()
}
override fun onStop() {
super.onStop()
val view = currentFocus
if (view != null) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromInputMethod(view.windowToken, 0)
}
}
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return super.onSupportNavigateUp()
}
}
| app/src/main/kotlin/de/cineaste/android/activity/AbstractSearchActivity.kt | 1480603550 |
/*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.model.tab.impl
import android.content.Context
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.annotation.AccountType
import de.vanita5.twittnuker.annotation.TabAccountFlags
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_USER_LIST
import de.vanita5.twittnuker.fragment.statuses.UserListTimelineFragment
import de.vanita5.twittnuker.model.AccountDetails
import de.vanita5.twittnuker.model.Tab
import de.vanita5.twittnuker.model.tab.DrawableHolder
import de.vanita5.twittnuker.model.tab.StringHolder
import de.vanita5.twittnuker.model.tab.TabConfiguration
import de.vanita5.twittnuker.model.tab.argument.UserListArguments
import de.vanita5.twittnuker.model.tab.conf.UserListExtraConfiguration
class UserListTimelineTabConfiguration : TabConfiguration() {
override val name = StringHolder.resource(R.string.list_timeline)
override val icon = DrawableHolder.Builtin.LIST
override val accountFlags = TabAccountFlags.FLAG_HAS_ACCOUNT or
TabAccountFlags.FLAG_ACCOUNT_REQUIRED
override val fragmentClass = UserListTimelineFragment::class.java
override fun checkAccountAvailability(details: AccountDetails) = when (details.type) {
AccountType.TWITTER -> true
else -> false
}
override fun getExtraConfigurations(context: Context) = arrayOf(
UserListExtraConfiguration(EXTRA_USER_LIST).headerTitle(R.string.title_user_list)
)
override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
val arguments = tab.arguments as UserListArguments
when (extraConf.key) {
EXTRA_USER_LIST -> {
val userList = (extraConf as UserListExtraConfiguration).value ?: return false
arguments.listId = userList.id
}
}
return true
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/tab/impl/UserListTimelineTabConfiguration.kt | 509359695 |
package com.github.kotlinz.kotlinz.data.identity
import com.github.kotlinz.kotlinz.K1
import com.github.kotlinz.kotlinz.type.monad.MonadOps
interface IdentityMonadOps: MonadOps<Identity.T>, IdentityMonad {
override fun <A, B> liftM(f: (A) -> B): (K1<Identity.T, A>) -> K1<Identity.T, B> {
return { m ->
val i = Identity.narrow(m)
i bind { x -> Identity.pure(f(x)) }
}
}
override fun <A, B, C> liftM2(f: (A, B) -> C): (K1<Identity.T, A>, K1<Identity.T, B>) -> K1<Identity.T, C> {
return { m1, m2 ->
val i1 = Identity.narrow(m1)
val i2 = Identity.narrow(m2)
i1 bind { x1 -> i2 bind { x2 -> Identity.pure(f(x1, x2)) } }
}
}
override fun <A, B, C, D> liftM3(f: (A, B, C) -> D): (K1<Identity.T, A>, K1<Identity.T, B>, K1<Identity.T, C>) -> K1<Identity.T, D> {
return { m1, m2, m3 ->
val i1 = Identity.narrow(m1)
val i2 = Identity.narrow(m2)
val i3 = Identity.narrow(m3)
i1 bind { x1 -> i2 bind { x2 -> i3 bind { x3 -> Identity.pure(f(x1, x2, x3)) } } }
}
}
} | src/main/kotlin/com/github/kotlinz/kotlinz/data/identity/IdentityMonadOps.kt | 2974126882 |
private var p = 1e9.toInt().toLong()
/**
* set true to enable debug
*/
internal var debug = false
private fun log2(x: Long): Int {
var x = x
var ans = 0
while (true) {
x = x shr 1
if (x == 0L) break
ans++
}
return ans
}
private fun mul(x: Long, y: Long, z: Long): Long {
var x = x
var y = y
if (z == 2L) {
when {
x and 1 != 0L -> y = y shr 1
y and 1 != 0L -> x = x shr 1
else -> throw RuntimeException("shit")
}
}
return x % p * (y % p) % p
}
private fun sumTimes(first: Long, n: Long, k: Long, t: Long): Long {
var first = first
var n = n
first -= k
if (first < 1) {
n -= 1 - first
first = 1
}
return if (n <= 0) 0 else mul(mul(first + first + n - 1, n, 2L), t, 1)
}
internal fun elderAge(n: Long, m: Long, k: Long, newp: Long): Long {
var n = n
var m = m
var k = k
if (n == 0L || m == 0L) return 0
if (k < 0) k = 0
if (n < m) {
val tmp = n
n = m
m = tmp
}
p = newp
if (n == m && n and -n == n) return sumTimes(1, n - 1, k, m)
val N = log2(n)
val M = log2(m)
val centerWidth = 1L shl N
val centerHeight = 1L shl M
if (N == M) {
val rightWidth = n - centerWidth
val bottomHeight = m - centerHeight
val bottomSum = sumTimes(centerHeight, centerWidth, k, bottomHeight)
return ((sumTimes(centerWidth, centerHeight, k, rightWidth) + bottomSum) % p + (elderAge(rightWidth, bottomHeight, k, p) + elderAge(centerWidth, centerHeight, k, p)) % p) % p
} else {
val leftWidth = 1L shl N
val leftSum = sumTimes(0, leftWidth, k, m)
var rightSum = elderAge(n - leftWidth, m, k - leftWidth, p)
if (leftWidth > k) {
rightSum += mul(mul(leftWidth - k, m, 1), n - leftWidth, 1)
rightSum %= p
}
return (leftSum + rightSum) % p
}
}
| codewars/authoring/kotlin/Immortal.kt | 2848691643 |
package ru.molkov.collapsarserver.setting
import java.text.SimpleDateFormat
import java.util.*
object DateHelper {
val DF_SIMPLE_FORMAT: SimpleDateFormat = SimpleDateFormat(Constants.Companion.NASA_DATE_FORMAT, Locale.US)
}
fun Date.asString(): String = DateHelper.DF_SIMPLE_FORMAT.format(this) | src/main/kotlin/ru/molkov/collapsarserver/setting/Extensions.kt | 3806838190 |
package com.github.ymkawb.moneyback.model
/**
* Created by nivanov on 03/03/17.
*/
abstract class Operation{} | app/src/main/java/com/github/ymkawb/moneyback/model/Operation.kt | 1026263886 |
package abi43_0_0.host.exp.exponent.modules.api.screens
import abi43_0_0.com.facebook.react.ReactPackage
import abi43_0_0.com.facebook.react.bridge.NativeModule
import abi43_0_0.com.facebook.react.bridge.ReactApplicationContext
import abi43_0_0.com.facebook.react.uimanager.ViewManager
class RNScreensPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext) =
emptyList<NativeModule>()
override fun createViewManagers(reactContext: ReactApplicationContext) =
listOf<ViewManager<*, *>>(
ScreenContainerViewManager(),
ScreenViewManager(),
ScreenStackViewManager(),
ScreenStackHeaderConfigViewManager(),
ScreenStackHeaderSubviewManager()
)
}
| android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/modules/api/screens/RNScreensPackage.kt | 3021635261 |
package expo.modules.kotlin
import expo.modules.kotlin.events.EventName
import expo.modules.kotlin.modules.Module
import java.lang.ref.WeakReference
class ModuleRegistry(
private val appContext: WeakReference<AppContext>
) : Iterable<ModuleHolder> {
private val registry = mutableMapOf<String, ModuleHolder>()
fun register(module: Module) {
val holder = ModuleHolder(module)
module._appContext = requireNotNull(appContext.get()) { "Cannot create a module for invalid app context." }
holder.post(EventName.MODULE_CREATE)
registry[holder.name] = holder
}
fun register(provider: ModulesProvider) = apply {
provider.getModulesList().forEach { type ->
val module = type.newInstance()
register(module)
}
}
fun hasModule(name: String): Boolean = registry.containsKey(name)
fun getModule(name: String): Module? = registry[name]?.module
fun getModuleHolder(name: String): ModuleHolder? = registry[name]
fun getModuleHolder(module: Module): ModuleHolder? =
registry.values.find { it.module === module }
fun post(eventName: EventName) {
forEach {
it.post(eventName)
}
}
@Suppress("UNCHECKED_CAST")
fun <Sender> post(eventName: EventName, sender: Sender) {
forEach {
it.post(eventName, sender)
}
}
@Suppress("UNCHECKED_CAST")
fun <Sender, Payload> post(eventName: EventName, sender: Sender, payload: Payload) {
forEach {
it.post(eventName, sender, payload)
}
}
override fun iterator(): Iterator<ModuleHolder> = registry.values.iterator()
}
| packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/ModuleRegistry.kt | 4032985567 |
/**
* Designed and developed by Aidan Follestad (@afollestad)
*
* 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.afollestad.photoaffix.engine
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat.PNG
import com.afollestad.photoaffix.engine.bitmaps.BitmapIterator
import com.afollestad.photoaffix.engine.bitmaps.BitmapManipulator
import com.afollestad.photoaffix.engine.photos.Photo
import com.afollestad.photoaffix.engine.subengines.DimensionsEngine
import com.afollestad.photoaffix.engine.subengines.ProcessingResult
import com.afollestad.photoaffix.engine.subengines.Size
import com.afollestad.photoaffix.engine.subengines.SizingResult
import com.afollestad.photoaffix.engine.subengines.StitchEngine
import com.afollestad.photoaffix.utilities.IoManager
import com.google.common.truth.Truth.assertThat
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.coroutines.runBlocking
import org.junit.Test
import java.io.File
class AffixEngineTest {
private val photos = listOf(
Photo(0, "file://idk/1", 0, testUriParser),
Photo(0, "file://idk/2", 0, testUriParser)
)
private val ioManager = mock<IoManager>()
private val bitmapManipulator = mock<BitmapManipulator>()
private val bitmapIterator = BitmapIterator(photos, bitmapManipulator)
private val dimensionsEngine = mock<DimensionsEngine>()
private val stitchEngine = mock<StitchEngine>()
private val engine = RealAffixEngine(
ioManager,
bitmapManipulator,
dimensionsEngine,
stitchEngine
)
// Process
@Test fun process() = runBlocking {
val size = Size(width = 1, height = 1)
val sizingResult = SizingResult(size = size)
whenever(dimensionsEngine.calculateSize(any()))
.doReturn(sizingResult)
val processResult = engine.process(photos)
assertThat(engine.getBitmapIterator().size()).isEqualTo(photos.size)
assertThat(processResult).isEqualTo(sizingResult)
}
// Commit results
@Test fun commitResult_noProcessed() = runBlocking {
engine.setBitmapIterator(bitmapIterator)
val bitmap = mock<Bitmap>()
val processingResult = ProcessingResult(
processedCount = 0,
output = bitmap
)
whenever(
stitchEngine.stitch(
bitmapIterator = bitmapIterator,
selectedScale = 1.0,
resultWidth = 1,
resultHeight = 1,
format = PNG,
quality = 100
)
).doReturn(processingResult)
val result = engine.commit(
scale = 1.0,
width = 1,
height = 1,
format = PNG,
quality = 100
)
assertThat(result.error).isNotNull()
assertThat(result.outputFile).isNull()
verify(bitmap).recycle()
}
@Test fun commitResult() = runBlocking {
engine.setBitmapIterator(bitmapIterator)
val bitmap = mock<Bitmap>()
val processingResult = ProcessingResult(
processedCount = 1,
output = bitmap
)
val outputFile = mock<File>()
whenever(ioManager.makeTempFile(".png"))
.doReturn(outputFile)
whenever(
stitchEngine.stitch(
bitmapIterator = bitmapIterator,
selectedScale = 1.0,
resultWidth = 1,
resultHeight = 1,
format = PNG,
quality = 100
)
).doReturn(processingResult)
val result = engine.commit(
scale = 1.0,
width = 1,
height = 1,
format = PNG,
quality = 100
)
assertThat(result.error).isNull()
assertThat(result.outputFile).isEqualTo(outputFile)
verify(bitmap).recycle()
verify(outputFile, never()).delete()
verify(bitmapManipulator).encodeBitmap(
bitmap = bitmap,
format = PNG,
quality = 100,
file = outputFile
)
}
@Test fun commitResult_encodeError() = runBlocking {
engine.setBitmapIterator(bitmapIterator)
val bitmap = mock<Bitmap>()
val processingResult = ProcessingResult(
processedCount = 0,
output = bitmap
)
val outputFile = mock<File>()
whenever(ioManager.makeTempFile(".png"))
.doReturn(outputFile)
whenever(
stitchEngine.stitch(
bitmapIterator = bitmapIterator,
selectedScale = 1.0,
resultWidth = 1,
resultHeight = 1,
format = PNG,
quality = 100
)
).doReturn(processingResult)
val error = Exception("Oh no!")
whenever(
bitmapManipulator.encodeBitmap(
any(), any(), any(), any()
)
).doAnswer { throw error }
val result = engine.commit(
scale = 1.0,
width = 1,
height = 1,
format = PNG,
quality = 100
)
verify(bitmap).recycle()
//verify(outputFile).delete()
assertThat(result.error).isNotNull()
assertThat(result.outputFile).isNull()
}
}
| engine/src/test/java/com/afollestad/photoaffix/engine/AffixEngineTest.kt | 1274203141 |
package expo.modules.updates.loader
import android.content.Context
import expo.modules.updates.UpdatesConfiguration
import expo.modules.updates.db.entity.AssetEntity
import expo.modules.updates.db.UpdatesDatabase
import expo.modules.updates.loader.FileDownloader.AssetDownloadCallback
import expo.modules.updates.loader.FileDownloader.ManifestDownloadCallback
import expo.modules.updates.UpdatesUtils
import java.io.File
import java.io.FileNotFoundException
import java.lang.AssertionError
import java.lang.Exception
import java.util.*
/**
* Subclass of [Loader] which handles copying the embedded update's assets into the
* expo-updates cache location.
*
* Rather than launching the embedded update directly from its location in the app bundle/apk, we
* first try to read it into the expo-updates cache and database and launch it like any other
* update. The benefits of this include (a) a single code path for launching most updates and (b)
* assets included in embedded updates and copied into the cache in this way do not need to be
* redownloaded if included in future updates.
*
* However, if a visual asset is included at multiple scales in an embedded update, we don't have
* access to and must skip copying scales that don't match the resolution of the current device. In
* this case, we cannot fully copy the embedded update, and instead launch it from the original
* location. We still copy the assets we can so they don't need to be redownloaded in the future.
*/
class EmbeddedLoader internal constructor(
private val context: Context,
private val configuration: UpdatesConfiguration,
database: UpdatesDatabase,
updatesDirectory: File?,
private val loaderFiles: LoaderFiles
) : Loader(
context, configuration, database, updatesDirectory, loaderFiles
) {
private val pixelDensity = context.resources.displayMetrics.density
constructor(
context: Context,
configuration: UpdatesConfiguration,
database: UpdatesDatabase,
updatesDirectory: File?
) : this(context, configuration, database, updatesDirectory, LoaderFiles()) {
}
override fun loadManifest(
context: Context,
database: UpdatesDatabase,
configuration: UpdatesConfiguration,
callback: ManifestDownloadCallback
) {
val updateManifest = loaderFiles.readEmbeddedManifest(this.context, this.configuration)
if (updateManifest != null) {
callback.onSuccess(updateManifest)
} else {
val message = "Embedded manifest is null"
callback.onFailure(message, Exception(message))
}
}
override fun loadAsset(
assetEntity: AssetEntity,
updatesDirectory: File?,
configuration: UpdatesConfiguration,
callback: AssetDownloadCallback
) {
val filename = UpdatesUtils.createFilenameForAsset(assetEntity)
val destination = File(updatesDirectory, filename)
if (loaderFiles.fileExists(destination)) {
assetEntity.relativePath = filename
callback.onSuccess(assetEntity, false)
} else {
try {
assetEntity.hash = loaderFiles.copyAssetAndGetHash(assetEntity, destination, context)
assetEntity.downloadTime = Date()
assetEntity.relativePath = filename
callback.onSuccess(assetEntity, true)
} catch (e: FileNotFoundException) {
throw AssertionError(
"APK bundle must contain the expected embedded asset " +
if (assetEntity.embeddedAssetFilename != null) assetEntity.embeddedAssetFilename else assetEntity.resourcesFilename
)
} catch (e: Exception) {
callback.onFailure(e, assetEntity)
}
}
}
override fun shouldSkipAsset(assetEntity: AssetEntity): Boolean {
return if (assetEntity.scales == null || assetEntity.scale == null) {
false
} else pickClosestScale(assetEntity.scales!!) != assetEntity.scale
}
// https://developer.android.com/guide/topics/resources/providing-resources.html#BestMatch
// If a perfect match is not available, the OS will pick the next largest scale.
// If only smaller scales are available, the OS will choose the largest available one.
private fun pickClosestScale(scales: Array<Float>): Float {
var closestScale = Float.MAX_VALUE
var largestScale = 0f
for (scale in scales) {
if (scale >= pixelDensity && scale < closestScale) {
closestScale = scale
}
if (scale > largestScale) {
largestScale = scale
}
}
return if (closestScale < Float.MAX_VALUE) closestScale else largestScale
}
companion object {
private val TAG = EmbeddedLoader::class.java.simpleName
const val BUNDLE_FILENAME = "app.bundle"
const val BARE_BUNDLE_FILENAME = "index.android.bundle"
}
}
| packages/expo-updates/android/src/main/java/expo/modules/updates/loader/EmbeddedLoader.kt | 967226149 |
package com.ridocula.restdroid.fragments
import android.app.Dialog
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.support.v7.app.AlertDialog
import android.widget.EditText
import com.ridocula.restdroid.R
import com.ridocula.restdroid.models.RequestCollection
import com.ridocula.restdroid.persistence.repository.LocalRequestRepository
import com.ridocula.restdroid.util.Utility
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
/**
* Created by tbaxter on 9/9/17.
*/
class AddRequestCollectionDialog : DialogFragment() {
private lateinit var etRequestCollectionName: EditText
companion object {
fun newInstance(title: String): AddRequestCollectionDialog {
val frag = AddRequestCollectionDialog()
val args = Bundle()
args.putString("title", title)
frag.arguments = args
return frag
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val builder = AlertDialog.Builder(activity)
val title = arguments.getString("title")
// Get the layout inflater
val inflater = activity.layoutInflater
val view = inflater.inflate(R.layout.dialog_add_request_collection, null)
etRequestCollectionName = view.findViewById(R.id.etRequestCollectionName)
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(view)
// Add action buttons
.setPositiveButton("Save", { dialog, id ->
// Save request collection
addRequestCollection()
})
.setNegativeButton("Cancel", { dialog, id -> this.dialog.cancel() })
return builder.create()
}
private fun addRequestCollection() {
// Save request collection
val requestCollection = RequestCollection(Utility.generateId(), etRequestCollectionName.text.toString())
val requestRepo = LocalRequestRepository(activity.applicationContext)
Single.fromCallable {
requestRepo.insertRequestCollection(requestCollection)
}.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe()
return
}
} | app/src/main/java/com/ridocula/restdroid/fragments/AddRequestCollectionDialog.kt | 1277353548 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.CargoConstants
import org.rust.cargo.project.model.cargoProjects
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.runconfig.command.RunCargoCommandActionBase
import org.rust.cargo.toolchain.RsToolchainBase
import org.rust.cargo.toolchain.tools.cargoOrWrapper
import org.rust.ide.actions.ui.showCargoNewCrateUI
import org.rust.openapiext.pathAsPath
import org.rust.stdext.unwrapOrThrow
class RsCreateCrateAction : RunCargoCommandActionBase() {
override fun actionPerformed(e: AnActionEvent) {
val dataContext = e.dataContext
val project = CommonDataKeys.PROJECT.getData(dataContext) ?: return
val root = getRootFolder(dataContext) ?: return
val toolchain = project.toolchain ?: return
val ui = showCargoNewCrateUI(project, root)
ui.selectCargoCrateSettings()?.let {
createProject(project, toolchain, root, it.crateName, it.binary)
}
}
private fun getRootFolder(dataContext: DataContext): VirtualFile? {
val file = CommonDataKeys.VIRTUAL_FILE.getData(dataContext) ?: return null
return if (!file.isDirectory) {
file.parent
} else file
}
private fun createProject(
project: Project,
toolchain: RsToolchainBase,
root: VirtualFile,
name: String,
binary: Boolean
) {
val cargo = toolchain.cargoOrWrapper(
project.cargoProjects.findProjectForFile(root)?.workspaceRootDir?.pathAsPath)
val targetDir = runWriteAction {
root.createChildDirectory(this, name)
}
cargo.init(project, project, targetDir, name, binary, "none").unwrapOrThrow()
val manifest = targetDir.findChild(CargoConstants.MANIFEST_FILE)
manifest?.let {
project.cargoProjects.attachCargoProject(it.pathAsPath)
}
}
}
| src/main/kotlin/org/rust/ide/actions/RsCreateCrateAction.kt | 2465808458 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.search.SearchScope
import com.intellij.psi.stubs.IStubElementType
import org.rust.ide.icons.RsIcons
import org.rust.lang.core.macros.RsExpandedElement
import org.rust.lang.core.psi.RsModItem
import org.rust.lang.core.psi.RsPsiImplUtil
import org.rust.lang.core.stubs.RsModItemStub
import javax.swing.Icon
val RsModItem.hasMacroUse: Boolean get() = MOD_ITEM_HAS_MACRO_USE_PROP.getByPsi(this)
val MOD_ITEM_HAS_MACRO_USE_PROP: StubbedAttributeProperty<RsModItem, RsModItemStub> =
StubbedAttributeProperty({ it.hasAttribute("macro_use") }, RsModItemStub::mayHaveMacroUse)
abstract class RsModItemImplMixin : RsStubbedNamedElementImpl<RsModItemStub>,
RsModItem {
constructor(node: ASTNode) : super(node)
constructor(stub: RsModItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getIcon(flags: Int): Icon =
iconWithVisibility(flags, RsIcons.MODULE)
override val `super`: RsMod get() = containingMod
override val modName: String? get() = name
override val pathAttribute: String? get() = queryAttributes.lookupStringValueForKey("path")
override val crateRelativePath: String? get() = RsPsiImplUtil.modCrateRelativePath(this)
override val ownsDirectory: Boolean = true // Any inline nested mod owns a directory
override val isCrateRoot: Boolean = false
override fun getContext(): PsiElement? = RsExpandedElement.getContextImpl(this)
override fun getUseScope(): SearchScope = RsPsiImplUtil.getDeclarationUseScope(this) ?: super.getUseScope()
}
| src/main/kotlin/org/rust/lang/core/psi/ext/RsModItem.kt | 1974016451 |
package com.example.config.web
import com.example.interceptor.TokenInterceptor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.InterceptorRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
/**
* Created by aixiaoai on 16/6/26.
*/
@Configuration
open class WebMvcConfig : WebMvcConfigurerAdapter() {
@Autowired
lateinit var tokenInterceptor: TokenInterceptor
override fun addInterceptors(registry: InterceptorRegistry?) {
registry?.addInterceptor(tokenInterceptor)?.excludePathPatterns("/api/login")?.excludePathPatterns("/api/register")?.addPathPatterns("/api/**")
}
} | src/main/kotlin/com/example/config/web/WebMvcConfig.kt | 2312042353 |
/*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.ui
import batect.logging.Logger
import batect.os.Dimensions
import batect.os.NativeMethodException
import batect.os.NativeMethods
import batect.os.NoConsoleException
import batect.os.SignalListener
import batect.os.data
import jnr.constants.platform.Signal
import java.util.concurrent.atomic.AtomicReference
class ConsoleDimensions(
private val nativeMethods: NativeMethods,
private val signalListener: SignalListener,
private val logger: Logger
) {
private val currentDimensions: AtomicReference<Result<Dimensions?>> = AtomicReference(Result.success(null))
private val listeners = mutableListOf<Listener>()
init {
signalListener.start(Signal.SIGWINCH, ::updateCachedDimensions)
updateCachedDimensions()
}
val current: Dimensions?
get() = currentDimensions.get().getOrThrow()
fun registerListener(listener: Listener): AutoCloseable {
listeners.add(listener)
return AutoCloseable { listeners.remove(listener) }
}
private fun updateCachedDimensions() {
try {
val newDimensions = nativeMethods.getConsoleDimensions()
currentDimensions.set(Result.success(newDimensions))
logger.info {
message("Got console dimensions.")
data("dimensions", newDimensions)
}
} catch (e: NoConsoleException) {
currentDimensions.set(Result.success(null))
} catch (e: NativeMethodException) {
logger.warn {
message("Getting console dimensions failed.")
exception(e)
}
currentDimensions.set(Result.failure(e))
}
listeners.forEach { it() }
}
}
private typealias Listener = () -> Unit
| app/src/main/kotlin/batect/ui/ConsoleDimensions.kt | 3643101755 |
package edu.ptu.java.component
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
| Component/src/test/java/edu/ptu/java/component/ExampleUnitTest.kt | 359299980 |
/*
* 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.window.integration
import androidx.annotation.GuardedBy
import androidx.core.util.Consumer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
import org.junit.Assert.assertTrue
/**
* Data structure to hold values in a mutable list.
*/
internal class TestConsumer<T>(count: Int) : Consumer<T> {
private val valueLock = ReentrantLock()
@GuardedBy("valueLock")
private val values = mutableListOf<T>()
private val countDownLock = ReentrantLock()
@GuardedBy("countDownLock")
private var valueLatch = CountDownLatch(count)
private val waitTimeSeconds: Long = 3L
/**
* Appends the new value at the end of the mutable list values.
*/
override fun accept(numLayoutFeatures: T) {
valueLock.withLock {
values.add(numLayoutFeatures)
}
countDownLock.withLock {
valueLatch.countDown()
}
}
/**
* Returns the current number of values stored.
*/
private fun size(): Int {
valueLock.withLock {
return values.size
}
}
/**
* Waits for the mutable list's length to be at a certain number (count).
* The method will wait waitTimeSeconds for the count before asserting false.
*/
fun waitForValueCount() {
assertTrue(
// Wait a total of waitTimeSeconds for the count before throwing an assertion error.
try {
valueLatch.await(waitTimeSeconds, TimeUnit.SECONDS)
} catch (e: InterruptedException) {
false
}
)
}
/**
* Returns {@code true} if there are no stored values, {@code false} otherwise.
*/
fun isEmpty(): Boolean {
return size() == 0
}
/**
* Returns the object in the mutable list at the requested index.
*/
fun get(valueIndex: Int): T {
valueLock.withLock {
return values[valueIndex]
}
}
} | window/integration-tests/configuration-change-tests/src/androidTest/java/androidx/window/integration/TestConsumer.kt | 3632636961 |
/*
* 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.
*/
@file:Suppress("UnstableApiUsage")
package androidx.compose.animation.core.lint
import androidx.compose.lint.test.Stubs
import androidx.compose.lint.test.compiledStub
import com.android.tools.lint.checks.infrastructure.LintDetectorTest
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/* ktlint-disable max-line-length */
@RunWith(JUnit4::class)
/**
* Test for [TransitionDetector].
*/
class TransitionDetectorTest : LintDetectorTest() {
override fun getDetector(): Detector = TransitionDetector()
override fun getIssues(): MutableList<Issue> =
mutableListOf(TransitionDetector.UnusedTransitionTargetStateParameter)
// Simplified Transition.kt stubs
private val TransitionStub = compiledStub(
filename = "Transition.kt",
filepath = "androidx/compose/animation/core",
checksum = 0x313a900e,
"""
package androidx.compose.animation.core
import androidx.compose.runtime.Composable
class Transition<S> {
class Segment<S>
}
@Composable
inline fun <S> Transition<S>.animateFloat(
noinline transitionSpec: @Composable Transition.Segment<S>.() -> Unit = {},
label: String = "FloatAnimation",
targetValueByState: @Composable (state: S) -> Float
): Float = 5f
""",
"""
META-INF/main.kotlin_module:
H4sIAAAAAAAAAGNgYGBmYGBgBGJWKM3Apc8ln5iXUpSfmVKhl5yfW5BfnKqX
mJeZm1iSmZ8HFClKFeIJKUrMK84ECXiXcPFyMafl5wuxhaQWl3iXKDFoMQAA
iDN6X1gAAAA=
""",
"""
androidx/compose/animation/core/Transition$Segment.class:
H4sIAAAAAAAAAJVQW2sTQRT+zuwm2263dltvqbd6A2se3DYUBC0FLQiBVcGU
vORpkh3iNLuzsjMpfcxv8R/4JPggwUd/lHh2LQj6ogPznfN95zJnzvcfX74C
OMADQk+arCp1dp5MyuJDaVUijS6k06VhpVLJSSWN1TV/OFDTQhkXgAi7h4Nn
6ak8k0kuzTR5Oz5VE/f86G+JEP+pBfAJ7UNttDsieLuPhxHaCEK0sELw3Xtt
CQfp/0/Gj22ms9Ll2iSvlZOZdJI1UZx5/F+qoUWgGUvnumZ77GX7hEfLRRSK
jgiXi1DEDMtFZ7no+isUU0/siZetbx/bIvbq9B53GBC3Q/ffJwzQIQQXYxLW
f0eezJj7x2WmCBupNurNvBir6kSOc1a20nIi86GsdM0vxKhvjKqOc2mt4k2t
DvTUSDevOBQOynk1Ua90nbf9bm6cLtRQW82FL4wpXTOdxT4Eb7s+/Jt6+Yy3
mCUN5zV1P2P1EzsCtxnbjRjgDmP0KwEh1tj62GEMWRPYxg2+d5sqD/caexP3
2T7leMQ16yN4fVzqY4MRcQ2bfWzh8ghkcQVXR/At1iyuWVy3CH4CEksXNqoC
AAA=
""",
"""
androidx/compose/animation/core/Transition.class:
H4sIAAAAAAAAAI1RTW8TMRB99m52023apuUr4atAeygRYtuIU6gqQSWkSAtI
bJVLTk7WCm52vWjtVD3mt/APOCFxQBFHfhRivFRCgkt9eOP3PG88Hv/89e07
gBfYY+gJnVWlyi7jaVl8Ko2MhVaFsKrUpFQyPquENsrxEIzh4DgdJOfiQsS5
0LP4/eRcTu3Lk/8lhva/WgifIThWWtkTBu/g6aiFAGGEBpoMvv2oDMOz5Pod
0SXbyby0udLxW2lFJqwgjRcXHr2POWgwsDlJl8qxQ9plR3TJarkZ8Q6PVsuI
tx00eWe17PnN1bLN+vyQD5j/uvHjc8DbnvP0qUzKqCbCVM4KqS1D//qN7l+Z
QnQZNv7qz+dUxz8tM8mwlSgt3y2KiazOxCQnZScppyIfiUo5fiW2hlrL6jQX
xkga11qqZlrYRUVHUVouqql8o1xe98NCW1XIkTKKjK+0Lm3dm8EROI3cLXqV
+wHC+8TimtPMel+x9oU2HA8Ig1oM8JCw9ScBEdYp+tgljEi7S7kddPGodnl4
XMd7eEJxQOct8myM4Q2xOcQWIdoOtofYwY0xmMFN3BqjYbBucNvgjkFo0PkN
zab+FKoCAAA=
""",
"""
androidx/compose/animation/core/TransitionKt$animateFloat$1.class:
H4sIAAAAAAAAAKVVXW8bRRQ9s3ZsZ7Mljpt+JIUSGtM6dujGIbRQuwGT2mSJ
ayocIqE8je2ps/F6ttpdW+EtD/0J/BAKEkUgIT/zo1DvrF03VkPbhJeZO3fu
uffMnTO7//z7598ANlBlKHDZ8ly7dWQ23e4T1xcml3aXB7YryeMJc9fj0rfV
eidID/dExXF5kM7HwRieVjtu4NjSPOx3TVsGwpPcMau822jxwsm9xz3ZVGl8
szKy8sXqu1dP10W7K2RQ3K0XNseJf5B2QEuGxf9mEUeU4fqbmcQRY4gVbUq3
yRDJrOwxRDPWyp6BBHQdU5ghR3Bg+wz3z8D6tZ4R1Zgt+25HMNzNnOP8BUWt
eB7ksHMKvlx1vbZ5KIKGx21qA5fSDfiwJTU3qPUch3jqaXXetKRVAhcnWzhu
sSUDj1LYTT+OSwyXmgei2RnleMQ93hUUyHArUz3kfW46XLbN7xqHohkUTnjq
Kkm7oNp9BVd1XMYCw8Z5usNw85RSK6+7GNbPnj6ODwzMIqlDw4cMMydUGMdH
DAmrVt8t1bbKDBcmJGpgGelp3MDHDNqTPEPqNEaJYtMJJahUN62KZBXwvWmy
VhnmXqZ8KALe4gEniNbtR+gtMzVMMbCOMiLkP7KVtUZWi8rlBseGPjjWtaQW
Tle15OB4UVtjN6KJwXFSyyZS0ZS2ra1FtnUFWafDFbl05U9dt+fTkwDlrjOs
nkX6cRQZ5if03xKPec8JGH4+i4Lf9h05RUpvQ1iniKRiYBNf0tW9qny7Q1yj
W25LqCtzm9zZ457NG47YVQPDbNWWotbrNoQ38kzX7bbkQc8jO/19TwZ2V1iy
b/s2bY+fROnVk2MwLCmFt+Vw3xe0nC3LpuP6dAy66AO3RU+x7va8pqjYqsD8
cPFANHrt8lEgiKorGRZGtfaGlU4UQJ70M0U3SB9sLChBkTKiZJPIaPyaVmmK
oEtGLBt9DuOZUhS2aDSGXlwIMXNK+4iEiAIhNJrjudT8H1hUEA0PwmD6xBFQ
wS8PQ0ZwZV3ENdovh9FzqCgfKQspIFmi7O+P+Hw1ym5kcwNc/x1Lv+LmLxMl
MFHCGJcwcAuZ8Gwr49NdCWOAmb+g/fgcud/wybPQEcM3NOoUNgxYwHbYmvtE
YMgxAiucS/iW5qf1h6VH+oQ89J1QaHq2vvTSqui5pfzSZNT/+GXo2aqeX86v
5u/cI7usY4eY3CXOt+lSzX1ELKxZyNOIdQufYsPCZ7izD+ZT1Of7iPr4wsc9
HwUf114AvnRqlvwHAAA=
""",
"""
androidx/compose/animation/core/TransitionKt.class:
H4sIAAAAAAAAAMVVT1MjRRR/PZkknSHAMAsI2d24stldYGEnZDHqJovLIsho
iJZBLhysJmmyA5MeamZCsRcLvfgFvOzN8uDRg6ctD1aKLS9+Jsvy9ZCEQKzC
eDFV6fev3++91/36zR9//fobACzDJwQWmKh5rl07Matu48j1ucmE3WCB7QrU
eNzc9pjwbSl/GsSBENAP2DEzHSbq5md7B7yK2giB5Lkb33BcFhD4Zrb074EL
pUM3cGxhHhw3zP2mqEqlb260uaVC6SJkJfBsUb/WY26DwJ/FypPS1WQLK4Nk
VtyuFFauC1ZcHAAxU+H1BhfBZeQvhR1IcdA6i4sI0+MVnj4CyfLv9WflNUVg
N7i5Fspsz+EFAndLrlc3D3iw5zEbwZkQbsDOA5XdoNx0HNwVKwYvbH+FgkYg
3ZOULQLuCeaYlpAZ+3bVj0OSwET1Ba8etv0/Zx5rcNxI4MFs/5X0lz23k4QR
GNVgGHQCI0H3+CpHvErBIBB12B53KIwTMALm1Xmww5wmf/6ygrlzCpPqsx8A
CIxl7Mx+5nJzEgudMrKeK4aFQZqWwJ3ruhDD9NdGYLw3aqbG91nTwejf/89v
xuq/GdlHhUEmxKUDzSzF4R0C1CpXtlfLa+sEng5QYR9YIQl3IZOAGbh3uQf/
oZg4PMC+CR1XOwEozBG43X/vXzVzy91LGOuc0hYPWI0FDO9LaRxHcF4SuUSx
fQ4lo6D+xJZcFrnaEoHfW6c5rXWqKXo8JFNKh4R/Xeny4aaRrpUqqUBvnaaU
LJlRaetUV+apoRrKppKN5DJU09VU2tCMji4maTaejZ79GFMoDddEjlJF1xBi
KHdfT6ZmjBvG2KaCtiQdNigdMVRKZ0dDT9Lx3Dz7jr55TVqnZ98qcS1Kz17l
skQWkyPy6ZCK7N/2cfQ29fJ/mHfolu5grZ8EHM2u6IBuvzySk2iys6E7L8pI
0KAKpPjmffm2CQxfwD86xDtT19waqkdLtuDlZmOPe9tytsns3SpzdphnS7mt
TFTsumBB00P+5hfnE9ESx7Zvo3n1YvgRyFy1dvO6tG0YR071cIsdtQMkLSG4
t+Yw3+do1ipu06vyDVvaptuQO33hYAkUUEH+FJiGKMRQeobSEcpRpOl5Y+g1
jD00buC6YEzgumi8hWskrxpTP4d+q7jG8Opuwig8Dz/xUeQjiJcKsdMo3Qpj
pMGA27hTcuP4V0JuEnURWAux4vBRG40iXcf/tIpCQr6Eq6uegLfhDvIy4Z/Q
OYY0P6GqX78C7Re434LZ0oQaRSlmzG9dW0gENnBVQRlJhCWlQrwhTEl+FoZg
Ar8LU0gf95T5uKfMPDxsl5nvlpnvlplvlxmBj1HS0DoT7p2GzbDwD8FCuov6
BcRd3IWIBY8sMHGFrIX3lLMw2jJu8OFdyO+C7mNrwns+vO/DLR8MHz7w4Umo
oT4UfBgP+Ukfij489WHlb+6OIxeBCQAA
"""
)
@Test
fun unreferencedParameters() {
lint().files(
kotlin(
"""
package foo
import androidx.compose.animation.core.*
import androidx.compose.runtime.*
val transition = Transition<Boolean>()
var foo = false
@Composable
fun Test() {
transition.animateFloat { if (foo) 1f else 0f }
transition.animateFloat(targetValueByState = { if (foo) 1f else 0f })
transition.animateFloat { param -> if (foo) 1f else 0f }
transition.animateFloat(targetValueByState = { param -> if (foo) 1f else 0f })
transition.animateFloat { _ -> if (foo) 1f else 0f }
transition.animateFloat(targetValueByState = { _ -> if (foo) 1f else 0f })
}
"""
),
TransitionStub,
Stubs.Composable
)
.run()
.expect(
"""
src/foo/test.kt:13: Error: Target state parameter it is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat { if (foo) 1f else 0f }
~~~~~~~~~~~~~~~~~~~~~~~
src/foo/test.kt:14: Error: Target state parameter it is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat(targetValueByState = { if (foo) 1f else 0f })
~~~~~~~~~~~~~~~~~~~~~~~
src/foo/test.kt:15: Error: Target state parameter param is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat { param -> if (foo) 1f else 0f }
~~~~~
src/foo/test.kt:16: Error: Target state parameter param is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat(targetValueByState = { param -> if (foo) 1f else 0f })
~~~~~
src/foo/test.kt:17: Error: Target state parameter _ is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat { _ -> if (foo) 1f else 0f }
~
src/foo/test.kt:18: Error: Target state parameter _ is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat(targetValueByState = { _ -> if (foo) 1f else 0f })
~
6 errors, 0 warnings
"""
)
}
@Test
fun unreferencedParameter_shadowedNames() {
lint().files(
kotlin(
"""
package foo
import androidx.compose.animation.core.*
import androidx.compose.runtime.*
val transition = Transition<Boolean>()
var foo = false
@Composable
fun Test() {
transition.animateFloat {
foo.let {
// These `it`s refer to the `let`, not the `animateFloat`, so we
// should still report an error
it.let {
if (it) 1f else 0f
}
}
}
transition.animateFloat { param ->
foo.let { param ->
// This `param` refers to the `let`, not the `animateFloat`, so we
// should still report an error
if (param) 1f else 0f
}
}
}
"""
),
TransitionStub,
Stubs.Composable
)
.run()
.expect(
"""
src/foo/test.kt:13: Error: Target state parameter it is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat {
^
src/foo/test.kt:22: Error: Target state parameter param is not used [UnusedTransitionTargetStateParameter]
transition.animateFloat { param ->
~~~~~
2 errors, 0 warnings
"""
)
}
@Test
fun noErrors() {
lint().files(
kotlin(
"""
package foo
import androidx.compose.animation.core.*
import androidx.compose.runtime.*
val transition = Transition<Boolean>()
var foo = false
@Composable
fun Test() {
transition.animateFloat { if (it) 1f else 0f }
transition.animateFloat(targetValueByState = { if (it) 1f else 0f })
transition.animateFloat { param -> if (param) 1f else 0f }
transition.animateFloat(targetValueByState = { param -> if (param) 1f else 0f })
transition.animateFloat { param ->
foo.let {
it.let {
if (param && it) 1f else 0f
}
}
}
transition.animateFloat {
foo.let { param ->
param.let { param ->
if (param && it) 1f else 0f
}
}
}
transition.animateFloat {
foo.run {
run {
if (this && it) 1f else 0f
}
}
}
fun multipleParameterLambda(lambda: (Boolean, Boolean) -> Float): Float
= lambda(true, true)
transition.animateFloat {
multipleParameterLambda { _, _ ->
multipleParameterLambda { param1, _ ->
if (param1 && it) 1f else 0f
}
}
}
}
"""
),
TransitionStub,
Stubs.Composable
)
.run()
.expectClean()
}
}
/* ktlint-enable max-line-length */
| compose/animation/animation-core-lint/src/test/java/androidx/compose/animation/core/lint/TransitionDetectorTest.kt | 2658891252 |
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.createFontFamilyResolver
import androidx.compose.ui.text.font.toFontFamily
import androidx.compose.ui.text.platform.SynchronizedObject
import androidx.compose.ui.text.platform.createSynchronizedObject
import androidx.compose.ui.text.platform.synchronized
import androidx.compose.ui.text.style.ResolvedTextDirection
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
/**
* The data class which holds the set of parameters of the text layout computation.
*/
class TextLayoutInput private constructor(
/**
* The text used for computing text layout.
*/
val text: AnnotatedString,
/**
* The text layout used for computing this text layout.
*/
val style: TextStyle,
/**
* A list of [Placeholder]s inserted into text layout that reserves space to embed icons or
* custom emojis. A list of bounding boxes will be returned in
* [TextLayoutResult.placeholderRects] that corresponds to this input.
*
* @see TextLayoutResult.placeholderRects
* @see MultiParagraph
* @see MultiParagraphIntrinsics
*/
val placeholders: List<AnnotatedString.Range<Placeholder>>,
/**
* The maxLines param used for computing this text layout.
*/
val maxLines: Int,
/**
* The maxLines param used for computing this text layout.
*/
val softWrap: Boolean,
/**
* The overflow param used for computing this text layout
*/
val overflow: TextOverflow,
/**
* The density param used for computing this text layout.
*/
val density: Density,
/**
* The layout direction used for computing this text layout.
*/
val layoutDirection: LayoutDirection,
/**
* The font resource loader used for computing this text layout.
*
* This is no longer used.
*
* @see fontFamilyResolver
*/
@Suppress("DEPRECATION") resourceLoader: Font.ResourceLoader?,
/**
* The font resolver used for computing this text layout.
*/
val fontFamilyResolver: FontFamily.Resolver,
/**
* The minimum width provided while calculating this text layout.
*/
val constraints: Constraints
) {
private var _developerSuppliedResourceLoader = resourceLoader
@Deprecated("Replaced with FontFamily.Resolver",
replaceWith = ReplaceWith("fontFamilyResolver"),
)
@Suppress("DEPRECATION")
val resourceLoader: Font.ResourceLoader
get() {
return _developerSuppliedResourceLoader
?: DeprecatedBridgeFontResourceLoader.from(fontFamilyResolver)
}
@Deprecated(
"Font.ResourceLoader is replaced with FontFamily.Resolver",
replaceWith = ReplaceWith("TextLayoutInput(text, style, placeholders, " +
"maxLines, softWrap, overflow, density, layoutDirection, fontFamilyResolver, " +
"constraints")
)
@Suppress("DEPRECATION")
constructor(
text: AnnotatedString,
style: TextStyle,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
softWrap: Boolean,
overflow: TextOverflow,
density: Density,
layoutDirection: LayoutDirection,
resourceLoader: Font.ResourceLoader,
constraints: Constraints
) : this(
text,
style,
placeholders,
maxLines,
softWrap,
overflow,
density,
layoutDirection,
resourceLoader,
createFontFamilyResolver(resourceLoader),
constraints
)
constructor(
text: AnnotatedString,
style: TextStyle,
placeholders: List<AnnotatedString.Range<Placeholder>>,
maxLines: Int,
softWrap: Boolean,
overflow: TextOverflow,
density: Density,
layoutDirection: LayoutDirection,
fontFamilyResolver: FontFamily.Resolver,
constraints: Constraints
) : this(
text,
style,
placeholders,
maxLines,
softWrap,
overflow,
density,
layoutDirection,
@Suppress("DEPRECATION") null,
fontFamilyResolver,
constraints
)
@Deprecated("Font.ResourceLoader is deprecated",
replaceWith = ReplaceWith("TextLayoutInput(text, style, placeholders," +
" maxLines, softWrap, overFlow, density, layoutDirection, fontFamilyResolver, " +
"constraints)")
)
// Unfortunately, there's no way to deprecate and add a parameter to a copy chain such that the
// resolution is valid.
//
// However, as this was never intended to be a public function we will not replace it. There is
// no use case for calling this method directly.
fun copy(
text: AnnotatedString = this.text,
style: TextStyle = this.style,
placeholders: List<AnnotatedString.Range<Placeholder>> = this.placeholders,
maxLines: Int = this.maxLines,
softWrap: Boolean = this.softWrap,
overflow: TextOverflow = this.overflow,
density: Density = this.density,
layoutDirection: LayoutDirection = this.layoutDirection,
@Suppress("DEPRECATION") resourceLoader: Font.ResourceLoader = this.resourceLoader,
constraints: Constraints = this.constraints
): TextLayoutInput {
return TextLayoutInput(
text = text,
style = style,
placeholders = placeholders,
maxLines = maxLines,
softWrap = softWrap,
overflow = overflow,
density = density,
layoutDirection = layoutDirection,
resourceLoader = resourceLoader,
fontFamilyResolver = fontFamilyResolver,
constraints = constraints
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TextLayoutInput) return false
if (text != other.text) return false
if (style != other.style) return false
if (placeholders != other.placeholders) return false
if (maxLines != other.maxLines) return false
if (softWrap != other.softWrap) return false
if (overflow != other.overflow) return false
if (density != other.density) return false
if (layoutDirection != other.layoutDirection) return false
if (fontFamilyResolver != other.fontFamilyResolver) return false
if (constraints != other.constraints) return false
return true
}
override fun hashCode(): Int {
var result = text.hashCode()
result = 31 * result + style.hashCode()
result = 31 * result + placeholders.hashCode()
result = 31 * result + maxLines
result = 31 * result + softWrap.hashCode()
result = 31 * result + overflow.hashCode()
result = 31 * result + density.hashCode()
result = 31 * result + layoutDirection.hashCode()
result = 31 * result + fontFamilyResolver.hashCode()
result = 31 * result + constraints.hashCode()
return result
}
override fun toString(): String {
return "TextLayoutInput(" +
"text=$text, " +
"style=$style, " +
"placeholders=$placeholders, " +
"maxLines=$maxLines, " +
"softWrap=$softWrap, " +
"overflow=$overflow, " +
"density=$density, " +
"layoutDirection=$layoutDirection, " +
"fontFamilyResolver=$fontFamilyResolver, " +
"constraints=$constraints" +
")"
}
}
@Suppress("DEPRECATION")
private class DeprecatedBridgeFontResourceLoader private constructor(
private val fontFamilyResolver: FontFamily.Resolver
) : Font.ResourceLoader {
@Deprecated(
"Replaced by FontFamily.Resolver, this method should not be called",
ReplaceWith("FontFamily.Resolver.resolve(font, )"),
)
override fun load(font: Font): Any {
return fontFamilyResolver.resolve(
font.toFontFamily(),
font.weight,
font.style
).value
}
companion object {
// In normal usage will be a map of size 1.
//
// To fill this map with a large number of entries an app must:
//
// 1. Repeatedly change FontFamily.Resolver
// 2. Call the deprecated method getFontResourceLoader on TextLayoutInput
//
// If this map is found to be large in profiling of an app, please modify your code to not
// call getFontResourceLoader, and evaluate if FontFamily.Resolver is being correctly cached
// (via e.g. remember)
var cache = mutableMapOf<FontFamily.Resolver, Font.ResourceLoader>()
val lock: SynchronizedObject = createSynchronizedObject()
fun from(fontFamilyResolver: FontFamily.Resolver): Font.ResourceLoader {
synchronized(lock) {
// the same resolver to return the same ResourceLoader
cache[fontFamilyResolver]?.let { return it }
val deprecatedBridgeFontResourceLoader = DeprecatedBridgeFontResourceLoader(
fontFamilyResolver
)
cache[fontFamilyResolver] = deprecatedBridgeFontResourceLoader
return deprecatedBridgeFontResourceLoader
}
}
}
}
/**
* The data class which holds text layout result.
*/
class TextLayoutResult constructor(
/**
* The parameters used for computing this text layout result.
*/
val layoutInput: TextLayoutInput,
/**
* The multi paragraph object.
*
* This is the result of the text layout computation.
*/
val multiParagraph: MultiParagraph,
/**
* The amount of space required to paint this text in Int.
*/
val size: IntSize
) {
/**
* The distance from the top to the alphabetic baseline of the first line.
*/
val firstBaseline: Float = multiParagraph.firstBaseline
/**
* The distance from the top to the alphabetic baseline of the last line.
*/
val lastBaseline: Float = multiParagraph.lastBaseline
/**
* Returns true if the text is too tall and couldn't fit with given height.
*/
val didOverflowHeight: Boolean get() = multiParagraph.didExceedMaxLines ||
size.height < multiParagraph.height
/**
* Returns true if the text is too wide and couldn't fit with given width.
*/
val didOverflowWidth: Boolean get() = size.width < multiParagraph.width
/**
* Returns true if either vertical overflow or horizontal overflow happens.
*/
val hasVisualOverflow: Boolean get() = didOverflowWidth || didOverflowHeight
/**
* Returns a list of bounding boxes that is reserved for [TextLayoutInput.placeholders].
* Each [Rect] in this list corresponds to the [Placeholder] passed to
* [TextLayoutInput.placeholders] and it will have the height and width specified in the
* [Placeholder]. It's guaranteed that [TextLayoutInput.placeholders] and
* [TextLayoutResult.placeholderRects] will have same length and order.
*
* @see TextLayoutInput.placeholders
* @see Placeholder
*/
val placeholderRects: List<Rect?> = multiParagraph.placeholderRects
/**
* Returns a number of lines of this text layout
*/
val lineCount: Int get() = multiParagraph.lineCount
/**
* Returns the start offset of the given line, inclusive.
*
* The start offset represents a position in text before the first character in the given line.
* For example, `getLineStart(1)` will return 4 for the text below
* <pre>
* ┌────┐
* │abcd│
* │efg │
* └────┘
* </pre>
*
* @param lineIndex the line number
* @return the start offset of the line
*/
fun getLineStart(lineIndex: Int): Int = multiParagraph.getLineStart(lineIndex)
/**
* Returns the end offset of the given line.
*
* The end offset represents a position in text after the last character in the given line.
* For example, `getLineEnd(0)` will return 4 for the text below
* <pre>
* ┌────┐
* │abcd│
* │efg │
* └────┘
* </pre>
*
* Characters being ellipsized are treated as invisible characters. So that if visibleEnd is
* false, it will return line end including the ellipsized characters and vice versa.
*
* @param lineIndex the line number
* @param visibleEnd if true, the returned line end will not count trailing whitespaces or
* linefeed characters. Otherwise, this function will return the logical line end. By default
* it's false.
* @return an exclusive end offset of the line.
*/
fun getLineEnd(lineIndex: Int, visibleEnd: Boolean = false): Int =
multiParagraph.getLineEnd(lineIndex, visibleEnd)
/**
* Returns true if the given line is ellipsized, otherwise returns false.
*
* @param lineIndex a 0 based line index
* @return true if the given line is ellipsized, otherwise false
*/
fun isLineEllipsized(lineIndex: Int): Boolean = multiParagraph.isLineEllipsized(lineIndex)
/**
* Returns the top y coordinate of the given line.
*
* @param lineIndex the line number
* @return the line top y coordinate
*/
fun getLineTop(lineIndex: Int): Float = multiParagraph.getLineTop(lineIndex)
/**
* Returns the bottom y coordinate of the given line.
*
* @param lineIndex the line number
* @return the line bottom y coordinate
*/
fun getLineBottom(lineIndex: Int): Float = multiParagraph.getLineBottom(lineIndex)
/**
* Returns the left x coordinate of the given line.
*
* @param lineIndex the line number
* @return the line left x coordinate
*/
fun getLineLeft(lineIndex: Int): Float = multiParagraph.getLineLeft(lineIndex)
/**
* Returns the right x coordinate of the given line.
*
* @param lineIndex the line number
* @return the line right x coordinate
*/
fun getLineRight(lineIndex: Int): Float = multiParagraph.getLineRight(lineIndex)
/**
* Returns the line number on which the specified text offset appears.
*
* If you ask for a position before 0, you get 0; if you ask for a position
* beyond the end of the text, you get the last line.
*
* @param offset a character offset
* @return the 0 origin line number.
*/
fun getLineForOffset(offset: Int): Int = multiParagraph.getLineForOffset(offset)
/**
* Returns line number closest to the given graphical vertical position.
*
* If you ask for a vertical position before 0, you get 0; if you ask for a vertical position
* beyond the last line, you get the last line.
*
* @param vertical the vertical position
* @return the 0 origin line number.
*/
fun getLineForVerticalPosition(vertical: Float): Int =
multiParagraph.getLineForVerticalPosition(vertical)
/**
* Get the horizontal position for the specified text [offset].
*
* Returns the relative distance from the text starting offset. For example, if the paragraph
* direction is Left-to-Right, this function returns positive value as a distance from the
* left-most edge. If the paragraph direction is Right-to-Left, this function returns negative
* value as a distance from the right-most edge.
*
* [usePrimaryDirection] argument is taken into account only when the offset is in the BiDi
* directional transition point. [usePrimaryDirection] is true means use the primary
* direction run's coordinate, and use the secondary direction's run's coordinate if false.
*
* @param offset a character offset
* @param usePrimaryDirection true for using the primary run's coordinate if the given
* offset is in the BiDi directional transition point.
* @return the relative distance from the text starting edge.
* @see MultiParagraph.getHorizontalPosition
*/
fun getHorizontalPosition(offset: Int, usePrimaryDirection: Boolean): Float =
multiParagraph.getHorizontalPosition(offset, usePrimaryDirection)
/**
* Get the text direction of the paragraph containing the given offset.
*
* @param offset a character offset
* @return the paragraph direction
*/
fun getParagraphDirection(offset: Int): ResolvedTextDirection =
multiParagraph.getParagraphDirection(offset)
/**
* Get the text direction of the resolved BiDi run that the character at the given offset
* associated with.
*
* @param offset a character offset
* @return the direction of the BiDi run of the given character offset.
*/
fun getBidiRunDirection(offset: Int): ResolvedTextDirection =
multiParagraph.getBidiRunDirection(offset)
/**
* Returns the character offset closest to the given graphical position.
*
* @param position a graphical position in this text layout
* @return a character offset that is closest to the given graphical position.
*/
fun getOffsetForPosition(position: Offset): Int =
multiParagraph.getOffsetForPosition(position)
/**
* Returns the bounding box of the character for given character offset.
*
* @param offset a character offset
* @return a bounding box for the character in pixels.
*/
fun getBoundingBox(offset: Int): Rect = multiParagraph.getBoundingBox(offset)
/**
* Returns the text range of the word at the given character offset.
*
* Characters not part of a word, such as spaces, symbols, and punctuation, have word breaks on
* both sides. In such cases, this method will return a text range that contains the given
* character offset.
*
* Word boundaries are defined more precisely in Unicode Standard Annex #29
* <http://www.unicode.org/reports/tr29/#Word_Boundaries>.
*/
fun getWordBoundary(offset: Int): TextRange = multiParagraph.getWordBoundary(offset)
/**
* Returns the rectangle of the cursor area
*
* @param offset An character offset of the cursor
* @return a rectangle of cursor region
*/
fun getCursorRect(offset: Int): Rect = multiParagraph.getCursorRect(offset)
/**
* Returns path that enclose the given text range.
*
* @param start an inclusive start character offset
* @param end an exclusive end character offset
* @return a drawing path
*/
fun getPathForRange(start: Int, end: Int): Path = multiParagraph.getPathForRange(start, end)
fun copy(
layoutInput: TextLayoutInput = this.layoutInput,
size: IntSize = this.size
): TextLayoutResult {
return TextLayoutResult(
layoutInput = layoutInput,
multiParagraph = multiParagraph,
size = size
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is TextLayoutResult) return false
if (layoutInput != other.layoutInput) return false
if (multiParagraph != other.multiParagraph) return false
if (size != other.size) return false
if (firstBaseline != other.firstBaseline) return false
if (lastBaseline != other.lastBaseline) return false
if (placeholderRects != other.placeholderRects) return false
return true
}
override fun hashCode(): Int {
var result = layoutInput.hashCode()
result = 31 * result + multiParagraph.hashCode()
result = 31 * result + size.hashCode()
result = 31 * result + firstBaseline.hashCode()
result = 31 * result + lastBaseline.hashCode()
result = 31 * result + placeholderRects.hashCode()
return result
}
override fun toString(): String {
return "TextLayoutResult(" +
"layoutInput=$layoutInput, " +
"multiParagraph=$multiParagraph, " +
"size=$size, " +
"firstBaseline=$firstBaseline, " +
"lastBaseline=$lastBaseline, " +
"placeholderRects=$placeholderRects" +
")"
}
} | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/TextLayoutResult.kt | 2580909849 |
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.test
import androidx.compose.foundation.layout.Column
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.semantics.SemanticsPropertyReceiver
import androidx.compose.ui.semantics.selected
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.semantics.testTag
import androidx.compose.ui.semantics.toggleableState
import androidx.compose.ui.state.ToggleableState
import androidx.compose.ui.test.junit4.createComposeRule
import org.junit.Rule
import org.junit.Test
class AssertsTest {
@get:Rule
val rule = createComposeRule()
@Test
fun assertIsOn_forCheckedElement_isOk() {
rule.setContent {
BoundaryNode { testTag = "test"; toggleableState = ToggleableState.On }
}
rule.onNodeWithTag("test")
.assertIsOn()
}
@Test(expected = AssertionError::class)
fun assertIsOn_forUncheckedElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; toggleableState = ToggleableState.Off }
}
rule.onNodeWithTag("test")
.assertIsOn()
}
@Test(expected = AssertionError::class)
fun assertIsOn_forNotToggleableElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test" }
}
rule.onNodeWithTag("test")
.assertIsOn()
}
@Test(expected = AssertionError::class)
fun assertIsOff_forCheckedElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; toggleableState = ToggleableState.On }
}
rule.onNodeWithTag("test")
.assertIsOff()
}
@Test
fun assertIsOff_forUncheckedElement_isOk() {
rule.setContent {
BoundaryNode { testTag = "test"; toggleableState = ToggleableState.Off }
}
rule.onNodeWithTag("test")
.assertIsOff()
}
@Test(expected = AssertionError::class)
fun assertIsOff_forNotToggleableElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; }
}
rule.onNodeWithTag("test")
.assertIsOff()
}
@Test(expected = AssertionError::class)
fun assertIsSelected_forNotSelectedElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; selected = false }
}
rule.onNodeWithTag("test")
.assertIsSelected()
}
@Test
fun assertIsSelected_forSelectedElement_isOk() {
rule.setContent {
BoundaryNode { testTag = "test"; selected = true }
}
rule.onNodeWithTag("test")
.assertIsSelected()
}
@Test(expected = AssertionError::class)
fun assertIsSelected_forNotSelectableElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; }
}
rule.onNodeWithTag("test")
.assertIsSelected()
}
@Test(expected = AssertionError::class)
fun assertIsNotSelected_forSelectedElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; selected = true }
}
rule.onNodeWithTag("test")
.assertIsNotSelected()
}
@Test
fun assertIsNotSelected_forNotSelectedElement_isOk() {
rule.setContent {
BoundaryNode { testTag = "test"; selected = false }
}
rule.onNodeWithTag("test")
.assertIsNotSelected()
}
@Test(expected = AssertionError::class)
fun assertIsNotSelected_forNotSelectableElement_throwsError() {
rule.setContent {
BoundaryNode { testTag = "test"; }
}
rule.onNodeWithTag("test")
.assertIsNotSelected()
}
@Composable
fun BoundaryNode(props: (SemanticsPropertyReceiver.() -> Unit)) {
Column(Modifier.semantics(properties = props)) {}
}
} | compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/AssertsTest.kt | 1864178963 |
/*
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby
data class SearchQuery(val q: String)
fun main(args: Array<String>) {
runApp(args) {
get("/") {
val q: List<String> by ctx.query
q
}
}
}
| tests/src/test/kotlin/io/jooby/App.kt | 3356809690 |
/*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengles.templates
import org.lwjgl.generator.*
import org.lwjgl.opengles.*
val NV_internalformat_sample_query = "NVInternalformatSampleQuery".nativeClassGLES("NV_internalformat_sample_query", postfix = NV) {
documentation =
"""
Native bindings to the $registryLink extension.
Some OpenGL implementations support modes of multisampling which have properties which are non-obvious to applications and/or which may not be
standards conformant. The idea of non-conformant AA modes is not new, and is exposed in both GLX and EGL with config caveats and the
GLX_NON_CONFORMANT_CONFIG for GLX and EGL_NON_CONFORMANT_CONFIG for EGL, or by querying the EGL_CONFORMANT attribute in newer versions of EGL.
Both of these mechanisms operate on a per-config basis, which works as intended for window-based configs. However, with the advent of
application-created FBOs, it is now possible to do all the multisample operations in an application-created FBO and never use a multisample window.
This extension further extends the internalformat query mechanism (first introduced by ARB_internalformat_query and extended in
ARB_internalformat_query2) and introduces a mechanism for a implementation to report properties of formats that may also be dependent on the number of
samples. This includes information such as whether the combination of format and samples should be considered conformant. This enables an
implementation to report caveats which might apply to both window and FBO-based rendering configurations.
Some NVIDIA drivers support multisample modes which are internally implemented as a combination of multisampling and automatic supersampling in order
to obtain a higher level of anti-aliasing than can be directly supported by hardware. This extension allows those properties to be queried by an
application with the MULTISAMPLES_NV, SUPERSAMPLE_SCALE_X_NV and SUPERSAMPLE_SCALE_Y_NV properties. For example, a 16xAA mode might be implemented by
using 4 samples and up-scaling by a factor of 2 in each of the x- and y-dimensions. In this example, the driver might report MULTSAMPLES_NV of 4,
SUPERSAMPLE_SCALE_X_NV of 2, SUPERSAMPLE_SCALE_Y_NV of 2 and CONFORMANT_NV of FALSE.
Requires ${GLES30.core}.
"""
IntConstant(
"Accepted by the {@code pname} parameter of GetInternalformatSampleivNV.",
"MULTISAMPLES_NV"..0x9371,
"SUPERSAMPLE_SCALE_X_NV"..0x9372,
"SUPERSAMPLE_SCALE_Y_NV"..0x9373,
"CONFORMANT_NV"..0x9374
)
void(
"GetInternalformatSampleivNV",
"",
GLenum.IN("target", ""),
GLenum.IN("internalformat", ""),
GLsizei.IN("samples", ""),
GLenum.IN("pname", ""),
AutoSize("params")..GLsizei.IN("bufSize", ""),
GLint_p.OUT("params", "")
)
} | modules/templates/src/main/kotlin/org/lwjgl/opengles/templates/NV_internalformat_sample_query.kt | 1989046151 |
package com.simplemobiletools.calculator.helpers
import android.content.Context
import com.simplemobiletools.commons.helpers.BaseConfig
class Config(context: Context) : BaseConfig(context) {
companion object {
fun newInstance(context: Context) = Config(context)
}
var useCommaAsDecimalMark: Boolean
get() = prefs.getBoolean(USE_COMMA_AS_DECIMAL_MARK, getDecimalSeparator() == COMMA)
set(useCommaAsDecimalMark) = prefs.edit().putBoolean(USE_COMMA_AS_DECIMAL_MARK, useCommaAsDecimalMark).apply()
}
| app/src/main/kotlin/com/simplemobiletools/calculator/helpers/Config.kt | 317822427 |
package org.andstatus.app.data.converter
import android.database.sqlite.SQLiteDatabase
class DatabaseUpgradeParams(
val db: SQLiteDatabase,
val oldVersion: Int,
val newVersion: Int
)
| app/src/main/kotlin/org/andstatus/app/data/converter/DatabaseUpgradeParams.kt | 3673854906 |
import junit.framework.TestCase.assertEquals
import org.example.codekata.kata13.countCodeLines
import org.junit.Test
import java.io.File
class Kata13Test {
@Test fun testCountCodeLines() {
val daveUri = "".javaClass.getResource("/kata13_data/Dave.java").toURI()
val helloUri = "".javaClass.getResource("/kata13_data/Hello.java").toURI()
assertEquals(3, countCodeLines(File(daveUri)))
assertEquals(5, countCodeLines(File(helloUri)))
}
} | src/test/kotlin/Kata13Test.kt | 2611843966 |
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.helper
import com.google.samples.apps.topeka.model.quiz.STRING_ARRAY
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class AnswerHelperTest {
@Test fun getAnswer_notNull() = assertThat(AnswerHelper.getReadableAnswer(STRING_ARRAY), notNullValue())
@Test fun getAnswer_allContained() {
for (it in STRING_ARRAY) {
assertThat(AnswerHelper.getReadableAnswer(STRING_ARRAY).contains(it), `is`(true))
}
}
@Test fun getAnswer_multipleAnswers_dontEndWithSeparator() {
assertThat(AnswerHelper.getReadableAnswer(STRING_ARRAY).endsWith(AnswerHelper.SEPARATOR),
`is`(false))
}
} | app/src/test/java/com/google/samples/apps/topeka/helper/AnswerHelperTest.kt | 1386008180 |
package app
import components.headerInput
import components.info
import components.todoBar
import components.todoList
import kotlinx.html.InputType
import kotlinx.html.id
import kotlinx.html.js.onChangeFunction
import kotlinx.html.title
import model.Todo
import model.TodoFilter
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.get
import org.w3c.dom.set
import react.*
import react.dom.input
import react.dom.label
import react.dom.section
import utils.translate
import kotlin.browser.document
import kotlin.browser.localStorage
object AppOptions {
var language = "no-language"
var localStorageKey = "todos-koltin-react"
}
class App : RComponent<App.Props, App.State>() {
override fun componentWillMount() {
console.log("component will mount app")
setState {
todos = loadTodos()
}
}
override fun RBuilder.render() {
val currentFilter = when (props.route) {
"pending" -> TodoFilter.PENDING
"completed" -> TodoFilter.COMPLETED
else -> TodoFilter.ANY
}
section("todoapp") {
headerInput(::createTodo)
if (state.todos.isNotEmpty()) {
val allChecked = isAllCompleted()
section("main") {
input(InputType.checkBox, classes = "toggle-all") {
attrs {
id = "toggle-all"
checked = allChecked
onChangeFunction = {event ->
val isChecked = (event.currentTarget as HTMLInputElement).checked
setAllStatus(isChecked)
}
}
}
label {
attrs["htmlFor"] = "toggle-all"
attrs.title = "Mark all as complete".translate()
}
todoList(::removeTodo, ::updateTodo, state.todos, currentFilter)
}
todoBar(pendingCount = countPending(),
anyCompleted = state.todos.any { todo -> todo.completed },
clearCompleted = ::clearCompleted,
currentFilter = currentFilter,
updateFilter = ::updateFilter)
}
}
info()
}
private fun loadTodos(): List<Todo> {
val storedTodosJSON = localStorage[AppOptions.localStorageKey]
return if (storedTodosJSON != null) {
JSON.parse<Array<Todo>>(storedTodosJSON).map {
Todo(it.id, it.title, it.completed)
}.toList()
} else {
emptyList()
}
}
private fun updateFilter(newFilter: TodoFilter) {
document.location!!.href = "#?route=${newFilter.name.toLowerCase()}"
}
private fun countPending() = pendingTodos().size
private fun removeTodo(todo: Todo) {
console.log("removeTodo [${todo.id}] ${todo.title}")
saveTodos(state.todos - todo)
}
private fun createTodo(todo: Todo) {
console.log("createTodo [${todo.id}] ${todo.title}")
saveTodos(state.todos + todo)
}
private fun updateTodo(todo: Todo) {
console.log("updateTodo [${todo.id}] ${todo.title}")
val newTodos = state.todos.map { oldTodo ->
if (todo.id == oldTodo.id) {
todo
} else {
oldTodo
}
}
saveTodos(newTodos)
}
private fun setAllStatus(newStatus: Boolean) {
saveTodos(state.todos.map { todo -> todo.copy(completed = newStatus) })
}
private fun saveTodos(updatedTodos: List<Todo>) {
console.log("saving: ${updatedTodos.toTypedArray()}")
storeTodos(updatedTodos)
setState {
todos = updatedTodos
}
}
private fun storeTodos(todos: List<Todo>) {
localStorage.setItem(AppOptions.localStorageKey, JSON.stringify(todos.toTypedArray()))
}
private fun clearCompleted() {
saveTodos(pendingTodos())
}
private fun isAllCompleted(): Boolean {
return state.todos.fold(true) { allCompleted, todo ->
allCompleted && todo.completed
}
}
private fun pendingTodos() : List<Todo> {
return state.todos.filter { todo -> !todo.completed }
}
class State(var todos: List<Todo>) : RState
class Props(var route: String) : RProps
}
fun RBuilder.app(route: String) = child(App::class) {
attrs.route = route
}
| examples/kotlin-react/src/app/App.kt | 2779693570 |
/**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.installation.servlet
import com.mycollab.core.utils.MimeTypesUtil
import org.slf4j.LoggerFactory
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* @author MyCollab Ltd.
* @since 3.0
*/
class AssetHttpServletRequestHandler : HttpServlet() {
@Throws(ServletException::class, IOException::class)
override fun doGet(request: HttpServletRequest, response: HttpServletResponse) {
val path = request.pathInfo
var resourcePath = "assets$path"
var inputStream = AssetHttpServletRequestHandler::class.java.classLoader.getResourceAsStream(resourcePath)
if (inputStream == null) {
resourcePath = "VAADIN/themes/mycollab$path"
inputStream = AssetHttpServletRequestHandler::class.java.classLoader.getResourceAsStream(resourcePath)
}
if (inputStream != null) {
response.setHeader("Content-Type", MimeTypesUtil.detectMimeType(path))
response.setHeader("Content-Length", inputStream.available().toString())
BufferedInputStream(inputStream).use { input ->
BufferedOutputStream(response.outputStream).use { output ->
val buffer = ByteArray(8192)
var length = input.read(buffer)
while (length > 0) {
output.write(buffer, 0, length)
length = input.read(buffer)
}
}
}
} else {
LOG.error("Can not find resource has path $path")
}
}
companion object {
private val LOG = LoggerFactory.getLogger(AssetHttpServletRequestHandler::class.java)
}
}
| mycollab-server-runner/src/main/java/com/mycollab/installation/servlet/AssetHttpServletRequestHandler.kt | 3913049018 |
package y2k.joyreactor.common.http
import okhttp3.MediaType
import okhttp3.RequestBody
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import y2k.joyreactor.common.stream
import java.net.URLEncoder
import java.util.*
class HttpRequestBuilder(private val httpClient: DefaultHttpClient) : RequestBuilder {
private val form = HashMap<String, String>()
private val headers = HashMap<String, String>()
override fun addField(key: String, value: String): HttpRequestBuilder {
form.put(key, value)
return this
}
override fun putHeader(name: String, value: String): HttpRequestBuilder {
headers.put(name, value)
return this
}
override fun get(url: String): Document {
val response = httpClient.executeRequest(url) {
headers.forEach { header(it.key, it.value) }
}
return response.stream().use { Jsoup.parse(it, "utf-8", url) }
}
override fun post(url: String): Document {
val response = httpClient.executeRequest(url) {
headers.forEach { header(it.key, it.value) }
post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), serializeForm()))
}
return response.stream().use { Jsoup.parse(it, "utf-8", url) }
}
private fun serializeForm(): ByteArray {
return form
.map { it.key + "=" + URLEncoder.encode(it.value, "UTF-8") }
.joinToString (separator = "&")
.toByteArray()
}
} | core/src/main/kotlin/y2k/joyreactor/common/http/HttpRequestBuilder.kt | 3695911765 |
package com.google.firebase.example.appcheck.kotlin
import com.google.firebase.appcheck.FirebaseAppCheck
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.http.GET
import retrofit2.http.Header
// [START appcheck_custom_backend]
class ApiWithAppCheckExample {
interface YourExampleBackendService {
@GET("yourExampleEndpoint")
fun exampleData(
@Header("X-Firebase-AppCheck") appCheckToken: String
): Call<List<String>>
}
var yourExampleBackendService: YourExampleBackendService = Retrofit.Builder()
.baseUrl("https://yourbackend.example.com/")
.build()
.create(YourExampleBackendService::class.java)
fun callApiExample() {
FirebaseAppCheck.getInstance()
.getAppCheckToken(false)
.addOnSuccessListener { tokenResponse ->
val appCheckToken = tokenResponse.token
val apiCall = yourExampleBackendService.exampleData(appCheckToken)
// ...
}
}
}
// [END appcheck_custom_backend]
| appcheck/app/src/main/java/com/google/firebase/example/appcheck/kotlin/ApiWithAppCheckExample.kt | 4070418577 |
/*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2021-present Benoit 'BoD' Lubek ([email protected])
*
* 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 org.jraf.android.cinetoday.app.tile.preview
import android.content.ComponentName
import android.os.Bundle
import android.widget.FrameLayout
import androidx.activity.ComponentActivity
import androidx.wear.tiles.manager.TileUiClient
import org.jraf.android.cinetoday.R
import org.jraf.android.cinetoday.app.tile.MoviesTodayTile
class TilePreviewActivity : ComponentActivity() {
private lateinit var tileUiClient: TileUiClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.tile_preview_activity)
val rootLayout = findViewById<FrameLayout>(R.id.conRoot)
tileUiClient = TileUiClient(
context = this,
component = ComponentName(this, MoviesTodayTile::class.java),
parentView = rootLayout
)
tileUiClient.connect()
}
override fun onDestroy() {
super.onDestroy()
tileUiClient.close()
}
} | app/src/debug/kotlin/org/jraf/android/cinetoday/app/tile/preview/TilePreviewActivity.kt | 1600741601 |
package qiuxiang.amap3d.map_view
import android.content.Context
import com.amap.api.maps.AMap
import com.amap.api.maps.model.HeatmapTileProvider
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.TileOverlay
import com.amap.api.maps.model.TileOverlayOptions
import com.facebook.react.views.view.ReactViewGroup
class HeatMap(context: Context) : ReactViewGroup(context), Overlay {
private var overlay: TileOverlay? = null
var data: List<LatLng> = emptyList()
var opacity: Double = 0.6
var radius: Int = 12
override fun add(map: AMap) {
overlay = map.addTileOverlay(
TileOverlayOptions().tileProvider(
HeatmapTileProvider.Builder()
.data(data)
.radius(radius)
.transparency(opacity)
.build()
)
)
}
override fun remove() {
overlay?.remove()
}
} | lib/android/src/main/java/qiuxiang/amap3d/map_view/HeatMap.kt | 311037958 |
package com.naosim.rpglib.android
import android.app.Dialog
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import android.widget.AdapterView
import android.widget.ListView
import android.widget.Toast
import com.naosim.rpglib.R
import com.naosim.rpglib.model.value.Item
class ItemSelectDialogFactory {
fun showItemListDialog(context: Context, itemList: List<Item>, onItemSelectedListener: (Item) -> Unit) {
if (itemList.size == 0) {
Toast.makeText(context, "どうぐがありません", Toast.LENGTH_SHORT).show()
return
}
createItemListDialog(context, itemList, onItemSelectedListener).show()
}
fun createItemListDialog(context: Context, itemList: List<Item>, onItemSelectedListener: (Item) -> Unit): Dialog {
val view = LayoutInflater.from(context).inflate(R.layout.view_item, null)
val alertDialog = AlertDialog.Builder(context).setView(view).create()
val listView = view.findViewById(R.id.itemListView) as ListView
listView.adapter = ItemListAdapter(context, itemList)
listView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
val selectedItem = adapterView.adapter.getItem(i) as Item
onItemSelectedListener.invoke(selectedItem)
alertDialog.dismiss()
}
view.findViewById(R.id.cancelButton).setOnClickListener { alertDialog.dismiss() }
return alertDialog
}
}
| rpglib/src/main/kotlin/com/naosim/rpglib/android/ItemSelectDialogFactory.kt | 2025264373 |
package org.xdty.callerinfo.settings
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import android.os.RemoteException
import android.preference.PreferenceScreen
import android.util.Log
import org.xdty.callerinfo.R
import org.xdty.callerinfo.exporter.Exporter
import org.xdty.callerinfo.plugin.IPluginService
import org.xdty.callerinfo.plugin.IPluginServiceCallback
import org.xdty.callerinfo.utils.Toasts.show
class PluginBinder(private val context: Context, private val preferenceDialogs: PreferenceDialogs,
private val preferenceActions: PreferenceActions) : ServiceConnection {
private val mPluginIntent = Intent().setComponent(ComponentName(
"org.xdty.callerinfo.plugin",
"org.xdty.callerinfo.plugin.PluginService"))
private var mPluginService: IPluginService? = null
fun bindPluginService() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(mPluginIntent)
} else {
context.startService(mPluginIntent)
}
context.bindService(mPluginIntent, this, Context.BIND_AUTO_CREATE)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun unBindPluginService() {
try {
context.unbindService(this)
context.stopService(mPluginIntent)
} catch (e: Exception) {
e.printStackTrace()
}
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.d(TAG, "onServiceConnected: $name")
mPluginService = IPluginService.Stub.asInterface(service)
try {
mPluginService?.registerCallback(object : IPluginServiceCallback.Stub() {
@Throws(RemoteException::class)
override fun onCallPermissionResult(success: Boolean) {
Log.d(TAG, "onCallPermissionResult: $success")
(context as Activity).runOnUiThread { preferenceActions.setChecked(R.string.auto_hangup_key, success) }
}
@Throws(RemoteException::class)
override fun onCallLogPermissionResult(success: Boolean) {
Log.d(TAG, "onCallLogPermissionResult: $success")
(context as Activity).runOnUiThread {
if (PluginStatus.isCheckRingOnce) {
preferenceActions.setChecked(R.string.ring_once_and_auto_hangup_key, success)
} else {
preferenceActions.setChecked(R.string.add_call_log_key, success)
}
}
}
@Throws(RemoteException::class)
override fun onStoragePermissionResult(success: Boolean) {
Log.d(TAG, "onStoragePermissionResult: $success")
if (success) {
if (PluginStatus.isCheckStorageExport) {
exportData()
} else {
importData()
}
} else {
show(context, R.string.storage_permission_failed)
}
}
})
enablePluginPreference()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun enablePluginPreference() {
val pluginPref = preferenceActions.findPreference(context.getString(R.string.plugin_key)) as PreferenceScreen?
pluginPref!!.isEnabled = true
pluginPref.summary = ""
}
override fun onServiceDisconnected(name: ComponentName) {
Log.d(TAG, "onServiceDisconnected: $name")
mPluginService = null
}
fun checkStoragePermission() {
try {
if (mPluginService != null) {
mPluginService!!.checkStoragePermission()
} else {
Log.e(TAG, "PluginService is stopped!!")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
@SuppressLint("CheckResult")
private fun importData() {
try {
if (mPluginService != null) {
val data = mPluginService!!.importData()
if (data.contains("Error:")) {
preferenceDialogs.showTextDialog(R.string.import_data,
context.getString(R.string.import_failed, data))
} else {
val exporter = Exporter(context)
exporter.fromString(data).subscribe { s ->
if (s == null) {
preferenceDialogs.showTextDialog(R.string.import_data,
R.string.import_succeed)
} else {
preferenceDialogs.showTextDialog(R.string.import_data,
context.getString(R.string.import_failed, s))
}
}
}
} else {
Log.e(TAG, "PluginService is stopped!!")
}
} catch (e: Exception) {
e.printStackTrace()
}
}
@SuppressLint("CheckResult")
private fun exportData() {
val exporter = Exporter(context)
exporter.export().subscribe { s ->
try {
val res = mPluginService!!.exportData(s)
if (res.contains("Error")) {
preferenceDialogs.showTextDialog(R.string.export_data,
context.getString(R.string.export_failed, res))
} else {
preferenceDialogs.showTextDialog(R.string.export_data,
context.getString(R.string.export_succeed, res))
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
fun checkCallPermission() {
try {
mPluginService?.checkCallPermission()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun checkCallLogPermission() {
try {
mPluginService?.checkCallLogPermission()
} catch (e: Exception) {
e.printStackTrace()
}
}
fun setIconStatus(show: Boolean) {
try {
mPluginService?.setIconStatus(show)
} catch (e: Exception) {
e.printStackTrace()
}
}
companion object {
private const val TAG = "PluginBinder"
}
} | app/src/main/java/org/xdty/callerinfo/settings/PluginBinder.kt | 2935632787 |
package uy.klutter.elasticsearch
import com.fasterxml.jackson.core.type.TypeReference
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.search.SearchHits
inline fun <reified T: Any> SearchResponse.getHitsAsObjects(): Sequence<T> {
return getHits().getHits().asSequence().map { EsConfig.objectMapper.readValue<T>(it.sourceAsString(), object : TypeReference<T>(){}) }
}
inline fun <reified T: Any> SearchHits.getHitsAsObjects(): Sequence<T> {
return getHits().asSequence().map { EsConfig.objectMapper.readValue<T>(it.sourceAsString(), object : TypeReference<T>(){}) }
}
| elasticsearch-5.x/src/main/kotlin/uy/klutter/elasticsearch/Results.kt | 298442692 |
/*
* Copyright (C) 2016-2017 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.xquery.ast.plugin
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathKindTest
/**
* A MarkLogic `BinaryTest` node in the XQuery AST.
*/
interface PluginBinaryTest : XPathKindTest
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/plugin/PluginBinaryTest.kt | 3248616953 |
package com.habitrpg.common.habitica.extensions
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.View
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.LinearLayout
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.drawable.toBitmap
import coil.imageLoader
import coil.request.ImageRequest
import com.habitrpg.android.habitica.extensions.setTintWith
import com.habitrpg.common.habitica.R
import com.habitrpg.common.habitica.extensions.DataBindingUtils.BASE_IMAGE_URL
import com.habitrpg.common.habitica.helpers.AppConfigManager
import com.habitrpg.common.habitica.views.PixelArtView
import java.util.Collections
import java.util.Date
fun PixelArtView.loadImage(imageName: String?, imageFormat: String? = null) {
if (imageName != null) {
val fullname = DataBindingUtils.getFullFilename(imageName, imageFormat)
if (tag == fullname) {
return
}
tag = fullname
bitmap = null
DataBindingUtils.loadImage(context, imageName, imageFormat) {
if (tag == fullname) {
bitmap = it.toBitmap()
}
}
}
}
fun PixelArtView.loadGif(
imageName: String?,
builder: ImageRequest.Builder.() -> Unit = {}
) {
if (imageName != null) {
val fullname = BASE_IMAGE_URL + DataBindingUtils.getFullFilename(imageName)
val request = ImageRequest.Builder(context)
.data(fullname)
.target(this)
.apply(builder)
.build()
context.imageLoader.enqueue(request)
}
}
object DataBindingUtils {
fun loadImage(context: Context, imageName: String, imageResult: (Drawable) -> Unit) {
loadImage(context, imageName, null, imageResult)
}
fun loadImage(
context: Context,
imageName: String,
imageFormat: String?,
imageResult: (Drawable) -> Unit
) {
val request = ImageRequest.Builder(context)
.data(BASE_IMAGE_URL + getFullFilename(imageName, imageFormat))
.target()
.target {
imageResult(it)
}
.build()
context.imageLoader.enqueue(request)
}
fun getFullFilename(imageName: String, imageFormat: String? = null): String {
val name = when {
spriteSubstitutions.containsKey(imageName) -> spriteSubstitutions[imageName]
FILENAME_MAP.containsKey(imageName) -> FILENAME_MAP[imageName]
imageName.startsWith("handleless") -> "chair_$imageName"
else -> imageName
}
return name + if (imageFormat == null && FILEFORMAT_MAP.containsKey(imageName)) {
"." + FILEFORMAT_MAP[imageName]
} else {
".${imageFormat ?: "png"}"
}
}
fun setRoundedBackground(view: View, color: Int) {
val drawable = ResourcesCompat.getDrawable(view.resources, R.drawable.layout_rounded_bg, null)
drawable?.setTintWith(color, PorterDuff.Mode.MULTIPLY)
view.background = drawable
}
class LayoutWeightAnimation(internal var view: View, internal var targetWeight: Float) : Animation() {
private var initializeWeight: Float = 0.toFloat()
private var layoutParams: LinearLayout.LayoutParams = view.layoutParams as LinearLayout.LayoutParams
init {
initializeWeight = layoutParams.weight
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
layoutParams.weight = initializeWeight + (targetWeight - initializeWeight) * interpolatedTime
view.requestLayout()
}
override fun willChangeBounds(): Boolean = true
}
const val BASE_IMAGE_URL = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/"
private val FILEFORMAT_MAP: Map<String, String>
private val FILENAME_MAP: Map<String, String>
private var spriteSubstitutions: Map<String, String> = HashMap()
get() {
if (Date().time - (lastSubstitutionCheck?.time ?: 0) > 180000) {
field = AppConfigManager().spriteSubstitutions()["generic"] ?: HashMap()
lastSubstitutionCheck = Date()
}
return field
}
private var lastSubstitutionCheck: Date? = null
init {
val tempMap = HashMap<String, String>()
tempMap["head_special_1"] = "gif"
tempMap["broad_armor_special_1"] = "gif"
tempMap["slim_armor_special_1"] = "gif"
tempMap["head_special_0"] = "gif"
tempMap["slim_armor_special_0"] = "gif"
tempMap["broad_armor_special_0"] = "gif"
tempMap["weapon_special_critical"] = "gif"
tempMap["weapon_special_0"] = "gif"
tempMap["shield_special_0"] = "gif"
tempMap["Pet-Wolf-Cerberus"] = "gif"
tempMap["armor_special_ks2019"] = "gif"
tempMap["slim_armor_special_ks2019"] = "gif"
tempMap["broad_armor_special_ks2019"] = "gif"
tempMap["eyewear_special_ks2019"] = "gif"
tempMap["head_special_ks2019"] = "gif"
tempMap["shield_special_ks2019"] = "gif"
tempMap["weapon_special_ks2019"] = "gif"
tempMap["Pet-Gryphon-Gryphatrice"] = "gif"
tempMap["Mount_Head_Gryphon-Gryphatrice"] = "gif"
tempMap["Mount_Body_Gryphon-Gryphatrice"] = "gif"
tempMap["background_clocktower"] = "gif"
tempMap["background_airship"] = "gif"
tempMap["background_steamworks"] = "gif"
tempMap["Pet_HatchingPotion_Veggie"] = "gif"
tempMap["Pet_HatchingPotion_Dessert"] = "gif"
tempMap["Pet-HatchingPotion-Dessert"] = "gif"
tempMap["quest_windup"] = "gif"
tempMap["Pet-HatchingPotion_Windup"] = "gif"
tempMap["Pet_HatchingPotion_Windup"] = "gif"
tempMap["quest_solarSystem"] = "gif"
tempMap["quest_virtualpet"] = "gif"
tempMap["Pet_HatchingPotion_VirtualPet"] = "gif"
FILEFORMAT_MAP = Collections.unmodifiableMap(tempMap)
val tempNameMap = HashMap<String, String>()
tempNameMap["head_special_1"] = "ContributorOnly-Equip-CrystalHelmet"
tempNameMap["armor_special_1"] = "ContributorOnly-Equip-CrystalArmor"
tempNameMap["head_special_0"] = "BackerOnly-Equip-ShadeHelmet"
tempNameMap["armor_special_0"] = "BackerOnly-Equip-ShadeArmor"
tempNameMap["shield_special_0"] = "BackerOnly-Shield-TormentedSkull"
tempNameMap["weapon_special_0"] = "BackerOnly-Weapon-DarkSoulsBlade"
tempNameMap["weapon_special_critical"] = "weapon_special_critical"
tempNameMap["Pet-Wolf-Cerberus"] = "Pet-Wolf-Cerberus"
FILENAME_MAP = Collections.unmodifiableMap(tempNameMap)
}
}
| common/src/main/java/com/habitrpg/common/habitica/extensions/DataBindingUtils.kt | 34798695 |
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
@Retention(AnnotationRetention.RUNTIME)
annotation class Ann(
val p1: Int,
val p2: Short,
val p3: Byte,
val p4: Int,
val p5: Int,
val p6: Int
)
val prop1: Int = 1 or 1
val prop2: Short = 1 and 1
val prop3: Byte = 1 xor 1
val prop4: Int = 1 shl 1
val prop5: Int = 1 shr 1
val prop6: Int = 1 ushr 1
@Ann(1 or 1, 1 and 1, 1 xor 1, 1 shl 1, 1 shr 1, 1 ushr 1) class MyClass
fun box(): String {
val annotation = MyClass::class.java.getAnnotation(Ann::class.java)!!
if (annotation.p1 != prop1) return "fail 1, expected = ${prop1}, actual = ${annotation.p1}"
if (annotation.p2 != prop2) return "fail 2, expected = ${prop2}, actual = ${annotation.p2}"
if (annotation.p3 != prop3) return "fail 3, expected = ${prop3}, actual = ${annotation.p3}"
if (annotation.p4 != prop4) return "fail 4, expected = ${prop4}, actual = ${annotation.p4}"
if (annotation.p5 != prop5) return "fail 5, expected = ${prop5}, actual = ${annotation.p5}"
if (annotation.p6 != prop6) return "fail 6, expected = ${prop6}, actual = ${annotation.p6}"
return "OK"
}
| backend.native/tests/external/codegen/box/evaluate/intrinsics.kt | 2385098074 |
/*
* Copyright 2019 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.q.metrics
import com.netflix.spectator.api.Counter
import com.netflix.spectator.api.Registry
import com.netflix.spectator.api.patterns.PolledMeter
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import java.time.Duration
import java.time.Instant
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
/**
* - can be registered as a queue EventPublisher
* - publishes metrics based on queue events
*/
class QueueMetricsPublisher(
val registry: Registry,
val clock: Clock
) : EventPublisher {
init {
PolledMeter.using(registry)
.withName("queue.last.poll.age")
.monitorValue(
this,
{
Duration
.between(it.lastQueuePoll, clock.instant())
.toMillis()
.toDouble()
}
)
PolledMeter.using(registry)
.withName("queue.last.retry.check.age")
.monitorValue(
this,
{
Duration
.between(it.lastRetryPoll, clock.instant())
.toMillis()
.toDouble()
}
)
}
override fun publishEvent(event: QueueEvent) {
when (event) {
QueuePolled -> _lastQueuePoll.set(clock.instant())
is MessageProcessing -> {
registry.timer("queue.message.lag").record(event.lag.toMillis(), TimeUnit.MILLISECONDS)
}
is RetryPolled -> _lastRetryPoll.set(clock.instant())
is MessagePushed -> event.counter.increment()
is MessageAcknowledged -> event.counter.increment()
is MessageRetried -> event.counter.increment()
is MessageDead -> event.counter.increment()
is MessageDuplicate -> event.counter.increment()
is LockFailed -> event.counter.increment()
is MessageRescheduled -> event.counter.increment()
is MessageNotFound -> event.counter.increment()
}
}
/**
* Count of messages pushed to the queue.
*/
private val MessagePushed.counter: Counter
get() = registry.counter("queue.pushed.messages")
/**
* Count of messages successfully processed and acknowledged.
*/
private val MessageAcknowledged.counter: Counter
get() = registry.counter("queue.acknowledged.messages")
/**
* Count of messages that have been retried. This does not mean unique
* messages, so retrying the same message again will still increment this
* count.
*/
private val MessageRetried.counter: Counter
get() = registry.counter("queue.retried.messages")
/**
* Count of messages that have exceeded [Queue.maxRetries] retry
* attempts and have been sent to the dead message handler.
*/
private val MessageDead.counter: Counter
get() = registry.counter("queue.dead.messages")
/**
* Count of messages that have been pushed or re-delivered while an identical
* message is already on the queue.
*/
private val MessageDuplicate.counter: Counter
get() = registry.counter(
"queue.duplicate.messages",
"messageType", payload.javaClass.simpleName
)
/**
* Count of attempted message reads that failed to acquire a lock (in other
* words, multiple Orca instance tried to read the same message).
*/
private val LockFailed.counter: Counter
get() = registry.counter("queue.lock.failed")
/**
* Count of attempted message rescheduling that succeeded (in other words,
* that message existed on the queue).
*/
private val MessageRescheduled.counter: Counter
get() = registry.counter("queue.reschedule.succeeded")
/**
* Count of attempted message rescheduling that failed (in other words,
* that message did not exist on the queue).
*/
private val MessageNotFound.counter: Counter
get() = registry.counter("queue.message.notfound")
/**
* The last time the [Queue.poll] method was executed.
*/
val lastQueuePoll: Instant
get() = _lastQueuePoll.get()
private val _lastQueuePoll = AtomicReference<Instant>(clock.instant())
/**
* The time the last [Queue.retry] method was executed.
*/
val lastRetryPoll: Instant
get() = _lastRetryPoll.get()
private val _lastRetryPoll = AtomicReference<Instant>(clock.instant())
}
| keiko-core/src/main/kotlin/com/netflix/spinnaker/q/metrics/QueueMetricsPublisher.kt | 3183970263 |
package me.liuqingwen.android.projectbasicmvp.view
import me.liuqingwen.android.projectbasicmvp.model.Movie
/**
* Created by Qingwen on 2018-2-16, project: ProjectBasicMVP.
*
* @Author: Qingwen
* @DateTime: 2018-2-16
* @Package: me.liuqingwen.android.projectbasicmvp.view in project: ProjectBasicMVP
*
* Notice: If you are using this class or file, check it and do some modification.
*/
interface IMovieView
{
fun onLoadStarted()
fun onLoadError(message: String?)
fun onLoadSuccess(it: List<Movie>)
} | ProjectBasicMVP/app/src/main/java/me/liuqingwen/android/projectbasicmvp/view/IMovieView.kt | 2829295360 |
/**
* Copyright 2017 Savvas Dalkitsis
* 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.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.infra.android
import android.content.Context
import android.support.annotation.StringRes
class StringUseCase(private val context:Context) {
fun getString(@StringRes resId: Int): String = context.getString(resId)
fun getString(@StringRes resId: Int, arg: String): String = context.getString(resId, arg)
} | infra/src/main/java/com/savvasdalkitsis/gameframe/infra/android/StringUseCase.kt | 1403148168 |
package eu.kanade.tachiyomi.source
import android.graphics.drawable.Drawable
import eu.kanade.domain.source.model.SourceData
import eu.kanade.domain.source.service.SourcePreferences
import eu.kanade.tachiyomi.extension.ExtensionManager
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
fun Source.icon(): Drawable? = Injekt.get<ExtensionManager>().getAppIconForSource(this.id)
fun Source.getPreferenceKey(): String = "source_$id"
fun Source.toSourceData(): SourceData = SourceData(id = id, lang = lang, name = name)
fun Source.getNameForMangaInfo(): String {
val preferences = Injekt.get<SourcePreferences>()
val enabledLanguages = preferences.enabledLanguages().get()
.filterNot { it in listOf("all", "other") }
val hasOneActiveLanguages = enabledLanguages.size == 1
val isInEnabledLanguages = lang in enabledLanguages
return when {
// For edge cases where user disables a source they got manga of in their library.
hasOneActiveLanguages && !isInEnabledLanguages -> toString()
// Hide the language tag when only one language is used.
hasOneActiveLanguages && isInEnabledLanguages -> name
else -> toString()
}
}
fun Source.isLocal(): Boolean = id == LocalSource.ID
fun Source.isLocalOrStub(): Boolean = isLocal() || this is SourceManager.StubSource
| app/src/main/java/eu/kanade/tachiyomi/source/SourceExtensions.kt | 2431406762 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast.evaluation
import com.intellij.lang.Language
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.*
import org.jetbrains.uast.values.UUndeterminedValue
import org.jetbrains.uast.values.UValue
abstract class AbstractEvaluatorExtension(override val language: Language) : UEvaluatorExtension {
override fun evaluatePostfix(
operator: UastPostfixOperator,
operandValue: UValue,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluatePrefix(
operator: UastPrefixOperator,
operandValue: UValue,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluateBinary(
binaryExpression: UBinaryExpression,
leftValue: UValue,
rightValue: UValue,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluateQualified(
accessType: UastQualifiedExpressionAccessType,
receiverInfo: UEvaluationInfo,
selectorInfo: UEvaluationInfo
): UEvaluationInfo = UUndeterminedValue to selectorInfo.state
override fun evaluateMethodCall(
target: PsiMethod,
argumentValues: List<UValue>,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
override fun evaluateVariable(
variable: UVariable,
state: UEvaluationState
): UEvaluationInfo = UUndeterminedValue to state
}
abstract class SimpleEvaluatorExtension : AbstractEvaluatorExtension(Language.ANY) {
override final fun evaluatePostfix(operator: UastPostfixOperator, operandValue: UValue, state: UEvaluationState): UEvaluationInfo {
val result = evaluatePostfix(operator, operandValue)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluatePostfix(operator, operandValue, state)
}
open fun evaluatePostfix(operator: UastPostfixOperator, operandValue: UValue): Any? = UUndeterminedValue
override final fun evaluatePrefix(operator: UastPrefixOperator, operandValue: UValue, state: UEvaluationState): UEvaluationInfo {
val result = evaluatePrefix(operator, operandValue)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluatePrefix(operator, operandValue, state)
}
open fun evaluatePrefix(operator: UastPrefixOperator, operandValue: UValue): Any? = UUndeterminedValue
override final fun evaluateBinary(binaryExpression: UBinaryExpression,
leftValue: UValue,
rightValue: UValue,
state: UEvaluationState): UEvaluationInfo {
val result = evaluateBinary(binaryExpression, leftValue, rightValue)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluateBinary(binaryExpression, leftValue, rightValue, state)
}
open fun evaluateBinary(binaryExpression: UBinaryExpression, leftValue: UValue, rightValue: UValue): Any? = UUndeterminedValue
override final fun evaluateMethodCall(target: PsiMethod, argumentValues: List<UValue>, state: UEvaluationState): UEvaluationInfo {
val result = evaluateMethodCall(target, argumentValues)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluateMethodCall(target, argumentValues, state)
}
open fun evaluateMethodCall(target: PsiMethod, argumentValues: List<UValue>): Any? = UUndeterminedValue
override final fun evaluateVariable(variable: UVariable, state: UEvaluationState): UEvaluationInfo {
val result = evaluateVariable(variable)
return if (result != UUndeterminedValue)
result.toConstant() to state
else
super.evaluateVariable(variable, state)
}
open fun evaluateVariable(variable: UVariable): Any? = UUndeterminedValue
}
| uast/uast-common/src/org/jetbrains/uast/evaluation/AbstractEvaluatorExtension.kt | 3485105769 |
package com.jdiazcano.modulartd.io
import com.badlogic.gdx.files.FileHandle
import com.google.gson.GsonBuilder
import com.jdiazcano.modulartd.beans.Map
import java.io.IOException
/**
* Json implementation for MapIO. This will be initialised with reflection
*/
class JsonMapIO : FileIO<Map> {
private val parser = GsonBuilder().create()
@Throws(MapDeserializationException::class)
override fun read(file: FileHandle): Map {
try {
return parser.fromJson(file.reader(), Map::class.java)
} catch (e: IOException) {
throw MapDeserializationException("Error deserialising Json", e)
}
}
@Throws(MapSerializationException::class)
override fun write(obj: Map, file: FileHandle) {
try {
file.writeString(parser.toJson(obj), false, "UTF-8")
} catch (e: IOException) {
throw MapSerializationException("Failed to write json to a file", e)
}
}
} | editor/core/src/main/kotlin/com/jdiazcano/modulartd/io/JsonMapIO.kt | 3395179215 |
package tech.thdev.app
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.myapplication", appContext.packageName)
}
} | app/src/androidTest/java/tech/thdev/app/ExampleInstrumentedTest.kt | 2905707243 |
package com.trevorhalvorson.ping
interface BasePresenter {
fun start()
fun stop()
} | app/src/main/kotlin/com/trevorhalvorson/ping/BasePresenter.kt | 2304036164 |
package com.guardafilme.data
import android.content.Intent
import android.support.v4.app.FragmentActivity
import com.firebase.ui.auth.AuthUI
import com.guardafilme.R
import java.util.*
import javax.inject.Inject
/**
* Created by lucassantos on 01/11/17.
*/
class AuthProvider @Inject constructor() {
fun getAuthIntent(): Intent {
return AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(
Arrays.asList(AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.PhoneBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()))
.setLogo(R.drawable.logo)
.setTheme(R.style.LoginTheme)
.build()
}
fun logoutUser(activity: FragmentActivity, completionListener: () -> Unit) {
AuthUI.getInstance()
.signOut(activity)
.addOnCompleteListener { task -> completionListener() }
}
} | app/src/main/java/com/guardafilme/data/AuthProvider.kt | 1327757106 |
package venus.riscv.insts
import venus.riscv.insts.dsl.ITypeInstruction
val addi = ITypeInstruction(
name = "addi",
opcode = 0b0010011,
funct3 = 0b000,
eval32 = { a, b -> a + b },
eval64 = { a, b -> a + b }
)
| src/main/kotlin/venus/riscv/insts/addi.kt | 1753477419 |
package io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.hashtags
import io.github.feelfreelinux.wykopmobilny.api.mywykop.MyWykopApi
import io.github.feelfreelinux.wykopmobilny.base.BasePresenter
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.NotificationsListView
import io.github.feelfreelinux.wykopmobilny.utils.rx.SubscriptionHelperApi
class HashTagsNotificationsListPresenter(val subscriptionHelper: SubscriptionHelperApi, val myWykopApi: MyWykopApi) : BasePresenter<NotificationsListView>() {
var page = 1
fun loadData(shouldRefresh : Boolean) {
if (shouldRefresh) page = 1
subscriptionHelper.subscribe(myWykopApi.getHashTagNotifications(page),
{
if (it.isNotEmpty()) {
page++
view?.addNotifications(it, shouldRefresh)
} else view?.disableLoading()
}, { view?.showErrorDialog(it) }, this)
}
fun readNotifications() {
subscriptionHelper.subscribe(myWykopApi.readHashTagNotifications(),
{ view?.showReadToast() }, { view?.showErrorDialog(it) }, this)
}
override fun unsubscribe() {
super.unsubscribe()
subscriptionHelper.dispose(this)
}
} | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notificationslist/hashtags/HashTagsNotificationsListPresenter.kt | 2040834582 |
package expo.modules.splashscreen.exceptions
import expo.modules.core.errors.CodedException
class NoContentViewException : CodedException("ContentView is not yet available. Call 'SplashScreen.show(...)' once 'setContentView()' is called.") {
override fun getCode(): String {
return "ERR_NO_CONTENT_VIEW_FOUND"
}
}
| packages/expo-splash-screen/android/src/main/java/expo/modules/splashscreen/exceptions/NoContentViewException.kt | 456790931 |
package com.auth0.android.request
/**
* Holder for the information required to configure a request
*/
public class RequestOptions(public val method: HttpMethod) {
public val parameters: MutableMap<String, Any> = mutableMapOf()
public val headers: MutableMap<String, String> = mutableMapOf()
} | auth0/src/main/java/com/auth0/android/request/RequestOptions.kt | 3843293915 |
/*
* Copyright 2019 Realm 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 io.realm.benchmarks
import androidx.benchmark.junit4.BenchmarkRule
import androidx.benchmark.junit4.measureRepeated
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.realm.Realm
import io.realm.RealmConfiguration
import io.realm.RealmResults
import io.realm.benchmarks.entities.AllTypes
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RealmResultsBenchmarks {
@get:Rule
val benchmarkRule = BenchmarkRule()
private val DATA_SIZE = 1000
private lateinit var realm: Realm
private lateinit var results: RealmResults<AllTypes>
@Before
fun before() {
Realm.init(InstrumentationRegistry.getInstrumentation().targetContext)
val config = RealmConfiguration.Builder().build()
Realm.deleteRealm(config)
realm = Realm.getInstance(config)
realm.beginTransaction()
for (i in 0 until DATA_SIZE) {
val obj = realm.createObject(AllTypes::class.java)
obj.columnLong = i.toLong()
obj.isColumnBoolean = i % 2 == 0
obj.columnString = "Foo $i"
obj.columnDouble = i + 1.234
}
realm.commitTransaction()
results = realm.where(AllTypes::class.java).findAll()
}
@After
fun after() {
realm.close()
}
@Test
fun get() {
benchmarkRule.measureRepeated {
val item = results[0]
}
}
@Test
fun size() {
benchmarkRule.measureRepeated {
val size = results.size.toLong()
}
}
@Test
fun min() {
benchmarkRule.measureRepeated {
val min = results.min(AllTypes.FIELD_LONG)
}
}
@Test
fun max() {
benchmarkRule.measureRepeated {
val max = results.max(AllTypes.FIELD_LONG)
}
}
@Test
fun average() {
benchmarkRule.measureRepeated {
val average = results.average(AllTypes.FIELD_LONG)
}
}
@Test
fun sum() {
benchmarkRule.measureRepeated {
val sum = results.sum(AllTypes.FIELD_LONG)
}
}
@Test
fun sort() {
benchmarkRule.measureRepeated {
val sorted = results.sort(AllTypes.FIELD_STRING)
}
}
}
| library-benchmarks/src/androidTest/java/io/realm/benchmarks/RealmResultsBenchmarks.kt | 3954691432 |
package com.rolandvitezhu.todocloud.ui.activity.main.fragment
import android.content.Context
import android.os.Bundle
import android.view.*
import android.view.ContextMenu.ContextMenuInfo
import android.view.View.OnCreateContextMenuListener
import android.view.View.OnTouchListener
import android.view.ViewTreeObserver.OnScrollChangedListener
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.ExpandableListView
import android.widget.ExpandableListView.*
import androidx.appcompat.view.ActionMode
import androidx.fragment.app.ListFragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import com.google.android.material.snackbar.Snackbar
import com.rolandvitezhu.todocloud.R
import com.rolandvitezhu.todocloud.app.AppController
import com.rolandvitezhu.todocloud.app.AppController.Companion.isActionModeEnabled
import com.rolandvitezhu.todocloud.app.AppController.Companion.showWhiteTextSnackbar
import com.rolandvitezhu.todocloud.data.Category
import com.rolandvitezhu.todocloud.data.PredefinedList
import com.rolandvitezhu.todocloud.database.TodoCloudDatabaseDao
import com.rolandvitezhu.todocloud.databinding.FragmentMainlistBinding
import com.rolandvitezhu.todocloud.repository.CategoryRepository
import com.rolandvitezhu.todocloud.repository.ListRepository
import com.rolandvitezhu.todocloud.repository.TodoRepository
import com.rolandvitezhu.todocloud.ui.activity.main.MainActivity
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.CategoryAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.ListAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.adapter.PredefinedListAdapter
import com.rolandvitezhu.todocloud.ui.activity.main.dialogfragment.*
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.CategoriesViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.ListsViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.PredefinedListsViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.UserViewModel
import com.rolandvitezhu.todocloud.ui.activity.main.viewmodel.viewmodelfactory.ListsViewModelFactory
import kotlinx.android.synthetic.main.fragment_mainlist.*
import kotlinx.android.synthetic.main.fragment_mainlist.view.*
import kotlinx.coroutines.launch
import java.util.*
import javax.inject.Inject
class MainListFragment() : ListFragment(), OnRefreshListener {
private val TAG: String = javaClass.simpleName
@Inject
lateinit var todoCloudDatabaseDao: TodoCloudDatabaseDao
@Inject
lateinit var todoRepository: TodoRepository
@Inject
lateinit var listDataSynchronizer: ListRepository
@Inject
lateinit var categoryRepository: CategoryRepository
@Inject
lateinit var predefinedListAdapter: PredefinedListAdapter
@Inject
lateinit var categoryAdapter: CategoryAdapter
@Inject
lateinit var listAdapter: ListAdapter
private var actionMode: ActionMode? = null
private var actionModeStartedWithELV: Boolean = false
private val selectedCategories: ArrayList<Category> = ArrayList()
private val selectedListsInCategory: ArrayList<com.rolandvitezhu.todocloud.data.List> = ArrayList()
private val selectedLists: ArrayList<com.rolandvitezhu.todocloud.data.List> = ArrayList()
private val categoriesViewModel by lazy {
activity?.let { ViewModelProvider(it).get(CategoriesViewModel::class.java) }
}
private val listsViewModel by lazy {
activity?.let {
ViewModelProvider(it, ListsViewModelFactory(categoriesViewModel)).
get(ListsViewModel::class.java)
}
}
private val predefinedListsViewModel by lazy {
activity?.let { ViewModelProvider(it).get(PredefinedListsViewModel::class.java) }
}
private val userViewModel by lazy {
activity?.let { ViewModelProvider(it).get(UserViewModel::class.java) }
}
private val isNoSelectedItems: Boolean
private get() {
val checkedItemCount: Int = checkedItemCount
return checkedItemCount == 0
}
private val checkedItemCount: Int
private get() {
return selectedCategories.size + selectedListsInCategory.size + selectedLists.size
}
override fun onAttach(context: Context) {
super.onAttach(context)
(requireActivity().application as AppController).appComponent.
fragmentComponent().create().inject(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
categoriesViewModel?.lhmCategories?.observe(
this,
{
lhmCategories ->
categoryAdapter.update(lhmCategories)
categoryAdapter.notifyDataSetChanged()
}
)
listsViewModel?.lists?.observe(
this,
{
lists ->
listAdapter.update(lists)
listAdapter.notifyDataSetChanged()
}
)
predefinedListsViewModel?.predefinedLists?.observe(
this,
{ predefinedLists ->
predefinedListAdapter.update(predefinedLists)
predefinedListAdapter.notifyDataSetChanged()
}
)
userViewModel?.user?.observe(
this,
{
user ->
// We do not need to do anything here. We use the userViewModel to bind the data,
// so it will automatically update on the UI. Use it as an example when implementing
// the same for the other viewmodels.
}
)
([email protected] as MainActivity).onPrepareNavigationHeader()
updateLists()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val fragmentMainListBinding: FragmentMainlistBinding =
FragmentMainlistBinding.inflate(inflater, container, false)
val view: View = fragmentMainListBinding.root
prepareExpandableListView(view)
prepareSwipeRefreshLayout(view)
syncData(view)
fragmentMainListBinding.mainListFragment = this
fragmentMainListBinding.executePendingBindings()
return view
}
private fun prepareSwipeRefreshLayout(view: View) {
setScrollViewSwipeRefreshBehavior(view)
view.swiperefreshlayout_mainlist?.setOnRefreshListener(this)
}
private fun setScrollViewSwipeRefreshBehavior(view: View) {
view.scrollview_mainlist?.viewTreeObserver?.addOnScrollChangedListener(
object : OnScrollChangedListener {
override fun onScrollChanged() {
try {
val scrollY: Int? = view.scrollview_mainlist?.scrollY
if (shouldSwipeRefresh(scrollY))
// We can only start the swipe refresh, when we are on the top of
// the list - which means scroll position y == 0 - and the action
// mode is disabled.
view.swiperefreshlayout_mainlist?.isEnabled = true
} catch (e: NullPointerException) {
// ScrollView nor SwipeRefreshLayout doesn't exists already.
}
}
private fun shouldSwipeRefresh(scrollY: Int?): Boolean {
return scrollY != null && scrollY == 0 && !isActionModeEnabled
}
})
}
private fun prepareExpandableListView(view: View) {
view.expandableheightexpandablelistview_mainlist_category?.setAdapter(categoryAdapter)
view.expandableheightexpandablelistview_mainlist_category?.
setOnChildClickListener(expLVChildClicked)
view.expandableheightexpandablelistview_mainlist_category?.
setOnGroupClickListener(expLVGroupClicked)
applyExpLVLongClickEvents(view)
}
private fun applyExpLVLongClickEvents(view: View) {
view.expandableheightexpandablelistview_mainlist_category?.
setOnCreateContextMenuListener(expLVCategoryContextMenuListener)
}
private val callback: ActionMode.Callback = object : ActionMode.Callback {
override fun onCreateActionMode(mode: ActionMode, menu: Menu): Boolean {
isActionModeEnabled = true
actionMode = mode
fixExpandableListViewBehavior()
return true
}
override fun onPrepareActionMode(mode: ActionMode, menu: Menu): Boolean {
val actionModeTitle: String = prepareActionModeTitle()
actionMode?.title = actionModeTitle
prepareMenu(mode, menu)
return true
}
override fun onActionItemClicked(mode: ActionMode, item: MenuItem): Boolean {
applyActionItemBehavior(item)
return true
}
override fun onDestroyActionMode(mode: ActionMode) {
deselectItems()
selectedCategories.clear()
selectedListsInCategory.clear()
selectedLists.clear()
listAdapter.clearSelection()
isActionModeEnabled = false
view?.expandableheightexpandablelistview_mainlist_category?.choiceMode =
AbsListView.CHOICE_MODE_NONE
view?.expandableheightlistview_mainlist_predefinedlist?.choiceMode =
AbsListView.CHOICE_MODE_NONE
}
/**
* If ActionMode has started with ExpandableListView, it may stop it accidentally. It can cause
* an unwanted click event after started the ActionMode. This method prevent that.
*/
private fun fixExpandableListViewBehavior() {
if (actionModeStartedWithELV) {
preventUnwantedClickEvent()
actionModeStartedWithELV = false
}
}
private fun preventUnwantedClickEvent() {
view?.expandableheightexpandablelistview_mainlist_category?.setOnTouchListener(
object : OnTouchListener {
override fun onTouch(v: View, event: MotionEvent): Boolean {
if (unwantedClickEventPassOut(event)) restoreDefaultBehavior()
return true
}
})
}
private fun unwantedClickEventPassOut(event: MotionEvent): Boolean {
return event.action == MotionEvent.ACTION_UP ||
event.action == MotionEvent.ACTION_CANCEL
}
private fun restoreDefaultBehavior() {
view?.expandableheightexpandablelistview_mainlist_category?.setOnTouchListener(null)
}
private fun prepareActionModeTitle(): String {
return checkedItemCount.toString() + " " + getString(R.string.all_selected)
}
private fun prepareMenu(mode: ActionMode, menu: Menu) {
if (oneCategorySelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_group, menu)
} else if (oneListInCategorySelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_child, menu)
} else if (oneListSelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_item, menu)
} else if (manyCategoriesSelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_many_group, menu)
} else if (manyListsInCategorySelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_many_child, menu)
} else if (manyListsSelected()) {
menu.clear()
mode.menuInflater.inflate(R.menu.layout_appbar_mainlist_many_item, menu)
} else if (manyCategoriesAndListsInCategorySelected()) {
menu.clear()
} else if (manyCategoriesAndListsSelected()) {
menu.clear()
} else if (manyListsInCategoryAndListsSelected()) {
menu.clear()
} else if (manyCategoriesAndListsInCategoryAndListsSelected()) {
menu.clear()
}
}
private fun applyActionItemBehavior(item: MenuItem) {
if (oneCategorySelected()) {
when (item.itemId) {
R.id.menuitem_layoutappbarmainlistgroup_createlist ->
openCreateListInCategoryDialogFragment()
R.id.menuitem_layoutappbarmainlistgroup_modify ->
openModifyCategoryDialogFragment()
R.id.menuitem_layoutappbarmainlistgroup_delete ->
openConfirmDeleteCategoryDialog()
}
} else if (oneListInCategorySelected()) {
when (item.itemId) {
R.id.menuitem_layoutappbarmainlistchild_modify ->
openModifyListInCategoryDialog()
R.id.menuitem_layoutappbarmainlistchild_delete ->
openConfirmDeleteListInCategoryDialog()
R.id.menuitem_layoutappbarmainlistchild_move -> openMoveListInCategoryDialog()
}
} else if (oneListSelected()) {
when (item.itemId) {
R.id.menuitem_layoutappbarmainlistitem_modify -> openModifyListDialog()
R.id.menuitem_layoutappbarmainlistitem_delete -> openConfirmDeleteListDialog()
R.id.menuitem_layoutappbarmainlistitem_move ->
openMoveListIntoAnotherCategoryDialog()
}
} else if (manyCategoriesSelected()) {
if (item.itemId == R.id.menuitem_layoutappbarmainlistmanygroup_delete)
openConfirmDeleteCategoriesDialog()
} else if (manyListsInCategorySelected()) {
if (item.itemId == R.id.menuitem_layoutappbarmainlistmanychild_delete)
openConfirmDeleteListsInCategoryDialog()
} else if (manyListsSelected()) {
if (item.itemId == R.id.menuitem_layoutappbarmainlistmanyitem_delete)
openConfirmDeleteListsDialog()
} else if (manyCategoriesAndListsInCategorySelected()) {
} else if (manyCategoriesAndListsSelected()) {
} else if (manyListsInCategoryAndListsSelected()) {
} else if (manyCategoriesAndListsInCategoryAndListsSelected()) {
}
}
private fun oneCategorySelected(): Boolean {
return (selectedCategories.size == 1) && (selectedListsInCategory.size == 0) && (selectedLists.size == 0)
}
private fun oneListInCategorySelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size == 1) && (selectedLists.size == 0)
}
private fun oneListSelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size == 0) && (selectedLists.size == 1)
}
private fun manyCategoriesSelected(): Boolean {
return (selectedCategories.size > 1) && (selectedListsInCategory.size == 0) && (selectedLists.size == 0)
}
private fun manyListsInCategorySelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size > 1) && (selectedLists.size == 0)
}
private fun manyListsSelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size == 0) && (selectedLists.size > 1)
}
private fun manyCategoriesAndListsInCategorySelected(): Boolean {
return (selectedCategories.size > 0) && (selectedListsInCategory.size > 0) && (selectedLists.size == 0)
}
private fun manyCategoriesAndListsSelected(): Boolean {
return (selectedCategories.size > 0) && (selectedListsInCategory.size == 0) && (selectedLists.size > 0)
}
private fun manyListsInCategoryAndListsSelected(): Boolean {
return (selectedCategories.size == 0) && (selectedListsInCategory.size > 0) && (selectedLists.size > 0)
}
private fun manyCategoriesAndListsInCategoryAndListsSelected(): Boolean {
return (selectedCategories.size > 0) && (selectedListsInCategory.size > 0) && (selectedLists.size > 0)
}
private fun deselectItems() {
deselectListItems()
deselectExpandableListViewVisibleItems()
}
private fun deselectListItems() {
for (i in 0 until listAdapter.count) {
view?.expandableheightlistview_mainlist_list?.setItemChecked(i, false)
}
}
/**
* Should deselect the visible items. Visible items are the group items, and the child
* items of expanded group items.
*/
private fun deselectExpandableListViewVisibleItems() {
if (view?.expandableheightexpandablelistview_mainlist_category != null) {
for (i in 0..view?.expandableheightexpandablelistview_mainlist_category!!.lastVisiblePosition) {
view!!.expandableheightexpandablelistview_mainlist_category!!.setItemChecked(i, false)
categoriesViewModel?.deselectItems()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.fragment_mainlist, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menuitem_mainlist_search ->
([email protected] as MainActivity).onSearchActionItemClick()
}
return super.onOptionsItemSelected(item)
}
private fun openCreateListDialogFragment() {
val createListDialogFragment = CreateListDialogFragment()
createListDialogFragment.setTargetFragment(this, 0)
createListDialogFragment.show(parentFragmentManager, "CreateListDialogFragment")
}
private fun openCreateCategoryDialogFragment() {
val createCategoryDialogFragment = CreateCategoryDialogFragment()
createCategoryDialogFragment.setTargetFragment(this, 0)
createCategoryDialogFragment.show(parentFragmentManager, "CreateCategoryDialogFragment")
}
private fun openCreateListInCategoryDialogFragment() {
categoriesViewModel?.category = selectedCategories.get(0)
val createListInCategoryDialogFragment = CreateListInCategoryDialogFragment()
createListInCategoryDialogFragment.setTargetFragment(this, 0)
createListInCategoryDialogFragment.show(parentFragmentManager, "CreateListInCategoryDialogFragment")
}
private fun openModifyListInCategoryDialog() {
listsViewModel?.list = selectedListsInCategory.get(0)
listsViewModel?.isInCategory = true
openModifyListDialogFragment()
}
private fun openConfirmDeleteListInCategoryDialog() {
val list: com.rolandvitezhu.todocloud.data.List = selectedListsInCategory.get(0)
val onlineId: String? = list.listOnlineId
val title: String? = list.title
val arguments = Bundle()
arguments.putString("itemType", "listInCategory")
arguments.putString("itemTitle", title)
arguments.putString("onlineId", onlineId)
listsViewModel?.isInCategory = true
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteListsInCategoryDialog() {
val arguments = Bundle()
arguments.putString("itemType", "listInCategory")
arguments.putParcelableArrayList("itemsToDelete", selectedListsInCategory)
listsViewModel?.isInCategory = true
openConfirmDeleteDialogFragment(arguments)
}
private fun openMoveListInCategoryDialog() {
lifecycleScope.launch {
val list: com.rolandvitezhu.todocloud.data.List = selectedListsInCategory.get(0)
categoriesViewModel?.category =
list.categoryOnlineId?.let{
todoCloudDatabaseDao.getCategoryByCategoryOnlineId(it)
}?: Category()
listsViewModel?.list = list
}
openMoveListDialogFragment()
}
private fun openMoveListIntoAnotherCategoryDialog() {
categoriesViewModel?.category = Category(getString(R.string.movelist_spinneritemlistnotincategory))
listsViewModel?.list = selectedLists.get(0)
openMoveListDialogFragment()
}
private fun openMoveListDialogFragment() {
val moveListDialogFragment = MoveListDialogFragment()
moveListDialogFragment.setTargetFragment(this, 0)
moveListDialogFragment.show(parentFragmentManager, "MoveListDialogFragment")
}
private fun openConfirmDeleteCategoryDialog() {
val category: Category = selectedCategories.get(0)
val onlineId: String? = category.categoryOnlineId
val title: String? = category.title
val arguments = Bundle()
arguments.putString("itemType", "category")
arguments.putString("itemTitle", title)
arguments.putString("onlineId", onlineId)
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteCategoriesDialog() {
val arguments = Bundle()
arguments.putString("itemType", "category")
arguments.putParcelableArrayList("itemsToDelete", selectedCategories)
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteDialogFragment(arguments: Bundle) {
val confirmDeleteDialogFragment = ConfirmDeleteDialogFragment()
confirmDeleteDialogFragment.setTargetFragment(this, 0)
confirmDeleteDialogFragment.arguments = arguments
confirmDeleteDialogFragment.show(parentFragmentManager, "ConfirmDeleteDialogFragment")
}
private fun openConfirmDeleteListDialog() {
val list: com.rolandvitezhu.todocloud.data.List = selectedLists.get(0)
val onlineId: String? = list.listOnlineId
val title: String? = list.title
val arguments = Bundle()
arguments.putString("itemType", "list")
arguments.putString("itemTitle", title)
arguments.putString("onlineId", onlineId)
listsViewModel?.isInCategory = false
openConfirmDeleteDialogFragment(arguments)
}
private fun openConfirmDeleteListsDialog() {
val arguments = Bundle()
arguments.putString("itemType", "list")
arguments.putParcelableArrayList("itemsToDelete", selectedLists)
listsViewModel?.isInCategory = false
openConfirmDeleteDialogFragment(arguments)
}
private fun openModifyCategoryDialogFragment() {
categoriesViewModel?.category = selectedCategories.get(0)
val modifyCategoryDialogFragment = ModifyCategoryDialogFragment()
modifyCategoryDialogFragment.setTargetFragment(this, 0)
modifyCategoryDialogFragment.show(parentFragmentManager, "ModifyCategoryDialogFragment")
}
private fun openModifyListDialog() {
listsViewModel?.list = selectedLists.get(0)
openModifyListDialogFragment()
}
private fun openModifyListDialogFragment() {
val modifyListDialogFragment = ModifyListDialogFragment()
modifyListDialogFragment.setTargetFragment(this, 0)
modifyListDialogFragment.show(parentFragmentManager, "ModifyListDialogFragment")
}
/**
* Show the circle icon as the synchronization starts and hide it as the synchronization
* finishes. Synchronizes all the entities - categories, lists, todos - between the local and
* remote database. Refreshes the UI to show the up-to-date data. Shows the error messages.
*/
private fun syncData(view: View?) {
lifecycleScope.launch {
try {
if (view != null)
view.swiperefreshlayout_mainlist?.isRefreshing = true
else
[email protected]_mainlist?.isRefreshing = true
categoriesViewModel?.onSynchronization()
listsViewModel?.onSynchronization()
categoriesViewModel?.updateCategoriesViewModel()
todoRepository.syncTodoData()
} catch (cause: Throwable) {
showErrorMessage(cause.message)
categoriesViewModel?.updateCategoriesViewModel()
listsViewModel?.updateListsViewModel()
} finally {
if (view != null)
view.swiperefreshlayout_mainlist?.isRefreshing = false
else
[email protected]_mainlist?.isRefreshing = false
}
}
}
/**
* Update all of the lists: predefined lists, lists, categories.
*/
private fun updateLists() {
lifecycleScope.launch {
predefinedListsViewModel?.updatePredefinedListsViewModel()
categoriesViewModel?.updateCategoriesViewModel()
listsViewModel?.updateListsViewModel()
}
}
val predefinedListItemClicked: OnItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
if (!isActionModeEnabled) {
val predefinedList: PredefinedList = parent.adapter.getItem(
position) as PredefinedList
([email protected] as MainActivity).onClickPredefinedList(predefinedList)
}
}
}
val listItemClicked: OnItemClickListener = object : OnItemClickListener {
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
val clickedList: com.rolandvitezhu.todocloud.data.List =
listAdapter.getItem(position) as com.rolandvitezhu.todocloud.data.List
if (!isActionModeEnabled) {
([email protected] as MainActivity).onClickList(clickedList)
} else {
handleItemSelection(position, clickedList)
}
}
private fun handleItemSelection(position: Int, clickedList: com.rolandvitezhu.todocloud.data.List) {
// Item checked state being set automatically on item click event. We should track
// the changes only.
if (view?.expandableheightlistview_mainlist_list?.isItemChecked(position) == true) {
selectedLists.add(clickedList)
listAdapter.toggleSelection(position)
} else {
selectedLists.remove(clickedList)
listAdapter.toggleSelection(position)
}
if (isNoSelectedItems) {
actionMode?.finish()
listAdapter.clearSelection()
} else {
actionMode?.invalidate()
}
}
}
val listItemLongClicked: OnItemLongClickListener = object : OnItemLongClickListener {
override fun onItemLongClick(parent: AdapterView<*>?, view: View, position: Int, id: Long):
Boolean {
if (!isActionModeEnabled) {
startActionMode(position)
listAdapter.toggleSelection(position)
}
return true
}
private fun startActionMode(position: Int) {
([email protected] as MainActivity).onStartActionMode(callback)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
view?.expandableheightlistview_mainlist_list?.setItemChecked(position, true)
val selectedList: com.rolandvitezhu.todocloud.data.List =
view?.expandableheightlistview_mainlist_list?.getItemAtPosition(position) as
com.rolandvitezhu.todocloud.data.List
selectedLists.add(selectedList)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
actionMode?.invalidate()
}
}
private val expLVChildClicked: OnChildClickListener = object : OnChildClickListener {
override fun onChildClick(parent: ExpandableListView, v: View, groupPosition: Int,
childPosition: Int, id: Long): Boolean {
val clickedList: com.rolandvitezhu.todocloud.data.List = categoryAdapter.getChild(
groupPosition,
childPosition
) as com.rolandvitezhu.todocloud.data.List
if (!isActionModeEnabled) {
([email protected] as MainActivity).onClickList(clickedList)
} else {
handleItemSelection(clickedList)
}
return true
}
private fun handleItemSelection(clickedList: com.rolandvitezhu.todocloud.data.List) {
categoriesViewModel?.toggleListSelected(clickedList)
if (clickedList.isSelected) {
selectedListsInCategory.add(clickedList)
} else {
selectedListsInCategory.remove(clickedList)
}
if (isNoSelectedItems) {
actionMode?.finish()
} else {
actionMode?.invalidate()
}
}
}
private val expLVGroupClicked: OnGroupClickListener = object : OnGroupClickListener {
override fun onGroupClick(parent: ExpandableListView, v: View, groupPosition: Int, id: Long): Boolean {
val packedPosition: Long = getPackedPositionForGroup(groupPosition)
val position: Int = parent.getFlatListPosition(packedPosition)
if (!isActionModeEnabled) {
handleGroupExpanding(parent, groupPosition)
} else {
handleItemSelection(parent, position)
}
return true
}
private fun handleItemSelection(
parent: ExpandableListView,
position: Int
) {
val clickedCategory: Category = parent.getItemAtPosition(position) as Category
categoriesViewModel?.toggleCategorySelected(clickedCategory)
if (clickedCategory.isSelected) {
selectedCategories.add(clickedCategory)
} else {
selectedCategories.remove(clickedCategory)
}
if (isNoSelectedItems) {
actionMode?.finish()
} else {
actionMode?.invalidate()
}
}
private fun handleGroupExpanding(parent: ExpandableListView, groupPosition: Int) {
if (!parent.isGroupExpanded(groupPosition)) {
parent.expandGroup(groupPosition)
} else {
parent.collapseGroup(groupPosition)
}
}
}
private val expLVCategoryContextMenuListener: OnCreateContextMenuListener =
object : OnCreateContextMenuListener {
override fun onCreateContextMenu(menu: ContextMenu, v: View,
menuInfo: ContextMenuInfo) {
if (!isActionModeEnabled &&
view?.expandableheightexpandablelistview_mainlist_category != null) {
val info: ExpandableListContextMenuInfo = menuInfo as ExpandableListContextMenuInfo
val packedPosition: Long = info.packedPosition
val position: Int = view?.expandableheightexpandablelistview_mainlist_category!!.
getFlatListPosition(packedPosition)
val packedPositionType: Int = getPackedPositionType(packedPosition)
if (categoryClicked(packedPositionType)) {
startActionModeWithCategory(position)
} else if (listClicked(packedPositionType)) {
startActionModeWithList(position)
}
}
}
private fun startActionModeWithList(position: Int) {
if (view?.expandableheightexpandablelistview_mainlist_category != null) {
actionModeStartedWithELV = true
([email protected] as MainActivity).onStartActionMode(callback)
val clickedList: com.rolandvitezhu.todocloud.data.List =
view?.expandableheightexpandablelistview_mainlist_category?.
getItemAtPosition(position) as com.rolandvitezhu.todocloud.data.List
categoriesViewModel?.toggleListSelected(clickedList)
selectedListsInCategory.add(clickedList)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
actionMode?.invalidate()
}
}
private fun startActionModeWithCategory(position: Int) {
if (view?.expandableheightexpandablelistview_mainlist_category != null) {
actionModeStartedWithELV = true
([email protected] as MainActivity).onStartActionMode(callback)
val clickedCategory: Category =
view?.expandableheightexpandablelistview_mainlist_category!!.
getItemAtPosition(position) as Category
categoriesViewModel?.toggleCategorySelected(clickedCategory)
selectedCategories.add(clickedCategory)
view?.expandableheightlistview_mainlist_list?.choiceMode =
AbsListView.CHOICE_MODE_MULTIPLE
actionMode?.invalidate()
}
}
private fun listClicked(packedPositionType: Int): Boolean {
return packedPositionType == PACKED_POSITION_TYPE_CHILD
}
private fun categoryClicked(packedPositionType: Int): Boolean {
return packedPositionType == PACKED_POSITION_TYPE_GROUP
}
}
/**
* Finish the action mode if the screen is in it.
*/
fun finishActionMode() {
actionMode?.finish()
}
override fun onRefresh() {
syncData(null)
}
private fun showErrorMessage(errorMessage: String?) {
if (errorMessage != null) {
val upperCaseErrorMessage = errorMessage.toUpperCase()
if (upperCaseErrorMessage.contains("FAILED TO CONNECT") ||
upperCaseErrorMessage.contains("UNABLE TO RESOLVE HOST") ||
upperCaseErrorMessage.contains("TIMEOUT")) {
showFailedToConnectError()
} else {
showAnErrorOccurredError()
}
}
}
private fun showFailedToConnectError() {
// Android Studio hotswap/coldswap may cause getView == null
try {
val snackbar: Snackbar = Snackbar.make(
view?.constraintlayout_mainlist!!,
R.string.all_failedtoconnect,
Snackbar.LENGTH_LONG
)
showWhiteTextSnackbar(snackbar)
} catch (e: NullPointerException) {
// Snackbar or constraintLayout doesn't exists already.
}
}
private fun showAnErrorOccurredError() {
try {
val snackbar: Snackbar = Snackbar.make(
view?.constraintlayout_mainlist!!,
R.string.all_anerroroccurred,
Snackbar.LENGTH_LONG
)
showWhiteTextSnackbar(snackbar)
} catch (e: NullPointerException) {
// Snackbar or constraintLayout doesn't exists already.
}
}
fun onFABCreateCategoryClick() {
openCreateCategoryDialogFragment()
this.main_fam.close(true)
}
fun onFABCreateListClick() {
openCreateListDialogFragment()
this.main_fam.close(true)
}
}
| app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/fragment/MainListFragment.kt | 2374005616 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.execution.ui
import com.intellij.execution.*
import com.intellij.execution.configurations.RunProfile
import com.intellij.execution.executors.DefaultRunExecutor
import com.intellij.execution.executors.ExecutorGroup
import com.intellij.execution.impl.*
import com.intellij.execution.impl.ExecutionManagerImpl.Companion.isProcessRunning
import com.intellij.execution.process.ProcessHandler
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ExecutionUtil
import com.intellij.icons.AllIcons
import com.intellij.ide.ActivityTracker
import com.intellij.ide.DataManager
import com.intellij.ide.ui.customization.CustomActionsSchema
import com.intellij.ide.ui.customization.CustomizableActionGroupProvider
import com.intellij.ide.ui.customization.CustomizationUtil
import com.intellij.ide.ui.customization.CustomizeActionGroupPanel
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.CustomComponentAction
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.State
import com.intellij.openapi.components.Storage
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.ToolWindowId
import com.intellij.openapi.wm.impl.headertoolbar.MainToolbarProjectWidgetFactory
import com.intellij.openapi.wm.impl.headertoolbar.MainToolbarWidgetFactory
import com.intellij.ui.*
import com.intellij.ui.components.JBPanel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.popup.PopupState
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.xmlb.annotations.*
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.ActionEvent
import java.awt.event.MouseEvent
import java.awt.geom.Area
import java.awt.geom.Line2D
import java.awt.geom.Rectangle2D
import java.awt.geom.RoundRectangle2D
import java.util.concurrent.locks.ReentrantLock
import java.util.function.Predicate
import java.util.function.Supplier
import javax.swing.*
import javax.swing.plaf.ButtonUI
import javax.swing.plaf.basic.BasicButtonListener
import javax.swing.plaf.basic.BasicButtonUI
import javax.swing.plaf.basic.BasicGraphicsUtils
import kotlin.concurrent.withLock
import kotlin.properties.Delegates
private const val RUN_TOOLBAR_WIDGET_GROUP = "RunToolbarWidgetCustomizableActionGroup"
internal class RunToolbarWidgetFactory : MainToolbarProjectWidgetFactory {
override fun createWidget(project: Project): JComponent = RunToolbarWidget(project)
override fun getPosition() = MainToolbarWidgetFactory.Position.Right
}
internal class RunToolbarWidgetCustomizableActionGroupProvider : CustomizableActionGroupProvider() {
override fun registerGroups(registrar: CustomizableActionGroupRegistrar?) {
if (ExperimentalUI.isNewUI()) {
registrar?.addCustomizableActionGroup(RUN_TOOLBAR_WIDGET_GROUP, ExecutionBundle.message("run.toolbar.widget.customizable.group.name"))
}
}
}
internal class RunToolbarWidget(val project: Project) : JBPanel<RunToolbarWidget>(VerticalLayout(0)) {
init {
isOpaque = false
add(createRunActionToolbar().component.apply {
isOpaque = false
}, VerticalLayout.CENTER)
}
private fun createRunActionToolbar(): ActionToolbar {
val actionGroup = CustomActionsSchema.getInstance().getCorrectedAction(RUN_TOOLBAR_WIDGET_GROUP) as ActionGroup
return ActionManager.getInstance().createActionToolbar(
ActionPlaces.MAIN_TOOLBAR,
actionGroup,
true
).apply {
targetComponent = null
setReservePlaceAutoPopupIcon(false)
layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY
}
}
}
internal class RunWithDropDownAction : AnAction(AllIcons.Actions.Execute), CustomComponentAction, DumbAware {
private val spinningIcon = SpinningProgressIcon()
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
if (!e.presentation.isEnabled) return
val conf = e.presentation.getClientProperty(CONF)
if (conf != null) {
val executor = getExecutorByIdOrDefault(e.presentation.getClientProperty(EXECUTOR_ID)!!)
RunToolbarWidgetRunAction(executor, false) { conf }.actionPerformed(e)
}
else {
ActionManager.getInstance().getAction("editRunConfigurations").actionPerformed(e)
}
}
override fun update(e: AnActionEvent) {
val project = e.project
if (project == null) {
e.presentation.icon = iconFor(LOADING)
e.presentation.text = ExecutionBundle.message("run.toolbar.widget.loading.text")
e.presentation.isEnabled = false
return
}
val conf: RunnerAndConfigurationSettings? = RunManager.getInstance(project).selectedConfiguration
val history = RunConfigurationStartHistory.getInstance(project)
val run = history.firstOrNull(conf) { it.state.isRunningState() } ?: history.firstOrNull(conf)
val isLoading = run?.state?.isBusyState() == true
val lastExecutorId = run?.executorId ?: DefaultRunExecutor.EXECUTOR_ID
e.presentation.putClientProperty(CONF, conf)
e.presentation.putClientProperty(EXECUTOR_ID, lastExecutorId)
if (conf != null) {
val isRunning = run?.state == RunState.STARTED || run?.state == RunState.TERMINATING
val canRestart = isRunning && !conf.configuration.isAllowRunningInParallel
e.presentation.putClientProperty(COLOR, if (isRunning) RunButtonColors.GREEN else RunButtonColors.BLUE)
e.presentation.icon = iconFor(when {
isLoading -> LOADING
canRestart -> RESTART
else -> lastExecutorId
})
e.presentation.text = conf.shortenName()
e.presentation.description = RunToolbarWidgetRunAction.reword(getExecutorByIdOrDefault(lastExecutorId), canRestart, conf.shortenName())
} else {
e.presentation.putClientProperty(COLOR, RunButtonColors.BLUE)
e.presentation.icon = iconFor(RUN)
e.presentation.text = ExecutionBundle.message("run.toolbar.widget.run.text")
e.presentation.description = ExecutionBundle.message("run.toolbar.widget.run.description")
}
e.presentation.isEnabled = !isLoading
}
private fun getExecutorByIdOrDefault(executorId: String): Executor {
return ExecutorRegistryImpl.getInstance().getExecutorById(executorId)
?: ExecutorRegistryImpl.getInstance().getExecutorById(DefaultRunExecutor.EXECUTOR_ID)
?: error("Run executor is not found")
}
private fun iconFor(executorId: String): Icon {
return when (executorId) {
RUN -> IconManager.getInstance().getIcon("expui/run/widget/run.svg", AllIcons::class.java)
DEBUG -> IconManager.getInstance().getIcon("expui/run/widget/debug.svg", AllIcons::class.java)
"Coverage" -> AllIcons.General.RunWithCoverage
LOADING -> spinningIcon
RESTART -> IconManager.getInstance().getIcon("expui/run/widget/restart.svg", AllIcons::class.java)
else -> IconManager.getInstance().getIcon("expui/run/widget/run.svg", AllIcons::class.java)
}
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
return RunDropDownButton(presentation.text, presentation.icon).apply {
addActionListener {
val anActionEvent = AnActionEvent.createFromDataContext(place, presentation, DataManager.getInstance().getDataContext(this))
if (it.modifiers and ActionEvent.SHIFT_MASK != 0) {
ActionManager.getInstance().getAction("editRunConfigurations").actionPerformed(anActionEvent)
}
else if (it.modifiers and ActionEvent.ALT_MASK != 0) {
CustomizeActionGroupPanel.showDialog(RUN_TOOLBAR_WIDGET_GROUP, listOf(IdeActions.GROUP_NAVBAR_TOOLBAR), ExecutionBundle.message("run.toolbar.widget.customizable.group.dialog.title"))
?.let { result ->
CustomizationUtil.updateActionGroup(result, RUN_TOOLBAR_WIDGET_GROUP)
CustomActionsSchema.setCustomizationSchemaForCurrentProjects()
}
}
else {
actionPerformed(anActionEvent)
}
}
}.let { Wrapper(it).apply { border = JBUI.Borders.emptyLeft(6) } }
}
override fun updateCustomComponent(wrapper: JComponent, presentation: Presentation) {
val component = (wrapper as Wrapper).targetComponent as RunDropDownButton
component.text = presentation.text?.let(::shorten)
component.icon = presentation.icon.also { currentIcon ->
if (spinningIcon === currentIcon) {
spinningIcon.setIconColor(component.foreground)
}
}
presentation.getClientProperty(COLOR)?.updateColors(component)
if (presentation.getClientProperty(CONF) == null) {
component.dropDownPopup = null
} else {
component.dropDownPopup = { context -> createPopup(context, context.getData(PlatformDataKeys.PROJECT)!!) }
}
component.toolTipText = presentation.description
component.invalidate()
}
private fun createPopup(context: DataContext, project: Project): JBPopup {
val actions = DefaultActionGroup()
val registry = ExecutorRegistry.getInstance()
val runExecutor = registry.getExecutorById(RUN) ?: error("No '$RUN' executor found")
val debugExecutor = registry.getExecutorById(DEBUG) ?: error("No '$DEBUG' executor found")
val profilerExecutor: ExecutorGroup<*>? = registry.getExecutorById(PROFILER) as? ExecutorGroup<*>
actions.add(RunToolbarWidgetRunAction(runExecutor) { RunManager.getInstance(it).selectedConfiguration })
actions.add(RunToolbarWidgetRunAction(debugExecutor) { RunManager.getInstance(it).selectedConfiguration })
if (profilerExecutor != null) {
actions.add(profilerExecutor.createExecutorActionGroup { RunManager.getInstance(it).selectedConfiguration })
}
actions.add(Separator.create(ExecutionBundle.message("run.toolbar.widget.dropdown.recent.separator.text")))
RunConfigurationStartHistory.getInstance(project).history().mapTo(mutableSetOf()) { it.configuration }.forEach { conf ->
actions.add(DefaultActionGroup(conf.shortenName(), true).apply {
templatePresentation.icon = conf.configuration.icon
if (conf.isRunning(project)) {
templatePresentation.icon = ExecutionUtil.getLiveIndicator(templatePresentation.icon)
}
add(RunToolbarWidgetRunAction(runExecutor) { conf })
add(RunToolbarWidgetRunAction(debugExecutor) { conf })
if (profilerExecutor != null) {
add(profilerExecutor.createExecutorActionGroup { conf })
}
add(Separator.create())
add(DumbAwareAction.create(ExecutionBundle.message("run.toolbar.widget.dropdown.edit.text")) {
it.project?.let { project ->
EditConfigurationsDialog(project, object: ProjectRunConfigurationConfigurable(project) {
override fun getSelectedConfiguration() = conf
}).show()
}
})
add(DumbAwareAction.create(ExecutionBundle.message("run.toolbar.widget.dropdown.delete.text")) {
val prj = it.project ?: return@create
if (Messages.showYesNoDialog(prj, ExecutionBundle.message("run.toolbar.widget.delete.dialog.message", conf.shortenName()), ExecutionBundle.message("run.toolbar.widget.delete.dialog.title"), null) == Messages.YES) {
val runManager = RunManagerImpl.getInstanceImpl(prj)
runManager.removeConfiguration(conf)
}
})
})
}
actions.add(Separator.create())
actions.add(DelegateAction({ ExecutionBundle.message("run.toolbar.widget.all.configurations") }, ActionManager.getInstance().getAction("ChooseRunConfiguration")))
actions.add(ActionManager.getInstance().getAction("editRunConfigurations"))
return JBPopupFactory.getInstance().createActionGroupPopup(
null,
actions,
context,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
true,
ActionPlaces.getPopupPlace(ActionPlaces.MAIN_TOOLBAR)
).apply { setShowSubmenuOnHover(true) }
}
private fun ExecutorGroup<*>.createExecutorActionGroup(conf: (Project) -> RunnerAndConfigurationSettings?) = DefaultActionGroup().apply {
templatePresentation.text = actionName
isPopup = true
childExecutors().forEach { executor ->
add(RunToolbarWidgetRunAction(executor, hideIfDisable = true, conf))
}
}
private class DelegateAction(val string: Supplier<@Nls String>, val delegate: AnAction) : AnAction() {
override fun isDumbAware() = delegate.isDumbAware
init {
shortcutSet = delegate.shortcutSet
}
override fun update(e: AnActionEvent) {
delegate.update(e)
e.presentation.text = string.get()
}
override fun beforeActionPerformedUpdate(e: AnActionEvent) {
delegate.beforeActionPerformedUpdate(e)
}
override fun actionPerformed(e: AnActionEvent) {
delegate.actionPerformed(e)
}
}
companion object {
private val CONF: Key<RunnerAndConfigurationSettings> = Key.create("RUNNER_AND_CONFIGURATION_SETTINGS")
private val COLOR: Key<RunButtonColors> = Key.create("RUN_BUTTON_COLOR")
private val EXECUTOR_ID: Key<String> = Key.create("RUN_WIDGET_EXECUTOR_ID")
const val RUN: String = DefaultRunExecutor.EXECUTOR_ID
const val DEBUG: String = ToolWindowId.DEBUG
const val PROFILER: String = "Profiler"
const val LOADING: String = "Loading"
const val RESTART: String = "Restart"
}
}
class StopWithDropDownAction : AnAction(), CustomComponentAction, DumbAware {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun actionPerformed(e: AnActionEvent) {
ExecutionManagerImpl.getInstance(e.project ?: return)
.getRunningDescriptors { true }
.forEach { descr ->
ExecutionManagerImpl.stopProcess(descr)
}
}
override fun update(e: AnActionEvent) {
val manger = ExecutionManagerImpl.getInstance(e.project ?: return)
val running = manger.getRunningDescriptors { true }
val activeProcesses = running.size
e.presentation.putClientProperty(ACTIVE_PROCESSES, activeProcesses)
e.presentation.isEnabled = activeProcesses > 0
// presentations should be visible because it has to take some fixed space
//e.presentation.isVisible = activeProcesses > 0
e.presentation.icon = IconLoader.getIcon("expui/run/widget/stop.svg", AllIcons::class.java.classLoader)
if (activeProcesses == 1) {
val first = running.first()
getConfigurations(manger, first)
?.shortenName()
?.let {
e.presentation.putClientProperty(SINGLE_RUNNING_NAME, it)
}
}
}
override fun createCustomComponent(presentation: Presentation, place: String): JComponent {
return RunDropDownButton(icon = AllIcons.Actions.Suspend).apply {
addActionListener {
actionPerformed(AnActionEvent.createFromDataContext(place, presentation, DataManager.getInstance().getDataContext(this)))
}
isPaintEnable = false
isCombined = true
}.let { Wrapper(it).apply { border = JBUI.Borders.emptyLeft(6) } }
}
override fun updateCustomComponent(component: JComponent, presentation: Presentation) {
val processes = presentation.getClientProperty(ACTIVE_PROCESSES) ?: 0
val wrapper = component as Wrapper
val button = wrapper.targetComponent as RunDropDownButton
RunButtonColors.RED.updateColors(button)
button.isPaintEnable = processes > 0
button.isEnabled = presentation.isEnabled
button.dropDownPopup = if (processes == 1) null else { context -> createPopup(context, context.getData(PlatformDataKeys.PROJECT)!!) }
button.toolTipText = when {
processes == 1 -> ExecutionBundle.message("run.toolbar.widget.stop.description", presentation.getClientProperty(SINGLE_RUNNING_NAME))
processes > 1 -> ExecutionBundle.message("run.toolbar.widget.stop.multiple.description")
else -> null
}
button.icon = presentation.icon
}
private fun createPopup(context: DataContext, project: Project): JBPopup {
val group = DefaultActionGroup()
val manager = ExecutionManagerImpl.getInstance(project)
val running = manager.getRunningDescriptors { true }.asReversed()
running.forEach { descr ->
val name = getConfigurations(manager, descr)?.shortenName() ?: descr.displayName
group.add(DumbAwareAction.create(name) {
ExecutionManagerImpl.stopProcess(descr)
})
}
group.addSeparator()
group.add(DumbAwareAction.create(ExecutionBundle.message("stop.all", KeymapUtil.getFirstKeyboardShortcutText("Stop"))) {
actionPerformed(it)
})
return JBPopupFactory.getInstance().createActionGroupPopup(
null,
group,
context,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
true,
ActionPlaces.getPopupPlace(ActionPlaces.MAIN_TOOLBAR)
)
}
companion object {
private val ACTIVE_PROCESSES: Key<Int> = Key.create("ACTIVE_PROCESSES")
private val SINGLE_RUNNING_NAME: Key<String> = Key.create("SINGLE_RUNNING_NAME")
}
}
private class RunToolbarWidgetRunAction(
executor: Executor,
val hideIfDisable: Boolean = false,
val settingSupplier: (Project) -> RunnerAndConfigurationSettings?,
) : ExecutorRegistryImpl.ExecutorAction(executor) {
override fun update(e: AnActionEvent) {
super.update(e)
val project = e.project ?: return
val configuration = getSelectedConfiguration(e) ?: return
val isRunning = configuration.isRunning(project, myExecutor.id)
if (isRunning && !configuration.configuration.isAllowRunningInParallel) {
e.presentation.icon = AllIcons.Actions.Restart
e.presentation.text = reword(myExecutor, true, configuration.shortenName())
}
else {
e.presentation.icon = myExecutor.icon
e.presentation.text = reword(myExecutor,false, configuration.shortenName())
}
if (hideIfDisable) {
e.presentation.isVisible = e.presentation.isEnabled
}
}
override fun getSelectedConfiguration(e: AnActionEvent): RunnerAndConfigurationSettings? {
return settingSupplier(e.project ?: return null)
}
companion object {
@Nls
fun reword(executor: Executor, restart: Boolean, configuration: String): String {
return when {
!restart -> ExecutionBundle.message("run.toolbar.widget.run.tooltip.text", executor.actionName, configuration)
executor.id == RunWithDropDownAction.RUN -> ExecutionBundle.message("run.toolbar.widget.rerun.text", configuration)
else -> ExecutionBundle.message("run.toolbar.widget.restart.text", executor.actionName, configuration)
}
}
}
}
private enum class RunButtonColors {
BLUE {
override fun updateColors(button: RunDropDownButton) {
button.foreground = getColor("RunWidget.foreground") { Color.WHITE }
button.separatorColor = getColor("RunWidget.separatorColor") { ColorUtil.withAlpha(Color.WHITE, 0.3) }
button.background = getColor("RunWidget.background") { ColorUtil.fromHex("#3574F0") }
button.hoverBackground = getColor("RunWidget.leftHoverBackground") { ColorUtil.fromHex("#3369D6") }
button.pressedBackground = getColor("RunWidget.leftPressedBackground") { ColorUtil.fromHex("#315FBD") }
}
},
GREEN {
override fun updateColors(button: RunDropDownButton) {
button.foreground = getColor("RunWidget.Running.foreground") { Color.WHITE }
button.separatorColor = getColor("RunWidget.Running.separatorColor") { ColorUtil.withAlpha(Color.WHITE, 0.3) }
button.background = getColor("RunWidget.Running.background") { ColorUtil.fromHex("#599E5E") }
button.hoverBackground = getColor("RunWidget.Running.leftHoverBackground") { ColorUtil.fromHex("#4F8453") }
button.pressedBackground = getColor("RunWidget.Running.leftPressedBackground") { ColorUtil.fromHex("#456B47") }
}
},
RED {
override fun updateColors(button: RunDropDownButton) {
button.foreground = getColor("RunWidget.StopButton.foreground") { Color.WHITE }
button.background = getColor("RunWidget.StopButton.background") { ColorUtil.fromHex("#EB7171") }
button.hoverBackground = getColor("RunWidget.StopButton.leftHoverBackground") { ColorUtil.fromHex("#E35252") }
button.pressedBackground = getColor("RunWidget.StopButton.leftPressedBackground") { ColorUtil.fromHex("#C94F4F") }
}
};
abstract fun updateColors(button: RunDropDownButton)
companion object {
private fun getColor(propertyName: String, defaultColor: () -> Color): JBColor {
return JBColor.lazy {
UIManager.getColor(propertyName) ?: let {
defaultColor().also {
UIManager.put(propertyName, it)
}
}
}
}
}
}
private open class RunDropDownButton(
@Nls text: String? = null,
icon: Icon? = null
) : JButton(text, icon) {
var dropDownPopup: ((DataContext) -> JBPopup)? by Delegates.observable(null) { prop, oldValue, newValue ->
firePropertyChange(prop.name, oldValue, newValue)
if (oldValue != newValue) {
revalidate()
repaint()
}
}
var separatorColor: Color? = null
var hoverBackground: Color? = null
var pressedBackground: Color? = null
var roundSize: Int = 8
/**
* When false the button isn't painted but still takes space in the UI.
*/
var isPaintEnable by Delegates.observable(true) { prop, oldValue, newValue ->
firePropertyChange(prop.name, oldValue, newValue)
if (oldValue != newValue) {
repaint()
}
}
/**
* When true there's no left/right parts.
*
* If [dropDownPopup] is set then it is shown instead of firing [actionListener].
*/
var isCombined by Delegates.observable(false) { prop, oldValue, newValue ->
firePropertyChange(prop.name, oldValue, newValue)
if (oldValue != newValue) {
revalidate()
repaint()
}
}
override fun setUI(ui: ButtonUI?) {
super.setUI(RunDropDownButtonUI())
}
}
private class RunDropDownButtonUI : BasicButtonUI() {
private var point: Point? = null
private val viewRect = Rectangle()
private val textRect = Rectangle()
private val iconRect = Rectangle()
override fun installDefaults(b: AbstractButton?) {
super.installDefaults(b)
b as RunDropDownButton
b.border = JBUI.Borders.empty(0, 7)
b.isOpaque = false
b.foreground = Color.WHITE
b.background = ColorUtil.fromHex("#3574F0")
b.hoverBackground = ColorUtil.fromHex("#3369D6")
b.pressedBackground = ColorUtil.fromHex("#315FBD")
b.horizontalAlignment = SwingConstants.LEFT
}
override fun createButtonListener(b: AbstractButton?): BasicButtonListener {
return MyHoverListener(b as RunDropDownButton)
}
override fun getPreferredSize(c: JComponent?): Dimension? {
c as RunDropDownButton
val prefSize = BasicGraphicsUtils.getPreferredButtonSize(c, c.iconTextGap)
return prefSize?.apply {
width = maxOf(width, if (c.isCombined) 0 else 72)
height = 26
/**
* If combined view is enabled the button should not draw a separate line
* and reserve a place if dropdown is not enabled. Therefore, add only a half
* of arrow icon width (the same as height, 'cause it's square).
*/
if (c.isCombined) {
width += height / 2
}
/**
* If it is not a combined view then check if dropdown required and add its width (= height).
*/
else if (c.dropDownPopup != null) {
width += height
}
}
}
override fun paint(g: Graphics, c: JComponent) {
val b = c as RunDropDownButton
if (!b.isPaintEnable) return
val bounds = g.clipBounds
val popupWidth = if (b.dropDownPopup != null) bounds.height else 0
val g2d = g.create(bounds.x, bounds.y, bounds.width, bounds.height) as Graphics2D
val text = layout(b, b.getFontMetrics(g2d.font), b.width - popupWidth, b.height)
try {
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)
g2d.color = c.background
val buttonRectangle: Shape = RoundRectangle2D.Double(
bounds.x.toDouble(),
bounds.y.toDouble(),
bounds.width.toDouble() - if (b.isCombined && b.dropDownPopup == null) bounds.height / 2 else 0,
bounds.height.toDouble(),
JBUIScale.scale(c.roundSize).toDouble(),
JBUIScale.scale(c.roundSize).toDouble()
)
g2d.fill(buttonRectangle)
val popupBounds = Rectangle(viewRect.x + viewRect.width + c.insets.right, bounds.y, bounds.height, bounds.height)
point?.let { p ->
g2d.color = if (b.model.isArmed && b.model.isPressed) c.pressedBackground else c.hoverBackground
val highlighted = Area(buttonRectangle)
if (!b.isCombined) {
if (popupBounds.contains(p)) {
highlighted.subtract(Area(Rectangle2D.Double(
bounds.x.toDouble(),
bounds.y.toDouble(),
bounds.width.toDouble() - popupBounds.width,
bounds.height.toDouble()
)))
}
else {
highlighted.subtract(Area(Rectangle2D.Double(
popupBounds.x.toDouble(),
popupBounds.y.toDouble(),
popupBounds.width.toDouble(),
popupBounds.height.toDouble()
)))
}
}
g2d.fill(highlighted)
}
if (popupWidth > 0) {
g2d.color = b.separatorColor
if (!b.isCombined) {
val gap = popupBounds.height / 5
g2d.drawLine(popupBounds.x, popupBounds.y + gap, popupBounds.x, popupBounds.y + popupBounds.height - gap)
}
g2d.color = b.foreground
paintArrow(c, g2d, popupBounds)
}
paintIcon(g2d, c, iconRect)
paintText(g2d, c, textRect, text)
}
finally {
g2d.dispose()
}
}
private fun paintArrow(c: Component, g: Graphics2D, r: Rectangle) {
JBInsets.removeFrom(r, JBUI.insets(1, 0, 1, 1))
val tW = JBUIScale.scale(8f)
val tH = JBUIScale.scale(tW / 2)
val xU = (r.getWidth() - tW) / 2 + r.x
val yU = (r.getHeight() - tH) / 2 + r.y
val leftLine = Line2D.Double(xU, yU, xU + tW / 2f, yU + tH)
val rightLine = Line2D.Double(xU + tW / 2f, yU + tH, xU + tW, yU)
g.color = c.foreground
g.stroke = BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER)
g.draw(leftLine)
g.draw(rightLine)
}
private fun layout(b: AbstractButton, fm: FontMetrics, width: Int, height: Int): String? {
val i = b.insets
viewRect.x = i.left
viewRect.y = i.top
viewRect.width = width - (i.right + viewRect.x)
viewRect.height = height - (i.bottom + viewRect.y)
textRect.height = 0
textRect.width = textRect.height
textRect.y = textRect.width
textRect.x = textRect.y
iconRect.height = 0
iconRect.width = iconRect.height
iconRect.y = iconRect.width
iconRect.x = iconRect.y
// layout the text and icon
return SwingUtilities.layoutCompoundLabel(
b, fm, b.text, b.icon,
b.verticalAlignment, b.horizontalAlignment,
b.verticalTextPosition, b.horizontalTextPosition,
viewRect, iconRect, textRect,
if (b.text == null) 0 else b.iconTextGap)
}
private inner class MyHoverListener(val button: RunDropDownButton) : BasicButtonListener(button) {
private val popupState = PopupState.forPopup()
override fun mouseEntered(e: MouseEvent) {
if (popupState.isShowing) return
super.mouseEntered(e)
point = e.point
e.component.repaint()
}
override fun mouseExited(e: MouseEvent) {
if (popupState.isShowing) return
super.mouseExited(e)
point = null
e.component.repaint()
}
override fun mouseMoved(e: MouseEvent) {
if (popupState.isShowing) return
super.mouseMoved(e)
point = e.point
e.component.repaint()
}
override fun mousePressed(e: MouseEvent) {
if (popupState.isShowing || popupState.isRecentlyHidden) return
val b = e.source as? RunDropDownButton
if (b?.dropDownPopup != null && b.isEnabled) {
if (b.isCombined || b.width - b.height < e.x) {
b.dropDownPopup?.invoke(DataManager.getInstance().getDataContext(e.component))
?.also {
popupState.prepareToShow(it)
it.addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
point = null
button.repaint()
}
})
}
?.showUnderneathOf(e.component)
return
}
}
super.mousePressed(e)
}
}
}
private fun RunnerAndConfigurationSettings.isRunning(project: Project, execId: String? = null) : Boolean {
return with(ExecutionManagerImpl.getInstance(project)) {
getRunningDescriptors {
s -> s.isOfSameType(this@isRunning)
}.any {
if (execId != null) {
getExecutors(it).asSequence().map(Executor::getId).contains(execId)
} else {
isProcessRunning(it)
}
}
}
}
@State(name = "RunConfigurationStartHistory", storages = [Storage(StoragePathMacros.PRODUCT_WORKSPACE_FILE)])
class RunConfigurationStartHistory(val project: Project) : PersistentStateComponent<RunConfigurationStartHistory.State> {
class State {
@XCollection(style = XCollection.Style.v2)
@OptionTag("element")
var history = mutableSetOf<Element>()
}
@Tag("element")
data class Element(
@Attribute
var setting: String? = "",
@Attribute
var executorId: String = "",
) {
@get:Transient
var state: RunState = RunState.UNDEFINED
}
class RunElement(
val configuration: RunnerAndConfigurationSettings,
val executorId: String,
state: RunState
) {
var state: RunState = state
set(value) {
if (field != value) {
getInstance(configuration.configuration.project)._state.history.find {
it.setting == configuration.uniqueID && it.executorId == executorId
}?.apply {
state = value
}
}
field = value
}
}
fun history(): List<RunElement> {
val settings = RunManager.getInstance(project).allSettings.associateBy { it.uniqueID }
return _state.history.mapNotNull { settings[it.setting]?.let { setting ->
RunElement(setting, it.executorId, it.state)
} }
}
fun register(setting: RunnerAndConfigurationSettings, executorId: String, state: RunState) {
_state.apply {
history = history.take(30).toMutableList().apply {
add(0, Element(setting.uniqueID, executorId).also {
it.state = state
})
}.toMutableSet()
}
}
fun firstOrNull(setting: RunnerAndConfigurationSettings?, predicate: Predicate<RunElement> = Predicate { true }): RunElement? {
setting ?: return null
return _state.history.firstOrNull {
it.setting == setting.uniqueID && predicate.test(RunElement(setting, it.executorId, it.state))
}?.let {
RunElement(setting, it.executorId, it.state)
}
}
private var _state = State()
override fun getState() = _state
override fun loadState(state: State) {
_state = state
}
companion object {
fun getInstance(project: Project): RunConfigurationStartHistory {
return project.getService(RunConfigurationStartHistory::class.java)
}
}
}
/**
* Registers one [ExecutionReasonableHistory] per project and
* disposes it with the project.
*/
private class ExecutionReasonableHistoryManager : StartupActivity.DumbAware {
override fun runActivity(project: Project) {
ExecutionReasonableHistory(
project,
onHistoryChanged = ::processHistoryChanged,
onAnyChange = ::configurationHistoryStateChanged
)
}
private fun processHistoryChanged(latest: ReasonableHistory.Elem<ExecutionEnvironment, RunState>?) {
if (latest != null) {
val (env, reason) = latest
getPersistedConfiguration(env.runnerAndConfigurationSettings)?.let { conf ->
if (reason == RunState.SCHEDULED) {
RunConfigurationStartHistory.getInstance(env.project).register(conf, env.executor.id, reason)
}
val runManager = RunManager.getInstance(env.project)
if (reason.isRunningState() && ExperimentalUI.isNewUI() && !runManager.isRunWidgetActive()) {
runManager.selectedConfiguration = conf
}
ActivityTracker.getInstance().inc()
} ?: logger<RunToolbarWidget>().warn(
"Cannot find persisted configuration of '${env.runnerAndConfigurationSettings}'." +
"It won't be saved in the run history."
)
}
}
private fun configurationHistoryStateChanged(env: ExecutionEnvironment, reason: RunState) {
RunConfigurationStartHistory.getInstance(env.project).firstOrNull(
getPersistedConfiguration(env.runnerAndConfigurationSettings)
) {
env.executor.id == it.executorId
}?.apply {
state = reason
ActivityTracker.getInstance().inc()
}
}
}
/**
* Listens to process startup and finish.
*/
private class ExecutionReasonableHistory(
project: Project,
onHistoryChanged: (latest: Elem<ExecutionEnvironment, RunState>?) -> Unit,
val onAnyChange: (ExecutionEnvironment, RunState) -> Unit
) : ReasonableHistory<ExecutionEnvironment, RunState>(onHistoryChanged), Disposable {
init {
Disposer.register(project, this)
project.messageBus.connect(this).subscribe(ExecutionManager.EXECUTION_TOPIC, object : ExecutionListener {
override fun processStartScheduled(executorId: String, env: ExecutionEnvironment) {
if (isPersistedTask(env)) {
advise(env, RunState.SCHEDULED)
}
onAnyChange(env, RunState.SCHEDULED)
}
override fun processNotStarted(executorId: String, env: ExecutionEnvironment, cause: Throwable?) {
discard(env, RunState.NOT_STARTED)
onAnyChange(env, RunState.NOT_STARTED)
}
override fun processStarted(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) {
if (isPersistedTask(env)) {
advise(env, RunState.STARTED)
}
onAnyChange(env, RunState.STARTED)
}
override fun processTerminating(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler) {
if (isPersistedTask(env)) {
advise(env, RunState.TERMINATING)
}
onAnyChange(env, RunState.TERMINATING)
}
override fun processTerminated(executorId: String, env: ExecutionEnvironment, handler: ProcessHandler, exitCode: Int) {
discard(env, RunState.TERMINATED)
onAnyChange(env, RunState.TERMINATED)
}
})
}
override fun dispose() {
history.clear()
}
}
enum class RunState {
UNDEFINED,
SCHEDULED,
NOT_STARTED,
STARTED,
TERMINATING,
TERMINATED;
fun isBusyState(): Boolean {
return this == SCHEDULED || this == TERMINATING
}
fun isRunningState(): Boolean {
return this == SCHEDULED || this == STARTED
}
}
/**
* Tracks some values and returns the latest one.
*
* @param listener fired if current value is changed; same as [latest]
*/
private open class ReasonableHistory<T, R>(
val listener: (latest: Elem<T, R>?) -> Unit
) {
class Elem<T, R>(val value: T, var reason: R) {
operator fun component1() = value
operator fun component2() = reason
}
protected val history = mutableListOf<Elem<T, R>>()
private val lock = ReentrantLock()
/**
* Returns the latest value in the history.
*/
private val latest: Elem<T, R>?
get() = lock.withLock { history.lastOrNull() }
/**
* Add a new value. If history doesn't contain the value or previous reason was different,
* then adds and fires [listener]. Nothing will be changed if the value is already in the history or
* the value is the latest but has same reason.
*/
fun advise(value: T, reason: R) = lock.withLock {
var l = latest
if (l != null && l.value == value) {
if (l.reason != reason) {
l.reason = reason
listener(l)
}
return
}
l = history.find { it.value == value }
if (l != null) {
// just update a reason
l.reason = reason
return
}
val newValue = Elem(value, reason)
history += newValue
listener(newValue)
}
/**
* Removes value from the history. Also, if removed value was the latest, then fires [listener].
*/
fun discard(value: T, reason: R) = lock.withLock {
if (history.lastOrNull()?.value == value) {
val oldValue = history.removeLast()
oldValue.reason = reason
listener(latest)
}
else {
history.removeIf { it.value == value }
}
}
}
private fun isPersistedTask(env: ExecutionEnvironment): Boolean {
return getPersistedConfiguration(env.runnerAndConfigurationSettings) != null
}
private fun getPersistedConfiguration(configuration: RunnerAndConfigurationSettings?): RunnerAndConfigurationSettings? {
var conf: RunProfile = (configuration ?: return null).configuration
if (conf is UserDataHolder) {
conf = conf.getUserData(ExecutionManagerImpl.DELEGATED_RUN_PROFILE_KEY) ?: conf
}
return RunManager.getInstance(configuration.configuration.project).allSettings.find { it.configuration == conf }
}
private fun getConfigurations(manager: ExecutionManagerImpl, descriptor: RunContentDescriptor): RunnerAndConfigurationSettings? {
return manager.getConfigurations(descriptor).firstOrNull()?.let(::getPersistedConfiguration)
}
@Nls
private fun RunnerAndConfigurationSettings.shortenName() = Executor.shortenNameIfNeeded(name)
@Nls
private fun shorten(@Nls text: String): String = StringUtil.shortenTextWithEllipsis(text, 27, 8) | platform/execution-impl/src/com/intellij/execution/ui/RunToolbarWidget.kt | 3440722367 |
package com.intellij.workspaceModel.storage.entities.test.api
import com.intellij.workspaceModel.storage.*
import com.intellij.workspaceModel.storage.EntityInformation
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId
import com.intellij.workspaceModel.storage.impl.EntityLink
import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase
import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData
import com.intellij.workspaceModel.storage.impl.extractOneToManyParent
import com.intellij.workspaceModel.storage.impl.updateOneToManyParentOfChild
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
import org.jetbrains.deft.annotations.Child
@GeneratedCodeApiVersion(1)
@GeneratedCodeImplVersion(1)
open class ChildSampleEntityImpl: ChildSampleEntity, WorkspaceEntityBase() {
companion object {
internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(SampleEntity::class.java, ChildSampleEntity::class.java, ConnectionId.ConnectionType.ONE_TO_MANY, true)
val connections = listOf<ConnectionId>(
PARENTENTITY_CONNECTION_ID,
)
}
@JvmField var _data: String? = null
override val data: String
get() = _data!!
override val parentEntity: SampleEntity?
get() = snapshot.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this)
override fun connectionIdList(): List<ConnectionId> {
return connections
}
class Builder(val result: ChildSampleEntityData?): ModifiableWorkspaceEntityBase<ChildSampleEntity>(), ChildSampleEntity.Builder {
constructor(): this(ChildSampleEntityData())
override fun applyToBuilder(builder: MutableEntityStorage) {
if (this.diff != null) {
if (existsInBuilder(builder)) {
this.diff = builder
return
}
else {
error("Entity ChildSampleEntity is already created in a different builder")
}
}
this.diff = builder
this.snapshot = builder
addToBuilder()
this.id = getEntityData().createEntityId()
// Process linked entities that are connected without a builder
processLinkedEntities(builder)
checkInitialization() // TODO uncomment and check failed tests
}
fun checkInitialization() {
val _diff = diff
if (!getEntityData().isDataInitialized()) {
error("Field ChildSampleEntity#data should be initialized")
}
if (!getEntityData().isEntitySourceInitialized()) {
error("Field ChildSampleEntity#entitySource should be initialized")
}
}
override fun connectionIdList(): List<ConnectionId> {
return connections
}
override var data: String
get() = getEntityData().data
set(value) {
checkModificationAllowed()
getEntityData().data = value
changedProperty.add("data")
}
override var entitySource: EntitySource
get() = getEntityData().entitySource
set(value) {
checkModificationAllowed()
getEntityData().entitySource = value
changedProperty.add("entitySource")
}
override var parentEntity: SampleEntity?
get() {
val _diff = diff
return if (_diff != null) {
_diff.extractOneToManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleEntity
} else {
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? SampleEntity
}
}
set(value) {
checkModificationAllowed()
val _diff = diff
if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
_diff.addEntity(value)
}
if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) {
_diff.updateOneToManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value)
}
else {
// Setting backref of the list
if (value is ModifiableWorkspaceEntityBase<*>) {
val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this
value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data
}
// else you're attaching a new entity to an existing entity that is not modifiable
this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value
}
changedProperty.add("parentEntity")
}
override fun getEntityData(): ChildSampleEntityData = result ?: super.getEntityData() as ChildSampleEntityData
override fun getEntityClass(): Class<ChildSampleEntity> = ChildSampleEntity::class.java
}
}
class ChildSampleEntityData : WorkspaceEntityData<ChildSampleEntity>() {
lateinit var data: String
fun isDataInitialized(): Boolean = ::data.isInitialized
override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildSampleEntity> {
val modifiable = ChildSampleEntityImpl.Builder(null)
modifiable.allowModifications {
modifiable.diff = diff
modifiable.snapshot = diff
modifiable.id = createEntityId()
modifiable.entitySource = this.entitySource
}
modifiable.changedProperty.clear()
return modifiable
}
override fun createEntity(snapshot: EntityStorage): ChildSampleEntity {
val entity = ChildSampleEntityImpl()
entity._data = data
entity.entitySource = entitySource
entity.snapshot = snapshot
entity.id = createEntityId()
return entity
}
override fun getEntityInterface(): Class<out WorkspaceEntity> {
return ChildSampleEntity::class.java
}
override fun serialize(ser: EntityInformation.Serializer) {
}
override fun deserialize(de: EntityInformation.Deserializer) {
}
override fun equals(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSampleEntityData
if (this.data != other.data) return false
if (this.entitySource != other.entitySource) return false
return true
}
override fun equalsIgnoringEntitySource(other: Any?): Boolean {
if (other == null) return false
if (this::class != other::class) return false
other as ChildSampleEntityData
if (this.data != other.data) return false
return true
}
override fun hashCode(): Int {
var result = entitySource.hashCode()
result = 31 * result + data.hashCode()
return result
}
} | platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildSampleEntityImpl.kt | 3641035479 |
// "Change to 'return@forEach'" "true"
// ACTION: Change to 'return@foo'
// ACTION: Change to 'return@forEach'
// ACTION: Do not show implicit receiver and parameter hints
// ERROR: The integer literal does not conform to the expected type Unit
// WITH_STDLIB
// COMPILER_ARGUMENTS: -XXLanguage:-NewInference
fun foo(f:()->Int){}
fun bar() {
foo {
listOf(1).forEach {
return<caret> 1
}
return@foo 1
}
} | plugins/kotlin/idea/tests/testData/quickfix/changeToLabeledReturn/multipleInner.kt | 130692700 |
package org.hexworks.zircon.internal.resource
import org.assertj.core.api.Assertions.assertThat
import org.hexworks.zircon.api.TrueTypeFontResources
import org.hexworks.zircon.api.resource.TilesetResource
import org.junit.Test
class TrueTypeTilesetResourcesTest {
@Test
fun shouldContainAllFonts() {
val fontCount = TrueTypeFontResources::class.members
.filter { it.isFinal }
.filter { it.parameters.size == 2 }
.map { accessor ->
assertThat(accessor.call(TrueTypeFontResources, 20))
.describedAs("Font: ${accessor.name}")
.isInstanceOf(TilesetResource::class.java)
1
}.fold(0, Int::plus)
assertThat(fontCount).isEqualTo(ENUM_FONTS.size)
}
companion object {
private val ENUM_FONTS = BuiltInTrueTypeFontResource.values().toList()
}
}
| zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/resource/TrueTypeTilesetResourcesTest.kt | 2472311866 |