content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package net.yslibrary.monotweety.appdata.user.remote
import io.reactivex.Single
import net.yslibrary.monotweety.appdata.user.User
interface UserRemoteRepository {
fun get(): Single<User>
}
| app/src/main/java/net/yslibrary/monotweety/appdata/user/remote/UserRemoteRepository.kt | 1884320763 |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.PsiTypesUtil.getPsiClass
import com.intellij.psi.util.PsiUtil.substituteTypeParameter
import com.intellij.psi.util.parents
import org.jetbrains.plugins.groovy.dgm.GdkMethodHolder.getHolderForClass
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrGdkMethod
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMember
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint
class CategoryMemberContributor : NonCodeMembersContributor() {
override fun processDynamicElements(qualifierType: PsiType, processor: PsiScopeProcessor, place: PsiElement, state: ResolveState) {
if (!processor.shouldProcessMethods() && !processor.shouldProcessProperties()) return
for (parent in place.parents()) {
if (parent is GrMember) break
if (parent !is GrClosableBlock) continue
val call = checkMethodCall(parent) ?: continue
val categories = getCategoryClasses(call, parent) ?: continue
val holders = categories.map { getHolderForClass(it, false) }
val stateWithContext = state.put(ClassHint.RESOLVE_CONTEXT, call)
for (category in holders) {
if (!category.processMethods(processor, stateWithContext, qualifierType, place.project)) return
}
}
}
private fun getCategoryClasses(call: GrMethodCall, closure: GrClosableBlock): List<PsiClass>? {
val closures = call.closureArguments
val args = call.expressionArguments
if (args.isEmpty()) return null
val lastArg = closure == args.last()
if (!lastArg && closure != closures.singleOrNull()) return null
if (call.resolveMethod() !is GrGdkMethod) return null
if (args.size == 1 || args.size == 2 && lastArg) {
val tupleType = args.first().type as? GrTupleType
tupleType?.let {
return it.componentTypes.mapNotNull {
getPsiClass(substituteTypeParameter(it, CommonClassNames.JAVA_LANG_CLASS, 0, false))
}
}
}
return args.mapNotNull {
(it as? GrReferenceExpression)?.resolve() as? PsiClass
}
}
private fun checkMethodCall(place: PsiElement): GrMethodCall? {
val context = place.context
val call = when (context) {
is GrMethodCall -> context
is GrArgumentList -> context.context as? GrMethodCall
else -> null
}
if (call == null) return null
val invoked = call.invokedExpression as? GrReferenceExpression
if (invoked?.referenceName != "use") return null
return call
}
} | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/CategoryMemberContributor.kt | 1212601790 |
package org.jetbrains.mazine.infer.type.parameter
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import java.lang.reflect.TypeVariable
class InferTypeParametersTest {
open class Base<P : Any, S : Any?>
open class A<AP : Any> : Base<AP, Int>()
open class B : A<String>()
class C : B()
class D<O> : B()
@Test
fun `Class itself should deliver its own type variables`() {
val actual = inferTypeParameters(Base::class.java, Base::class.java).values
assertThat(actual.filterIsInstance<TypeVariable<*>>().map { it.name })
.containsExactly("P", "S")
.inOrder()
}
@Test
fun `Parameterized direct inheritor should deliver inlined parameters`() {
val actual = inferTypeParameters(Base::class.java, A::class.java).values
assertThat(actual.map { it.toString() })
.containsExactly("AP", "class ${Int::class.javaObjectType.name}")
.inOrder()
}
@Test
fun `Indirect inheritor that defines explicit type should deliver inlined parameters`() {
val actual = inferTypeParameters(Base::class.java, B::class.java).values
assertThat(actual)
.containsExactly(String::class.java, Int::class.javaObjectType)
.inOrder()
}
@Test
fun `Indirect inheritor that defines no parameter should deliver inherited inlined parameters`() {
val actual = inferTypeParameters(Base::class.java, C::class.java).values
assertThat(actual)
.containsExactly(String::class.java, Int::class.javaObjectType)
.inOrder()
}
@Test
fun `Parameters of the inheritor should not confuse`() {
val actual = inferTypeParameters(Base::class.java, D::class.java).values
assertThat(actual)
.containsExactly(String::class.java, Int::class.javaObjectType)
.inOrder()
}
} | src/test/kotlin/org/jetbrains/mazine/infer/type/parameter/InferTypeParametersTest.kt | 1049136187 |
/*
* Copyright 2021 Google LLC
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* 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.
*/
// TEST PROCESSOR: ThrowListProcessor
// EXPECTED:
// java.io.IOException,java.util.NoSuchElementException
// java.io.IOException,java.lang.IndexOutOfBoundsException
// java.io.IOException,java.util.NoSuchElementException
// java.lang.IndexOutOfBoundsException
// java.io.IOException
// java.io.IOException,java.lang.IndexOutOfBoundsException
// java.lang.IndexOutOfBoundsException
// java.lang.IllegalArgumentException
// java.lang.IllegalStateException
// java.io.IOException
// java.lang.IllegalStateException,java.lang.IllegalArgumentException
// java.io.IOException
// java.lang.IndexOutOfBoundsException
// java.io.IOException,java.lang.IndexOutOfBoundsException
// java.io.IOException
// END
// MODULE: lib
// FILE: JavaLib.java
import java.io.IOException;
import java.lang.IndexOutOfBoundsException;
public class JavaLib {
public JavaLib() throws IOException {
}
public void foo() throws IOException {
throw new IOException();
}
public void foo(int i) throws IndexOutOfBoundsException {
throw new IndexOutOfBoundsException();
}
public void foo(String[] s) throws IOException, IndexOutOfBoundsException {
throw new IOException();
}
}
// FILE: KtLib.kt
import java.io.IOException
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
class KtLib {
@Throws(java.io.IOException::class)
fun throwsLibKt() {
throw java.io.IOException()
}
@Throws(java.lang.IndexOutOfBoundsException::class)
fun throwsLibKt(i: Int) {
throw java.lang.IndexOutOfBoundsException()
}
@Throws(java.io.IOException::class, java.lang.IndexOutOfBoundsException::class)
fun throwsLibKt(s: Array<String>) {
throw java.io.IOException()
}
@get:Throws(IllegalArgumentException::class)
val getterThrows: Int = 3
@set:Throws(IllegalStateException::class)
var setterThrows: Int = 3
@get:Throws(IOException::class)
@set:Throws(IllegalStateException::class, IllegalArgumentException::class)
var bothThrows: Int = 3
}
// MODULE: main(lib)
// FILE: ThrowsException.java
import java.io.IOException;
import java.lang.IndexOutOfBoundsException;
public class ThrowsException {
public int foo() throws IOException, IndexOutOfBoundsException{
return 1;
}
}
// FILE: a.kt
class ThrowsKt {
@Throws(java.io.IOException::class, java.util.NoSuchElementException::class)
fun throwsKT()
@set:Throws(java.lang.IndexOutOfBoundsException::class)
var a: Int
@Throws(java.io.IOException::class, java.util.NoSuchElementException::class)
get() {
return 1
}
set(a: Int) {
}
}
| test-utils/testData/api/throwList.kt | 3429107356 |
package domain.intent
import adeln.boilerplate.CheckerService
import adeln.boilerplate.MainActivity
import android.content.Context
import android.content.Intent
import common.intent.intent
enum class LaunchSource {
DEFAULT,
RECORD_SHORTCUT
}
private val LAUNCH_SOURCE = "launch source"
fun mainActivityIntent(c: Context, src: LaunchSource): Intent =
intent<MainActivity>(c).putExtra(LAUNCH_SOURCE, src.ordinal)
fun mainActivityExtent(i: Intent): LaunchSource =
LaunchSource.values[i.getIntExtra(LAUNCH_SOURCE, 0)]
fun checkerServiceIntent(c: Context): Intent =
intent<CheckerService>(c) | app/src/main/kotlin/domain/intent/intent.kt | 2742012329 |
package ru.dyatel.tsuschedule.model
import android.content.Context
import ru.dyatel.tsuschedule.R
import ru.dyatel.tsuschedule.layout.FilterView
import ru.dyatel.tsuschedule.layout.SubgroupFilterView
abstract class Filter(var enabled: Boolean) {
abstract fun apply(lesson: GroupLesson): GroupLesson?
}
abstract class PredefinedFilter : Filter(false) {
abstract fun createView(context: Context): FilterView
abstract fun save(): Map<String, String>
abstract fun load(data: Map<String, String>)
}
class CommonPracticeFilter : PredefinedFilter() {
override fun createView(context: Context) = FilterView(context).also {
it.setHeader(R.string.filter_common_practice)
it.attachFilter(this)
}
override fun save() = emptyMap<String, String>()
override fun load(data: Map<String, String>) = Unit
override fun apply(lesson: GroupLesson): GroupLesson {
return with(lesson) {
val newSubgroup = subgroup.takeUnless { type == LessonType.PRACTICE }
GroupLesson(parity, weekday, time, discipline, auditory, teacher, type, newSubgroup)
}
}
}
class SubgroupFilter : PredefinedFilter() {
private companion object {
const val SUBGROUP_KEY = "subgroup"
}
var subgroup = 1
override fun createView(context: Context) = SubgroupFilterView(context).also { it.attachFilter(this) }
override fun save() = mapOf(SUBGROUP_KEY to subgroup.toString())
override fun load(data: Map<String, String>) {
data[SUBGROUP_KEY]?.let { subgroup = it.toInt() }
}
override fun apply(lesson: GroupLesson) = lesson.takeIf { it.subgroup == null || it.subgroup == subgroup }
}
| src/main/kotlin/ru/dyatel/tsuschedule/model/Filters.kt | 324081086 |
package com.telesoftas.core.common.extension
import android.app.Activity
import android.app.Application
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.view.View
import com.telesoftas.core.common.presenter.Presenter
import timber.log.Timber
@Suppress("UNCHECKED_CAST")
fun <V> Presenter<V>.attach(view: V) {
when (view) {
is Activity -> attachToActivity(this as Presenter<Activity>, view)
is Fragment -> attachToFragment(this as Presenter<Fragment>, view)
is View -> attachToView(this as Presenter<View>, view)
}
}
private fun <V : View> attachToView(presenter: Presenter<V>, rootView: V) {
rootView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View) {
if (rootView == view) {
logAttach(presenter, rootView)
presenter.takeView(rootView)
}
}
override fun onViewDetachedFromWindow(view: View) {
if (rootView == view) {
logDetach(presenter, rootView)
rootView.removeOnAttachStateChangeListener(this)
presenter.dropView()
}
}
})
}
private fun <V : Activity> attachToActivity(presenter: Presenter<V>, view: V) {
val application = view.application
application.registerActivityLifecycleCallbacks(object : SimpleActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (view == activity) {
logAttach(presenter, view)
presenter.takeView(view)
}
}
override fun onActivityDestroyed(activity: Activity) {
if (view == activity) {
logDetach(presenter, view)
application.unregisterActivityLifecycleCallbacks(this)
presenter.dropView()
}
}
})
}
private fun <V : Fragment> attachToFragment(presenter: Presenter<V>, view: V) {
val fragmentManager = view.fragmentManager
fragmentManager?.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentCreated(
manager: FragmentManager,
fragment: Fragment,
savedInstanceState: Bundle?
) {
if (view == fragment) {
logAttach(presenter, view)
presenter.takeView(view)
}
}
override fun onFragmentDestroyed(manager: FragmentManager, fragment: Fragment) {
if (view == fragment) {
logDetach(presenter, view)
manager.unregisterFragmentLifecycleCallbacks(this)
presenter.dropView()
}
}
}, false)
}
private fun <V> logAttach(presenter: Presenter<V>, view: V) {
Timber.d("Attaching $view to ${presenter.javaClass.simpleName}")
}
private fun <V> logDetach(presenter: Presenter<V>, view: V) {
Timber.d("Detaching $view from ${presenter.javaClass.simpleName}")
}
internal interface SimpleActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityDestroyed(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle?) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {}
} | telesoftas-common/src/main/kotlin/com/telesoftas/core/common/extension/PresenterExtension.kt | 3721069065 |
/*
* Copyright (C) 2017. Uber Technologies
*
* 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.uber.rib.core
/**
* Enum consisting of event types that occur when [RouterNavigator] is used for transition.
*/
enum class RouterNavigatorEventType {
WILL_ATTACH_TO_HOST
}
| android/libraries/rib-router-navigator/src/main/kotlin/com/uber/rib/core/RouterNavigatorEventType.kt | 885287125 |
/*
* Copyright 2020 Thomas Nappo (Jire)
*
* 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.jire.strukt
import it.unimi.dsi.fastutil.longs.LongHeapPriorityQueue
import it.unimi.dsi.fastutil.longs.LongPriorityQueue
import net.openhft.chronicle.core.OS
import net.openhft.chronicle.core.StruktOS
import org.jire.strukt.internal.AbstractStrukts
import java.io.File
import java.io.RandomAccessFile
import java.nio.channels.FileChannel
import kotlin.reflect.KClass
open class FixedStrukts(
type: KClass<*>,
val capacity: Long,
val persistedTo: File? = null
) : AbstractStrukts(type) {
var baseAddress = UNSET_BASE_ADDRESS
var baseSize = 0L
var offset = 0L
val freed: LongPriorityQueue = LongHeapPriorityQueue()
val raf = if (persistedTo == null) null else RandomAccessFile(persistedTo, "rw")
override fun free() = if (raf == null) {
OS.memory().freeMemory(baseAddress, baseSize)
true
} else {
OS.unmap(baseAddress, baseSize)
raf.channel.close()
raf.close()
val file = persistedTo!!
file.deleteOnExit()
file.delete()
}
private fun allocateBase() {
baseSize = size * (capacity + 1)
baseAddress = if (raf == null)
OS.memory().allocate(baseSize)
else StruktOS.map(
raf.channel,
FileChannel.MapMode.READ_WRITE, 0, baseSize
)
for (field in fields) {
field.writeDefault(baseAddress)
}
offset += size
}
override fun allocate(): Long {
if (!freed.isEmpty) {
return freed.dequeueLong()
}
if (baseAddress == UNSET_BASE_ADDRESS) {
allocateBase()
return allocate()
}
val address = baseAddress + offset
OS.memory().copyMemory(baseAddress, address, size)
offset += size
return address
}
override fun free(address: Long): Boolean {
freed.enqueue(address)
return true
}
companion object {
private const val UNSET_BASE_ADDRESS = -1L
}
} | src/main/kotlin/org/jire/strukt/FixedStrukts.kt | 2570779735 |
package com.sangcomz.fishbun.adapter.image.impl
import android.graphics.Matrix
import android.net.Uri
import android.widget.ImageView
import coil.api.load
import coil.request.LoadRequestBuilder
import coil.size.Scale
import com.sangcomz.fishbun.adapter.image.ImageAdapter
/**
* Created by sangcomz on 23/07/2017.
*/
class CoilAdapter : ImageAdapter {
override fun loadImage(target: ImageView, loadUrl: Uri) {
target.load(loadUrl) {
scale(Scale.FIT)
scale(Scale.FILL)
}
}
override fun loadDetailImage(target: ImageView, loadUrl: Uri) {
target.load(loadUrl) {
scale(Scale.FIT)
}
}
}
| FishBun/src/main/java/com/sangcomz/fishbun/adapter/image/impl/CoilAdapter.kt | 62907861 |
/*
Copyright (C) 2015 - 2020 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.server
import io.grpc.ManagedChannelBuilder
import io.rouz.grpc.ManyToManyCall
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import orbit.shared.addressable.AddressableLease
import orbit.shared.addressable.AddressableReference
import orbit.shared.addressable.Key
import orbit.shared.mesh.NodeId
import orbit.shared.mesh.NodeInfo
import orbit.shared.net.Message
import orbit.shared.net.MessageContent
import orbit.shared.proto.AddressableManagementGrpc
import orbit.shared.proto.AddressableManagementOuterClass
import orbit.shared.proto.ConnectionGrpc
import orbit.shared.proto.Messages
import orbit.shared.proto.Node
import orbit.shared.proto.NodeManagementGrpc
import orbit.shared.proto.NodeManagementOuterClass
import orbit.shared.proto.joinCluster
import orbit.shared.proto.leaveCluster
import orbit.shared.proto.openStream
import orbit.shared.proto.renewLease
import orbit.shared.proto.toAddressableLease
import orbit.shared.proto.toAddressableReferenceProto
import orbit.shared.proto.toMessage
import orbit.shared.proto.toMessageProto
import orbit.shared.proto.toNodeId
import orbit.shared.proto.toNodeInfo
class TestClient(private val onReceive: (msg: Message) -> Unit = {}) {
var nodeId: NodeId = NodeId.generate("test")
private lateinit var connectionChannel: ManyToManyCall<Messages.MessageProto, Messages.MessageProto>
private lateinit var nodeChannel: NodeManagementGrpc.NodeManagementStub
private lateinit var addressableChannel: AddressableManagementGrpc.AddressableManagementStub
private var challengeToken: String? = null
private var messageId = 0L
suspend fun connect(port: Int = 50056): TestClient {
val channel = ManagedChannelBuilder.forTarget("0.0.0.0:${port}")
.usePlaintext()
.intercept(TestAuthInterceptor { nodeId })
.enableRetry()
.build()
nodeChannel = NodeManagementGrpc.newStub(channel)
val response = nodeChannel.joinCluster(
NodeManagementOuterClass.JoinClusterRequestProto.newBuilder().setCapabilities(
Node.CapabilitiesProto.newBuilder().addAddressableTypes("test").build()
).build()
)
nodeId = response.info.id.toNodeId()
challengeToken = response.info.lease.challengeToken
connectionChannel = ConnectionGrpc.newStub(channel).openStream()
addressableChannel = AddressableManagementGrpc.newStub(channel)
GlobalScope.launch {
for (msg in connectionChannel) {
onMessage(msg.toMessage())
}
}
return this
}
fun disconnect() {
connectionChannel.close()
}
suspend fun drain() {
nodeChannel.leaveCluster(
NodeManagementOuterClass.LeaveClusterRequestProto.newBuilder().build()
)
}
fun onMessage(msg: Message) {
val content = if (msg.content is MessageContent.InvocationRequest)
(msg.content as MessageContent.InvocationRequest).arguments
else
"Error: ${(msg.content as MessageContent.Error).description}"
println("Message received on node ${nodeId} - ${content}")
onReceive(msg)
}
fun sendMessage(msg: String, address: String? = null) {
println("Sending message to ${address} - ${msg}")
val message = Message(
MessageContent.InvocationRequest(
AddressableReference(
"test",
if (address != null) Key.StringKey(address) else Key.NoKey
), "report",
msg
),
source = nodeId,
messageId = ++messageId
)
connectionChannel.send(message.toMessageProto())
}
suspend fun renewAddressableLease(address: String): AddressableLease? {
val response = addressableChannel.renewLease(
AddressableManagementOuterClass.RenewAddressableLeaseRequestProto.newBuilder()
.setReference(AddressableReference("test", Key.of(address)).toAddressableReferenceProto())
.build()
)
return response.lease?.toAddressableLease()
}
suspend fun renewNodeLease(): NodeInfo? {
val response = nodeChannel.renewLease(
NodeManagementOuterClass.RenewNodeLeaseRequestProto.newBuilder()
.setCapabilities(Node.CapabilitiesProto.newBuilder().addAddressableTypes("test").build())
.setChallengeToken(challengeToken)
.build()
)
return response.info?.toNodeInfo()
}
} | src/orbit-server/src/test/kotlin/orbit/server/TestClient.kt | 3905405870 |
package mbuhot.eskotlin.aggregation
import org.elasticsearch.index.query.QueryBuilder
import org.elasticsearch.search.aggregations.AggregationBuilder
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder
/**
*/
data class FilterAggregationData(
var name: String? = null,
var filter: QueryBuilder? = null
)
fun filterAggregation(init: FilterAggregationData.() -> Unit): AggregationBuilder {
val params = FilterAggregationData().apply(init)
return FilterAggregationBuilder(
params.name,
params.filter
)
} | src/main/kotlin/mbuhot/eskotlin/aggregation/FilterAggregation.kt | 2570939845 |
@file:Suppress("UnsafeCastFromDynamic")
package kodando.react.dom
import org.w3c.dom.HTMLTableElement
external interface HtmlTableElementProps : HtmlElementProps<HTMLTableElement> {
var align: String?
var border: String?
var frame: String?
var summary: String?
var cellPadding: Any?
var cellSpacing: Any?
}
| kodando-react-dom/src/main/kotlin/kodando/react/dom/HtmlTableElementProps.kt | 1311009066 |
package components.progressBar
import javax.swing.JComponent
/**
* Created by vicboma on 05/12/16.
*/
interface MenuBar {
fun createSubMenu(parent: MenuBar?, child: JComponent?): MenuBar
fun createSubMenu(parent: MenuBar?, child: MutableList<JComponent?>): MenuBar
fun addMenu(menuList: List<Menu>) : MenuBar
fun addMenu(menu: Menu) : MenuBar
} | 14-start-async-menuBar-block-application/src/main/kotlin/components/menuBar/MenuBar.kt | 1910122166 |
public fun main(args: Array<String>) {
println("Hello, World!")
}
| src/main/kotlin/Main.kt | 187091657 |
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.example.paging.pagingwithnetwork.reddit.repository.inMemory.byItem
import android.arch.lifecycle.MutableLiveData
import android.arch.paging.DataSource
import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi
import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost
import java.util.concurrent.Executor
/**
* A simple data source factory which also provides a way to observe the last created data source.
* This allows us to channel its network request status etc back to the UI. See the Listing creation
* in the Repository class.
*/
class SubRedditDataSourceFactory(
private val redditApi: RedditApi,
private val subredditName: String,
private val retryExecutor: Executor) : DataSource.Factory<String, RedditPost> {
val sourceLiveData = MutableLiveData<ItemKeyedSubredditDataSource>()
override fun create(): DataSource<String, RedditPost> {
val source = ItemKeyedSubredditDataSource(redditApi, subredditName, retryExecutor)
sourceLiveData.postValue(source)
return source
}
} | PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inMemory/byItem/SubRedditDataSourceFactory.kt | 4206345916 |
package gl8080.lifegame.web.exception
import javax.transaction.RollbackException
import javax.ws.rs.core.Context
import javax.ws.rs.core.Response
import javax.ws.rs.ext.ExceptionMapper
import javax.ws.rs.ext.Provider
import javax.ws.rs.ext.Providers
@Provider
class RollBackExceptionMapper: ExceptionMapper<RollbackException> {
@Context
lateinit private var providers: Providers
override fun toResponse(e: RollbackException?): Response? {
val cause = e?.cause
val type = cause?.javaClass as Class<Throwable>
val exceptionMapper = this.providers.getExceptionMapper(type)
if (exceptionMapper == null) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build()
} else {
return exceptionMapper.toResponse(cause)
}
}
} | src/main/kotlin/gl8080/lifegame/web/exception/RollBackExceptionMapper.kt | 3158139359 |
package lt.vilnius.tvarkau.dagger.module
import com.nhaarman.mockito_kotlin.mock
import dagger.Module
import dagger.Provides
import lt.vilnius.tvarkau.fragments.interactors.MultipleReportsMapInteractor
import lt.vilnius.tvarkau.mvp.interactors.ReportTypesInteractor
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import javax.inject.Singleton
/**
* @author Martynas Jurkus
*/
@Module
class TestDataModule {
@Provides
@Singleton
fun provideReportTypesInteractor(): ReportTypesInteractor = mock()
@Provides
@Singleton
fun provideMultipleReportsMapInteractor(): MultipleReportsMapInteractor = mock()
@Provides
@Singleton
@RawOkHttpClient
fun provideRawOkHttpClient(): OkHttpClient = mock()
@Provides
@Singleton
fun provideCache(): Cache = Cache(File("/"), 1000)
} | app/src/test/java/lt/vilnius/tvarkau/dagger/module/TestDataModule.kt | 1790235828 |
/*
* Copyright (C) 2015 The SlimRoms Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.slim.slimfilemanager.settings
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.text.TextUtils
import com.slim.slimfilemanager.widget.TabItem
import java.util.ArrayList
import java.util.Arrays
object SettingsProvider {
// File Manager
val KEY_ENABLE_ROOT = "enable_root"
val THEME = "app_theme"
val SORT_MODE = "sort_mode"
val SMALL_INDICATOR = "small_indicator"
// Text Editor
val USE_MONOSPACE = "use_monospace"
val EDITOR_WRAP_CONTENT = "editor_wrap_content"
val SUGGESTION_ACTIVE = "suggestion_active"
val EDITOR_ENCODING = "editor_encoding"
val FONT_SIZE = "font_size"
val SPLIT_TEXT = "page_system_active"
operator fun get(context: Context): SharedPreferences {
return PreferenceManager.getDefaultSharedPreferences(context)
}
fun put(context: Context): SharedPreferences.Editor {
return get(context).edit()
}
fun put(context: Context, key: String, o: Any) {
if (o is Boolean) {
put(context).putBoolean(key, o).apply()
} else if (o is String) {
put(context).putString(key, o).apply()
} else if (o is Int) {
put(context).putInt(key, o).apply()
}
}
fun getString(context: Context, key: String, defValue: String): String? {
return get(context).getString(key, defValue)
}
fun putString(context: Context, key: String, value: String) {
put(context).putString(key, value).apply()
}
fun getBoolean(context: Context, key: String, defValue: Boolean): Boolean {
return get(context).getBoolean(key, defValue)
}
fun putBoolean(context: Context, key: String, b: Boolean) {
put(context).putBoolean(key, b).apply()
}
fun getInt(context: Context, key: String, defValue: Int): Int {
var i: Int
try {
i = get(context).getInt(key, defValue)
} catch (e: Exception) {
i = Integer.parseInt(get(context).getString(key, Integer.toString(defValue))!!)
}
return i
}
fun putInt(context: Context, key: String, value: Int) {
put(context).putInt(key, value).commit()
}
fun getTabList(context: Context, key: String,
def: ArrayList<TabItem>): ArrayList<TabItem> {
val items = ArrayList<TabItem>()
val array = ArrayList(
Arrays.asList(*TextUtils.split(get(context).getString(key, ""), "‚‗‚")))
for (s in array) {
items.add(TabItem.fromString(s))
}
if (array.isEmpty()) {
items.addAll(def)
}
return items
}
fun putTabList(context: Context, key: String, tabs: ArrayList<TabItem>) {
val items = ArrayList<String>()
for (item in tabs) {
items.add(item.toString())
}
put(context).putString(key, TextUtils.join("‚‗‚", items)).apply()
}
fun remove(context: Context, key: String) {
put(context).remove(key).apply()
}
} | manager/src/main/java/com/slim/slimfilemanager/settings/SettingsProvider.kt | 2115306796 |
package com.infinum.dbinspector.domain.shared.mappers
import com.infinum.dbinspector.data.models.local.cursor.output.Field
import com.infinum.dbinspector.data.models.local.cursor.output.FieldType
import com.infinum.dbinspector.data.models.local.cursor.output.QueryResult
import com.infinum.dbinspector.domain.Mappers
import com.infinum.dbinspector.domain.shared.models.Cell
import com.infinum.dbinspector.domain.shared.models.Page
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlin.test.assertEquals
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
@DisplayName("ContentMapper tests")
internal class ContentMapperTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory<Mappers.Cell> { mockk<CellMapper>() }
}
)
@Test
fun `Empty local value maps to empty domain value`() =
test {
val given = mockk<QueryResult> {
every { rows } returns listOf()
every { nextPage } returns null
every { beforeCount } returns 0
every { afterCount } returns 0
}
val expected = Page(
cells = listOf()
)
val cellMapper: Mappers.Cell = get()
val mapper = ContentMapper(cellMapper)
coEvery { cellMapper.invoke(any()) } returns mockk()
val actual = mapper(given)
coVerify(exactly = 0) { cellMapper.invoke(any()) }
assertEquals(expected, actual)
}
@Test
fun `QueryResult local value maps to Page with same domain value`() =
test {
val given = mockk<QueryResult> {
every { rows } returns listOf(
mockk {
every { position } returns 0
every { fields } returns listOf(
Field(
FieldType.INTEGER,
text = "1"
)
)
}
)
every { nextPage } returns null
every { beforeCount } returns 0
every { afterCount } returns 0
}
val expectedCell = Cell(
text = "1"
)
val expected = Page(
cells = listOf(
expectedCell
)
)
val cellMapper: Mappers.Cell = get()
val mapper = ContentMapper(cellMapper)
coEvery { cellMapper.invoke(any()) } returns expectedCell
val actual = mapper(given)
coVerify(exactly = 1) { cellMapper.invoke(any()) }
assertEquals(expected, actual)
}
}
| dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/shared/mappers/ContentMapperTest.kt | 3635462368 |
package com.infinum.dbinspector.data.sources.local.proto.history
import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import com.google.protobuf.InvalidProtocolBufferException
import com.infinum.dbinspector.data.models.local.proto.output.HistoryEntity
import java.io.InputStream
import java.io.OutputStream
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.suspendCancellableCoroutine
internal class HistorySerializer : Serializer<HistoryEntity> {
override val defaultValue: HistoryEntity =
HistoryEntity.getDefaultInstance()
override suspend fun readFrom(input: InputStream): HistoryEntity =
suspendCancellableCoroutine { continuation ->
try {
continuation.resume(HistoryEntity.parseFrom(input))
} catch (exception: InvalidProtocolBufferException) {
continuation.resumeWithException(CorruptionException("Cannot read proto.", exception))
}
}
override suspend fun writeTo(t: HistoryEntity, output: OutputStream): Unit =
suspendCancellableCoroutine { continuation ->
t.writeTo(output)
continuation.resume(Unit)
}
}
| dbinspector/src/main/kotlin/com/infinum/dbinspector/data/sources/local/proto/history/HistorySerializer.kt | 434770343 |
package io.stardog.stardao.kotlin.partial
import io.stardog.stardao.annotations.Id
import io.stardog.stardao.annotations.Updatable
import io.stardog.stardao.kotlin.partial.annotations.PartialDataObjects
import org.junit.Test
import kotlin.test.assertEquals
class DtoGenerateProcessorTest {
@Test
fun testWhatever() {
val user = ExampleUser("Foo", "Test")
assertEquals("Foo", user.id)
}
}
@PartialDataObjects(["Test"])
data class ExampleUser(
@Id
val id: String,
@Updatable
val name: String
) | stardao-kotlin-partial/src/test/kotlin/io/stardog/stardao/kotlin/partial/DtoGenerateProcessorTest.kt | 3341471729 |
package de.westnordost.streetcomplete.view
import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
/** A relative layout that can be animated via an ObjectAnimator on the yFraction and xFraction
* properties. I.e., it can be animated to slide up and down, left and right */
class SlidingRelativeLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: RelativeLayout(context, attrs, defStyleAttr) {
var yFraction: Float = 0f
set(fraction) {
field = fraction
if (height != 0) translationY = height * yFraction
}
var xFraction: Float = 0f
set(fraction) {
field = fraction
if (width != 0) translationX = width * xFraction
}
}
| app/src/main/java/de/westnordost/streetcomplete/view/SlidingRelativeLayout.kt | 3827535760 |
/*
* Copyright (c) 2017.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.processModel
import net.devrieze.util.Handle
import net.devrieze.util.overlay
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.processModel.Split
import nl.adaptivity.process.processModel.StartNode
import nl.adaptivity.process.processModel.engine.ConditionResult
import nl.adaptivity.process.processModel.engine.ExecutableCondition
import nl.adaptivity.process.processModel.engine.ExecutableJoin
import nl.adaptivity.process.processModel.engine.evalCondition
import nl.adaptivity.util.multiplatform.assert
import nl.adaptivity.util.security.Principal
import nl.adaptivity.xmlutil.util.ICompactFragment
import kotlin.jvm.JvmStatic
class JoinInstance : ProcessNodeInstance<JoinInstance> {
interface Builder : ProcessNodeInstance.Builder<ExecutableJoin, JoinInstance> {
val isFinished: Boolean
get() = state == NodeInstanceState.Complete || state == NodeInstanceState.Failed
override fun doProvideTask(engineData: MutableProcessEngineDataAccess): Boolean {
if (!isFinished) {
val shouldProgress = node.provideTask(engineData, this)
if (shouldProgress) {
val directSuccessors = processInstanceBuilder.getDirectSuccessorsFor(this.handle)
val canAdd = directSuccessors
.none { it.state.isCommitted || it.state.isFinal }
if (canAdd) {
state = NodeInstanceState.Acknowledged
return true
}
}
return shouldProgress
}
return false
}
override fun doTakeTask(engineData: MutableProcessEngineDataAccess): Boolean {
return node.takeTask(this)
}
override fun doStartTask(engineData: MutableProcessEngineDataAccess): Boolean {
if (node.startTask(this)) {
return updateTaskState(engineData, cancelState = NodeInstanceState.Cancelled)
} else {
return false
}
}
override fun doFinishTask(engineData: MutableProcessEngineDataAccess, resultPayload: ICompactFragment?) {
if (state == NodeInstanceState.Complete) {
return
}
var committedPredecessorCount = 0
var completedPredecessorCount = 0
predecessors
.map { processInstanceBuilder.getChildNodeInstance(it) }
.filter { it.state.isCommitted }
.forEach {
if (!it.state.isFinal) {
throw ProcessException("Predecessor $it is committed but not final, cannot finish join without cancelling the predecessor")
} else {
committedPredecessorCount++
if (it.state == NodeInstanceState.Complete) {
if (node.evalCondition(processInstanceBuilder, it, this) == ConditionResult.TRUE) {
completedPredecessorCount++
}
}
}
}
super.doFinishTask(engineData, resultPayload)
// Store before cancelling predecessors, the cancelling will likely hit this child
processInstanceBuilder.storeChild(this)
processInstanceBuilder.store(engineData)
skipPredecessors(engineData)
if (committedPredecessorCount < node.min) {
throw ProcessException("Finishing the join is not possible as the minimum amount of predecessors ${node.min} was not reached (predecessor count: $committedPredecessorCount)")
}
engineData.commit()
}
fun failSkipOrCancel(
engineData: MutableProcessEngineDataAccess,
cancelState: NodeInstanceState,
cause: Throwable
) {
when {
state.isCommitted -> failTask(engineData, cause)
cancelState.isSkipped -> state = NodeInstanceState.Skipped
else -> cancel(engineData)
}
}
}
class ExtBuilder(instance: JoinInstance, processInstanceBuilder: ProcessInstance.Builder) :
ProcessNodeInstance.ExtBuilder<ExecutableJoin, JoinInstance>(instance, processInstanceBuilder), Builder {
override var node: ExecutableJoin by overlay { instance.node }
override fun build() = if (changed) JoinInstance(this).also { invalidateBuilder(it) } else base
override fun skipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) =
skipTaskImpl(engineData, newState)
}
class BaseBuilder(
node: ExecutableJoin,
predecessors: Iterable<Handle<SecureObject<ProcessNodeInstance<*>>>>,
processInstanceBuilder: ProcessInstance.Builder,
owner: Principal,
entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = NodeInstanceState.Pending
) : ProcessNodeInstance.BaseBuilder<ExecutableJoin, JoinInstance>(
node,
predecessors,
processInstanceBuilder,
owner,
entryNo,
handle,
state
), Builder {
override fun build() = JoinInstance(this)
override fun skipTask(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) =
skipTaskImpl(engineData, newState)
}
override val node: ExecutableJoin
get() = super.node as ExecutableJoin
@Suppress("UNCHECKED_CAST")
override val handle: Handle<SecureObject<JoinInstance>>
get() = super.handle as Handle<SecureObject<JoinInstance>>
fun canFinish() = predecessors.size >= node.min
constructor(
node: ExecutableJoin,
predecessors: Collection<Handle<SecureObject<ProcessNodeInstance<*>>>>,
processInstanceBuilder: ProcessInstance.Builder,
hProcessInstance: Handle<SecureObject<ProcessInstance>>,
owner: Principal,
entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = NodeInstanceState.Pending,
results: Iterable<ProcessData> = emptyList()
) :
super(node, predecessors, processInstanceBuilder, hProcessInstance, owner, entryNo, handle, state, results) {
if (predecessors.any { !it.isValid }) {
throw ProcessException("When creating joins all handles should be valid $predecessors")
}
}
constructor(builder: Builder) : this(
builder.node,
builder.predecessors,
builder.processInstanceBuilder,
builder.hProcessInstance,
builder.owner,
builder.entryNo,
builder.handle,
builder.state,
builder.results
)
override fun builder(processInstanceBuilder: ProcessInstance.Builder) =
ExtBuilder(this, processInstanceBuilder)
companion object {
fun build(
joinImpl: ExecutableJoin,
predecessors: Set<Handle<SecureObject<ProcessNodeInstance<*>>>>,
processInstanceBuilder: ProcessInstance.Builder,
entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = NodeInstanceState.Pending,
body: Builder.() -> Unit
): JoinInstance {
return JoinInstance(
BaseBuilder(
joinImpl,
predecessors,
processInstanceBuilder,
processInstanceBuilder.owner,
entryNo,
handle,
state
).apply(body)
)
}
fun build(
joinImpl: ExecutableJoin,
predecessors: Set<Handle<SecureObject<ProcessNodeInstance<*>>>>,
processInstance: ProcessInstance,
entryNo: Int,
handle: Handle<SecureObject<ProcessNodeInstance<*>>> = Handle.invalid(),
state: NodeInstanceState = NodeInstanceState.Pending,
body: Builder.() -> Unit
): JoinInstance {
return build(joinImpl, predecessors, processInstance.builder(), entryNo, handle, state, body)
}
/**
* Update the state of the task. Returns true if the task should now be finished by the caller.
* @param cancelState The state to use when the instance cannot work
* @return `true` if the caller should finish the task, `false` if not
*/
@JvmStatic
private fun Builder.updateTaskState(
engineData: MutableProcessEngineDataAccess,
cancelState: NodeInstanceState
): Boolean {
if (state.isFinal) return false // Don't update if we're already complete
val join = node
val totalPossiblePredecessors = join.predecessors.size
var realizedPredecessors = 0
val instantiatedPredecessors = predecessors.map {
processInstanceBuilder.getChildNodeInstance(it).also {
if(it.state.isFinal) realizedPredecessors++
}
}
var mustDecide = false
if (realizedPredecessors == totalPossiblePredecessors) {
/* Did we receive all possible predecessors. In this case we need to decide */
state = NodeInstanceState.Started
mustDecide = true
}
var complete = 0
var skippedOrNever = 0
var pending = 0
for (predecessor in instantiatedPredecessors) {
val condition = node.conditions[predecessor.node.identifier] as? ExecutableCondition
val conditionResult = condition.evalCondition(processInstanceBuilder, predecessor, this)
if (conditionResult == ConditionResult.NEVER) {
skippedOrNever += 1
} else {
when (predecessor.state) {
NodeInstanceState.Complete -> complete += 1
NodeInstanceState.Skipped,
NodeInstanceState.SkippedCancel,
NodeInstanceState.Cancelled,
NodeInstanceState.SkippedFail,
NodeInstanceState.Failed -> skippedOrNever += 1
else -> pending += 1
}
}
}
if (totalPossiblePredecessors - skippedOrNever < join.min) {
// XXX this needs to be done in the caller
if (complete > 0) {
failTask(engineData, ProcessException("Too many predecessors have failed"))
} else {
// cancelNoncompletedPredecessors(engineData)
failSkipOrCancel(engineData, cancelState, ProcessException("Too many predecessors have failed"))
}
}
if (complete >= join.min) {
if (totalPossiblePredecessors - complete - skippedOrNever == 0) return true
if (complete >= join.max || (realizedPredecessors == totalPossiblePredecessors)) {
return true
}
}
if (mustDecide) {
if (state==NodeInstanceState.Started) {
cancel(engineData)
} else {
failSkipOrCancel(engineData, cancelState, ProcessException("Unexpected failure to complete join"))
}
}
return false
}
private fun Builder.skipTaskImpl(engineData: MutableProcessEngineDataAccess, newState: NodeInstanceState) {
// Skipping a join merely triggers a recalculation
assert(newState == NodeInstanceState.Skipped || newState == NodeInstanceState.SkippedCancel || newState == NodeInstanceState.SkippedFail)
val updateResult = updateTaskState(engineData, newState)
processInstanceBuilder.storeChild(this)
processInstanceBuilder.store(engineData)
if (state.isSkipped) {
skipPredecessors(engineData)
}
}
private fun Builder.skipPredecessors(engineData: MutableProcessEngineDataAccess) {
if (node.isMultiMerge) return // multimerge joins should not have their predecessors skipped
val pseudoContext = PseudoInstance.PseudoContext(processInstanceBuilder)
pseudoContext.populatePredecessorsFor(handle)
val toSkipCancel = mutableListOf<ProcessNodeInstance<*>>()
val predQueue = ArrayDeque<IProcessNodeInstance>()//.apply { add(pseudoContext.getNodeInstance(handle)!!) }
for (hpred in pseudoContext.getNodeInstance(handle)!!.predecessors) {
val pred = pseudoContext.getNodeInstance(hpred)
if (pred?.state?.isFinal == false) predQueue.add(pred)
}
while (predQueue.isNotEmpty()) {
val pred = predQueue.removeFirst()
when {
pred.state.isFinal && pred.node !is StartNode -> Unit
pred is PseudoInstance -> if (pred.node !is Split) {
pred.state = NodeInstanceState.AutoCancelled
for (hppred in pred.predecessors) {
pseudoContext.getNodeInstance(hppred)?.let { predQueue.add(it) }
}
}
pred is ProcessNodeInstance<*> -> {
if (pred.node !is Split) {
toSkipCancel.add(pred)
for (hppred in pred.predecessors) {
val ppred = pseudoContext.getNodeInstance(hppred) ?: continue
predQueue.add(ppred)
}
}
}
}
}
for (predecessor in toSkipCancel) {
processInstanceBuilder.updateChild(predecessor.handle) {
cancelAndSkip(engineData)
}
}
}
}
}
| ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processModel/JoinInstance.kt | 1784735938 |
/*
* Copyright 2020 Alex Almeida Tavella
*
* 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 br.com.core.tmdb.api
import br.com.moov.core.di.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import okhttp3.Interceptor
import okhttp3.Response
import java.util.Locale
import javax.inject.Inject
@ContributesBinding(AppScope::class)
class TmdbRequestInterceptor @Inject constructor(
private val apiKey: String,
private val cacheDuration: Long
) : Interceptor {
companion object {
const val QUERY_PARAM_API_KEY = "api_key"
const val QUERY_PARAM_LANGUAGE = "language"
const val HEADER_PARAM_CACHE_CONTROL = "Cache-Control"
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val url = request.url.newBuilder()
.addQueryParameter(QUERY_PARAM_API_KEY, apiKey)
.addQueryParameter(QUERY_PARAM_LANGUAGE, Locale.getDefault().getLanguageString())
.build()
val newRequest = request.newBuilder()
.url(url)
.addHeader(HEADER_PARAM_CACHE_CONTROL, "public, max-age=$cacheDuration")
.build()
return chain.proceed(newRequest)
}
}
fun Locale.getLanguageString(): String {
val sb = StringBuilder()
sb.append(language)
if (!country.isNullOrBlank() && country.length == 2) {
sb.append("-").append(country)
}
return sb.toString()
}
| core-lib/tmdb/src/main/java/br/com/core/tmdb/api/TmdbRequestInterceptor.kt | 1331809301 |
/*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.servlet
import net.devrieze.util.*
import net.devrieze.util.security.AuthenticationNeededException
import net.devrieze.util.security.SYSTEMPRINCIPAL
import net.devrieze.util.security.SecureObject
import nl.adaptivity.io.Writable
import nl.adaptivity.io.WritableReader
import nl.adaptivity.messaging.*
import nl.adaptivity.process.IMessageService
import nl.adaptivity.process.MessageSendingResult
import nl.adaptivity.process.engine.*
import nl.adaptivity.process.engine.ProcessInstance.ProcessInstanceRef
import nl.adaptivity.process.engine.processModel.*
import nl.adaptivity.process.messaging.ActivityResponse
import nl.adaptivity.process.messaging.EndpointServlet
import nl.adaptivity.process.messaging.GenericEndpoint
import nl.adaptivity.process.processModel.IXmlMessage
import nl.adaptivity.process.processModel.RootProcessModel
import nl.adaptivity.process.processModel.engine.*
import nl.adaptivity.process.util.Constants
import nl.adaptivity.rest.annotations.HttpMethod
import nl.adaptivity.rest.annotations.RestMethod
import nl.adaptivity.rest.annotations.RestParam
import nl.adaptivity.rest.annotations.RestParamType
import nl.adaptivity.util.DomUtil
import nl.adaptivity.util.SerializableData
import nl.adaptivity.util.commitSerializable
import nl.adaptivity.xmlutil.*
import org.jetbrains.annotations.TestOnly
import org.w3.soapEnvelope.Envelope
import org.w3c.dom.Element
import org.w3c.dom.Node
import java.io.*
import javax.activation.DataHandler
import javax.activation.DataSource
import javax.jws.WebMethod
import javax.jws.WebParam
import javax.jws.WebParam.Mode
import javax.servlet.ServletConfig
import javax.servlet.ServletException
import javax.servlet.http.HttpServletResponse
import javax.xml.bind.annotation.XmlElementWrapper
import javax.xml.namespace.QName
import javax.xml.stream.*
import javax.xml.stream.events.*
import javax.xml.stream.events.Namespace
import javax.xml.transform.Result
import javax.xml.transform.Source
import java.net.URI
import java.security.Principal
import java.sql.SQLException
import java.util.*
import java.util.concurrent.ExecutionException
import java.util.concurrent.Future
import java.util.logging.Level
import java.util.logging.Logger
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* The service representing a process engine.
*
* @param TR The type of transaction used. Mainly used for testing with memory based storage
*/
/*
@ServiceInfo(targetNamespace = ServletProcessEngine.SERVICE_NS,
interfaceNS = ServletProcessEngine.SERVICE_NS,
interfaceLocalname = "soap",
interfacePrefix = "pe",
serviceLocalname = ServletProcessEngine.SERVICE_LOCALNAME)
*/
open class ServletProcessEngine<TR : ProcessTransaction> : EndpointServlet(), GenericEndpoint {
private lateinit var processEngine: ProcessEngine<TR, *>
private lateinit var messageService: MessageService
override val serviceName: QName
get() = QName(Constants.PROCESS_ENGINE_NS, SERVICE_LOCALNAME)
override val endpointName: String
get() = "soap"
override val endpointLocation: URI?
get() = null
inner class MessageService(localEndpoint: EndpointDescriptor) :
IMessageService<ServletProcessEngine.NewServletMessage> {
override var localEndpoint: EndpointDescriptor = localEndpoint
internal set
override fun createMessage(message: IXmlMessage): NewServletMessage {
return NewServletMessage(message, localEndpoint)
}
override fun sendMessage(
engineData: ProcessEngineDataAccess,
protoMessage: NewServletMessage,
activityInstanceContext: ActivityInstanceContext
): MessageSendingResult {
val nodeHandle = activityInstanceContext.handle
protoMessage.setHandle(engineData, activityInstanceContext)
val result = MessagingRegistry.sendMessage(
protoMessage,
MessagingCompletionListener(
nodeHandle,
protoMessage.owner
),
DataSource::class.java, emptyArray()
)
if (result.isCancelled) {
return MessageSendingResult.FAILED
}
if (result.isDone) {
try {
result.get()
return MessageSendingResult.ACKNOWLEDGED
} catch (e: ExecutionException) {
val cause = e.cause
if (cause is RuntimeException) {
throw cause
}
throw RuntimeException(cause)
} catch (e: InterruptedException) {
return MessageSendingResult.SENT
}
}
return MessageSendingResult.SENT
}
}
private inner class MessagingCompletionListener(
private val handle: Handle<SecureObject<ProcessNodeInstance<*>>>,
private val owner: Principal
) : CompletionListener<DataSource> {
override fun onMessageCompletion(future: Future<out DataSource>) {
[email protected](future, handle, owner)
}
}
class NewServletMessage(
private val message: IXmlMessage,
private val localEndpoint: EndpointDescriptor
) : ISendableMessage, Writable {
private var activityInstanceContext: ActivityInstanceContext? = null
private var data: Writable? = null
internal val owner: Principal
get() = activityInstanceContext?.owner
?: throw IllegalStateException("The message has not been initialised with a node yet")
private val source: XmlReader
get() = message.messageBody.getXmlReader()
override fun getDestination(): EndpointDescriptor? {
return message.endpointDescriptor
}
override fun getMethod(): String? {
return message.method
}
override fun getHeaders(): Collection<ISendableMessage.IHeader> {
val contentType = message.contentType
return if (contentType.isEmpty()) {
emptyList()
} else {
listOf(Header("Content-type", contentType))
}
}
override fun getBodySource(): Writable? = data
override fun getBodyReader(): Reader {
val d = data
return if (d == null) StringReader("") else WritableReader(d) // XXX see if there's a better way
}
override fun getContentType(): String {
return message.contentType
}
@Throws(IOException::class)
override fun writeTo(destination: Writer) {
data!!.writeTo(destination)
}
fun setHandle(engineData: ProcessEngineDataAccess, activityInstanceContext: ActivityInstanceContext) {
this.activityInstanceContext = activityInstanceContext
try {
val processInstance = engineData.instance(activityInstanceContext.processContext.handle).withPermission()
data = activityInstanceContext.instantiateXmlPlaceholders(processInstance, source, false, localEndpoint)
} catch (e: Exception) {
when (e) {
is MessagingException -> throw e
else -> throw MessagingException(e)
}
}
}
override fun getAttachments(): Map<String, DataSource> {
return emptyMap()
}
companion object {
@Throws(FactoryConfigurationError::class, XMLStreamException::class)
fun fillInActivityMessage(
messageBody: Source,
result: Result,
nodeInstance: ProcessNodeInstance<*>,
localEndpoint: EndpointDescriptor
) {
// TODO use multiplatform api
val xif = XMLInputFactory.newInstance()
val xof = XMLOutputFactory.newInstance()
val xer = xif.createXMLEventReader(messageBody)
val xew = xof.createXMLEventWriter(result)
while (xer.hasNext()) {
val event = xer.nextEvent()
if (event.isStartElement) {
val se = event.asStartElement()
val eName = se.name
if (Constants.MODIFY_NS_STR == eName.namespaceURI) {
@Suppress("UNCHECKED_CAST")
val attributes = se.attributes as Iterator<Attribute>
when (eName.localPart) {
"attribute" -> writeAttribute(nodeInstance, xer, attributes, xew)
"element" -> writeElement(nodeInstance, xer, attributes, xew, localEndpoint)
else -> throw HttpResponseException(
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
"Unsupported activity modifier"
)
}
} else {
xew.add(se)
}
} else {
if (event.isCharacters) {
val c = event.asCharacters()
val charData = c.data
var i = 0
while (i < charData.length) {
if (!Character.isWhitespace(charData[i])) {
break
}
++i
}
if (i == charData.length) {
continue // ignore it, and go to next event
}
}
if (event is Namespace) {
if (event.namespaceURI != Constants.MODIFY_NS_STR) {
xew.add(event)
}
} else {
try {
xew.add(event)
} catch (e: IllegalStateException) {
val errorMessage = StringBuilder("Error adding event: ")
errorMessage.append(event.toString()).append(' ')
if (event.isStartElement) {
errorMessage.append('<').append(event.asStartElement().name).append('>')
} else if (event.isEndElement) {
errorMessage.append("</").append(event.asEndElement().name).append('>')
}
logger.log(Level.WARNING, errorMessage.toString(), e)
// baos.reset(); baos.close();
throw e
}
}
}
}
}
@Throws(XMLStreamException::class)
private fun writeElement(
nodeInstance: ProcessNodeInstance<*>,
`in`: XMLEventReader,
attributes: Iterator<Attribute>,
out: XMLEventWriter,
localEndpoint: EndpointDescriptor
) {
var valueName: String? = null
run {
while (attributes.hasNext()) {
val attr = attributes.next()
val attrName = attr.name.localPart
if ("value" == attrName) {
valueName = attr.value
}
}
}
run {
val ev = `in`.nextEvent()
while (!ev.isEndElement) {
if (ev.isStartElement) {
throw MessagingFormatException("Violation of schema")
}
if (ev.isAttribute) {
val attr = ev as Attribute
val attrName = attr.name.localPart
if ("value" == attrName) {
valueName = attr.value
}
}
}
}
if (valueName != null) {
val xef = XMLEventFactory.newInstance()
if ("handle" == valueName) {
out.add(xef.createCharacters(java.lang.Long.toString(nodeInstance.getHandleValue())))
} else if ("endpoint" == valueName) {
val qname1 = QName(Constants.MY_JBI_NS_STR, "endpointDescriptor", "")
val namespaces = listOf(
xef.createNamespace(
"",
Constants.MY_JBI_NS_STR
)
)
out.add(xef.createStartElement(qname1, null, namespaces.iterator()))
run {
// EndpointDescriptor localEndpoint = nodeInstance.getProcessInstance().getEngine().getLocalEndpoint();
out.add(xef.createAttribute("serviceNS", localEndpoint.serviceName!!.namespaceURI))
out.add(xef.createAttribute("serviceLocalName", localEndpoint.serviceName!!.localPart))
out.add(xef.createAttribute("endpointName", localEndpoint.endpointName))
out.add(
xef.createAttribute(
"endpointLocation",
localEndpoint.endpointLocation!!.toString()
)
)
}
out.add(xef.createEndElement(qname1, namespaces.iterator()))
}
} else {
throw MessagingFormatException("Missing parameter name")
}
}
@Throws(XMLStreamException::class)
private fun writeAttribute(
nodeInstance: ProcessNodeInstance<*>,
`in`: XMLEventReader,
attributes: Iterator<Attribute>,
out: XMLEventWriter
) {
var valueName: String? = null
var paramName: String? = null
run {
while (attributes.hasNext()) {
val attr = attributes.next()
val attrName = attr.name.localPart
if ("value" == attrName) {
valueName = attr.value
} else if ("name" == attrName) {
paramName = attr.value
}
}
}
run {
val ev = `in`.nextEvent()
while (!ev.isEndElement) {
if (ev.isStartElement) {
throw MessagingFormatException("Violation of schema")
}
if (ev.isAttribute) {
val attr = ev as Attribute
val attrName = attr.name.localPart
if ("value" == attrName) {
valueName = attr.value
} else if ("name" == attrName) {
paramName = attr.value
}
}
}
}
if (valueName != null) {
val xef = XMLEventFactory.newInstance()
when (valueName) {
"handle" -> out.add(
xef.createAttribute(paramName ?: "handle", nodeInstance.getHandleValue().toString())
)
"owner" -> out.add(xef.createAttribute(paramName ?: "owner", nodeInstance.owner.name))
"instancehandle" -> out.add(
xef.createAttribute(paramName ?: "instancehandle", nodeInstance.owner.name)
)
}
} else {
throw MessagingFormatException("Missing parameter name")
}
}
}
}
override fun destroy() {
MessagingRegistry.getMessenger().unregisterEndpoint(this)
}
override fun getServletInfo(): String {
return "ServletProcessEngine"
}
@TestOnly
protected fun init(engine: ProcessEngine<TR, *>) {
processEngine = engine
}
@Throws(ServletException::class)
override fun init(config: ServletConfig) {
super.init(config)
val hostname: String? = config.getInitParameter("hostname") ?: "localhost"
val port = config.getInitParameter("port")
val localURL: URI
localURL = when (port) {
null -> URI.create("http://" + hostname + config.servletContext.contextPath)
else -> URI.create("http://" + hostname + ":" + port + config.servletContext.contextPath)
}
messageService = MessageService(asEndpoint(localURL))
val logger = Logger.getLogger(ServletProcessEngine::class.java.name)
processEngine = ProcessEngine.newInstance(messageService, logger) as ProcessEngine<TR, *>
MessagingRegistry.getMessenger().registerEndpoint(this)
}
/**
* Get the list of all process models in the engine. This will be limited to user owned ones. The list will contain only
* a summary of each model including name, id and uuid, not the content.
*
* XXX check security properly.
*/
@RestMethod(method = HttpMethod.GET, path = "/processModels")
fun getProcesModelRefs(
@RestParam(
type = RestParamType.PRINCIPAL
) user: Principal
): SerializableData<List<IProcessModelRef<*, *>>> = translateExceptions {
processEngine.startTransaction().use { transaction ->
val processModels = processEngine.getProcessModels(transaction.readableEngineData, user)
val list = ArrayList<IProcessModelRef<ExecutableProcessNode, ExecutableProcessModel>>()
for (pm in processModels) {
list.add(pm.withPermission().ref)
}
return transaction.commitSerializable(list, REFS_TAG)
}
}
/**
* Get the full process model content for the model with the given handle.
* @param handle The handle of the process model
* @param user The user whose permissions are verified
* @return The process model
* @throws FileNotFoundException When the model does not exist. This is translated to a 404 error in http.
*/
@RestMethod(method = HttpMethod.GET, path = "/processModels/\${handle}")
fun getProcessModel(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
): ExecutableProcessModel = translateExceptions {
try {
processEngine.startTransaction().use { transaction ->
val handle1 = if (handle < 0) Handle.invalid<SecureObject<ExecutableProcessModel>>() else Handle(handle)
processEngine.invalidateModelCache(handle1)
return transaction.commit<ExecutableProcessModel>(
processEngine.getProcessModel(transaction.readableEngineData, handle1, user)
?: throw FileNotFoundException()
)
}
} catch (e: NullPointerException) {
throw HandleNotFoundException("Process handle invalid", e)
}
}
/**
* Update the process model with the given handle.
* @param handle The model handle
* @param attachment The actual new model
* @param user The user performing the update. This will be verified against ownership and permissions
* @return A reference to the model. This may include a newly generated uuid if not was provided.
* @throws IOException
*/
@RestMethod(method = HttpMethod.POST, path = "/processModels/\${handle}")
@Throws(IOException::class)
fun updateProcessModel(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(name = "processUpload", type = RestParamType.ATTACHMENT) attachment: DataHandler,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
): ProcessModelRef<*, *> = translateExceptions {
val builder = XmlStreaming.deSerialize(attachment.inputStream, XmlProcessModel.Builder::class.java)
return updateProcessModel(handle, builder, user)
}
/**
* Update the process model with the given handle.
* @param handle The model handle
* @param processModelBuilder The actual new model
* @param user The user performing the update. This will be verified against ownership and permissions
* @return A reference to the model. This may include a newly generated uuid if not was provided.
*/
@WebMethod(operationName = "updateProcessModel")
fun updateProcessModel(
@WebParam(name = "handle") handle: Long,
@WebParam(
name = "processModel",
mode = Mode.IN
) processModelBuilder: RootProcessModel.Builder?,
@WebParam(name = "principal", mode = Mode.IN, header = true) @RestParam(
type = RestParamType.PRINCIPAL
) user: Principal?
)
: ProcessModelRef<*, *> = translateExceptions {
if (user == null) throw AuthenticationNeededException("There is no user associated with this request")
if (processModelBuilder != null) {
processModelBuilder.handle = handle
try {
processEngine.startTransaction().use { transaction ->
val updatedRef = processEngine.updateProcessModel(
transaction, if (handle < 0) Handle.invalid() else Handle(handle),
ExecutableProcessModel(processModelBuilder),
user
)
val update2 = ProcessModelRef.get(updatedRef)
return transaction.commit(update2)
}
} catch (e: SQLException) {
logger.log(Level.WARNING, "Error updating process model", e)
throw HttpResponseException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e)
}
}
throw HttpResponseException(HttpServletResponse.SC_BAD_REQUEST, "The posted process model is not valid")
}
/**
* Add a process model to the system.
* @param attachment The process model to add.
* @param owner The creator/owner of the model.
* @return A reference to the model with handle and a new uuid if none was provided.
*/
@RestMethod(method = HttpMethod.POST, path = "/processModels")
@Throws(IOException::class)
fun postProcessModel(
@RestParam(name = "processUpload", type = RestParamType.ATTACHMENT) attachment: DataHandler,
@RestParam(type = RestParamType.PRINCIPAL) owner: Principal
): ProcessModelRef<*, *>? = translateExceptions {
val processModel = XmlStreaming.deSerialize(attachment.inputStream, XmlProcessModel.Builder::class.java)
return postProcessModel(processModel, owner)
}
/**
* Add a process model to the system.
* @param processModel The process model to add.
* @param owner The creator/owner of the model.
* @return A reference to the model with handle and a new uuid if none was provided.
*/
@WebMethod(operationName = "postProcessModel")
fun postProcessModel(
@WebParam(name = "processModel", mode = Mode.IN) processModel: XmlProcessModel.Builder?,
@RestParam(type = RestParamType.PRINCIPAL)
@WebParam(name = "principal", mode = Mode.IN, header = true) owner: Principal?
)
: ProcessModelRef<*, *>? = translateExceptions {
if (owner == null) throw AuthenticationNeededException("There is no user associated with this request")
if (processModel != null) {
processModel.handle = -1 // The handle cannot be set
processEngine.startTransaction().use { transaction ->
val newModelRef = processEngine.addProcessModel(transaction, processModel, owner)
return transaction.commit(ProcessModelRef.get(newModelRef))
}
}
return null
}
/**
* Rename the given process model.
* @param handle The handle to the model
* @param name The new name
* @param user The user performing the action.
*/
@RestMethod(method = HttpMethod.POST, path = "/processModels/\${handle}")
@Throws(FileNotFoundException::class)
fun renameProcess(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(name = "name", type = RestParamType.QUERY) name: String,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
) {
processEngine.renameProcessModel(user, if (handle < 0) Handle.invalid() else Handle(handle), name)
}
/**
* Delete the process model.
* @param handle The handle of the process model to delete
* @param user A user with permission to delete the model.
*/
@RestMethod(method = HttpMethod.DELETE, path = "/processModels/\${handle}")
fun deleteProcess(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
) = translateExceptions {
processEngine.startTransaction().use { transaction ->
if (!processEngine.removeProcessModel(
transaction,
if (handle < 0) Handle.invalid() else Handle(handle),
user
)) {
throw HttpResponseException(HttpServletResponse.SC_NOT_FOUND, "The given process does not exist")
}
transaction.commit()
}
}
/**
* Create a new process instance and start it.
*
* @param handle The handle of the process to start.
* @param name The name that will allow the user to remember the instance. If `null` a name will
* be assigned. This name has no semantic meaning.
* @param owner The owner of the process instance. (Who started it).
* @return A handle to the process
*/
@WebMethod
@RestMethod(method = HttpMethod.POST, path = "/processModels/\${handle}", query = ["op=newInstance"])
fun startProcess(
@WebParam(name = "handle") @RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@WebParam(name = "name") @RestParam(name = "name", type = RestParamType.QUERY) name: String?,
@WebParam(name = "uuid") @RestParam(name = "uuid", type = RestParamType.QUERY) uuid: String?,
@WebParam(name = "owner", header = true) @RestParam(type = RestParamType.PRINCIPAL) owner: Principal
): SerializableData<HProcessInstance> = translateExceptions {
processEngine.startTransaction().use { transaction ->
val uuid: UUID = uuid?.let { UUID.fromString(it) } ?: UUID.randomUUID()
return transaction.commitSerializable(
processEngine.startProcess(
transaction, owner, if (handle < 0) Handle.invalid() else Handle(handle),
name ?: "<unnamed>", uuid, null
),
ProcessInstance.HANDLEELEMENTNAME
)
}
}
/**
* Get a list of all process instances owned by the current user. This will provide a summary list, providing a subset.
* of information from the process instance.
* @param owner The user.
* @return A list of process instances.
*/
@RestMethod(method = HttpMethod.GET, path = "/processInstances")
@XmlElementWrapper(name = "processInstances", namespace = Constants.PROCESS_ENGINE_NS)
fun getProcesInstanceRefs(@RestParam(type = RestParamType.PRINCIPAL) owner: Principal?)
: SerializableData<Collection<ProcessInstanceRef>> = translateExceptions {
if (owner == null) throw AuthenticationNeededException()
processEngine.startTransaction().use { transaction ->
val list = ArrayList<ProcessInstanceRef>()
for (pi in processEngine.getOwnedProcessInstances(transaction, owner)) {
list.add(pi.ref)
}
transaction.commitSerializable(list, INSTANCEREFS_TAG)
}
}
/**
* Get the given process instance.
* @param handle The handle of the instance.
* @param user A user with permission to see the model.
* @return The full process instance.
*/
@RestMethod(method = HttpMethod.GET, path = "/processInstances/\${handle}")
fun getProcessInstance(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal?
): SerializableData<ProcessInstance> = translateExceptions {
processEngine.startTransaction().use { transaction ->
return transaction.commitSerializable(
processEngine.getProcessInstance(
transaction,
if (handle < 0) Handle.invalid() else Handle(handle),
user!!
)
)
}
}
/**
* Cause the process instance state to be re-evaluated. For failed service invocations, this will cause the server to
* try again.
* @param handle The handle of the instance
* @param user A user with appropriate permissions.
* @return A string indicating success.
*/
@RestMethod(method = HttpMethod.GET, path = "/processInstances/\${handle}", query = ["op=tickle"])
@Throws(FileNotFoundException::class)
fun tickleProcessInstance(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
): String = translateExceptions {
processEngine.startTransaction().use { transaction ->
transaction.commit(processEngine.tickleInstance(transaction, handle, user))
return "success"
}
}
/**
* Cancel the process instance execution. This will cause all aspects of the instance to be cancelled. Note that this
* cannot undo the past.
* @param handle The instance to cancel
* @param user A user with permission to cancel the instance.
* @return The instance that was cancelled.
*/
@RestMethod(method = HttpMethod.DELETE, path = "/processInstances/\${handle}")
fun cancelProcessInstance(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
): ProcessInstance = translateExceptions {
processEngine.startTransaction().use { transaction ->
return transaction.commit(
processEngine.cancelInstance(transaction, if (handle < 0) Handle.invalid() else Handle(handle), user)
)
}
}
/**
* Get the data for a specific task.
* @param handle The handle
* @param user A user with appropriate permissions
* @return The node instance.
* @throws FileNotFoundException
* @throws SQLException
* @throws XmlException
*/
@WebMethod(operationName = "getProcessNodeInstance")
fun getProcessNodeInstanceSoap(
@WebParam(name = "handle", mode = Mode.IN) handle: Long,
@WebParam(name = "user", mode = Mode.IN) user: Principal
): XmlProcessNodeInstance? = translateExceptions {
return getProcessNodeInstance(handle, user)
}
/**
* Get the information for a specific task.
* @param handle The handle of the task
* @param user A user with appropriate permissions
* @return the task
* @throws FileNotFoundException
* @throws SQLException
* @throws XmlException
*/
@RestMethod(method = HttpMethod.GET, path = "/tasks/\${handle}")
fun getProcessNodeInstance(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
): XmlProcessNodeInstance? = translateExceptions {
processEngine.startTransaction().use { transaction ->
val nodeInstance = processEngine.getNodeInstance(
transaction,
if (handle < 0) Handle.invalid() else Handle(handle),
user
)
?: return null
return transaction.commit(
nodeInstance.toSerializable(transaction.readableEngineData, messageService.localEndpoint)
)
}
}
/**
* Update the state of a task.
* @param handle Handle of the task to update
* @param newState The new state
* @param user A user with appropriate permissions
* @return the new state of the task. This may be different than requested, for example due to engine semantics. (either further, or no change at all)
*/
@WebMethod(operationName = "updateTaskState")
@Throws(FileNotFoundException::class)
fun updateTaskStateSoap(
@WebParam(name = "handle", mode = Mode.IN) handle: Long,
@WebParam(name = "state", mode = Mode.IN) newState: NodeInstanceState,
@WebParam(name = "user", mode = Mode.IN) user: Principal
): NodeInstanceState = translateExceptions {
return updateTaskState(handle, newState, user)
}
/**
* Update the state of a task.
* @param handle Handle of the task to update
* @param newState The new state
* @param user A user with appropriate permissions
* @return the new state of the task. This may be different than requested, for example due to engine semantics. (either further, or no change at all)
*/
@RestMethod(method = HttpMethod.POST, path = "/tasks/\${handle}", query = ["state"])
fun updateTaskState(
@RestParam(name = "handle", type = RestParamType.VAR) handle: Long,
@RestParam(name = "state", type = RestParamType.QUERY) newState: NodeInstanceState,
@RestParam(type = RestParamType.PRINCIPAL) user: Principal
): NodeInstanceState = translateExceptions {
try {
processEngine.startTransaction().use { transaction ->
return transaction.commit(
processEngine.updateTaskState(
transaction, if (handle < 0) Handle.invalid() else Handle(handle), newState,
user
)
)
}
} catch (e: SQLException) {
throw HttpResponseException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e)
}
}
/**
* finish a task. Process aware services will need to call this to signal completion.
* @param handle Handle of the task to update
* @param payload An XML document that is the "result" of the service.
* @param user A user with appropriate permissions
* @return the new state of the task. This may be different than requested, for example due to engine semantics. (either further, or no change at all)
*/
@WebMethod(operationName = "finishTask")
@RestMethod(method = HttpMethod.POST, path = "/tasks/\${handle}", query = ["state=Complete"])
fun finishTask(
@WebParam(name = "handle", mode = Mode.IN)
@RestParam(name = "handle", type = RestParamType.VAR)
handle: Long,
@WebParam(name = "payload", mode = Mode.IN)
@RestParam(name = "payload", type = RestParamType.QUERY)
payload: Node,
@RestParam(type = RestParamType.PRINCIPAL)
@WebParam(name = "principal", mode = Mode.IN, header = true)
user: Principal
)
: NodeInstanceState = translateExceptions {
val payloadNode = DomUtil.nodeToFragment(payload)
processEngine.startTransaction().use { transaction ->
return transaction.commit(
processEngine.finishTask(
transaction, if (handle < 0) Handle.invalid() else Handle(handle), payloadNode,
user
).state
)
}
}
/**
* Handle the completing of sending a message and receiving some sort of
* reply. If the reply is an ActivityResponse message we handle that
* specially.
* @throws SQLException
*/
@OptIn(ProcessInstanceStorage::class)
@Throws(FileNotFoundException::class)
fun onMessageCompletion(
future: Future<out DataSource>,
handle: Handle<SecureObject<ProcessNodeInstance<*>>>,
owner: Principal
) = translateExceptions {
// XXX do this better
if (future.isCancelled) {
processEngine.startTransaction().use { transaction ->
processEngine.cancelledTask(transaction, handle, owner)
transaction.commit()
}
} else {
try {
val result = future.get()
processEngine.startTransaction().use { transaction ->
val inst = processEngine.getNodeInstance(transaction, handle, SYSTEMPRINCIPAL)
?: throw HttpResponseException(
404,
"The process node with handle $handle does not exist or is not visible"
)
assert(inst.state === NodeInstanceState.Pending)
if (inst.state === NodeInstanceState.Pending) {
val processInstance = transaction.readableEngineData.instance(
inst.hProcessInstance
).withPermission()
processInstance.update(transaction.writableEngineData) {
updateChild(inst) {
state = NodeInstanceState.Sent
}
}
}
transaction.commit()
}
try {
val domResult = DomUtil.tryParseXml(result.inputStream) ?: throw HttpResponseException(
HttpServletResponse.SC_BAD_REQUEST,
"Content is not an XML document"
)
var rootNode: Element? = domResult.documentElement
// If we are seeing a Soap Envelope, if there is an activity response in the header treat that as the root node.
if (Envelope.NAMESPACE == rootNode!!.namespaceURI && Envelope.ELEMENTLOCALNAME == rootNode.localName) {
val header = DomUtil.getFirstChild(
rootNode, Envelope.NAMESPACE,
org.w3.soapEnvelope.Header.ELEMENTLOCALNAME
)
if (header != null) {
rootNode = DomUtil.getFirstChild(
header, Constants.PROCESS_ENGINE_NS,
ActivityResponse.ELEMENTLOCALNAME
)
}
}
if (rootNode != null) {
// If we receive an ActivityResponse, treat that specially.
if (Constants.PROCESS_ENGINE_NS == rootNode.namespaceURI && ActivityResponse.ELEMENTLOCALNAME == rootNode.localName) {
val taskStateAttr = rootNode.getAttribute(ActivityResponse.ATTRTASKSTATE)
try {
processEngine.startTransaction().use { transaction ->
val nodeInstanceState = NodeInstanceState.valueOf(taskStateAttr)
processEngine.updateTaskState(transaction, handle, nodeInstanceState, owner)
transaction.commit()
return
}
} catch (e: NullPointerException) {
e.printStackTrace()
// ignore
} catch (e: IllegalArgumentException) {
processEngine.startTransaction().use { transaction ->
processEngine.errorTask(transaction, handle, e, owner)
transaction.commit()
}
}
}
} else {
processEngine.startTransaction().use { transaction ->
// XXX By default assume that we have finished the task
processEngine.finishedTask(transaction, handle, result, owner)
transaction.commit()
}
}
} catch (e: NullPointerException) {
// ignore
} catch (e: IOException) {
// It's not xml or has more than one xml element ignore that and fall back to handling unknown services
}
} catch (e: ExecutionException) {
logger.log(Level.INFO, "Task $handle: Error in messaging", e.cause)
processEngine.startTransaction().use { transaction ->
processEngine.errorTask(transaction, handle, e.cause ?: e, owner)
transaction.commit()
}
} catch (e: InterruptedException) {
logger.log(Level.INFO, "Task $handle: Interrupted", e)
processEngine.startTransaction().use { transaction ->
processEngine.cancelledTask(transaction, handle, owner)
transaction.commit()
}
}
}
}
override fun isSameService(other: EndpointDescriptor?): Boolean {
return Constants.PROCESS_ENGINE_NS == other!!.serviceName!!.namespaceURI &&
SERVICE_LOCALNAME == other.serviceName!!.localPart &&
endpointName == other.endpointName
}
override fun initEndpoint(config: ServletConfig) {
// We know our config, don't do anything.
}
protected open fun setLocalEndpoint(localURL: URI) {
messageService.localEndpoint = asEndpoint(localURL)
}
private fun asEndpoint(localURL: URI): EndpointDescriptorImpl {
return EndpointDescriptorImpl(serviceName, endpointName, localURL)
}
companion object {
private const val serialVersionUID = -6277449163953383974L
@Suppress("MemberVisibilityCanBePrivate")
const val SERVICE_NS = Constants.PROCESS_ENGINE_NS
const val SERVICE_LOCALNAME = "ProcessEngine"
@Suppress("unused")
@JvmStatic
val SERVICE_QNAME = QName(SERVICE_NS, SERVICE_LOCALNAME)
/*
* Methods inherited from JBIProcessEngine
*/
internal val logger: Logger
get() {
val logger = Logger.getLogger(ServletProcessEngine::class.java.name)
logger.level = Level.ALL
return logger
}
private val REFS_TAG = QName(SERVICE_NS, "processModels")
private val INSTANCEREFS_TAG = QName(SERVICE_NS, "processInstances")
}
}
@OptIn(ExperimentalContracts::class)
internal inline fun <E : GenericEndpoint, R> E.translateExceptions(body: E.() -> R): R {
contract {
callsInPlace(body, InvocationKind.EXACTLY_ONCE)
}
try {
return body()
} catch (e: HandleNotFoundException) {
throw HttpResponseException(HttpServletResponse.SC_NOT_FOUND, e)
} catch (e: SQLException) {
ServletProcessEngine.logger.log(Level.WARNING, "Error getting process model references", e)
throw HttpResponseException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e)
}
}
| ProcessEngine/servlet/src/main/java/nl/adaptivity/process/engine/servlet/ServletProcessEngine.kt | 3481163211 |
package de.westnordost.streetcomplete.data.visiblequests
import de.westnordost.streetcomplete.data.Database
import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.Columns.QUEST_PRESET_ID
import javax.inject.Inject
import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.Columns.QUEST_TYPE
import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.Columns.VISIBILITY
import de.westnordost.streetcomplete.data.visiblequests.VisibleQuestTypeTable.NAME
/** Stores which quest types are visible by user selection and which are not */
class VisibleQuestTypeDao @Inject constructor(private val db: Database) {
fun put(presetId: Long, questTypeName: String, visible: Boolean) {
db.replace(NAME, listOf(
QUEST_PRESET_ID to presetId,
QUEST_TYPE to questTypeName,
VISIBILITY to if (visible) 1 else 0
))
}
fun put(presetId: Long, questTypeNames: Iterable<String>, visible: Boolean) {
val vis = if (visible) 1 else 0
db.replaceMany(NAME,
arrayOf(QUEST_PRESET_ID, QUEST_TYPE, VISIBILITY),
questTypeNames.map { arrayOf(presetId, it, vis) }
)
}
fun get(presetId: Long, questTypeName: String): Boolean =
db.queryOne(NAME,
columns = arrayOf(VISIBILITY),
where = "$QUEST_PRESET_ID = ? AND $QUEST_TYPE = ?",
args = arrayOf(presetId, questTypeName)
) { it.getInt(VISIBILITY) != 0 } ?: true
fun getAll(presetId: Long): MutableMap<String, Boolean> {
val result = mutableMapOf<String, Boolean>()
db.query(NAME, where = "$QUEST_PRESET_ID = $presetId") { cursor ->
val questTypeName = cursor.getString(QUEST_TYPE)
val visible = cursor.getInt(VISIBILITY) != 0
result[questTypeName] = visible
}
return result
}
fun clear(presetId: Long) {
db.delete(NAME, where = "$QUEST_PRESET_ID = $presetId")
}
}
| app/src/main/java/de/westnordost/streetcomplete/data/visiblequests/VisibleQuestTypeDao.kt | 575126374 |
package epsz.mapalarm.gateways
import com.google.android.gms.location.LocationServices
import com.mapalarm.UserSituationGateway
import com.mapalarm.datatypes.Position
import com.mapalarm.datatypes.UserSituation
class GoogleApiUserSituationGateway(val apiConnector: GoogleApiConnector) : UserSituationGateway {
override fun getSituation(callback: (UserSituation) -> Unit, onError: () -> Unit) {
apiConnector.doWithGoogleClient( { returnLastLocation(callback, onError) }, onError)
}
private fun returnLastLocation(callback: (UserSituation) -> Unit, onError: () -> Unit) {
var location = LocationServices.FusedLocationApi.getLastLocation(apiConnector.googleApiClient)
if (location != null)
callback(UserSituation(Position(location.latitude, location.longitude)))
else
onError()
}
} | app/src/main/java/epsz/mapalarm/gateways/GoogleApiUserSituationGateway.kt | 4121530122 |
package com.naosim.rtm.domain.repository
import com.naosim.rtm.domain.model.auth.Token
import com.naosim.rtm.domain.model.timeline.TimelineId
interface RtmRepository: RtmAuthRepository, RtmTaskRepository {
fun createTimeline(token: Token): TimelineId
} | src/main/java/com/naosim/rtm/domain/repository/RtmRepository.kt | 2240819734 |
package name.kropp.intellij.makefile
import com.intellij.application.options.*
import com.intellij.psi.codeStyle.*
class MakefileLangCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() {
override fun customizeDefaults(commonSettings: CommonCodeStyleSettings, indentOptions: CommonCodeStyleSettings.IndentOptions) {
indentOptions.TAB_SIZE = 4
indentOptions.USE_TAB_CHARACTER = true
}
override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) {
if (settingsType == SettingsType.INDENT_SETTINGS) {
consumer.showStandardOptions("TAB_SIZE")
}
}
override fun getCodeSample(settingsType: SettingsType): String {
return """# Simple Makefile
include make.mk
all: hello
GCC = gcc \
-O2
<target>.o.c</target>:
ifeq ($(FOO),'bar')
${'\t'}$(GCC) -c qwe \
-Wall
else
${'\t'}echo "Hello World"
endif"""
}
override fun getIndentOptionsEditor(): IndentOptionsEditor = IndentOptionsEditor()
override fun getLanguage() = MakefileLanguage
} | src/main/kotlin/name/kropp/intellij/makefile/MakefileLangCodeStyleSettingsProvider.kt | 2976977355 |
package moe.tlaster.openween
import android.content.Context
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("moe.tlaster.openween", appContext.packageName)
}
}
| app/src/androidTest/java/moe/tlaster/openween/ExampleInstrumentedTest.kt | 401126270 |
package com.github.pockethub.android.ui.item.news
import android.view.View
import androidx.core.text.buildSpannedString
import com.github.pockethub.android.ui.view.OcticonTextView
import com.github.pockethub.android.util.AvatarLoader
import com.meisolsson.githubsdk.model.GitHubEvent
import com.meisolsson.githubsdk.model.payload.CreatePayload
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.news_item.*
class CreateEventItem(
avatarLoader: AvatarLoader,
gitHubEvent: GitHubEvent
) : NewsItem(avatarLoader, gitHubEvent) {
override fun bind(holder: ViewHolder, position: Int) {
super.bind(holder, position)
holder.tv_event_icon.text = OcticonTextView.ICON_CREATE
holder.tv_event.text = buildSpannedString {
val context = holder.root.context
boldActor(context, this, gitHubEvent)
val payload = gitHubEvent.payload() as CreatePayload?
val refType: String? = payload?.refType()?.name?.toLowerCase()
append(" created $refType ")
if ("repository" != refType) {
append("${payload?.ref()} at ")
boldRepo(context, this, gitHubEvent)
} else {
boldRepoName(context, this, gitHubEvent)
}
}
holder.tv_event_details.visibility = View.GONE
}
}
| app/src/main/java/com/github/pockethub/android/ui/item/news/CreateEventItem.kt | 2583397411 |
package de.devmil.paperlaunch.locale
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.Toolbar
import de.devmil.paperlaunch.R
class EditSettingActivity : Activity() {
private var btnOk: Button? = null
private var rbEnable: RadioButton? = null
private var rbDisable: RadioButton? = null
private var toolbar: Toolbar? = null
private var imgResult: ImageView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_edit_setting)
btnOk = findViewById(R.id.activity_edit_setting_btn_ok)
rbEnable = findViewById(R.id.activity_edit_setting_rbEnable)
rbDisable = findViewById(R.id.activity_edit_setting_rbDisable)
toolbar = findViewById(R.id.activity_edit_settings_toolbar)
imgResult = findViewById(R.id.activity_edit_setting_img_result)
setActionBar(toolbar)
var isEnabled = true
if(intent.hasExtra(LocaleConstants.EXTRA_BUNDLE)) {
val localeBundle = intent.getBundleExtra(LocaleConstants.EXTRA_BUNDLE)
if(LocaleBundle.isValid(localeBundle)) {
isEnabled = LocaleBundle.from(localeBundle).isEnabled
}
}
rbEnable?.isChecked = isEnabled
rbDisable?.isChecked = !isEnabled
rbEnable?.setOnCheckedChangeListener { _, _ ->
updateResultImage()
}
rbDisable?.setOnCheckedChangeListener { _, _ ->
updateResultImage()
}
btnOk?.setOnClickListener {
rbEnable?.let { itRbEnable ->
val localeBundle = LocaleBundle(itRbEnable.isChecked)
val resultIntent = Intent()
resultIntent.putExtra(LocaleConstants.EXTRA_BUNDLE, localeBundle.toBundle())
val stringResource =
if(itRbEnable.isChecked)
R.string.activity_edit_setting_description_enable
else
R.string.activity_edit_setting_description_disable
resultIntent.putExtra(LocaleConstants.EXTRA_BLURB, getString(stringResource))
setResult(RESULT_OK, resultIntent)
}
finish()
}
updateResultImage()
}
private fun updateResultImage() {
val isEnabled = rbEnable?.isChecked ?: false
imgResult?.setImageResource(if(isEnabled) R.mipmap.ic_play_arrow_black_24dp else R.mipmap.ic_pause_black_24dp)
}
}
| app/src/main/java/de/devmil/paperlaunch/locale/EditSettingActivity.kt | 1841553127 |
package com.thunderclouddev.changelogs.logging
import com.crashlytics.android.Crashlytics
import com.thunderclouddev.changelogs.preferences.BuildConfig
import com.thunderclouddev.changelogs.preferences.UserPreferences
/**
* Created by david on 5/5/17.
*/
class CrashlyticsVariableLogger(private val preferences: UserPreferences,
private val buildConfig: BuildConfig) : VariableLogger.Logger {
override fun storeBoolVariable(key: String, value: Boolean) {
if (buildConfig.enableCrashlytics && preferences.allowAnonymousLogging) {
Crashlytics.setBool(key, value)
}
}
override fun storeDoubleVariable(key: String, value: Double) {
if (buildConfig.enableCrashlytics && preferences.allowAnonymousLogging) {
Crashlytics.setDouble(key, value)
}
}
override fun storeFloatVariable(key: String, value: Float) {
if (buildConfig.enableCrashlytics && preferences.allowAnonymousLogging) {
Crashlytics.setFloat(key, value)
}
}
override fun storeIntVariable(key: String, value: Int) {
if (buildConfig.enableCrashlytics && preferences.allowAnonymousLogging) {
Crashlytics.setInt(key, value)
}
}
override fun storeStringVariable(key: String, value: String) {
if (buildConfig.enableCrashlytics && preferences.allowAnonymousLogging) {
Crashlytics.setString(key, value)
}
}
} | app/src/dist/java/com/thunderclouddev/changelogs/logging/CrashlyticsVariableLogger.kt | 2262730612 |
package nl.hannahsten.texifyidea.inspections.latex.codestyle
import nl.hannahsten.texifyidea.file.LatexFileType
import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase
import nl.hannahsten.texifyidea.lang.alias.CommandManager
import nl.hannahsten.texifyidea.psi.LatexKeyvalPair
import nl.hannahsten.texifyidea.settings.conventions.LabelConventionType
import nl.hannahsten.texifyidea.settings.conventions.TexifyConventionsScheme
import nl.hannahsten.texifyidea.testutils.updateConvention
import nl.hannahsten.texifyidea.util.childrenOfType
class LatexMissingLabelInspectionTest : TexifyInspectionTestBase(LatexMissingLabelInspection()) {
override fun setUp() {
super.setUp()
// reset to default
myFixture.updateConvention { s -> s.currentScheme = TexifyConventionsScheme() }
}
override fun getTestDataPath(): String {
return "test/resources/inspections/latex/missinglabel"
}
fun `test missing label warnings`() {
myFixture.configureByFile("MissingLabelWarnings.tex")
myFixture.checkHighlighting(false, false, true, false)
}
fun `test no missing label warning if convention is disabled`() {
myFixture.updateConvention { s ->
s.getLabelConvention("\\section", LabelConventionType.COMMAND)!!.enabled = false
s.getLabelConvention("figure", LabelConventionType.ENVIRONMENT)!!.enabled = false
}
myFixture.configureByText(
LatexFileType,
"""
\begin{document}
\section{some section}
\begin{figure}
\end{figure}
\end{document}
""".trimIndent()
)
myFixture.checkHighlighting(false, false, true, false)
}
fun `test missing figure label warnings`() = testHighlighting(
"""
\begin{document}
% figure without label
<weak_warning descr="Missing label">\begin{figure}
\end{figure}</weak_warning>
% figure with label
\begin{figure}
\label{fig:figure-label}
\end{figure}
% figure with label in caption
\begin{figure}
\caption{Some text \label{fig:figure-caption-label}}
\end{figure}
\end{document}
""".trimIndent()
)
fun `test missing section label no warnings (custom label command)`() {
myFixture.configureByText(
LatexFileType,
"""
\newcommand{\mylabels}[2]{\section{#1}\label{sec:#2}}
\newcommand{\mylabel}[1]{\label{sec:#1}}
\section{some sec}\mylabel{some-sec}
""".trimIndent()
)
CommandManager.updateAliases(setOf("\\label"), project)
myFixture.checkHighlighting(false, false, true, false)
}
fun `test quick fix in figure with caption`() = testQuickFix(
before = """
\begin{document}
\begin{figure}
\caption{Some Caption}
\end{figure}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\begin{figure}
\caption{Some Caption}\label{fig:figure}<caret>
\end{figure}
\end{document}
""".trimIndent()
)
fun `test label name generation`() = testQuickFix(
before = """
\section{~Ação –função}
""".trimIndent(),
after = """
\section{~Ação –função}\label{sec:acao-funcao}
""".trimIndent(),
numberOfFixes = 2
)
fun `test quick fix in figure`() = testQuickFix(
before = """
\begin{document}
\begin{figure}
\end{figure}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\begin{figure}
\label{fig:figure}<caret>
\end{figure}
\end{document}
""".trimIndent()
)
fun `test missing listings label warnings`() = testHighlighting(
"""
\usepackage{listings}
\begin{document}
<weak_warning descr="Missing label">\begin{lstlisting}
\end{lstlisting}</weak_warning>
\begin{lstlisting}[label=somelabel]
\end{lstlisting}
\begin{lstlisting}[label={label with spaces}]
\end{lstlisting}
\end{document}
""".trimIndent()
)
fun `test listings label no warnings`() = testHighlighting(
"""
\usepackage{listings}
\begin{document}
\begin{lstlisting}[language=Python, label=somelabel]
\end{lstlisting}
\begin{lstlisting}[label={label with spaces}]
\end{lstlisting}
\end{document}
""".trimIndent()
)
fun `test exam parts`() = testHighlighting(
"""
\documentclass{exam}
\begin{document}
\begin{questions}
\question
\begin{parts}
\part a
\end{parts}
\end{questions}
\end{document}
""".trimIndent()
)
fun `test quick fix in listings with no other parameters`() = testQuickFix(
before = """
\begin{document}
\begin{lstlisting}
\end{lstlisting}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\begin{lstlisting}[label={lst:lstlisting}]
\end{lstlisting}
\end{document}
""".trimIndent()
)
fun `test quick fix in listings when label already exists`() = testQuickFix(
before = """
\begin{document}
\label{lst:lstlisting}
\begin{lstlisting}
\end{lstlisting}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\label{lst:lstlisting}
\begin{lstlisting}[label={lst:lstlisting2}]
\end{lstlisting}
\end{document}
""".trimIndent()
)
fun `test quick fix in listings with other parameters`() {
testQuickFix(
before = """
\begin{document}
\begin{lstlisting}[someoption,otheroption={with value}]
\end{lstlisting}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\begin{lstlisting}[someoption,otheroption={with value},label={lst:lstlisting}]
\end{lstlisting}
\end{document}
""".trimIndent()
)
// Sometimes, errors in psi structure only show when initiating a WalkingState
myFixture.file.children.first().childrenOfType(LatexKeyvalPair::class)
}
fun `test fix all missing label problems in this file`() = testQuickFixAll(
before = """
\section{one}
\section{two}
""".trimIndent(),
after = """
\section{one}\label{sec:one}
\section{two}\label{sec:two}
""".trimIndent(),
quickFixName = "Add label for this command",
numberOfFixes = 4
)
fun `test missing lstinputlistings label warnings`() = testHighlighting(
"""
\usepackage{listings}
\begin{document}
<weak_warning descr="Missing label">\lstinputlisting{some/file}</weak_warning>
\lstinputlisting[label={lst:inputlisting}]{some/file}
\lstinputlisting[label={lst:inputlisting with spaces}]{some/file}
\end{document}
""".trimIndent()
)
fun `test lstinputlistings label no warnings`() = testHighlighting(
"""
\usepackage{listings}
\begin{document}
\lstinputlisting[label={lst:inputlisting}]{some/file}
\lstinputlisting[label={lst:inputlisting with spaces}]{some/file}
\end{document}
""".trimIndent()
)
fun `test quick fix in lstinputlistings with other parameters`() = testQuickFix(
before = """
\begin{document}
\lstinputlisting[someoption,otheroption={with value}]{some/file}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\lstinputlisting[someoption,otheroption={with value},label={lst:lstinputlisting}]{some/file}
\end{document}
""".trimIndent()
)
fun `test quick fix in lstinputlistings creates optional parameters at correct position`() = testQuickFix(
before = """
\begin{document}
\lstinputlisting{some/file}
\end{document}
""".trimIndent(),
after = """
\begin{document}
\lstinputlisting[label={lst:lstinputlisting}]{some/file}
\end{document}
""".trimIndent()
)
} | test/nl/hannahsten/texifyidea/inspections/latex/codestyle/LatexMissingLabelInspectionTest.kt | 638034957 |
package nl.hannahsten.texifyidea.structure.latex
import nl.hannahsten.texifyidea.TexifyIcons
import nl.hannahsten.texifyidea.psi.LatexCommands
import nl.hannahsten.texifyidea.structure.EditableHintPresentation
/**
* @author Hannah Schellekens
*/
class LatexPartPresentation(partCommand: LatexCommands) : EditableHintPresentation {
private val partName: String
private var hint = ""
init {
if (partCommand.commandToken.text != "\\part") {
throw IllegalArgumentException("command is no \\part-command")
}
this.partName = partCommand.requiredParameters[0]
}
override fun getPresentableText() = partName
override fun getLocationString() = hint
override fun getIcon(b: Boolean) = TexifyIcons.DOT_PART
override fun setHint(hint: String) {
this.hint = hint
}
} | src/nl/hannahsten/texifyidea/structure/latex/LatexPartPresentation.kt | 980036511 |
package net.twisterrob.test.jfixture.examples.journey
import java.time.Duration
interface JourneyView {
fun show(model: Model)
}
data class Model(
val journeyId: String,
val origin: String,
val destination: String,
val length: Duration,
val changeCount: Int,
val trainOnly: Boolean
)
interface DataSource<T> {
fun getById(id: String): Single<T>
}
class JourneyPresenter(
private val view: JourneyView,
private val dataSource: DataSource<Journey>,
private val mapper: (Journey) -> Model
) {
fun load(journeyId: String) {
dataSource
.getById(journeyId)
.map(mapper)
.subscribe { model ->
view.show(model)
}
}
}
class Single<T> private constructor(private val value: T) {
fun <R> map(mapper: (T) -> R): Single<R> =
Single(mapper(value))
fun subscribe(observer: (T) -> Unit) = observer(value)
companion object {
fun <T> just(value: T) = Single(value)
}
}
| JFixturePlayground/src/main/java/net/twisterrob/test/jfixture/examples/journey/JourneyPresenter.kt | 3457195126 |
package com.osacky.flank.gradle
import org.gradle.api.file.Directory
import org.gradle.api.file.ProjectLayout
import org.gradle.api.provider.Provider
internal val ProjectLayout.fladleDir: Provider<Directory>
get() = buildDirectory.dir("fladle")
| buildSrc/src/main/java/com/osacky/flank/gradle/ProjectExtensions.kt | 3782978476 |
/*
* Copyright (c) 2016 - 2019 Rui Zhao <[email protected]>
*
* This file is part of Easer.
*
* Easer 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.
*
* Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>.
*/
package ryey.easer
import android.content.Context
import org.acra.ReportField
import org.acra.data.CrashReportData
import org.acra.sender.ReportSender
import java.io.File
import java.io.FileWriter
import java.text.SimpleDateFormat
import java.util.*
class ErrorSender : ReportSender {
override fun send(context: Context, errorContent: CrashReportData) {
if (SettingsUtils.logging(context)) {
val dir = File(EaserApplication.LOG_DIR)
if (!dir.exists()) {
dir.mkdirs()
}
val dateFormat = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss")
val date = Date()
val filename = dateFormat.format(date) + ".log"
val reportFile = File(dir, filename)
FileWriter(reportFile).use {
for (elem in FIELDS) {
it.append("%s: %s\n".format(elem, errorContent.getString(elem)))
}
}
}
}
companion object {
val FIELDS = arrayOf(
ReportField.BUILD_CONFIG,
ReportField.APP_VERSION_CODE,
ReportField.USER_CRASH_DATE,
ReportField.ANDROID_VERSION,
ReportField.BRAND,
ReportField.PHONE_MODEL,
ReportField.PRODUCT,
ReportField.STACK_TRACE
)
}
} | app/src/main/java/ryey/easer/ErrorSender.kt | 1253957710 |
package net.gotev.uploadservice
import net.gotev.uploadservice.extensions.isASCII
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class ASCIIStringsTests {
@Test
fun `null string is not ASCII`() {
val testString: String? = null
assertFalse(testString.isASCII())
}
@Test
fun `empty string is not ASCII`() {
val testString = ""
assertFalse(testString.isASCII())
}
@Test
fun `numeric string is ASCII`() {
val testString = "1234567890.0123"
assertTrue(testString.isASCII())
}
@Test
fun `ASCII string`() {
val testString = "asa83254vhsdfu2385923asoasn2313214aSDDBCBXCB#++"
assertTrue(testString.isASCII())
}
@Test
fun `not ASCII string`() {
val testString = "ç°§éàìòù*?"
assertFalse(testString.isASCII())
}
@Test
fun `not ASCII string 2`() {
val testString = "ьАСДВВЕЯРТСДцзчьзц сдфсдф зфдсф сд"
assertFalse(testString.isASCII())
}
@Test
fun `not ASCII string 3`() {
val testString = "asa83254vhsdfu2385923asoasn2313214aSDDBCBXCB#++💪"
assertFalse(testString.isASCII())
}
}
| uploadservice/src/test/java/net/gotev/uploadservice/ASCIIStringsTests.kt | 3189310746 |
package tv.superawesome.sdk.publisher.common.components
import tv.superawesome.sdk.publisher.common.datasources.NetworkDataSourceType
import tv.superawesome.sdk.publisher.common.extensions.baseUrl
import tv.superawesome.sdk.publisher.common.models.*
import tv.superawesome.sdk.publisher.common.network.DataResult
interface AdProcessorType {
suspend fun process(placementId: Int, ad: Ad): DataResult<AdResponse>
}
class AdProcessor(
private val htmlFormatter: HtmlFormatterType,
private val vastParser: VastParserType,
private val networkDataSource: NetworkDataSourceType,
private val encoder: EncoderType,
) : AdProcessorType {
override suspend fun process(placementId: Int, ad: Ad): DataResult<AdResponse> {
val response = AdResponse(placementId, ad)
when (ad.creative.format) {
CreativeFormatType.ImageWithLink -> {
response.html = htmlFormatter.formatImageIntoHtml(ad)
response.baseUrl = ad.creative.details.image?.baseUrl
}
CreativeFormatType.RichMedia -> {
response.html = htmlFormatter.formatRichMediaIntoHtml(placementId, ad)
response.baseUrl = ad.creative.details.url?.baseUrl
}
CreativeFormatType.Tag -> {
response.html = htmlFormatter.formatTagIntoHtml(ad)
response.baseUrl = Constants.defaultSuperAwesomeUrl
}
CreativeFormatType.Video -> {
if (ad.isVpaid) {
response.html = ad.creative.details.tag
} else {
ad.creative.details.vast?.let { url ->
response.vast = handleVast(url, null)
response.baseUrl = response.vast?.url?.baseUrl
response.vast?.url?.let {
when (val downloadFileResult = networkDataSource.downloadFile(it)) {
is DataResult.Success -> response.filePath =
downloadFileResult.value
is DataResult.Failure -> return downloadFileResult
}
} ?: return DataResult.Failure(Exception("empty url"))
}
}
}
}
ad.creative.referral?.let {
response.referral = encoder.encodeUrlParamsFromObject(it.toMap())
}
return DataResult.Success(response)
}
private suspend fun handleVast(url: String, initialVast: VastAd?): VastAd? {
val result = networkDataSource.getData(url)
if (result is DataResult.Success) {
val vast = vastParser.parse(result.value)
if (vast?.type == VastType.Wrapper && vast.redirect != null) {
val mergedVast = vast.merge(initialVast)
return handleVast(vast.redirect, mergedVast)
}
return vast
}
return initialVast
}
}
| superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/components/AdProcessor.kt | 1360499911 |
/*
* Copyright (c) 2019 Ericsson Research and others
*
* 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 se.ericsson.cf.scott.sandbox.twin.xtra.trs
import eu.scott.warehouse.domains.trs.TrsServerAck
import eu.scott.warehouse.domains.trs.TrsServerAnnouncement
import eu.scott.warehouse.domains.trs.TrsXConstants
import eu.scott.warehouse.lib.MqttTrsServices
import eu.scott.warehouse.lib.MqttTopics
import org.eclipse.lyo.oslc4j.core.OSLC4JUtils
import org.eclipse.lyo.oslc4j.core.exception.LyoModelException
import org.eclipse.lyo.oslc4j.provider.jena.JenaModelHelper
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttException
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.slf4j.LoggerFactory
import se.ericsson.cf.scott.sandbox.twin.xtra.TwinAdaptorHelper
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.ws.rs.core.UriBuilder
import kotlin.math.roundToLong
class TrsMqttPlanManager() {
private val log = LoggerFactory.getLogger(javaClass)
private lateinit var mqttClient: MqttClient
private lateinit var trsTopic: String
constructor(mqttClient: MqttClient) : this() {
this.mqttClient = mqttClient
}
fun connectAndSubscribeToPlans() {
try {
registerWithWHC(mqttClient)
} catch (e: MqttException) {
log.error("Failed to connect to the MQTT broker")
}
}
fun unregisterTwinAndDisconnect() {
try {
// we need to send LWT by hand due to a clean disconnect
mqttClient.publish(MqttTopics.REGISTRATION_ANNOUNCE,
getTwinUnregistrationMessage().payload, 2, false)
mqttClient.disconnect()
log.debug("Disconnected from the MQTT broker")
} catch (e: MqttException) {
log.error("Failed to disconnect from the MQTT broker")
}
}
private fun registerWithWHC(mqttClient: MqttClient) {
val latch = CountDownLatch(1)
try {
mqttClient.subscribe(MqttTopics.REGISTRATION_ACK) { _, message ->
completeRegistration(message, latch)
}
} catch (e: MqttException) {
log.error("Something went wrong with the REG_ACK subscription", e)
}
try {
var n = 1
while (latch.count > 0) {
// back off exponentially but no more than 30s
val backoffDelay = (Math.exp(n+2.0)*2).coerceAtMost(30000.0)
log.trace("Posting the registration message")
mqttClient.publish(MqttTopics.REGISTRATION_ANNOUNCE, getTwinRegistrationMessage())
latch.await(backoffDelay.roundToLong(), TimeUnit.MILLISECONDS)
if (latch.count > 0) {
log.warn("Failed to register the twin with the WHC, attempting again")
}
// give up after 10 attempts
if(n <= 10) {
n += 1
} else {
log.error("Give up on registration with the WHC")
break
}
}
} catch (e: MqttException) {
log.error("Failed to publish the twin registration message")
log.debug("Failed to publish the twin registration message", e)
} catch (e: InterruptedException) {
log.error("The program was interrupted before the latch reached zero")
}
}
private fun completeRegistration(message: MqttMessage, latch: CountDownLatch) {
val model = MqttTrsServices.extractModelFromMessage(message)
try {
val serverAck = JenaModelHelper.unmarshalSingle(model, TrsServerAck::class.java)
if (getTwinUUID() == serverAck.adaptorId) {
log.debug("The WHC registration of the {} has been confirmed", getTwinUUID())
trsTopic = serverAck.trsTopic
latch.countDown()
}
} catch (e: LyoModelException) {
log.error("Error unmarshalling TrsServerAck from the server response", e)
}
}
// HELPERS
private fun getTwinUUID() = TwinAdaptorHelper.getTwinUUID()
private fun getTwinRegistrationMessage(isLeaving: Boolean = false): MqttMessage {
val trsUri = UriBuilder.fromUri(OSLC4JUtils.getServletURI()).path("trs").build()
val announcement = TrsServerAnnouncement(getTwinUUID(), TrsXConstants.TYPE_TWIN, trsUri, MqttTopics.REGISTRATION_ANNOUNCE,
isLeaving)
return MqttTrsServices.msgFromResources(announcement)
}
private fun getTwinUnregistrationMessage(): MqttMessage {
return getTwinRegistrationMessage(true)
}
}
| lyo-services/webapp-twin-robot/src/main/java/se/ericsson/cf/scott/sandbox/twin/xtra/trs/TrsMqttPlanManager.kt | 3283121751 |
/*
* Copyright (C) 2015 Daniel Schaal <[email protected]>
*
* This file is part of OCReader.
*
* OCReader 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.
*
* OCReader 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 OCReader. If not, see <http://www.gnu.org/licenses/>.
*
*/
@file:JvmName("StringUtils")
package email.schaal.ocreader.util
import android.content.Context
import android.graphics.Color
import android.text.format.DateUtils
import androidx.core.text.HtmlCompat
import email.schaal.ocreader.R
import email.schaal.ocreader.database.model.Feed
import okhttp3.HttpUrl
import java.util.*
fun String.htmlLink(href: String?) = if(href != null) "<a href=\"${href}\">${this}</a>" else this
/**
* Utility functions to handle Strings.
*/
fun getByLine(context: Context, template: String, author: String?, feed: Feed?): String {
return if (author != null && feed != null) {
String.format(template, context.getString(R.string.by_author_on_feed, author, feed.name.htmlLink(feed.link)))
} else if(author != null) {
String.format(template, context.getString(R.string.by_author, author))
} else if (feed != null) {
String.format(template, context.getString(R.string.on_feed, feed.name.htmlLink(feed.link)))
} else {
""
}
}
fun Date.getTimeSpanString(endDate: Date = Date()): CharSequence {
return DateUtils.getRelativeTimeSpanString(
this.time,
endDate.time,
DateUtils.MINUTE_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL)
}
fun String.cleanString(): String {
return HtmlCompat.fromHtml(this, HtmlCompat.FROM_HTML_MODE_COMPACT).toString()
}
fun Int.asCssString(): String { // Use US locale so we always get a . as decimal separator for a valid css value
return String.format(Locale.US, "rgba(%d,%d,%d,%.2f)",
Color.red(this),
Color.green(this),
Color.blue(this),
Color.alpha(this) / 255.0)
}
fun HttpUrl.buildBaseUrl(apiRoot: String): HttpUrl {
return this
.newBuilder()
.addPathSegments(apiRoot)
.build()
}
| app/src/main/java/email/schaal/ocreader/util/StringUtils.kt | 1352219516 |
package com.didichuxing.doraemondemo.amap
import android.content.Context
import android.util.Log
import com.amap.api.maps.AMap
import com.amap.api.maps.AMapUtils
import com.amap.api.maps.model.LatLng
import com.amap.api.navi.AMapNavi
import com.amap.api.navi.AMapNaviListener
import com.amap.api.navi.enums.NaviType
import com.amap.api.navi.model.*
import io.reactivex.disposables.Disposable
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2/25/21-20:00
* 描 述:
* 修订历史:
* ================================================
*/
class DefaultNaviListener(val mAMap: AMap, val mAMapNavi: AMapNavi, val context: Context) :
AMapNaviListener {
// private var mNaviRouteOverlay: NaviRouteOverlay? = null
//
// init {
// mNaviRouteOverlay = NaviRouteOverlay(mAMap, null)
// }
private var disp: Disposable? = null
private var mNaviLocation: AMapNaviLocation? = null
companion object {
const val TAG = "DefaultNaviListener"
}
override fun onInitNaviFailure() {
}
override fun onInitNaviSuccess() {
}
override fun onStartNavi(p0: Int) {
}
override fun onTrafficStatusUpdate() {
}
/**
* 改变位置时自动回调
*/
override fun onLocationChange(location: AMapNaviLocation?) {
val calculateLineDistance: Float = if (mNaviLocation == null || location == null) -1f else
AMapUtils.calculateLineDistance(
LatLng(mNaviLocation!!.coord.latitude, mNaviLocation!!.coord.longitude),
LatLng(location.coord.latitude, location.coord.longitude)
)
if (calculateLineDistance < 0) {
Log.v(TAG, "⚠️高德定位:" + location.getString())
} else if (calculateLineDistance > 50) {
Log.w(TAG, "⚠️高德定位:跳动距离:" + calculateLineDistance + " " + location.getString())
} else {
Log.v(TAG, "⚠️高德定位:跳动距离:" + calculateLineDistance + " " + location.getString())
}
mNaviLocation = location
}
private fun AMapNaviLocation?.getString(): String {
return if (this != null) "lat,lng:${coord?.latitude},:${coord?.longitude}, 精度:$accuracy, 速度:$speed, 方向:$bearing, 海拔:$altitude, 时间:$time"
else "null"
}
override fun onGetNavigationText(p0: Int, p1: String?) {
}
override fun onGetNavigationText(p0: String?) {
}
override fun onEndEmulatorNavi() {
}
override fun onArriveDestination() {
}
override fun onCalculateRouteFailure(p0: Int) {
}
override fun onCalculateRouteFailure(p0: AMapCalcRouteResult?) {
}
override fun onReCalculateRouteForYaw() {
}
override fun onReCalculateRouteForTrafficJam() {
}
override fun onArrivedWayPoint(p0: Int) {
}
override fun onGpsOpenStatus(p0: Boolean) {
}
override fun onNaviInfoUpdate(p0: NaviInfo?) {
}
override fun updateCameraInfo(p0: Array<out AMapNaviCameraInfo>?) {
}
override fun updateIntervalCameraInfo(
p0: AMapNaviCameraInfo?,
p1: AMapNaviCameraInfo?,
p2: Int
) {
}
override fun onServiceAreaUpdate(p0: Array<out AMapServiceAreaInfo>?) {
}
override fun showCross(p0: AMapNaviCross?) {
}
override fun hideCross() {
}
override fun showModeCross(p0: AMapModelCross?) {
}
override fun hideModeCross() {
}
override fun showLaneInfo(p0: Array<out AMapLaneInfo>?, p1: ByteArray?, p2: ByteArray?) {
}
override fun showLaneInfo(p0: AMapLaneInfo?) {
}
override fun hideLaneInfo() {
}
override fun onCalculateRouteSuccess(p0: IntArray?) {
}
/**
* 线路规划成功
*/
override fun onCalculateRouteSuccess(result: AMapCalcRouteResult?) {
// LogHelper.i(TAG, "mAMapNavi.naviPath.coordList===>${mAMapNavi.naviPath.coordList.size}")
// RouterManager.mCoordList = mAMapNavi.naviPath.coordList
val naviRouteOverlay = NaviRouteOverlay(mAMap, mAMapNavi.naviPath, context)
naviRouteOverlay.setShowDefaultLineArrow(true)
naviRouteOverlay.addToMap()
// naviRouteOverlay.removeFromMap()
mAMapNavi.setEmulatorNaviSpeed(10)
/**
* CRUISE
巡航模式(数值:3)
EMULATOR
模拟导航(数值:2)
GPS
实时导航(数值:1)
NONE
未开始导航(数值:-1)
*/
mAMapNavi.startNavi(NaviType.GPS)
// disp = MockGPSTaskManager.startGpsMockTask(mAMapNavi.naviPath)?.subscribe()
}
override fun notifyParallelRoad(p0: Int) {
}
override fun OnUpdateTrafficFacility(p0: Array<out AMapNaviTrafficFacilityInfo>?) {
}
override fun OnUpdateTrafficFacility(p0: AMapNaviTrafficFacilityInfo?) {
}
override fun updateAimlessModeStatistics(p0: AimLessModeStat?) {
}
override fun updateAimlessModeCongestionInfo(p0: AimLessModeCongestionInfo?) {
}
override fun onPlayRing(p0: Int) {
}
override fun onNaviRouteNotify(p0: AMapNaviRouteNotifyData?) {
}
override fun onGpsSignalWeak(p0: Boolean) {
}
fun onDestroy() {
if (disp != null && !disp!!.isDisposed()) {
disp!!.dispose()
}
}
} | Android/app/src/main/java/com/didichuxing/doraemondemo/amap/DefaultNaviListener.kt | 1978836474 |
package ademar.study.test.test
import ademar.study.test.R
import ademar.study.test.test.Fixture.NO_CONNECTION
import ademar.study.test.test.Fixture.UNAUTHORIZED
import ademar.study.test.test.Fixture.UNKNOWN
import android.content.Context
import android.support.annotation.CallSuper
import com.nhaarman.mockito_kotlin.whenever
import io.reactivex.android.plugins.RxAndroidPlugins
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import org.assertj.core.api.Assertions.fail
import org.junit.After
import org.junit.Before
import org.mockito.Mock
import org.mockito.MockitoAnnotations
abstract class BaseTest {
@Mock lateinit var mockContext: Context
private var rxError: Throwable? = null
@Before
@CallSuper
open fun setUp() {
MockitoAnnotations.initMocks(this)
rxError = null
RxAndroidPlugins.setInitMainThreadSchedulerHandler {
Schedulers.trampoline()
}
RxJavaPlugins.setIoSchedulerHandler {
Schedulers.trampoline()
}
RxJavaPlugins.setErrorHandler { error ->
println("Received error $error stacktrace:")
error.printStackTrace()
rxError = error
}
whenever(mockContext.getString(R.string.error_message_unknown)).thenReturn(UNKNOWN)
whenever(mockContext.getString(R.string.error_message_unauthorized)).thenReturn(UNAUTHORIZED)
whenever(mockContext.getString(R.string.error_message_no_connection)).thenReturn(NO_CONNECTION)
}
@After
@CallSuper
open fun tearDown() {
if (rxError != null) {
fail("Error on rx: $rxError")
}
RxAndroidPlugins.reset()
RxJavaPlugins.reset()
}
}
| Projects/Test/app/src/test/java/ademar/study/test/test/BaseTest.kt | 2859391908 |
package com.ternaryop.photoshelf.tumblr.dialog
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.activity.result.contract.ActivityResultContract
import com.ternaryop.compat.os.getSerializableCompat
object PostEditorActivityResultContracts {
class New constructor(
private val tumblrPostDialog: TumblrPostDialog
) : ActivityResultContract<NewPostEditorData, NewPostEditorResult?>() {
override fun createIntent(context: Context, input: NewPostEditorData): Intent {
return tumblrPostDialog.newPostEditorIntent(context, input)
}
override fun parseResult(resultCode: Int, intent: Intent?): NewPostEditorResult? {
if (resultCode == Activity.RESULT_OK) {
return intent?.extras?.getSerializableCompat(TumblrPostDialog.ARG_RESULT, NewPostEditorResult::class.java)
}
return null
}
}
class Edit constructor(
private val tumblrPostDialog: TumblrPostDialog
) : ActivityResultContract<EditPostEditorData, PostEditorResult?>() {
override fun createIntent(context: Context, input: EditPostEditorData): Intent {
return tumblrPostDialog.editPostEditorIntent(context, input)
}
override fun parseResult(resultCode: Int, intent: Intent?): PostEditorResult? {
if (resultCode == Activity.RESULT_OK) {
return intent?.extras?.getSerializableCompat(TumblrPostDialog.ARG_RESULT, PostEditorResult::class.java)
}
return null
}
}
}
| tumblr-dialog/src/main/java/com/ternaryop/photoshelf/tumblr/dialog/PostEditorActivityResultContracts.kt | 2937811108 |
package io.gitlab.arturbosch.detekt.formatting.wrappers
import com.pinterest.ktlint.ruleset.standard.FilenameRule
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.formatting.FormattingRule
/**
* See <a href="https://ktlint.github.io">ktlint-website</a> for documentation.
*/
@ActiveByDefault(since = "1.0.0")
class Filename(config: Config) : FormattingRule(config) {
override val wrapping = FilenameRule()
override val issue = issueFor("Checks if top level class matches the filename")
}
| detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/Filename.kt | 833419700 |
package org.ygl
import org.antlr.v4.runtime.tree.xpath.XPath
import org.ygl.BrainSaverParser.*
fun resolveGlobals(parser: BrainSaverParser, tree: ProgramContext): Map<String, Symbol> {
val globals = HashMap<String, Symbol>()
val finalGlobals = HashMap<String, Symbol>()
var address = 0
val readSymbols = XPath.findAll(tree, "//atom", parser)
.mapNotNull { it as? AtomIdContext }
.map { it.text }
.toCollection(HashSet())
XPath.findAll(tree, "//globalVariable", parser)
.mapNotNull { ctx -> ctx as? GlobalVariableContext }
.forEach { ctx ->
val name = ctx.Identifier().text
if (globals.containsKey(name)) throw CompilationException("global symbol $name redefined", ctx)
when (ctx.atom()) {
is BrainSaverParser.AtomIntContext -> {
globals[name] = Symbol(name, 1, address, Type.INT, ctx.rhs.text.toInt())
address += 1
}
is BrainSaverParser.AtomStrContext -> {
globals[name] = Symbol(name, 1, address, Type.STRING, ctx.rhs.text)
address += ctx.rhs.text.length
}
}
}
for ((name, symbol) in globals) {
if (!readSymbols.contains(name)) {
throw CompilationException("unused global variable $name")
}
finalGlobals.put(name, symbol)
}
return finalGlobals
} | src/main/java/org/ygl/GlobalResolver.kt | 3607934441 |
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.misc
import java.io.File
import java.lang.ref.WeakReference
import java.nio.file.*
import java.nio.file.StandardWatchEventKinds.*
import java.util.*
class FileWatcher {
private val watchServiceByFileSystem = mutableMapOf<FileSystem, WatchService>()
private val entriesByDirectory = mutableMapOf<Path, MutableList<Entry>>()
@Synchronized
fun register(file: File, listener: FileListener, useCanonical: Boolean = true) {
register((if (useCanonical) file.canonicalFile else file).toPath(), listener)
}
@Synchronized
fun register(file: Path, listener: FileListener) {
val directory: Path
if (Files.isDirectory(file)) {
directory = file
} else {
directory = file.parent
}
var list: MutableList<Entry>? = entriesByDirectory[directory]
if (list == null) {
list = ArrayList<Entry>()
entriesByDirectory.put(directory, list)
directory.register(watchService(directory), ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY)
}
list.add(Entry(listener, file))
}
@Synchronized
fun unregister(listener: FileListener) {
for (list in entriesByDirectory.values) {
for (entry in list) {
if (entry.weakListener.get() === listener) {
list.remove(entry)
return
}
}
}
}
/**
* This allows a single FileListener to unregister from just ONE of the files that it is listening to.
*/
@Synchronized
fun unregister(file: Path, dl: FileListener) {
val directory: Path
if (Files.isDirectory(file)) {
directory = file
} else {
directory = file.parent
}
val list: MutableList<Entry> = entriesByDirectory[directory] ?: return
for (entry in list) {
if (entry.weakListener.get() === dl) {
list.remove(entry)
break
}
}
if (list.isEmpty()) {
entriesByDirectory.remove(directory)
}
}
private fun watchService(directory: Path): WatchService = watchService(directory.fileSystem)
@Synchronized
private fun watchService(filesystem: FileSystem): WatchService =
watchServiceByFileSystem[filesystem] ?: createWatchService(filesystem)
@Synchronized
private fun createWatchService(filesystem: FileSystem): WatchService {
val watchService = filesystem.newWatchService()!!
watchServiceByFileSystem.put(filesystem, watchService)
startPolling(watchService)
return watchService
}
private fun startPolling(watcher: WatchService) {
val thread = Thread(Runnable {
while (true) {
poll(watcher)
}
})
thread.isDaemon = true
thread.start()
}
private fun poll(watcher: WatchService) {
val key: WatchKey
try {
key = watcher.take()
} catch (x: InterruptedException) {
return
}
val directory = key.watchable() as Path
/*
* I used this tutorial, but it seems broken, as it misses some changes :-(
* https://docs.oracle.com/javase/tutorial/essential/io/notification.html
*
* We cannot reply on WatchService to tell us about ALL changes to the directory, because
* we need to perform a reset in order to receive further changes. If the directory is changed AGAIN
* before the reset is called, then we will not see the 2nd change. This is common, because
* when saving documents, an application will often save to a temporary file, and then rename it to
* the real file (e.g. gedit does this).
* So instead, we keep track of each listener's file's last modified time-stamp, and check each listener of
* this directory to see if their file has changed.
*
* i.e. we ignore the result of key.pollEvents()
*/
key.pollEvents()
if (!notifyListeners(directory)) {
key.cancel()
return
}
val valid = key.reset()
if (!valid) {
// Directory has been deleted, so remove all the listeners
removeAll(directory)
}
}
@Synchronized
private fun removeAll(directory: Path) {
entriesByDirectory.remove(directory)
}
@Synchronized
private fun notifyListeners(directory: Path): Boolean {
val list = entriesByDirectory[directory] ?: return false
if (list.isEmpty()) {
entriesByDirectory.remove(directory)
return false
}
for (entry in list) {
val listener = entry.weakListener.get()
if (listener == null) {
list.remove(entry)
// Recurse to prevent concurrent modification exception.
return notifyListeners(directory)
}
try {
entry.check()
} catch (e: Exception) {
e.printStackTrace()
list.remove(entry)
// Recurse to prevent concurrent modification exception.
return notifyListeners(directory)
}
}
return true
}
private inner class Entry(listener: FileListener, private val path: Path) {
internal val weakListener = WeakReference<FileListener>(listener)
internal var lastModified: Long = path.toFile().lastModified()
fun check() {
val lm = path.toFile().lastModified()
if (lastModified != lm) {
val listener = this.weakListener.get()
if (listener != null) {
this.lastModified = lm
listener.fileChanged(path)
}
}
}
override fun toString(): String {
return "FileWatching Entry for listener ${weakListener.get()}"
}
}
companion object {
var instance: FileWatcher = FileWatcher()
}
}
| paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/misc/FileWatcher.kt | 3616568263 |
package io.gitlab.arturbosch.detekt.rules.coroutines
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.internal.DefaultRuleSetProvider
/**
* The coroutines rule set analyzes code for potential coroutines problems.
*/
@ActiveByDefault(since = "1.4.0")
class CoroutinesProvider : DefaultRuleSetProvider {
override val ruleSetId: String = "coroutines"
override fun instance(config: Config): RuleSet = RuleSet(
ruleSetId,
listOf(
GlobalCoroutineUsage(config),
RedundantSuspendModifier(config),
SleepInsteadOfDelay(config),
SuspendFunWithFlowReturnType(config)
)
)
}
| detekt-rules-coroutines/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/coroutines/CoroutinesProvider.kt | 1246548902 |
package net.nemerosa.ontrack.extension.sonarqube.casc
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.casc.context.settings.AbstractSubSettingsContext
import net.nemerosa.ontrack.extension.casc.schema.*
import net.nemerosa.ontrack.extension.sonarqube.measures.SonarQubeMeasuresSettings
import net.nemerosa.ontrack.model.settings.CachedSettingsService
import net.nemerosa.ontrack.model.settings.SettingsManagerService
import org.springframework.stereotype.Component
@Component
class SonarQubeMeasuresSettingsContext(
settingsManagerService: SettingsManagerService,
cachedSettingsService: CachedSettingsService,
) : AbstractSubSettingsContext<SonarQubeMeasuresSettings>(
"sonarqube-measures",
SonarQubeMeasuresSettings::class,
settingsManagerService,
cachedSettingsService
) {
override val type: CascType = cascObject(
"SonarQube measures settings",
cascField(SonarQubeMeasuresSettings::measures,
cascArray(
"List of SonarQube measures",
cascString
)
),
cascField(SonarQubeMeasuresSettings::disabled, required = false),
cascField(SonarQubeMeasuresSettings::coverageThreshold, required = false),
cascField(SonarQubeMeasuresSettings::blockerThreshold, required = false),
)
override fun adjustNodeBeforeParsing(node: JsonNode): JsonNode =
node.ifMissing(
SonarQubeMeasuresSettings::disabled to SonarQubeMeasuresSettings.DEFAULT_DISABLED,
SonarQubeMeasuresSettings::coverageThreshold to SonarQubeMeasuresSettings.DEFAULT_COVERAGE_THRESHOLD,
SonarQubeMeasuresSettings::blockerThreshold to SonarQubeMeasuresSettings.DEFAULT_BLOCKER_THRESHOLD,
)
} | ontrack-extension-sonarqube/src/main/java/net/nemerosa/ontrack/extension/sonarqube/casc/SonarQubeMeasuresSettingsContext.kt | 566649281 |
package net.nemerosa.ontrack.model.security
import java.io.Serializable
/**
* A project role is the association between an identifier, a name and a set of
* [project functions][net.nemerosa.ontrack.model.security.ProjectFunction].
*/
data class ProjectRole(
/**
* Project role's identifier
*/
val id: String,
/**
* Project role's name
*/
val name: String,
/**
* Description
*/
val description: String,
/**
* Associated set of project functions
*/
val functions: Set<Class<out ProjectFunction>>) : Serializable {
fun isGranted(functionToCheck: Class<out ProjectFunction>): Boolean =
functions.any { functionToCheck.isAssignableFrom(it) }
} | ontrack-model/src/main/java/net/nemerosa/ontrack/model/security/ProjectRole.kt | 1099634939 |
package be.florien.anyflow.view.connect
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import be.florien.anyflow.R
import be.florien.anyflow.api.model.Account
import be.florien.anyflow.api.model.AccountList
import be.florien.anyflow.databinding.ItemAccountBinding
import org.simpleframework.xml.core.Persister
import java.io.InputStreamReader
/**
* Created by florien on 4/03/18.
*/
class ConnectActivity : ConnectActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val reader = InputStreamReader(assets.open("mock_account.xml"))
val osd = Persister().read(AccountList::class.java, reader)
binding.extra?.mockAccount?.layoutManager = LinearLayoutManager(this)
binding.extra?.mockAccount?.adapter = AccountAdapter(osd.accounts)
}
inner class AccountAdapter(val accounts: List<Account>) : RecyclerView.Adapter<AccountViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AccountViewHolder = AccountViewHolder(parent)
override fun getItemCount(): Int = accounts.size
override fun onBindViewHolder(holder: AccountViewHolder, position: Int) {
holder.bindAccount(accounts[position])
}
}
inner class AccountViewHolder(
parent: ViewGroup,
private val binding: ItemAccountBinding
= DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_account, parent, false))
: RecyclerView.ViewHolder(binding.root) {
private lateinit var boundAccount: Account
fun bindAccount(account: Account) {
boundAccount = account
binding.accountName = account.name
itemView.setOnClickListener {
vm.server = account.server
vm.username = account.user
vm.password = account.password
vm.connect()
}
}
}
} | app/src/mock/java/be/florien/anyflow/view/connect/ConnectActivity.kt | 3438299258 |
package org.rust.ide.surroundWith.statement
import org.rust.ide.surroundWith.RsSurrounderTestBase
class RsWithForSurrounderTest : RsSurrounderTestBase(RsWithForSurrounder()) {
fun testNotApplicable1() {
doTestNotApplicable(
"""
fn main() {
let mut server <selection>= Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
)
}
fun testNotApplicable2() {
doTestNotApplicable(
"""
fn main() {
<selection>#![cfg(test)]
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
)
}
fun testNotApplicable3() {
doTestNotApplicable(
"""
fn main() {
loop<selection> {
for 1 in 1..10 {
println!("Hello, world!");
}
}</selection>
}
"""
)
}
fun testApplicableComment() {
doTest(
"""
fn main() {
<selection>// comment
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap(); // comment</selection>
}
"""
,
"""
fn main() {
for <caret> {
// comment
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap(); // comment
}
}
"""
,
checkSyntaxErrors = false
)
}
fun testSimple1() {
doTest(
"""
fn main() {
<selection>let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
,
"""
fn main() {
for <caret> {
let mut server = Nickel::new();
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();
}
}
"""
,
checkSyntaxErrors = false
)
}
fun testSimple2() {
doTest(
"""
fn main() {
let mut server = Nickel::new();<selection>
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();</selection>
}
"""
,
"""
fn main() {
let mut server = Nickel::new();
for <caret> {
server.get("**", hello_world);
server.listen("127.0.0.1:6767").unwrap();
}
}
"""
,
checkSyntaxErrors = false
)
}
fun testSimple3() {
doTest(
"""
fn main() {
<selection>let mut server = Nickel::new();
server.get("**", hello_world);</selection>
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
"""
fn main() {
for <caret> {
let mut server = Nickel::new();
server.get("**", hello_world);
}
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
checkSyntaxErrors = false
)
}
fun testSingleLine() {
doTest(
"""
fn main() {
let mut server = Nickel::new();
server.get("**", hello_world)<caret>;
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
"""
fn main() {
let mut server = Nickel::new();
for <caret> {
server.get("**", hello_world);
}
server.listen("127.0.0.1:6767").unwrap();
}
"""
,
checkSyntaxErrors = false
)
}
fun testNested() {
doTest(
"""
fn main() {
<selection>loop {
println!("Hello");
}</selection>
}
"""
,
"""
fn main() {
for <caret> {
loop {
println!("Hello");
}
}
}
"""
,
checkSyntaxErrors = false
)
}
}
| src/test/kotlin/org/rust/ide/surroundWith/statement/RsWithForSurrounderTest.kt | 3862282236 |
package io.mockk.proxy.jvm.advice
import java.lang.reflect.Method
import java.util.concurrent.Callable
internal class MethodCall(
private val self: Any,
private val method: Method,
private val args: Array<Any?>
) : Callable<Any?> {
override fun call(): Any? {
method.isAccessible = true
return method.invoke(self, *args)
}
}
| modules/mockk-agent/src/jvmMain/kotlin/io/mockk/proxy/jvm/advice/MethodCall.kt | 1172045258 |
/*
* 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.context
import org.mapdb.DB
import svnserver.config.SharedConfig
import java.io.IOException
import java.nio.file.Path
import java.util.*
import javax.annotation.concurrent.ThreadSafe
/**
* Simple context object.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
@ThreadSafe
class SharedContext private constructor(val basePath: Path, val cacheDB: DB, val realm: String) : Context<Shared>(), AutoCloseable {
@Throws(IOException::class)
fun ready() {
for (item in ArrayList(values())) {
item.ready(this)
}
}
@Throws(Exception::class)
override fun close() {
super.close()
cacheDB.close()
}
companion object {
@Throws(Exception::class)
fun create(basePath: Path, realm: String, cacheDb: DB, shared: Collection<SharedConfig>): SharedContext {
val context = SharedContext(basePath, cacheDb, realm)
for (config in shared) {
config.create(context)
}
for (item in ArrayList(context.values())) {
item.init(context)
}
return context
}
}
}
| src/main/kotlin/svnserver/context/SharedContext.kt | 1375803441 |
/*
* Copyright (C) 2017 Artem Hluhovskyi
*
* 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.dewarder.akommons.content.preferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class BooleanPreferencesProperty(
private val defaultValue: Boolean,
private val key: String?
) : ReadWriteProperty<SharedPreferencesProvider, Boolean> {
override fun getValue(thisRef: SharedPreferencesProvider, property: KProperty<*>): Boolean {
val key = key ?: property.name
return thisRef.sharedPreferences.getBoolean(key, defaultValue)
}
override fun setValue(thisRef: SharedPreferencesProvider, property: KProperty<*>, value: Boolean) {
val key = key ?: property.name
thisRef.sharedPreferences.save(key, value)
}
} | akommons/src/main/java/com/dewarder/akommons/content/preferences/BooleanPreferencesProperty.kt | 510852922 |
/*
* 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.ext.gitlab.config
import com.google.api.client.auth.oauth.OAuthGetAccessToken
import com.google.api.client.auth.oauth2.PasswordTokenRequest
import com.google.api.client.auth.oauth2.TokenResponseException
import com.google.api.client.http.HttpTransport
import com.google.api.client.http.javanet.NetHttpTransport
import com.google.api.client.json.jackson2.JacksonFactory
import org.gitlab.api.GitlabAPI
import org.gitlab.api.GitlabAPIException
import org.gitlab.api.TokenType
import org.gitlab.api.models.GitlabSession
import svnserver.context.Shared
import svnserver.context.SharedContext
import java.io.IOException
import java.net.HttpURLConnection
/**
* GitLab context.
*
* @author Artem V. Navrotskiy <[email protected]>
*/
class GitLabContext internal constructor(val config: GitLabConfig) : Shared {
@Throws(IOException::class)
fun connect(username: String, password: String): GitlabSession {
val token = obtainAccessToken(gitLabUrl, username, password, false)
val api = connect(gitLabUrl, token)
return api.currentSession
}
fun connect(): GitlabAPI {
return Companion.connect(gitLabUrl, token)
}
val gitLabUrl: String
get() = config.url
val token: GitLabToken
get() = config.getToken()
val hookPath: String
get() = config.hookPath
companion object {
private val transport: HttpTransport = NetHttpTransport()
fun sure(context: SharedContext): GitLabContext {
return context.sure(GitLabContext::class.java)
}
@Throws(IOException::class)
fun obtainAccessToken(gitlabUrl: String, username: String, password: String, sudoScope: Boolean): GitLabToken {
return try {
val tokenServerUrl = OAuthGetAccessToken(gitlabUrl + "/oauth/token?scope=api" + if (sudoScope) "%20sudo" else "")
val oauthResponse = PasswordTokenRequest(transport, JacksonFactory.getDefaultInstance(), tokenServerUrl, username, password).execute()
GitLabToken(TokenType.ACCESS_TOKEN, oauthResponse.accessToken)
} catch (e: TokenResponseException) {
if (sudoScope && e.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
// Fallback for pre-10.2 gitlab versions
val session = GitlabAPI.connect(gitlabUrl, username, password)
GitLabToken(TokenType.PRIVATE_TOKEN, session.privateToken)
} else {
throw GitlabAPIException(e.message, e.statusCode, e)
}
}
}
fun connect(gitlabUrl: String, token: GitLabToken): GitlabAPI {
return GitlabAPI.connect(gitlabUrl, token.value, token.type)
}
}
}
| src/main/kotlin/svnserver/ext/gitlab/config/GitLabContext.kt | 3258845381 |
package com.protryon.jasm
import com.shapesecurity.functional.Pair
import java.util.ArrayList
class MethodDescriptor(var returnType: JType, var parameters: ArrayList<JType>) {
override fun toString(): String {
val builder = StringBuilder("(")
for (param in parameters) {
builder.append(param.toDescriptor())
}
builder.append(")")
builder.append(returnType.toDescriptor())
return builder.toString()
}
fun niceString(methodName: String): String {
val builder = StringBuilder()
builder.append(returnType.niceName)
builder.append(" ").append(methodName).append("(")
var first = true
for (param in parameters) {
if (first) {
first = false
} else {
builder.append(", ")
}
builder.append(param.niceName)
}
builder.append(")")
return builder.toString()
}
override fun equals(o: Any?): Boolean {
if (o !is MethodDescriptor) {
return false
}
if (o.returnType != this.returnType) {
return false
}
if (o.parameters.size != this.parameters.size) {
return false
}
for (i in this.parameters.indices) {
if (this.parameters[i] != o.parameters[i]) {
return false
}
}
return true
}
override fun hashCode(): Int {
return this.returnType.hashCode() + this.parameters.hashCode()
}
companion object {
fun fromString(classpath: Classpath, str: String): MethodDescriptor? {
if (str[0] != '(') {
return null
}
val end = str.indexOf(")", 1)
var params = str.substring(1, end)
val returnDescriptor = str.substring(end + 1)
val returnType = JType.fromDescriptor(classpath, returnDescriptor)
val parameters = ArrayList<JType>()
while (params.length > 0) {
val pair = JType.fromDescriptorWithLength(classpath, params)
params = params.substring(pair.right)
parameters.add(pair.left)
}
return MethodDescriptor(returnType, parameters)
}
}
}
| src/main/java/com/protryon/jasm/MethodDescriptor.kt | 3487290261 |
package tornadofx.testapps
import javafx.scene.layout.BorderStrokeStyle
import javafx.scene.shape.StrokeLineCap
import javafx.scene.shape.StrokeLineJoin
import javafx.scene.shape.StrokeType
import tornadofx.*
class BrokenLineApp : App(BrokenLineView::class, BrokenStyles::class)
class BrokenLineView : View("Broken Line Test") {
override val root = stackpane {
line {
addClass(BrokenStyles.blue)
endXProperty().bind([email protected]())
endYProperty().bind([email protected]())
}
line {
addClass(BrokenStyles.blue)
endXProperty().bind([email protected]())
startYProperty().bind([email protected]())
}
label("This is a label with a border").addClass(BrokenStyles.red)
}
}
class BrokenStyles : Stylesheet() {
companion object {
val red by cssclass()
val blue by cssclass()
}
init {
root {
padding = box(25.px)
backgroundColor += c("white")
}
red {
val radius = box(50.px)
backgroundColor += c("white", 0.9)
backgroundRadius += radius
borderColor += box(c("red"))
borderWidth += box(5.px)
borderRadius += radius
borderStyle += BorderStrokeStyle(
StrokeType.CENTERED,
StrokeLineJoin.MITER,
StrokeLineCap.SQUARE,
10.0,
0.0,
listOf(5.0, 15.0, 0.0, 15.0)
)
padding = box(50.px)
}
blue {
stroke = c("dodgerblue")
strokeWidth = 5.px
strokeType = StrokeType.CENTERED
strokeLineCap = StrokeLineCap.SQUARE
strokeDashArray = listOf(25.px, 15.px, 0.px, 15.px)
}
}
} | src/test/kotlin/tornadofx/testapps/BrokenLineTest.kt | 2341321771 |
package com.telenav.osv.data.collector.phonedata.util
import android.os.SystemClock
class MillisecondsConverter : TimestampConverter() {
/**
* This method returns the UTC time of the sensor event reading.
* Use case: event timestamp represents the time passed from device reboot in milliseconds
*
* @param eventTimestamp The time of a sensor event
* @return The UTC time of the sensor event reading
*/
override fun getTimestamp(eventTimestamp: Long): Long {
var timestamp: Long = 0
val currentTimeMillis = System.currentTimeMillis()
val correction = SystemClock.elapsedRealtime() - eventTimestamp
timestamp = if (correction > 0) {
currentTimeMillis - correction
} else {
currentTimeMillis
}
return timestamp
}
} | app/src/main/java/com/telenav/osv/data/collector/phonedata/util/MillisecondsConverter.kt | 1217986157 |
/*
* Copyright 2018, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.testing.espresso.BasicSample
import androidx.test.ext.junit.rules.activityScenarioRule
import android.app.Activity
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.launchActivity
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions
import androidx.test.espresso.action.ViewActions.*
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* The kotlin equivalent to the ChangeTextBehaviorTest, that
* showcases simple view matchers and actions like [ViewMatchers.withId],
* [ViewActions.click] and [ViewActions.typeText], and ActivityScenarioRule
*
*
* Note that there is no need to tell Espresso that a view is in a different [Activity].
*/
@RunWith(AndroidJUnit4::class)
@LargeTest
class ChangeTextBehaviorKtTest {
/**
* Use [ActivityScenarioRule] to create and launch the activity under test before each test,
* and close it after each test. This is a replacement for
* [androidx.test.rule.ActivityTestRule].
*/
@get:Rule var activityScenarioRule = activityScenarioRule<MainActivity>()
@Test
fun changeText_sameActivity() {
// Type text and then press the button.
onView(withId(R.id.editTextUserInput))
.perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard())
onView(withId(R.id.changeTextBt)).perform(click())
// Check that the text was changed.
onView(withId(R.id.textToBeChanged)).check(matches(withText(STRING_TO_BE_TYPED)))
}
@Test
fun changeText_newActivity() {
// Type text and then press the button.
onView(withId(R.id.editTextUserInput)).perform(typeText(STRING_TO_BE_TYPED),
closeSoftKeyboard())
onView(withId(R.id.activityChangeTextBtn)).perform(click())
// This view is in a different Activity, no need to tell Espresso.
onView(withId(R.id.show_text_view)).check(matches(withText(STRING_TO_BE_TYPED)))
}
companion object {
val STRING_TO_BE_TYPED = "Espresso"
}
} | ui/espresso/BasicSample/app/src/androidTest/java/com/example/android/testing/espresso/BasicSample/ChangeTextBehaviorKtTest.kt | 4235411899 |
/*
* 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.fragment
import android.app.Dialog
import android.content.DialogInterface
import android.os.Bundle
import android.support.v4.app.FragmentManager
import android.support.v7.app.AlertDialog
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_USER_LIST
import de.vanita5.twittnuker.extension.applyOnShow
import de.vanita5.twittnuker.extension.applyTheme
import de.vanita5.twittnuker.model.ParcelableUserList
class DestroyUserListDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface, which: Int) {
when (which) {
DialogInterface.BUTTON_POSITIVE -> {
val userList = userList
val twitter = twitterWrapper
twitter.destroyUserListAsync(userList.account_key, userList.id)
}
else -> {
}
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
val builder = AlertDialog.Builder(context)
val userList = userList
builder.setTitle(getString(R.string.delete_user_list, userList.name))
builder.setMessage(getString(R.string.delete_user_list_confirm_message, userList.name))
builder.setPositiveButton(android.R.string.ok, this)
builder.setNegativeButton(android.R.string.cancel, null)
val dialog = builder.create()
dialog.applyOnShow { applyTheme() }
return dialog
}
private val userList: ParcelableUserList
get() = arguments.getParcelable<ParcelableUserList>(EXTRA_USER_LIST)
companion object {
private const val FRAGMENT_TAG = "destroy_user_list"
fun show(fm: FragmentManager, userList: ParcelableUserList): DestroyUserListDialogFragment {
val args = Bundle()
args.putParcelable(EXTRA_USER_LIST, userList)
val f = DestroyUserListDialogFragment()
f.arguments = args
f.show(fm, FRAGMENT_TAG)
return f
}
}
} | twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/DestroyUserListDialogFragment.kt | 932823251 |
package com.calebprior.boilerplate.utility
@Target(AnnotationTarget.PROPERTY)
annotation class UpdateOnViewBound | app/src/main/kotlin/com/calebprior/boilerplate/utility/UpdateOnViewBound.kt | 1723252242 |
package org.akvo.caddisfly.util
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
import android.view.View
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.content.ContextCompat
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
//https://medium.com/@felipegi91_89910/thanks-daniele-bottillo-b57caf823e34
class DrawableMatcher private constructor(private val expectedId: Int) : TypeSafeMatcher<View>(View::class.java) {
private var resourceName: String? = null
override fun matchesSafely(target: View): Boolean {
var backgroundBitmap: Bitmap? = null
var resourceBitmap: Bitmap? = null
val clazz = target.javaClass
if (clazz == AppCompatImageView::class.java) {
val image = target as AppCompatImageView
if (expectedId == ANY) {
return image.drawable != null
}
if (expectedId < 0) {
return image.background == null
}
resourceBitmap = drawableToBitmap(image.drawable)
backgroundBitmap = drawableToBitmap(image.background)
}
if (clazz == ImageView::class.java) {
val image = target as ImageView
if (expectedId == ANY) {
return image.drawable != null
}
if (expectedId < 0) {
return image.background == null
}
resourceBitmap = drawableToBitmap(image.drawable)
backgroundBitmap = drawableToBitmap(image.background)
}
val resources = target.context.resources
val expectedDrawable = ContextCompat.getDrawable(target.context, expectedId)
resourceName = resources.getResourceEntryName(expectedId)
if (expectedDrawable == null) {
return false
}
val otherBitmap = drawableToBitmap(expectedDrawable)
return resourceBitmap != null && resourceBitmap.sameAs(otherBitmap) || backgroundBitmap != null && backgroundBitmap.sameAs(otherBitmap)
}
// private Bitmap getBitmap(Drawable drawable) {
// Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
// Canvas canvas = new Canvas(bitmap);
// drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
// drawable.draw(canvas);
// return bitmap;
// }
override fun describeTo(description: Description) {
description.appendText("with drawable from resource id: ")
description.appendValue(expectedId)
if (resourceName != null) {
description.appendText("[")
description.appendText(resourceName)
description.appendText("]")
}
}
companion object {
// private static final int EMPTY = -1;
private const val ANY = -2
fun hasDrawable(): Matcher<View> {
return DrawableMatcher(ANY)
}
private fun drawableToBitmap(drawable: Drawable): Bitmap {
val bitmap: Bitmap = if (drawable.intrinsicWidth <= 0 || drawable.intrinsicHeight <= 0) {
Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888) // Single color bitmap will be created of 1x1 pixel
} else {
Bitmap.createBitmap(drawable.intrinsicWidth, drawable.intrinsicHeight, Bitmap.Config.ARGB_8888)
}
if (drawable is BitmapDrawable) {
if (drawable.bitmap != null) {
return drawable.bitmap
}
}
val canvas = Canvas(bitmap)
drawable.setBounds(0, 0, canvas.width, canvas.height)
drawable.draw(canvas)
return bitmap
}
}
} | caddisfly-app/app/src/androidTest/java/org/akvo/caddisfly/util/DrawableMatcher.kt | 4173801657 |
package com.stripe.android.paymentsheet
import android.app.Application
import android.content.Context
import androidx.activity.result.ActivityResultLauncher
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.SavedStateHandle
import androidx.test.core.app.ApplicationProvider
import com.stripe.android.ApiKeyFixtures
import com.stripe.android.PaymentConfiguration
import com.stripe.android.core.Logger
import com.stripe.android.core.injection.Injectable
import com.stripe.android.core.injection.InjectorKey
import com.stripe.android.core.injection.NonFallbackInjector
import com.stripe.android.core.injection.WeakMapInjectorRegistry
import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncher
import com.stripe.android.googlepaylauncher.GooglePayPaymentMethodLauncherContract
import com.stripe.android.googlepaylauncher.injection.GooglePayPaymentMethodLauncherFactory
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.StripeIntent
import com.stripe.android.payments.paymentlauncher.StripePaymentLauncherAssistedFactory
import com.stripe.android.paymentsheet.analytics.EventReporter
import com.stripe.android.paymentsheet.forms.FormViewModel
import com.stripe.android.paymentsheet.injection.FormViewModelSubcomponent
import com.stripe.android.paymentsheet.injection.PaymentSheetViewModelSubcomponent
import com.stripe.android.paymentsheet.model.StripeIntentValidator
import com.stripe.android.paymentsheet.paymentdatacollection.FormFragmentArguments
import com.stripe.android.paymentsheet.repositories.StripeIntentRepository
import com.stripe.android.paymentsheet.viewmodels.BaseSheetViewModel
import com.stripe.android.ui.core.Amount
import com.stripe.android.ui.core.address.AddressRepository
import com.stripe.android.ui.core.forms.resources.LpmRepository
import com.stripe.android.ui.core.forms.resources.StaticAddressResourceRepository
import com.stripe.android.ui.core.forms.resources.StaticLpmResourceRepository
import com.stripe.android.utils.FakeCustomerRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.After
import org.junit.Rule
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import javax.inject.Provider
@ExperimentalCoroutinesApi
internal open class PaymentSheetViewModelTestInjection {
@get:Rule
val rule = InstantTaskExecutorRule()
private val testDispatcher = UnconfinedTestDispatcher()
private val context = ApplicationProvider.getApplicationContext<Context>()
val eventReporter = mock<EventReporter>()
private val googlePayPaymentMethodLauncherFactory =
createGooglePayPaymentMethodLauncherFactory()
private val stripePaymentLauncherAssistedFactory = mock<StripePaymentLauncherAssistedFactory>()
private lateinit var injector: NonFallbackInjector
@After
open fun after() {
WeakMapInjectorRegistry.clear()
}
private fun createGooglePayPaymentMethodLauncherFactory() =
object : GooglePayPaymentMethodLauncherFactory {
override fun create(
lifecycleScope: CoroutineScope,
config: GooglePayPaymentMethodLauncher.Config,
readyCallback: GooglePayPaymentMethodLauncher.ReadyCallback,
activityResultLauncher: ActivityResultLauncher<GooglePayPaymentMethodLauncherContract.Args>,
skipReadyCheck: Boolean
): GooglePayPaymentMethodLauncher {
val googlePayPaymentMethodLauncher = mock<GooglePayPaymentMethodLauncher>()
readyCallback.onReady(true)
return googlePayPaymentMethodLauncher
}
}
@ExperimentalCoroutinesApi
fun createViewModel(
stripeIntent: StripeIntent,
customerRepositoryPMs: List<PaymentMethod> = emptyList(),
@InjectorKey injectorKey: String,
args: PaymentSheetContract.Args = PaymentSheetFixtures.ARGS_CUSTOMER_WITH_GOOGLEPAY
): PaymentSheetViewModel = runBlocking {
PaymentSheetViewModel(
ApplicationProvider.getApplicationContext(),
args,
eventReporter,
{ PaymentConfiguration(ApiKeyFixtures.FAKE_PUBLISHABLE_KEY) },
StripeIntentRepository.Static(stripeIntent),
StripeIntentValidator(),
FakeCustomerRepository(customerRepositoryPMs),
FakePrefsRepository(),
lpmResourceRepository = StaticLpmResourceRepository(
LpmRepository(
LpmRepository.LpmRepositoryArguments(
ApplicationProvider.getApplicationContext<Application>().resources
)
).apply {
this.forceUpdate(
listOf(
PaymentMethod.Type.Card.code,
PaymentMethod.Type.USBankAccount.code
),
null
)
}
),
mock(),
stripePaymentLauncherAssistedFactory,
googlePayPaymentMethodLauncherFactory,
Logger.noop(),
testDispatcher,
injectorKey,
savedStateHandle = SavedStateHandle().apply {
set(BaseSheetViewModel.SAVE_RESOURCE_REPOSITORY_READY, true)
},
linkLauncher = mock()
)
}
@FlowPreview
fun registerViewModel(
@InjectorKey injectorKey: String,
viewModel: PaymentSheetViewModel,
lpmRepository: LpmRepository,
addressRepository: AddressRepository,
formViewModel: FormViewModel = FormViewModel(
context = context,
formFragmentArguments = FormFragmentArguments(
PaymentMethod.Type.Card.code,
showCheckbox = true,
showCheckboxControlledFields = true,
merchantName = "Merchant, Inc.",
amount = Amount(50, "USD"),
initialPaymentMethodCreateParams = null
),
lpmResourceRepository = StaticLpmResourceRepository(lpmRepository),
addressResourceRepository = StaticAddressResourceRepository(addressRepository),
showCheckboxFlow = mock()
)
) {
injector = object : NonFallbackInjector {
override fun inject(injectable: Injectable<*>) {
(injectable as? PaymentSheetViewModel.Factory)?.let {
val mockBuilder = mock<PaymentSheetViewModelSubcomponent.Builder>()
val mockSubcomponent = mock<PaymentSheetViewModelSubcomponent>()
val mockSubComponentBuilderProvider =
mock<Provider<PaymentSheetViewModelSubcomponent.Builder>>()
whenever(mockBuilder.build()).thenReturn(mockSubcomponent)
whenever(mockBuilder.savedStateHandle(any())).thenReturn(mockBuilder)
whenever(mockBuilder.paymentSheetViewModelModule(any())).thenReturn(mockBuilder)
whenever(mockSubcomponent.viewModel).thenReturn(viewModel)
whenever(mockSubComponentBuilderProvider.get()).thenReturn(mockBuilder)
injectable.subComponentBuilderProvider = mockSubComponentBuilderProvider
}
(injectable as? FormViewModel.Factory)?.let {
val mockBuilder = mock<FormViewModelSubcomponent.Builder>()
val mockSubcomponent = mock<FormViewModelSubcomponent>()
val mockSubComponentBuilderProvider =
mock<Provider<FormViewModelSubcomponent.Builder>>()
whenever(mockBuilder.build()).thenReturn(mockSubcomponent)
whenever(mockBuilder.formFragmentArguments(any())).thenReturn(mockBuilder)
whenever(mockSubcomponent.viewModel).thenReturn(formViewModel)
whenever(mockSubComponentBuilderProvider.get()).thenReturn(mockBuilder)
injectable.subComponentBuilderProvider = mockSubComponentBuilderProvider
}
}
}
viewModel.injector = injector
WeakMapInjectorRegistry.register(injector, injectorKey)
}
}
| paymentsheet/src/test/java/com/stripe/android/paymentsheet/PaymentSheetViewModelTestInjection.kt | 2563022634 |
/*
* Copyright 2017 Paulo Fernando
*
* 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 site.paulo.localchat.data
import site.paulo.localchat.data.model.firebase.ChatMessage
import timber.log.Timber
import java.util.concurrent.atomic.AtomicInteger
import com.anupcowkur.reservoir.Reservoir
import java.io.IOException
import javax.inject.Singleton
@Singleton
class MessagesManager {
private object HOLDER {
val INSTANCE = MessagesManager()
}
companion object {
val instance: MessagesManager by lazy { HOLDER.INSTANCE }
}
/** Every message is stored here */ //TODO just stored the last x messages by chat
val chatMessages = mutableMapOf<String, MutableList<ChatMessage>>()
val chatListeners = mutableMapOf<String, MessagesListener>()
fun add(chatMessage: ChatMessage, chatId: String) {
if(!chatMessages.containsKey(chatId)) {
chatMessages.put(chatId, mutableListOf())
}
chatMessages[chatId]?.add(chatMessage)
chatListeners[chatId]?.messageReceived(chatMessage)
}
fun unreadMessages(chatId: String, userId: String) {
try {
val key = "$chatId-unread-$userId"
if(!Reservoir.contains(key)) {
Reservoir.put(key, AtomicInteger(0))
}
val unread = Reservoir.get<AtomicInteger>(key, AtomicInteger::class.java)
Reservoir.put(key, unread.incrementAndGet())
} catch (e: IOException) {
Timber.e(e)
}
}
fun readMessages(chatId: String, userId: String) {
try {
Reservoir.put("$chatId-unread-$userId", AtomicInteger(0))
} catch (e: IOException) {
Timber.e(e)
}
}
fun getUnreadMessages(chatId: String, userId: String): Int {
try {
val key = "$chatId-unread-$userId"
if(!Reservoir.contains(key)) {
Reservoir.put(key, AtomicInteger(0))
}
return Reservoir.get<AtomicInteger>(key, AtomicInteger::class.java).get()
} catch (e: Exception) {
Timber.e(e)
}
return 0
}
fun hasUnread(chatId: String, userId: String): Boolean {
return getUnreadMessages(chatId, userId) > 0
}
/**
* Register a message listener and returns the messages already received
*/
fun registerListener(messageListener: MessagesListener, chatId: String): MutableList<ChatMessage>? {
chatListeners.put(chatId, messageListener)
return chatMessages[chatId]
}
} | app/src/main/kotlin/site/paulo/localchat/data/MessagesManager.kt | 3758841789 |
package expo.modules.imagepicker.tasks
import android.content.ContentResolver
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import android.util.Log
import androidx.exifinterface.media.ExifInterface
import expo.modules.core.Promise
import expo.modules.core.errors.ModuleDestroyedException
import expo.modules.imagepicker.ExifDataHandler
import expo.modules.imagepicker.ImagePickerConstants
import expo.modules.imagepicker.ImagePickerConstants.exifTags
import expo.modules.imagepicker.exporters.ImageExporter
import expo.modules.imagepicker.exporters.ImageExporter.Listener
import expo.modules.imagepicker.fileproviders.FileProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
open class ImageResultTask(
private val promise: Promise,
private val uri: Uri,
private val contentResolver: ContentResolver,
private val fileProvider: FileProvider,
private val isEdited: Boolean,
private val withExifData: Boolean,
private val imageExporter: ImageExporter,
private var exifDataHandler: ExifDataHandler?,
private val coroutineScope: CoroutineScope
) {
/**
* We need to make coroutine wait till the file is generated, while the underlying
* thread is free to continue executing other coroutines.
*/
private suspend fun getFile(): File = suspendCancellableCoroutine { cancellableContinuation ->
try {
val outputFile = fileProvider.generateFile()
cancellableContinuation.resume(outputFile)
} catch (e: Exception) {
cancellableContinuation.resumeWithException(e)
}
}
/**
* We need to make coroutine wait till the exif data is being read, while the underlying
* thread is free to continue executing other coroutines.
*/
private suspend fun getExifData(): Bundle? = suspendCancellableCoroutine { cancellableContinuation ->
try {
val exif = if (withExifData) readExif() else null
cancellableContinuation.resume(exif)
} catch (e: Exception) {
cancellableContinuation.resumeWithException(e)
}
}
fun execute() {
coroutineScope.launch {
try {
val outputFile = getFile()
if (isEdited) {
exifDataHandler?.copyExifData(uri, contentResolver)
}
val exif = getExifData()
val imageExporterHandler = object : Listener {
override fun onResult(out: ByteArrayOutputStream?, width: Int, height: Int) {
val response = Bundle().apply {
putString("uri", Uri.fromFile(outputFile).toString())
putInt("width", width)
putInt("height", height)
putBoolean("cancelled", false)
putString("type", "image")
out?.let {
putString("base64", Base64.encodeToString(it.toByteArray(), Base64.NO_WRAP))
}
exif?.let {
putBundle("exif", it)
}
}
promise.resolve(response)
}
override fun onFailure(cause: Throwable?) {
promise.reject(ImagePickerConstants.ERR_CAN_NOT_SAVE_RESULT, ImagePickerConstants.CAN_NOT_SAVE_RESULT_MESSAGE, cause)
}
}
imageExporter.export(uri, outputFile, imageExporterHandler)
} catch (e: ModuleDestroyedException) {
Log.i(ImagePickerConstants.TAG, ImagePickerConstants.COROUTINE_CANCELED, e)
promise.reject(ImagePickerConstants.COROUTINE_CANCELED, e)
} catch (e: IOException) {
promise.reject(ImagePickerConstants.ERR_CAN_NOT_EXTRACT_METADATA, ImagePickerConstants.CAN_NOT_EXTRACT_METADATA_MESSAGE, e)
} catch (e: Exception) {
Log.e(ImagePickerConstants.TAG, ImagePickerConstants.UNKNOWN_EXCEPTION, e)
promise.reject(ImagePickerConstants.UNKNOWN_EXCEPTION, e)
}
}
}
@Throws(IOException::class)
private fun readExif() = Bundle().apply {
contentResolver.openInputStream(uri)?.use { input ->
val exifInterface = ExifInterface(input)
exifTags.forEach { (type, name) ->
if (exifInterface.getAttribute(name) != null) {
when (type) {
"string" -> putString(name, exifInterface.getAttribute(name))
"int" -> putInt(name, exifInterface.getAttributeInt(name, 0))
"double" -> putDouble(name, exifInterface.getAttributeDouble(name, 0.0))
}
}
}
// Explicitly get latitude, longitude, altitude with their specific accessor functions.
exifInterface.latLong?.let { latLong ->
putDouble(ExifInterface.TAG_GPS_LATITUDE, latLong[0])
putDouble(ExifInterface.TAG_GPS_LONGITUDE, latLong[1])
putDouble(ExifInterface.TAG_GPS_ALTITUDE, exifInterface.getAltitude(0.0))
}
}
}
}
| packages/expo-image-picker/android/src/main/java/expo/modules/imagepicker/tasks/ImageResultTask.kt | 3443121014 |
package com.github.kittinunf.fuel.core
import java.util.concurrent.Callable
import java.util.concurrent.Executor
import java.util.concurrent.ExecutorService
import java.util.concurrent.Future
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
typealias RequestTransformer = (Request) -> Request
typealias ResponseTransformer = (Request, Response) -> Response
typealias InterruptCallback = (Request) -> Unit
typealias ResponseValidator = (Response) -> Boolean
data class RequestExecutionOptions(
val client: Client,
val socketFactory: SSLSocketFactory? = null,
val hostnameVerifier: HostnameVerifier? = null,
val executorService: ExecutorService,
val callbackExecutor: Executor,
val requestTransformer: RequestTransformer,
var responseTransformer: ResponseTransformer
) {
val requestProgress: Progress = Progress()
val responseProgress: Progress = Progress()
var timeoutInMillisecond: Int = 15_000
var timeoutReadInMillisecond: Int = 15_000
var decodeContent: Boolean? = null
var allowRedirects: Boolean? = null
var useHttpCache: Boolean? = null
var interruptCallbacks: MutableCollection<InterruptCallback> = mutableListOf()
var forceMethods: Boolean = false
var responseValidator: ResponseValidator = { response ->
!(response.isServerError || response.isClientError)
}
/**
* Executes a callback [f] onto the [Executor]
*
* @note this can be used to handle callbacks on a different Thread than the network request is made
*/
fun callback(f: () -> Unit) = callbackExecutor.execute(f)
/**
* Submits the task to the [ExecutorService]
*
* @param task [Callable] the execution of [Request] that yields a [Response]
* @return [Future] the future that resolves to a [Response]
*/
fun submit(task: Callable<Response>): Future<Response> = executorService.submit(task)
val interruptCallback: InterruptCallback = { request -> interruptCallbacks.forEach { it(request) } }
/**
* Append a response transformer
*/
operator fun plusAssign(next: ResponseTransformer) {
val previous = responseTransformer
responseTransformer = { request, response -> next(request, previous(request, response)) }
}
}
| fuel/src/main/kotlin/com/github/kittinunf/fuel/core/RequestExecutionOptions.kt | 2848946019 |
package com.xenoage.utils.math
/**
* Interface for a 2D shape (rectangle, circle, polygon, ...).
*/
interface Shape {
/** Returns true, if the given point is contained within this shape. */
operator fun contains(point: Point2f): Boolean
}
| utils-kotlin/src/com/xenoage/utils/math/Shape.kt | 1396962163 |
// Copyright 2015-present 650 Industries. All rights reserved.
package host.exp.exponent
import android.content.Context
import host.exp.exponent.analytics.EXL
import host.exp.exponent.experience.ExperienceActivity
class ExponentUncaughtExceptionHandler(private val context: Context) : Thread.UncaughtExceptionHandler {
private val oldExceptionHandler = Thread.getDefaultUncaughtExceptionHandler()
override fun uncaughtException(thread: Thread, ex: Throwable) {
try {
ExperienceActivity.removeNotification(context)
} catch (e: Throwable) {
// Don't ever want to crash before getting to default exception handler
EXL.e(TAG, e)
}
oldExceptionHandler.uncaughtException(thread, ex)
// TODO: open up home screen with error screen preloaded.
// KernelProvider.getInstance().handleError doesn't always work because sometimes the process gets corrupted.
System.exit(1)
}
companion object {
private val TAG = ExponentUncaughtExceptionHandler::class.java.simpleName
}
}
| android/expoview/src/main/java/host/exp/exponent/ExponentUncaughtExceptionHandler.kt | 2407606144 |
package <%= appPackage %>.ui.util
import android.app.Activity
import android.os.Bundle
import <%= appPackage %>.R
import com.readystatesoftware.chuck.Chuck
import io.palaima.debugdrawer.actions.ActionsModule
import io.palaima.debugdrawer.actions.ButtonAction
import io.palaima.debugdrawer.commons.BuildModule
import io.palaima.debugdrawer.commons.DeviceModule
import io.palaima.debugdrawer.commons.NetworkModule
import io.palaima.debugdrawer.commons.SettingsModule
import io.palaima.debugdrawer.timber.TimberModule
import io.palaima.debugdrawer.view.DebugView
class DebugViewActivity : Activity() {
private lateinit var debugView: DebugView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_debug_view)
debugView = findViewById(R.id.debug_view)
val chuckBtn = ButtonAction(
"ChuckInterceptor ",
{ startActivity(Chuck.getLaunchIntent(this)) }
)
debugView.modules(
ActionsModule(
chuckBtn),
TimberModule(),
BuildModule(this),
DeviceModule(this),
NetworkModule(this),
SettingsModule(this)
)
}
override protected fun onStart() {
super.onStart()
debugView.onStart()
}
override protected fun onResume() {
super.onResume()
debugView.onResume()
}
override protected fun onPause() {
super.onPause()
debugView.onPause()
}
override protected fun onStop() {
super.onStop()
debugView.onStop()
}
} | generator-ssb/generators/templates/template-normal/app/src/main/kotlin/com/grayherring/temp/ui/util/DebugViewActivity.kt | 1050970926 |
package org.jetbrains.fortran.ide.inspections
import org.junit.Test
class FortranTypeCheckInspectionTest() : FortranInspectionsBaseTestCase(FortranTypeCheckInspection()) {
@Test
fun testDeclarationIntegerToInteger() = checkByText(
"""
program p
integer :: a = 1
end program
""", true
)
@Test
fun testDeclarationIntegerArithmBinaryOperationToInteger() = checkByText("""
program p
integer :: a = 1 + 3 * 2 - 8 / 19 - 0
end program
""", true)
@Test
fun testDeclarationParenthesizedIntegerToInteger() = checkByText("""
program p
integer :: a = (((((1)))))
end program
""", true)
@Test
fun testDeclarationCharacterToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `character`">"a"</warning>
end program
""", true)
@Test
fun testDeclarationLogicalToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `logical`">.true.</warning>
end program
""", true)
@Test
fun testDeclarationComplexToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `complex`">(1, 2)</warning>
end program
""", true)
@Test
fun testDeclarationRealToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `real`">3.14</warning>
end program
""", true)
@Test
fun testDeclarationDoublePrecisionRealToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `double precision`">1.0D0</warning>
end program
""", true)
@Test
fun testDeclarationRealAdditionToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `real`">1 + 1.0</warning>
end program
""", true)
@Test
fun testDeclarationLogicalAndToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched typesexpected `integer`, found `logical`">.true. .AND. .false.</warning>
end program
""", true)
@Test
fun testDeclarationUnableToInferTypeToInteger() = checkByText("""
program p
integer :: a = <warning descr="mismatched argument typesleft argument: integer, right argument: logical">1 + .true.</warning>
end program
""", true)
@Test
fun testDeclarationRealToReal() = checkByText("""
program p
real :: a = 1.0
end program
""", true)
@Test
fun testDeclarationCharacterToReal() = checkByText("""
program p
real :: a = <warning descr="mismatched typesexpected `real`, found `character`">"1.0"</warning>
end program
""", true)
@Test
fun testDeclarationLogicalToReal() = checkByText("""
program p
real :: a = <warning descr="mismatched typesexpected `real`, found `logical`">.true.</warning>
end program
""", true)
@Test
fun testDeclarationComplexToReal() = checkByText("""
program p
real :: a = <warning descr="mismatched typesexpected `real`, found `complex`">(1.0, 2.0)</warning>
end program
""", true)
@Test
fun testDeclarationIntegerToReal() = checkByText("""
program p
real :: a = 3
end program
""", true)
@Test
fun testDeclarationDoublePrecisionRealToReal() = checkByText("""
program p
real :: a = <warning descr="mismatched typesexpected `real`, found `double precision`">1.0D0</warning>
end program
""", true)
@Test
fun testDeclarationRealAdditionToReal() = checkByText("""
program p
real :: a = 1 + 1.0
end program
""", true)
@Test
fun testDeclarationLogicalNotToReal() = checkByText("""
program p
real :: a = <warning descr="mismatched typesexpected `real`, found `logical`">.not. .true.</warning>
end program
""", true)
@Test
fun testDeclarationParenthesizedRealToReal() = checkByText("""
program p
real :: a = (((((1)))))
end program
""", true)
@Test
fun testDeclarationUnableToInferTypeToReal() = checkByText("""
program p
real :: a = <warning descr="mismatched argument typesleft argument: real, right argument: character">1.1 + "0.1"</warning>
end program
""", true)
@Test
fun testDeclarationLogicalToLogical() = checkByText("""
program p
logical :: a = .true.
logical :: b = .false.
end program
""", true)
@Test
fun testDeclarationCharacterToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `character`">"true"</warning>
end program
""", true)
@Test
fun testDeclarationIntegerToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `integer`">0</warning>
end program
""", true)
@Test
fun testDeclarationRealToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `real`">0.0</warning>
end program
""", true)
@Test
fun testDeclarationComplexToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `complex`">(1, 0)</warning>
end program
""", true)
@Test
fun testDeclarationDoublePrecisionLogicalToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `double precision`">1.0D0</warning>
end program
""", true)
@Test
fun testDeclarationRealAdditionToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `real`">0 - 1.0</warning>
end program
""", true)
@Test
fun testDeclarationLogicalNotToLogical() = checkByText("""
program p
logical :: a = .not. .false.
end program
""", true)
@Test
fun testDeclarationParenthesizedIntegerToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched typesexpected `logical`, found `integer`">(((((1)))))</warning>
end program
""", true)
@Test
fun testDeclarationParenthesizedLogicalToLogical() = checkByText("""
program p
logical :: a = (((((.true.)))))
end program
""", true)
@Test
fun testDeclarationUnableToInferTypeToLogical() = checkByText("""
program p
logical :: a = <warning descr="mismatched argument typesleft argument: logical, right argument: character">.true. .OR. "false"</warning>
end program
""", true)
@Test
fun testDeclarationComplexToComplex() = checkByText("""
program p
complex :: a = (1.0, 2)
end program
""", true)
@Test
fun testDeclarationCharacterToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `character`">"(1, 2.0)"</warning>
end program
""", true)
@Test
fun testDeclarationIntegerToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `integer`">0</warning>
end program
""", true)
@Test
fun testDeclarationRealToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `real`">0.0</warning>
end program
""", true)
@Test
fun testDeclarationDoublePrecisionToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `double precision`">1.0D0</warning>
end program
""", true)
@Test
fun testDeclarationRealAdditionToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `real`">0 - 1.0</warning>
end program
""", true)
@Test
fun testDeclarationComplexMultiplicationToComplex() = checkByText("""
program p
complex :: a = (0.1, 8.9) * (1.0, 2)
end program
""", true)
@Test
fun testDeclarationLogicalOrToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `logical`">.true. .OR. (.not. .false.)</warning>
end program
""", true)
@Test
fun testDeclarationUnableToInferTypeToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched argument typesleft argument: complex, right argument: character">(1.0, 2) + "(0.1, 0.2)"</warning>
end program
""", true)
@Test
fun testDeclarationCharacterToCharacter() = checkByText("""
program p
character :: a = "a"
end program
""", true)
@Test
fun testDeclarationComplexToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `complex`">(1, 2.0)</warning>
end program
""", true)
@Test
fun testDeclarationIntegerToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `integer`">0</warning>
end program
""", true)
@Test
fun testDeclarationRealToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `real`">0.0</warning>
end program
""", true)
@Test
fun testDeclarationDoublePrecisionToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `double precision`">1.0D0</warning>
end program
""", true)
@Test
fun testDeclarationRealPowerToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `real`">2.1 ** 1</warning>
end program
""", true)
@Test
fun testDeclarationComplexMultiplicationToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `complex`">(0.1, 8.9) * (1.0, 2)</warning>
end program
""", true)
@Test
fun testDeclarationLogicalOrToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched typesexpected `character`, found `logical`">.true. .OR. (.not. .false.)</warning>
end program
""", true)
@Test
fun testDeclarationConcatToCharacter() = checkByText("""
program p
character :: a = "a"
character :: b = "b"
character :: ab = a // b
end program
""", true)
@Test
fun testDeclarationUnableToInferTypeToCharacter() = checkByText("""
program p
character :: a = <warning descr="mismatched argument typesleft argument: character, right argument: complex">"(1.0, 2)" // (0.1, 0.2)</warning>
end program
""", true)
@Test
fun testAssignmentIntegerToInteger() = checkByText("""
program p
integer :: a = 1
a = -1
end program
""", true)
@Test
fun testAssignmentIntegerArithmBinaryOperationToInteger() = checkByText("""
program p
integer :: a = 1
a = a + 3 * 2 - 8 / 19 - 0
end program
""", true)
@Test
fun testAssignmentParenthesizedIntegerToInteger() = checkByText("""
program p
integer :: a = 1
a = (((((1)))))
end program
""", true)
@Test
fun testAssignmentLogicalToInteger() = checkByText("""
program p
integer :: a = 1
a = <warning descr="mismatched typesexpected `integer`, found `logical`">.true.</warning>
end program
""", true)
@Test
fun testAssignmentRealToInteger() = checkByText("""
program p
integer :: a = 2
a = <warning descr="mismatched typesexpected `integer`, found `real`">3.14</warning>
end program
""", true)
@Test
fun testAssignmentRealAdditionToInteger() = checkByText("""
program p
integer :: a = 1
a = <warning descr="mismatched typesexpected `integer`, found `real`">1 + 1.0</warning>
end program
""", true)
@Test
fun testAssignmentRealToReal() = checkByText("""
program p
real :: a
a = 1.1
a = -1.2
a = 4.5
end program
""", true)
@Test
fun testAssignmentCharacterToReal() = checkByText("""
program p
real :: a = 2
a = <warning descr="mismatched typesexpected `real`, found `character`">"1.0"</warning>
end program
""", true)
@Test
fun testAssignmentIntegerToReal() = checkByText("""
program p
real :: a = 3.14
a = 3
end program
""", true)
@Test
fun testAssignmentLogicalNotToReal() = checkByText("""
program p
real :: a = 2
a = <warning descr="mismatched typesexpected `real`, found `logical`">.not. .true.</warning>
end program
""", true)
@Test
fun testAssignmentLogicalToLogical() = checkByText("""
program p
logical :: a
logical :: b
a = .true.
b = .false.
end program
""", true)
@Test
fun testAssignmentIntegerToLogical() = checkByText("""
program p
logical :: a = .true.
a = <warning descr="mismatched typesexpected `logical`, found `integer`">0</warning>
end program
""", true)
@Test
fun testAssignmentComplexToLogical() = checkByText("""
program p
logical :: a
a = .true.
a = <warning descr="mismatched typesexpected `logical`, found `complex`">(1, 0)</warning>
a = .false.
end program
""", true)
@Test
fun testAssignmentLogicalNotToLogical() = checkByText("""
program p
logical :: a
a = .not. .false.
end program
""", true)
@Test
fun testAssignmentComplexToComplex() = checkByText("""
program p
complex :: a
a = (1.0, 2)
end program
""", true)
@Test
fun testAssignmentRealToComplex() = checkByText("""
program p
complex :: a = (1, 2)
a = <warning descr="mismatched typesexpected `complex`, found `real`">0.0</warning>
end program
""", true)
@Test
fun testAssignmentDoublePrecisionToComplex() = checkByText("""
program p
complex :: a = <warning descr="mismatched typesexpected `complex`, found `double precision`">1.0D0</warning>
end program
""", true)
@Test
fun testAssignmentCharacterToCharacter() = checkByText("""
program p
character :: a
a = "a"
end program
""", true)
@Test
fun testAssignmentComplexToCharacter() = checkByText("""
program p
character :: a = "a"
a = "b"
a = <warning descr="mismatched typesexpected `character`, found `complex`">(1, 2.0)</warning>
end program
""", true)
@Test
fun testAssignmentConcatToCharacter() = checkByText("""
program p
character :: a = "a"
character :: b = "b"
character :: ab
ab = a // b
end program
""", true)
@Test
fun testDeclarationDoublePrecisionToDoublePrecision() = checkByText("""
program p
double precision :: a = 0.25D0
end program
""", true)
@Test
fun testDeclarationCharacterToDoublePrecision() = checkByText("""
program p
double precision :: a = <warning descr="mismatched typesexpected `double precision`, found `character`">"1.0D0"</warning>
end program
""", true)
@Test
fun testDeclarationLogicalToDoublePrecision() = checkByText("""
program p
double precision :: a = <warning descr="mismatched typesexpected `double precision`, found `logical`">.true.</warning>
end program
""", true)
@Test
fun testDeclarationComplexToDoublePrecision() = checkByText("""
program p
double precision :: a = <warning descr="mismatched typesexpected `double precision`, found `complex`">(1.0D0, 2.0D0)</warning>
end program
""", true)
@Test
fun testDeclarationIntegerToDoublePrecision() = checkByText("""
program p
double precision :: a = 3
end program
""", true)
@Test
fun testDeclarationRealToDoublePrecision() = checkByText("""
program p
double precision :: a = 1.0
end program
""", true)
@Test
fun testDeclarationDoublePrecisionAdditionToDoublePrecision() = checkByText("""
program p
double precision :: a = 1 + 1.0 + 1.0D0
end program
""", true)
@Test
fun testDeclarationLogicalNotToDoublePrecision() = checkByText("""
program p
double precision :: a = <warning descr="mismatched typesexpected `double precision`, found `logical`">.not. .true.</warning>
end program
""", true)
@Test
fun testDeclarationParenthesizedDoublePrecisionToDoublePrecision() = checkByText("""
program p
double precision :: a = (((((1.24D0)))))
end program
""", true)
@Test
fun testDeclarationUnableToInferTypeToDoublePrecision() = checkByText("""
program p
double precision :: a = <warning descr="mismatched argument typesleft argument: double precision, right argument: character">1.1D0 + "0.1"</warning>
end program
""", true)
@Test
fun testDeclarationIntegerArray() = checkByText("""
program p
integer, dimension(3) :: a = (/1, 2, 3/)
end program
""", true)
@Test
fun testAssignmentIntegerArray() = checkByText("""
program p
integer, dimension(3) :: a
a = (/1, 2, 3/)
end program
""", true)
@Test
fun testDeclarationRealToIntegerArray() = checkByText("""
program p
integer, dimension(3) :: a
a = <warning descr="mismatched typesexpected `integer array of shape (1:3)`, found `real array of shape (1:3)`">(/1, 2, 3.1/)</warning>
end program
""", true)
@Test
fun testAssignmentIntegerToRealArray() = checkByText("""
program p
real, dimension(3) :: a
a = (/1, 2, 3/)
end program
""", true)
@Test
fun testAssignmentMalformedArrayConstructorToCharacterArray() = checkByText("""
program p
character, dimension(3) :: a
a = (/"a", <warning descr="mismatched array constructor element typearray base type: character, element type: integer">2</warning>, "c"/)
end program
""", true)
@Test
fun testAssignmentCorrectImplicitDo() = checkByText("""
program p
integer, dimension(3) :: a
a = (/(I, I = 4, 6)/)
end program
""", true)
@Test
fun testAssignmentWrongArraySize() = checkByText("""
program p
logical, dimension(3) :: a
a = <warning descr="mismatched typesexpected `logical array of shape (1:3)`, found `logical array of shape (1:2)`">(/.true., .false./)</warning>
end program
""", true)
@Test
fun testDoublePrecisionArray() = checkByText("""
program p
double precision, dimension(3) :: a
a = (/1, 1.0, 1.0D0/)
a = <warning descr="mismatched typesexpected `double precision array of shape (1:3)`, found `logical array of shape (1:3)`">(/.true., .false., .true./)</warning>
end program
""", true)
// TODO incorrect implicit do test
} | src/test/kotlin/org/jetbrains/fortran/ide/inspections/FortranTypeCheckInspectionTest.kt | 1679252109 |
val property = "test" | core/testdata/properties/valueProperty.kt | 2382095360 |
package org.mightyfrog.android.s4fd.details
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.appbar.AppBarLayout
import com.raizlabs.android.dbflow.sql.language.Select
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_details.*
import org.mightyfrog.android.s4fd.App
import org.mightyfrog.android.s4fd.R
import org.mightyfrog.android.s4fd.data.KHCharacter
import org.mightyfrog.android.s4fd.data.KHCharacter_Table
import org.mightyfrog.android.s4fd.details.tabcontents.attacks.AttacksFragment
import org.mightyfrog.android.s4fd.details.tabcontents.attributes.AttributesFragment
import org.mightyfrog.android.s4fd.details.tabcontents.miscs.MiscsFragment
import org.mightyfrog.android.s4fd.util.Const
import javax.inject.Inject
/**
* @author Shigehiro Soejima
*/
class DetailsActivity : AppCompatActivity(), DetailsContract.View, AppBarLayout.OnOffsetChangedListener {
@Inject
lateinit var detailsPresenter: DetailsPresenter
private val id: Int by lazy {
intent.getIntExtra("id", 0)
}
private val character: KHCharacter by lazy {
Select().from(KHCharacter::class.java).where(KHCharacter_Table.id.eq(id)).querySingle() as KHCharacter
}
private var charToCompare: KHCharacter? = null
private var isAppBarCollapsed = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (id <= 0 || id > Const.CHARACTER_COUNT) {
finish()
return
}
setTheme(resources.getIdentifier("CharTheme.$id", "style", packageName))
setContentView(R.layout.activity_details)
DaggerDetailsComponent.builder()
.appComponent((application as App).getAppComponent())
.detailsModule(DetailsModule(this))
.build()
.inject(this)
setSupportActionBar(toolbar)
val titles = resources.getStringArray(R.array.detail_tabs)
viewPager.adapter = TabContentAdapter(titles, supportFragmentManager, id)
viewPager.offscreenPageLimit = 3
tabLayout.setupWithViewPager(viewPager)
tabLayout.addOnTabSelectedListener(object : com.google.android.material.tabs.TabLayout.OnTabSelectedListener {
override fun onTabReselected(tab: com.google.android.material.tabs.TabLayout.Tab?) {
// no-op
}
override fun onTabUnselected(tab: com.google.android.material.tabs.TabLayout.Tab?) {
// no-op
}
override fun onTabSelected(tab: com.google.android.material.tabs.TabLayout.Tab?) {
invalidateOptionsMenu()
}
})
fab.setOnClickListener {
detailsPresenter compareTo id
}
findViewById<AppBarLayout>(R.id.appbar).addOnOffsetChangedListener(this)
Picasso.with(this)
.load(character.mainImageUrl)
.into(backdrop)
viewPager.post {
detailsPresenter.setCharToCompareIfAny(id)
supportActionBar?.apply {
title = character.displayName?.trim()
setDisplayHomeAsUpEnabled(true)
}
}
}
override fun onStart() {
super.onStart()
backdrop.visibility = View.VISIBLE
}
override fun onStop() {
backdrop.visibility = View.GONE
super.onStop()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.details, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
menu?.findItem(R.id.open_in_browser)?.isVisible = tabLayout.selectedTabPosition == 3
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> supportFinishAfterTransition()
R.id.open_in_browser -> openInBrowser()
}
return super.onOptionsItemSelected(item)
}
override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
appBarLayout ?: return
val maxScroll = appBarLayout.totalScrollRange
val percentage = Math.abs(verticalOffset) / maxScroll.toFloat()
if (percentage >= 0.7f && isAppBarCollapsed) {
fab.hide()
(vsThumbnail.parent as View).animate().setDuration(500L).alpha(0f).start()
isAppBarCollapsed = !isAppBarCollapsed
} else if (percentage < 0.7f && !isAppBarCollapsed) {
fab.show()
(vsThumbnail.parent as View).animate().setDuration(500L).alpha(1f).start()
isAppBarCollapsed = !isAppBarCollapsed
}
charToCompare?.apply {
if (percentage == 1f) {
collapsingToolbarLayout.title = getString(R.string.attr_compare, character.displayName, displayName)
} else {
collapsingToolbarLayout.title = character.displayName?.trim()
}
}
}
override fun setSubtitle(resId: Int, vararg args: String?) {
supportActionBar?.subtitle = getString(resId, args)
}
override fun clearSubtitle() {
supportActionBar?.subtitle = null
}
override fun hideVsThumbnail() {
vsThumbnail.visibility = View.GONE
}
override fun showVsThumbnail(charToCompare: KHCharacter?) {
with(vsThumbnail) {
charToCompare?.apply {
Picasso.with(context)
.load(thumbnailUrl)
.into(this@with)
(parent as androidx.cardview.widget.CardView).setCardBackgroundColor(Color.parseColor(colorTheme))
}
visibility = View.VISIBLE
alpha = 0f
animate().setDuration(750L).alpha(1f).start()
}
}
override fun setCharToCompare(charToCompare: KHCharacter?) {
this.charToCompare = charToCompare
val f0 = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 0) as AttributesFragment
f0.setCharToCompare(charToCompare)
val f1 = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 1) as AttacksFragment
f1.setCharToCompare(charToCompare)
val f2 = supportFragmentManager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 2) as MiscsFragment
f2.setCharToCompare(charToCompare)
}
override fun showCompareDialog(list: List<KHCharacter>, displayNames: List<String>, scrollPosition: Int) {
val dialog = AlertDialog.Builder(this)
.setTitle(R.string.compare)
.setSingleChoiceItems(displayNames.toTypedArray(), scrollPosition) { dialogInterface, which ->
detailsPresenter.setCharToCompare(id, list[which])
dialogInterface.dismiss()
}
.setNeutralButton(R.string.clear) { _, _ ->
detailsPresenter.setCharToCompare(id, null)
}
.setNegativeButton(R.string.cancel, null)
.create()
dialog.ownerActivity = this
dialog.show()
}
override fun showActivityCircle() {
activity_circle.visibility = View.VISIBLE
}
override fun hideActivityCircle() {
activity_circle.visibility = View.GONE
}
override fun setPresenter(presenter: DetailsPresenter) {
detailsPresenter = presenter
}
override fun showErrorMessage(msg: String) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
override fun showErrorMessage(resId: Int) {
showErrorMessage(getString(resId))
}
private fun openInBrowser() {
Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(character.fullUrl)
when (resolveActivity(packageManager)) {
null -> {
Toast.makeText(this@DetailsActivity, "No browser found :(", Toast.LENGTH_LONG).show()
}
else -> {
startActivity(this)
}
}
}
}
}
| app/src/main/java/org/mightyfrog/android/s4fd/details/DetailsActivity.kt | 4186268787 |
/*
* 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.input
import androidx.compose.ui.text.InternalTextApi
/**
* Like [toCharArray] but copies the entire source string.
* Workaround for compiler error when giving [toCharArray] above default parameters.
*/
private fun String.toCharArray(
destination: CharArray,
destinationOffset: Int
) = toCharArray(destination, destinationOffset, startIndex = 0, endIndex = this.length)
/**
* Copies characters from this [String] into [destination].
*
* Platform-specific implementations should use native functions for performing this operation if
* they exist, since they will likely be more efficient than copying each character individually.
*
* @param destination The [CharArray] to copy into.
* @param destinationOffset The index in [destination] to start copying to.
* @param startIndex The index in `this` of the first character to copy from (inclusive).
* @param endIndex The index in `this` of the last character to copy from (exclusive).
*/
internal expect fun String.toCharArray(
destination: CharArray,
destinationOffset: Int,
startIndex: Int,
endIndex: Int
)
/**
* The gap buffer implementation
*
* @param initBuffer An initial buffer. This class takes ownership of this object, so do not modify
* array after passing to this constructor
* @param initGapStart An initial inclusive gap start offset of the buffer
* @param initGapEnd An initial exclusive gap end offset of the buffer
*/
private class GapBuffer(initBuffer: CharArray, initGapStart: Int, initGapEnd: Int) {
/**
* The current capacity of the buffer
*/
private var capacity = initBuffer.size
/**
* The buffer
*/
private var buffer = initBuffer
/**
* The inclusive start offset of the gap
*/
private var gapStart = initGapStart
/**
* The exclusive end offset of the gap
*/
private var gapEnd = initGapEnd
/**
* The length of the gap.
*/
private fun gapLength(): Int = gapEnd - gapStart
/**
* [] operator for the character at the index.
*/
operator fun get(index: Int): Char {
if (index < gapStart) {
return buffer[index]
} else {
return buffer[index - gapStart + gapEnd]
}
}
/**
* Check if the gap has a requested size, and allocate new buffer if there is enough space.
*/
private fun makeSureAvailableSpace(requestSize: Int) {
if (requestSize <= gapLength()) {
return
}
// Allocating necessary memory space by doubling the array size.
val necessarySpace = requestSize - gapLength()
var newCapacity = capacity * 2
while ((newCapacity - capacity) < necessarySpace) {
newCapacity *= 2
}
val newBuffer = CharArray(newCapacity)
buffer.copyInto(newBuffer, 0, 0, gapStart)
val tailLength = capacity - gapEnd
val newEnd = newCapacity - tailLength
buffer.copyInto(newBuffer, newEnd, gapEnd, gapEnd + tailLength)
buffer = newBuffer
capacity = newCapacity
gapEnd = newEnd
}
/**
* Delete the given range of the text.
*/
private fun delete(start: Int, end: Int) {
if (start < gapStart && end <= gapStart) {
// The remove happens in the head buffer. Copy the tail part of the head buffer to the
// tail buffer.
//
// Example:
// Input:
// buffer: ABCDEFGHIJKLMNOPQ*************RSTUVWXYZ
// del region: |-----|
//
// First, move the remaining part of the head buffer to the tail buffer.
// buffer: ABCDEFGHIJKLMNOPQ*****KLKMNOPQRSTUVWXYZ
// move data: ^^^^^^^ => ^^^^^^^^
//
// Then, delete the given range. (just updating gap positions)
// buffer: ABCD******************KLKMNOPQRSTUVWXYZ
// del region: |-----|
//
// Output: ABCD******************KLKMNOPQRSTUVWXYZ
val copyLen = gapStart - end
buffer.copyInto(buffer, gapEnd - copyLen, end, gapStart)
gapStart = start
gapEnd -= copyLen
} else if (start < gapStart && end >= gapStart) {
// The remove happens with accrossing the gap region. Just update the gap position
//
// Example:
// Input:
// buffer: ABCDEFGHIJKLMNOPQ************RSTUVWXYZ
// del region: |-------------------|
//
// Output: ABCDEFGHIJKL********************UVWXYZ
gapEnd = end + gapLength()
gapStart = start
} else { // start > gapStart && end > gapStart
// The remove happens in the tail buffer. Copy the head part of the tail buffer to the
// head buffer.
//
// Example:
// Input:
// buffer: ABCDEFGHIJKL************MNOPQRSTUVWXYZ
// del region: |-----|
//
// First, move the remaining part in the tail buffer to the head buffer.
// buffer: ABCDEFGHIJKLMNO*********MNOPQRSTUVWXYZ
// move dat: ^^^ <= ^^^
//
// Then, delete the given range. (just updating gap positions)
// buffer: ABCDEFGHIJKLMNO******************VWXYZ
// del region: |-----|
//
// Output: ABCDEFGHIJKLMNO******************VWXYZ
val startInBuffer = start + gapLength()
val endInBuffer = end + gapLength()
val copyLen = startInBuffer - gapEnd
buffer.copyInto(buffer, gapStart, gapEnd, startInBuffer)
gapStart += copyLen
gapEnd = endInBuffer
}
}
/**
* Replace the certain region of text with given text
*
* @param start an inclusive start offset for replacement.
* @param end an exclusive end offset for replacement
* @param text a text to replace
*/
fun replace(start: Int, end: Int, text: String) {
makeSureAvailableSpace(text.length - (end - start))
delete(start, end)
text.toCharArray(buffer, gapStart)
gapStart += text.length
}
/**
* Write the current text into outBuf.
* @param builder The output string builder
*/
fun append(builder: StringBuilder) {
builder.append(buffer, 0, gapStart)
builder.append(buffer, gapEnd, capacity - gapEnd)
}
/**
* The lengh of this gap buffer.
*
* This doesn't include internal hidden gap length.
*/
fun length() = capacity - gapLength()
override fun toString(): String = StringBuilder().apply { append(this) }.toString()
}
/**
* An editing buffer that uses Gap Buffer only around the cursor location.
*
* Different from the original gap buffer, this gap buffer doesn't convert all given text into
* mutable buffer. Instead, this gap buffer converts cursor around text into mutable gap buffer
* for saving construction time and memory space. If text modification outside of the gap buffer
* is requested, this class flush the buffer and create new String, then start new gap buffer.
*
* @param text The initial text
* @suppress
*/
@InternalTextApi // "Used by benchmarks"
class PartialGapBuffer(var text: String) {
internal companion object {
const val BUF_SIZE = 255
const val SURROUNDING_SIZE = 64
const val NOWHERE = -1
}
private var buffer: GapBuffer? = null
private var bufStart = NOWHERE
private var bufEnd = NOWHERE
/**
* The text length
*/
val length: Int
get() {
val buffer = buffer ?: return text.length
return text.length - (bufEnd - bufStart) + buffer.length()
}
/**
* Replace the certain region of text with given text
*
* @param start an inclusive start offset for replacement.
* @param end an exclusive end offset for replacement
* @param text a text to replace
*/
fun replace(start: Int, end: Int, text: String) {
require(start <= end) {
"start index must be less than or equal to end index: $start > $end"
}
require(start >= 0) {
"start must be non-negative, but was $start"
}
val buffer = buffer
if (buffer == null) { // First time to create gap buffer
val charArray = CharArray(maxOf(BUF_SIZE, text.length + 2 * SURROUNDING_SIZE))
// Convert surrounding text into buffer.
val leftCopyCount = minOf(start, SURROUNDING_SIZE)
val rightCopyCount = minOf(this.text.length - end, SURROUNDING_SIZE)
// Copy left surrounding
this.text.toCharArray(charArray, 0, start - leftCopyCount, start)
// Copy right surrounding
this.text.toCharArray(
charArray,
charArray.size - rightCopyCount,
end,
end + rightCopyCount
)
// Copy given text into buffer
text.toCharArray(charArray, leftCopyCount)
this.buffer = GapBuffer(
charArray,
initGapStart = leftCopyCount + text.length,
initGapEnd = charArray.size - rightCopyCount
)
bufStart = start - leftCopyCount
bufEnd = end + rightCopyCount
return
}
// Convert user space offset into buffer space offset
val bufferStart = start - bufStart
val bufferEnd = end - bufStart
if (bufferStart < 0 || bufferEnd > buffer.length()) {
// Text modification outside of gap buffer has requested. Flush the buffer and try it
// again.
this.text = toString()
this.buffer = null
bufStart = NOWHERE
bufEnd = NOWHERE
return replace(start, end, text)
}
buffer.replace(bufferStart, bufferEnd, text)
}
/**
* [] operator for the character at the index.
*/
operator fun get(index: Int): Char {
val buffer = buffer ?: return text[index]
if (index < bufStart) {
return text[index]
}
val gapBufLength = buffer.length()
if (index < gapBufLength + bufStart) {
return buffer[index - bufStart]
}
return text[index - (gapBufLength - bufEnd + bufStart)]
}
override fun toString(): String {
val b = buffer ?: return text
val sb = StringBuilder()
sb.append(text, 0, bufStart)
b.append(sb)
sb.append(text, bufEnd, text.length)
return sb.toString()
}
}
| compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/input/GapBuffer.kt | 3919217370 |
package com.mateuszkoslacz.moviper.rxsample.viper.view.activity
import android.content.Context
import android.content.Intent
import android.view.View
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.mateuszkoslacz.moviper.base.view.activity.autoinject.passive.ViperLceAiPassiveActivity
import com.mateuszkoslacz.moviper.iface.interactor.CommonViperInteractor
import com.mateuszkoslacz.moviper.iface.presenter.ViperPresenter
import com.mateuszkoslacz.moviper.iface.routing.CommonViperRouting
import com.mateuszkoslacz.moviper.rxsample.R
import com.mateuszkoslacz.moviper.rxsample.viper.contract.UserDetailsContract
import com.mateuszkoslacz.moviper.rxsample.viper.entity.User
import com.mateuszkoslacz.moviper.presentersdispatcher.MoviperPresentersDispatcher
import kotlinx.android.synthetic.main.activity_user_details.*
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
class UserDetailsActivity :
ViperLceAiPassiveActivity<LinearLayout, User, UserDetailsContract.View>(),
UserDetailsContract.View, UserDetailsContract.ViewHelper {
override val avatarClicks: Observable<String>
get() = mAvatarClicks
override val avatarImageView: View
get() = avatar
internal var mAvatarClicks = PublishSubject.create<String>()
override fun bindDataToViews(user: User) {
login?.text = user.login
url?.text = user.url
name?.text = user.name
company?.text = user.company
blog?.text = user.blog
location?.text = user.location
email?.text = user.email
Glide.with(this)
.load(user.avatarUrl)
.into(avatar)
avatar?.setOnClickListener { mAvatarClicks.onNext(user.avatarUrl) }
}
override fun setData(user: User) = bindDataToViews(user)
override fun getErrorMessage(e: Throwable, pullToRefresh: Boolean): String = e.message!!
override fun loadData(pullToRefresh: Boolean) {}
override fun createPresenter(): ViperPresenter<UserDetailsContract.View> =
MoviperPresentersDispatcher.getInstance().getPresenterForView(this)
as ViperPresenter<UserDetailsContract.View>
override fun getLayoutId(): Int = R.layout.activity_user_details
companion object {
val USER_EXTRA = "USER_EXTRA"
fun start(context: Context, user: User) {
context.startActivity(getStartingIntent(context, user))
}
fun getStartingIntent(context: Context, user: User): Intent {
val starter = Intent(context, UserDetailsActivity::class.java)
starter.putExtra(USER_EXTRA, user.login)
return starter
}
}
}
| sample-super-rx-ai-kotlin/src/main/java/com/mateuszkoslacz/moviper/rxsample/viper/view/activity/UserDetailsActivity.kt | 951440303 |
@file:JvmName("LockScreenHelper")
package nerd.tuxmobil.fahrplan.congress.utils
import android.app.Activity
import android.os.Build
import android.view.WindowManager
/**
* Enables this [Activity][this] to be shown on top of the lock screen whenever the lock screen
* is up and the [Activity] is resumed.
*/
fun Activity.showWhenLockedCompat() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
setShowWhenLocked(true)
} else {
@Suppress("DEPRECATION")
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
}
}
| app/src/main/java/nerd/tuxmobil/fahrplan/congress/utils/LockScreenHelper.kt | 23826341 |
package at.ac.tuwien.caa.docscan.camera
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.annotation.Nullable
import androidx.recyclerview.widget.GridLayoutManager
import at.ac.tuwien.caa.docscan.R
import at.ac.tuwien.caa.docscan.databinding.TextDirSheetDialogBinding
class TextOrientationActionSheet(
sheetActions: ArrayList<SheetAction>, selectionListener: SheetSelection,
dialogListener: DialogStatus, var confirmListener: DialogConfirm,
private val opaque: Boolean = true
) : ActionSheet(sheetActions, selectionListener, dialogListener) {
private lateinit var binding: TextDirSheetDialogBinding
override fun onCreate(@Nullable savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val style: Int =
if (opaque)
R.style.BottomSheetDialogDarkTheme
else
R.style.TransparentBottomSheetDialogDarkTheme
setStyle(STYLE_NORMAL, style)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
// Lambda for RecyclerView clicks. Got this from:
// https://www.andreasjakl.com/recyclerview-kotlin-style-click-listener-android/
val sheetAdapter =
SheetAdapter(sheetActions) { sheetAction: SheetAction -> sheetClicked(sheetAction) }
binding.sheetDialogRecyclerview.apply {
adapter = sheetAdapter
layoutManager = GridLayoutManager([email protected], 2)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = TextDirSheetDialogBinding.inflate(layoutInflater, container, false)
binding.apply {
textOrientationSheetOkButton.setOnClickListener {
dismiss()
}
textOrientationSheetCancelButton.setOnClickListener {
dismiss()
confirmListener.onCancel()
}
}
return binding.root
}
override fun sheetClicked(sheetAction: SheetAction) {
// Just tell the listener, but do not close the dialog. So do not call super.sheetClicked
listener?.onSheetSelected(sheetAction)
}
override fun onStart() {
// Don't dim the background, because we need to see what is happening there:
super.onStart()
val window = dialog?.window
val windowParams = window!!.attributes
windowParams.dimAmount = 0f
windowParams.flags = windowParams.flags or WindowManager.LayoutParams.FLAG_DIM_BEHIND
window.attributes = windowParams
}
interface DialogConfirm {
fun onOk()
fun onCancel()
}
}
| app/src/main/java/at/ac/tuwien/caa/docscan/camera/TextOrientationActionSheet.kt | 4278531520 |
package com.lwh.jackknife.crash.filter
import java.util.*
/**
* It is used to combine the superposition of two or more filters.
* 通过它来组合两种或两种以上的过滤器的叠加。
*/
class CrashFilterChain {
private val filters: MutableList<CrashFilter>
fun addFirst(filter: CrashFilter): CrashFilterChain {
filters.add(0, filter)
return this
}
fun addLast(filter: CrashFilter): CrashFilterChain {
filters.add(filter)
return this
}
/**
* The whole filter chain.
* 一条完整的过滤器链。
*/
val filter: CrashFilter?
get() {
var first: CrashFilter? = null
var last: CrashFilter? = null //上次的
for (i in filters.indices) {
val filter = filters[i]
if (i == 0) {
first = filter
} else {
last!!.setNextFilter(filter)
}
last = filter
}
return first
}
init {
filters = LinkedList()
}
} | bugskiller/src/main/java/com/lwh/jackknife/crash/filter/CrashFilterChain.kt | 1795529135 |
package com.adgvcxz.diycode.util
/**
* zhaowei
* Created by zhaowei on 2017/2/16.
*/
enum class FragmentLifeCycleEvent {
Attach,
Create,
CreateView,
ActivityCreated,
Start,
Resume,
Pause,
Stop,
DestroyView,
Destroy,
Detach
}
| app/src/main/java/com/adgvcxz/diycode/util/FragmentLifeCycleEvent.kt | 2644242674 |
/*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.viewmodel
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.annotation.DrawableRes
import androidx.core.graphics.drawable.DrawableCompat
import net.mm2d.android.util.DrawableUtils
import net.mm2d.android.util.toDisplayableString
import net.mm2d.dmsexplorer.R
import net.mm2d.dmsexplorer.domain.entity.ContentEntity
import net.mm2d.dmsexplorer.domain.entity.ContentType
import net.mm2d.dmsexplorer.settings.Settings
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class ContentItemModel(
context: Context,
entity: ContentEntity,
val selected: Boolean
) {
val accentBackground: Drawable
val accentText: String
val title: String
val description: String
val hasDescription: Boolean
@DrawableRes
val imageResource: Int
val isProtected: Boolean
init {
val name = entity.name
accentText = if (name.isEmpty()) "" else name.substring(0, 1).toDisplayableString()
val generator = Settings.get()
.themeParams
.themeColorGenerator
accentBackground = DrawableUtils.get(context, R.drawable.ic_circle)!!.also {
it.mutate()
DrawableCompat.setTint(it, generator.getIconColor(name))
}
title = name.toDisplayableString()
description = entity.description
hasDescription = description.isNotEmpty()
imageResource = getImageResource(entity)
isProtected = entity.isProtected
}
@DrawableRes
private fun getImageResource(entity: ContentEntity): Int = when (entity.type) {
ContentType.CONTAINER -> R.drawable.ic_folder
ContentType.MOVIE -> R.drawable.ic_movie
ContentType.MUSIC -> R.drawable.ic_music
ContentType.PHOTO -> R.drawable.ic_image
else -> 0
}
}
| mobile/src/main/java/net/mm2d/dmsexplorer/viewmodel/ContentItemModel.kt | 1125546617 |
/*
* Copyright (c) 2017 stfalcon.com
*
* 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.stfalcon.new_uaroads_android.features.record
import android.location.Location
import com.stfalcon.mvphelper.IPresenter
import com.stfalcon.new_uaroads_android.features.record.service.IRecordService
/*
* Created by Anton Bevza on 4/19/17.
*/
class RecordContract {
interface View {
fun showLastSessionDistance(distance: Int)
fun showProcessedDistance(distance: Int)
fun showCurrentSessionDistance(distance: Int)
fun showForceValue(value: Double)
fun showIdleState()
fun showRecordState()
fun showPauseState()
fun showGpsSignalStatus(location: Location)
fun startRecordService()
fun showError(error: String?)
fun showAuthState(isAuth: Boolean)
fun navigateToSettings()
fun openHomePage()
}
interface Presenter: IPresenter<View> {
fun onStartButtonClicked()
fun onPauseButtonClicked()
fun onStopButtonClicked()
fun onContinueButtonClicked()
fun onServiceConnected(service: IRecordService)
fun onServiceDisconnected()
fun onLoginButtonClicked()
fun onCopyrightClicked()
}
}
| app/src/main/java/com/stfalcon/new_uaroads_android/features/record/RecordContract.kt | 54225121 |
package com.nobrain.android.lottiefiles.repository
interface FilePath {
fun path() : String
} | app/src/main/kotlin/com/nobrain/android/lottiefiles/repository/FilePath.kt | 4121879592 |
package core.impl
import core.api.camelCase
import org.junit.Assert.assertEquals
import org.junit.Test
class CoreImplTest {
@Test fun testCamelCaseVar() {
val foo = ImplType("foo_bar")
assertEquals("FooBar", foo.camelName)
}
@Test fun testCamelCaseFun() {
// Testing transitivity here. TODO: Once strict deps are in place, delete this case.
assertEquals("FooBar", "foo_bar".camelCase())
}
}
| examples/associates/projects/core/impl/src/test/kotlin/core/impl/CoreImplTest.kt | 242947706 |
package carbon.widget
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
class ViewPagerAdapter : PagerAdapter {
class Item(val view: View, val title: String?)
val items: Array<Item>
constructor(views: Array<View>) : super() {
this.items = (views.map { Item(it, null) }).toTypedArray()
}
constructor(items: Array<Item>) : super() {
this.items = items
}
override fun getPageTitle(position: Int): CharSequence? {
return items[position].title
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun getCount() = items.size
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val pager = container as ViewPager
val view = items[position].view
pager.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, view: Any) {
container.removeView(view as View)
}
} | carbon/src/main/java/carbon/widget/ViewPagerAdapter.kt | 2531177718 |
package com.vimeo.stag.processor.functional
import com.google.testing.compile.Compilation
import com.vimeo.sample_java_model.*
import com.vimeo.stag.processor.ProcessorTester
import com.vimeo.stag.processor.StagProcessor
import com.vimeo.stag.processor.isSuccessful
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import kotlin.reflect.KClass
/**
* Functional tests for the integrations in the `integration-test-java` module.
*/
class JavaIntegrationFunctionalTests {
private val processorTester = ProcessorTester({ StagProcessor() }, "-AstagAssumeHungarianNotation=true")
private val module = "integration-test-java"
@Test
fun `AlternateNameModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(AlternateNameModel::class)
}
@Test
fun `AlternateNameModel1 compiles successfully`() {
assertThatClassCompilationIsSuccessful(AlternateNameModel1::class)
}
@Test
fun `BaseExternalModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(BaseExternalModel::class)
}
@Test
fun `BooleanFields compiles successfully`() {
assertThatClassCompilationIsSuccessful(BooleanFields::class)
}
@Test
fun `EnumWithFieldsModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(EnumWithFieldsModel::class)
}
@Test
fun `ExternalAbstractClass compiles successfully`() {
assertThatClassCompilationIsSuccessful(ExternalAbstractClass::class)
}
@Test
fun `ExternalModel1 compiles successfully`() {
assertThatClassCompilationIsSuccessful(ExternalModel1::class)
}
@Test
fun `ExternalModel2 compiles successfully`() {
assertThatClassCompilationIsSuccessful(ExternalModel2::class)
}
@Test
fun `ExternalModelGeneric compiles successfully`() {
assertThatClassCompilationIsSuccessful(ExternalModelGeneric::class)
}
@Test
fun `ExternalModelGeneric1 compiles successfully`() {
assertThatClassCompilationIsSuccessful(ExternalModelGeneric1::class)
}
@Test
fun `ModelWithNestedInterface compiles successfully`() {
assertThatClassCompilationIsSuccessful(ModelWithNestedInterface::class)
}
@Test
fun `NativeJavaModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(NativeJavaModel::class)
}
@Test
fun `NativeJavaModelExtension compiles successfully`() {
assertThatClassCompilationIsSuccessful(NativeJavaModelExtension::class)
}
@Test
fun `NativeJavaModelExtensionWithoutAnnotation compiles successfully`() {
assertThatClassCompilationIsSuccessful(NativeJavaModelExtensionWithoutAnnotation::class)
}
@Test
fun `RawGenericField compiles successfully`() {
assertThatClassCompilationIsSuccessful(RawGenericField::class)
}
@Test
fun `NullFields compiles successfully`() {
assertThatClassCompilationIsSuccessful(NullFields::class)
}
@Test
fun `PrivateMembers compiles successfully`() {
assertThatClassCompilationIsSuccessful(PrivateMembers::class)
}
@Test
fun `WildcardModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(WildcardModel::class)
}
@Test
fun `DynamicallyTypedModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(DynamicallyTypedModel::class)
}
@Test
fun `DynamicallyTypedWildcard compiles successfully`() {
assertThatClassCompilationIsSuccessful(DynamicallyTypedWildcard::class)
}
@Test
fun `AbstractDataList compiles successfully`() {
assertThatClassCompilationIsSuccessful(AbstractDataList::class)
}
@Test
fun `SuperAbstractDataList compiles successfully`() {
assertThatClassCompilationIsSuccessful(SuperAbstractDataList::class)
}
@Test
fun `ConcreteDataList compiles successfully`() {
assertThatClassCompilationIsSuccessful(ConcreteDataList::class)
}
@Test
fun `PublicFieldsNoHungarian compiles successfully`() {
val processorTesterWithNoHungarian = ProcessorTester({ StagProcessor() }, "-AstagAssumeHungarianNotation=false")
assertThat(processorTesterWithNoHungarian.compileClassesInModule(module, PublicFieldsNoHungarian::class).isSuccessful()).isTrue()
val processorTesterWithHungarian = ProcessorTester({ StagProcessor() }, "-AstagAssumeHungarianNotation=true")
assertThat(processorTesterWithHungarian.compileClassesInModule(module, PublicFieldsNoHungarian::class).isSuccessful()).isTrue()
}
@Test
fun `SwappableParserExampleModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(SwappableParserExampleModel::class)
}
@Test
fun `WrapperTypeAdapterModel compiles successfully`() {
assertThatClassCompilationIsSuccessful(WrapperTypeAdapterModel::class)
}
@Test
fun `Verify that compilation is deterministic`() {
val classes = arrayOf(
AlternateNameModel::class,
AlternateNameModel1::class,
BaseExternalModel::class,
BooleanFields::class,
EnumWithFieldsModel::class,
ExternalAbstractClass::class,
ExternalModel1::class,
ExternalModel2::class,
ExternalModelGeneric::class,
ExternalModelGeneric1::class,
ModelWithNestedInterface::class,
NativeJavaModel::class,
NativeJavaModelExtension::class,
NativeJavaModelExtensionWithoutAnnotation::class,
RawGenericField::class,
NullFields::class,
PrivateMembers::class,
WildcardModel::class,
DynamicallyTypedModel::class,
DynamicallyTypedWildcard::class,
AbstractDataList::class,
SuperAbstractDataList::class,
ConcreteDataList::class
)
val compilation1Hash = processorTester.compileClassesInModule(module, *classes).hashOutput()
val compilation2Hash = processorTester.compileClassesInModule(module, *classes).hashOutput()
assertThat(compilation1Hash).isEqualTo(compilation2Hash)
}
/**
* Returns the concatenation of the hash of each file generated by the [Compilation].
*/
private fun Compilation.hashOutput(): String = generatedFiles()
.joinToString { it.getCharContent(false).hashCode().toString() }
private fun <T : Any> assertThatClassCompilationIsSuccessful(kClass: KClass<T>) {
assertThat(processorTester.compileClassesInModule(module, kClass).isSuccessful()).isTrue()
}
}
| stag-library-compiler/src/test/java/com/vimeo/stag/processor/functional/JavaIntegrationFunctionalTests.kt | 2790868888 |
package de.westnordost.streetcomplete.quests.housenumber
sealed class HousenumberAnswer
data class ConscriptionNumber(val number: String, val streetNumber: String? = null) : HousenumberAnswer()
data class HouseNumber(val number: String) : HousenumberAnswer()
data class HouseName(val name: String) : HousenumberAnswer()
data class HouseAndBlockNumber(val houseNumber: String, val blockNumber: String) : HousenumberAnswer()
object NoHouseNumber : HousenumberAnswer()
| app/src/main/java/de/westnordost/streetcomplete/quests/housenumber/HousenumberAnswer.kt | 728777093 |
/*
* 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.xquery
import com.intellij.psi.PsiElement
/**
* An XQuery 3.0 `WindowVars` node in the XQuery AST.
*/
interface XQueryWindowVars : PsiElement
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/xquery/XQueryWindowVars.kt | 4013675243 |
package leetcode
/**
* https://leetcode.com/problems/divide-a-string-into-groups-of-size-k/
*/
class Problem2138 {
fun divideString(s: String, k: Int, fill: Char): Array<String> {
val answer = mutableListOf<String>()
var i = 0
while (i < s.length) {
answer += if (i + k > s.length) {
s.substring(i) + fill.toString().repeat(k - s.substring(i).length)
} else {
s.substring(i, i + k)
}
i += k
}
return answer.toTypedArray()
}
}
| src/main/kotlin/leetcode/Problem2138.kt | 3590261301 |
// IGNORE_BACKEND: NATIVE
class A : Map<String, String> {
override val size: Int get() = 56
override fun isEmpty(): Boolean {
throw UnsupportedOperationException()
}
override fun containsKey(key: String): Boolean {
throw UnsupportedOperationException()
}
override fun containsValue(value: String): Boolean {
throw UnsupportedOperationException()
}
override fun get(key: String): String? {
throw UnsupportedOperationException()
}
override val keys: Set<String> get() {
throw UnsupportedOperationException()
}
override val values: Collection<String> get() {
throw UnsupportedOperationException()
}
override val entries: Set<Map.Entry<String, String>> get() {
throw UnsupportedOperationException()
}
}
fun box(): String {
val a = A()
if (a.size != 56) return "fail 1: ${a.size}"
val x: Map<String, String> = a
if (x.size != 56) return "fail 2: ${x.size}"
return "OK"
} | backend.native/tests/external/codegen/box/specialBuiltins/maps.kt | 1918644689 |
fun main(args : Array<String>) {
try {
try {
println("Try")
throw Error("Error happens")
println("After throw")
} catch (e: Error) {
println("Catch")
throw Exception()
println("After throw")
} finally {
println("Finally")
}
println("After nested try")
} catch (e: Error) {
println("Caught Error")
} catch (e: Exception) {
println("Caught Exception")
}
println("Done")
} | backend.native/tests/codegen/try/finally4.kt | 275370632 |
package eu.kanade.tachiyomi.data.download
import android.content.Context
import android.webkit.MimeTypeMap
import com.elvishew.xlog.XLog
import com.hippo.unifile.UniFile
import com.jakewharton.rxrelay.BehaviorRelay
import com.jakewharton.rxrelay.PublishRelay
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.data.download.model.DownloadQueue
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.source.online.fetchAllImageUrlsFromPageList
import eu.kanade.tachiyomi.util.*
import kotlinx.coroutines.async
import okhttp3.Response
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import timber.log.Timber
/**
* This class is the one in charge of downloading chapters.
*
* Its [queue] contains the list of chapters to download. In order to download them, the downloader
* subscriptions must be running and the list of chapters must be sent to them by [downloadsRelay].
*
* The queue manipulation must be done in one thread (currently the main thread) to avoid unexpected
* behavior, but it's safe to read it from multiple threads.
*
* @param context the application context.
* @param provider the downloads directory provider.
* @param cache the downloads cache, used to add the downloads to the cache after their completion.
* @param sourceManager the source manager.
*/
class Downloader(
private val context: Context,
private val provider: DownloadProvider,
private val cache: DownloadCache,
private val sourceManager: SourceManager
) {
/**
* Store for persisting downloads across restarts.
*/
private val store = DownloadStore(context, sourceManager)
/**
* Queue where active downloads are kept.
*/
val queue = DownloadQueue(store)
/**
* Notifier for the downloader state and progress.
*/
private val notifier by lazy { DownloadNotifier(context) }
/**
* Downloader subscriptions.
*/
private val subscriptions = CompositeSubscription()
/**
* Relay to send a list of downloads to the downloader.
*/
private val downloadsRelay = PublishRelay.create<List<Download>>()
/**
* Relay to subscribe to the downloader status.
*/
val runningRelay: BehaviorRelay<Boolean> = BehaviorRelay.create(false)
/**
* Whether the downloader is running.
*/
@Volatile private var isRunning: Boolean = false
init {
launchNow {
val chapters = async { store.restore() }
queue.addAll(chapters.await())
}
}
/**
* Starts the downloader. It doesn't do anything if it's already running or there isn't anything
* to download.
*
* @return true if the downloader is started, false otherwise.
*/
fun start(): Boolean {
if (isRunning || queue.isEmpty())
return false
if (!subscriptions.hasSubscriptions())
initializeSubscriptions()
val pending = queue.filter { it.status != Download.DOWNLOADED }
pending.forEach { if (it.status != Download.QUEUE) it.status = Download.QUEUE }
downloadsRelay.call(pending)
return !pending.isEmpty()
}
/**
* Stops the downloader.
*/
fun stop(reason: String? = null) {
destroySubscriptions()
queue
.filter { it.status == Download.DOWNLOADING }
.forEach { it.status = Download.ERROR }
if (reason != null) {
notifier.onWarning(reason)
} else {
if (notifier.paused) {
notifier.paused = false
notifier.onDownloadPaused()
} else if (notifier.isSingleChapter && !notifier.errorThrown) {
notifier.isSingleChapter = false
} else {
notifier.dismiss()
}
}
}
/**
* Pauses the downloader
*/
fun pause() {
destroySubscriptions()
queue
.filter { it.status == Download.DOWNLOADING }
.forEach { it.status = Download.QUEUE }
notifier.paused = true
}
/**
* Removes everything from the queue.
*
* @param isNotification value that determines if status is set (needed for view updates)
*/
fun clearQueue(isNotification: Boolean = false) {
destroySubscriptions()
//Needed to update the chapter view
if (isNotification) {
queue
.filter { it.status == Download.QUEUE }
.forEach { it.status = Download.NOT_DOWNLOADED }
}
queue.clear()
notifier.dismiss()
}
/**
* Prepares the subscriptions to start downloading.
*/
private fun initializeSubscriptions() {
if (isRunning) return
isRunning = true
runningRelay.call(true)
subscriptions.clear()
subscriptions += downloadsRelay.concatMapIterable { it }
.concatMap { downloadChapter(it).subscribeOn(Schedulers.io()) }
.onBackpressureBuffer()
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ completeDownload(it)
}, { error ->
DownloadService.stop(context)
Timber.e(error)
notifier.onError(error.message)
})
}
/**
* Destroys the downloader subscriptions.
*/
private fun destroySubscriptions() {
if (!isRunning) return
isRunning = false
runningRelay.call(false)
subscriptions.clear()
}
/**
* Creates a download object for every chapter and adds them to the downloads queue.
*
* @param manga the manga of the chapters to download.
* @param chapters the list of chapters to download.
* @param autoStart whether to start the downloader after enqueing the chapters.
*/
fun queueChapters(manga: Manga, chapters: List<Chapter>, autoStart: Boolean) = launchUI {
val source = sourceManager.get(manga.source) as? HttpSource ?: return@launchUI
// Called in background thread, the operation can be slow with SAF.
val chaptersWithoutDir = async {
val mangaDir = provider.findMangaDir(manga, source)
chapters
// Avoid downloading chapters with the same name.
.distinctBy { it.name }
// Filter out those already downloaded.
.filter { mangaDir?.findFile(provider.getChapterDirName(it)) == null }
// Add chapters to queue from the start.
.sortedByDescending { it.source_order }
}
// Runs in main thread (synchronization needed).
val chaptersToQueue = chaptersWithoutDir.await()
// Filter out those already enqueued.
.filter { chapter -> queue.none { it.chapter.id == chapter.id } }
// Create a download for each one.
.map { Download(source, manga, it) }
if (chaptersToQueue.isNotEmpty()) {
queue.addAll(chaptersToQueue)
// Initialize queue size.
notifier.initialQueueSize = queue.size
if (isRunning) {
// Send the list of downloads to the downloader.
downloadsRelay.call(chaptersToQueue)
}
// Start downloader if needed
if (autoStart) {
DownloadService.start([email protected])
}
}
}
/**
* Returns the observable which downloads a chapter.
*
* @param download the chapter to be downloaded.
*/
private fun downloadChapter(download: Download): Observable<Download> = Observable.defer {
val chapterDirname = provider.getChapterDirName(download.chapter)
val mangaDir = provider.getMangaDir(download.manga, download.source)
val tmpDir = mangaDir.createDirectory("${chapterDirname}_tmp")
val pageListObservable = if (download.pages == null) {
// Pull page list from network and add them to download object
download.source.fetchPageList(download.chapter)
.doOnNext { pages ->
if (pages.isEmpty()) {
throw Exception("Page list is empty")
}
download.pages = pages
}
} else {
// Or if the page list already exists, start from the file
Observable.just(download.pages!!)
}
pageListObservable
.doOnNext { _ ->
// Delete all temporary (unfinished) files
tmpDir.listFiles()
?.filter { it.name!!.endsWith(".tmp") }
?.forEach { it.delete() }
download.downloadedImages = 0
download.status = Download.DOWNLOADING
}
// Get all the URLs to the source images, fetch pages if necessary
.flatMap { download.source.fetchAllImageUrlsFromPageList(it) }
// Start downloading images, consider we can have downloaded images already
.concatMap { page -> getOrDownloadImage(page, download, tmpDir) }
// Do when page is downloaded.
.doOnNext { notifier.onProgressChange(download) }
.toList()
.map { _ -> download }
// Do after download completes
.doOnNext { ensureSuccessfulDownload(download, mangaDir, tmpDir, chapterDirname) }
// If the page list threw, it will resume here
.onErrorReturn { error ->
// [EXH]
XLog.w("> Download error!", error)
XLog.w("> (source.id: %s, source.name: %s, manga.id: %s, manga.url: %s, chapter.id: %s, chapter.url: %s)",
download.source.id,
download.source.name,
download.manga.id,
download.manga.url,
download.chapter.id,
download.chapter.url)
download.status = Download.ERROR
notifier.onError(error.message, download.chapter.name)
download
}
}
/**
* Returns the observable which gets the image from the filesystem if it exists or downloads it
* otherwise.
*
* @param page the page to download.
* @param download the download of the page.
* @param tmpDir the temporary directory of the download.
*/
private fun getOrDownloadImage(page: Page, download: Download, tmpDir: UniFile): Observable<Page> {
// If the image URL is empty, do nothing
if (page.imageUrl == null)
return Observable.just(page)
val filename = String.format("%03d", page.number)
val tmpFile = tmpDir.findFile("$filename.tmp")
// Delete temp file if it exists.
tmpFile?.delete()
// Try to find the image file.
val imageFile = tmpDir.listFiles()!!.find { it.name!!.startsWith("$filename.") }
// If the image is already downloaded, do nothing. Otherwise download from network
val pageObservable = if (imageFile != null)
Observable.just(imageFile)
else
downloadImage(page, download.source, tmpDir, filename)
return pageObservable
// When the image is ready, set image path, progress (just in case) and status
.doOnNext { file ->
page.uri = file.uri
page.progress = 100
download.downloadedImages++
page.status = Page.READY
}
.map { page }
// Mark this page as error and allow to download the remaining
.onErrorReturn {
page.progress = 0
page.status = Page.ERROR
page
}
}
/**
* Returns the observable which downloads the image from network.
*
* @param page the page to download.
* @param source the source of the page.
* @param tmpDir the temporary directory of the download.
* @param filename the filename of the image.
*/
private fun downloadImage(page: Page, source: HttpSource, tmpDir: UniFile, filename: String): Observable<UniFile> {
page.status = Page.DOWNLOAD_IMAGE
page.progress = 0
return source.fetchImage(page)
.map { response ->
val file = tmpDir.createFile("$filename.tmp")
try {
response.body()!!.source().saveTo(file.openOutputStream())
val extension = getImageExtension(response, file)
file.renameTo("$filename.$extension")
} catch (e: Exception) {
// [EXH]
XLog.w("> Failed to fetch image!", e)
XLog.w("> (source.id: %s, source.name: %s, page.index: %s, page.url: %s, page.imageUrl: %s)",
source.id,
source.name,
page.index,
page.url,
page.imageUrl)
response.close()
file.delete()
throw e
}
file
}
// Retry 3 times, waiting 2, 4 and 8 seconds between attempts.
.retryWhen(RetryWithDelay(3, { (2 shl it - 1) * 1000 }, Schedulers.trampoline()))
}
/**
* Returns the extension of the downloaded image from the network response, or if it's null,
* analyze the file. If everything fails, assume it's a jpg.
*
* @param response the network response of the image.
* @param file the file where the image is already downloaded.
*/
private fun getImageExtension(response: Response, file: UniFile): String {
// Read content type if available.
val mime = response.body()?.contentType()?.let { ct -> "${ct.type()}/${ct.subtype()}" }
// Else guess from the uri.
?: context.contentResolver.getType(file.uri)
// Else read magic numbers.
?: ImageUtil.findImageType { file.openInputStream() }?.mime
return MimeTypeMap.getSingleton().getExtensionFromMimeType(mime) ?: "jpg"
}
/**
* Checks if the download was successful.
*
* @param download the download to check.
* @param mangaDir the manga directory of the download.
* @param tmpDir the directory where the download is currently stored.
* @param dirname the real (non temporary) directory name of the download.
*/
private fun ensureSuccessfulDownload(download: Download, mangaDir: UniFile,
tmpDir: UniFile, dirname: String) {
// Ensure that the chapter folder has all the images.
val downloadedImages = tmpDir.listFiles().orEmpty().filterNot { it.name!!.endsWith(".tmp") }
download.status = if (downloadedImages.size == download.pages!!.size) {
Download.DOWNLOADED
} else {
Download.ERROR
}
// Only rename the directory if it's downloaded.
if (download.status == Download.DOWNLOADED) {
tmpDir.renameTo(dirname)
cache.addChapter(dirname, mangaDir, download.manga)
}
}
/**
* Completes a download. This method is called in the main thread.
*/
private fun completeDownload(download: Download) {
// Delete successful downloads from queue
if (download.status == Download.DOWNLOADED) {
// remove downloaded chapter from queue
queue.remove(download)
}
if (areAllDownloadsFinished()) {
if (notifier.isSingleChapter && !notifier.errorThrown) {
notifier.onDownloadCompleted(download, queue)
}
DownloadService.stop(context)
}
}
/**
* Returns true if all the queued downloads are in DOWNLOADED or ERROR state.
*/
private fun areAllDownloadsFinished(): Boolean {
return queue.none { it.status <= Download.DOWNLOADING }
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/download/Downloader.kt | 1812248662 |
package org.jetbrains.settingsRepository.git
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.ProcessNotCreatedException
import com.intellij.openapi.util.text.StringUtil
import org.eclipse.jgit.lib.Repository
import org.eclipse.jgit.transport.URIish
import org.jetbrains.keychain.Credentials
import org.jetbrains.settingsRepository.LOG
private var canUseGitExe = true
// https://www.kernel.org/pub/software/scm/git/docs/git-credential.html
fun getCredentialsUsingGit(uri: URIish, repository: Repository): Credentials? {
if (!canUseGitExe || repository.getConfig().getSubsections("credential").isEmpty()) {
return null
}
val commandLine = GeneralCommandLine()
commandLine.setExePath("git")
commandLine.addParameter("credential")
commandLine.addParameter("fill")
commandLine.setPassParentEnvironment(true)
val process: Process
try {
process = commandLine.createProcess()
}
catch (e: ProcessNotCreatedException) {
canUseGitExe = false
return null
}
val writer = process.getOutputStream().writer()
writer.write("url=")
writer.write(uri.toPrivateString())
writer.write("\n\n")
writer.close();
val reader = process.getInputStream().reader().buffered()
var username: String? = null
var password: String? = null
while (true) {
val line = reader.readLine()?.trim()
if (line == null || line.isEmpty()) {
break
}
fun readValue() = line.substring(line.indexOf('=') + 1).trim()
if (line.startsWith("username=")) {
username = readValue()
}
else if (line.startsWith("password=")) {
password = readValue()
}
}
reader.close()
val errorText = process.getErrorStream().reader().readText()
if (!StringUtil.isEmpty(errorText)) {
LOG.warn(errorText)
}
return if (username == null && password == null) null else Credentials(username, password)
}
| plugins/settings-repository/src/git/gitCredential.kt | 1949406653 |
/*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.github.andrewoma.kwery.mappertest.example.test
import com.github.andrewoma.kwery.core.Session
import com.github.andrewoma.kwery.mapper.AbstractDao
import com.github.andrewoma.kwery.mappertest.example.*
import java.time.Duration
import java.time.LocalDateTime
import kotlin.properties.Delegates
abstract class AbstractFilmDaoTest<T : Any, ID : Any, D : AbstractDao<T, ID>> : AbstractDaoTest<T, ID, D>() {
var sd: FilmData by Delegates.notNull()
var staticId = -500
override fun afterSessionSetup() {
sd = initialise("filmSchema") { initialiseFilmSchema(it) }
super.afterSessionSetup()
}
}
//language=SQL
val filmSchema = """
create sequence actor_seq;
create table actor (
actor_id integer generated by default as sequence actor_seq primary key,
first_name character varying(255) not null,
last_name character varying(255) null,
last_update timestamp not null
);
create table film (
film_id integer identity,
title character varying(255) not null,
release_year integer,
language_id integer not null ,
original_language_id integer,
length integer,
rating character varying (255),
last_update timestamp not null,
special_features varchar(255) array
);
create table language (
language_id integer identity,
name character varying(255) not null,
last_update timestamp not null
);
create table film_actor (
film_id integer not null,
actor_id integer not null,
last_update timestamp not null,
primary key(film_id, actor_id)
)
"""
class FilmData {
fun <T : Any> notNull() = Delegates.notNull<T>()
var actorBrad: Actor by notNull()
var actorKate: Actor by notNull()
var languageEnglish: Language by notNull()
var languageSpanish: Language by notNull()
var filmUnderworld: Film by notNull()
var filmUnderworld2: Film by notNull()
}
fun initialiseFilmSchema(session: Session): FilmData {
for (statement in filmSchema.split(";".toRegex())) {
session.update(statement)
}
// Use negative ids for static content
var id = -1000
val d = FilmData()
val actorDao = ActorDao(session, FilmActorDao(session))
d.actorBrad = actorDao.insert(Actor(Name("Brad", "Pitt"), --id, LocalDateTime.now()))
d.actorKate = actorDao.insert(Actor(Name("Kate", "Beckinsale"), --id, LocalDateTime.now()))
val languageDao = LanguageDao(session)
d.languageEnglish = languageDao.insert(Language(--id, "English", LocalDateTime.now()))
d.languageSpanish = languageDao.insert(Language(--id, "Spanish", LocalDateTime.now()))
val filmDao = FilmDao(session)
d.filmUnderworld = filmDao.insert(Film(--id, "Static Underworld", 2003, d.languageEnglish, null, Duration.ofMinutes(121),
FilmRating.NC_17, LocalDateTime.now(), listOf("Commentaries", "Behind the Scenes")))
d.filmUnderworld2 = filmDao.insert(Film(--id, "Static Underworld: Evolution", 2006, d.languageEnglish, null,
Duration.ofMinutes(106), FilmRating.R, LocalDateTime.now(), listOf("Behind the Scenes")))
return d
}
| mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/test/AbstractFilmDaoTest.kt | 272633842 |
package com.episode6.hackit.chop.slf4j
import com.episode6.hackit.chop.Chop
import com.episode6.hackit.mockspresso.annotation.RealObject
import com.episode6.hackit.mockspresso.quick.BuildQuickMockspresso
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.*
import org.slf4j.Logger
class Slf4jTreeTest {
companion object {
val LOG_TAG = "TEST_TAG"
val LOG_MESSAGE = "test log message"
fun expectedOutput(level: Chop.Level): String = "::$LOG_TAG::$level:: $LOG_MESSAGE"
}
@get:Rule
val mockspresso = BuildQuickMockspresso.with()
.injector().simple()
.mocker().mockito()
.buildRule()
@RealObject
lateinit var tree: Slf4jTree
@Mock
lateinit var logger: Logger
@Test
fun testAlwaysEnabled() {
Chop.Level.values().forEach {
assertThat(tree.supportsLevel(it)).isTrue()
}
}
@Test
fun testLogVerbose() {
tree.chopLog(Chop.Level.V, LOG_TAG, LOG_MESSAGE)
verify(logger).debug(expectedOutput(Chop.Level.V))
verifyNoMoreInteractions(logger)
}
@Test
fun testLogDebug() {
tree.chopLog(Chop.Level.D, LOG_TAG, LOG_MESSAGE)
verify(logger).debug(expectedOutput(Chop.Level.D))
verifyNoMoreInteractions(logger)
}
@Test
fun testLogInfo() {
tree.chopLog(Chop.Level.I, LOG_TAG, LOG_MESSAGE)
verify(logger).info(expectedOutput(Chop.Level.I))
verifyNoMoreInteractions(logger)
}
@Test
fun testLogWarning() {
tree.chopLog(Chop.Level.W, LOG_TAG, LOG_MESSAGE)
verify(logger).warn(expectedOutput(Chop.Level.W))
verifyNoMoreInteractions(logger)
}
@Test
fun testLogError() {
tree.chopLog(Chop.Level.E, LOG_TAG, LOG_MESSAGE)
verify(logger).error(expectedOutput(Chop.Level.E))
verifyNoMoreInteractions(logger)
}
}
| chop-slf4j/src/test/kotlin/com/episode6/hackit/chop/slf4j/Slf4jTreeTest.kt | 1971491398 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.actions
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.testGuiFramework.recorder.GlobalActionRecorder
import com.intellij.testGuiFramework.recorder.GuiRecorderManager
import com.intellij.testGuiFramework.recorder.ui.Notifier
/**
* @author Sergey Karashevich
*/
class StartPauseRecAction : ToggleAction(null, "Start/Stop GUI Script Recording", AllIcons.Ide.Macro.Recording_1) {
override fun isSelected(actionEvent: AnActionEvent?): Boolean = GlobalActionRecorder.isActive
override fun setSelected(actionEvent: AnActionEvent?, toStart: Boolean) {
val presentation = actionEvent?.presentation ?: templatePresentation
if (toStart) {
presentation.description = "Stop GUI Script Recording"
Notifier.updateStatus("Recording started")
GlobalActionRecorder.activate()
}
else {
presentation.description = "Start GUI Script Recording"
Notifier.updateStatus("Recording paused")
GlobalActionRecorder.deactivate()
GuiRecorderManager.placeCaretToEnd()
}
}
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/actions/StartPauseRecAction.kt | 3819820798 |
/*
* Copyright 2017 [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 nomic.stdlib
import nomic.core.script.ClasspathScript
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.data.Index
import org.junit.Test
/**
* @author [email protected]
*/
class FactionsTest {
@Test
fun `compilation of script with groups should create facts in these groups`() {
val compiler = nomic.compiler.Compiler()
val script = ClasspathScript("/factions_test.box")
val facts = compiler.compile(script);
assertThat(facts)
.hasSize(8)
.contains(DebugFact("Hello global"), Index.atIndex(3))
.contains(DebugFact("Hello group 1"), Index.atIndex(4))
.contains(DebugFact("Hello group 4"), Index.atIndex(7))
}
} | nomic-stdlib-dsl/src/test/kotlin/nomic/stdlib/FactionsTest.kt | 565774439 |
package info.nightscout.androidaps.plugins.general.maintenance
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.core.content.FileProvider
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus
import info.nightscout.androidaps.interfaces.BuildHelper
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import java.io.*
import java.util.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MaintenancePlugin @Inject constructor(
injector: HasAndroidInjector,
private val context: Context,
rh: ResourceHelper,
private val sp: SP,
private val nsSettingsStatus: NSSettingsStatus,
aapsLogger: AAPSLogger,
private val buildHelper: BuildHelper,
private val config: Config,
private val fileListProvider: PrefFileListProvider,
private val loggerUtils: LoggerUtils
) : PluginBase(
PluginDescription()
.mainType(PluginType.GENERAL)
.fragmentClass(MaintenanceFragment::class.java.name)
.alwaysVisible(false)
.alwaysEnabled(true)
.pluginIcon(R.drawable.ic_maintenance)
.pluginName(R.string.maintenance)
.shortName(R.string.maintenance_shortname)
.preferencesId(R.xml.pref_maintenance)
.description(R.string.description_maintenance),
aapsLogger, rh, injector
) {
fun sendLogs() {
val recipient = sp.getString(R.string.key_maintenance_logs_email, "[email protected]")
val amount = sp.getInt(R.string.key_maintenance_logs_amount, 2)
val logs = getLogFiles(amount)
val zipDir = fileListProvider.ensureTempDirExists()
val zipFile = File(zipDir, constructName())
aapsLogger.debug("zipFile: ${zipFile.absolutePath}")
val zip = zipLogs(zipFile, logs)
val attachmentUri =
FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileprovider", zip)
val emailIntent: Intent = this.sendMail(attachmentUri, recipient, "Log Export")
aapsLogger.debug("sending emailIntent")
context.startActivity(emailIntent)
}
fun deleteLogs(keep: Int) {
val logDir = File(loggerUtils.logDirectory)
val files = logDir.listFiles { _: File?, name: String ->
(name.startsWith("AndroidAPS") && name.endsWith(".zip"))
}
val autotunefiles = logDir.listFiles { _: File?, name: String ->
(name.startsWith("autotune") && name.endsWith(".zip"))
}
val amount = sp.getInt(R.string.key_logshipper_amount, keep)
val keepIndex = amount - 1
if (autotunefiles != null && autotunefiles.isNotEmpty()) {
Arrays.sort(autotunefiles) { f1: File, f2: File -> f2.name.compareTo(f1.name) }
var delAutotuneFiles = listOf(*autotunefiles)
if (keepIndex < delAutotuneFiles.size) {
delAutotuneFiles = delAutotuneFiles.subList(keepIndex, delAutotuneFiles.size)
for (file in delAutotuneFiles) {
file.delete()
}
}
}
if (files == null || files.isEmpty()) return
Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) }
var delFiles = listOf(*files)
if (keepIndex < delFiles.size) {
delFiles = delFiles.subList(keepIndex, delFiles.size)
for (file in delFiles) {
file.delete()
}
}
val exportDir = fileListProvider.ensureTempDirExists()
if (exportDir.exists()) {
exportDir.listFiles()?.let { expFiles ->
for (file in expFiles) file.delete()
}
exportDir.delete()
}
}
/**
* returns a list of log files. The number of returned logs is given via the amount
* parameter.
*
* The log files are sorted by the name descending.
*
* @param amount
* @return
*/
fun getLogFiles(amount: Int): List<File> {
aapsLogger.debug("getting $amount logs from directory ${loggerUtils.logDirectory}")
val logDir = File(loggerUtils.logDirectory)
val files = logDir.listFiles { _: File?, name: String ->
(name.startsWith("AndroidAPS")
&& (name.endsWith(".log")
|| name.endsWith(".zip") && !name.endsWith(loggerUtils.suffix)))
} ?: emptyArray()
Arrays.sort(files) { f1: File, f2: File -> f2.name.compareTo(f1.name) }
val result = listOf(*files)
var toIndex = amount
if (toIndex > result.size) {
toIndex = result.size
}
aapsLogger.debug("returning sublist 0 to $toIndex")
return result.subList(0, toIndex)
}
fun zipLogs(zipFile: File, files: List<File>): File {
aapsLogger.debug("creating zip ${zipFile.absolutePath}")
try {
zip(zipFile, files)
} catch (e: IOException) {
aapsLogger.error("Cannot retrieve zip", e)
}
return zipFile
}
/**
* construct the name of zip file which is used to export logs.
*
* The name is constructed using the following scheme:
* AndroidAPS_LOG_ + Long Time + .log.zip
*
* @return
*/
private fun constructName(): String {
return "AndroidAPS_LOG_" + System.currentTimeMillis() + loggerUtils.suffix
}
private fun zip(zipFile: File?, files: List<File>) {
val bufferSize = 2048
val out = ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile)))
for (file in files) {
val data = ByteArray(bufferSize)
FileInputStream(file).use { fileInputStream ->
BufferedInputStream(fileInputStream, bufferSize).use { origin ->
val entry = ZipEntry(file.name)
out.putNextEntry(entry)
var count: Int
while (origin.read(data, 0, bufferSize).also { count = it } != -1) {
out.write(data, 0, count)
}
}
}
}
out.close()
}
@Suppress("SameParameterValue")
private fun sendMail(attachmentUri: Uri, recipient: String, subject: String): Intent {
val builder = StringBuilder()
builder.append("ADD TIME OF EVENT HERE: " + System.lineSeparator())
builder.append("ADD ISSUE DESCRIPTION OR GITHUB ISSUE REFERENCE NUMBER: " + System.lineSeparator())
builder.append("-------------------------------------------------------" + System.lineSeparator())
builder.append("(Please remember this will send only very recent logs." + System.lineSeparator())
builder.append("If you want to provide logs for event older than a few hours," + System.lineSeparator())
builder.append("you have to do it manually)" + System.lineSeparator())
builder.append("-------------------------------------------------------" + System.lineSeparator())
builder.append(rh.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator())
if (config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator())
builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator())
builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator())
builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator())
builder.append(rh.gs(R.string.configbuilder_nightscoutversion_label) + " " + nsSettingsStatus.getVersion() + System.lineSeparator())
if (buildHelper.isEngineeringMode()) builder.append(rh.gs(R.string.engineering_mode_enabled))
return sendMail(attachmentUri, recipient, subject, builder.toString())
}
/**
* send a mail with the given file to the recipients with the given subject.
*
* the returned intent should be used to really send the mail using
*
* startActivity(Intent.createChooser(emailIntent , "Send email..."));
*
* @param attachmentUri
* @param recipient
* @param subject
* @param body
*
* @return
*/
private fun sendMail(
attachmentUri: Uri,
recipient: String,
subject: String,
body: String
): Intent {
aapsLogger.debug("sending email to $recipient with subject $subject")
val emailIntent = Intent(Intent.ACTION_SEND)
emailIntent.type = "text/plain"
emailIntent.putExtra(Intent.EXTRA_EMAIL, arrayOf(recipient))
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject)
emailIntent.putExtra(Intent.EXTRA_TEXT, body)
aapsLogger.debug("put path $attachmentUri")
emailIntent.putExtra(Intent.EXTRA_STREAM, attachmentUri)
emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return emailIntent
}
} | app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt | 1776203412 |
package com.trevorhalvorson.ping.sendMessage
import android.app.AlertDialog
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TextInputEditText
import android.telephony.PhoneNumberUtils
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Patterns
import android.util.TypedValue.COMPLEX_UNIT_PX
import android.view.View
import android.view.View.GONE
import android.view.View.VISIBLE
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions.*
import com.google.android.libraries.remixer.annotation.*
import com.google.android.libraries.remixer.ui.view.RemixerFragment
import com.google.gson.Gson
import com.trevorhalvorson.ping.BuildConfig
import com.trevorhalvorson.ping.R
import com.trevorhalvorson.ping.builder.BuilderActivity
import com.trevorhalvorson.ping.builder.BuilderConfig
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_send_message.*
import kotlinx.android.synthetic.main.layout_number_pad.*
import javax.inject.Inject
class SendMessageActivity : AppCompatActivity(), SendMessageContract.View, View.OnClickListener {
@Inject lateinit var sendMessagePresenter: SendMessageContract.Presenter
override fun setPresenter(presenter: SendMessageContract.Presenter) {
sendMessagePresenter = presenter
}
override fun showProgress() {
progressDialog = ProgressDialog.show(this,
getString(R.string.message_progress_dialog_title_text),
getString(R.string.message_progress_dialog_message_text), true, false)
}
override fun hideProgress() {
progressDialog?.dismiss()
}
override fun showError(error: String?) {
if (error != null) {
errorDialog = AlertDialog.Builder(this)
.setTitle(getString(R.string.error_dialog_title_text))
.setMessage(error)
.create()
errorDialog?.show()
}
}
override fun hideError() {
errorDialog?.dismiss()
}
override fun clearInput() {
number_edit_text.text.clear()
}
override fun showPinError() {
pinEditText?.error = getString(R.string.pin_error_message)
}
override fun showAdminView() {
val view = layoutInflater.inflate(R.layout.dialog_admin, send_message_layout, false)
val dialog = AlertDialog.Builder(this).setView(view)
.setTitle(getString(R.string.dialog_admin_title))
.setNegativeButton(getString(R.string.dialog_admin_negative_button),
{ dialogInterface, _ ->
dialogInterface.cancel()
hideConfigButton()
adminMode = false
})
.create()
dialog.show()
view.findViewById<Button>(R.id.edit_configs_button).setOnClickListener {
showConfigView()
dialog.cancel()
}
view.findViewById<Button>(R.id.show_builder_view_button).setOnClickListener {
val builderIntent = Intent(this, BuilderActivity::class.java)
builderIntent.putExtra("config", Gson().toJson(
BuilderConfig(
title_text.text.toString(),
title_text.textSize.toString(),
title_text.currentTextColor.toHex(),
imageUrl,
main_image.width.toString(),
main_image.height.toString(),
main_image.scaleType.toString(),
copy_text.text.toString(),
copy_text.textSize.toString(),
copy_text.currentTextColor.toHex(),
send_button.text.toString(),
send_button.currentTextColor.toHex(),
(send_button.background as ColorDrawable).color.toHex(),
number_edit_text.currentTextColor.toHex(),
(number_text_input_layout.background as ColorDrawable).color
.toHex(),
num_pad_0.currentTextColor.toHex(),
(layout_number_pad.background as ColorDrawable).color.toHex(),
(container_linear_layout.background as ColorDrawable).color
.toHex(),
pin,
message,
BuildConfig.MESSAGING_URL_BASE,
BuildConfig.MESSAGING_URL_PATH,
BuildConfig.BUILDER_URL_BASE,
BuildConfig.BUILDER_URL_PATH,
BuildConfig.EMAIL
)))
startActivity(builderIntent)
}
}
override fun showConfigView() {
RemixerFragment.newInstance().showRemixer(supportFragmentManager,
RemixerFragment.REMIXER_TAG)
}
private var progressDialog: ProgressDialog? = null
private var errorDialog: AlertDialog? = null
private var message = BuildConfig.MESSAGE
private var imageUrl = BuildConfig.IMAGE_URL
private var pin = BuildConfig.PIN
private var phoneNumber: String? = null
private var adminMode: Boolean = false
private var pinEditText: TextInputEditText? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_send_message)
AndroidInjection.inject(this)
hideSystemUI()
send_button.setOnClickListener {
sendMessagePresenter.sendMessage(phoneNumber!!, message)
}
number_edit_text.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(editable: Editable?) {
}
override fun beforeTextChanged(number: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(number: CharSequence, p1: Int, p2: Int, p3: Int) {
val isValid = Patterns.PHONE.matcher(number).matches() &&
!PhoneNumberUtils.isEmergencyNumber(number.toString());
send_button.isEnabled = isValid
if (isValid) phoneNumber = number.toString()
}
})
num_pad_1.setOnClickListener(this)
num_pad_2.setOnClickListener(this)
num_pad_3.setOnClickListener(this)
num_pad_4.setOnClickListener(this)
num_pad_5.setOnClickListener(this)
num_pad_6.setOnClickListener(this)
num_pad_7.setOnClickListener(this)
num_pad_8.setOnClickListener(this)
num_pad_9.setOnClickListener(this)
num_pad_0.setOnClickListener(this)
num_pad_del.setOnClickListener {
if (number_edit_text.text.isNotEmpty()) {
number_edit_text.text.delete(number_edit_text.text.length - 1,
number_edit_text.text.length)
}
}
num_pad_del.setOnLongClickListener {
clearInput()
true
}
var blankClickCount = 0
num_pad_blank.setOnClickListener {
if (++blankClickCount == 7) {
showConfigButton()
blankClickCount = 0
}
}
config_button.setOnClickListener {
if (adminMode) {
showAdminView()
} else {
val view = layoutInflater.inflate(R.layout.dialog_pin, send_message_layout, false)
pinEditText = view.findViewById(R.id.pin_edit_text)
val dialog = AlertDialog.Builder(this).setView(view)
.setTitle(getString(R.string.dialog_pin_title))
.setNegativeButton(getString(R.string.dialog_pin_negative_button),
{ dialogInterface, _ ->
dialogInterface.cancel()
hideConfigButton()
})
.create()
dialog.show()
view.findViewById<Button>(R.id.submit_pin_button).setOnClickListener {
if (sendMessagePresenter.submitPin(pinEditText?.text.toString())) {
adminMode = true
dialog.cancel()
}
}
}
}
RemixerBinder.bind(this)
}
private fun showConfigButton() {
num_pad_blank.visibility = GONE
config_button.visibility = VISIBLE
}
private fun hideConfigButton() {
config_button.visibility = GONE
num_pad_blank.visibility = VISIBLE
}
override fun onClick(view: View?) {
number_edit_text.text.append((view as TextView).text)
}
override fun onBackPressed() {
// prevent user from exiting app via the back button
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
hideSystemUI()
}
private fun hideSystemUI() {
window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
.or(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
.or(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
.or(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
.or(View.SYSTEM_UI_FLAG_FULLSCREEN)
.or(View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
}
// Remixer UI controls
@StringVariableMethod(title = "Title Text", initialValue = BuildConfig.TITLE_TEXT)
fun setTitleText(text: String?) {
if (text != null) {
title_text.text = text
}
}
@RangeVariableMethod(title = "Title Text Size", initialValue = BuildConfig.TITLE_TEXT_SIZE,
minValue = 12F, maxValue = 120F)
fun setTitleTextSize(textSize: Float?) {
if (textSize != null) {
title_text.setTextSize(COMPLEX_UNIT_PX, textSize)
}
}
@ColorListVariableMethod(title = "Title Text Color",
initialValue = BuildConfig.TITLE_TEXT_COLOR, limitedToValues = intArrayOf(
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setTitleTextColor(color: Int?) {
if (color != null) {
title_text.setTextColor(color)
}
}
@StringVariableMethod(title = "Image URL", initialValue = BuildConfig.IMAGE_URL)
fun setMainImageUrl(url: String?) {
if (!TextUtils.isEmpty(url)) {
imageUrl = url!!
Glide.with(this).load(imageUrl).apply(centerCropTransform()).into(main_image)
}
}
@RangeVariableMethod(title = "Image Width", initialValue = BuildConfig.IMAGE_WIDTH,
minValue = 0F, maxValue = 1200F)
fun setMainImageWidth(width: Float?) {
if (width != null) {
main_image.layoutParams.width = width.toInt()
main_image.requestLayout()
Glide.with(this).clear(main_image)
Glide.with(this).load(imageUrl).into(main_image)
}
}
@RangeVariableMethod(title = "Image Height", initialValue = BuildConfig.IMAGE_HEIGHT,
minValue = 0F, maxValue = 1200F)
fun setMainImageHeight(height: Float?) {
if (height != null) {
main_image.layoutParams.height = height.toInt()
main_image.requestLayout()
Glide.with(this).clear(main_image)
Glide.with(this).load(imageUrl).into(main_image)
}
}
@StringListVariableMethod(title = "Image Scale Type",
initialValue = BuildConfig.IMAGE_SCALE_TYPE, limitedToValues = arrayOf(
"CENTER",
"CENTER_CROP",
"CENTER_INSIDE",
"FIT_CENTER",
"FIT_XY"
))
fun setMainImageScaleType(type: String?) {
val scaleType: ImageView.ScaleType? = when (type) {
"CENTER" -> ImageView.ScaleType.CENTER
"CENTER_CROP" -> ImageView.ScaleType.CENTER_CROP
"CENTER_INSIDE" -> ImageView.ScaleType.CENTER_INSIDE
"FIT_CENTER" -> ImageView.ScaleType.FIT_CENTER
"FIT_XY" -> ImageView.ScaleType.FIT_XY
else -> {
ImageView.ScaleType.CENTER
}
}
main_image.scaleType = scaleType
main_image.requestLayout()
Glide.with(this).clear(main_image)
Glide.with(this).load(imageUrl).into(main_image)
}
@StringVariableMethod(title = "Copy Text", initialValue = BuildConfig.COPY_TEXT)
fun setCopyText(text: String?) {
if (text != null) {
copy_text.text = text
}
}
@RangeVariableMethod(title = "Copy Text Size", initialValue = BuildConfig.COPY_TEXT_SIZE,
minValue = 12F, maxValue = 120F)
fun setCopyTextSize(textSize: Float?) {
if (textSize != null) {
copy_text.setTextSize(COMPLEX_UNIT_PX, textSize)
}
}
@ColorListVariableMethod(title = "Copy Text Color", initialValue = BuildConfig.COPY_TEXT_COLOR,
limitedToValues = intArrayOf(
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setCopyTextColor(color: Int?) {
if (color != null) {
copy_text.setTextColor(color)
}
}
@StringVariableMethod(title = "Send Button Text", initialValue = BuildConfig.SEND_BUTTON_TEXT)
fun setSendButtonText(text: String?) {
if (text != null) {
send_button.text = text
}
}
@ColorListVariableMethod(title = "Send Button Text Color",
initialValue = BuildConfig.SEND_BUTTON_TEXT_COLOR, limitedToValues = intArrayOf(
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setSendButtonTextColor(color: Int?) {
if (color != null) {
send_button.setTextColor(color)
}
}
@ColorListVariableMethod(title = "Send Message Button Color",
initialValue = BuildConfig.SEND_BUTTON_BACKGROUND_COLOR, limitedToValues = intArrayOf(
0xFFCCCCCC.toInt(),
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setSendButtonBackgroundColor(color: Int?) {
if (color != null) {
send_button.setBackgroundColor(color)
}
}
@ColorListVariableMethod(title = "Phone Number Background Color",
initialValue = BuildConfig.PHONE_INPUT_BACKGROUND_COLOR, limitedToValues = intArrayOf(
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setPhoneNumberBackgroundTextColor(color: Int?) {
if (color != null) {
number_text_input_layout.setBackgroundColor(color)
}
}
@ColorListVariableMethod(title = "Phone Number Input Text Color",
initialValue = BuildConfig.PHONE_INPUT_TEXT_COLOR, limitedToValues = intArrayOf(
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setPhoneNumberInputTextColor(color: Int?) {
if (color != null) {
number_edit_text.setTextColor(color)
}
}
@ColorListVariableMethod(title = "Number Pad Text Color",
initialValue = BuildConfig.NUM_PAD_TEXT_COLOR, limitedToValues = intArrayOf(
0xFF000000.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFFFFFFFF.toInt()
))
fun setPhoneNumberPadTextColor(color: Int?) {
if (color != null) {
num_pad_1.setTextColor(color)
num_pad_2.setTextColor(color)
num_pad_3.setTextColor(color)
num_pad_4.setTextColor(color)
num_pad_5.setTextColor(color)
num_pad_6.setTextColor(color)
num_pad_7.setTextColor(color)
num_pad_8.setTextColor(color)
num_pad_9.setTextColor(color)
num_pad_0.setTextColor(color)
num_pad_del.setTextColor(color)
}
}
@ColorListVariableMethod(title = "Number Pad Background Color",
initialValue = BuildConfig.NUM_PAD_BACKGROUND_COLOR, limitedToValues = intArrayOf(
0xFFFFFFFF.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFF000000.toInt()
))
fun setPhoneNumberPadBackgroundColor(color: Int?) {
if (color != null && layout_number_pad != null) {
layout_number_pad.setBackgroundColor(color)
}
}
@ColorListVariableMethod(title = "Main Background Color",
initialValue = BuildConfig.BACKGROUND_COLOR, limitedToValues = intArrayOf(
0xFFFFFFFF.toInt(),
0xFFE91E63.toInt(),
0xFF9C27B0.toInt(),
0xFF673AB7.toInt(),
0xFF3F51B5.toInt(),
0xFF2196F3.toInt(),
0xFF03A9F4.toInt(),
0xFF00BCD4.toInt(),
0xFF009688.toInt(),
0xFF4CAF50.toInt(),
0xFF8BC34A.toInt(),
0xFFFFEB3B.toInt(),
0xFFFFC107.toInt(),
0xFF8BC34A.toInt(),
0xFFFF9800.toInt(),
0xFFFF5722.toInt(),
0xFF9E9E9E.toInt(),
0xFF607D8B.toInt(),
0xFF424242.toInt(),
0xFF37474F.toInt(),
0xFF212121.toInt(),
0xFF263238.toInt(),
0xFF000000.toInt()
))
fun setBackgroundColor(color: Int?) {
if (color != null) {
container_linear_layout.setBackgroundColor(color)
}
}
@StringVariableMethod(title = "Message", initialValue = BuildConfig.MESSAGE)
fun setMessageText(s: String?) {
if (s != null) {
message = s
}
}
@StringVariableMethod(title = "PIN", initialValue = BuildConfig.PIN)
fun setPin(s: String?) {
if (s != null) {
pin = s
}
}
}
fun Int.toHex(): String {
return "0xFF" + String.format("%06X", 0xFFFFFF and this)
} | app/src/main/kotlin/com/trevorhalvorson/ping/sendMessage/SendMessageActivity.kt | 1455650958 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.