repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
calintat/sensors
app/src/main/java/com/calintat/sensors/recycler/LoggerViewHolder.kt
1
630
package com.calintat.sensors.recycler import android.support.v7.widget.RecyclerView import android.view.View import android.widget.TextView import com.calintat.sensors.R import com.calintat.sensors.api.Logger import org.jetbrains.anko.find class LoggerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val time = itemView.find<TextView>(R.id.logger_list_item_time) private val data = itemView.find<TextView>(R.id.logger_list_item_data) fun bindItem(item: Logger.Snapshot) { time.text = item.printTimeInSeconds() data.text = item.data.joinToString(separator = "\n") } }
apache-2.0
a9f8d0cfde0247e96d1e0c139b8550ed
27.681818
76
0.753968
3.727811
false
false
false
false
apioo/psx-schema
tests/Generator/resource/kotlin_oop.kt
1
318
open class Human { var firstName: String? = null } open class Student : Human { var matricleNumber: String? = null } typealias StudentMap = Map<Student> open class Map<T> { var totalResults: Int? = null var entries: Array<T>? = null } open class RootSchema { var students: StudentMap? = null }
apache-2.0
ac0db9b8d2e136e6bb2e7de0e574e8c5
16.666667
38
0.666667
3.347368
false
false
false
false
ibinti/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ContractInferenceIndex.kt
3
4235
/* * Copyright 2000-2016 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.codeInspection.dataFlow import com.intellij.lang.LighterAST import com.intellij.lang.LighterASTNode import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.psi.impl.source.JavaLightStubBuilder import com.intellij.psi.impl.source.PsiFileImpl import com.intellij.psi.impl.source.PsiMethodImpl import com.intellij.psi.impl.source.tree.JavaElementType import com.intellij.psi.impl.source.tree.JavaElementType.* import com.intellij.psi.impl.source.tree.LightTreeUtil import com.intellij.psi.impl.source.tree.RecursiveLighterASTNodeWalkingVisitor import com.intellij.psi.util.PsiUtil import com.intellij.util.gist.GistManager import java.util.* /** * @author peter */ private val gist = GistManager.getInstance().newPsiFileGist("contractInference", 2, MethodDataExternalizer) { file -> indexFile(file.node.lighterAST) } private fun indexFile(tree: LighterAST): Map<Int, MethodData> { val result = HashMap<Int, MethodData>() object : RecursiveLighterASTNodeWalkingVisitor(tree) { var methodIndex = 0 override fun visitNode(element: LighterASTNode) { if (element.tokenType === METHOD) { calcData(tree, element)?.let { data -> result[methodIndex] = data } methodIndex++ } if (JavaLightStubBuilder.isCodeBlockWithoutStubs(element)) return super.visitNode(element) } }.visitNode(tree.root) return result } private fun calcData(tree: LighterAST, method: LighterASTNode): MethodData? { val body = LightTreeUtil.firstChildOfType(tree, method, CODE_BLOCK) ?: return null val statements = ContractInferenceInterpreter.getStatements(body, tree) val contracts = ContractInferenceInterpreter(tree, method, body).inferContracts(statements) val nullityVisitor = NullityInference.NullityInferenceVisitor(tree, body) val purityVisitor = PurityInference.PurityInferenceVisitor(tree, body) for (statement in statements) { walkMethodBody(tree, statement) { nullityVisitor.visitNode(it); purityVisitor.visitNode(it) } } return createData(body, contracts, nullityVisitor.result, purityVisitor.result) } private fun walkMethodBody(tree: LighterAST, root: LighterASTNode, processor: (LighterASTNode) -> Unit) { object : RecursiveLighterASTNodeWalkingVisitor(tree) { override fun visitNode(element: LighterASTNode) { val type = element.tokenType if (type === CLASS || type === FIELD || type == METHOD || type == ANNOTATION_METHOD || type === LAMBDA_EXPRESSION) return processor(element) super.visitNode(element) } }.visitNode(root) } private fun createData(body: LighterASTNode, contracts: List<PreContract>, nullity: NullityInferenceResult?, purity: PurityInferenceResult?): MethodData? { if (nullity == null && purity == null && !contracts.isNotEmpty()) return null return MethodData(nullity, purity, contracts, body.startOffset, body.endOffset) } fun getIndexedData(method: PsiMethodImpl): MethodData? = gist.getFileData(method.containingFile)?.get(methodIndex(method)) private fun methodIndex(method: PsiMethodImpl): Int? { val file = method.containingFile as PsiFileImpl if (file.elementTypeForStubBuilder == null) return null val stubTree = try { file.stubTree ?: file.calcStubTree() } catch (e: ProcessCanceledException) { throw e } catch (e: RuntimeException) { throw RuntimeException("While inferring contract for " + PsiUtil.getMemberQualifiedName(method), e) } return stubTree.plainList.filter { it.stubType == JavaElementType.METHOD }.map { it.psi }.indexOf(method) }
apache-2.0
c3380a2c00b67a795a7607abffa8dc05
37.162162
127
0.745927
4.379524
false
false
false
false
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/db/UserDao.kt
2
1553
package chat.rocket.android.db import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import androidx.room.Update import chat.rocket.android.db.model.BaseUserEntity import chat.rocket.android.db.model.UserEntity import chat.rocket.android.db.model.UserStatus import timber.log.Timber @Dao abstract class UserDao : BaseDao<UserEntity> { @Query(""" UPDATE users set STATUS = "offline" """) abstract fun clearStatus() @Update(onConflict = OnConflictStrategy.IGNORE) abstract fun update(user: UserEntity): Int @Query("UPDATE OR IGNORE users set STATUS = :status where ID = :id") abstract fun update(id: String, status: String): Int @Query("SELECT id FROM users WHERE ID = :id") abstract fun findUser(id: String): String? @Query("SELECT * FROM users WHERE ID = :id") abstract fun getUser(id: String): UserEntity? @Transaction open fun upsert(user: BaseUserEntity) { internalUpsert(user) } @Transaction open fun upsert(users: List<BaseUserEntity>) { users.forEach { internalUpsert(it) } } private inline fun internalUpsert(user: BaseUserEntity) { val count = if (user is UserStatus) { update(user.id, user.status) } else { update(user as UserEntity) } if (count == 0 && user is UserEntity) { Timber.d("missing user, inserting: ${user.id}") insert(user) } } }
mit
2ab2575d6f10b50e0c5d5d6f29627b86
27.254545
72
0.66774
4.130319
false
false
false
false
tmarsteel/kotlin-prolog
async/src/main/kotlin/com/github/prologdb/async/WorkableFutureImpl.kt
1
10898
package com.github.prologdb.async import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.Future import java.util.concurrent.TimeUnit import kotlin.coroutines.* import kotlin.coroutines.cancellation.CancellationException class WorkableFutureImpl<T>(override val principal: Any, code: suspend WorkableFutureBuilder.() -> T) : WorkableFuture<T> { private val onComplete = object : Continuation<T> { override val context: CoroutineContext = EmptyCoroutineContext override fun resumeWith(result: Result<T>) { try { synchronized(mutex) { if (result.isSuccess) { [email protected] = result.getOrNull() } else { error = result.exceptionOrNull()!! } } } finally { state = State.COMPLETED tearDown() } } } private val mutex = Any() @Volatile private var result: T? = null @Volatile private var error: Throwable? = null @Volatile private var state: State = State.RUNNING @Volatile private var currentWaitingFuture: Future<*>? = null @Volatile private var currentFoldingSequence: LazySequence<*>? = null @Volatile private var currentFoldingCarry: Any? = null @Volatile private var currentFoldingAccumulator: ((Any, Any) -> Any)? = null /** * Teardown code, in the reverse order as it was added using [WorkableFutureBuilder.finally]; see * [LinkedList.addFirst]. * Is set on the first call to [WorkableFutureBuilder.finally] because it is expected * that most futures will not have teardown logic. */ private var teardownLogic: LinkedList<() -> Any?>? = null @Volatile private var tornDown: Boolean = false override fun isDone(): Boolean = state == State.COMPLETED override fun isCancelled(): Boolean = false override fun step(): Boolean { synchronized(mutex) { when (state) { State.RUNNING -> continuation.resume(Unit) State.WAITING_ON_FUTURE -> { val future = currentWaitingFuture!! if (future.isDone) { state = State.RUNNING currentWaitingFuture = null continuation.resume(Unit) } else if (future is WorkableFuture) { if (future.step()) { state = State.RUNNING currentWaitingFuture = null continuation.resume(Unit) } } } State.FOLDING_SEQUENCE -> { val sequence = currentFoldingSequence!! var seqState = sequence.state if (seqState == LazySequence.State.PENDING) { seqState = sequence.step() } when (seqState) { LazySequence.State.DEPLETED -> { // great, accumulation is done val result = currentFoldingCarry!! state = State.RUNNING sequence.close() currentFoldingSequence = null currentFoldingCarry = null currentFoldingCarry = null continuation.resume(result) } LazySequence.State.RESULTS_AVAILABLE -> { val element = sequence.tryAdvance()!! currentFoldingCarry = currentFoldingAccumulator!!(currentFoldingCarry!!, element) } LazySequence.State.FAILED -> { val exception = try { sequence.tryAdvance() null } catch (ex: Throwable) { ex } ?: throw IllegalStateException("Subsequence failed but did not throw the execption when tryAdvance() was called") state = State.RUNNING currentFoldingCarry = null currentFoldingSequence = null currentFoldingAccumulator = null continuation.resumeWithException(exception) } LazySequence.State.PENDING -> { /* cannot do anything */ } } } State.COMPLETED -> { } } } return isDone } override fun get(): T { do { step() when(state) { State.RUNNING -> { /* do nothing, keep looping */ } State.FOLDING_SEQUENCE -> { /* do nothing, keep looping */ } State.COMPLETED -> return result ?: throw error!! State.WAITING_ON_FUTURE -> { try { currentWaitingFuture!!.get() } catch (handleLater: Exception) { /* calling get() will complete the future * the next iteration will call step() * step() will detect that the future is * completed and update the state accordingly * the COMPLETED branch of this when() will * pick that up */ } } } } while (true) } override fun get(timeout: Long, unit: TimeUnit?): T { TODO("Implement only when needed.") } override fun cancel(mayInterruptIfRunning: Boolean): Boolean { fun continueWithCancellationException() { state = State.RUNNING continuation.resumeWithException(CancellationException().apply { fillInStackTrace() }) } synchronized(mutex) { when (state) { State.WAITING_ON_FUTURE, State.FOLDING_SEQUENCE, State.RUNNING -> { currentWaitingFuture?.let { future -> if (!future.isDone) { if (!future.cancel(mayInterruptIfRunning)) { throw WorkableFutureNotCancellableException("Waiting on nested future which is not done and cannot be cancelled.") } } } currentWaitingFuture = null currentFoldingSequence?.close() currentFoldingSequence = null continueWithCancellationException() if (state != State.COMPLETED || error == null || error!! !is CancellationException) { throw WorkableFutureNotCancellableException() } return true } State.COMPLETED -> { return false } } } } private fun tearDown() { if (tornDown) { throw IllegalStateException("TearDown already executed.") } tornDown = true teardownLogic?.let { var errors: ArrayList<Throwable>? = null it.forEach { tearDown -> try { tearDown() } catch (ex: Throwable) { if (errors == null) errors = ArrayList() errors!!.add(ex) } } if (errors != null && errors!!.isNotEmpty()) { val topEx = RuntimeException("TearDown code errored after cancel", errors!!.first()) val errorIt = errors!!.iterator() errorIt.next() // skip first, is set as cause errorIt.forEachRemaining(topEx::addSuppressed) throw topEx } } } private val Builder = object : WorkableFutureBuilder { override val principal = [email protected] override suspend fun <E> await(future: Future<E>): E { if (future is WorkableFuture) { PrincipalConflictException.requireCompatible(principal, future.principal) } synchronized(mutex) { if (state != State.RUNNING) { throw IllegalStateException("Future is in state $state, cannot wait for a future.") } if (future.isDone) { return try { future.get() } catch (ex: ExecutionException) { throw ex.cause ?: ex } } currentWaitingFuture = future state = State.WAITING_ON_FUTURE } suspendCoroutine<Any> { continuation = it } return try { future.get() } catch (ex: ExecutionException) { throw ex.cause ?: ex } } override suspend fun <E : Any, C> foldRemaining(sequence: LazySequence<E>, initial: C, accumulator: (C, E) -> C): C { PrincipalConflictException.requireCompatible(principal, sequence.principal) synchronized(mutex) { if (state != State.RUNNING) { throw IllegalStateException("Future is in state $state, cannot fold a sequence") } currentFoldingSequence = sequence currentFoldingCarry = initial @Suppress("UNCHECKED_CAST") currentFoldingAccumulator = accumulator as (Any, Any) -> Any state = State.FOLDING_SEQUENCE } return suspendCoroutine { @Suppress("UNCHECKED_CAST") continuation = it as Continuation<Any> } } override fun finally(code: () -> Any?) { if (teardownLogic == null) { teardownLogic = LinkedList() } teardownLogic!!.addFirst(code) } } @Volatile private var continuation: Continuation<Any> = run { @Suppress("UNCHECKED_CAST") code.createCoroutine(Builder, onComplete) as Continuation<Any> } private enum class State { RUNNING, COMPLETED, WAITING_ON_FUTURE, FOLDING_SEQUENCE } }
mit
a95df239b8a1439d79e59ef39d8bf89e
34.268608
146
0.483483
5.961707
false
false
false
false
industrial-data-space/trusted-connector
ids-connector/src/main/kotlin/de/fhg/aisec/ids/ConnectorConfiguration.kt
1
3901
/*- * ========================LICENSE_START================================= * ids-connector * %% * Copyright (C) 2021 Fraunhofer AISEC * %% * 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. * =========================LICENSE_END================================== */ package de.fhg.aisec.ids import de.fhg.aisec.ids.api.cm.ContainerManager import de.fhg.aisec.ids.api.infomodel.InfoModel import de.fhg.aisec.ids.api.settings.Settings import de.fhg.aisec.ids.camel.idscp2.Utils import de.fhg.aisec.ids.rm.RouteManagerService import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.CommandLineRunner import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import java.net.URI import java.util.Arrays @Configuration class ConnectorConfiguration { @Autowired(required = false) private var cml: ContainerManager? = null @Autowired private lateinit var settings: Settings @Autowired private lateinit var im: InfoModel @Autowired private lateinit var rm: RouteManagerService @Bean fun configureIdscp2(): CommandLineRunner { return CommandLineRunner { Utils.connectorUrlProducer = { settings.connectorProfile.connectorUrl ?: URI.create("http://connector.ids") } Utils.maintainerUrlProducer = { settings.connectorProfile.maintainerUrl ?: URI.create("http://connector-maintainer.ids") } Utils.dapsUrlProducer = { settings.connectorConfig.dapsUrl } TrustedConnector.LOG.info("Information model {} loaded", BuildConfig.INFOMODEL_VERSION) Utils.infomodelVersion = BuildConfig.INFOMODEL_VERSION } } @Bean fun listBeans(ctx: ApplicationContext): CommandLineRunner { return CommandLineRunner { val beans: Array<String> = ctx.beanDefinitionNames Arrays.sort(beans) for (bean in beans) { TrustedConnector.LOG.info("Loaded bean: {}", bean) } } } @Bean fun listContainers(ctx: ApplicationContext): CommandLineRunner { return CommandLineRunner { val containers = cml?.list(false) for (container in containers ?: emptyList()) { TrustedConnector.LOG.debug("Container: {}", container.names) } } } @Bean fun showConnectorProfile(ctx: ApplicationContext): CommandLineRunner { return CommandLineRunner { val connector = im.connector if (connector == null) { TrustedConnector.LOG.info("No connector profile stored yet.") } else { TrustedConnector.LOG.info("Connector profile: {}", connector) } } } @Bean fun showCamelInfo(ctx: ApplicationContext): CommandLineRunner { return CommandLineRunner { val routes = rm.routes for (route in routes) { TrustedConnector.LOG.debug("Route: {}", route.shortName) } val components = rm.listComponents() for (component in components) { TrustedConnector.LOG.debug("Component: {}", component.bundle) } } } }
apache-2.0
abd30cf5a3134937c441f76f74d4dea5
33.522124
99
0.63394
4.83995
false
true
false
false
wickedwukong/kotlin-koans
src/util/LinksToDocumentation.kt
1
2914
package util /** * @see <a href="http://kotlinlang.org/docs/reference/basic-syntax.html#defining-functions">Function syntax</a> */ fun doc0() {} /** * @see <a href="http://kotlinlang.org/docs/reference/functions.html#default-arguments">Default and named arguments</a> */ fun doc2() {} /** * @see <a href="http://kotlinlang.org/docs/reference/lambdas.html">Lambdas</a> */ fun doc4() {} /** * @see <a href="http://kotlinlang.org/docs/reference/basic-types.html#string-literals">String literals and string templates</a> */ fun doc5() {} /** * @see <a href="http://kotlinlang.org/docs/reference/classes.html">Classes</a>, <a href="http://kotlinlang.org/docs/reference/properties.html">Properties</a>, <a href="https://kotlinlang.org/docs/reference/data-classes.html">Data classes</a> */ fun doc6() {} /** * @see <a href="http://kotlinlang.org/docs/reference/null-safety.html">Null safety and safe calls</a> */ fun doc7() {} /** * @see <a href="http://kotlinlang.org/docs/reference/typecasts.html#smart-casts">Smart casts</a>, * <a href="http://kotlinlang.org/docs/reference/control-flow.html#when-expression">When</a>, * <a href="https://kotlinlang.org/docs/reference/sealed-classes.html">Sealed classes</a> */ fun doc8() {} /** * @see <a href="http://kotlinlang.org/docs/reference/extensions.html">Extension functions</a> */ fun doc9() {} /** * @see <a href="https://kotlinlang.org/docs/reference/object-declarations.html">Object expressions</a> */ fun doc10() {} /** * @see <a href="https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions">SAM-conversions</a> */ fun doc11() {} /** * @see <a href="https://kotlinlang.org/docs/reference/collections.html">Collections</a>, * <a href="http://blog.jetbrains.com/kotlin/2012/09/kotlin-m3-is-out/#Collections">Hierarchy illustration</a> */ fun doc12() {} /** * @see <a href="http://kotlinlang.org/docs/reference/operator-overloading.html">Operator overloading</a> */ fun doc25() {} /** * @see <a href="http://kotlinlang.org/docs/reference/control-flow.html#for-loops">For-loop</a> */ fun doc28() {} /** * @see <a href="http://kotlinlang.org/docs/reference/ranges.html">Ranges</a> */ fun doc26() {} /** * @see <a href="http://kotlinlang.org/docs/reference/multi-declarations.html#multi-declarations">Destructuring declarations</a> */ fun doc30() {} /** * @see <a href="http://kotlinlang.org/docs/reference/properties.html#properties-and-fields">Properties</a> */ fun doc32() {} /** * @see <a href="http://kotlinlang.org/docs/reference/delegated-properties.html">Delegated Properties</a> */ fun doc34() {} /** * @see <a href="https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver">Function Literals with Receiver</a> */ fun doc36() {} /** * @see <a href="https://kotlinlang.org/docs/reference/type-safe-builders.html">Type-Safe Builders</a> */ fun doc39() {}
mit
ca9f5fe63f8fbf750549d9775bbc8efc
27.578431
136
0.681537
3.083598
false
false
false
false
a642500/Ybook
app/src/main/kotlin/com/ybook/app/ui/search/SearchResultFragment.kt
1
11919
/* Copyright 2015 Carlos 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.ybook.app.ui.search import android.app.Fragment import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import android.view.View import android.net.Uri import android.app.Activity import com.ybook.app.R import android.support.v7.widget.Toolbar import android.app.LoaderManager import com.ybook.app.bean.SearchResponse import android.content.Loader import android.content.AsyncTaskLoader import android.content.Context import java.util.ArrayList import android.support.v7.widget.RecyclerView import com.ybook.app.net.SearchRequest import android.os.Handler import org.apache.http.NameValuePair import org.apache.http.message.BasicNameValuePair import com.ybook.app.net.getMainUrl import org.apache.http.HttpStatus import com.ybook.app.net.MSG_SUCCESS import org.apache.http.util.EntityUtils import com.ybook.app.util.JSONHelper import com.ybook.app.util.OneResultException import com.ybook.app.net.MSG_ONE_SEARCH_RESULT import com.ybook.app.net.MSG_ERROR import org.apache.http.impl.client.DefaultHttpClient import com.ybook.app.net.PostHelper import com.ybook.app.bean.DetailResponse import com.ybook.app.id import android.widget.TextView import android.widget.ImageView import android.support.v7.widget.RecyclerView.ViewHolder import me.toxz.kotlin.after import com.squareup.picasso.Picasso import android.view.animation.AnimationUtils import com.ybook.app.util.BooksListUtil /** * A new implement to display search result interface, replacing the [[link:SearchActivity]] with Fragment. * This implement is better for adapting LoaderManager and Fragment. * * Activities that contain this fragment must implement the * {@link SearchResultFragment.OnFragmentInteractionListener} interface to handle interaction events. * And an argument to contain the search keyword is necessary. * * Use the {@link SearchResultFragment#newInstance} factory method to create an instance of this fragment. */ public class SearchResultFragment// Required empty public constructor : Fragment(), //the loaded results may contain only one items, which will be DetailResponse rather than SearchResponse LoaderManager.LoaderCallbacks<Array<SearchResponse.SearchObject>>, View.OnClickListener { override fun onClick(v: View) { throw UnsupportedOperationException() } val BUNDLE_KEY_PAGE = "page" val BUNDLE_KEY_KEYWORD = "keyword" val mUtil = BooksListUtil.getInstance(getActivity())//TODO NullPointerException val mListItems: ArrayList<SearchResponse.SearchObject> = ArrayList() val mAdapter: RecyclerView.Adapter<SearchViewHolder>? = null override fun onCreateLoader(id: Int, args: Bundle?): Loader<Array<SearchResponse.SearchObject>>? { if (args == null) { return null } else { val page = args.getInt(BUNDLE_KEY_PAGE) val key = args.getString(BUNDLE_KEY_KEYWORD) return SearchLoader(page, key, getActivity()) } } /** * to handle the loaded data. */ override fun onLoadFinished(loader: Loader<Array<SearchResponse.SearchObject>>?, data: Array<SearchResponse.SearchObject>?) { if (data != null) { if ((loader as SearchLoader).page == 0) { onNewData(data) } else onData(data) } } /** * add the data to result list. */ private fun onData(data: Array<SearchResponse.SearchObject>) { mListItems.addAll(data) mAdapter!!.notifyDataSetChanged() } /** * replace the data of result list */ private fun onNewData(data: Array<SearchResponse.SearchObject>) { mListItems.clear() mListItems.addAll(data) mAdapter!!.notifyDataSetChanged() } override fun onLoaderReset(loader: Loader<Array<SearchResponse.SearchObject>>?) { //nothing now } // variables that control the Action Bar auto hide behavior (aka "quick recall") private var mActionBarAutoHideEnabled = false private var mActionBarAutoHideSensivity = 0 private var mActionBarAutoHideMinY = 0 private var mActionBarAutoHideSignal = 0 private var mActionBarShown = true private var mActionBarToolbar: Toolbar? = null private var mSearchKey: String? = null /** * listener to reflect to the interaction. */ private var mListener: OnFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super<Fragment>.onCreate(savedInstanceState) if (getArguments() != null) { mSearchKey = getArguments().getString(ARG_PARAM_SEARCH_KEY) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_search_result, container, false) } // TODO: Rename method, update argument and hook method into UI event public fun onButtonPressed(uri: Uri) { if (mListener != null) { mListener!!.onFragmentInteraction(uri) } } override fun onAttach(activity: Activity?) { super<Fragment>.onAttach(activity) try { mListener = activity as OnFragmentInteractionListener } catch (e: ClassCastException) { throw ClassCastException(activity!!.toString() + " must implement OnFragmentInteractionListener") } } override fun onDetach() { super<Fragment>.onDetach() mListener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p/> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public trait OnFragmentInteractionListener { // TODO: Update argument type and name public fun onFragmentInteraction(uri: Uri) } class object { // the fragment initialization parameters, e.g. ARG_PARAM_SEARCH_KEY private val ARG_PARAM_SEARCH_KEY = "searchKey" /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param searchKey the key word to search. * @return A new instance of fragment SearchResultFragment. */ public fun newInstance(searchKey: String): SearchResultFragment { val fragment = SearchResultFragment() val args = Bundle() args.putString(ARG_PARAM_SEARCH_KEY, searchKey) fragment.setArguments(args) return fragment } } public inner class SearchAdapter() : RecyclerView.Adapter<ViewHolder>() { private val VIEW_TYPE_HEADER = 0 private val VIEW_TYPE_ITEM = 1 var lastPosition: Int = -1 override fun getItemViewType(position: Int): Int { return if ((position == 0)) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM } override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder? { if (viewType == VIEW_TYPE_HEADER) return HeaderViewHolder(LayoutInflater.from(parent?.getContext()).inflate(R.layout.padding_action_bar, parent, false)) else return SearchViewHolder(LayoutInflater.from(parent?.getContext()).inflate(R.layout.search_result_item, parent, false)).after { it.view setOnClickListener this@SearchResultFragment it.markBtn setOnClickListener this@SearchResultFragment } } var oldPaddingTop: Int? = null override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (holder is SearchViewHolder) { val item = mListItems[position - 1]//headView added holder.titleText setText item.title holder.idText setText item.id holder.authorText setText item.author holder.pressText setText item.press Picasso.with(getActivity()) load item.coverImgUrl error (getActivity().getResources().getDrawable(R.drawable.ic_error)) into holder.coverImage holder.view setTag item holder.markBtn setTag item holder.markBtn setImageResource(if (item isMarked mUtil) R.drawable.ic_marked else R.drawable.ic_mark) } } override fun getItemCount(): Int = mListItems.size + 1 private fun setAnimation(viewToAnimate: View, position: Int) { // If the bound view wasn't previously displayed on screen, it's animated if (position > lastPosition) { val animation = AnimationUtils.loadAnimation(viewToAnimate.getContext(), android.R.anim.slide_in_left); viewToAnimate.startAnimation(animation); lastPosition = position; } } } } public class SearchLoader(val page: Int, val key: String, con: Context) : AsyncTaskLoader<Array<SearchResponse.SearchObject>>(con) { val searchClient = object : DefaultHttpClient() {} override fun loadInBackground(): Array<SearchResponse.SearchObject>? { val re = search(SearchRequest(key, page)) when ( re ) { is DetailResponse -> null//TODO is SearchResponse -> return re.objects//TODO improve } return null } public fun search(req: SearchRequest): Any? { val data = ArrayList<NameValuePair>() data.add(BasicNameValuePair("key", req.key)) data.add(BasicNameValuePair("curr_page", req.currPage.toString())) data.add(BasicNameValuePair("se_type", req.searchType)) data.add(BasicNameValuePair("lib_code", req.libCode.toString())) var re: Any ? = null try { val rep = searchClient.execute(PostHelper.newPost(getMainUrl() + "/search", data)) when (rep.getStatusLine().getStatusCode()) { HttpStatus.SC_OK -> { val str = EntityUtils.toString(rep.getEntity()) try { re = JSONHelper.readSearchResponse(str) } catch(e: OneResultException) { re = JSONHelper.readDetailResponse(str) } } } rep.getEntity().consumeContent() } catch (e: Exception) { e.printStackTrace() } return re } } public class SearchHeaderViewHolder(view: View) : RecyclerView.ViewHolder(view) public class SearchItemViewHolder(val view: View) : RecyclerView.ViewHolder(view) { val titleText = (view id R.id.text_view_book_title) as TextView val idText = (view id R.id.text_view_book_query_id) as TextView val authorText = (view id R.id.text_view_book_author) as TextView val pressText = (view id R.id.text_view_book_publisher) as TextView val markBtn = (view id R.id.bookMarkBtn) as ImageView val coverImage = (view id R.id.image_view_book_cover) as ImageView }
apache-2.0
9e2b945e7c659b9878cb656ea5dd7b7e
36.25
164
0.672372
4.637743
false
false
false
false
davidwhitman/deep-link-launcher
app/src/main/kotlin/com/thunderclouddev/deeplink/utils/Extensions.kt
1
2132
package com.thunderclouddev.deeplink.utils import android.content.Intent import android.content.pm.PackageManager import android.content.pm.ResolveInfo import android.view.View import com.thunderclouddev.deeplink.ui.Uri fun Throwable.hasCause(type: Class<*>): Boolean { var cause = this while (cause.cause != null) { cause = cause.cause!! if (cause.javaClass.name == type.name) { return true } } return false } fun Intent?.hasAnyHandlingActivity(packageManager: PackageManager) = if (this == null) false else packageManager.queryIntentActivities(this, 0).isNotEmpty() fun Intent?.handlingActivities(packageManager: PackageManager): List<ResolveInfo> = if (this == null) emptyList<ResolveInfo>() else packageManager.queryIntentActivities(this, PackageManager.MATCH_DEFAULT_ONLY) val Any?.simpleClassName: String get() = this?.javaClass?.simpleName ?: String.empty @Suppress("unused") val String.Companion.empty: String get() = "" fun String?.getOrNullIfBlank() = if (this.isNullOrBlank()) null else this fun CharSequence?.isNotNullOrBlank() = !this.isNullOrBlank() fun CharSequence.allIndicesOf(terms: Collection<String>): MutableList<Int> { val indices = mutableListOf<Int>() terms.forEach { term -> var index = this.indexOf(term) while (index >= 0) { indices.add(index) index = this.indexOf(term, index + 1) } } return indices } val Boolean.visibleOrGone: Int get() = if (this) View.VISIBLE else View.GONE var View.showing: Boolean get() = this.visibility == View.VISIBLE set(value) { this.visibility = value.visibleOrGone } fun String?.isUri(): Boolean { if (this != null) { try { val uri = Uri.parse(this) return uri.scheme.isNotNullOrBlank() && uri.authority.isNotNullOrBlank() } catch (ignored: IllegalArgumentException) { } } return false } fun String?.asUri(): Uri? = Uri.parse(this) fun <T> Iterable<T>.firstOr(defaultItem: T): T { return this.firstOrNull() ?: defaultItem }
gpl-3.0
92f102271a9a64534ff543277899bde6
25.65
133
0.669794
4.1
false
false
false
false
suzp1984/Algorithms-Collection
kotlin/basics/src/main/kotlin/ElementSort.kt
1
5181
package io.github.suzp1984.algorithms import java.util.* import kotlin.math.min fun <T> Array<T>.swap(i : Int, j : Int) { val t = this[i] this[i] = this[j] this[j] = t } fun <T : Comparable<T>> Array<T>.selectionSort() { indices.forEach { i -> var minIndex = i (i + 1 until size) .asSequence() .filter { this[it] < this[minIndex] } .forEach { minIndex = it } swap(minIndex, i) } } fun <T : Comparable<T>> Array<T>.insertionSort() { (1 until size).forEach { i -> (i downTo 1) .asSequence() .takeWhile { this[it] < this[it - 1] } .forEach { swap(it, it - 1) } } } fun <T : Comparable<T>> Array<T>.improvedInsertionSort() { (1 until size).forEach { i -> val t = this[i] val seqIndex = (i downTo 1) .asSequence() .takeWhile { this[it-1] > t } seqIndex.forEach { this[it] = this[it-1] } val lastIndex = seqIndex.lastOrNull() if (lastIndex != null) this[lastIndex - 1] = t } } fun <T : Comparable<T>> Array<T>.bubbleSort() { (0 until size).forEach { (1 until size - it).forEach { if (this[it] < this[it-1]) { swap(it, it-1) } } } } private fun <T : Comparable<T>> Array<T>.__merge(l : Int, mid : Int, r : Int) { val aux = copyOfRange(l, r + 1) var i = l var j = mid + 1 (l until r + 1).forEach { when { i > mid -> { this[it] = aux[j-l] j++ } j > r -> { this[it] = aux[i-l] i++ } aux[i-l] < aux[j-l] -> { this[it] = aux[i-l] i++ } else -> { this[it] = aux[j-l] j++ } } } } fun <T : Comparable<T>> Array<T>.mergeSort() { fun <T : Comparable<T>> Array<T>.__mergeSort(l : Int, r : Int) { if (l >= r) return val mid = l/2 + r/2 __mergeSort(l, mid) __mergeSort(mid+1, r) __merge(l, mid, r) } __mergeSort(0, size-1) } fun <T : Comparable<T>> Array<T>.bottomUpMergeSort() { var sz = 1 while (sz <= size) { var i = 0 while (i + sz < size) { __merge(i, i + sz - 1, min(i + sz + sz - 1, size - 1)) i += sz + sz } sz += sz } } fun <T : Comparable<T>> Array<T>.quickSort() { fun <T : Comparable<T>> Array<T>.__partition(l : Int, r : Int) : Int { val t = this[l] var j = l (l+1 until r+1).forEach { if (this[it] < t) { swap(++j, it) } } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortRandom() { fun <T : Comparable<T>> Array<T>.__partition(l : Int, r : Int) : Int { swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var j = l (l+1 until r+1).forEach { if (this[it] < t) { swap(++j, it) } } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortDoublePartition() { fun <T : Comparable<T>> Array<T>.__double_partition(l : Int, r : Int) : Int { swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var i = l + 1 var j = r while (true) { while (i <= r && this[i] < t) i++ while (j >= l + 1 && this[j] > t) j-- if (i > j) break swap(i, j) i++ j-- } swap(l, j) return j } fun <T : Comparable<T>> Array<T>.__quickSort(l : Int, r : Int) { if (l >= r) return val p = __double_partition(l, r) __quickSort(l, p - 1) __quickSort(p + 1, r) } __quickSort(0, size-1) } fun <T : Comparable<T>> Array<T>.quickSortTriplePartition() { fun <T : Comparable<T>> Array<T>.__triple_partition(l : Int, r : Int) { if (l >= r) { return } swap(l, Random().nextInt(r - l + 1) + l) val t = this[l] var lt = l var gt = r + 1; var i = l + 1; while (i < gt) { if (this[i] < t) { swap(i, lt + 1) lt++ i++ } else if (this[i] > t) { swap(i, gt - 1) gt-- } else { i++ } } swap(l, lt) __triple_partition(l, lt - 1) __triple_partition(gt, r) } __triple_partition(0, size - 1) }
apache-2.0
9837555f47f21a9a7d3842967bb9caff
21.628821
81
0.411697
3.178528
false
false
false
false
marvec/engine
lumeer-core/src/test/kotlin/io/lumeer/core/util/js/DataFiltersJsParserTest.kt
2
8466
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * 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 io.lumeer.core.util.js import io.lumeer.api.model.* import io.lumeer.api.model.Collection import io.lumeer.engine.api.data.DataDocument import org.assertj.core.api.Assertions import org.junit.Test import java.util.concurrent.Executors import java.util.concurrent.ThreadPoolExecutor import java.util.concurrent.TimeUnit class DataFiltersJsParserTest { private val collection1 = Collection("c1", "c1", "", "", "", null, Permissions(), setOf(Attribute("a1")), mapOf(), "", null).apply { id = "c1" } private val collection2 = Collection("c2", "c2", "", "", "", null, Permissions(), setOf(Attribute("a1")), mapOf(), "", null).apply { id = "c2" } private val linkType = LinkType("lt1", listOf(collection1.id, collection2.id), listOf(), mapOf(), Permissions(), LinkPermissionsType.Custom).apply { id = "lt1" } @Test fun test() { val c1AttributeId = collection1.attributes.first().id val document1 = Document(DataDocument(c1AttributeId, "abc")).apply { id = "d1" collectionId = collection1.id } val document2 = Document(DataDocument(c1AttributeId, "abcd")).apply { id = "d2" collectionId = collection1.id } val c2AttributeId = collection2.attributes.first().id val document3 = Document(DataDocument(c2AttributeId, "lumeer")).apply { id = "d3" collectionId = collection2.id } val document4 = Document(DataDocument(c2AttributeId, "nolumeer")).apply { id = "d4" collectionId = collection2.id } val permissions = AllowedPermissions.allAllowed() val collectionsPermissions = mapOf(collection1.id to permissions, collection2.id to permissions) val linkTypPermissions = mapOf(linkType.id to permissions) val constraintData = ConstraintData(listOf(), null, mapOf(), CurrencyData(listOf(), listOf()), "Europe/Bratislava", listOf(), listOf()) val link1 = LinkInstance(linkType.id, listOf(document1.id, document3.id)).apply { id = "li1" } val link2 = LinkInstance(linkType.id, listOf(document2.id, document4.id)).apply { id = "li2" } val simpleQuery = Query(listOf(QueryStem(null, collection1.id, listOf(), setOf(), listOf(), listOf())), setOf(), 0, 10) val simpleResult = DataFilter.filterDocumentsAndLinksByQuery( listOf(document1, document2), listOf(collection1), listOf(), listOf(), simpleQuery, collectionsPermissions, linkTypPermissions, constraintData, true ) val simpleResult2 = DataFilter.filterDocumentsAndLinksByQueryFromJson( listOf(document1, document2), listOf(collection1), listOf(), listOf(), simpleQuery, collectionsPermissions, linkTypPermissions, constraintData, true ) Assertions.assertThat(simpleResult.first).containsOnly(document1, document2) Assertions.assertThat(simpleResult2.first).containsOnly(document1, document2) val throughLinkFilter = CollectionAttributeFilter.createFromValues(collection2.id, c2AttributeId, ConditionType.EQUALS, "lumeer") val linkQuery = Query(listOf(QueryStem(null, collection1.id, listOf(linkType.id), setOf(), listOf(throughLinkFilter), listOf())), setOf(), 0, 10) val linkResult = DataFilter.filterDocumentsAndLinksByQuery( listOf(document1, document2, document3, document4), listOf(collection1, collection2), listOf(linkType), listOf(link1, link2), linkQuery, collectionsPermissions, linkTypPermissions, constraintData, true ) val linkResult2 = DataFilter.filterDocumentsAndLinksByQueryFromJson( listOf(document1, document2, document3, document4), listOf(collection1, collection2), listOf(linkType), listOf(link1, link2), linkQuery, collectionsPermissions, linkTypPermissions, constraintData, true ) Assertions.assertThat(linkResult.first).containsOnly(document1, document3) Assertions.assertThat(linkResult.second).containsOnly(link1) Assertions.assertThat(linkResult2.first).containsOnly(document1, document3) Assertions.assertThat(linkResult2.second).containsOnly(link1) } @Test fun performanceTest() { Task(1, 1000).run() } @Test fun multiThreadingTest() { val executor = Executors.newFixedThreadPool(4) as ThreadPoolExecutor for (i in 1..16) { executor.submit(Task(i, 10)) } executor.shutdown() executor.awaitTermination(30, TimeUnit.SECONDS) } class Task(val id: Int, val tasks: Int) : Runnable { private val collection1 = Collection("c1", "c1", "", "", "", null, Permissions(), setOf(Attribute("a1")), mapOf(), "", null).apply { id = "c1" } private val collection2 = Collection("c2", "c2", "", "", "", null, Permissions(), setOf(Attribute("a1")), mapOf(), "", null).apply { id = "c2" } private val linkType = LinkType("lt1", listOf(collection1.id, collection2.id), listOf(), mapOf(), Permissions(), LinkPermissionsType.Custom).apply { id = "lt1" } override fun run() { val c1AttributeId = collection1.attributes.first().id val document1 = Document(DataDocument(c1AttributeId, "abc")).apply { id = "d1" collectionId = collection1.id } val document2 = Document(DataDocument(c1AttributeId, "abcd")).apply { id = "d2" collectionId = collection1.id } val c2AttributeId = collection2.attributes.first().id val document3 = Document(DataDocument(c2AttributeId, "lumeer")).apply { id = "d3" collectionId = collection2.id } val document4 = Document(DataDocument(c2AttributeId, "nolumeer")).apply { id = "d4" collectionId = collection2.id } val permissions = AllowedPermissions.allAllowed() val collectionsPermissions = mapOf(collection1.id to permissions, collection2.id to permissions) val linkTypPermissions = mapOf(linkType.id to permissions) val constraintData = ConstraintData(listOf(), null, mapOf(), CurrencyData(listOf(), listOf()), "Europe/Bratislava", listOf(), listOf()) val documents = mutableListOf<Document>() val links = mutableListOf<LinkInstance>() for (i in 1..tasks) { val d = Document(document1).apply { id = "doc${i}" } documents.add(d) val l = LinkInstance(linkType.id, listOf(d.id, document3.id)).apply { id = "li${i}" } links.add(l) } val throughLinkFilter = CollectionAttributeFilter.createFromValues(collection2.id, c2AttributeId, ConditionType.EQUALS, "lumeer") val linkQuery = Query(listOf(QueryStem(null, collection1.id, listOf(linkType.id), setOf(), listOf(throughLinkFilter), listOf())), setOf(), 0, 10) val linkResult = DataFilter.filterDocumentsAndLinksByQueryFromJson( documents, listOf(collection1, collection2), listOf(linkType), links, linkQuery, collectionsPermissions, linkTypPermissions, constraintData, true ) } } }
gpl-3.0
637f6eac66f1f19ec4e7bfc0f7e4cd17
44.272727
169
0.629341
4.441763
false
false
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/systems/gui/Guis.kt
2
25191
package com.cout970.magneticraft.systems.gui import com.cout970.magneticraft.api.internal.registries.machines.gasificationunit.GasificationUnitRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.grinder.GrinderRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.hydraulicpress.HydraulicPressRecipeManager import com.cout970.magneticraft.api.internal.registries.machines.sieve.SieveRecipeManager import com.cout970.magneticraft.api.registries.machines.hydraulicpress.HydraulicPressMode import com.cout970.magneticraft.features.automatic_machines.TileFilter import com.cout970.magneticraft.features.automatic_machines.TileInserter import com.cout970.magneticraft.features.automatic_machines.TileRelay import com.cout970.magneticraft.features.automatic_machines.TileTransposer import com.cout970.magneticraft.features.computers.ContainerComputer import com.cout970.magneticraft.features.computers.ContainerMiningRobot import com.cout970.magneticraft.features.computers.TileComputer import com.cout970.magneticraft.features.computers.TileMiningRobot import com.cout970.magneticraft.features.electric_conductors.TileTeslaTower import com.cout970.magneticraft.features.electric_machines.* import com.cout970.magneticraft.features.fluid_machines.TileSmallTank import com.cout970.magneticraft.features.heat_machines.* import com.cout970.magneticraft.features.items.Upgrades import com.cout970.magneticraft.features.manual_machines.ContainerFabricator import com.cout970.magneticraft.features.manual_machines.TileBox import com.cout970.magneticraft.features.manual_machines.TileFabricator import com.cout970.magneticraft.features.multiblocks.ContainerShelvingUnit import com.cout970.magneticraft.features.multiblocks.tileentities.* import com.cout970.magneticraft.misc.gui.SlotType import com.cout970.magneticraft.misc.inventory.isNotEmpty import com.cout970.magneticraft.misc.network.IBD import com.cout970.magneticraft.misc.t import com.cout970.magneticraft.misc.vector.Vec2d import com.cout970.magneticraft.misc.vector.vec2Of import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.FORGE_ENERGY import com.cout970.magneticraft.registry.fromItem import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.gui.components.CompFabricatorMatches import com.cout970.magneticraft.systems.gui.components.ComponentShelvingUnit import com.cout970.magneticraft.systems.gui.components.MonitorComponent import com.cout970.magneticraft.systems.gui.components.bars.* import com.cout970.magneticraft.systems.tilemodules.ModulePumpjack.Status.* import net.minecraft.init.Items import net.minecraft.item.crafting.FurnaceRecipes import net.minecraft.tileentity.TileEntityFurnace import net.minecraftforge.items.wrapper.InvWrapper fun GuiBuilder.boxGui(tile: TileBox) { container { slotGroup(3, 9, tile.inventory, 0, "inv_start") region(0, 27) playerInventory("player_inv_offset") } } fun GuiBuilder.electricHeaterGui(tile: TileElectricHeater) { container { playerInventory() } bars { electricBar(tile.electricNode) heatBar(tile.heatNode) consumptionBar(tile.electricHeaterModule.consumption, Config.electricHeaterMaxProduction) productionBar(tile.electricHeaterModule.production, Config.electricHeaterMaxProduction) } } fun GuiBuilder.rfHeaterGui(tile: TileRfHeater) { container { playerInventory() } bars { rfBar(tile.rfModule.storage) heatBar(tile.node) consumptionBar(tile.electricHeaterModule.consumption, Config.electricHeaterMaxProduction) productionBar(tile.electricHeaterModule.production, Config.electricHeaterMaxProduction) } } fun GuiBuilder.combustionChamberGui(tile: TileCombustionChamber) { container { slot(tile.invModule.inventory, 0, "fuel_slot", SlotType.INPUT) region(0, 1, filter = { it, _ -> it.isNotEmpty && it.item == Items.COAL }) playerInventory() } bars { heatBar(tile.node) fuelBar(tile.combustionChamberModule) slotSpacer() } } fun GuiBuilder.steamBoilerGui(tile: TileSteamBoiler) { container { playerInventory() } bars { heatBar(tile.node) machineFluidBar(tile.boilerModule.production, tile.boilerModule.maxProduction) tank(tile.waterTank, TankIO.IN) tank(tile.steamTank, TankIO.OUT) } } fun GuiBuilder.batteryBlockGui(tile: TileBattery) { container { slot(tile.invModule.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.invModule.inventory, 1, "output_slot", SlotType.OUTPUT) region(0, 1, filter = { it, _ -> FORGE_ENERGY!!.fromItem(it)?.canReceive() ?: false }) region(1, 1, filter = { it, _ -> FORGE_ENERGY!!.fromItem(it)?.canExtract() ?: false }) playerInventory() } bars { electricBar(tile.node) electricTransferBar(tile.storageModule.chargeRate, -tile.storageModule.maxChargeSpeed, tile.storageModule.maxChargeSpeed) storageBar(tile.storageModule) electricTransferBar(tile.itemChargeModule.itemChargeRate, -tile.itemChargeModule.transferRate, tile.itemChargeModule.transferRate) slotSpacer() } } fun GuiBuilder.electricFurnaceGui(tile: TileElectricFurnace) { container { slot(tile.invModule.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.invModule.inventory, 1, "output_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> FurnaceRecipes.instance().getSmeltingResult(it).isNotEmpty }) region(1, 1, filter = { _, _ -> false }) playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) consumptionBar(tile.processModule.consumption, Config.electricFurnaceMaxConsumption) progressBar(tile.processModule.timedProcess) slotSpacer() } } fun GuiBuilder.bigElectricFurnaceGui(tile: TileBigElectricFurnace) { container { slot(tile.invModule.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.invModule.inventory, 1, "output_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> FurnaceRecipes.instance().getSmeltingResult(it).isNotEmpty }) region(1, 1, filter = { _, _ -> false }) playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) consumptionBar(tile.processModule.consumption, Config.bigElectricFurnaceMaxConsumption) progressBar(tile.processModule.timedProcess) slotSpacer() } } fun GuiBuilder.brickFurnaceGui(tile: TileBrickFurnace) { container { slot(tile.invModule.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.invModule.inventory, 1, "output_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> FurnaceRecipes.instance().getSmeltingResult(it).isNotEmpty }) region(1, 1, filter = { _, _ -> false }) playerInventory() } bars { heatBar(tile.node) consumptionBar(tile.processModule.consumption, Config.electricFurnaceMaxConsumption) progressBar(tile.processModule.timedProcess) slotSpacer() } } fun GuiBuilder.thermopileGui(tile: TileThermopile) { container { playerInventory() } bars { electricBar(tile.node) storageBar(tile.storage) productionBar(tile.thermopileModule.production, Config.thermopileProduction) StaticBarProvider(0.0, 10_000.0, tile.thermopileModule::totalFlux).let { prov -> genericBar(2, 4, prov, prov.toIntText(postfix = " Heat Flux/t")) } } } fun GuiBuilder.windTurbineGui(tile: TileWindTurbine) { container { playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) productionBar(tile.windTurbineModule.production, Config.windTurbineMaxProduction) StaticBarProvider(0.0, 1.0, tile.windTurbineModule::openSpace).let { prov -> genericBar(8, 5, prov, prov.toPercentText("Wind clearance: ")) } StaticBarProvider(0.0, 1.0, tile.windTurbineModule::currentWind).let { prov -> genericBar(9, 7, prov, prov.toPercentText("Wind speed: ", "%")) } } } fun GuiBuilder.gasificationUnitGui(tile: TileGasificationUnit) { container { slot(tile.inv, 0, "input_slot", SlotType.INPUT) slot(tile.inv, 1, "output_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> GasificationUnitRecipeManager.findRecipe(it) != null }) region(1, 1, filter = { _, _ -> false }) playerInventory() } bars { heatBar(tile.heatNode) consumptionBar(tile.process.consumption, Config.gasificationUnitConsumption) progressBar(tile.process.timedProcess) slotSpacer() tank(tile.tank, TankIO.OUT) } } fun GuiBuilder.grinderGui(tile: TileGrinder) { container { slot(tile.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.inventory, 1, "output_slot", SlotType.OUTPUT, blockInput = true) slot(tile.inventory, 2, "output2_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> GrinderRecipeManager.findRecipe(it) != null }) region(1, 1, filter = { _, _ -> false }) region(2, 1, filter = { _, _ -> false }) playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) consumptionBar(tile.processModule.consumption, Config.grinderMaxConsumption) progressBar(tile.processModule.timedProcess) drawable(vec2Of(40, 50), "arrow_offset", "arrow_size", "arrow_uv") } } fun GuiBuilder.sieveGui(tile: TileSieve) { container { slot(tile.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.inventory, 1, "output_slot", SlotType.OUTPUT, blockInput = true) slot(tile.inventory, 2, "output2_slot", SlotType.OUTPUT, blockInput = true) slot(tile.inventory, 3, "output3_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> SieveRecipeManager.findRecipe(it) != null }) region(1, 1, filter = { _, _ -> false }) region(2, 1, filter = { _, _ -> false }) region(3, 1, filter = { _, _ -> false }) playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) consumptionBar(tile.processModule.consumption, Config.sieveMaxConsumption) progressBar(tile.processModule.timedProcess) drawable(vec2Of(62, 50), "arrow_offset", "arrow_size", "arrow_uv") } } fun GuiBuilder.containerGui(tile: TileContainer) { container { val inv = tile.stackInventoryModule.getGuiInventory() slot(inv, 0, "input_slot", SlotType.INPUT) slot(inv, 1, "output_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { _, i -> i != 1 }) region(1, 1, filter = { _, _ -> false }) playerInventory() } bars { val mod = tile.stackInventoryModule val callback = CallbackBarProvider(mod::amount, mod::maxItems, ZERO) genericBar(7, 3, callback) { listOf("Items: ${mod.amount}/${mod.maxItems}") } slotSpacer() } } fun GuiBuilder.pumpjackGui(tile: TilePumpjack) { container { playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) consumptionBar(tile.pumpjackModule.production, Config.pumpjackConsumption) val mod = tile.pumpjackModule val processCallback = CallbackBarProvider({ when (mod.status) { SEARCHING_OIL, SEARCHING_DEPOSIT, DIGGING -> { mod.processPercent } SEARCHING_SOURCE, EXTRACTING -> { mod.depositLeft } } }, { when (mod.status) { SEARCHING_OIL, SEARCHING_DEPOSIT, DIGGING -> { 1.0 } SEARCHING_SOURCE, EXTRACTING -> { mod.depositSize } } }, ZERO) genericBar(6, 3, processCallback) { val percent = "%.2f".format(mod.processPercent * 100f) val amount = "${mod.depositLeft}/${mod.depositSize}" when (mod.status) { SEARCHING_OIL -> listOf("Searching for oil: $percent%") SEARCHING_DEPOSIT -> listOf("Scanning deposit size: $percent%") DIGGING -> listOf("Mining to deposit: $percent%") SEARCHING_SOURCE -> listOf("Oil deposit: $amount blocks", "Moving to next source: $percent%") EXTRACTING -> listOf("Oil deposit: $amount blocks", "Extracting...") } } tank(tile.tank, TankIO.OUT) } } fun GuiBuilder.oilHeaterGui(tile: TileOilHeater) { container { playerInventory() } bars { heatBar(tile.node) consumptionBar(tile.processModule.consumption, tile.processModule.costPerTick) tank(tile.inputTank, TankIO.IN) tank(tile.outputTank, TankIO.OUT) } } fun GuiBuilder.refineryGui(tile: TileRefinery) { container { playerInventory() } bars { machineFluidBar(tile.processModule.consumption, Config.refineryMaxConsumption) tank(tile.steamTank, TankIO.IN) tank(tile.inputTank, TankIO.IN) tank(tile.outputTank0, TankIO.OUT) tank(tile.outputTank1, TankIO.OUT) tank(tile.outputTank2, TankIO.OUT) } } fun GuiBuilder.steamEngineGui(tile: TileSteamEngine) { container { playerInventory() } bars { electricBar(tile.node) storageBar(tile.storageModule) productionBar(tile.steamGeneratorModule.production, tile.steamGeneratorModule.maxProduction) tank(tile.tank, TankIO.IN) } } fun GuiBuilder.bigCombustionChamberGui(tile: TileBigCombustionChamber) { container { slot(tile.inventory, 0, "fuel_slot") region(0, 1) { it, _ -> TileEntityFurnace.isItemFuel(it) } playerInventory() } bars { heatBar(tile.node) fuelBar(tile.bigCombustionChamberModule) tank(tile.tank, TankIO.IN) slotSpacer() } } fun GuiBuilder.bigSteamBoilerGui(tile: TileBigSteamBoiler) { container { playerInventory() } bars { heatBar(tile.node) machineFluidBar(tile.boiler.production, tile.boiler.maxProduction) tank(tile.input, TankIO.IN) tank(tile.output, TankIO.OUT) } } fun GuiBuilder.steamTurbineGui(tile: TileSteamTurbine) { container { playerInventory() } bars { electricBar(tile.node) productionBar(tile.steamGeneratorModule.production, tile.steamGeneratorModule.maxProduction) tank(tile.tank, TankIO.IN) } } fun GuiBuilder.relayGui(tile: TileRelay) { container { slotGroup(3, 3, tile.inventory, 0, "inv_start") region(0, 9) playerInventory() } bars { slotSpacer(3, 3) } } fun GuiBuilder.filterGui(tile: TileFilter) { container { slotGroup(3, 3, tile.inventory, 0, "inv_start", SlotType.FILTER) region(0, 9) { _, _ -> false } playerInventory() } bars { slotSpacer(3, 3) } } fun GuiBuilder.transposerGui(tile: TileTransposer) { container { slotGroup(3, 3, tile.inventory, 0, "inv_start", SlotType.FILTER) region(0, 9) { _, _ -> false } playerInventory() } bars { slotSpacer(3, 3) } } fun GuiBuilder.fabricatorGui(tile: TileFabricator) { containerClass = ::ContainerFabricator container { slotGroup(3, 3, InvWrapper(tile.fabricatorModule.recipeGrid), 0, "recipe_grid", SlotType.FILTER) slotButton(tile.fabricatorModule.craftingResult, 0, "recipe_result") { player, type -> if (player.world.isServer) { if (type == 1) { tile.fabricatorModule.clearGrid() } else if (type == 0) { tile.fabricatorModule.requestItemCraft() } } } slotGroup(3, 3, tile.inventory, 0, "inv_start") region(0, 9) { _, _ -> false } region(9, 1) { _, _ -> false } region(10, 9) playerInventory() } components { custom { CompFabricatorMatches(tile) } } bars { slotSpacer(3, 3) slotSpacer() slotSpacer(3, 3) } } fun GuiBuilder.solarTowerGui(tile: TileSolarTower) { container { playerInventory() onClick("btn1") { sendToServer(IBD().setBoolean(0, true)) } receiveDataFromClient { tile.solarTowerModule.searchMirrors = true } } bars { heatBar(tile.node) productionBar(tile.solarTowerModule.production, 500) clickButton("btn1", "button_offset") drawable(vec2Of(0), "icon_offset", "icon_size", "icon_uv") } } fun GuiBuilder.inserterGui(tile: TileInserter) { container { slot(tile.inventory, 0, "grabbed") slot(tile.inventory, 1, "upgrade1") slot(tile.inventory, 2, "upgrade2") slotGroup(3, 3, tile.filters, 0, "filters", SlotType.FILTER) region(0, 1) { stack, _ -> stack.item != Upgrades.inserterUpgrade } region(1, 2) { stack, _ -> stack.item == Upgrades.inserterUpgrade } region(3, 9) { _, _ -> false } playerInventory() switchButtonState("btn0") { tile.inserterModule.whiteList } switchButtonState("btn1") { tile.inserterModule.useOreDictionary } switchButtonState("btn2") { tile.inserterModule.useMetadata } switchButtonState("btn3") { tile.inserterModule.useNbt } switchButtonState("btn4") { tile.inserterModule.canDropItems } switchButtonState("btn5") { tile.inserterModule.canGrabItems } onClick("btn0") { sendToServer(IBD().setInteger(0, 0)) } onClick("btn1") { sendToServer(IBD().setInteger(0, 1)) } onClick("btn2") { sendToServer(IBD().setInteger(0, 2)) } onClick("btn3") { sendToServer(IBD().setInteger(0, 3)) } onClick("btn4") { sendToServer(IBD().setInteger(0, 4)) } onClick("btn5") { sendToServer(IBD().setInteger(0, 5)) } receiveDataFromClient { it.getInteger(0) { prop -> val mod = tile.inserterModule when (prop) { 0 -> mod.whiteList = !mod.whiteList 1 -> mod.useOreDictionary = !mod.useOreDictionary 2 -> mod.useMetadata = !mod.useMetadata 3 -> mod.useNbt = !mod.useNbt 4 -> mod.canDropItems = !mod.canDropItems 5 -> mod.canGrabItems = !mod.canGrabItems } } } } bars { slotSpacer(3, 3) slotSpacer(1, 2) group(vec2Of(38, 58)) { switchButton("btn0", "btn0_offset", "btn0_on", "btn0_off", t("gui.magneticraft.inserter.btn0"), t("gui.magneticraft.inserter.btn0_off")) switchButton("btn1", "btn1_offset", "btn1_on", "btn1_off", t("gui.magneticraft.inserter.btn1"), t("gui.magneticraft.inserter.btn1_off")) switchButton("btn2", "btn2_offset", "btn2_on", "btn2_off", t("gui.magneticraft.inserter.btn2"), t("gui.magneticraft.inserter.btn2_off")) switchButton("btn3", "btn3_offset", "btn3_on", "btn3_off", t("gui.magneticraft.inserter.btn3"), t("gui.magneticraft.inserter.btn3_off")) switchButton("btn4", "btn4_offset", "btn4_on", "btn4_off", t("gui.magneticraft.inserter.btn4"), t("gui.magneticraft.inserter.btn4_off")) switchButton("btn5", "btn5_offset", "btn5_on", "btn5_off", t("gui.magneticraft.inserter.btn5"), t("gui.magneticraft.inserter.btn5_off")) } } } fun GuiBuilder.hydraulicPressGui(tile: TileHydraulicPress) { container { slot(tile.inventory, 0, "input_slot", SlotType.INPUT) slot(tile.inventory, 1, "output_slot", SlotType.OUTPUT, blockInput = true) region(0, 1, filter = { it, _ -> HydraulicPressRecipeManager.findRecipe(it, tile.hydraulicPressModule.mode) != null }) region(1, 1, filter = { _, _ -> false }) playerInventory() receiveDataFromClient { data -> data.getInteger(0) { tile.hydraulicPressModule.mode = HydraulicPressMode.values()[it] } } onClick("btn0_0") { sendToServer(IBD().setInteger(0, 0)) } onClick("btn0_1") { sendToServer(IBD().setInteger(0, 1)) } onClick("btn0_2") { sendToServer(IBD().setInteger(0, 2)) } selectButtonState("btn0") { tile.hydraulicPressModule.mode.ordinal } } bars { electricBar(tile.node) storageBar(tile.storageModule) consumptionBar(tile.processModule.consumption, Config.hydraulicPressMaxConsumption) progressBar(tile.processModule.timedProcess) drawable(Vec2d.ZERO, "arrow_offset", "arrow_size", "arrow_uv") slotSpacer() selectButton(vec2Of(18, 68), "btn0") { option("opt0_offset", "opt0_background", t("gui.magneticraft.hydraulic_press.opt0")) option("opt1_offset", "opt1_background", t("gui.magneticraft.hydraulic_press.opt1")) option("opt2_offset", "opt2_background", t("gui.magneticraft.hydraulic_press.opt2")) } } } fun GuiBuilder.shelvingUnitGui(@Suppress("UNUSED_PARAMETER") tile: TileShelvingUnit) { containerClass = ::ContainerShelvingUnit container { onClick("btn1") { sendToServer(IBD().setBoolean(DATA_ID_SHELVING_UNIT_SORT, true)) } onClick("btn0_0") { (container as ContainerShelvingUnit).levelButton(0) } onClick("btn0_1") { (container as ContainerShelvingUnit).levelButton(1) } onClick("btn0_2") { (container as ContainerShelvingUnit).levelButton(2) } selectButtonState("btn0") { (container as ContainerShelvingUnit).currentLevel.ordinal } } components { searchBar("search0", "search_pos") scrollBar("scroll0", "scroll_pos", 19) custom { ComponentShelvingUnit() } clickButton("btn1", "button_offset") drawable("button_icon_pos", "button_icon_size", "button_icon_uv") selectButton("btn0") { option("opt0_offset", "opt0_background", t("gui.magneticraft.shelving_unit.opt0")) option("opt1_offset", "opt1_background", t("gui.magneticraft.shelving_unit.opt1")) option("opt2_offset", "opt2_background", t("gui.magneticraft.shelving_unit.opt2")) } } } fun GuiBuilder.rfTransformerGui(tile: TileRfTransformer) { container { playerInventory() } bars { electricBar(tile.node) rfBar(tile.storage) } } fun GuiBuilder.electricEngineGui(tile: TileElectricEngine) { container { playerInventory() } bars { electricBar(tile.node) rfBar(tile.storage) } } fun GuiBuilder.airlockGui(tile: TileAirLock) { container { playerInventory() } bars { electricBar(tile.node) } } fun GuiBuilder.smallTankGui(tile: TileSmallTank) { container { playerInventory() } bars { tank(tile.tank, TankIO.INOUT) } } fun GuiBuilder.teslaTowerGui(tile: TileTeslaTower) { container { playerInventory() } bars { electricBar(tile.node) } } fun GuiBuilder.solarPanelGui(tile: TileSolarPanel) { container { playerInventory() } bars { electricBar(tile.node) } } fun GuiBuilder.computerGui(tile: TileComputer) { containerClass = ::ContainerComputer val motherboard = tile.computerModule.motherboard container { onClick("btn0") { sendToServer(IBD().setInteger(DATA_ID_COMPUTER_BUTTON, 0)) } } components { custom { MonitorComponent(tile.ref, tile.monitor, tile.keyboard) } clickButton("btn0", "button_offset") light("button_icon_offset", "button_icon_size", "button_icon_on_uv") { motherboard.isOnline } light("button_icon_offset", "button_icon_size", "button_icon_off_uv") { !motherboard.isOnline } } } fun GuiBuilder.miningRobotGui(tile: TileMiningRobot) { containerClass = ::ContainerMiningRobot val motherboard = tile.computerModule.motherboard container { onClick("btn0") { sendToServer(IBD().setInteger(DATA_ID_COMPUTER_BUTTON, 0)) } } components { custom { MonitorComponent(tile.ref, tile.monitor, tile.keyboard) } clickButton("btn0", "button_offset") light("button_icon_offset", "button_icon_size", "button_icon_on_uv") { motherboard.isOnline } light("button_icon_offset", "button_icon_size", "button_icon_off_uv") { !motherboard.isOnline } electricBar("electric_bar_offset", tile.node) storageBar("storage_bar_offset", tile.energyStorage) } }
gpl-2.0
a5e48d161b0eeb55a0a0bb11ffc9eec1
34.632249
148
0.648644
3.752011
false
false
false
false
Magneticraft-Team/Magneticraft
ignore/test/block/BlockComputer.kt
2
3938
package block import com.cout970.magneticraft.Magneticraft import com.cout970.magneticraft.misc.block.get import com.cout970.magneticraft.misc.inventory.get import com.cout970.magneticraft.misc.inventory.set import com.cout970.magneticraft.misc.tileentity.getTile import com.cout970.magneticraft.misc.world.isServer import com.cout970.magneticraft.registry.ITEM_FLOPPY_DISK import com.cout970.magneticraft.registry.fromItem import com.cout970.magneticraft.tileentity.computer.TileComputer import com.teamwizardry.librarianlib.common.base.block.BlockModContainer import net.minecraft.block.material.Material import net.minecraft.block.state.BlockStateContainer import net.minecraft.block.state.IBlockState import net.minecraft.entity.EntityLivingBase import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.ItemStack import net.minecraft.tileentity.TileEntity import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.math.BlockPos import net.minecraft.world.World /** * Created by cout970 on 2016/09/30. */ object BlockComputer : BlockModContainer("computer", Material.IRON) { init { lightOpacity = 0 } override fun isFullBlock(state: IBlockState?) = false override fun isOpaqueCube(state: IBlockState?) = false override fun isFullCube(state: IBlockState?) = false override fun isVisuallyOpaque() = false override fun createTileEntity(worldIn: World, meta: IBlockState): TileEntity = TileComputer() override fun onBlockActivated(worldIn: World, pos: BlockPos, state: IBlockState?, playerIn: EntityPlayer, hand: EnumHand?, heldItem: ItemStack?, side: EnumFacing?, hitX: Float, hitY: Float, hitZ: Float): Boolean { if (!playerIn.isSneaking) { if (worldIn.isServer) { var block = true if (heldItem != null) { val cap = ITEM_FLOPPY_DISK!!.fromItem(heldItem) if (cap != null) { val tile = worldIn.getTile<TileComputer>(pos) if (tile != null && tile.inv[0] == null) { val index = playerIn.inventory.currentItem if (index in 0..8) { tile.inv[0] = playerIn.inventory.removeStackFromSlot(index) } } else { block = false } } else { block = false } } else { block = false } if (!block) { playerIn.openGui(Magneticraft, -1, worldIn, pos.x, pos.y, pos.z) } } return true } else { if (worldIn.isServer && hand == EnumHand.MAIN_HAND && heldItem == null) { val tile = worldIn.getTile<TileComputer>(pos) if (tile != null && tile.inv[0] != null) { playerIn.inventory.addItemStackToInventory(tile.inv.extractItem(0, 64, false)) } } } return super.onBlockActivated(worldIn, pos, state, playerIn, hand, heldItem, side, hitX, hitY, hitZ) } override fun onBlockPlacedBy(worldIn: World?, pos: BlockPos, state: IBlockState?, placer: EntityLivingBase, stack: ItemStack?) { super.onBlockPlacedBy(worldIn, pos, state, placer, stack) worldIn?.setBlockState(pos, defaultState.withProperty(PROPERTY_DIRECTION, placer.horizontalFacing.opposite)) } override fun getMetaFromState(state: IBlockState): Int = state[PROPERTY_DIRECTION].ordinal override fun getStateFromMeta(meta: Int): IBlockState = defaultState.withProperty(PROPERTY_DIRECTION, EnumFacing.getHorizontal(meta)) override fun createBlockState(): BlockStateContainer = BlockStateContainer(this, PROPERTY_DIRECTION) }
gpl-2.0
d77116a7533dfcc719f8552d11b38877
40.904255
217
0.64195
4.654846
false
false
false
false
facebook/litho
litho-core-kotlin/src/test/kotlin/com/facebook/litho/StateEqualityTest.kt
1
4066
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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.facebook.litho import com.facebook.litho.testing.LithoViewRule import com.facebook.litho.testing.testrunner.LithoTestRunner import java.util.concurrent.atomic.AtomicReference import org.assertj.core.api.Assertions.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.annotation.LooperMode /** Unit tests for equals of [State]. */ @LooperMode(LooperMode.Mode.LEGACY) @RunWith(LithoTestRunner::class) class StateEqualityTest { @Rule @JvmField val lithoViewRule = LithoViewRule() @Test fun `same state with same value is equal`() { val stateBox = AtomicReference<State<Int>>() val testView = lithoViewRule.render { StateBoxComponent(initialState1 = 1, initialState2 = 1, stateBox1 = stateBox) } val firstState = stateBox.get() stateBox.set(null) // initial states changing just to bust cache testView.setRoot(StateBoxComponent(initialState1 = 2, initialState2 = 2, stateBox1 = stateBox)) val secondState = stateBox.get() assertThat(firstState).isEqualTo(secondState) } @Test fun `different state with same value is not equal`() { val stateBox1 = AtomicReference<State<Int>>() val stateBox2 = AtomicReference<State<Int>>() lithoViewRule.render { StateBoxComponent( initialState1 = 1, initialState2 = 1, stateBox1 = stateBox1, stateBox2 = stateBox2) } assertThat(stateBox1.get()).isNotEqualTo(stateBox2.get()) } @Test fun `same state with different values is not equal`() { val stateBox = AtomicReference<State<Int>>() lithoViewRule.render { StateBoxComponent(initialState1 = 1, initialState2 = 1, stateBox1 = stateBox) } val firstState = stateBox.get() stateBox.set(null) firstState.updateSync(17) val secondState = stateBox.get() assertThat(firstState).isNotEqualTo(secondState) } @Test fun `same state from different trees is not equal`() { val stateBox = AtomicReference<State<Int>>() lithoViewRule.render { StateBoxComponent(initialState1 = 1, initialState2 = 1, stateBox1 = stateBox) } val firstState = stateBox.get() stateBox.set(null) lithoViewRule.render { StateBoxComponent(initialState1 = 1, initialState2 = 1, stateBox1 = stateBox) } val secondState = stateBox.get() assertThat(firstState).isNotEqualTo(secondState) } @Test fun `same state with different keys is not equal`() { val stateBox1 = AtomicReference<State<Int>>() val stateBox2 = AtomicReference<State<Int>>() lithoViewRule.render { Column { child(StateBoxComponent(initialState1 = 1, initialState2 = 1, stateBox1 = stateBox1)) child(StateBoxComponent(initialState1 = 1, initialState2 = 1, stateBox1 = stateBox2)) } } assertThat(stateBox1.get()).isNotEqualTo(stateBox2.get()) } private data class DataClassDemo(val i: Int) private class StateBoxComponent<T>( private val initialState1: T, private val initialState2: T, private val stateBox1: AtomicReference<State<T>>? = null, private val stateBox2: AtomicReference<State<T>>? = null, ) : KComponent() { override fun ComponentScope.render(): Component? { val state1 = useState { initialState1 } val state2 = useState { initialState2 } stateBox1?.set(state1) stateBox2?.set(state2) return Column() } } }
apache-2.0
4eac44c38bab8f22c4be99d21fe41b5d
29.118519
99
0.704624
4.029732
false
true
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/icons/CustomIconPack.kt
1
8389
package app.lawnchair.icons import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.content.res.Resources import android.content.res.XmlResourceParser import android.graphics.drawable.Drawable import android.util.Xml import com.android.launcher3.R import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOn import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import org.xmlpull.v1.XmlPullParserFactory import java.io.IOException class CustomIconPack(context: Context, packPackageName: String) : IconPack(context, packPackageName) { private val packResources = context.packageManager.getResourcesForApplication(packPackageName) private val componentMap = mutableMapOf<ComponentName, IconEntry>() private val calendarMap = mutableMapOf<ComponentName, IconEntry>() private val clockMap = mutableMapOf<ComponentName, IconEntry>() private val clockMetas = mutableMapOf<IconEntry, ClockMetadata>() private val idCache = mutableMapOf<String, Int>() override val label = context.packageManager.let { pm -> pm.getApplicationInfo(packPackageName, 0).loadLabel(pm).toString() } init { startLoad() } override fun getIcon(componentName: ComponentName) = componentMap[componentName] override fun getCalendar(componentName: ComponentName) = calendarMap[componentName] override fun getClock(entry: IconEntry) = clockMetas[entry] override fun getCalendars(): MutableSet<ComponentName> = calendarMap.keys override fun getClocks(): MutableSet<ComponentName> = clockMap.keys override fun getIcon(iconEntry: IconEntry, iconDpi: Int): Drawable? { val id = getDrawableId(iconEntry.name) if (id == 0) return null return try { ExtendedBitmapDrawable.wrap( packResources, packResources.getDrawableForDensity(id, iconDpi, null), true ) } catch (e: Resources.NotFoundException) { null } } fun createFromExternalPicker(icon: Intent.ShortcutIconResource): IconPickerItem? { val id = packResources.getIdentifier(icon.resourceName, null, null) if (id == 0) return null val simpleName = packResources.getResourceEntryName(id) return IconPickerItem(packPackageName, simpleName, simpleName, IconType.Normal) } override fun loadInternal() { val parseXml = getXml("appfilter") ?: return val compStart = "ComponentInfo{" val compStartLength = compStart.length val compEnd = "}" val compEndLength = compEnd.length try { while (parseXml.next() != XmlPullParser.END_DOCUMENT) { if (parseXml.eventType != XmlPullParser.START_TAG) continue val name = parseXml.name val isCalendar = name == "calendar" when (name) { "item", "calendar" -> { var componentName: String? = parseXml["component"] val drawableName = parseXml[if (isCalendar) "prefix" else "drawable"] if (componentName != null && drawableName != null) { if (componentName.startsWith(compStart) && componentName.endsWith(compEnd)) { componentName = componentName.substring(compStartLength, componentName.length - compEndLength) } val parsed = ComponentName.unflattenFromString(componentName) if (parsed != null) { if (isCalendar) { calendarMap[parsed] = IconEntry(packPackageName, drawableName, IconType.Calendar) } else { componentMap[parsed] = IconEntry(packPackageName, drawableName, IconType.Normal) } } } } "dynamic-clock" -> { val drawableName = parseXml["drawable"] if (drawableName != null) { if (parseXml is XmlResourceParser) { clockMetas[IconEntry(packPackageName, drawableName, IconType.Normal)] = ClockMetadata( parseXml.getAttributeIntValue(null, "hourLayerIndex", -1), parseXml.getAttributeIntValue(null, "minuteLayerIndex", -1), parseXml.getAttributeIntValue(null, "secondLayerIndex", -1), parseXml.getAttributeIntValue(null, "defaultHour", 0), parseXml.getAttributeIntValue(null, "defaultMinute", 0), parseXml.getAttributeIntValue(null, "defaultSecond", 0)) } } } } } componentMap.forEach { (componentName, iconEntry) -> if (clockMetas.containsKey(iconEntry)) { clockMap[componentName] = iconEntry } } } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } catch (e: XmlPullParserException) { e.printStackTrace() } catch (e: IOException) { e.printStackTrace() } catch (e: IllegalStateException) { e.printStackTrace() } } @Suppress("BlockingMethodInNonBlockingContext") override fun getAllIcons(): Flow<List<IconPickerCategory>> = flow { load() val result = mutableListOf<IconPickerCategory>() var currentTitle: String? = null val currentItems = mutableListOf<IconPickerItem>() suspend fun endCategory() { if (currentItems.isEmpty()) return val title = currentTitle ?: context.getString(R.string.icon_picker_default_category) result.add(IconPickerCategory(title, ArrayList(currentItems))) currentTitle = null currentItems.clear() emit(ArrayList(result)) } val parser = getXml("drawable") while (parser != null && parser.next() != XmlPullParser.END_DOCUMENT) { if (parser.eventType != XmlPullParser.START_TAG) continue when (parser.name) { "category" -> { val title = parser["title"] ?: continue endCategory() currentTitle = title } "item" -> { val drawableName = parser["drawable"] ?: continue val resId = getDrawableId(drawableName) if (resId != 0) { val item = IconPickerItem(packPackageName, drawableName, drawableName, IconType.Normal) currentItems.add(item) } } } } endCategory() }.flowOn(Dispatchers.IO) private fun getDrawableId(name: String) = idCache.getOrPut(name) { packResources.getIdentifier(name, "drawable", packPackageName) } private fun getXml(name: String): XmlPullParser? { val res: Resources try { res = context.packageManager.getResourcesForApplication(packPackageName) val resourceId = res.getIdentifier(name, "xml", packPackageName) return if (0 != resourceId) { context.packageManager.getXml(packPackageName, resourceId, null) } else { val factory = XmlPullParserFactory.newInstance() val parser = factory.newPullParser() parser.setInput(res.assets.open("$name.xml"), Xml.Encoding.UTF_8.toString()) parser } } catch (e: PackageManager.NameNotFoundException) { } catch (e: IOException) { } catch (e: XmlPullParserException) { } return null } } private operator fun XmlPullParser.get(key: String): String? = this.getAttributeValue(null, key)
gpl-3.0
374142dadcc003947393066c3759615e
42.242268
126
0.584694
5.252974
false
false
false
false
Shashi-Bhushan/General
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/dsbook/methods/backtracking/CoinChange.kt
1
2193
package `in`.shabhushan.cp_trials.dsbook.methods.backtracking object CoinChange { /** * Given a candidates of coins, deduce whether a target amount could be derived * as change of these coins */ fun coinChangePossible( candidates: IntArray, target: Int, currentChange: Int = 0 ): Boolean { if (currentChange == target) return true for (candidate in candidates) { if (currentChange + candidate <= target && coinChangePossible(candidates, target, currentChange + candidate)) return true } return false } /** * Greedily I could find if it's possible to have this target amount in change * But, If i have to find target change amount as minimum number of coins * I could not do this greedily. For, 1, 3, 4, If I greedily choose the largest coin, I would get 4, 1, 1 as possible solution. * But, the solution for this is [3, 3] */ fun coinChangeMinimumCoins( candidates: IntArray, target: Int ): Int { val dp = IntArray(target + 1) { Integer.MAX_VALUE } dp[0] = 0 (1..target).forEach { i -> for(x in candidates) { if (0 <= i - x) dp[i] = Math.min(dp[i], dp[i - x] + 1) } println("Array : ${dp.contentToString()}") } return dp[target] } fun coinChangeTotalCanonicallySimilarWays( candidates: IntArray, target: Int ): Int { val dp = IntArray(target + 1) dp[0] = 1 println("Array : ${dp.contentToString()}") for(candidate in candidates) { (1..target).forEach { current -> if (0 <= current - candidate) dp[current] += dp[current - candidate] } println("Array : ${dp.contentToString()}") } println() return dp[target] } fun coinChangeTotalWays( candidates: IntArray, target: Int ): Int { val dp = IntArray(target + 1) dp[0] = 1 println("Array : ${dp.contentToString()}") (1..target).forEach { current -> for(candidate in candidates) { if (0 <= current - candidate) dp[current] += dp[current - candidate] } println("Array : ${dp.contentToString()}") } println() return dp[target] } }
gpl-2.0
0b9933f26af0c44896211091afd3bfc2
24.206897
129
0.601003
3.860915
false
false
false
false
wasabeef/recyclerview-animators
animators/src/main/java/jp/wasabeef/recyclerview/animators/ScaleInTopAnimator.kt
1
1813
package jp.wasabeef.recyclerview.animators import android.view.animation.Interpolator import androidx.recyclerview.widget.RecyclerView /** * Copyright (C) 2021 Daichi Furiya / Wasabeef * * 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. */ open class ScaleInTopAnimator : BaseItemAnimator { constructor() constructor(interpolator: Interpolator) { this.interpolator = interpolator } override fun preAnimateRemoveImpl(holder: RecyclerView.ViewHolder) { holder.itemView.pivotY = 0f } override fun animateRemoveImpl(holder: RecyclerView.ViewHolder) { holder.itemView.animate().apply { scaleX(0f) scaleY(0f) duration = removeDuration interpolator = interpolator setListener(DefaultRemoveAnimatorListener(holder)) startDelay = getRemoveDelay(holder) }.start() } override fun preAnimateAddImpl(holder: RecyclerView.ViewHolder) { holder.itemView.pivotY = 0f holder.itemView.scaleX = 0f holder.itemView.scaleY = 0f } override fun animateAddImpl(holder: RecyclerView.ViewHolder) { holder.itemView.animate().apply { scaleX(1f) scaleY(1f) duration = addDuration interpolator = interpolator setListener(DefaultAddAnimatorListener(holder)) startDelay = getAddDelay(holder) }.start() } }
apache-2.0
0d244a34d2209b0090ef839cbfa0de1e
30.258621
75
0.732488
4.368675
false
false
false
false
google/horologist
media-ui/src/test/java/com/google/android/horologist/media/ui/state/mapper/DownloadMediaUiModelMapperTest.kt
1
3905
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.state.mapper import com.google.android.horologist.media.model.Media import com.google.android.horologist.media.model.MediaDownload import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import com.google.android.horologist.media.ui.state.model.DownloadMediaUiModel import com.google.common.truth.Truth.assertThat import org.junit.Test class DownloadMediaUiModelMapperTest { @Test fun givenStatusIdle_thenMapsCorrectly() { // given val id = "id" val title = "title" val artist = "artist" val artworkUri = "artworkUri" val mediaDownload = MediaDownload( media = Media( id = id, uri = "", title = title, artist = artist, artworkUri = artworkUri ), status = MediaDownload.Status.Idle, size = MediaDownload.Size.Unknown ) // when val result = DownloadMediaUiModelMapper.map(mediaDownload) // then assertThat(result).isEqualTo( DownloadMediaUiModel.NotDownloaded( id = id, title = title, artist = artist, artworkUri = artworkUri ) ) } @Test fun givenStatusInProgressZeroSizeUnknown_thenMapsCorrectly() { // given val id = "id" val title = "title" val artist = "artist" val artworkUri = "artworkUri" val mediaDownload = MediaDownload( media = Media( id = id, uri = "", title = title, artist = artist, artworkUri = artworkUri ), status = MediaDownload.Status.InProgress(progress = 0F), size = MediaDownload.Size.Unknown ) // when val result = DownloadMediaUiModelMapper.map(mediaDownload) // then assertThat(result).isEqualTo( DownloadMediaUiModel.Downloading( id = id, title = title, artworkUri = artworkUri, progress = DownloadMediaUiModel.Progress.Waiting, size = DownloadMediaUiModel.Size.Unknown ) ) } @Test fun givenStatusCompleted_thenMapsCorrectly() { // given val id = "id" val title = "title" val artist = "artist" val artworkUri = "artworkUri" val mediaDownload = MediaDownload( media = Media( id = id, uri = "", title = title, artist = artist, artworkUri = artworkUri ), status = MediaDownload.Status.Completed, size = MediaDownload.Size.Unknown ) // when val result = DownloadMediaUiModelMapper.map(mediaDownload) // then assertThat(result).isEqualTo( DownloadMediaUiModel.Downloaded( id = id, title = title, artist = artist, artworkUri = artworkUri ) ) } }
apache-2.0
eae879d38a7b8335126afdae5c1ee718
29.271318
78
0.570551
5.097911
false
false
false
false
AerisG222/maw_photos_android
MaWPhotos/src/main/java/us/mikeandwan/photos/ui/controls/photocomment/PhotoCommentViewModel.kt
1
1999
package us.mikeandwan.photos.ui.controls.photocomment import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import us.mikeandwan.photos.domain.ActiveIdRepository import us.mikeandwan.photos.domain.PhotoRepository import us.mikeandwan.photos.domain.models.PhotoComment import us.mikeandwan.photos.domain.models.ExternalCallStatus import javax.inject.Inject @HiltViewModel class PhotoCommentViewModel @Inject constructor ( private val activeIdRepository: ActiveIdRepository, private val photoRepository: PhotoRepository ): ViewModel() { private val _comments = MutableStateFlow(emptyList<PhotoComment>()) val comments = _comments.asStateFlow() fun addComments(comment: String) { viewModelScope.launch { addCommentsInternal(comment) } } private suspend fun addCommentsInternal(comment: String) { val photoId = activeIdRepository.getActivePhotoId().first() if(photoId != null && comment.isNotBlank()) { photoRepository.addComment(photoId, comment) .collect { result -> if(result is ExternalCallStatus.Success) { _comments.value = result.result } } } } init { viewModelScope.launch { activeIdRepository .getActivePhotoId() .filter { it != null } .flatMapLatest { photoRepository.getComments(it!!) } .map { when(it) { is ExternalCallStatus.Loading -> emptyList() is ExternalCallStatus.Error -> emptyList() is ExternalCallStatus.Success -> it.result } } .onEach { _comments.value = it } .launchIn(this) } } }
mit
1216c3bca79cf16a15b275168e22699e
33.482759
71
0.621311
5.138817
false
false
false
false
OurFriendIrony/MediaNotifier
app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/clients/tmdb/movie/search/MovieSearch.kt
1
836
package uk.co.ourfriendirony.medianotifier.clients.tmdb.movie.search import com.fasterxml.jackson.annotation.* @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown = true) @JsonPropertyOrder("page", "total_results", "total_pages", "results") class MovieSearch { @get:JsonProperty("page") @set:JsonProperty("page") @JsonProperty("page") var page: Int? = null @get:JsonProperty("total_results") @set:JsonProperty("total_results") @JsonProperty("total_results") var totalResults: Int? = null @get:JsonProperty("total_pages") @set:JsonProperty("total_pages") @JsonProperty("total_pages") var totalPages: Int? = null @get:JsonProperty("results") @set:JsonProperty("results") @JsonProperty("results") var results: List<MovieSearchResult>? = null }
apache-2.0
a7dba4d2b8e64ecd79cb5dd7bfdd07d7
28.892857
69
0.708134
3.980952
false
false
false
false
jtransc/jtransc
jtransc-core/src/com/jtransc/gen/common/StringPool.kt
2
604
package com.jtransc.gen.common class StringPool { enum class Type { GLOBAL, PER_CLASS } private var lastId = 0 private val stringIds = hashMapOf<String, Int>() private var valid = false private var cachedEntries = listOf<CommonGenerator.StringInPool>() fun alloc(str: String): Int { return stringIds.getOrPut(str) { valid = false lastId++ } } fun getAllSorted(): List<CommonGenerator.StringInPool> { if (!valid) { cachedEntries = stringIds.entries.map { CommonGenerator.StringInPool(it.value, it.key) }.sortedBy { it.id }.toList() valid = true } return cachedEntries } }
apache-2.0
2713d03e2e197d84f14d845395d7fd12
24.208333
119
0.711921
3.355556
false
false
false
false
msebire/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/ActionButtonFixture.kt
3
2343
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.fixtures import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.impl.ActionButton import com.intellij.testGuiFramework.impl.findComponent import org.fest.swing.core.Robot import java.awt.Container class ActionButtonFixture(robot: Robot, target: ActionButton) : JComponentFixture<ActionButtonFixture, ActionButton>( ActionButtonFixture::class.java, robot, target) { companion object { fun actionIdMatcher(actionId: String): (ActionButton) -> Boolean = { val buttonActionId = ActionManager.getInstance().getId(it.action) it.isEnabled && it.isShowing && buttonActionId != null && buttonActionId == actionId } fun actionClassNameMatcher(actionClassName: String): (ActionButton) -> Boolean = { (it.isShowing && it.isEnabled && it.action != null && it.action.javaClass.simpleName == actionClassName) } fun textMatcher(text: String): (ActionButton) -> Boolean = { if (!it.isShowing || !it.isEnabled) false else text == it.action.templatePresentation.text } fun textMatcherAnyState(text: String): (ActionButton) -> Boolean = { if (!it.isShowing) false else text == it.action.templatePresentation.text } fun fixtureByActionId(container: Container?, robot: Robot, actionId: String): ActionButtonFixture = ActionButtonFixture(robot, robot.findComponent(container, ActionButton::class.java, actionIdMatcher(actionId))) fun fixtureByActionClassName(container: Container?, robot: Robot, actionClassName: String): ActionButtonFixture = ActionButtonFixture(robot, robot.findComponent(container, ActionButton::class.java, actionClassNameMatcher(actionClassName))) fun fixtureByText(container: Container?, robot: Robot, text: String): ActionButtonFixture = ActionButtonFixture(robot, robot.findComponent(container, ActionButton::class.java, textMatcher(text))) fun fixtureByTextAnyState(container: Container?, robot: Robot, text: String): ActionButtonFixture = ActionButtonFixture(robot, robot.findComponent(container, ActionButton::class.java, textMatcherAnyState(text))) } }
apache-2.0
e2a9173c558df2b4b3d5d535e14088e5
45.86
140
0.746479
4.762195
false
false
false
false
dexbleeker/hamersapp
hamersapp/src/main/java/nl/ecci/hamers/ui/activities/MainActivity.kt
1
5632
package nl.ecci.hamers.ui.activities import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatDelegate import androidx.core.view.GravityCompat import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentTransaction import com.bumptech.glide.Glide import kotlinx.android.synthetic.main.element_header.view.* import kotlinx.android.synthetic.main.element_toolbar.* import kotlinx.android.synthetic.main.main.* import nl.ecci.hamers.R import nl.ecci.hamers.data.GetCallback import nl.ecci.hamers.data.Loader import nl.ecci.hamers.ui.fragments.* import nl.ecci.hamers.utils.DataUtils import nl.ecci.hamers.utils.DataUtils.getGravatarURL import nl.ecci.hamers.utils.Utils import java.text.SimpleDateFormat import java.util.* class MainActivity : HamersActivity() { private var backPressedOnce: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) initDrawer() initToolbar() if (savedInstanceState == null) { selectItem(this, navigation_view.menu.getItem(0)) val night_mode = prefs?.getString("night_mode", "off") AppCompatDelegate.setDefaultNightMode(getNightModeInt(night_mode.toString())) recreate() } DataUtils.hasApiKey(this, prefs) fillHeader() } private fun initDrawer() { navigation_view?.setNavigationItemSelectedListener { menuItem -> selectItem(this@MainActivity, menuItem) menuItem.isChecked = true drawer_layout!!.closeDrawers() Utils.hideKeyboard(parent) true } } override fun initToolbar() { super.initToolbar() val mDrawerToggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.drawer_open, R.string.drawer_close ) drawer_layout.addDrawerListener(mDrawerToggle) mDrawerToggle.syncState() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { drawer_layout.openDrawer(GravityCompat.START) return true } } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (backPressedOnce) { super.onBackPressed() return } this.backPressedOnce = true Utils.showToast(this, getString(R.string.press_back_again), Toast.LENGTH_SHORT) Handler().postDelayed({ backPressedOnce = false }, 2000) } private fun fillHeader() { val user = DataUtils.getOwnUser(this) if (user.id != Utils.notFound) { val headerView = LayoutInflater.from(this).inflate(R.layout.element_header, navigation_view, false) navigation_view.addHeaderView(headerView) headerView.header_user_name.text = user.name headerView.header_user_email.text = user.email // Image Glide.with(applicationContext).load(getGravatarURL(user.email)).into(headerView.header_user_image) } else { Loader.getData(this, Loader.WHOAMIURL, -1, object : GetCallback { override fun onSuccess(response: String) { fillHeader() } }, null) } } companion object { val locale = Locale("nl") val dbDF = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", locale) val appDF = SimpleDateFormat("EEE dd MMM yyyy HH:mm", locale) val appDTF = SimpleDateFormat("EEEE dd MMMM yyyy", locale) private const val PLAY_SERVICES_RESOLUTION_REQUEST = 9000 @AppCompatDelegate.NightMode fun getNightModeInt(nightMode: String): Int { return when (nightMode) { "auto" -> AppCompatDelegate.MODE_NIGHT_AUTO "on" -> AppCompatDelegate.MODE_NIGHT_YES else -> AppCompatDelegate.MODE_NIGHT_NO } } /** * Swaps fragments in the main content view * This method is static to allow for usage in ChangeFragment */ fun selectItem(activity: HamersActivity, menuItem: MenuItem) { val fragmentClass: Class<*> = when (menuItem.itemId) { R.id.navigation_item_events -> EventFragment::class.java R.id.navigation_item_beers -> BeerFragment::class.java R.id.navigation_item_news -> NewsFragment::class.java R.id.navigation_item_users -> UserFragment::class.java R.id.navigation_item_meetings -> MeetingFragment::class.java R.id.navigation_item_stickers -> StickerFragment::class.java R.id.navigation_item_settings -> SettingsFragment::class.java R.id.navigation_item_changes -> ChangeFragment::class.java R.id.navigation_item_about -> AboutFragment::class.java else -> QuoteFragment::class.java } val fragment = fragmentClass.newInstance() as Fragment val transaction = activity.supportFragmentManager.beginTransaction() transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN) transaction.replace(R.id.content_frame, fragment).commit() } } }
gpl-3.0
b01d472f9841e5095ef87c7d39359179
35.335484
111
0.637607
4.693333
false
false
false
false
hschroedl/FluentAST
core/src/main/kotlin/at.hschroedl.fluentast/Fluentast.kt
1
8670
package at.hschroedl.fluentast import at.hschroedl.fluentast.ast.FluentMemberValuePair import at.hschroedl.fluentast.ast.FluentVariableDeclarationFragment import at.hschroedl.fluentast.ast.FluentVariableDeclarationFragmentImpl import at.hschroedl.fluentast.ast.expression.* import at.hschroedl.fluentast.ast.statement.* import at.hschroedl.fluentast.ast.type.FluentArrayType import at.hschroedl.fluentast.ast.type.FluentPrimitiveType import at.hschroedl.fluentast.ast.type.FluentSimpleType import at.hschroedl.fluentast.ast.type.FluentType import org.eclipse.jdt.core.dom.* import org.eclipse.jdt.core.dom.IfStatement import org.eclipse.jdt.core.dom.InfixExpression import org.eclipse.jdt.core.dom.ReturnStatement fun annotation(name: String): FluentMarkerAnnotation { return FluentMarkerAnnotation(name) } fun annotation(name: String, expression: FluentExpression): FluentSingleMemberAnnotation { return FluentSingleMemberAnnotation(name, expression) } fun annotation(name: String, vararg members: FluentMemberValuePair): FluentNormalAnnotation { return FluentNormalAnnotation(name, *members) } fun b(value: Boolean): FluentBooleanLiteral { return FluentBooleanLiteral(value) } fun c(value: Char): FluentCharacterLiteral { return FluentCharacterLiteral(value) } fun i(value: Int): FluentNumberLiteral { return FluentNumberLiteral(value) } fun s(literal: String): FluentStringLiteral { return FluentStringLiteral(literal) } fun ternary(condition: FluentExpression, then: FluentExpression, `else`: FluentExpression): FluentConditionalExpression { return FluentConditionalExpression(condition, then, `else`) } fun instanceof(left: FluentExpression, right: FluentType): FluentInstanceOfExpression { return FluentInstanceOfExpression(left, right) } fun invocation(name: String): FluentMethodInvocation { return FluentMethodInvocation(name = name) } fun invocation(expression: FluentExpression, typeParameter: List<FluentType>, name: String, vararg arguments: FluentExpression): FluentMethodInvocation { return FluentMethodInvocation(expression, typeParameter, name, *arguments) } fun n(name: String): FluentName { return FluentName(name) } fun fragment(name: String): FluentVariableDeclarationFragmentImpl { return FluentVariableDeclarationFragmentImpl(name) } fun fragment(name: String, initializer: FluentExpression): FluentVariableDeclarationFragmentImpl { return FluentVariableDeclarationFragmentImpl(name, initializer = initializer) } fun p(type: String): FluentPrimitiveType { return FluentPrimitiveType(type) } fun name(name: String): FluentName { return FluentName(name) } fun null_(): FluentNullLiteral { return FluentNullLiteral() } fun stmnt(content: String): FluentStatement { return FluentParsedStatement(content) } fun t(name: String): FluentType { return FluentSimpleType(name) } fun pair(name: String, value: FluentExpression): FluentMemberValuePair { return FluentMemberValuePair(name, value) } fun break_(): FluentStatement { return FluentBreakStatement() } fun return_(): FluentStatement { return FluentReturnStatement(null) } fun return_(expression: FluentExpression): FluentReturnStatement { return FluentReturnStatement(expression) } fun empty(): FluentStatement { return FluentEmptyStatement() } fun exp(content: String): FluentExpression { return FluentParsedExpression(content) } fun paranthesis(expression: FluentExpression): FluentParenthesizedExpression { return FluentParenthesizedExpression(expression) } fun superField(field: String): FluentSuperFieldAccess { return FluentSuperFieldAccess(null, field) } fun superField(className: String, field: String): FluentSuperFieldAccess { return FluentSuperFieldAccess(className, field) } fun superMethod(name: String): FluentSuperMethodInvocation { return FluentSuperMethodInvocation(name = name) } fun superMethod(qualifier: String, typeParameter: List<FluentType>, name: String, vararg arguments: FluentExpression): FluentSuperMethodInvocation { return FluentSuperMethodInvocation(qualifier, typeParameter, name, *arguments) } fun decl(name: String, initializer: Int): FluentVariableDeclarationExpression { return FluentVariableDeclarationExpression(p("int"), FluentVariableDeclarationFragmentImpl( name, initializer = i(initializer))) } fun decl(name: String, initializer: Boolean): FluentVariableDeclarationExpression { return FluentVariableDeclarationExpression(p("boolean"), FluentVariableDeclarationFragmentImpl( name, initializer = b(initializer))) } fun decl(name: String, initializer: Char): FluentVariableDeclarationExpression { return FluentVariableDeclarationExpression(p("char"), FluentVariableDeclarationFragmentImpl( name, initializer = c(initializer))) } fun decl(type: FluentType, initializer: String): FluentExpression { return FluentVariableDeclarationExpression(type, FluentVariableDeclarationFragmentImpl( initializer, initializer = null)) } fun decl(type: FluentType, vararg fragment: FluentVariableDeclarationFragment): FluentVariableDeclarationExpression { return FluentVariableDeclarationExpression(type, *fragment) } fun infix(operator: String): FluentInfixOperatorPartial { return FluentInfixOperatorPartial(operator) } fun this_(): FluentThisExpression { return FluentThisExpression() } fun this_(qualifier: String): FluentThisExpression { return FluentThisExpression(qualifier) } fun clazz(type: FluentType): FluentTypeLiteral { return FluentTypeLiteral(type) } fun newArray(type: FluentArrayType, initializer: FluentArrayInitializer?): FluentArrayCreation { return FluentArrayCreation(type, initializer) } fun newArray(type: FluentArrayType): FluentArrayCreation { return FluentArrayCreation(type, null) } fun arrayInit(vararg expression: FluentExpression): FluentArrayInitializer { return FluentArrayInitializer(*expression) } fun assignment(left: FluentExpression, operator: String, right: FluentExpression): FluentAssignment { return FluentAssignment(left, operator, right) } fun assert(expression: FluentExpression): FluentAssertStatement { return FluentAssertStatement(expression) } fun assert(expression: FluentExpression, message: FluentExpression): FluentAssertStatement { return FluentAssertStatement(expression, message) } fun body(): FluentBlock { return FluentStatementBlock() } fun body(vararg statements: FluentStatement): FluentBlock { return FluentStatementBlock(arrayOf(*statements)) } fun body(content: String): FluentBlock { return FluentParsedBlock(content) } fun block(): FluentBlock { return FluentStatementBlock() } fun block(vararg statements: FluentStatement): FluentBlock { return FluentStatementBlock(arrayOf(*statements)) } fun stmnt(expression: FluentExpression): FluentExpressionStatement { return FluentExpressionStatement(expression) } fun if_(condition: FluentExpression): FluentIfPartial { return FluentIfPartial(condition) } fun for_(): FluentForStatement.ForPartial { return FluentForStatement.ForPartial(mutableListOf(), null, mutableListOf()) } fun for_(init: FluentExpression, expression: FluentExpression?, update: FluentExpression): FluentForStatement.ForPartial { return FluentForStatement.ForPartial(mutableListOf(init), expression, mutableListOf(update)) } fun while_(condition: FluentExpression): FluentWhileStatement.DoPartial { return FluentWhileStatement.DoPartial(condition) } fun cast(type: FluentType, expression: FluentExpression): FluentCastExpression { return FluentCastExpression(type, expression) } fun postfix(operator: String): FluentPostfixExpression.PostfixPartial { return FluentPostfixExpression.PostfixPartial(operator) } fun prefix(operator: String, expression: FluentExpression): FluentPrefixExpression { return FluentPrefixExpression(operator, expression) }
apache-2.0
f28cfad9f79715c6bf1de5ca15caf17f
29.748227
99
0.730565
4.937358
false
false
false
false
SerCeMan/intellij-community
platform/configuration-store-impl/testSrc/MockStreamProvider.kt
5
1423
package com.intellij.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.impl.stores.StreamProvider import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SmartList import java.io.File import java.io.FileInputStream import java.io.InputStream class MockStreamProvider(private val myBaseDir: File) : StreamProvider { override fun isApplicable(fileSpec: String, roamingType: RoamingType) = roamingType === RoamingType.PER_USER override fun saveContent(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { FileUtil.writeToFile(File(myBaseDir, fileSpec), content, 0, size) } override fun loadContent(fileSpec: String, roamingType: RoamingType): InputStream? { val file = File(myBaseDir, fileSpec) //noinspection IOResourceOpenedButNotSafelyClosed return if (file.exists()) FileInputStream(file) else null } override fun listSubFiles(fileSpec: String, roamingType: RoamingType): Collection<String> { if (roamingType !== RoamingType.PER_USER) { return emptyList() } val files = File(myBaseDir, fileSpec).listFiles() ?: return emptyList() val names = SmartList<String>() for (file in files) { names.add(file.getName()) } return names } override fun delete(fileSpec: String, roamingType: RoamingType) { FileUtil.delete(File(myBaseDir, fileSpec)) } }
apache-2.0
428fe8c78d0a9147991f8850e12cfc86
34.575
110
0.752635
4.391975
false
false
false
false
krischik/Fit-Import
app/src/androidTest/kotlin/com.krischik/fit_import/GoogleFit_Test.kt
1
6468
/********************************************************** {{{1 *********** * Copyright © 2015 … 2016 "Martin Krischik" «[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/ ********************************************************** }}}1 **********/ package com.krischik.fit_import import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.IsEqual.equalTo /** * Created by krma1 on 08.12.15. * @author "Martin Krischik" «[email protected]» * @version 1.0 * @since 1.0 */ public class GoogleFit_Test : android.test.ActivityInstrumentationTestCase2<MainActivity_>(MainActivity_::class.java) { /** * Logging tag */ private val TAG = com.krischik.Log.getLogTag(GoogleFit_Test::class.java); /** * Randim number generator */ private val Random = java.util.Random (java.util.Date ().time) /** * Test opening the main activity (smoke test / release compatible version) */ @android.test.suitebuilder.annotation.Smoke @android.test.suitebuilder.annotation.SmallTest @hugo.weaving.DebugLog public fun test_00_Insert_Weight() { com.krischik.Log.d (TAG, "+ test_00_Insert_Weight") com.krischik.test.Utilities.asyncAssertTrue ( message = { "Application should connect to Google Fit" }, condition = { activity?.isConnected ?: false }, timeout = com.krischik.test.Utilities.seconds(30.0f)) val weight = 80.0f + (Random.nextFloat() * 20.0f - 10.0f) val fat = 20.0f + (Random.nextFloat() * 10.0f - 5.0f) val withings = com.krischik.fit_import.Withings ( /* Time => */java.util.Date (), /* weight => */weight, /* Fat => */fat, /* No_Fat => */weight - fat, /* Comment => */"test_00_Insert_Weight") val Google_Fit = activity?.googleFit Google_Fit?.insertWeight (withings) com.krischik.Log.d (TAG, "- test_00_Insert_Weight") } // test_00_Insert_Weight /** * Test opening the main activity (smoke test / release compatible version) */ @android.test.suitebuilder.annotation.Smoke @android.test.suitebuilder.annotation.SmallTest @hugo.weaving.DebugLog public fun test_01_Insert_Training() { com.krischik.Log.d (TAG, "+ test_01_Insert_Training") com.krischik.test.Utilities.asyncAssertTrue ( message = { "Application should connect to Google Fit" }, condition = { activity?.isConnected ?: false }, timeout = com.krischik.test.Utilities.seconds(30.0f)) val puls = 140 + (Random.nextInt (20) - 10) val watt = 160 + (Random.nextInt (20) - 10) val uMin = 70 + (Random.nextInt (20) - 10) val kCal = 500 + (Random.nextInt (100) - 50) val km = 6 + (Random.nextInt (3) - 2) val end = java.util.Date () val start = java.util.Date (end.time - com.krischik.test.Utilities.minutes(30.0f)) val ketfit = Ketfit ( /* start => */start, /* end => */end, /* Watt => */watt, /* puls => */puls, /* Umin => */uMin, /* kCal => */kCal, /* km => */km, /* ω => */0) val Google_Fit = activity?.googleFit Google_Fit?.insertTraining (ketfit); com.krischik.Log.d (TAG, "- test_01_Insert_Training") } // test_01_Insert_Training /** * Test opening the main activity (smoke test / release compatible version) */ @android.test.suitebuilder.annotation.Smoke @android.test.suitebuilder.annotation.SmallTest @hugo.weaving.DebugLog public fun test_02_Insert_Weights() { com.krischik.Log.d (TAG, "+ test_02_Insert_Weights") com.krischik.test.Utilities.asyncAssertTrue ( message = { "Application should connect to Google Fit" }, condition = { activity?.isConnected ?: false }, timeout = com.krischik.test.Utilities.seconds(30.0f)) val Google_Fit = activity?.googleFit val testData = GoogleFit_Test::class.java.getResourceAsStream("/Withings.csv") val test = ReadWithings (testData) var recordCount = 0; Read_Lines@ while (true) { val testRecord = test.read() if (testRecord == null) break@Read_Lines recordCount = recordCount + 1; com.krischik.Log.v (TAG, "Read Record %1\$d: %2\$s", recordCount, testRecord) Google_Fit?.insertWeight (testRecord) } // when assertThat(recordCount, equalTo(11)) test.close () com.krischik.Log.d (TAG, "- test_02_Insert_Weights") } // test_02_Insert_Weights /** * Test opening the main activity (smoke test / release compatible version) */ @android.test.suitebuilder.annotation.Smoke @android.test.suitebuilder.annotation.SmallTest @hugo.weaving.DebugLog public fun test_03_Insert_Trainings() { com.krischik.Log.d (TAG, "+ test_03_Insert_Trainings") com.krischik.test.Utilities.asyncAssertTrue ( message = { "Application should connect to Google Fit" }, condition = { activity?.isConnected ?: false }, timeout = com.krischik.test.Utilities.seconds(30.0f)) val Google_Fit = activity?.googleFit val testData = GoogleFit_Test::class.java.getResourceAsStream("/ketfit.csv") val test = ReadKetfit (testData) var recordCount = 0; Read_Lines@ while (true) { val testRecord = test.read() if (testRecord == null) break@Read_Lines recordCount = recordCount + 1; com.krischik.Log.v (TAG, "Read Record %1\$d: %2\$s", recordCount, testRecord) Google_Fit?.insertTraining (testRecord); } // when assertThat(recordCount, equalTo(16)) test.close () com.krischik.Log.d (TAG, "- test_02_Insert_Trainings") } // test_00_Insert_Weight } // GoogleFIT_Test // vim: set nowrap tabstop=8 shiftwidth=3 softtabstop=3 expandtab textwidth=96 : // vim: set fileencoding=utf-8 filetype=kotlin foldmethod=syntax spell spelllang=en_gb :
gpl-3.0
8eb893d06733f6f71f128a0e26bdde8e
33.918919
90
0.640402
3.557269
false
true
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/VideoPlayer.kt
1
3957
/**************************************************************************************** * Copyright (c) 2014 Timothy Rae <[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 com.ichi2.anki import android.app.Activity import android.content.res.Configuration import android.media.MediaPlayer import android.os.Bundle import android.view.SurfaceHolder import android.view.WindowManager.LayoutParams import android.widget.VideoView import com.ichi2.anki.UIUtils.showThemedToast import com.ichi2.libanki.Sound import com.ichi2.themes.Themes import timber.log.Timber class VideoPlayer : Activity(), SurfaceHolder.Callback { private lateinit var mVideoView: VideoView private val mSoundPlayer: Sound = Sound() private var mPath: String? = null /** Called when the activity is first created. */ @Suppress("DEPRECATION") // #9332: UI Visibility -> Insets override fun onCreate(savedInstanceState: Bundle?) { Timber.i("onCreate") super.onCreate(savedInstanceState) Themes.disableXiaomiForceDarkMode(this) setContentView(R.layout.video_player) mPath = intent.getStringExtra("path") Timber.i("Video Player intent had path: %s", mPath) window.setFlags( LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN ) window.addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON) mVideoView = findViewById(R.id.video_surface) mVideoView.holder.addCallback(this) } override fun surfaceCreated(holder: SurfaceHolder) { Timber.i("surfaceCreated") if (mPath == null) { // #5911 - path shouldn't be null. I couldn't determine why this happens. CrashReportService.sendExceptionReport("Video: mPath was unexpectedly null", "VideoPlayer surfaceCreated") Timber.e("path was unexpectedly null") showThemedToast(this, getString(R.string.video_creation_error), true) finish() return } mSoundPlayer.playSound(mPath!!, { mp: MediaPlayer? -> finish() val originalListener = Sound.mediaCompletionListener originalListener?.onCompletion(mp) }, mVideoView, null) } override fun surfaceChanged( holder: SurfaceHolder, format: Int, width: Int, height: Int ) { // TODO Auto-generated method stub } override fun surfaceDestroyed(holder: SurfaceHolder) { mSoundPlayer.stopSounds() finish() } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) mSoundPlayer.notifyConfigurationChanged(mVideoView) } public override fun onStop() { super.onStop() } }
gpl-3.0
c6268a2424d9f18460887294683d3faf
41.095745
118
0.578469
5.297189
false
true
false
false
infinum/android_dbinspector
dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/databases/remove/RemoveDatabaseDialog.kt
1
2967
package com.infinum.dbinspector.ui.databases.remove import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.fragment.app.setFragmentResult import com.infinum.dbinspector.R import com.infinum.dbinspector.databinding.DbinspectorDialogRemoveDatabaseBinding import com.infinum.dbinspector.domain.database.models.DatabaseDescriptor import com.infinum.dbinspector.ui.Presentation.Constants.Keys.REMOVE_DATABASE import com.infinum.dbinspector.ui.Presentation.Constants.Keys.REMOVE_DATABASE_DESCRIPTOR import com.infinum.dbinspector.ui.Presentation.Constants.Keys.SHOULD_REFRESH import com.infinum.dbinspector.ui.shared.base.BaseActivity import com.infinum.dbinspector.ui.shared.base.BaseBottomSheetDialogFragment import com.infinum.dbinspector.ui.shared.delegates.viewBinding import getParcelableCompat import org.koin.androidx.viewmodel.ext.android.viewModel internal class RemoveDatabaseDialog : BaseBottomSheetDialogFragment<RemoveDatabaseState, Any>(R.layout.dbinspector_dialog_remove_database) { companion object { fun withDatabaseDescriptor(database: DatabaseDescriptor): RemoveDatabaseDialog { val fragment = RemoveDatabaseDialog() fragment.arguments = Bundle().apply { putParcelable(REMOVE_DATABASE_DESCRIPTOR, database) } return fragment } } override val binding: DbinspectorDialogRemoveDatabaseBinding by viewBinding( DbinspectorDialogRemoveDatabaseBinding::bind ) override val viewModel: RemoveDatabaseViewModel by viewModel() private var database: DatabaseDescriptor? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) database = arguments?.getParcelableCompat( REMOVE_DATABASE_DESCRIPTOR, DatabaseDescriptor::class.java ) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding) { toolbar.setNavigationOnClickListener { dismiss() } messageView.text = String.format( getString(R.string.dbinspector_delete_database_confirm), database?.name.orEmpty() ) removeButton.setOnClickListener { view -> database?.let { viewModel.remove(view.context, it) } ?: (activity as? BaseActivity<*, *>)?.showDatabaseParametersError() } } } override fun onState(state: RemoveDatabaseState) = when (state) { is RemoveDatabaseState.Removed -> { setFragmentResult( REMOVE_DATABASE, bundleOf( SHOULD_REFRESH to state.success ) ) dismiss() } } override fun onEvent(event: Any) = Unit }
apache-2.0
c633c7760f3f44a396338cb6254578fa
36.0875
106
0.682845
5.242049
false
false
false
false
matkoniecz/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/map/Compass.kt
1
5905
package de.westnordost.streetcomplete.map import android.hardware.* import android.location.Location import android.os.Handler import android.os.HandlerThread import android.view.Display import android.view.Surface import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import java.lang.Math.toRadians import kotlin.math.PI import kotlin.math.abs /** Component that gets the sensor data from accelerometer and magnetic field, smoothens it out and * makes callbacks to report a simple rotation to its parent. */ class Compass( private val sensorManager: SensorManager, private val display: Display, private val callback: (rotation: Float, tilt: Float) -> Unit ) : SensorEventListener, LifecycleObserver { private val accelerometer: Sensor? private val magnetometer: Sensor? private val sensorThread: HandlerThread private val sensorHandler: Handler private var gravity: FloatArray? = null private var geomagnetic: FloatArray? = null private var declination = 0f private var rotation = 0f private var tilt = 0f private var dispatcherThread: Thread? = null init { accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) sensorThread = HandlerThread("Compass Sensor Thread") sensorThread.start() sensorHandler = Handler(sensorThread.looper) } private fun remapToDisplayRotation(r: FloatArray) { val h: Int val v: Int when (display.rotation) { Surface.ROTATION_90 -> { h = SensorManager.AXIS_Y v = SensorManager.AXIS_MINUS_X } Surface.ROTATION_180 -> { h = SensorManager.AXIS_MINUS_X v = SensorManager.AXIS_MINUS_Y } Surface.ROTATION_270 -> { h = SensorManager.AXIS_MINUS_Y v = SensorManager.AXIS_X } Surface.ROTATION_0 -> { h = SensorManager.AXIS_X v = SensorManager.AXIS_Y } else -> return } SensorManager.remapCoordinateSystem(r, h, v, r) } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { accelerometer?.let { sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI, sensorHandler) } magnetometer?.let { sensorManager.registerListener(this, it, SensorManager.SENSOR_DELAY_UI, sensorHandler) } dispatcherThread = Thread( { dispatchLoop() }, "Compass Dispatcher Thread") dispatcherThread?.start() } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun onPause() { sensorManager.unregisterListener(this) dispatcherThread?.interrupt() dispatcherThread = null } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { sensorHandler.removeCallbacksAndMessages(null) sensorThread.quit() } override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {} override fun onSensorChanged(event: SensorEvent) { if (event.sensor.type == Sensor.TYPE_MAGNETIC_FIELD) { geomagnetic = event.values.copyOf() } else if (event.sensor.type == Sensor.TYPE_ACCELEROMETER) { gravity = event.values.copyOf() } val grav = gravity ?: return val geomag = geomagnetic ?: return val R = FloatArray(9) val I = FloatArray(9) val success = SensorManager.getRotationMatrix(R, I, grav, geomag) if (success) { remapToDisplayRotation(R) val orientation = FloatArray(3) SensorManager.getOrientation(R, orientation) val azimuth = orientation[0] + declination val pitch = orientation[1] val roll = orientation[2] rotation = azimuth tilt = pitch } /* reset to null. We want to do the recalculation of rotation and tilt only if the result from *both* sensors arrived each */ gravity = null geomagnetic = null } private fun dispatchLoop() { var first = true var lastTilt = 0f var lastRotation = 0f var t = 0f var r = 0f while (!Thread.interrupted()) { try { Thread.sleep(1000 / MAX_DISPATCH_FPS.toLong()) } catch (e: InterruptedException) { return } if (first && (rotation != 0f || tilt != 0f)) { r = rotation t = tilt first = false } else { r = smoothenAngle(rotation, r, SMOOTHEN_FACTOR) t = smoothenAngle(tilt, t, SMOOTHEN_FACTOR) } if (abs(lastTilt - t) > MIN_DIFFERENCE || abs(lastRotation - r) > MIN_DIFFERENCE) { callback(r, t) lastTilt = t lastRotation = r } } } fun setLocation(location: Location) { val geomagneticField = GeomagneticField( location.latitude.toFloat(), location.longitude.toFloat(), location.altitude.toFloat(), System.currentTimeMillis() ) declination = toRadians(geomagneticField.declination.toDouble()).toFloat() } private fun smoothenAngle( newValue: Float, oldValue: Float, factor: Float): Float { var delta = newValue - oldValue while (delta > +PI) delta -= 2 * PI.toFloat() while (delta < -PI) delta += 2 * PI.toFloat() return oldValue + factor * delta } companion object { private const val MAX_DISPATCH_FPS = 30 private const val SMOOTHEN_FACTOR = 0.1f private const val MIN_DIFFERENCE = 0.001f } }
gpl-3.0
ec8d1801002b4222bb8cb6053043245d
32.551136
117
0.611177
4.620501
false
false
false
false
pdvrieze/ProcessManager
ProcessEngine/core/src/jvmMain/kotlin/nl/adaptivity/process/engine/ProcessDataExt.kt
1
1741
/* * Copyright (c) 2019. * * 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 import nl.adaptivity.util.DomUtil import org.w3c.dom.DocumentFragment import org.w3c.dom.Node import org.w3c.dom.NodeList actual val ProcessData.contentFragment: DocumentFragment get() = DomUtil.childrenToDocumentFragment(contentStream) @Suppress("DEPRECATION", "FunctionName") @Deprecated("") fun ProcessData(name: String, nodeList: NodeList?) = ProcessData(name, node = (if (nodeList == null || nodeList.length <= 1) toNode(nodeList) else DomUtil.toDocFragment(nodeList))) @Suppress("FunctionName") @Deprecated("Use compactFragments directly", ReplaceWith("ProcessData(name, DomUtil.nodeToFragment(node))", "nl.adaptivity.process.engine.ProcessData", "nl.adaptivity.util.DomUtil")) fun ProcessData(name: String, node: Node?) = ProcessData(name, DomUtil.nodeToFragment(node)) private fun toNode(value: NodeList?): Node? { if (value == null || value.length == 0) { return null } assert(value.length == 1) return value.item(0) }
lgpl-3.0
9b011308c9b81e008c59f4fa1f001025
39.488372
131
0.723722
4.106132
false
false
false
false
akvo/akvo-flow-mobile
app/src/main/java/org/akvo/flow/service/bootstrap/ZipFileLister.kt
1
2080
/* * Copyright (C) 2021 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow 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. * * Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.service.bootstrap import android.os.Environment import org.akvo.flow.util.FileUtil import java.io.File import java.util.ArrayList import java.util.Locale import javax.inject.Inject class ZipFileLister @Inject constructor() { /** * returns an ordered list of zip files that exist in the device's bootstrap * directory */ fun listSortedZipFiles(): List<File> { val zipFiles = listZipFiles() if (zipFiles.isNotEmpty()) { zipFiles.sort() } return zipFiles } fun listZipFiles(): MutableList<File> { val zipFiles: MutableList<File> = ArrayList() if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) { val dir = FileUtil.getFilesDir(FileUtil.FileType.INBOX) val fileList = dir.listFiles() if (fileList != null) { for (file in fileList) { if (isZipFile(file)) { zipFiles.add(file) } } } } return zipFiles } private fun isZipFile(file: File): Boolean { return file.isFile && file.name.lowercase(Locale.getDefault()).endsWith(ARCHIVE_SUFFIX) } companion object { const val ARCHIVE_SUFFIX = ".zip" } }
gpl-3.0
d495c7bfeaba0a7bdf7d36e4fe696b05
30.530303
95
0.6375
4.388186
false
false
false
false
andrei-heidelbacher/algoventure-core
src/main/kotlin/com/aheidelbacher/algoventure/core/act/ActingSystem.kt
1
3237
/* * Copyright 2016 Andrei Heidelbacher <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aheidelbacher.algoventure.core.act import com.aheidelbacher.algostorm.event.Event import com.aheidelbacher.algostorm.event.Publisher import com.aheidelbacher.algostorm.event.Subscribe import com.aheidelbacher.algostorm.event.Subscriber import com.aheidelbacher.algostorm.state.Layer.ObjectGroup import com.aheidelbacher.algostorm.state.Object import com.aheidelbacher.algostorm.systems.script.ScriptingSystem.RunScriptWithResult class ActingSystem( private val objectGroup: ObjectGroup, private val publisher: Publisher ) : Subscriber { companion object { const val ACTOR_SCRIPT: String = "actorScript" const val SPEED: String = "speed" const val STAMINA: String = "stamina" val Object.isActor: Boolean get() = contains(ACTOR_SCRIPT) && contains(SPEED) && contains(STAMINA) val Object.actorScript: String get() = getString(ACTOR_SCRIPT) ?: error("Object $id must contain $ACTOR_SCRIPT property!") val Object.speed: Int get() = getInt(SPEED) ?: error("Object $id must contain $SPEED property!") val Object.stamina: Int get() = getInt(STAMINA) ?: error("Object $id must contain $STAMINA property!") fun Object.addStamina(stamina: Int) { set(STAMINA, this.stamina + stamina) } } object NewAct : Event @Subscribe fun onActionCompleted(event: ActionCompleted) { objectGroup[event.objectId]?.let { it.addStamina(-event.usedStamina) } publisher.post(NewAct) } @Subscribe fun onNewAct(event: NewAct) { objectGroup.objectSet.filter { it.isActor }.maxBy { it.stamina }?.let { obj -> if (obj.stamina < 0) { publisher.post(NewTurn) objectGroup.objectSet.filter { it.isActor }.forEach { it.addStamina(it.speed) } } else { publisher.publish(RunScriptWithResult( obj.actorScript, Action::class, objectGroup, obj.id ) { action -> if (action is Action? && action != null) { require(action.objectId == obj.id) { "Actor id ${action.objectId} should be ${obj.id}!" } publisher.post(action) } }) } } } }
apache-2.0
f26c056d1d6665cba8b0a1e395f08cb1
34.966667
85
0.595613
4.630901
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/feed/FeedManager.kt
1
4852
package com.pr0gramm.app.feed import com.pr0gramm.app.Logger import com.pr0gramm.app.api.pr0gramm.Api import com.pr0gramm.app.util.trace import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch class FeedManager(private val scope: CoroutineScope, private val feedService: FeedService, private var feed: Feed) { private val logger = Logger("FeedService") private val subject = BroadcastChannel<Update>(8) private var job: Job? = null /** * True, if this feed manager is currently performing a load operation. */ val isLoading: Boolean get() = job?.isActive == true private val feedType: FeedType get() = feed.feedType val updates: Flow<Update> get() = subject.asFlow().onStart { emit(Update.NewFeed(feed)) } init { trace { "<init>(${feed.filter}" } } /** * Stops all loading operations and resets the feed to the given value. */ fun reset(feed: Feed = this.feed.copy(items = listOf(), isAtStart = false, isAtEnd = false)) { trace { "reset(${feed.filter})" } publish(feed, remote = false) } /** * Resets the current feed and loads all items around the given offset. * Leave 'around' null to just load from the beginning. */ fun restart(around: Long? = null) { trace { "reload(${feed.filter})" } load { publish(Update.LoadingStarted(LoadingSpace.NEXT)) feedService.load(feedQuery().copy(around = around)) } } /** * Load the next page of the feed */ fun next() { val oldest = feed.oldestNonPlaceholderItem if (feed.isAtEnd || isLoading || oldest == null) return load { publish(Update.LoadingStarted(LoadingSpace.NEXT)) feedService.load(feedQuery().copy(older = oldest.id(feedType))) } } /** * Load the previous page of the feed */ fun previous() { val newest = feed.newestNonPlaceholderItem if (feed.isAtStart || isLoading || newest == null) return load { publish(Update.LoadingStarted(LoadingSpace.PREV)) feedService.load(feedQuery().copy(newer = newest.id(feedType))) } } fun stop() { trace { "stop()" } job?.cancel() } private fun load(block: suspend () -> Api.Feed) { stop() logger.debug { "Start new load request now." } job = scope.launch { try { val update = try { block() } catch (_: CancellationException) { return@launch } // loading finished publish(Update.LoadingStopped) handleFeedUpdate(update) } catch (err: Throwable) { publish(Update.LoadingStopped) publishError(err) } } } private fun handleFeedUpdate(update: Api.Feed) { // check for invalid content type. update.error?.let { error -> publishError(when (error) { "notPublic" -> FeedException.NotPublicException() "notFound" -> FeedException.NotFoundException() "sfwRequired" -> FeedException.InvalidContentTypeException(ContentType.SFW) "nsfwRequired" -> FeedException.InvalidContentTypeException(ContentType.NSFW) "nsflRequired" -> FeedException.InvalidContentTypeException(ContentType.NSFL) else -> FeedException.GeneralFeedException(error) }) return } val merged = feed.mergeWith(update) publish(merged, remote = true) } /** * Update and publish a new feed. */ private fun publish(newFeed: Feed, remote: Boolean) { feed = newFeed publish(Update.NewFeed(newFeed, remote)) } private fun publishError(err: Throwable) { subject.trySend(Update.Error(err)).isSuccess } private fun publish(update: Update) { subject.trySend(update).isSuccess } private fun feedQuery(): FeedService.FeedQuery { return FeedService.FeedQuery(feed.filter, feed.contentType) } sealed class Update { object LoadingStopped : Update() data class LoadingStarted(val where: LoadingSpace = LoadingSpace.NEXT) : Update() data class Error(val err: Throwable) : Update() data class NewFeed(val feed: Feed, val remote: Boolean = false) : Update() } enum class LoadingSpace { NEXT, PREV } }
mit
8635a9cf9ea44f0592ae968c3cbf2525
28.95679
116
0.604905
4.467772
false
false
false
false
trmollet/tuto_kotlin
src/i_introduction/_4_Lambdas/n04Lambdas.kt
1
737
package i_introduction._4_Lambdas import util.TODO import util.doc4 fun example() { val sum = { x: Int, y: Int -> x + y } val square: (Int) -> Int = { x -> x * x } sum(1, square(2)) == 5 } fun todoTask4(collection: Collection<Int>): Nothing = TODO( """ Task 4. Rewrite 'JavaCode4.task4()' in Kotlin using lambdas: return true if the collection contains an even number. You can find the appropriate function to call on 'Collection' by using code completion. Don't use the class 'Iterables'. """, documentation = doc4(), references = { JavaCode4().task4(collection) }) fun task4(collection: Collection<Int>): Boolean = collection.any { n -> n % 2 == 0 }
mit
3125e81ba45ff1f01fc6f45499a8e691
28.52
95
0.610583
3.798969
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/domain/call/CallManagerImpl.kt
1
21617
package com.quickblox.sample.conference.kotlin.domain.call import android.content.Context import android.content.Intent import android.os.Bundle import android.os.CountDownTimer import android.os.Handler import android.os.Looper import androidx.annotation.IntDef import com.quickblox.chat.model.QBChatDialog import com.quickblox.conference.ConferenceSession import com.quickblox.conference.QBConferenceRole import com.quickblox.conference.WsException import com.quickblox.conference.callbacks.ConferenceEntityCallback import com.quickblox.conference.callbacks.ConferenceSessionCallbacks import com.quickblox.sample.conference.kotlin.R import com.quickblox.sample.conference.kotlin.data.DataCallBack import com.quickblox.sample.conference.kotlin.domain.DomainCallback import com.quickblox.sample.conference.kotlin.domain.call.CallManagerImpl.Companion.CallType.Companion.CONVERSATION import com.quickblox.sample.conference.kotlin.domain.call.CallManagerImpl.Companion.CallType.Companion.STREAM import com.quickblox.sample.conference.kotlin.domain.call.entities.* import com.quickblox.sample.conference.kotlin.domain.call.entities.SessionState.* import com.quickblox.sample.conference.kotlin.domain.call.entities.SessionStateImpl.* import com.quickblox.sample.conference.kotlin.domain.repositories.call.CallRepository import com.quickblox.sample.conference.kotlin.presentation.resources.ResourcesManager import com.quickblox.videochat.webrtc.* import com.quickblox.videochat.webrtc.AppRTCAudioManager.* import com.quickblox.videochat.webrtc.QBRTCCameraVideoCapturer.QBRTCCameraCapturerException import com.quickblox.videochat.webrtc.callbacks.QBRTCClientAudioTracksCallback import com.quickblox.videochat.webrtc.callbacks.QBRTCClientVideoTracksCallbacks import com.quickblox.videochat.webrtc.callbacks.QBRTCSessionStateCallback import com.quickblox.videochat.webrtc.view.QBRTCVideoTrack import org.webrtc.CameraVideoCapturer import java.util.* private const val MAX_CONFERENCE_OPPONENTS_ALLOWED = 12 private const val ICE_FAILED_REASON = "ICE failed" private const val ONLINE_INTERVAL = 3000L private const val MILLIS_FUTURE = 7000L private const val SECONDS_13 = 13000L /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ class CallManagerImpl(private val context: Context, private val resourcesManager: ResourcesManager, private val callRepository: CallRepository) : CallManager { private var currentSession: ConferenceSession? = null private var qbRtcSessionStateListener: QBRTCSessionStateCallback<ConferenceSession>? = null private var conferenceSessionListener: ConferenceSessionCallbacks? = null private var videoTrackListener: QBRTCClientVideoTracksCallbacks<ConferenceSession>? = null private var audioTrackListener: QBRTCClientAudioTracksCallback<ConferenceSession>? = null private var callListeners = hashSetOf<CallListener>() private var reconnectionListeners = hashSetOf<ReconnectionListener>() private val subscribedPublishers = hashSetOf<Int?>() private val callEntities = sortedSetOf(CallEntity.ComparatorImpl()) private var audioManager: AppRTCAudioManager? = null private var callType: Int? = null private var currentDialog: QBChatDialog? = null private val timer = OnlineParticipantsCheckerCountdown(MILLIS_FUTURE, ONLINE_INTERVAL) private val sessionState = SessionStateImpl() private var backgroundState = false companion object { @IntDef(CONVERSATION, STREAM) annotation class CallType { companion object { const val CONVERSATION = 0 const val STREAM = 1 } } } override fun getSessionState(): SessionState { return sessionState } override fun setBackgroundState(backgroundState: Boolean) { this.backgroundState = backgroundState if (!isSharing() && backgroundState) { saveVideoState() setVideoEnabled(false) } } override fun saveVideoState() { sessionState.videoEnabled = isVideoEnabled() } override fun subscribeReconnectionListener(reconnectionListener: ReconnectionListener?) { reconnectionListener?.let { reconnectionListeners.add(it) } } override fun unsubscribeReconnectionListener(reconnectionListener: ReconnectionListener?) { reconnectionListeners.remove(reconnectionListener) } override fun getRole(): QBConferenceRole? { return currentSession?.conferenceRole } override fun getCallType(): Int? { return callType } override fun setDefaultReconnectionState() { sessionState.reconnection = ReconnectionState.DEFAULT } override fun getSession(): ConferenceSession? { return currentSession } override fun getCurrentDialog(): QBChatDialog? { return currentDialog } override fun getCallEntities(): Set<CallEntity> { return callEntities } override fun createSession(currentUserId: Int, dialog: QBChatDialog?, roomId: String?, role: QBConferenceRole?, callType: Int?, callback: DomainCallback<ConferenceSession, Exception>) { currentSession?.leave() ?: run { sessionState.setDefault() } callRepository.createSession(currentUserId, object : DataCallBack<ConferenceSession, Exception> { override fun onSuccess(result: ConferenceSession, bundle: Bundle?) { if (result.activePublishers.size >= MAX_CONFERENCE_OPPONENTS_ALLOWED) { result.leave() callback.onError(Exception(resourcesManager.get().getString(R.string.full_room))) return } currentDialog = dialog currentSession = result videoTrackListener = VideoTrackListener() audioTrackListener = AudioTrackListener() qbRtcSessionStateListener = QBRTCSessionStateListener() conferenceSessionListener = ConferenceSessionListener() initAudioManager() currentSession?.addSessionCallbacksListener(qbRtcSessionStateListener) currentSession?.addConferenceSessionListener(conferenceSessionListener) currentSession?.addVideoTrackCallbacksListener(videoTrackListener) currentSession?.addAudioTrackCallbacksListener(audioTrackListener) joinConference(roomId, role) callback.onSuccess(result, null) [email protected] = callType if ([email protected] == STREAM && role == QBConferenceRole.PUBLISHER) { timer.start() } } override fun onError(error: Exception) { callback.onError(error) } }) } private fun joinConference(dialogId: String?, role: QBConferenceRole?) { currentSession?.joinDialog(dialogId, role, object : ConferenceEntityCallback<ArrayList<Int?>> { override fun onSuccess(publishers: ArrayList<Int?>?) { // empty } override fun onError(exception: WsException) { releaseSession(exception) } }) } private fun initAudioManager() { audioManager = create(context) audioManager?.selectAudioDevice(AudioDevice.SPEAKER_PHONE) audioManager?.start { _: AudioDevice, _: Set<AudioDevice?>? -> } } override fun subscribeCallListener(callListener: CallListener) { callListeners.add(callListener) } override fun unsubscribeCallListener(callListener: CallListener) { callListeners.remove(callListener) } override fun swapCamera() { currentSession?.mediaStreamManager?.videoCapturer?.let { val videoCapturer = currentSession?.mediaStreamManager?.videoCapturer as QBRTCCameraVideoCapturer videoCapturer.switchCamera(object : CameraVideoCapturer.CameraSwitchHandler { override fun onCameraSwitchDone(isSwitch: Boolean) { sessionState.frontCamera = isSwitch } override fun onCameraSwitchError(exception: String?) { callListeners.forEach { callListener -> callListener.onError(Exception(exception)) } } }) } } private fun getOnlineParticipants() { currentSession?.getOnlineParticipants(object : ConferenceEntityCallback<Map<Int, Boolean>> { override fun onSuccess(integerBooleanMap: Map<Int, Boolean>) { if (callListeners.isNotEmpty()) { for (callListener in callListeners) { Handler(Looper.getMainLooper()).post { callListener.setOnlineParticipants(integerBooleanMap.size - 1) } } } } override fun onError(e: WsException) { // empty } }) } override fun setAudioEnabled(enable: Boolean) { currentSession?.mediaStreamManager?.localAudioTrack?.setEnabled(enable) } override fun setVideoEnabled(enable: Boolean) { currentSession?.mediaStreamManager?.localVideoTrack?.setEnabled(enable) } override fun leaveSession() { releaseSession(null) } override fun startSharing(permissionIntent: Intent) { QBRTCMediaConfig.setVideoWidth(QBRTCMediaConfig.VideoQuality.HD_VIDEO.width) QBRTCMediaConfig.setVideoHeight(QBRTCMediaConfig.VideoQuality.HD_VIDEO.height) currentSession?.mediaStreamManager?.videoCapturer = QBRTCScreenCapturer(permissionIntent, null) setVideoEnabled(true) sessionState.showedSharing = true } override fun stopSharing(callback: DomainCallback<Unit?, Exception>) { try { currentSession?.mediaStreamManager?.videoCapturer = QBRTCCameraVideoCapturer(context, null) if (!sessionState.frontCamera) { swapCamera() } sessionState.showedSharing = false callback.onSuccess(Unit, null) } catch (exception: QBRTCCameraCapturerException) { callback.onError(exception) } } override fun isSharing(): Boolean { return sessionState.showedSharing } override fun isAudioEnabled(): Boolean { currentSession?.mediaStreamManager?.localAudioTrack?.enabled()?.let { return it } return false } override fun isVideoEnabled(): Boolean { currentSession?.mediaStreamManager?.localVideoTrack?.enabled()?.let { return it } return false } override fun isFrontCamera(): Boolean { return sessionState.frontCamera } private inner class QBRTCSessionStateListener : QBRTCSessionStateCallback<ConferenceSession> { override fun onStateChanged(session: ConferenceSession?, state: BaseSession.QBRTCSessionState) { for (callListener in callListeners) { callListener.onStateChanged(session, state) } } override fun onConnectedToUser(session: ConferenceSession?, userId: Int?) { if (userId == currentSession?.currentUserID && sessionState.reconnection == ReconnectionState.IN_PROGRESS) { sessionState.reconnection = ReconnectionState.COMPLETED for (reconnectionListener in reconnectionListeners) { Handler(Looper.getMainLooper()).post { reconnectionListener.onChangedState(sessionState.reconnection) } } } } override fun onDisconnectedFromUser(session: ConferenceSession?, userId: Int) { if (userId == currentSession?.currentUserID && currentSession?.conferenceRole == QBConferenceRole.PUBLISHER) { sessionState.reconnection = ReconnectionState.IN_PROGRESS sessionState.audioEnabled = isAudioEnabled() if (!backgroundState) { sessionState.videoEnabled = isVideoEnabled() } sessionState.frontCamera = isFrontCamera() for (reconnectionListener in reconnectionListeners) { Handler(Looper.getMainLooper()).post { reconnectionListener.onChangedState(sessionState.reconnection) } } } else if (currentSession?.conferenceRole == QBConferenceRole.LISTENER) { sessionState.reconnection = ReconnectionState.IN_PROGRESS for (reconnectionListener in reconnectionListeners) { Handler(Looper.getMainLooper()).post { reconnectionListener.onChangedState(sessionState.reconnection) } } currentSession?.leave() } } override fun onConnectionClosedForUser(session: ConferenceSession?, userId: Int) { val callEntity = callEntities.find { it.getUserId() == userId } callEntity?.let { callEntity.releaseView() callEntities.remove(callEntity) } for (callListener in callListeners) { callListener.leftPublisher(userId) } } } private inner class ConferenceSessionListener : ConferenceSessionCallbacks { override fun onPublishersReceived(publishersList: ArrayList<Int>) { subscribePublishers(publishersList) } override fun onPublisherLeft(userId: Int?) { subscribedPublishers.remove(userId) } override fun onMediaReceived(p0: String?, p1: Boolean) { //empty } override fun onSlowLinkReceived(p0: Boolean, p1: Int) { //empty } override fun onError(exception: WsException?) { if (exception?.message == ICE_FAILED_REASON) { releaseSession(exception) } } override fun onSessionClosed(session: ConferenceSession?) { if (session == currentSession && sessionState.reconnection == ReconnectionState.IN_PROGRESS) { timer.cancel() ReconnectionTimer().start() } } } private fun subscribePublishers(publishersList: ArrayList<Int>) { publishersList.let { for (publisher in publishersList) { currentSession?.subscribeToPublisher(publisher) } subscribedPublishers.addAll(publishersList) } } private inner class VideoTrackListener : QBRTCClientVideoTracksCallbacks<ConferenceSession> { override fun onLocalVideoTrackReceive(qbrtcSession: ConferenceSession?, videoTrack: QBRTCVideoTrack?) { val callEntity = callEntities.find { it.getUserId() == qbrtcSession?.currentUserID } if (callEntity == null) { val entity = CallEntityImpl(currentSession?.currentUserID, null, videoTrack, null, null, true ) callEntities.add(entity) if (!sessionState.frontCamera) { swapCamera() } if (backgroundState) { setVideoEnabled(false) } else { setVideoEnabled(sessionState.videoEnabled) } for (callListener in callListeners) { currentSession?.currentUserID?.let { userId -> callListener.receivedLocalVideoTrack(userId) } } return } if (!isSharing()) { callEntity.releaseView() callEntity.setVideoTrack(videoTrack) for (callListener in callListeners) { currentSession?.currentUserID?.let { userId -> callListener.receivedLocalVideoTrack(userId) } } } } override fun onRemoteVideoTrackReceive(session: ConferenceSession?, videoTrack: QBRTCVideoTrack, userId: Int) { val callEntity = callEntities.find { it.getUserId() == userId } if (callEntity == null) { callEntities.add(CallEntityImpl(userId, null, videoTrack, null, null, false)) } else { callEntity.releaseView() callEntity.setVideoTrack(videoTrack) } } } private inner class AudioTrackListener : QBRTCClientAudioTracksCallback<ConferenceSession> { override fun onLocalAudioTrackReceive(conferenceSession: ConferenceSession, qbrtcAudioTrack: QBRTCAudioTrack) { currentSession?.mediaStreamManager?.localAudioTrack?.setEnabled(sessionState.audioEnabled) } override fun onRemoteAudioTrackReceive(conferenceSession: ConferenceSession?, qbrtcAudioTrack: QBRTCAudioTrack, userId: Int) { val callEntity = callEntities.find { it.getUserId() == userId } callEntity?.setAudioTrack(qbrtcAudioTrack) for (callListener in callListeners) { callListener.receivedRemoteVideoTrack(userId) } } } private inner class OnlineParticipantsCheckerCountdown constructor(millisInFuture: Long, countDownInterval: Long) : CountDownTimer(millisInFuture, countDownInterval) { override fun onTick(millisUntilFinished: Long) { getOnlineParticipants() } override fun onFinish() { start() } } private fun releaseSession(exception: Exception?) { callListeners.forEach { callListener -> callListener.releaseSession(exception) } callEntities.forEach { it.releaseView() } currentSession?.removeSessionCallbacksListener(qbRtcSessionStateListener) currentSession?.removeConferenceSessionListener(conferenceSessionListener) currentSession?.removeVideoTrackCallbacksListener(videoTrackListener) currentSession?.removeAudioTrackCallbacksListener(audioTrackListener) currentSession?.leave() audioManager?.stop() audioManager = null currentSession = null videoTrackListener = null audioTrackListener = null qbRtcSessionStateListener = null conferenceSessionListener = null sessionState.reconnection = ReconnectionState.DEFAULT timer.cancel() currentDialog = null callType = null sessionState.videoEnabled = false callEntities.clear() } private inner class ReconnectionTimer { private var timer: Timer? = Timer() private var lastDelay: Long = 0 private var delay: Long = 1000 private var newDelay: Long = 0 fun start() { if (newDelay >= SECONDS_13) { sessionState.reconnection = ReconnectionState.FAILED for (reconnectionListener in reconnectionListeners) { Handler(Looper.getMainLooper()).post { reconnectionListener.onChangedState(sessionState.reconnection) } } return } newDelay = lastDelay + delay lastDelay = delay delay = newDelay timer?.cancel() timer = Timer() timer?.schedule(object : TimerTask() { override fun run() { currentSession?.currentUserID?.let { createSession(it, currentDialog, currentSession?.dialogID, currentSession?.conferenceRole, callType, object : DomainCallback<ConferenceSession, Exception> { override fun onSuccess(result: ConferenceSession, bundle: Bundle?) { timer?.purge() timer?.cancel() timer = null if (sessionState.showedSharing) { for (reconnectionListener in reconnectionListeners) { reconnectionListener.requestPermission() } } sessionState.reconnection = ReconnectionState.COMPLETED for (reconnectionListener in reconnectionListeners) { Handler(Looper.getMainLooper()).post { reconnectionListener.onChangedState(sessionState.reconnection) } } } override fun onError(error: Exception) { start() } }) } ?: run { for (reconnectionListener in reconnectionListeners) { Handler(Looper.getMainLooper()).post { reconnectionListener.onChangedState(sessionState.reconnection) } } } } }, newDelay) } } }
bsd-3-clause
0902ce474a54926c21b6471bb8733390
39.709981
171
0.626018
5.651242
false
false
false
false
GeoffreyMetais/vlc-android
application/tools/src/main/java/org/videolan/tools/Preferences.kt
1
1962
/***************************************************************************** * Preferences.java * * Copyright © 2011-2014 VLC authors and VideoLAN * * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.tools import android.content.SharedPreferences import android.content.SharedPreferences.Editor import org.json.JSONArray import org.json.JSONException object Preferences { val TAG = "VLC/UiTools/Preferences" fun getFloatArray(pref: SharedPreferences, key: String): FloatArray? { var array: FloatArray? = null val s = pref.getString(key, null) if (s != null) { try { val json = JSONArray(s) array = FloatArray(json.length()) for (i in array.indices) array[i] = json.getDouble(i).toFloat() } catch (e: JSONException) { e.printStackTrace() } } return array } fun putFloatArray(editor: Editor, key: String, array: FloatArray) { try { val json = JSONArray() for (f in array) json.put(f.toDouble()) editor.putString(key, json.toString()) } catch (e: JSONException) { e.printStackTrace() } } }
gpl-2.0
39c22af2ded644e619a448da6ae67621
31.147541
80
0.611423
4.592506
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/preferences/DefaultFilterProvider.kt
1
9025
package org.tasks.preferences import android.content.Context import com.todoroo.astrid.api.* import com.todoroo.astrid.api.Filter import com.todoroo.astrid.core.BuiltInFilterExposer import com.todoroo.astrid.core.BuiltInFilterExposer.Companion.getMyTasksFilter import com.todoroo.astrid.data.Task import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.runBlocking import org.tasks.R import org.tasks.Strings.isNullOrEmpty import org.tasks.data.* import org.tasks.filters.PlaceFilter import timber.log.Timber import javax.inject.Inject class DefaultFilterProvider @Inject constructor( // TODO: don't inject context, it breaks built-in filters when overriding language @param:ApplicationContext private val context: Context, private val preferences: Preferences, private val filterDao: FilterDao, private val tagDataDao: TagDataDao, private val googleTaskListDao: GoogleTaskListDao, private val caldavDao: CaldavDao, private val locationDao: LocationDao, private val googleTaskDao: GoogleTaskDao) { var dashclockFilter: Filter @Deprecated("use coroutines") get() = runBlocking { getFilterFromPreference(R.string.p_dashclock_filter) } set(filter) = setFilterPreference(filter, R.string.p_dashclock_filter) var lastViewedFilter: Filter @Deprecated("use coroutines") get() = runBlocking { getFilterFromPreference(R.string.p_last_viewed_list) } set(filter) = setFilterPreference(filter, R.string.p_last_viewed_list) var defaultList: Filter @Deprecated("use coroutines") get() = runBlocking { getDefaultList() } set(filter) = setFilterPreference(filter, R.string.p_default_list) @Deprecated("use coroutines") val startupFilter: Filter get() = runBlocking { getStartupFilter() } fun setBadgeFilter(filter: Filter) = setFilterPreference(filter, R.string.p_badge_list) suspend fun getBadgeFilter() = getFilterFromPreference(R.string.p_badge_list) suspend fun getDefaultList() = getFilterFromPreference(preferences.getStringValue(R.string.p_default_list), null) ?: getAnyList() suspend fun getLastViewedFilter() = getFilterFromPreference(R.string.p_last_viewed_list) suspend fun getDefaultOpenFilter() = getFilterFromPreference(R.string.p_default_open_filter) fun setDefaultOpenFilter(filter: Filter) = setFilterPreference(filter, R.string.p_default_open_filter) suspend fun getStartupFilter(): Filter = if (preferences.getBoolean(R.string.p_open_last_viewed_list, true)) { getLastViewedFilter() } else { getDefaultOpenFilter() } @Deprecated("use coroutines") fun getFilterFromPreferenceBlocking(prefString: String?) = runBlocking { getFilterFromPreference(prefString) } suspend fun getFilterFromPreference(resId: Int): Filter = getFilterFromPreference(preferences.getStringValue(resId)) suspend fun getFilterFromPreference(prefString: String?): Filter = getFilterFromPreference(prefString, getMyTasksFilter(context.resources))!! private suspend fun getAnyList(): Filter { val filter = googleTaskListDao.getAllLists().getOrNull(0)?.let(::GtasksFilter) ?: caldavDao.getCalendars().getOrElse(0) { caldavDao.getLocalList(context) }.let(::CaldavFilter) defaultList = filter return filter } private suspend fun getFilterFromPreference(preferenceValue: String?, def: Filter?) = try { preferenceValue?.let { loadFilter(it) } ?: def } catch (e: Exception) { Timber.e(e) def } private suspend fun loadFilter(preferenceValue: String): Filter? { val split = preferenceValue.split(":") return when (split[0].toInt()) { TYPE_FILTER -> getBuiltInFilter(split[1].toInt()) TYPE_CUSTOM_FILTER -> filterDao.getById(split[1].toLong())?.let(::CustomFilter) TYPE_TAG -> { val tag = tagDataDao.getByUuid(split[1]) if (tag == null || isNullOrEmpty(tag.name)) null else TagFilter(tag) } TYPE_GOOGLE_TASKS -> googleTaskListDao.getById(split[1].toLong())?.let { GtasksFilter(it) } TYPE_CALDAV -> caldavDao.getCalendarByUuid(split[1])?.let { CaldavFilter(it) } TYPE_LOCATION -> locationDao.getPlace(split[1])?.let { PlaceFilter(it) } else -> null } } private fun setFilterPreference(filter: Filter, prefId: Int) = getFilterPreferenceValue(filter).let { preferences.setString(prefId, it) } fun getFilterPreferenceValue(filter: Filter): String? = when (val filterType = getFilterType(filter)) { TYPE_FILTER -> getFilterPreference(filterType, getBuiltInFilterId(filter)) TYPE_CUSTOM_FILTER -> getFilterPreference(filterType, (filter as CustomFilter).id) TYPE_TAG -> getFilterPreference(filterType, (filter as TagFilter).uuid) TYPE_GOOGLE_TASKS -> getFilterPreference(filterType, (filter as GtasksFilter).storeId) TYPE_CALDAV -> getFilterPreference(filterType, (filter as CaldavFilter).uuid) TYPE_LOCATION -> getFilterPreference(filterType, (filter as PlaceFilter).uid) else -> null } private fun <T> getFilterPreference(type: Int, value: T) = "$type:$value" private fun getFilterType(filter: Filter) = when (filter) { is TagFilter -> TYPE_TAG is GtasksFilter -> TYPE_GOOGLE_TASKS is CustomFilter -> TYPE_CUSTOM_FILTER is CaldavFilter -> TYPE_CALDAV is PlaceFilter -> TYPE_LOCATION else -> TYPE_FILTER } private fun getBuiltInFilter(id: Int): Filter = when (id) { FILTER_TODAY -> BuiltInFilterExposer.getTodayFilter(context.resources) FILTER_RECENTLY_MODIFIED -> BuiltInFilterExposer.getRecentlyModifiedFilter(context.resources) FILTER_SNOOZED -> BuiltInFilterExposer.getSnoozedFilter(context.resources) FILTER_NOTIFICATIONS -> BuiltInFilterExposer.getNotificationsFilter(context) else -> getMyTasksFilter(context.resources) } private fun getBuiltInFilterId(filter: Filter) = with(filter) { when { isToday() -> FILTER_TODAY isRecentlyModified() -> FILTER_RECENTLY_MODIFIED isSnoozed() -> FILTER_SNOOZED isNotifications() -> FILTER_NOTIFICATIONS else -> FILTER_MY_TASKS } } suspend fun getList(task: Task): Filter { var originalList: Filter? = null if (task.isNew) { if (task.hasTransitory(GoogleTask.KEY)) { val listId = task.getTransitory<String>(GoogleTask.KEY)!! val googleTaskList = googleTaskListDao.getByRemoteId(listId) if (googleTaskList != null) { originalList = GtasksFilter(googleTaskList) } } else if (task.hasTransitory(CaldavTask.KEY)) { val caldav = caldavDao.getCalendarByUuid(task.getTransitory(CaldavTask.KEY)!!) if (caldav != null) { originalList = CaldavFilter(caldav) } } } else { val googleTask = googleTaskDao.getByTaskId(task.id) val caldavTask = caldavDao.getTask(task.id) if (googleTask != null) { val googleTaskList = googleTaskListDao.getByRemoteId(googleTask.listId!!) if (googleTaskList != null) { originalList = GtasksFilter(googleTaskList) } } else if (caldavTask != null) { val calendarByUuid = caldavDao.getCalendarByUuid(caldavTask.calendar!!) if (calendarByUuid != null) { originalList = CaldavFilter(calendarByUuid) } } } return originalList ?: getDefaultList() } private fun Filter.isToday() = BuiltInFilterExposer.isTodayFilter(context, this) private fun Filter.isRecentlyModified() = BuiltInFilterExposer.isRecentlyModifiedFilter(context, this) private fun Filter.isSnoozed() = BuiltInFilterExposer.isSnoozedFilter(context, this) private fun Filter.isNotifications() = BuiltInFilterExposer.isNotificationsFilter(context, this) companion object { private const val TYPE_FILTER = 0 private const val TYPE_CUSTOM_FILTER = 1 private const val TYPE_TAG = 2 private const val TYPE_GOOGLE_TASKS = 3 private const val TYPE_CALDAV = 4 private const val TYPE_LOCATION = 5 private const val FILTER_MY_TASKS = 0 private const val FILTER_TODAY = 1 @Suppress("unused") private const val FILTER_UNCATEGORIZED = 2 private const val FILTER_RECENTLY_MODIFIED = 3 private const val FILTER_SNOOZED = 4 private const val FILTER_NOTIFICATIONS = 5 } }
gpl-3.0
d4e8075f9a8c35136d409916b536e341
42.186603
114
0.663601
4.45679
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/data/TagDataDao.kt
1
6638
package org.tasks.data import androidx.core.util.Pair import androidx.lifecycle.LiveData import androidx.room.* import com.todoroo.astrid.api.FilterListItem.NO_ORDER import com.todoroo.astrid.data.Task import com.todoroo.astrid.helper.UUIDHelper import org.tasks.db.DbUtils import org.tasks.filters.AlphanumComparator import org.tasks.filters.TagFilters import org.tasks.time.DateTimeUtils.currentTimeMillis import java.util.* import kotlin.collections.HashSet @Dao abstract class TagDataDao { @Query("SELECT * FROM tagdata") abstract fun subscribeToTags(): LiveData<List<TagData>> @Query("SELECT * FROM tagdata WHERE name = :name COLLATE NOCASE LIMIT 1") abstract suspend fun getTagByName(name: String): TagData? /** * If a tag already exists in the database that case insensitively matches the given tag, return * that. Otherwise, return the argument */ suspend fun getTagWithCase(tag: String): String? = getTagByName(tag)?.name ?: tag suspend fun searchTags(query: String): List<TagData> = searchTagsInternal("%$query%").sort() @Query("SELECT * FROM tagdata WHERE name LIKE :query AND name NOT NULL AND name != ''") protected abstract suspend fun searchTagsInternal(query: String): List<TagData> @Query("SELECT * FROM tagdata") abstract suspend fun getAll(): List<TagData> @Query("SELECT * FROM tagdata WHERE remoteId = :uuid LIMIT 1") abstract suspend fun getByUuid(uuid: String): TagData? @Query("SELECT * FROM tagdata WHERE remoteId IN (:uuids)") abstract suspend fun getByUuid(uuids: Collection<String>): List<TagData> @Query("SELECT * FROM tagdata WHERE name IS NOT NULL AND name != '' ORDER BY UPPER(name) ASC") abstract suspend fun tagDataOrderedByName(): List<TagData> @Delete internal abstract suspend fun deleteTagData(tagData: TagData) @Query("DELETE FROM tags WHERE tag_uid = :tagUid") internal abstract suspend fun deleteTags(tagUid: String) @Query("SELECT * FROM tags WHERE task IN (:tasks) AND tag_uid NOT IN (:tagsToKeep)") internal abstract suspend fun tagsToDelete(tasks: List<Long>, tagsToKeep: List<String>): List<Tag> suspend fun getTagSelections(tasks: List<Long>): Pair<Set<String>, Set<String>> { val allTags = getAllTags(tasks) val tags = allTags.map { t: String? -> HashSet<String>(t?.split(",") ?: emptySet()) } val partialTags = tags.flatten().toMutableSet() var commonTags: MutableSet<String>? = null if (tags.isEmpty()) { commonTags = HashSet() } else { for (s in tags) { if (commonTags == null) { commonTags = s.toMutableSet() } else { commonTags.retainAll(s) } } } partialTags.removeAll(commonTags!!) return Pair(partialTags, commonTags) } @Query("SELECT GROUP_CONCAT(DISTINCT(tag_uid)) FROM tasks" + " LEFT JOIN tags ON tags.task = tasks._id" + " WHERE tasks._id IN (:tasks)" + " GROUP BY tasks._id") internal abstract suspend fun getAllTags(tasks: List<Long>): List<String> @Transaction open suspend fun applyTags( tasks: List<Task>, partiallySelected: List<TagData>, selected: List<TagData>): List<Long> { val modified = HashSet<Long>() val keep = partiallySelected.plus(selected).map { it.remoteId!! } for (sublist in tasks.chunked(DbUtils.MAX_SQLITE_ARGS - keep.size)) { val tags = tagsToDelete(sublist.map(Task::id), keep) deleteTags(tags) modified.addAll(tags.map(Tag::task)) } for (task in tasks) { val added = selected subtract getTagDataForTask(task.id) if (added.isNotEmpty()) { modified.add(task.id) insert(added.map { Tag(task, it) }) } } return ArrayList(modified) } @Transaction open suspend fun delete(tagData: TagData) { deleteTags(tagData.remoteId!!) deleteTagData(tagData) } @Delete abstract suspend fun delete(tagData: List<TagData>) @Delete internal abstract suspend fun deleteTags(tags: List<Tag>) @Query("SELECT tagdata.* FROM tagdata " + "INNER JOIN tags ON tags.tag_uid = tagdata.remoteId " + "WHERE tags.task = :id " + "ORDER BY UPPER(tagdata.name) ASC") abstract suspend fun getTagDataForTask(id: Long): List<TagData> @Query("SELECT * FROM tagdata WHERE name IN (:names)") abstract suspend fun getTags(names: List<String>): List<TagData> @Update abstract suspend fun update(tagData: TagData) @Insert abstract suspend fun insert(tag: TagData): Long @Insert abstract suspend fun insert(tags: Iterable<Tag>) suspend fun createNew(tag: TagData) { if (Task.isUuidEmpty(tag.remoteId)) { tag.remoteId = UUIDHelper.newUUID() } tag.id = insert(tag) } @Query("SELECT tagdata.*, COUNT(tasks._id) AS count" + " FROM tagdata" + " LEFT JOIN tags ON tags.tag_uid = tagdata.remoteId" + " LEFT JOIN tasks ON tags.task = tasks._id AND tasks.deleted = 0 AND tasks.completed = 0 AND tasks.hideUntil < :now" + " WHERE tagdata.name IS NOT NULL AND tagdata.name != ''" + " GROUP BY tagdata.remoteId") abstract suspend fun getTagFilters(now: Long = currentTimeMillis()): List<TagFilters> @Query("UPDATE tagdata SET td_order = $NO_ORDER") abstract suspend fun resetOrders() @Query("UPDATE tagdata SET td_order = :order WHERE _id = :id") abstract suspend fun setOrder(id: Long, order: Int) suspend fun getTags(task: Task) = ArrayList(if (task.isNew) { task.tags.mapNotNull { getTagByName(it) } } else { getTagDataForTask(task.id) }) companion object { private val COMPARATOR = Comparator<TagData> { f1, f2 -> when { f1.order == NO_ORDER && f2.order == NO_ORDER -> f1.id!!.compareTo(f2.id!!) f1.order == NO_ORDER -> 1 f2.order == NO_ORDER -> -1 f1.order < f2.order -> -1 f1.order > f2.order -> 1 else -> AlphanumComparator.TAGDATA.compare(f1, f2) } } private fun List<TagData>.sort(): List<TagData> = if (all { it.order == NO_ORDER }) { sortedWith(AlphanumComparator.TAGDATA) } else { sortedWith(COMPARATOR) } } }
gpl-3.0
e8cecabdc29347ef9926bac88a48eb69
36.297753
130
0.621573
4.115313
false
false
false
false
NextFaze/dev-fun
demo/src/main/java/com/nextfaze/devfun/demo/util/ActivityTracking.kt
1
3930
package com.nextfaze.devfun.demo.util import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import com.nextfaze.devfun.demo.inject.Initializer import java.lang.ref.WeakReference import javax.inject.Inject import javax.inject.Singleton import kotlin.reflect.KProperty internal typealias OnActivityCreated = (activity: Activity, savedInstanceState: Bundle?) -> Unit internal typealias OnActivityStarted = (activity: Activity) -> Unit internal typealias OnActivityResumed = (activity: Activity) -> Unit internal typealias OnActivityPaused = (activity: Activity) -> Unit internal typealias OnActivityStopped = (activity: Activity) -> Unit internal typealias OnActivitySave = (activity: Activity, outState: Bundle) -> Unit internal typealias OnActivityDestroyed = (activity: Activity) -> Unit internal inline fun Context.registerActivityCallbacks( crossinline onCreated: OnActivityCreated, crossinline onStarted: OnActivityStarted, crossinline onResumed: OnActivityResumed, crossinline onPaused: OnActivityPaused, crossinline onDestroyed: OnActivityDestroyed ) = this.registerActivityCallbacks(onCreated, onStarted, onResumed, onPaused, {}, { _, _ -> }, onDestroyed) internal inline fun Context.registerActivityCallbacks( crossinline onCreated: OnActivityCreated, crossinline onStarted: OnActivityStarted, crossinline onResumed: OnActivityResumed, crossinline onPaused: OnActivityPaused, crossinline onStopped: OnActivityStopped, crossinline onSave: OnActivitySave, crossinline onDestroyed: OnActivityDestroyed ) = (this.applicationContext as Application).registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = onCreated.invoke(activity, savedInstanceState) override fun onActivityStarted(activity: Activity) = onStarted.invoke(activity) override fun onActivityResumed(activity: Activity) = onResumed.invoke(activity) override fun onActivityPaused(activity: Activity) = onPaused.invoke(activity) override fun onActivityStopped(activity: Activity) = onStopped.invoke(activity) override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = onSave.invoke(activity, outState) override fun onActivityDestroyed(activity: Activity) = onDestroyed.invoke(activity) }) @Singleton internal class ActivityTracker @Inject constructor() : Initializer { var activity by weak<Activity?> { null } private set private var isResumed = false override fun invoke(application: Application) { application.registerActivityCallbacks( onCreated = this::onActivityCreated, onStarted = this::onActivityStarted, onResumed = this::onActivityResumed, onPaused = { isResumed = false }, onDestroyed = this::onActivityDestroyed ) } private fun onActivityCreated(activity: Activity, @Suppress("UNUSED_PARAMETER") savedInstanceState: Bundle?) { this.activity = activity } private fun onActivityStarted(activity: Activity) { this.activity = activity } private fun onActivityResumed(activity: Activity) { this.activity = activity isResumed = true } private fun onActivityDestroyed(activity: Activity) { if (this.activity == activity) { this.activity = null } } } private class WeakProperty<T>(initialValue: T?) { private var value = WeakReference(initialValue) operator fun getValue(thisRef: Any?, property: KProperty<*>): T? = value.get() operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { this.value = WeakReference(value) } } private inline fun <reified T> weak(body: () -> T) = WeakProperty(body.invoke())
apache-2.0
2e0fc02d1ba312a2e1a1f8fd62d79a52
39.515464
136
0.741221
5.03201
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/dialogs/ColorWheelPicker.kt
1
3938
package org.tasks.dialogs import android.app.Activity import android.app.Activity.RESULT_CANCELED import android.app.Activity.RESULT_OK import android.app.Dialog import android.content.DialogInterface import android.content.Intent import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.fragment.app.Fragment import com.flask.colorpicker.ColorPickerView import com.flask.colorpicker.builder.ColorPickerDialogBuilder import dagger.hilt.android.AndroidEntryPoint import org.tasks.R import org.tasks.billing.Inventory import org.tasks.billing.PurchaseActivity import javax.inject.Inject @AndroidEntryPoint class ColorWheelPicker : DialogFragment() { companion object { const val EXTRA_SELECTED = "extra_selected" private const val REQUEST_PURCHASE = 10010 fun newColorWheel(target: Fragment?, rc: Int, selected: Int): ColorWheelPicker { val args = Bundle() args.putInt(EXTRA_SELECTED, selected) val dialog = ColorWheelPicker() dialog.setTargetFragment(target, rc) dialog.arguments = args return dialog } } interface ColorPickedCallback { fun onColorPicked(color: Int) } @Inject lateinit var inventory: Inventory var dialog: AlertDialog? = null var selected = -1 var callback: ColorPickedCallback? = null override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { selected = savedInstanceState?.getInt(EXTRA_SELECTED) ?: requireArguments().getInt(EXTRA_SELECTED, 0) val button = if (inventory.purchasedThemes()) R.string.ok else R.string.upgrade_to_pro val builder = ColorPickerDialogBuilder .with(activity) .wheelType(ColorPickerView.WHEEL_TYPE.CIRCLE) .density(7) .setOnColorChangedListener { which -> selected = which } .setOnColorSelectedListener { which -> selected = which } .lightnessSliderOnly() .setPositiveButton(button) { _, _, _ -> if (inventory.purchasedThemes()) { deliverSelection() } else { startActivityForResult( Intent(context, PurchaseActivity::class.java), REQUEST_PURCHASE ) } } .setNegativeButton(R.string.cancel, null) if (selected != 0) { builder.initialColor(selected) } dialog = builder.build() return dialog as Dialog } override fun onAttach(activity: Activity) { super.onAttach(activity) if (activity is ColorPickedCallback) { callback = activity } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { if (requestCode == REQUEST_PURCHASE) { if (inventory.hasPro) { deliverSelection() } else { dialog?.cancel() } } else { super.onActivityResult(requestCode, resultCode, data) } } private fun deliverSelection() { dialog?.dismiss() if (targetFragment == null) { callback?.onColorPicked(selected) } else { val data = Intent().putExtra(EXTRA_SELECTED, selected) targetFragment?.onActivityResult(targetRequestCode, RESULT_OK, data) } } override fun onCancel(dialog: DialogInterface) { targetFragment?.onActivityResult(targetRequestCode, RESULT_CANCELED, null) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(EXTRA_SELECTED, selected) } }
gpl-3.0
ae16ee9ff2dc4257975504dd9def3e01
31.825
109
0.613255
5.127604
false
false
false
false
apollo-rsps/apollo
game/plugin/skills/herblore/src/IdentifyHerbAction.kt
1
1393
import java.util.Objects import org.apollo.game.action.ActionBlock import org.apollo.game.action.AsyncAction import org.apollo.game.model.entity.Player import org.apollo.game.plugin.api.herblore import org.apollo.util.LanguageUtil class IdentifyHerbAction( player: Player, private val slot: Int, private val herb: Herb ) : AsyncAction<Player>(0, true, player) { override fun action(): ActionBlock = { if (mob.herblore.current < herb.level) { mob.sendMessage("You need a Herblore level of ${herb.level} to clean this herb.") stop() } val inventory = mob.inventory if (inventory.removeSlot(slot, 1) > 0) { inventory.add(herb.identified) mob.herblore.experience += herb.experience val name = herb.identifiedName val article = LanguageUtil.getIndefiniteArticle(name) mob.sendMessage("You identify the herb as $article $name.") } stop() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as IdentifyHerbAction return mob == other.mob && herb == other.herb && slot == other.slot } override fun hashCode(): Int = Objects.hash(mob, herb, slot) companion object { const val IDENTIFY_OPTION = 1 } }
isc
3d0631a32fc62ca8f2c2c98c73c4ff77
27.44898
93
0.636755
3.923944
false
false
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/query/handlers/PotCreatedEventHandler.kt
1
1623
package com.flexpoker.table.query.handlers import com.flexpoker.framework.event.EventHandler import com.flexpoker.framework.pushnotifier.PushNotificationPublisher import com.flexpoker.login.repository.LoginRepository import com.flexpoker.pushnotifications.TableUpdatedPushNotification import com.flexpoker.table.command.events.PotCreatedEvent import com.flexpoker.table.query.dto.PotDTO import com.flexpoker.table.query.repository.TableRepository import org.springframework.stereotype.Component import javax.inject.Inject @Component class PotCreatedEventHandler @Inject constructor( private val tableRepository: TableRepository, private val pushNotificationPublisher: PushNotificationPublisher, private val loginRepository: LoginRepository ) : EventHandler<PotCreatedEvent> { override fun handle(event: PotCreatedEvent) { handleUpdatingTable(event) handlePushNotifications(event) } private fun handleUpdatingTable(event: PotCreatedEvent) { val tableDTO = tableRepository.fetchById(event.aggregateId) val playerUsernames = event.playersInvolved.map { loginRepository.fetchUsernameByAggregateId(it) }.toSet() val updatedPots = tableDTO.pots!!.plus(PotDTO(playerUsernames, 0, true, emptySet())) val updatedTable = tableDTO.copy(version = event.version, pots = updatedPots) tableRepository.save(updatedTable) } private fun handlePushNotifications(event: PotCreatedEvent) { val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId) pushNotificationPublisher.publish(pushNotification) } }
gpl-2.0
4dc172b7e8501269ad24a03dc0375faf
41.736842
114
0.796057
5.087774
false
false
false
false
aglne/mycollab
mycollab-web/src/main/java/com/mycollab/module/project/view/page/PageUrlResolver.kt
3
5143
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.project.view.page import com.mycollab.common.UrlTokenizer import com.mycollab.core.MyCollabException import com.mycollab.core.utils.StringUtils import com.mycollab.vaadin.EventBusFactory import com.mycollab.module.page.domain.Page import com.mycollab.module.page.service.PageService import com.mycollab.module.project.event.ProjectEvent import com.mycollab.module.project.view.ProjectUrlResolver import com.mycollab.module.project.view.parameters.PageScreenData import com.mycollab.module.project.view.parameters.ProjectScreenData import com.mycollab.spring.AppContextUtil import com.mycollab.vaadin.UserUIContext import com.mycollab.vaadin.mvp.PageActionChain /** * @author MyCollab Ltd * @since 6.0.0 */ class PageUrlResolver : ProjectUrlResolver() { init { this.addSubResolver("list", ListUrlResolver()) this.addSubResolver("add", AddUrlResolver()) this.addSubResolver("edit", EditUrlResolver()) this.addSubResolver("preview", PreviewUrlResolver()) } private class ListUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { try { val tokenizer = UrlTokenizer(params[0]) val projectId = tokenizer.getInt() val pagePath = tokenizer.remainValue val chain = PageActionChain(ProjectScreenData.Goto(projectId), PageScreenData.Search(pagePath)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } catch (e: Exception) { throw MyCollabException(e) } } } private class PreviewUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { try { val tokenizer = UrlTokenizer(params[0]) val projectId = tokenizer.getInt() val pagePath = tokenizer.remainValue val pageService = AppContextUtil.getSpringBean(PageService::class.java) val page = pageService.getPage(pagePath, UserUIContext.getUsername()) if (page != null) { val chain = PageActionChain(ProjectScreenData.Goto(projectId), PageScreenData.Read(page)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } else { val chain = PageActionChain(ProjectScreenData.Goto(projectId)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } catch (e: Exception) { throw MyCollabException(e) } } } private class EditUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { try { val tokenizer = UrlTokenizer(params[0]) val projectId = tokenizer.getInt() val pagePath = tokenizer.remainValue val pageService = AppContextUtil.getSpringBean(PageService::class.java) val page = pageService.getPage(pagePath, UserUIContext.getUsername()) if (page != null) { val chain = PageActionChain(ProjectScreenData.Goto(projectId), PageScreenData.Edit(page)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } else { val chain = PageActionChain(ProjectScreenData.Goto(projectId)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } } catch (e: Exception) { throw MyCollabException(e) } } } private class AddUrlResolver : ProjectUrlResolver() { override fun handlePage(vararg params: String) { try { val tokenizer = UrlTokenizer(params[0]) val projectId = tokenizer.getInt() val pagePath = tokenizer.remainValue val page = Page() page.path = "$pagePath/${StringUtils.generateSoftUniqueId()}" val chain = PageActionChain(ProjectScreenData.Goto(projectId), PageScreenData.Add(page)) EventBusFactory.getInstance().post(ProjectEvent.GotoMyProject(this, chain)) } catch (e: Exception) { throw MyCollabException(e) } } } }
agpl-3.0
4bd9b0b5d775bf6c81512e8bae1859cd
43.336207
111
0.644885
5.046124
false
false
false
false
StephaneBg/ScoreItProject
data/src/main/java/com/sbgapps/scoreit/cache/model/UniversalLapData.kt
1
1140
/* * Copyright 2018 Stéphane Baiget * * 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.sbgapps.scoreit.cache.model import androidx.room.Entity import androidx.room.ForeignKey import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "laps", foreignKeys = [(ForeignKey( entity = UniversalGameData::class, parentColumns = arrayOf("id"), childColumns = arrayOf("gameId"), onDelete = ForeignKey.CASCADE ))] ) data class UniversalLapData( @PrimaryKey(autoGenerate = true) val id: Long? = null, val gameId: Long, var points: MutableList<Int> )
apache-2.0
4951821fa99c7cfb91827e87de4cec40
29.810811
75
0.71993
4.218519
false
false
false
false
cbeust/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/Jvm.kt
2
5459
package com.beust.kobalt import com.beust.kobalt.misc.kobaltLog import com.beust.kobalt.misc.warn import java.io.File import java.io.IOException open class Jvm constructor( val os: OperatingSystem, var javaBase: File? = null) : JavaInfo() { private var _javaHome: File? = null override var javaHome: File? = null get() = _javaHome!! override var runtimeJar: File? = null private fun findRuntimeJar() : File? { var runtimeJar = File(javaBase, "lib/rt.jar") if (runtimeJar.exists()) { return runtimeJar } runtimeJar = File(javaBase, "jre/lib/rt.jar") return if (runtimeJar.exists()) runtimeJar else null } override var toolsJar: File? = null private var userSupplied: Boolean? = false private var javaVersion: String? = null init { if (javaBase == null) { //discover based on what's in the sys. property try { javaBase = File(System.getProperty("java.home")).canonicalFile } catch (e: IOException) { throw KobaltException(e) } _javaHome = findJavaHome(javaBase!!) javaVersion = SystemProperties.Companion.javaVersion userSupplied = false } else { //precisely use what the user wants and validate strictly further on _javaHome = javaBase!! userSupplied = true javaVersion = null } toolsJar = findToolsJar(javaBase!!) runtimeJar = findRuntimeJar() } private fun findJavaHome(javaBase: File): File { val toolsJar = findToolsJar(javaBase) if (toolsJar != null) { return toolsJar.parentFile.parentFile } else if (javaBase.name.equals("jre", true) && File(javaBase.parentFile, "bin/java").exists()) { return javaBase.parentFile } else { return javaBase } } private fun findToolsJar(jh: File): File? { javaHome = jh var toolsJar = File(javaHome, "lib/tools.jar") if (toolsJar.exists()) { return toolsJar } if (javaHome!!.name.equals("jre", true)) { _javaHome = javaHome!!.parentFile toolsJar = File(javaHome, "lib/tools.jar") if (toolsJar.exists()) { return toolsJar } } if (os.isWindows()) { val version = SystemProperties.Companion.javaVersion if (javaHome!!.name.toRegex().matches("jre\\d+") || javaHome!!.name == "jre$version") { _javaHome = File(javaHome!!.parentFile, "jdk$version") toolsJar = File(javaHome, "lib/tools.jar") if (toolsJar.exists()) { return toolsJar } } } return null } // open fun isIbmJvm(): Boolean { // return false // } override fun findExecutable(command: String): File { if (javaHome != null) { val jdkHome = if (javaHome!!.endsWith("jre")) javaHome!!.parentFile else javaHome val exec = File(jdkHome, "bin/" + command) val executable = File(os.getExecutableName(exec.absolutePath)) if (executable.isFile) { return executable } } // if (userSupplied) { // //then we want to validate strictly // throw JavaHomeException(String.format("The supplied javaHome seems to be invalid." + " I cannot find the %s executable. Tried location: %s", command, executable.getAbsolutePath())) // } val pathExecutable = os.findInPath(command) if (pathExecutable != null) { kobaltLog(2, "Unable to find the $command executable using home: " + "$javaHome but found it on the PATH: $pathExecutable.") return pathExecutable } warn("Unable to find the $command executable. Tried the java home: $javaHome" + " and the PATH. We will assume the executable can be ran in the current " + "working folder.") return java.io.File(os.getExecutableName(command)) } } class AppleJvm : Jvm { override var runtimeJar: File? = File(javaHome!!.getParentFile(), "Classes/classes.jar") override var toolsJar: File? = File(javaHome!!.getParentFile(), "Classes/tools.jar") constructor(os: OperatingSystem) : super(os) { } constructor(current: OperatingSystem, javaHome: File) : super(current, javaHome) { } /** * {@inheritDoc} */ // fun getInheritableEnvironmentVariables(envVars: Map<String, *>): Map<String, *> { // val vars = HashMap<String, Any>() // for (entry in envVars.entrySet()) { // if (entry.getKey().toRegex().matches("APP_NAME_\\d+") || // entry.getKey().toRegex().matches("JAVA_MAIN_CLASS_\\d+")) { // continue // } // vars.put(entry.getKey(), entry.getValue()) // } // return vars // } } class IbmJvm(os: OperatingSystem, suppliedJavaBase: File) : Jvm(os, suppliedJavaBase) { override var runtimeJar: File? = throw IllegalArgumentException("Not implemented") override var toolsJar: File? = throw IllegalArgumentException("Not implemented") // override fun isIbmJvm(): Boolean { // return true // } }
apache-2.0
97e3b183e4186b7d5c0d33d023825abf
33.11875
194
0.572083
4.434606
false
false
false
false
S3S3L/utils
src/main/kotlin/com/s3s3l/kotlin/utils/string/AtomicLetter.kt
1
773
package com.s3s3l.kotlin.utils.string class AtomicLetter() { private var init: Char = 'a' private var current: Char = 'a' constructor(ch: Char) : this() { if (ch < 'a' || ch > 'z') { throw IllegalArgumentException("letter is out of range, only [a-z] is supported.") } this.init = ch; this.current = ch } fun get(): Char { return this.current } fun reset() { this.current = this.init } fun getAndIncrease(): Char { if (this.current > 'z') { throw IllegalArgumentException("letter is out of range, only [a-z] is supported.") } return this.current++ } fun increaseAndGet(): Char { if (this.current >= 'z') { throw IllegalArgumentException("letter is out of range, only [a-z] is supported."); } return ++this.current; } }
apache-2.0
d1248b29ba0aa6cf7542fdfd37a5372c
18.35
86
0.636481
3.007782
false
false
false
false
jitsi/jicofo
jicofo/src/test/kotlin/org/jitsi/jicofo/mock/MockColibri2Server.kt
1
8367
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2022-Present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.mock import org.jitsi.utils.MediaType import org.jitsi.xmpp.extensions.colibri.SourcePacketExtension import org.jitsi.xmpp.extensions.colibri2.Colibri2Endpoint import org.jitsi.xmpp.extensions.colibri2.Colibri2Error import org.jitsi.xmpp.extensions.colibri2.ConferenceModifiedIQ import org.jitsi.xmpp.extensions.colibri2.ConferenceModifyIQ import org.jitsi.xmpp.extensions.colibri2.MediaSource import org.jitsi.xmpp.extensions.colibri2.Sctp import org.jitsi.xmpp.extensions.colibri2.Sources import org.jitsi.xmpp.extensions.colibri2.Transport import org.jitsi.xmpp.extensions.jingle.DtlsFingerprintPacketExtension import org.jitsi.xmpp.extensions.jingle.IceUdpTransportPacketExtension import org.jitsi.xmpp.util.createError import org.jivesoftware.smack.packet.IQ import org.jivesoftware.smack.packet.StanzaError import org.jivesoftware.smack.packet.StanzaError.Condition.bad_request import org.jivesoftware.smack.packet.StanzaError.Condition.conflict import org.jivesoftware.smack.packet.StanzaError.Condition.feature_not_implemented import org.jivesoftware.smack.packet.StanzaError.Condition.item_not_found import java.lang.Exception import kotlin.jvm.Throws import kotlin.random.Random class MockColibri2Server { private val conferences = mutableMapOf<String, Conference>() fun stop() = conferences.clear() fun handleConferenceModifyIq(request: ConferenceModifyIQ): IQ { val conference: Conference = if (request.create) { if (conferences.containsKey(request.meetingId)) { return createError(request, conflict, "Conference already exists") } val newConference = Conference(request.meetingId) conferences[request.meetingId] = newConference newConference } else { conferences[request.meetingId] ?: return createError(request, item_not_found, "Conference not found") } return try { conference.handleRequest(request) } catch (e: IqProcessingException) { // Make sure to tag the error as coming from a bridge, otherwise item_not_found may be misiterpreted. return createError(request, e.condition, e.message, Colibri2Error()) } } private fun expireConference(meetingId: String) = conferences.remove(meetingId) private inner class Conference(val meetingId: String) { val endpoints = mutableMapOf<String, Endpoint>() @Throws(IqProcessingException::class) fun handleRequest(request: ConferenceModifyIQ): IQ { val responseBuilder = ConferenceModifiedIQ.builder(ConferenceModifiedIQ.Builder.createResponse(request)) if (request.create) { responseBuilder.setSources(buildFeedbackSources(Random.nextLong(), Random.nextLong())) } request.endpoints.forEach { responseBuilder.addEndpoint(handleEndpoint(it)) } if (request.relays.isNotEmpty()) { throw RuntimeException("Relays not implemented") } if (!request.create && endpoints.isEmpty()) { expireConference(meetingId) } return responseBuilder.build() } private fun expireEndpoint(id: String) = endpoints.remove(id) private fun handleEndpoint(c2endpoint: Colibri2Endpoint): Colibri2Endpoint { val respBuilder = Colibri2Endpoint.getBuilder().apply { setId(c2endpoint.id) } if (c2endpoint.expire) { expireEndpoint(c2endpoint.id) respBuilder.setExpire(true) return respBuilder.build() } val endpoint = if (c2endpoint.create) { if (endpoints.containsKey(c2endpoint.id)) { throw IqProcessingException(conflict, "Endpoint with ID ${c2endpoint.id} already exists") } val transport = c2endpoint.transport ?: throw IqProcessingException( bad_request, "Attempt to create endpoint ${c2endpoint.id} with no <transport>" ) val newEndpoint = Endpoint(c2endpoint.id).apply { transport.sctp?.let { sctp -> if (sctp.role != null && sctp.role != Sctp.Role.SERVER) { throw IqProcessingException( feature_not_implemented, "Unsupported SCTP role: ${sctp.role}" ) } if (sctp.port != null) { throw IqProcessingException(bad_request, "Specific SCTP port requested, not supported.") } useSctp = true } } endpoints[c2endpoint.id] = newEndpoint newEndpoint } else { endpoints[c2endpoint.id] ?: throw IqProcessingException( item_not_found, "Unknown endpoint ${c2endpoint.id}" ) } // c2endpoint.transport?.iceUdpTransport?.let { endpoint.setTransportInfo(it) } if (c2endpoint.create) { val transBuilder = Transport.getBuilder() transBuilder.setIceUdpExtension(endpoint.describeTransport()) if (c2endpoint.transport?.sctp != null) { transBuilder.setSctp( Sctp.Builder() .setPort(5000) .setRole(Sctp.Role.SERVER) .build() ) } respBuilder.setTransport(transBuilder.build()) } c2endpoint.forceMute?.let { endpoint.forceMuteAudio = it.audio endpoint.forceMuteVideo = it.video } return respBuilder.build() } private inner class Endpoint(val id: String) { var useSctp = false var forceMuteAudio = false var forceMuteVideo = false fun describeTransport() = IceUdpTransportPacketExtension().apply { password = "password-$meetingId-$id" ufrag = "ufrag-$meetingId-$id" // TODO add some candidates? addChildExtension( DtlsFingerprintPacketExtension().apply { hash = "sha-256" text = "AC:58:2D:03:40:89:87:30:6C:25:2C:50:17:5C:5C:2E:" + "1F:A1:19:19:4D:74:A5:37:35:22:6E:8E:DF:55:13:8E" } ) } } } } private class IqProcessingException( val condition: StanzaError.Condition, message: String ) : Exception(message) { override fun toString() = "$condition $message" } private fun buildFeedbackSources(localAudioSsrc: Long, localVideoSsrc: Long): Sources = Sources.getBuilder().apply { addMediaSource( MediaSource.getBuilder() .setType(MediaType.AUDIO) .setId("jvb-a0") .addSource( SourcePacketExtension().apply { ssrc = localAudioSsrc name = "jvb-a0" } ) .build() ) addMediaSource( MediaSource.getBuilder() .setType(MediaType.VIDEO) .setId("jvb-v0") .addSource( SourcePacketExtension().apply { ssrc = localVideoSsrc name = "jvb-v0" } ) .build() ) }.build()
apache-2.0
1ee2e26b5ab59acde848e774b369247f
38.466981
116
0.595673
4.625207
false
false
false
false
UnknownJoe796/ponderize
app/src/main/java/com/ivieleague/ponderize/Style.kt
1
607
package com.ivieleague.ponderize import android.graphics.Color import android.view.Gravity import android.widget.TextView import org.jetbrains.anko.dip import org.jetbrains.anko.padding import org.jetbrains.anko.textColor /** * Created by josep on 10/4/2015. */ public fun TextView.styleDefault() { textSize = 18f textColor = Color.WHITE padding = dip(4) } public fun TextView.styleItem() { styleDefault() minHeight = dip(40) textSize = 18f gravity = Gravity.CENTER_VERTICAL padding = dip(8) } public fun TextView.styleHeader() { styleDefault() textSize = 24f }
mit
77a37d3bbb53c593d19ebe6e652946b0
19.266667
37
0.719934
3.656627
false
false
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/view/PaymentRelayActivityTest.kt
1
2548
package com.stripe.android.view import android.content.Context import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import com.google.common.truth.Truth.assertThat import com.stripe.android.PaymentRelayContract import com.stripe.android.PaymentRelayStarter import com.stripe.android.StripeErrorFixtures import com.stripe.android.core.exception.PermissionException import com.stripe.android.model.PaymentIntentFixtures import com.stripe.android.payments.PaymentFlowResult import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class PaymentRelayActivityTest { private val context = ApplicationProvider.getApplicationContext<Context>() private val contract = PaymentRelayContract() @Test fun `activity started with PaymentIntentArgs should finish with expected result`() { createActivity( PaymentRelayStarter.Args.PaymentIntentArgs( PaymentIntentFixtures.PI_REQUIRES_MASTERCARD_3DS2 ) ) { paymentFlowResult -> assertThat(paymentFlowResult) .isEqualTo( PaymentFlowResult.Unvalidated( clientSecret = "pi_1ExkUeAWhjPjYwPiXph9ouXa_secret_nGTdfGlzL9Uop59wN55LraiC7" ) ) } } @Test fun `activity started with ErrorArgs should finish with expected result`() { val exception = PermissionException( stripeError = StripeErrorFixtures.INVALID_REQUEST_ERROR ) createActivity( PaymentRelayStarter.Args.ErrorArgs( exception, requestCode = 50000 ) ) { paymentFlowResult -> assertThat(paymentFlowResult) .isEqualTo( PaymentFlowResult.Unvalidated( exception = exception ) ) } } private fun createActivity( args: PaymentRelayStarter.Args, onComplete: (PaymentFlowResult.Unvalidated) -> Unit ) { ActivityScenario.launch<PaymentRelayActivity>( contract.createIntent( context, args ) ).use { activityScenario -> activityScenario.onActivity { activity -> onComplete( contract.parseResult(0, activityScenario.result.resultData) ) } } } }
mit
96ce7c8d17d507aaa660914ecb6cbf5c
32.973333
101
0.636185
5.232033
false
true
false
false
JoachimR/Bible2net
app/src/main/java/de/reiss/bible2net/theword/note/list/NoteListFragment.kt
1
3867
package de.reiss.bible2net.theword.note.list import android.view.LayoutInflater import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import de.reiss.bible2net.theword.App import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.architecture.AppFragment import de.reiss.bible2net.theword.architecture.AsyncLoad import de.reiss.bible2net.theword.databinding.NoteListFragmentBinding import de.reiss.bible2net.theword.model.Note import de.reiss.bible2net.theword.note.details.NoteDetailsActivity class NoteListFragment : AppFragment<NoteListFragmentBinding, NoteListViewModel>( R.layout.note_list_fragment ), NoteClickListener { companion object { fun createInstance() = NoteListFragment() } private val listItemAdapter = NoteListItemAdapter(noteClickListener = this) override fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?) = NoteListFragmentBinding.inflate(inflater, container, false) override fun initViews() { with(binding.noteListRecyclerView) { layoutManager = LinearLayoutManager(context) adapter = listItemAdapter addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) } } override fun defineViewModelProvider(): ViewModelProvider = ViewModelProviders.of( this, NoteListViewModel.Factory( App.component.noteListRepository ) ) override fun defineViewModel(): NoteListViewModel = loadViewModelProvider().get(NoteListViewModel::class.java) override fun initViewModelObservers() { viewModel.notesLiveData().observe( this, Observer<AsyncLoad<FilteredNotes>> { updateUi() } ) } override fun onResume() { super.onResume() tryLoadNotes() } override fun onNoteClicked(note: Note) { activity?.let { it.startActivity(NoteDetailsActivity.createIntent(context = it, note = note)) } } fun applyFilter(query: String) { tryRefreshFilter(query) } private fun tryLoadNotes() { if (viewModel.isLoadingNotes().not()) { viewModel.loadNotes() } } private fun tryRefreshFilter(query: String) { if (viewModel.isLoadingNotes().not()) { viewModel.applyNewFilter(query) } } private fun updateUi() { if (viewModel.isLoadingNotes()) { binding.noteListLoading.setLoading(true) binding.noteListNoNotes.visibility = GONE binding.noteListRecyclerView.visibility = GONE } else { binding.noteListLoading.setLoading(false) val filteredNotes = viewModel.notes() val listItems = NoteListBuilder.buildList(filteredNotes.filteredItems) if (listItems.isEmpty()) { binding.noteListRecyclerView.visibility = GONE binding.noteListNoNotes.visibility = VISIBLE binding.noteListNoNotesText.text = if (filteredNotes.allItems.isEmpty()) { getString(R.string.no_notes) } else { getString(R.string.no_notes_for_filter, filteredNotes.query) } } else { binding.noteListRecyclerView.visibility = VISIBLE binding.noteListNoNotes.visibility = GONE listItemAdapter.updateContent(listItems) } } } }
gpl-3.0
0a196d91a6dae47b8e1dfd27d83906ca
32.336207
93
0.658909
5.088158
false
false
false
false
AndroidX/androidx
compose/material/material/src/commonMain/kotlin/androidx/compose/material/pullrefresh/PullRefreshIndicatorTransform.kt
3
3113
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.pullrefresh import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.drawWithContent import androidx.compose.ui.graphics.drawscope.clipRect import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.debugInspectorInfo import androidx.compose.ui.platform.inspectable /** * A modifier for translating the position and scaling the size of a pull-to-refresh indicator * based on the given [PullRefreshState]. * * @sample androidx.compose.material.samples.PullRefreshIndicatorTransformSample * * @param state The [PullRefreshState] which determines the position of the indicator. * @param scale A boolean controlling whether the indicator's size scales with pull progress or not. */ @ExperimentalMaterialApi // TODO: Consider whether the state parameter should be replaced with lambdas. fun Modifier.pullRefreshIndicatorTransform( state: PullRefreshState, scale: Boolean = false, ) = inspectable(inspectorInfo = debugInspectorInfo { name = "pullRefreshIndicatorTransform" properties["state"] = state properties["scale"] = scale }) { Modifier // Essentially we only want to clip the at the top, so the indicator will not appear when // the position is 0. It is preferable to clip the indicator as opposed to the layout that // contains the indicator, as this would also end up clipping shadows drawn by items in a // list for example - so we leave the clipping to the scrolling container. We use MAX_VALUE // for the other dimensions to allow for more room for elevation / arbitrary indicators - we // only ever really want to clip at the top edge. .drawWithContent { clipRect( top = 0f, left = -Float.MAX_VALUE, right = Float.MAX_VALUE, bottom = Float.MAX_VALUE ) { [email protected]() } } .graphicsLayer { translationY = state.position - size.height if (scale && !state.refreshing) { val scaleFraction = LinearOutSlowInEasing .transform(state.position / state.threshold) .coerceIn(0f, 1f) scaleX = scaleFraction scaleY = scaleFraction } } }
apache-2.0
311dca0080c481503b5104e3811286a5
40.52
100
0.695792
4.77454
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/macros/MacroExpansionManager.kt
2
44590
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.macros import com.google.common.annotations.VisibleForTesting import com.intellij.codeInsight.template.TemplateManager import com.intellij.openapi.Disposable import com.intellij.openapi.application.* import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.TextEditor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.* import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.RefreshQueue import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.testFramework.PlatformTestUtil import com.intellij.util.io.DataOutputStream import com.intellij.util.io.createDirectories import com.intellij.util.io.delete import com.intellij.util.io.exists import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.jetbrains.annotations.TestOnly import org.rust.RsTask import org.rust.cargo.project.model.CargoProject import org.rust.cargo.project.model.CargoProjectsService import org.rust.cargo.project.model.CargoProjectsService.CargoProjectsListener import org.rust.cargo.project.model.cargoProjects import org.rust.cargo.project.settings.RustProjectSettingsService import org.rust.cargo.project.settings.rustSettings import org.rust.cargo.project.workspace.PackageOrigin import org.rust.ide.experiments.RsExperiments import org.rust.ide.experiments.RsExperiments.EVALUATE_BUILD_SCRIPTS import org.rust.ide.experiments.RsExperiments.PROC_MACROS import org.rust.lang.RsFileType import org.rust.lang.core.crate.Crate import org.rust.lang.core.crate.CratePersistentId import org.rust.lang.core.crate.crateGraph import org.rust.lang.core.crate.impl.FakeCrate import org.rust.lang.core.indexing.RsIndexableSetContributor import org.rust.lang.core.macros.errors.* import org.rust.lang.core.psi.* import org.rust.lang.core.psi.RsProcMacroKind.DERIVE import org.rust.lang.core.psi.RsProcMacroKind.FUNCTION_LIKE import org.rust.lang.core.psi.RsPsiTreeChangeEvent.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve2.* import org.rust.openapiext.* import org.rust.stdext.* import org.rust.stdext.RsResult.Err import org.rust.stdext.RsResult.Ok import org.rust.taskQueue import java.io.IOException import java.lang.ref.SoftReference import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.Pair typealias MacroExpansionCachedResult = CachedValueProvider.Result<RsResult<MacroExpansion, GetMacroExpansionError>> interface MacroExpansionManager { val indexableDirectory: VirtualFile? fun getExpansionFor(call: RsPossibleMacroCall): MacroExpansionCachedResult fun getExpandedFrom(element: RsExpandedElement): RsPossibleMacroCall? /** * An optimized equivalent for: * ``` * when (val expandedFrom = getExpandedFrom(macroCall)?.kind) { * is MacroCall -> expandedFrom.call.context * is MetaItem -> expandedFrom.meta.owner?.context * null -> null * } * ``` */ fun getContextOfMacroCallExpandedFrom(stubParent: RsFile): PsiElement? fun isExpansionFileOfCurrentProject(file: VirtualFile): Boolean fun getCrateForExpansionFile(file: VirtualFile): CratePersistentId? fun reexpand() val macroExpansionMode: MacroExpansionMode @TestOnly fun setUnitTestExpansionModeAndDirectory( mode: MacroExpansionScope, cacheDirectory: String = "", clearCacheBeforeDispose: Boolean = false ): Disposable @TestOnly fun updateInUnitTestMode() companion object { @JvmStatic fun isExpansionFile(file: VirtualFile): Boolean = file.fileSystem == MacroExpansionFileSystem.getInstance() @JvmStatic fun invalidateCaches() { getCorruptionMarkerFile().apply { parent?.createDirectories() Files.createFile(this) } } @Synchronized fun checkInvalidatedStorage() { if (getCorruptionMarkerFile().exists()) { try { getBaseMacroDir().cleanDirectory() } catch (e: IOException) { MACRO_LOG.warn(e) } } } } } @JvmField val MACRO_LOG: Logger = Logger.getInstance("#org.rust.macros") // The path is visible in indexation progress const val MACRO_EXPANSION_VFS_ROOT = "rust_expanded_macros" private const val CORRUPTION_MARKER_NAME = "corruption.marker" fun getBaseMacroDir(): Path = RsPathManager.pluginDirInSystem().resolve("macros") private fun getCorruptionMarkerFile(): Path = getBaseMacroDir().resolve(CORRUPTION_MARKER_NAME) @State(name = "MacroExpansionManager", storages = [ Storage(StoragePathMacros.WORKSPACE_FILE, roamingType = RoamingType.DISABLED), Storage("misc.xml", roamingType = RoamingType.DISABLED, deprecated = true) ]) class MacroExpansionManagerImpl( val project: Project ) : MacroExpansionManager, PersistentStateComponent<MacroExpansionManagerImpl.PersistentState>, com.intellij.configurationStore.SettingsSavingComponent, Disposable { data class PersistentState(var directoryName: String? = null) private var dirs: Dirs? = null // Guarded by the platform RWLock. Assigned only once private var inner: MacroExpansionServiceImplInner? = null @Volatile private var isDisposed: Boolean = false override fun getState(): PersistentState { return PersistentState(dirs?.projectDirName) } override suspend fun save() { inner?.save() } override fun loadState(state: PersistentState) { // initialized manually at setUnitTestExpansionModeAndDirectory if (isUnitTestMode) return val dirs = updateDirs(state.directoryName) this.dirs = dirs MACRO_LOG.debug("Loading MacroExpansionManager") ApplicationManager.getApplication().executeOnPooledThread { val impl = MacroExpansionServiceBuilder.build(project, dirs) MACRO_LOG.debug("Loading MacroExpansionManager - data loaded") invokeLater { runWriteAction { if (isDisposed) return@runWriteAction // Publish `inner` in the same write action where `stateLoaded` is called. // The write action also makes it synchronized with `CargoProjectsService.initialized` inner = impl impl.stateLoaded(this) } } } } override fun noStateLoaded() { loadState(PersistentState(null)) } override val indexableDirectory: VirtualFile? get() = inner?.expansionsDirVi override fun getExpansionFor(call: RsPossibleMacroCall): MacroExpansionCachedResult { val impl = inner return when { call is RsMacroCall && call.macroName == "include" -> expandIncludeMacroCall(call) impl != null -> impl.getExpansionFor(call) isUnitTestMode && call is RsMacroCall -> expandMacroOld(call) else -> CachedValueProvider.Result.create( Err(GetMacroExpansionError.MacroExpansionEngineIsNotReady), project.rustStructureModificationTracker ) } } private fun expandIncludeMacroCall(call: RsMacroCall): MacroExpansionCachedResult { val expansion: RsResult<MacroExpansion, GetMacroExpansionError> = run { val includingFile = call.findIncludingFile() ?: return@run Err(GetMacroExpansionError.IncludingFileNotFound) val items = includingFile.stubChildrenOfType<RsExpandedElement>() Ok(MacroExpansion.Items(includingFile, items)) } return CachedValueProvider.Result.create(expansion, call.rustStructureOrAnyPsiModificationTracker) } override fun getExpandedFrom(element: RsExpandedElement): RsPossibleMacroCall? { // For in-memory expansions element.getUserData(RS_EXPANSION_MACRO_CALL)?.let { return it } val inner = inner return if (inner != null && inner.isExpansionModeNew) { inner.getExpandedFrom(element) } else { null } } override fun getContextOfMacroCallExpandedFrom(stubParent: RsFile): PsiElement? { val inner = inner return if (inner != null && inner.isExpansionModeNew) { inner.getContextOfMacroCallExpandedFrom(stubParent) } else { null } } override fun isExpansionFileOfCurrentProject(file: VirtualFile): Boolean = inner?.isExpansionFileOfCurrentProject(file) == true override fun getCrateForExpansionFile(file: VirtualFile): CratePersistentId? = inner?.getCrateForExpansionFile(file)?.first override fun reexpand() { inner?.reexpand() } override val macroExpansionMode: MacroExpansionMode get() = inner?.expansionMode ?: MacroExpansionMode.OLD override fun setUnitTestExpansionModeAndDirectory( mode: MacroExpansionScope, cacheDirectory: String, clearCacheBeforeDispose: Boolean ): Disposable { check(isUnitTestMode) val dir = updateDirs(cacheDirectory.ifEmpty { null }) val impl = MacroExpansionServiceBuilder.build(project, dir) this.dirs = dir this.inner = impl impl.macroExpansionMode = mode runWriteAction { ProjectRootManagerEx.getInstanceEx(project) .makeRootsChange(EmptyRunnable.getInstance(), false, true) } val saveCacheOnDispose = cacheDirectory.isNotEmpty() val disposable = impl.setupForUnitTests(saveCacheOnDispose, clearCacheBeforeDispose) Disposer.register(disposable) { this.inner = null this.dirs = null } return disposable } override fun updateInUnitTestMode() { inner?.updateInUnitTestMode() } override fun dispose() { inner?.dispose() isDisposed = true } } private fun updateDirs(projectDirName: String?): Dirs { return updateDirs0(projectDirName ?: randomLowercaseAlphabetic(8)) } private fun updateDirs0(projectDirName: String): Dirs { val baseProjectDir = getBaseMacroDir() .also { it.createDirectories() } return Dirs( baseProjectDir.resolve("$projectDirName.dat"), projectDirName ) } private data class Dirs( val dataFile: Path, val projectDirName: String ) { // Path in the MacroExpansionVFS val expansionDirPath: String get() = "/$MACRO_EXPANSION_VFS_ROOT/$projectDirName" } private object MacroExpansionServiceBuilder { fun build(project: Project, dirs: Dirs): MacroExpansionServiceImplInner { val dataFile = dirs.dataFile MacroExpansionManager.checkInvalidatedStorage() MacroExpansionFileSystemRootsLoader.loadProjectDirs() val loadedFsDir = load(dataFile) val vfs = MacroExpansionFileSystem.getInstance() if (loadedFsDir != null) { vfs.setDirectory(dirs.expansionDirPath, loadedFsDir) } else { MACRO_LOG.debug("Using fresh ExpandedMacroStorage") vfs.createDirectoryIfNotExistsOrDummy(dirs.expansionDirPath) } val expansionsDirVi = vfs.refreshAndFindFileByPath(dirs.expansionDirPath) ?: error("Impossible because the directory is just created; ${dirs.expansionDirPath}") return MacroExpansionServiceImplInner(project, dirs, expansionsDirVi) } private fun load(dataFile: Path): MacroExpansionFileSystem.FSItem.FSDir? { return try { dataFile.newInflaterDataInputStream().use { data -> MacroExpansionFileSystem.readFSItem(data, null) as? MacroExpansionFileSystem.FSItem.FSDir } } catch (e: java.nio.file.NoSuchFileException) { null } catch (e: Exception) { MACRO_LOG.warn(e) null } } } /** See [MacroExpansionFileSystem] docs for explanation of what happens here */ private object MacroExpansionFileSystemRootsLoader { @Synchronized fun loadProjectDirs() { val vfs = MacroExpansionFileSystem.getInstance() if (!vfs.exists("/$MACRO_EXPANSION_VFS_ROOT")) { val root = MacroExpansionFileSystem.FSItem.FSDir(null, MACRO_EXPANSION_VFS_ROOT) try { val dirs = getProjectListDataFile().newInflaterDataInputStream().use { data -> val count = data.readInt() (0 until count).map { val name = data.readUTF() val ts = data.readLong() MacroExpansionFileSystem.FSItem.FSDir.DummyDir(root, name, ts) } } for (dir in dirs) { root.addChild(dir) } } catch (ignored: java.nio.file.NoSuchFileException) { } catch (e: Exception) { MACRO_LOG.warn(e) } finally { vfs.setDirectory("/$MACRO_EXPANSION_VFS_ROOT", root, override = false) } } } fun saveProjectDirs() { val root = MacroExpansionFileSystem.getInstance().getDirectory("/$MACRO_EXPANSION_VFS_ROOT") ?: return val dataFile = getProjectListDataFile() Files.createDirectories(dataFile.parent) dataFile.newDeflaterDataOutputStream().use { data -> val children = root.copyChildren() data.writeInt(children.size) for (dir in children) { data.writeUTF(dir.name) data.writeLong(dir.timestamp) } } } private fun getProjectListDataFile(): Path = getBaseMacroDir().resolve("project_list.dat") } private class MacroExpansionServiceImplInner( private val project: Project, val dirs: Dirs, val expansionsDirVi: VirtualFile ) { val modificationTracker: SimpleModificationTracker = SimpleModificationTracker() @Volatile private var lastSavedStorageModCount: Long = modificationTracker.modificationCount private val lastUpdatedMacrosAt: MutableMap<CratePersistentId, Long> = hashMapOf() private val dataFile: Path get() = dirs.dataFile @TestOnly var macroExpansionMode: MacroExpansionScope = MacroExpansionScope.NONE fun isExpansionFileOfCurrentProject(file: VirtualFile): Boolean { return VfsUtil.isAncestor(expansionsDirVi, file, true) } fun getCrateForExpansionFile(virtualFile: VirtualFile): Pair<Int, String>? { if (!isExpansionFileOfCurrentProject(virtualFile)) return null val expansionName = virtualFile.name val crateId = virtualFile.parent.parent.parent.name.toIntOrNull() ?: return null return crateId to expansionName } suspend fun save() { if (lastSavedStorageModCount == modificationTracker.modificationCount) return @Suppress("BlockingMethodInNonBlockingContext") withContext(Dispatchers.IO) { // ensure dispatcher knows we are doing blocking IO // Using a buffer to avoid IO in the read action // BACKCOMPAT: 2020.1 use async read action and extract `runReadAction` from `withContext` val (buffer, modCount) = runReadAction { val buffer = BufferExposingByteArrayOutputStream(1024 * 1024) // average stdlib storage size DataOutputStream(buffer).use { data -> val dirToSave = MacroExpansionFileSystem.getInstance().getDirectory(dirs.expansionDirPath) ?: run { MACRO_LOG.warn("Expansion directory does not exist when saving the component: ${dirs.expansionDirPath}") MacroExpansionFileSystem.FSItem.FSDir(null, dirs.projectDirName) } MacroExpansionFileSystem.writeFSItem(data, dirToSave) } buffer to modificationTracker.modificationCount } Files.createDirectories(dataFile.parent) dataFile.newDeflaterDataOutputStream().use { it.write(buffer.internalBuffer) } MacroExpansionFileSystemRootsLoader.saveProjectDirs() lastSavedStorageModCount = modCount } } fun dispose() { // Can be invoked in heavy tests (e.g. RsRealProjectAnalysisTest) if (!isUnitTestMode) { releaseExpansionDirectory() } } private fun releaseExpansionDirectory() { val vfs = MacroExpansionFileSystem.getInstanceOrNull() ?: return // null means plugin unloading // See [MacroExpansionFileSystem] docs for explanation of what happens here RefreshQueue.getInstance().refresh(/* async = */ !isUnitTestMode, /* recursive = */ true, { vfs.makeDummy(dirs.expansionDirPath) }, listOf(expansionsDirVi)) } private fun cleanMacrosDirectoryAndStorage() { submitTask(object : Task.Backgroundable(project, "Cleaning outdated macros", false), RsTask { override fun run(indicator: ProgressIndicator) { if (!isUnitTestMode) checkReadAccessNotAllowed() val vfs = MacroExpansionFileSystem.getInstance() vfs.cleanDirectoryIfExists(dirs.expansionDirPath) vfs.createDirectoryIfNotExistsOrDummy(dirs.expansionDirPath) dirs.dataFile.delete() WriteAction.runAndWait<Throwable> { VfsUtil.markDirtyAndRefresh(false, true, true, expansionsDirVi) modificationTracker.incModificationCount() if (!project.isDisposed) { project.rustPsiManager.incRustStructureModificationCount() } } } override val runSyncInUnitTests: Boolean get() = true override val taskType: RsTask.TaskType get() = RsTask.TaskType.MACROS_CLEAR }) } private fun submitTask(task: Task.Backgroundable) { project.taskQueue.run(task) } fun stateLoaded(parentDisposable: Disposable) { check(!isUnitTestMode) // initialized manually at setUnitTestExpansionModeAndDirectory checkWriteAccessAllowed() setupListeners(parentDisposable) deleteOldExpansionDir() val cargoProjects = project.cargoProjects when { !cargoProjects.initialized -> { // Do nothing. If `CargoProjectService` is not initialized yet, it will make // roots change at the end of initialization (at the same write action where // `initialized = true` is assigned) and `processUnprocessedMacros` will be // triggered by `CargoProjectsService.CARGO_PROJECTS_TOPIC` MACRO_LOG.debug("Loading MacroExpansionManager finished - no events fired") } !cargoProjects.hasAtLeastOneValidProject -> { // `CargoProjectService` is already initialized, but there are no Rust projects. // No projects - no macros cleanMacrosDirectoryAndStorage() MACRO_LOG.debug("Loading MacroExpansionManager finished - no rust projects") } else -> { // `CargoProjectService` is already initialized and there are Rust projects. // Make roots change in order to refresh [RsIndexableSetContributor] // which value is changed after `inner` assigning ProjectRootManagerEx.getInstanceEx(project) .makeRootsChange(EmptyRunnable.getInstance(), false, true) processUnprocessedMacros() MACRO_LOG.debug("Loading MacroExpansionManager finished - roots change fired") } } } private fun setupListeners(disposable: Disposable) { val treeChangeListener = ChangedMacroUpdater() PsiManager.getInstance(project).addPsiTreeChangeListener(treeChangeListener, disposable) ApplicationManager.getApplication().addApplicationListener(treeChangeListener, disposable) val connect = project.messageBus.connect(disposable) connect.subscribe(CargoProjectsService.CARGO_PROJECTS_TOPIC, treeChangeListener) project.rustPsiManager.subscribeRustPsiChange(connect, treeChangeListener) connect.subscribe(RustProjectSettingsService.RUST_SETTINGS_TOPIC, object : RustProjectSettingsService.RustSettingsListener { override fun rustSettingsChanged(e: RustProjectSettingsService.RustSettingsChangedEvent) { if (!e.affectsCargoMetadata) { // if affect cargo metadata, will be invoked by CARGO_PROJECTS_TOPIC if (e.isChanged(RustProjectSettingsService.State::macroExpansionEngine)) { settingsChanged() } } } }) } // Previous plugin versions stored expansion to this directory // TODO remove it someday private fun deleteOldExpansionDir() { val oldDirPath = Paths.get(PathManager.getSystemPath()).resolve("rust_expanded_macros") if (oldDirPath.exists()) { oldDirPath.delete() val oldDirVFile = LocalFileSystem.getInstance().findFileByIoFile(oldDirPath.toFile()) if (oldDirVFile != null) { VfsUtil.markDirtyAndRefresh(true, true, true, oldDirVFile) } } } private fun settingsChanged() { if (!isExpansionModeNew) { cleanMacrosDirectoryAndStorage() } project.runWriteCommandAction { project.defMapService.scheduleRebuildAllDefMaps() project.rustPsiManager.incRustStructureModificationCount() } processUnprocessedMacros() } private enum class ChangedMacrosScope { NONE, CHANGED, UNPROCESSED } private inner class ChangedMacroUpdater : RsPsiTreeChangeAdapter(), RustPsiChangeListener, ApplicationListener, CargoProjectsListener { private var shouldProcessChangedMacrosOnWriteActionFinish: ChangedMacrosScope = ChangedMacrosScope.NONE override fun handleEvent(event: RsPsiTreeChangeEvent) { if (!isExpansionModeNew) return val file = event.file as? RsFile ?: return if (RsPsiManager.isIgnorePsiEvents(file)) return val virtualFile = file.virtualFile ?: return if (virtualFile !is VirtualFileWithId) return if (file.treeElement == null) return val element = when (event) { is ChildAddition.After -> event.child is ChildReplacement.After -> event.newChild is ChildrenChange.After -> if (!event.isGenericChange) event.parent else return else -> return } // Handle attribute rename `#[foo]` -> `#[bar]` val parentOrSelf = element.ancestorOrSelf<RsMetaItem>() ?: element val macroCalls = parentOrSelf.descendantsOfTypeOrSelf<RsPossibleMacroCall>() if (macroCalls.isNotEmpty()) { if (!MacroExpansionManager.isExpansionFile(virtualFile)) { scheduleChangedMacrosUpdate(ChangedMacrosScope.CHANGED) } } } override fun rustPsiChanged(file: PsiFile, element: PsiElement, isStructureModification: Boolean) { if (!isExpansionModeNew) return val shouldScheduleUpdate = (isStructureModification || element.ancestorOrSelf<RsPossibleMacroCall>()?.isTopLevelExpansion == true || RsProcMacroPsiUtil.canBeInProcMacroCallBody(element)) && file.virtualFile?.let { MacroExpansionManager.isExpansionFile(it) } == false if (shouldScheduleUpdate && file is RsFile) { scheduleChangedMacrosUpdate(ChangedMacrosScope.CHANGED) project.defMapService.onFileChanged(file) } } override fun cargoProjectsUpdated(service: CargoProjectsService, projects: Collection<CargoProject>) { scheduleChangedMacrosUpdate(ChangedMacrosScope.UNPROCESSED) } override fun afterWriteActionFinished(action: Any) { val shouldProcessChangedMacros = shouldProcessChangedMacrosOnWriteActionFinish shouldProcessChangedMacrosOnWriteActionFinish = ChangedMacrosScope.NONE when (shouldProcessChangedMacros) { ChangedMacrosScope.NONE -> Unit ChangedMacrosScope.CHANGED -> processChangedMacros() ChangedMacrosScope.UNPROCESSED -> processUnprocessedMacros() } } private fun scheduleChangedMacrosUpdate(scope: ChangedMacrosScope) { shouldProcessChangedMacrosOnWriteActionFinish = scope } } fun reexpand() { cleanMacrosDirectoryAndStorage() processUnprocessedMacros() } val expansionMode: MacroExpansionMode get() { return if (isUnitTestMode) { MacroExpansionMode.New(macroExpansionMode) } else { project.rustSettings.macroExpansionEngine.toMode() } } val isExpansionModeNew: Boolean get() = expansionMode is MacroExpansionMode.New private fun processUnprocessedMacros() { MACRO_LOG.info("processUnprocessedMacros") processMacros(RsTask.TaskType.MACROS_UNPROCESSED) } private fun processChangedMacros() { MACRO_LOG.info("processChangedMacros") // Fixes inplace rename when the renamed element is referenced from a macro call body if (isTemplateActiveInAnyEditor()) return processMacros(RsTask.TaskType.MACROS_FULL) } private fun processMacros(taskType: RsTask.TaskType) { if (!isExpansionModeNew) return val task = MacroExpansionTask( project, modificationTracker, lastUpdatedMacrosAt, dirs.projectDirName, taskType, ) submitTask(task) } private fun isTemplateActiveInAnyEditor(): Boolean { val tm = TemplateManager.getInstance(project) for (editor in FileEditorManager.getInstance(project).allEditors) { if (editor is TextEditor && tm.getActiveTemplate(editor.editor) != null) return true } return false } private fun <T> everChanged(result: T): CachedValueProvider.Result<T> = CachedValueProvider.Result.create(result, ModificationTracker.EVER_CHANGED) fun getExpansionFor(call: RsPossibleMacroCall): MacroExpansionCachedResult { if (expansionMode == MacroExpansionMode.DISABLED) { return everChanged(Err(GetMacroExpansionError.MacroExpansionIsDisabled)) } if (expansionMode == MacroExpansionMode.OLD) { if (call !is RsMacroCall) return everChanged(Err(GetMacroExpansionError.MemExpAttrMacro)) return expandMacroOld(call) } val containingFile: VirtualFile? = call.containingFile.virtualFile if (!call.isTopLevelExpansion || containingFile?.fileSystem?.isSupportedFs != true) { return expandMacroToMemoryFile(call, storeRangeMap = true) } val info = getModInfo(call.containingMod) ?: return everChanged(Err(GetMacroExpansionError.ModDataNotFound)) val macroIndex = info.getMacroIndex(call, info.crate) ?: return everChanged(Err(getReasonWhyExpansionFileNotFound(call, info.crate, info.defMap, null))) val expansionFile = getExpansionFile(info.defMap, macroIndex) ?: return everChanged(Err(getReasonWhyExpansionFileNotFound(call, info.crate, info.defMap, macroIndex))) val expansion = Ok(getExpansionFromExpandedFile(MacroExpansionContext.ITEM, expansionFile)!!) return if (call is RsMacroCall) { CachedValueProvider.Result.create(expansion, modificationTracker, call.modificationTracker) } else { CachedValueProvider.Result.create( expansion, modificationTracker, call.rustStructureOrAnyPsiModificationTracker ) } } fun getExpandedFrom(element: RsExpandedElement): RsPossibleMacroCall? { checkReadAccessAllowed() val parent = element.stubParent as? RsFile ?: return null return CachedValuesManager.getCachedValue(parent, GET_EXPANDED_FROM_KEY) { CachedValueProvider.Result.create( doGetExpandedFromForExpansionFile(parent), PsiModificationTracker.MODIFICATION_COUNT ) } } private fun doGetExpandedFromForExpansionFile(parent: RsFile): RsPossibleMacroCall? { val (defMap, expansionName) = getDefMapForExpansionFile(parent) ?: return null val (modData, macroIndex, kind) = defMap.expansionNameToMacroCall[expansionName] ?: return null val crate = project.crateGraph.findCrateById(defMap.crate) ?: return null // todo remove crate from RsModInfo val info = RsModInfo(project, defMap, modData, crate, dataPsiHelper = null) return info.findMacroCall(macroIndex, kind) } /** @see MacroExpansionManager.getContextOfMacroCallExpandedFrom */ fun getContextOfMacroCallExpandedFrom(stubParent: RsFile): PsiElement? { checkReadAccessAllowed() return CachedValuesManager.getCachedValue(stubParent, GET_CONTEXT_OF_MACRO_CALL_EXPANDED_FROM_KEY) { CachedValueProvider.Result.create( doGetContextOfMacroCallExpandedFrom(stubParent), PsiModificationTracker.MODIFICATION_COUNT ) } } fun doGetContextOfMacroCallExpandedFrom(stubParent: RsFile): PsiElement? { checkReadAccessAllowed() val (defMap, expansionName) = getDefMapForExpansionFile(stubParent) ?: return null val (modData, _, _) = defMap.expansionNameToMacroCall[expansionName] ?: return null return modData.toRsMod(project).singleOrNull() } private fun RsModInfo.findMacroCall(macroIndex: MacroIndex, kind: RsProcMacroKind): RsPossibleMacroCall? { val modIndex = modData.macroIndex val ownerIndex = if (kind == DERIVE) macroIndex.parent else macroIndex val parentIndex = ownerIndex.parent val parent = if (MacroIndex.equals(parentIndex, modIndex)) { modData.toRsMod(this).singleOrNull() } else { getExpansionFile(defMap, parentIndex) } ?: return null val owner = parent.findItemWithMacroIndex(ownerIndex.last, crate) return if (kind == FUNCTION_LIKE) { owner as? RsMacroCall } else { if (owner !is RsAttrProcMacroOwner) return null owner.findAttrOrDeriveMacroCall(macroIndex.last, crate) } } private fun RsAttrProcMacroOwner.findAttrOrDeriveMacroCall( macroIndexInParent: Int, crate: Crate, ): RsPossibleMacroCall? { val attr = ProcMacroAttribute.getProcMacroAttributeWithoutResolve( this, explicitCrate = crate, withDerives = true ) return when (attr) { is ProcMacroAttribute.Attr -> attr.attr is ProcMacroAttribute.Derive -> attr.derives.elementAtOrNull(macroIndexInParent) ProcMacroAttribute.None -> null } } private fun getExpansionFile(defMap: CrateDefMap, callIndex: MacroIndex): RsFile? { val expansionName = defMap.macroCallToExpansionName[callIndex] ?: return null // "/rust_expanded_macros/<projectId>/<crateId>/<mixHash>_<order>.rs" val expansionPath = "${defMap.crate}/${expansionNameToPath(expansionName)}" val file = expansionsDirVi.findFileByRelativePath(expansionPath) ?: return null if (!file.isValid) return null testAssert { file.fileType == RsFileType } return file.toPsiFile(project) as? RsFile } private fun getReasonWhyExpansionFileNotFound( call: RsPossibleMacroCall, crate: Crate, defMap: CrateDefMap, callIndex: MacroIndex? ): GetMacroExpansionError { if (!call.existsAfterExpansion(crate)) { return GetMacroExpansionError.CfgDisabled } val resolveResult = call.resolveToMacroWithoutPsiWithErr() val isProcMacro = resolveResult is Ok && resolveResult.ok.data is RsProcMacroData || resolveResult is Err && resolveResult.err is ResolveMacroWithoutPsiError.NoProcMacroArtifact val procMacroExperimentalFeature = when (val callKind = call.kind) { is RsPossibleMacroCallKind.MacroCall -> RsExperiments.FN_LIKE_PROC_MACROS is RsPossibleMacroCallKind.MetaItem -> if (RsProcMacroPsiUtil.canBeCustomDerive(callKind.meta)) { RsExperiments.DERIVE_PROC_MACROS } else { RsExperiments.ATTR_PROC_MACROS } } val procMacroExpansionIsDisabled = isProcMacro && (!isFeatureEnabled(EVALUATE_BUILD_SCRIPTS) || !isFeatureEnabled(PROC_MACROS) && !isFeatureEnabled(procMacroExperimentalFeature)) if (procMacroExpansionIsDisabled) { return GetMacroExpansionError.ExpansionError(ProcMacroExpansionError.ProcMacroExpansionIsDisabled) } resolveResult.unwrapOrElse { return it.toExpansionError() } if (callIndex == null) { return GetMacroExpansionError.NoMacroIndex } val expansionName = defMap.macroCallToExpansionName[callIndex] ?: return GetMacroExpansionError.ExpansionNameNotFound val mixHash = extractMixHashFromExpansionName(expansionName) val expansion = MacroExpansionSharedCache.getInstance().getExpansionIfCached(mixHash) // generic error if we don't know exact error ?: return GetMacroExpansionError.ExpansionFileNotFound val error = expansion.err() ?: return GetMacroExpansionError.InconsistentExpansionCacheAndVfs return GetMacroExpansionError.ExpansionError(error) } private fun getDefMapForExpansionFile(file: RsFile): Pair<CrateDefMap, String>? { val virtualFile = file.virtualFile ?: return null val (crateId, expansionName) = getCrateForExpansionFile(virtualFile) ?: return null val defMap = project.defMapService.getOrUpdateIfNeeded(crateId) ?: return null return defMap to expansionName } @TestOnly fun setupForUnitTests(saveCacheOnDispose: Boolean, clearCacheBeforeDispose: Boolean): Disposable { val disposable = Disposable { disposeUnitTest(saveCacheOnDispose, clearCacheBeforeDispose) } setupListeners(disposable) return disposable } @TestOnly fun updateInUnitTestMode() { processChangedMacros() } private fun disposeUnitTest(saveCacheOnDispose: Boolean, clearCacheBeforeDispose: Boolean) { check(isUnitTestMode) project.taskQueue.cancelTasks(RsTask.TaskType.MACROS_CLEAR) val taskQueue = project.taskQueue if (!taskQueue.isEmpty) { while (!taskQueue.isEmpty && !project.isDisposed) { PlatformTestUtil.dispatchAllEventsInIdeEventQueue() Thread.sleep(10) } } if (clearCacheBeforeDispose) { MacroExpansionFileSystem.getInstance().cleanDirectoryIfExists(dirs.expansionDirPath) } if (saveCacheOnDispose) { runBlocking { save() } } else { dirs.dataFile.delete() } releaseExpansionDirectory() } } private val GET_EXPANDED_FROM_KEY: Key<CachedValue<RsPossibleMacroCall?>> = Key.create("GET_EXPANDED_FROM_KEY") private val GET_CONTEXT_OF_MACRO_CALL_EXPANDED_FROM_KEY: Key<CachedValue<PsiElement?>> = Key.create("GET_CONTEXT_OF_MACRO_CALL_EXPANDED_FROM_KEY") /** * Ensures that [MacroExpansionManager] service is loaded when [CargoProjectsService] is initialized. * [MacroExpansionManager] should be loaded in order to add expansion directory to the index via * [RsIndexableSetContributor] */ class MacroExpansionManagerWaker : CargoProjectsListener { override fun cargoProjectsUpdated(service: CargoProjectsService, projects: Collection<CargoProject>) { if (projects.isNotEmpty()) { service.project.macroExpansionManager } } } private fun expandMacroOld(call: RsMacroCall): MacroExpansionCachedResult { // Most of std macros contain the only `impl`s which are not supported for now, so ignoring them if (call.containingCrate.origin == PackageOrigin.STDLIB) { return memExpansionResult(call, Err(GetMacroExpansionError.OldEngineStd)) } return expandMacroToMemoryFile( call, // Old macros already consume too much memory, don't force them to consume more by range maps storeRangeMap = isUnitTestMode // false ) } private fun expandMacroToMemoryFile(call: RsPossibleMacroCall, storeRangeMap: Boolean): MacroExpansionCachedResult { val modificationTrackers = getModificationTrackersForMemExpansion(call) val oldCachedResultSoftReference = call.getUserData(RS_EXPANSION_RESULT_SOFT) extractExpansionResult(oldCachedResultSoftReference, modificationTrackers)?.let { return it } val def = call.resolveToMacroWithoutPsiWithErr() .unwrapOrElse { return CachedValueProvider.Result(Err(it.toExpansionError()), modificationTrackers) } val crate = call.containingCrate if (crate is FakeCrate) return CachedValueProvider.Result(Err(GetMacroExpansionError.Unresolved), modificationTrackers) val result = FunctionLikeMacroExpander.forCrate(crate).expandMacro( def, call, storeRangeMap, useCache = true ).map { expansion -> val context = call.context as? RsElement expansion.elements.forEach { it.setExpandedFrom(call) if (context != null) { it.setExpandedElementContext(context) } } if (context != null) { // `lazy = false` in order to prevent deep stack overflow if the expansion is deep expansion.file.setRsFileContext(context, lazy = false) } expansion }.mapErr { when (it) { MacroExpansionAndParsingError.MacroCallSyntaxError -> GetMacroExpansionError.MacroCallSyntax is MacroExpansionAndParsingError.ParsingError -> GetMacroExpansionError.MemExpParsingError( it.expansionText, it.context ) is MacroExpansionAndParsingError.ExpansionError -> GetMacroExpansionError.ExpansionError(it.error) } } if (result is Ok) { val newCachedResult = CachedMemExpansionResult(result, modificationTrackers.modificationCount(), call) // We want to guarantee that only one expansion RsFile per macro call exists in the memory at a time. // That is, if someone holds a strong reference to expansion PSI, the SoftReference must not be cleared. // This is possible if the expansion RsFile holds a strong reference to the object under SoftReference. result.ok.file.putUserData(RS_EXPANSION_RESULT, newCachedResult) val newCachedResultSoftReference = SoftReference(newCachedResult) var prevReference = oldCachedResultSoftReference while (!call.replace(RS_EXPANSION_RESULT_SOFT, prevReference, newCachedResultSoftReference)) { prevReference = call.getUserData(RS_EXPANSION_RESULT_SOFT) extractExpansionResult(prevReference, modificationTrackers)?.let { return it } } } return CachedValueProvider.Result(result, modificationTrackers) } private val RS_EXPANSION_RESULT_SOFT: Key<SoftReference<CachedMemExpansionResult>> = Key("org.rust.lang.core.macros.RS_EXPANSION_RESULT_SOFT") private val RS_EXPANSION_RESULT: Key<CachedMemExpansionResult> = Key("org.rust.lang.core.macros.RS_EXPANSION_RESULT") private data class CachedMemExpansionResult( val result: RsResult<MacroExpansion, GetMacroExpansionError>, val modificationCount: Long, // Guarantees the macro call is retained in the memory if links to expansion PSI exist val call: RsPossibleMacroCall, ) private fun extractExpansionResult( cachedResultSoftReference: SoftReference<CachedMemExpansionResult>?, modificationTrackers: Array<Any>, ): CachedValueProvider.Result<RsResult<MacroExpansion, GetMacroExpansionError>>? { val cachedResult = cachedResultSoftReference?.get() if (cachedResult != null && cachedResult.modificationCount == modificationTrackers.modificationCount()) { return CachedValueProvider.Result(cachedResult.result, modificationTrackers) } return null } private fun memExpansionResult( call: RsPossibleMacroCall, result: RsResult<MacroExpansion, GetMacroExpansionError> ): MacroExpansionCachedResult { // Note: the cached result must be invalidated when `RsFile.cachedData` is invalidated val modificationTrackers = getModificationTrackersForMemExpansion(call) return CachedValueProvider.Result.create(result, modificationTrackers) } // Note: the cached result must be invalidated when `RsFile.cachedData` is invalidated private fun getModificationTrackersForMemExpansion(call: RsPossibleMacroCall): Array<Any> { val structureModTracker = call.rustStructureOrAnyPsiModificationTracker return when { // Non-physical PSI does not have event system, but we can track the file changes !call.isPhysical -> arrayOf(structureModTracker, call.containingFile) call is RsMacroCall -> arrayOf(structureModTracker, call.modificationTracker) else -> arrayOf(structureModTracker) } } private fun Array<Any>.modificationCount(): Long = sumOf { when (it) { is ModificationTracker -> it.modificationCount is PsiFile -> it.modificationStamp else -> error("Unknown dependency: ${it.javaClass}") } } private val RS_EXPANSION_MACRO_CALL = Key.create<RsPossibleMacroCall>("org.rust.lang.core.psi.RS_EXPANSION_MACRO_CALL") @VisibleForTesting fun RsExpandedElement.setExpandedFrom(call: RsPossibleMacroCall) { putUserData(RS_EXPANSION_MACRO_CALL, call) } private val VirtualFileSystem.isSupportedFs: Boolean get() = this is LocalFileSystem || this is MacroExpansionFileSystem enum class MacroExpansionScope { ALL, WORKSPACE, NONE } sealed class MacroExpansionMode { object Disabled : MacroExpansionMode() object Old : MacroExpansionMode() data class New(val scope: MacroExpansionScope) : MacroExpansionMode() companion object { @JvmField val DISABLED: Disabled = Disabled @JvmField val OLD: Old = Old @JvmField val NEW_ALL: New = New(MacroExpansionScope.ALL) } } private fun RustProjectSettingsService.MacroExpansionEngine.toMode(): MacroExpansionMode = when (this) { RustProjectSettingsService.MacroExpansionEngine.DISABLED -> MacroExpansionMode.DISABLED RustProjectSettingsService.MacroExpansionEngine.OLD, RustProjectSettingsService.MacroExpansionEngine.NEW -> MacroExpansionMode.NEW_ALL } val Project.macroExpansionManager: MacroExpansionManager get() = service() // BACKCOMPAT 2019.3: use serviceIfCreated val Project.macroExpansionManagerIfCreated: MacroExpansionManager? get() = this.getServiceIfCreated(MacroExpansionManager::class.java) // "abcdef_i.rs" → "a/b/abcdef_i.rs" fun expansionNameToPath(name: String): String = "${name[0]}/${name[1]}/$name"
mit
9cd4562efd85d5a69c259a060f5e5ae2
39.351131
132
0.682044
5.065667
false
false
false
false
googlecast/CastAndroidTvReceiver
app-kotlin/src/main/kotlin/com/google/sample/cast/atvreceiver/ui/PlaybackActivity.kt
1
1869
/** * Copyright 2022 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.sample.cast.atvreceiver.ui import android.R import androidx.fragment.app.FragmentActivity import android.os.Bundle import android.content.Intent import com.google.android.gms.cast.tv.CastReceiverContext /** * Loads [PlaybackVideoFragment]. */ class PlaybackActivity : FragmentActivity() { private var playbackVideoFragment: PlaybackVideoFragment? = null public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) playbackVideoFragment = PlaybackVideoFragment() if (savedInstanceState == null) { supportFragmentManager .beginTransaction() .replace(R.id.content, playbackVideoFragment!!) .commit() } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) val mediaManager = CastReceiverContext.getInstance().mediaManager if (mediaManager.onNewIntent(intent)) { // If the SDK recognizes the intent, you should early return. return } // If the SDK doesn’t recognize the intent, you can handle the intent with // your own logic. playbackVideoFragment!!.processIntent(intent) } }
apache-2.0
a12a43f047c5d9e2dca882ec11bf1721
34.923077
82
0.695769
4.6675
false
false
false
false
rejasupotaro/octodroid
app/src/main/kotlin/com/example/octodroid/activities/MainActivity.kt
1
4375
package com.example.octodroid.activities import android.content.Context import android.content.Intent import android.os.Bundle import android.support.design.widget.TabLayout import android.support.v4.view.ViewPager import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.View import butterknife.bindView import com.example.octodroid.R import com.example.octodroid.data.SessionManager import com.example.octodroid.data.prefs.OctodroidPrefs import com.example.octodroid.data.prefs.OctodroidPrefsSchema import com.example.octodroid.fragments.RepositoryEventListFragment import com.example.octodroid.intent.RequestCode import com.example.octodroid.views.components.ViewPagerAdapter import com.rejasupotaro.octodroid.models.Repository import com.rejasupotaro.octodroid.models.Resource import java.util.* class MainActivity : AppCompatActivity() { val tabLayout: TabLayout by bindView(R.id.repository_view_pager_tabs) val viewPager: ViewPager by bindView(R.id.repository_view_pager) val emptyViewContainer: View by bindView(R.id.empty_view_container) private val repositories = ArrayList<Repository>() private val onPageChangeListener = object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { val repository = repositories.get(position) setTitle(repository) } override fun onPageScrollStateChanged(state: Int) { } } protected override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (SessionManager.isLoggedIn(this)) { SessionManager.login(this) setupViews() } else { LoginActivity.launch(this) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> return true R.id.action_add_repository -> { RepositoryListActivity.launch(this) return true } R.id.action_logout -> { SessionManager.logout(this) LoginActivity.launch(this) return true } else -> return super.onOptionsItemSelected(item) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { RequestCode.ADD_REPOSITORY -> setupViews() else -> { } } } private fun setTitle(repository: Repository) { supportActionBar!!.title = repository.fullName } private fun setupViews() { val prefs = OctodroidPrefs.get(this) if (prefs.selectedSerializedRepositories.isEmpty()) { emptyViewContainer.visibility = View.VISIBLE title = "" } else { repositories.clear() emptyViewContainer.visibility = View.GONE val pagerAdapter = ViewPagerAdapter(supportFragmentManager) for (serializedRepositories in prefs.selectedSerializedRepositories) { val repository = Resource.fromJson(serializedRepositories, Repository::class.java) val fragment = RepositoryEventListFragment.newInstance(repository) pagerAdapter.addFragment(fragment, repository.name) repositories.add(repository) } viewPager.adapter = pagerAdapter viewPager.addOnPageChangeListener(onPageChangeListener) tabLayout.setupWithViewPager(viewPager) setTitle(repositories.get(0)) } findViewById(R.id.add_repository_button).setOnClickListener { RepositoryListActivity.launch(this) } } companion object { fun launch(context: Context) { val intent = Intent(context, MainActivity::class.java) intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) context.startActivity(intent) } } }
mit
f6a4c8c31a02ed51ef51466ef8f49ed3
32.914729
102
0.670629
4.882813
false
false
false
false
androidx/androidx
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/ComposableCallChecker.kt
3
25025
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin import androidx.compose.compiler.plugins.kotlin.analysis.ComposeWritableSlices import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType import org.jetbrains.kotlin.container.StorageComponentContainer import org.jetbrains.kotlin.container.useInstance import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.PropertyGetterDescriptor import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.descriptors.synthetic.FunctionInterfaceConstructorDescriptor import org.jetbrains.kotlin.extensions.StorageComponentContainerContributor import org.jetbrains.kotlin.js.resolve.diagnostics.findPsi import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.psi.KtAnnotatedExpression import org.jetbrains.kotlin.psi.KtAnnotationEntry import org.jetbrains.kotlin.psi.KtCallableReferenceExpression import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtLambdaExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPropertyAccessor import org.jetbrains.kotlin.psi.KtPsiUtil import org.jetbrains.kotlin.psi.KtTryExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getValueArgumentForExpression import org.jetbrains.kotlin.resolve.calls.checkers.AdditionalTypeChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallChecker import org.jetbrains.kotlin.resolve.calls.checkers.CallCheckerContext import org.jetbrains.kotlin.resolve.calls.context.CallPosition import org.jetbrains.kotlin.resolve.calls.context.ResolutionContext import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall import org.jetbrains.kotlin.resolve.inline.InlineUtil.isInlinedArgument import org.jetbrains.kotlin.resolve.sam.getSingleAbstractMethodOrNull import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.lowerIfFlexible import org.jetbrains.kotlin.types.typeUtil.builtIns import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.upperIfFlexible import org.jetbrains.kotlin.util.OperatorNameConventions open class ComposableCallChecker : CallChecker, AdditionalTypeChecker, StorageComponentContainerContributor { override fun registerModuleComponents( container: StorageComponentContainer, platform: TargetPlatform, moduleDescriptor: ModuleDescriptor ) { container.useInstance(this) } private fun checkInlineLambdaCall( resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext ) { if (resolvedCall !is VariableAsFunctionResolvedCall) return val descriptor = resolvedCall.variableCall.resultingDescriptor if (descriptor !is ValueParameterDescriptor) return if (descriptor.type.hasDisallowComposableCallsAnnotation()) return val function = descriptor.containingDeclaration if ( function is FunctionDescriptor && function.isInline && function.isMarkedAsComposable() ) { val bindingContext = context.trace.bindingContext var node: PsiElement? = reportOn loop@while (node != null) { when (node) { is KtLambdaExpression -> { val arg = getArgumentDescriptor(node.functionLiteral, bindingContext) if (arg?.type?.hasDisallowComposableCallsAnnotation() == true) { val parameterSrc = descriptor.findPsi() if (parameterSrc != null) { missingDisallowedComposableCallPropagation( context, parameterSrc, descriptor, arg ) } } } is KtFunction -> { val fn = bindingContext[BindingContext.FUNCTION, node] if (fn == function) { return } } } node = node.parent as? KtElement } } } override fun check( resolvedCall: ResolvedCall<*>, reportOn: PsiElement, context: CallCheckerContext ) { if (!resolvedCall.isComposableInvocation()) { checkInlineLambdaCall(resolvedCall, reportOn, context) return } val bindingContext = context.trace.bindingContext var node: PsiElement? = reportOn loop@while (node != null) { when (node) { is KtFunctionLiteral -> { // keep going, as this is a "KtFunction", but we actually want the // KtLambdaExpression } is KtLambdaExpression -> { val descriptor = bindingContext[BindingContext.FUNCTION, node.functionLiteral] if (descriptor == null) { illegalCall(context, reportOn) return } val composable = descriptor.isComposableCallable(bindingContext) if (composable) return val arg = getArgumentDescriptor(node.functionLiteral, bindingContext) if (arg?.type?.hasDisallowComposableCallsAnnotation() == true) { context.trace.record( ComposeWritableSlices.LAMBDA_CAPABLE_OF_COMPOSER_CAPTURE, descriptor, false ) context.trace.report( ComposeErrors.CAPTURED_COMPOSABLE_INVOCATION.on( reportOn, arg, arg.containingDeclaration ) ) return } // TODO(lmr): in future, we should check for CALLS_IN_PLACE contract val isInlined = isInlinedArgument( node.functionLiteral, bindingContext, true ) if (!isInlined) { illegalCall(context, reportOn) return } else { // since the function is inlined, we continue going up the PSI tree // until we find a composable context. We also mark this lambda context.trace.record( ComposeWritableSlices.LAMBDA_CAPABLE_OF_COMPOSER_CAPTURE, descriptor, true ) } } is KtTryExpression -> { val tryKeyword = node.tryKeyword if ( node.tryBlock.textRange.contains(reportOn.textRange) && tryKeyword != null ) { context.trace.report( ComposeErrors.ILLEGAL_TRY_CATCH_AROUND_COMPOSABLE.on(tryKeyword) ) } } is KtFunction -> { val descriptor = bindingContext[BindingContext.FUNCTION, node] if (descriptor == null) { illegalCall(context, reportOn) return } val composable = descriptor.isComposableCallable(bindingContext) if (!composable) { illegalCall(context, reportOn, node.nameIdentifier ?: node) } if (descriptor.hasReadonlyComposableAnnotation()) { // enforce that the original call was readonly if (!resolvedCall.isReadOnlyComposableInvocation()) { illegalCallMustBeReadonly( context, reportOn ) } } return } is KtProperty -> { // NOTE: since we're explicitly going down a different branch for // KtPropertyAccessor, the ONLY time we make it into this branch is when the // call was done in the initializer of the property/variable. val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, node] if ( descriptor !is LocalVariableDescriptor && node.annotationEntries.hasComposableAnnotation(bindingContext) ) { // composables shouldn't have initializers in the first place illegalCall(context, reportOn) return } } is KtPropertyAccessor -> { val property = node.property val isComposable = node .annotationEntries.hasComposableAnnotation(bindingContext) if (!isComposable) { illegalCall(context, reportOn, property.nameIdentifier ?: property) } val descriptor = bindingContext[BindingContext.PROPERTY_ACCESSOR, node] ?: return if (descriptor.hasReadonlyComposableAnnotation()) { // enforce that the original call was readonly if (!resolvedCall.isReadOnlyComposableInvocation()) { illegalCallMustBeReadonly( context, reportOn ) } } return } is KtCallableReferenceExpression -> { illegalComposableFunctionReference(context, node) return } is KtFile -> { // if we've made it this far, the call was made in a non-composable context. illegalCall(context, reportOn) return } is KtClass -> { // composable calls are never allowed in the initializers of a class illegalCall(context, reportOn) return } } node = node.parent as? KtElement } } private fun missingDisallowedComposableCallPropagation( context: CallCheckerContext, unmarkedParamEl: PsiElement, unmarkedParamDescriptor: ValueParameterDescriptor, markedParamDescriptor: ValueParameterDescriptor ) { context.trace.report( ComposeErrors.MISSING_DISALLOW_COMPOSABLE_CALLS_ANNOTATION.on( unmarkedParamEl, unmarkedParamDescriptor, markedParamDescriptor, markedParamDescriptor.containingDeclaration ) ) } private fun illegalCall( context: CallCheckerContext, callEl: PsiElement, functionEl: PsiElement? = null ) { context.trace.report(ComposeErrors.COMPOSABLE_INVOCATION.on(callEl)) if (functionEl != null) { context.trace.report(ComposeErrors.COMPOSABLE_EXPECTED.on(functionEl)) } } private fun illegalCallMustBeReadonly( context: CallCheckerContext, callEl: PsiElement ) { context.trace.report(ComposeErrors.NONREADONLY_CALL_IN_READONLY_COMPOSABLE.on(callEl)) } private fun illegalComposableFunctionReference( context: CallCheckerContext, refExpr: KtCallableReferenceExpression ) { context.trace.report(ComposeErrors.COMPOSABLE_FUNCTION_REFERENCE.on(refExpr)) } override fun checkType( expression: KtExpression, expressionType: KotlinType, expressionTypeWithSmartCast: KotlinType, c: ResolutionContext<*> ) { val bindingContext = c.trace.bindingContext val expectedType = c.expectedType if (expectedType === TypeUtils.NO_EXPECTED_TYPE) return if (expectedType === TypeUtils.UNIT_EXPECTED_TYPE) return if (expectedType.isAnyOrNullableAny()) return val expectedComposable = c.hasComposableExpectedType(expression) if (expression is KtLambdaExpression) { val descriptor = bindingContext[BindingContext.FUNCTION, expression.functionLiteral] ?: return val isComposable = descriptor.isComposableCallable(bindingContext) if (expectedComposable != isComposable) { val isInlineable = isInlinedArgument( expression.functionLiteral, c.trace.bindingContext, true ) if (isInlineable) return if (!expectedComposable && isComposable) { val inferred = c.trace.bindingContext[ ComposeWritableSlices.INFERRED_COMPOSABLE_DESCRIPTOR, descriptor ] == true if (inferred) { return } } val reportOn = if (expression.parent is KtAnnotatedExpression) expression.parent as KtExpression else expression c.trace.report( ComposeErrors.TYPE_MISMATCH.on( reportOn, expectedType, expressionTypeWithSmartCast ) ) } return } else { val nullableAnyType = expectedType.builtIns.nullableAnyType val anyType = expectedType.builtIns.anyType if (anyType == expectedType.lowerIfFlexible() && nullableAnyType == expectedType.upperIfFlexible() ) return val nullableNothingType = expectedType.builtIns.nullableNothingType // Handle assigning null to a nullable composable type if (expectedType.isMarkedNullable && expressionTypeWithSmartCast == nullableNothingType ) return val isComposable = expressionType.hasComposableAnnotation() if (expectedComposable != isComposable) { val reportOn = if (expression.parent is KtAnnotatedExpression) expression.parent as KtExpression else expression c.trace.report( ComposeErrors.TYPE_MISMATCH.on( reportOn, expectedType, expressionTypeWithSmartCast ) ) } return } } } fun ResolvedCall<*>.isReadOnlyComposableInvocation(): Boolean { if (this is VariableAsFunctionResolvedCall) { return false } return when (val candidateDescriptor = candidateDescriptor) { is ValueParameterDescriptor -> false is LocalVariableDescriptor -> false is PropertyDescriptor -> { val isGetter = valueArguments.isEmpty() val getter = candidateDescriptor.getter if (isGetter && getter != null) { getter.hasReadonlyComposableAnnotation() } else { false } } is PropertyGetterDescriptor -> candidateDescriptor.hasReadonlyComposableAnnotation() else -> candidateDescriptor.hasReadonlyComposableAnnotation() } } fun ResolvedCall<*>.isComposableInvocation(): Boolean { if (this is VariableAsFunctionResolvedCall) { if (variableCall.candidateDescriptor.type.hasComposableAnnotation()) return true if (functionCall.resultingDescriptor.hasComposableAnnotation()) return true return false } val candidateDescriptor = candidateDescriptor if (candidateDescriptor is FunctionDescriptor) { if (candidateDescriptor.isOperator && candidateDescriptor.name == OperatorNameConventions.INVOKE ) { if (dispatchReceiver?.type?.hasComposableAnnotation() == true) { return true } } } return when (candidateDescriptor) { is ValueParameterDescriptor -> false is LocalVariableDescriptor -> false is PropertyDescriptor -> { val isGetter = valueArguments.isEmpty() val getter = candidateDescriptor.getter if (isGetter && getter != null) { getter.hasComposableAnnotation() } else { false } } is PropertyGetterDescriptor -> candidateDescriptor.hasComposableAnnotation() else -> candidateDescriptor.hasComposableAnnotation() } } internal fun CallableDescriptor.isMarkedAsComposable(): Boolean { return when (this) { is PropertyGetterDescriptor -> hasComposableAnnotation() is ValueParameterDescriptor -> type.hasComposableAnnotation() is LocalVariableDescriptor -> type.hasComposableAnnotation() is PropertyDescriptor -> false else -> hasComposableAnnotation() } } // if you called this, it would need to be a composable call (composer, changed, etc.) fun CallableDescriptor.isComposableCallable(bindingContext: BindingContext): Boolean { // if it's marked as composable then we're done if (isMarkedAsComposable()) return true if ( this is FunctionDescriptor && bindingContext[ComposeWritableSlices.INFERRED_COMPOSABLE_DESCRIPTOR, this] == true ) { // even though it's not marked, it is inferred as so by the type system (by being passed // into a parameter marked as composable or a variable typed as one. This isn't much // different than being marked explicitly. return true } val functionLiteral = findPsi() as? KtFunctionLiteral // if it isn't a function literal then we are out of things to try. ?: return false if (functionLiteral.annotationEntries.hasComposableAnnotation(bindingContext)) { // in this case the function literal itself is being annotated as composable but the // annotation isn't in the descriptor itself return true } val lambdaExpr = functionLiteral.parent as? KtLambdaExpression if ( lambdaExpr != null && bindingContext[ComposeWritableSlices.INFERRED_COMPOSABLE_LITERAL, lambdaExpr] == true ) { // this lambda was marked as inferred to be composable return true } return false } // the body of this function can have composable calls in it, even if it itself is not // composable (it might capture a composer from the parent) fun FunctionDescriptor.allowsComposableCalls(bindingContext: BindingContext): Boolean { // if it's callable as a composable, then the answer is yes. if (isComposableCallable(bindingContext)) return true // otherwise, this is only true if it is a lambda which can be capable of composer // capture return bindingContext[ ComposeWritableSlices.LAMBDA_CAPABLE_OF_COMPOSER_CAPTURE, this ] == true } // The resolution context usually contains a call position, which records // the ResolvedCall and ValueParameterDescriptor for the call that we are // currently resolving. However, it is possible to end up in the // [ComposableCallChecker] or [ComposeTypeResolutionInterceptorExtension] // before the frontend computes the call position (e.g., when intercepting // function literal descriptors). // // In this case, the function below falls back to looking at the parse tree // for `expression`, to determine whether we are resolving a value argument. private fun ResolutionContext<*>.getValueArgumentPosition( expression: KtExpression ): CallPosition.ValueArgumentPosition? = when (val position = callPosition) { is CallPosition.ValueArgumentPosition -> position is CallPosition.Unknown -> getValueArgumentPositionFromPsi(expression, trace.bindingContext) else -> null } private fun getValueArgumentPositionFromPsi( expression: KtExpression, context: BindingContext, ): CallPosition.ValueArgumentPosition? { val resolvedCall = KtPsiUtil .getParentCallIfPresent(expression) .getResolvedCall(context) ?: return null val valueArgument = resolvedCall.call.getValueArgumentForExpression(expression) ?: return null val argumentMatch = resolvedCall.getArgumentMapping(valueArgument) as? ArgumentMatch ?: return null return CallPosition.ValueArgumentPosition( resolvedCall, argumentMatch.valueParameter, valueArgument ) } private fun getArgumentDescriptor( expression: KtExpression, context: BindingContext ): ValueParameterDescriptor? = getValueArgumentPositionFromPsi(expression, context)?.valueParameter internal fun ResolutionContext<*>.hasComposableExpectedType(expression: KtExpression): Boolean { if (expectedType.hasComposableAnnotation()) return true // The Kotlin frontend discards all annotations when computing function // types for fun interfaces. As a workaround we retrieve the fun interface // from the current value argument position and check the annotations on the // underlying method. if (expectedType.isSpecialType || !expectedType.isBuiltinFunctionalType) return false val position = getValueArgumentPosition(expression) ?: return false // There are two kinds of SAM conversions in Kotlin. // // - Explicit SAM conversion by calling a synthetic fun interface constructor, // i.e., `A { ... }` or `A(f)` for a fun interface `A`. // - Implicit SAM conversion by calling a function which expects a fun interface // in a value parameter. // // For explicit SAM conversion we check for the presence of a synthetic call, // otherwise we check the type of the value parameter descriptor. val callDescriptor = position.resolvedCall.resultingDescriptor.original val samDescriptor = if (callDescriptor is FunctionInterfaceConstructorDescriptor) { callDescriptor.baseDescriptorForSynthetic } else { position.valueParameter.type.constructor.declarationDescriptor as? ClassDescriptor ?: return false } return getSingleAbstractMethodOrNull(samDescriptor)?.hasComposableAnnotation() == true } fun List<KtAnnotationEntry>.hasComposableAnnotation(bindingContext: BindingContext): Boolean { for (entry in this) { val descriptor = bindingContext.get(BindingContext.ANNOTATION, entry) ?: continue if (descriptor.isComposableAnnotation) return true } return false }
apache-2.0
fa2779a17cce5eadddb9dcf94866219b
40.847826
99
0.612547
5.991142
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtsp/src/main/java/com/pedro/rtsp/utils/BitrateManager.kt
2
1200
/* * Copyright (C) 2021 pedroSG94. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pedro.rtsp.utils /** * Created by pedro on 10/07/19. * * Calculate video and audio bitrate per second */ open class BitrateManager(private val connectCheckerRtsp: ConnectCheckerRtsp) { private var bitrate: Long = 0 private var timeStamp = System.currentTimeMillis() @Synchronized fun calculateBitrate(size: Long) { bitrate += size val timeDiff = System.currentTimeMillis() - timeStamp if (timeDiff >= 1000) { connectCheckerRtsp.onNewBitrateRtsp((bitrate / (timeDiff / 1000f)).toLong()) timeStamp = System.currentTimeMillis() bitrate = 0 } } }
apache-2.0
3ac56512bd25a1673d4b5753ac16cc82
29.794872
82
0.719167
4.095563
false
false
false
false
world-federation-of-advertisers/panel-exchange-client
src/test/kotlin/org/wfanet/panelmatch/client/privatemembership/QueryIdGeneratorTest.kt
1
1760
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.panelmatch.client.privatemembership import com.google.common.truth.Truth.assertThat import com.google.common.truth.Truth.assertWithMessage import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class QueryIdGeneratorTest { @Test fun generatesEntireRange() { for (size in listOf(0, 1, 2, 10, 100)) { assertWithMessage("Range size: $size") .that(generateQueryIds(size).asSequence().toList()) .containsExactlyElementsIn(0 until size) } } @Test fun generatesAllSequences() { val size = 5 val numPermutations = 5 * 4 * 3 * 2 val iterationsPerPermutation = 100 val numIterations = numPermutations * iterationsPerPermutation val histogram = (0 until numIterations) .map { generateQueryIds(size).asSequence().toList() } .groupingBy { it } .eachCount() assertThat(histogram.size).isEqualTo(numPermutations) assertThat(histogram.values.minOrNull()).isAtLeast(iterationsPerPermutation / 2) assertThat(histogram.values.maxOrNull()).isAtMost(iterationsPerPermutation * 2) } }
apache-2.0
403df0d0dfb777e8ab6bdab19e3ca348
33.509804
84
0.729545
4.180523
false
true
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/fx/state/ReportDataHolder.kt
1
2117
package de.pbauerochse.worklogviewer.fx.state import de.pbauerochse.worklogviewer.details.FetchWorkItemsForIssueTask import de.pbauerochse.worklogviewer.events.EventBus import de.pbauerochse.worklogviewer.events.Subscribe import de.pbauerochse.worklogviewer.tasks.Tasks import de.pbauerochse.worklogviewer.timereport.IssueWithWorkItems import de.pbauerochse.worklogviewer.timereport.TimeReport import de.pbauerochse.worklogviewer.workitem.add.event.WorkItemAddedEvent import javafx.beans.property.SimpleObjectProperty /** * For static access to the current [TimeReport] * being displayed */ object ReportDataHolder { val currentTimeReportProperty = SimpleObjectProperty<TimeReport?>(null) init { EventBus.subscribe(this) } @Subscribe fun workItemCreated(event: WorkItemAddedEvent) { currentTimeReportProperty.value?.let { timeReport -> if (timeReport.reportParameters.timerange.contains(event.addedWorkItem.workDateAtLocalZone.toLocalDate())) { // only update report, when the added WorkItem is within the currently displayed range val fetchWorkItemsTask = FetchWorkItemsForIssueTask(event.issue, timeReport.reportParameters.timerange).apply { setOnSucceeded { updateTimeReport((it.source as FetchWorkItemsForIssueTask).value, timeReport) } } Tasks.startBackgroundTask(fetchWorkItemsTask) } } } /** * adds the given [IssueWithWorkItems] into the old [TimeReport] * by creating a copy with the [IssueWithWorkItems] applied * to the copy */ private fun updateTimeReport(issueWithWorkItems: IssueWithWorkItems, oldTimeReport: TimeReport) { val issueList = oldTimeReport.issues.toMutableList() // remove existing issue and add the current item issueList.removeIf { it.issue.id == issueWithWorkItems.issue.id } issueList.add(issueWithWorkItems) val updatedTimeReport = TimeReport(oldTimeReport.reportParameters, issueList) currentTimeReportProperty.set(updatedTimeReport) } }
mit
aa7bc82cbe88dab37aa5975d287b598c
39.730769
127
0.740198
4.822323
false
false
false
false
Gnar-Team/Gnar-bot
src/main/kotlin/xyz/gnarbot/gnar/listeners/BotListener.kt
1
4689
package xyz.gnarbot.gnar.listeners import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.events.* import net.dv8tion.jda.api.events.guild.GuildJoinEvent import net.dv8tion.jda.api.events.guild.GuildLeaveEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent import net.dv8tion.jda.api.hooks.ListenerAdapter import xyz.gnarbot.gnar.Bot import xyz.gnarbot.gnar.BotLoader import xyz.gnarbot.gnar.commands.Context import java.util.concurrent.TimeUnit class BotListener(private val bot: Bot) : ListenerAdapter() { override fun onGuildJoin(event: GuildJoinEvent) { Bot.getLogger().info("✅ Joined `" + event.guild.name + "`") } override fun onGuildMessageReceived(event: GuildMessageReceivedEvent) { if (event.author.isBot) { if (event.author === event.jda.selfUser) { if (bot.options.ofGuild(event.guild).command.isAutoDelete) { event.message.delete().queueAfter(10, TimeUnit.SECONDS) } } return } if ((event.message.contentRaw.startsWith('_') && event.message.contentRaw.endsWith('_')) || (event.message.contentRaw.startsWith(BotLoader.BOT.configuration.prefix) && (event.message.contentRaw.endsWith(BotLoader.BOT.configuration.prefix)))) { return } //Prevent markdown responses bot.commandDispatcher.handle(Context(bot, event)) } override fun onGuildMemberJoin(event: GuildMemberJoinEvent) { if (bot.isLoaded) { val options = bot.options.ofGuild(event.guild) // Autorole if (options.roles.autoRole != null) { val role = event.guild.getRoleById(options.roles.autoRole!!) // If role is null then unset if (role == null) { options.roles.autoRole = null return } // If bot cant interact with role then unset if (!event.guild.selfMember.canInteract(role) || !event.guild.selfMember.hasPermission(Permission.MANAGE_ROLES)) { options.roles.autoRole = null return } // Add the role to the member event.guild.addRoleToMember(event.member, role).reason("Auto-role").queue() } } } override fun onStatusChange(event: StatusChangeEvent) { Bot.getLogger().info(String.format("Shard #%d: Changed from %s to %s", event.jda.shardInfo.shardId, event.oldStatus, event.newStatus)) } override fun onGuildLeave(event: GuildLeaveEvent) { bot.players.destroy(event.guild) Bot.getLogger().info("❌ Left `" + event.guild.name + "`") } override fun onReady(event: ReadyEvent) { Bot.getLogger().info("JDA " + event.jda.shardInfo.shardId + " is ready.") } override fun onResume(event: ResumedEvent) { Bot.getLogger().info("JDA " + event.jda.shardInfo.shardId + " has resumed.") } override fun onReconnect(event: ReconnectedEvent) { Bot.getLogger().info("JDA " + event.jda.shardInfo.shardId + " has reconnected.") } override fun onDisconnect(event: DisconnectEvent) { if (event.isClosedByServer) { Bot.getLogger().info("JDA " + event.jda.shardInfo.shardId + " has disconnected (closed by server). " + "Code: " + event.serviceCloseFrame?.closeCode + " " + event.closeCode) } else { if (event.clientCloseFrame != null) { Bot.getLogger().info("JDA " + event.jda.shardInfo.shardId + " has disconnected. " + "Code: " + event.clientCloseFrame?.closeCode + " " + event.clientCloseFrame?.closeReason) } else { Bot.getLogger().info("JDA " + event.jda.shardInfo.shardId + " has disconnected. CCF Null. Code: " + event.closeCode) } } // Clean up all of the MusicManagers associated with that shard. val iterator = bot.players.registry.entries.iterator() while (iterator.hasNext()) { val entry = iterator.next() if (entry.value == null) { iterator.remove() Bot.getLogger().warn("Null manager for id " + entry.key) } else if (entry.value.guild.jda === event.jda) { entry.value.destroy() iterator.remove() } } } override fun onException(event: ExceptionEvent) { if (!event.isLogged) Bot.getLogger().error("Error thrown by JDA.", event.cause) } }
mit
45ec5e97a6b9782fea1f699a1920b1ca
39.387931
251
0.611099
4.228339
false
false
false
false
Hentioe/BloggerMini
app/src/main/kotlin/io/bluerain/tweets/ui/LoginActivity.kt
1
1799
package io.bluerain.tweets.ui import android.os.Bundle import android.view.View import android.widget.Toast import io.bluerain.tweets.R import io.bluerain.tweets.base.BaseActivity import io.bluerain.tweets.data.service.ServiceFactory import io.bluerain.tweets.presenter.LoginPresenter import io.bluerain.tweets.view.ILoginView import kotlinx.android.synthetic.main.activity_login_main.* import net.grandcentrix.thirtyinch.TiActivity /** * Created by hentioe on 17-4-22. * 登录界面 Activity */ class LoginActivity : BaseActivity<LoginPresenter, ILoginView>(), ILoginView { override fun initEvent() { } override fun success() { Launcher.EDITOR!!.putString(Launcher.PREFER_KEY_TOKEN, Launcher.TOKEN).commit() Launcher.EDITOR!!.putString(Launcher.PREFER_KEY_SERVER, Launcher.APT_ROOT).commit() Launcher.reLaunch(this) finish() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login_main) val actionBar = supportActionBar if (actionBar != null) { actionBar.title = "登录" } edt_login_server.setText(Launcher.PREFERENCES?.getString(Launcher.PREFER_KEY_SERVER, resources.getString(R.string.default_api_server))) } override fun providePresenter(): LoginPresenter { return LoginPresenter() } override fun initAll() { } fun login(view: View) { Launcher.APT_ROOT = edt_login_server.text.toString() ServiceFactory.init() presenter.login(edt_login_username.text.toString().trim(), edt_login_password.text.toString().trim()) } override fun onBackPressed() { super.onBackPressed() Launcher.DELAY = 500L } }
gpl-3.0
fb204754662c46e7715c2c728477f1a2
28.295082
109
0.6939
4.185012
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/sdk/HaskellSdkConfigurable.kt
1
2024
package org.jetbrains.haskell.sdk import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.projectRoots.AdditionalDataConfigurable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkAdditionalData import com.intellij.openapi.projectRoots.SdkModificator import javax.swing.* public class HaskellSdkConfigurable() : AdditionalDataConfigurable { private val myForm: HaskellSdkConfigurableForm = HaskellSdkConfigurableForm() private var mySdk: Sdk? = null override fun setSdk(sdk: Sdk?) { mySdk = sdk } override fun createComponent(): JComponent { return JPanel(); //myForm.getContentPanel() } override fun isModified(): Boolean { return myForm.isModified } override fun apply() { /* val newData = HaskellSdkAdditionalData(myForm.getCabalPath(), myForm.getCabalLibPath()) val modificator = mySdk!!.getSdkModificator() modificator.setSdkAdditionalData(newData) ApplicationManager.getApplication()!!.runWriteAction(object : Runnable { override fun run() { modificator.commitChanges() } }) */ myForm.isModified = false } override fun reset() { /* val data = mySdk!!.getSdkAdditionalData() val ghcData: HaskellSdkAdditionalData? if (data != null) { if (!(data is HaskellSdkAdditionalData)) { return } ghcData = (data as HaskellSdkAdditionalData) val cabalPath = ghcData?.getCabalPath() ?: "" val cabalDataPath = ghcData?.getCabalDataPath() ?: "" myForm.init(cabalPath, cabalDataPath) } else { myForm.init(HaskellSdkAdditionalData.getDefaultCabalPath(), HaskellSdkAdditionalData.getDefaultCabalDataPath()) } */ myForm.isModified = false } override fun disposeUIResources() { } }
apache-2.0
7fc4ac8855229f0e810efb1b1a248187
28.764706
95
0.645257
5.034826
false
true
false
false
jeffgbutler/mybatis-dynamic-sql
src/test/kotlin/nullability/test/LikeNotLikeTest.kt
1
6893
/* * Copyright 2016-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nullability.test import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class LikeNotLikeTest { @Test fun `Test That Null Like Causes Compile Error`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom fun testFunction() { countFrom(person) { where { firstName isLike null } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(9, 34))) } @Test fun `Test That Null Like When Present is OK`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom fun testFunction() { countFrom(person) { where { firstName isLikeWhenPresent null } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.hasErrors()).isFalse } @Test fun `Test That Null Not Like Causes Compile Error`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom fun testFunction() { val ids = listOf(4, null) countFrom(person) { where { firstName isNotLike null } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(10, 37))) } @Test fun `Test That Null Not Like When Present is OK`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom fun testFunction() { countFrom(person) { where { firstName isNotLikeWhenPresent null } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.hasErrors()).isFalse } @Test fun `Test That Null Elements Like Causes Compile Error`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom import org.mybatis.dynamic.sql.util.kotlin.elements.isLike fun testFunction() { countFrom(person) { where { firstName (isLike(null)) } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(10, 35))) } @Test fun `Test That Null Elements Like When Present is OK`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom import org.mybatis.dynamic.sql.util.kotlin.elements.isLikeWhenPresent fun testFunction() { countFrom(person) { where { firstName (isLikeWhenPresent(null)) } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.hasErrors()).isFalse } @Test fun `Test That Null Elements Not Like Causes Compile Error`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom import org.mybatis.dynamic.sql.util.kotlin.elements.isNotLike fun testFunction() { val ids = listOf(4, null) countFrom(person) { where { firstName (isNotLike(null)) } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.errorLocations()).isEqualTo(listOf(ErrorLocation(11, 38))) } @Test fun `Test That Null Elements Not Like When Present is OK`() { val source = """ package temp.kotlin.test import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom import org.mybatis.dynamic.sql.util.kotlin.elements.isNotLikeWhenPresent fun testFunction() { countFrom(person) { where { firstName (isNotLikeWhenPresent(null)) } } } """ val compilerMessageCollector = compile(source) assertThat(compilerMessageCollector.hasErrors()).isFalse } }
apache-2.0
a1462ac7cea357c6863d4d7c0a867d6e
35.860963
102
0.618889
5.206193
false
true
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem1865.kt
1
900
package leetcode class Problem1865 { class FindSumPairs(val nums1: IntArray, val nums2: IntArray) { private val nums2Map = mutableMapOf<Int, Int>() init { for (num in nums2) { nums2Map[num] = (nums2Map[num] ?: 0) + 1 } } fun add(index: Int, `val`: Int) { val oldCount = nums2Map[nums2[index]]!! - 1 if (oldCount == 0) { nums2Map -= nums2[index] } else { nums2Map[nums2[index]] = oldCount } nums2[index] += `val` nums2Map[nums2[index]] = (nums2Map[nums2[index]] ?: 0) + 1 } fun count(tot: Int): Int { var count = 0 for (num1 in nums1) { val num2 = tot - num1 count += nums2Map[num2] ?: 0 } return count } } }
mit
816e8234290e76439daa4dc290bdc108
26.272727
70
0.444444
3.76569
false
false
false
false
otormaigh/UL.DashNav
app/src/main/kotlin/ie/elliot/uldashnav/ui/view/CircleBar.kt
1
3698
package ie.elliot.uldashnav.ui.view import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import android.support.annotation.ColorRes import android.support.annotation.DimenRes import android.support.v4.content.ContextCompat import android.util.AttributeSet import android.view.View import android.view.animation.AccelerateDecelerateInterpolator import ie.elliot.uldashnav.R /** * @author Elliot Tormey * @since 11/02/2017 */ open class CircleBar(context: Context, attributeSet: AttributeSet?, @ColorRes defaultBackgroundRes: Int, @DimenRes private val radiusResId: Int) : View(context, attributeSet) { constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0, 0) private val backgroundPaint: Paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG) } private var barWidth: Float = 0f private val widthAnimator: ValueAnimator = ValueAnimator.ofFloat(0f, 1f) var shouldAnimate: Boolean = true var circleRadius: Float = 0f init { widthAnimator.duration = 700 widthAnimator.interpolator = AccelerateDecelerateInterpolator() @ColorRes val backgroundColour: Int if (attributeSet != null) { val typedArray = context.theme.obtainStyledAttributes(attributeSet, R.styleable.CircleBar, 0, 0) try { backgroundColour = typedArray.getColor(R.styleable.CircleBar_backgroundColour, defaultBackgroundRes) } finally { typedArray.recycle() } } else { backgroundColour = defaultBackgroundRes } circleRadius = context.resources.getDimension(radiusResId) backgroundPaint.style = Paint.Style.FILL backgroundPaint.color = ContextCompat.getColor(context, backgroundColour) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val minHeight: Int // If height is supplied by the user, respect its value. // Else set height to default value. if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY) { minHeight = View.MeasureSpec.getSize(heightMeasureSpec) } else { minHeight = Math.round(resources.getDimension(radiusResId)) * 2 } setMeasuredDimension(widthMeasureSpec, minHeight) setBarWidth(measuredWidth.toFloat(), shouldAnimate) } @SuppressLint("DrawAllocation") override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // Left corner canvas.drawCircle(circleRadius, circleRadius, circleRadius, backgroundPaint) // Right corner canvas.drawCircle(barWidth - circleRadius, circleRadius, circleRadius, backgroundPaint) // In-between canvas.drawRect(RectF(circleRadius, 0f, barWidth - circleRadius, height.toFloat()), backgroundPaint) } private fun setBarWidth(barWidth: Float, shouldAnimate: Boolean) { if (shouldAnimate) { setBarWidth(0f, false) widthAnimator.addUpdateListener({ animation -> val interpolation = animation.animatedValue as Float setBarWidth(interpolation * barWidth, false) }) if (!widthAnimator.isStarted) { widthAnimator.start() } } else { this.barWidth = barWidth postInvalidate() } } }
mit
c03e8605c22cf0e6cd57cf0f1252699b
34.912621
116
0.666306
5.107735
false
false
false
false
GLodi/GitNav
app/src/main/java/giuliolodi/gitnav/ui/base/BaseFragment.kt
1
2927
/* * Copyright 2017 GLodi * * 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 giuliolodi.gitnav.ui.base import android.content.Context import android.graphics.Bitmap import android.os.Bundle import android.support.v4.app.Fragment import android.view.View import giuliolodi.gitnav.di.component.ActivityComponent /** * Created by giulio on 28/05/2017. */ abstract class BaseFragment : Fragment(), BaseContract.View { private var mBaseActivity: BaseActivity? = null private var mBaseDrawerActivity: BaseDrawerActivity? = null /* * Each fragment will initialize its view inside initLayout, which is called * at the end of onViewCreated. */ override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initLayout(view, savedInstanceState) } protected abstract fun initLayout(view: View?, savedInstanceState: Bundle?) // Attach fragment and inform its activity. override fun onAttach(context: Context?) { super.onAttach(context) if (context is BaseActivity) { mBaseActivity = context mBaseActivity?.onFragmentAttached() } else if (context is BaseDrawerActivity) { mBaseDrawerActivity = context mBaseDrawerActivity?.onFragmentAttached() } } override fun onDetach() { mBaseActivity = null mBaseDrawerActivity = null super.onDetach() } fun getBaseActivity(): BaseActivity? { return mBaseActivity } fun getBaseDrawerActivity(): BaseDrawerActivity? { return mBaseDrawerActivity } fun getActivityComponent(): ActivityComponent? { if (mBaseActivity != null) return mBaseActivity?.getActivityComponent() else if (mBaseDrawerActivity != null) return mBaseDrawerActivity?.getActivityComponent() return null } // Not used here override fun initDrawer(username: String, fullName: String?, email: String?, profilePic: Bitmap?) { } override fun isNetworkAvailable(): Boolean { if (mBaseActivity != null) return mBaseActivity?.isNetworkAvailable()!! else return mBaseDrawerActivity?.isNetworkAvailable()!! } interface Callback { fun onFragmentAttached() fun onFragmentDetached(tag: String) } }
apache-2.0
17b7f12c70cef63d6bfd4d8926db379b
28.575758
103
0.683977
5.037866
false
false
false
false
divinespear/jpa-schema-gradle-plugin
src/functionalTest/kotlin/io/github/divinespear/plugin/test/functional/issue/Issue29GroovySpec.kt
1
2825
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.divinespear.plugin.test.functional.issue import io.github.divinespear.plugin.test.GroovyFunctionalSpec import io.github.divinespear.plugin.test.helper.runHibernateTask import io.kotest.matchers.and import io.kotest.matchers.should import io.kotest.matchers.string.contain class Issue29GroovySpec : GroovyFunctionalSpec() { private fun script(version: String) = """ plugins { id 'java-library' id 'io.github.divinespear.jpa-schema-generate' id 'io.spring.dependency-management' version '1.0.10.RELEASE' id 'org.springframework.boot' version '$version' } repositories { mavenCentral() } dependencies { compile 'org.springframework.boot:spring-boot-starter-data-jpa' runtime fileTree(dir: "../../../lib", include: "*.jar") } generateSchema { vendor = 'hibernate' packageToScan = [ 'io.github.divinespear.model' ] scriptAction = "drop-and-create" properties = [ 'hibernate.physical_naming_strategy' : 'org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy', 'hibernate.id.new_generator_mappings': 'false' ] targets { h2script { databaseProductName = "H2" databaseMajorVersion = 1 databaseMinorVersion = 4 createOutputFileName = "h2-create.sql" dropOutputFileName = "h2-drop.sql" } } } """.trimIndent() init { "spring-boot 1.5.10" should { "have spring dependencies" { runHibernateTask(script("1.5.10.RELEASE")) { it.output should (contain("org.springframework/spring-aspects/") and contain("org.springframework/spring-context/")) } } } "spring-boot 2.0.0" should { "have spring dependencies" { runHibernateTask(script("2.0.0.RELEASE")) { it.output should (contain("org.springframework/spring-aspects/") and contain("org.springframework/spring-context/")) } } } } }
apache-2.0
fd1d21e99ef754af418c3a9fcc6350a4
33.036145
126
0.676106
4.118076
false
true
false
false
da1z/intellij-community
platform/external-system-impl/src/com/intellij/openapi/externalSystem/configurationStore/ExternalSystemStreamProviderFactory.kt
1
5883
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.configurationStore import com.intellij.ProjectTopics import com.intellij.configurationStore.FileStorageAnnotation import com.intellij.configurationStore.StreamProviderFactory import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManager import com.intellij.openapi.module.Module import com.intellij.openapi.project.ModuleListener import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.isExternalStorageEnabled import com.intellij.openapi.roots.ProjectModelElement import com.intellij.openapi.startup.StartupManager import com.intellij.util.Function import org.jdom.Element import java.util.* import java.util.concurrent.atomic.AtomicBoolean private val EXTERNAL_MODULE_STORAGE_ANNOTATION = FileStorageAnnotation(StoragePathMacros.MODULE_FILE, false, ExternalModuleStorage::class.java) private val LOG = logger<ExternalSystemStreamProviderFactory>() // todo handle module rename internal class ExternalSystemStreamProviderFactory(private val project: Project) : StreamProviderFactory { val moduleStorage = ModuleFileSystemExternalSystemStorage(project) val fileStorage = ProjectFileSystemExternalSystemStorage(project) private var isStorageFlushInProgress = false private val isReimportOnMissedExternalStorageScheduled = AtomicBoolean(false) init { // flush on save to be sure that data is saved (it is easy to reimport if corrupted (force exit, blue screen), but we need to avoid it if possible) ApplicationManager.getApplication().messageBus .connect(project) .subscribe(ProjectEx.ProjectSaved.TOPIC, ProjectEx.ProjectSaved { if (it === project && !isStorageFlushInProgress && moduleStorage.isDirty) { isStorageFlushInProgress = true ApplicationManager.getApplication().executeOnPooledThread { try { LOG.runAndLogException { moduleStorage.forceSave() } } finally { isStorageFlushInProgress = false } } } }) project.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener { override fun moduleRemoved(project: Project, module: Module) { moduleStorage.remove(module.name) } override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) { for (module in modules) { moduleStorage.rename(oldNameProvider.`fun`(module), module.name) } } }) } override fun customizeStorageSpecs(component: PersistentStateComponent<*>, componentManager: ComponentManager, storages: List<Storage>, operation: StateStorageOperation): List<Storage>? { val project = componentManager as? Project ?: (componentManager as Module).project // we store isExternalStorageEnabled option in the project workspace file, so, for such components external storage is always disabled and not applicable if ((storages.size == 1 && storages.first().value == StoragePathMacros.WORKSPACE_FILE) || !project.isExternalStorageEnabled) { return null } if (componentManager is Project) { val fileSpec = storages.firstOrNull()?.value if (fileSpec == "libraries") { val result = ArrayList<Storage>(storages.size + 1) result.add(FileStorageAnnotation("$fileSpec.xml", false, ExternalProjectFilteringStorage::class.java)) result.addAll(storages) return result } } if (component !is ProjectModelElement) { return null } // Keep in mind - this call will require storage for module because module option values are used. // We cannot just check that module name exists in the nameToData - new external system module will be not in the nameToData because not yet saved. if (operation == StateStorageOperation.WRITE && component.externalSource == null) { return null } // on read we cannot check because on import module is just created and not yet marked as external system module, // so, we just add our storage as first and default storages in the end as fallback // on write default storages also returned, because default FileBasedStorage will remove data if component has external source val result = ArrayList<Storage>(storages.size + 1) if (componentManager is Project) { result.add(FileStorageAnnotation(storages.get(0).value, false, ExternalProjectStorage::class.java)) } else { result.add(EXTERNAL_MODULE_STORAGE_ANNOTATION) } result.addAll(storages) return result } fun readModuleData(name: String): Element? { if (!moduleStorage.hasSomeData && isReimportOnMissedExternalStorageScheduled.compareAndSet(false, true) && !project.isInitialized) { StartupManager.getInstance(project).runWhenProjectIsInitialized { val externalProjectsManager = ExternalProjectsManager.getInstance(project) externalProjectsManager.runWhenInitialized { externalProjectsManager.externalProjectsWatcher.markDirtyAllExternalProjects() } } } val result = moduleStorage.read(name) if (result == null) { // todo we must detect situation when module was really stored but file was somehow deleted by user / corrupted // now we use file-based storage, and, so, not easy to detect this situation on start (because all modules data stored not in the one file, but per file) } return result } }
apache-2.0
ae273a4581f44dcd828460c2fb31ff03
45.698413
189
0.747578
4.989822
false
false
false
false
apollostack/apollo-android
apollo-runtime-common/src/jvmMain/kotlin/com/apollographql/apollo3/subscription/AppSync.kt
1
2240
package com.apollographql.apollo3.subscription import com.apollographql.apollo3.api.internal.json.BufferedSinkJsonWriter import com.apollographql.apollo3.api.internal.json.Utils import okhttp3.HttpUrl import okio.Buffer /** * TODO: move to commonMain. * We're missing OkHttp HttpUrl */ object AppSync { /** * Helper method that builds the final web socket URL. It will append the authorization and payload arguments as query parameters. * * Example: * ``` * buildWebSocketUrl( * baseWebSocketUrl = "wss://example1234567890000.appsync-realtime-api.us-east-1.amazonaws.com/graphql", * // This example uses an API key. See the AppSync documentation for information on what to pass * authorization = mapOf( * "host" to "example1234567890000.appsync-api.us-east-1.amazonaws.com", * "x-api-key" to "da2-12345678901234567890123456" * ) * ) * ``` * * @param baseWebSocketUrl The base web socket URL. * @param authorization The authorization as per the AppSync documentation. * @param payload An optional payload. Defaults to an empty object. */ fun buildWebSocketUrl( baseWebSocketUrl: String, authorization: Map<String, Any?>, payload: Map<String, Any?> = emptyMap(), ): String = baseWebSocketUrl .let { url -> when { url.startsWith("ws://", ignoreCase = true) -> "http" + url.drop(2) url.startsWith("wss://", ignoreCase = true) -> "https" + url.drop(3) else -> url } } .let { HttpUrl.get(it) } .newBuilder() .setQueryParameter("header", authorization.base64Encode()) .setQueryParameter("payload", payload.base64Encode()) .build() .toString() .let { url -> when { url.startsWith("http://", ignoreCase = true) -> "ws" + url.drop(4) url.startsWith("https://", ignoreCase = true) -> "wss" + url.drop(5) else -> url } } private fun Map<String, Any?>.base64Encode(): String { val buffer = Buffer() Utils.writeToJson(this, BufferedSinkJsonWriter(buffer)) return buffer.readByteString().base64() } }
mit
2504551d3ba858045e5d15f27db82ea9
33.476923
132
0.618304
4.148148
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/util/AlertUtil.kt
1
928
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.AlertType import java.util.* object AlertUtil { fun decodeAlertSet(encoded: Byte): EnumSet<AlertType> { val encodedInt = encoded.toInt() and 0xff val alertList = AlertType.values() .filter { it != AlertType.UNKNOWN } // 0xff && <something> will always be true .filter { (it.value.toInt() and 0xff) and encodedInt != 0 } .toList() return if (alertList.isEmpty()) { EnumSet.noneOf(AlertType::class.java) } else { EnumSet.copyOf(alertList) } } fun encodeAlertSet(alertSet: EnumSet<AlertType>): Byte = alertSet.fold( 0, { out, slot -> out or (slot.value.toInt() and 0xff) } ).toByte() }
agpl-3.0
b9da6ad9b9f552a6b652465f3f334007
29.933333
91
0.596983
4.070175
false
false
false
false
Heiner1/AndroidAPS
medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.kt
1
25171
package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryDecoder import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDecodeStatus import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType.Companion.getByCode import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BasalProfile import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.BolusWizardDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.DailyTotalsDTO import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.experimental.and /** * This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes * management and modified/extended for AAPS. * * * Author: Andy {[email protected]} */ @Singleton class MedtronicPumpHistoryDecoder @Inject constructor( aapsLogger: AAPSLogger, medtronicUtil: MedtronicUtil, bitUtils: ByteUtil ) : MedtronicHistoryDecoder<PumpHistoryEntry>(aapsLogger, medtronicUtil, bitUtils) { //private var tbrPreviousRecord: PumpHistoryEntry? = null private var changeTimeRecord: PumpHistoryEntry? = null override fun createRecords(dataClearInput: MutableList<Byte>): MutableList<PumpHistoryEntry> { prepareStatistics() var counter = 0 var record = 0 var incompletePacket: Boolean val outList: MutableList<PumpHistoryEntry> = mutableListOf() var skipped: String? = null if (dataClearInput.size == 0) { aapsLogger.error(LTag.PUMPBTCOMM, "Empty page.") return outList } do { val opCode: Int = dataClearInput[counter].toInt() var special = false incompletePacket = false var skippedRecords = false if (opCode == 0) { counter++ if (skipped == null) skipped = "0x00" else skipped += " 0x00" continue } else { if (skipped != null) { aapsLogger.warn(LTag.PUMPBTCOMM, " ... Skipped $skipped") skipped = null skippedRecords = true } } if (skippedRecords) { aapsLogger.error(LTag.PUMPBTCOMM, "We had some skipped bytes, which might indicate error in pump history. Please report this problem.") } val entryType = getByCode(opCode.toByte()) val pe = PumpHistoryEntry() pe.setEntryType(medtronicUtil.medtronicPumpModel, entryType, if (entryType == PumpHistoryEntryType.UnknownBasePacket) opCode.toByte() else null) pe.offset = counter counter++ if (counter >= 1022) { break } val listRawData: MutableList<Byte> = ArrayList() listRawData.add(opCode.toByte()) if (entryType === PumpHistoryEntryType.UnabsorbedInsulin || entryType === PumpHistoryEntryType.UnabsorbedInsulin512) { val elements: Int = dataClearInput[counter].toInt() listRawData.add(elements.toByte()) counter++ val els = getUnsignedInt(elements) for (k in 0 until els - 2) { if (counter < 1022) { listRawData.add(dataClearInput[counter]) counter++ } } special = true } else { for (j in 0 until entryType.getTotalLength(medtronicUtil.medtronicPumpModel) - 1) { try { listRawData.add(dataClearInput[counter]) counter++ } catch (ex: Exception) { aapsLogger.error( LTag.PUMPBTCOMM, "OpCode: " + ByteUtil.shortHexString(opCode.toByte()) + ", Invalid package: " + ByteUtil.getHex(listRawData)) // throw ex; incompletePacket = true break } } if (incompletePacket) break } if (entryType === PumpHistoryEntryType.None) { aapsLogger.error(LTag.PUMPBTCOMM, "Error in code. We should have not come into this branch.") } else { if (pe.entryType === PumpHistoryEntryType.UnknownBasePacket) { pe.opCode = opCode.toByte() } if (entryType.getHeadLength(medtronicUtil.medtronicPumpModel) == 0) special = true pe.setData(listRawData, special) val decoded = decodeRecord(pe) if (decoded === RecordDecodeStatus.OK || decoded === RecordDecodeStatus.Ignored) { //Log.i(TAG, "#" + record + " " + decoded.getDescription() + " " + pe); } else { aapsLogger.warn(LTag.PUMPBTCOMM, "#" + record + " " + decoded.description + " " + pe) } addToStatistics(pe, decoded, null) record++ if (decoded === RecordDecodeStatus.OK) // we add only OK records, all others are ignored { outList.add(pe) } } } while (counter < dataClearInput.size) return outList } override fun decodeRecord(record: PumpHistoryEntry): RecordDecodeStatus { return try { decodeRecordInternal(record) } catch (ex: Exception) { aapsLogger.error(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, " Error decoding: type=%s, ex=%s", record.entryType.name, ex.message, ex)) //ex.printStackTrace() RecordDecodeStatus.Error } } private fun decodeRecordInternal(entry: PumpHistoryEntry): RecordDecodeStatus { if (entry.dateTimeLength > 0) { decodeDateTime(entry) } return when (entry.entryType) { PumpHistoryEntryType.ChangeBasalPattern, PumpHistoryEntryType.CalBGForPH, PumpHistoryEntryType.ChangeRemoteId, PumpHistoryEntryType.ClearAlarm, PumpHistoryEntryType.ChangeAlarmNotifyMode, PumpHistoryEntryType.EnableDisableRemote, PumpHistoryEntryType.BGReceived, PumpHistoryEntryType.SensorAlert, PumpHistoryEntryType.ChangeTimeFormat, PumpHistoryEntryType.ChangeReservoirWarningTime, PumpHistoryEntryType.ChangeBolusReminderEnable, PumpHistoryEntryType.SetBolusReminderTime, PumpHistoryEntryType.ChangeChildBlockEnable, PumpHistoryEntryType.BolusWizardEnabled, PumpHistoryEntryType.ChangeBGReminderOffset, PumpHistoryEntryType.ChangeAlarmClockTime, PumpHistoryEntryType.ChangeMeterId, PumpHistoryEntryType.ChangeParadigmID, PumpHistoryEntryType.JournalEntryMealMarker, PumpHistoryEntryType.JournalEntryExerciseMarker, PumpHistoryEntryType.DeleteBolusReminderTime, PumpHistoryEntryType.SetAutoOff, PumpHistoryEntryType.SelfTest, PumpHistoryEntryType.JournalEntryInsulinMarker, PumpHistoryEntryType.JournalEntryOtherMarker, PumpHistoryEntryType.BolusWizardSetup512, PumpHistoryEntryType.ChangeSensorSetup2, PumpHistoryEntryType.ChangeSensorAlarmSilenceConfig, PumpHistoryEntryType.ChangeSensorRateOfChangeAlertSetup, PumpHistoryEntryType.ChangeBolusScrollStepSize, PumpHistoryEntryType.BolusWizardSetup, PumpHistoryEntryType.ChangeVariableBolus, PumpHistoryEntryType.ChangeAudioBolus, PumpHistoryEntryType.ChangeBGReminderEnable, PumpHistoryEntryType.ChangeAlarmClockEnable, PumpHistoryEntryType.BolusReminder, PumpHistoryEntryType.DeleteAlarmClockTime, PumpHistoryEntryType.ChangeCarbUnits, PumpHistoryEntryType.ChangeWatchdogEnable, PumpHistoryEntryType.ChangeOtherDeviceID, PumpHistoryEntryType.ReadOtherDevicesIDs, PumpHistoryEntryType.BGReceived512, PumpHistoryEntryType.SensorStatus, PumpHistoryEntryType.ReadCaptureEventEnabled, PumpHistoryEntryType.ChangeCaptureEventEnable, PumpHistoryEntryType.ReadOtherDevicesStatus -> RecordDecodeStatus.OK PumpHistoryEntryType.Sensor_0x54, PumpHistoryEntryType.Sensor_0x55, PumpHistoryEntryType.Sensor_0x51, PumpHistoryEntryType.Sensor_0x52, PumpHistoryEntryType.EventUnknown_MM512_0x2e -> { aapsLogger.debug(LTag.PUMPBTCOMM, " -- ignored Unknown Pump Entry: $entry") RecordDecodeStatus.Ignored } PumpHistoryEntryType.UnabsorbedInsulin, PumpHistoryEntryType.UnabsorbedInsulin512 -> RecordDecodeStatus.Ignored PumpHistoryEntryType.DailyTotals522, PumpHistoryEntryType.DailyTotals523, PumpHistoryEntryType.DailyTotals515, PumpHistoryEntryType.EndResultTotals -> decodeDailyTotals(entry) PumpHistoryEntryType.ChangeBasalProfile_OldProfile, PumpHistoryEntryType.ChangeBasalProfile_NewProfile -> decodeBasalProfile(entry) PumpHistoryEntryType.BasalProfileStart -> decodeBasalProfileStart(entry) PumpHistoryEntryType.ChangeTime -> { changeTimeRecord = entry RecordDecodeStatus.OK } PumpHistoryEntryType.NewTimeSet -> { decodeChangeTime(entry) RecordDecodeStatus.OK } PumpHistoryEntryType.TempBasalDuration -> // decodeTempBasal(entry); RecordDecodeStatus.OK PumpHistoryEntryType.TempBasalRate -> // decodeTempBasal(entry); RecordDecodeStatus.OK PumpHistoryEntryType.Bolus -> { decodeBolus(entry) RecordDecodeStatus.OK } PumpHistoryEntryType.BatteryChange -> { decodeBatteryActivity(entry) RecordDecodeStatus.OK } PumpHistoryEntryType.LowReservoir -> { decodeLowReservoir(entry) RecordDecodeStatus.OK } PumpHistoryEntryType.LowBattery, PumpHistoryEntryType.SuspendPump, PumpHistoryEntryType.ResumePump, PumpHistoryEntryType.Rewind, PumpHistoryEntryType.NoDeliveryAlarm, PumpHistoryEntryType.ChangeTempBasalType, PumpHistoryEntryType.ChangeMaxBolus, PumpHistoryEntryType.ChangeMaxBasal, PumpHistoryEntryType.ClearSettings, PumpHistoryEntryType.SaveSettings -> RecordDecodeStatus.OK PumpHistoryEntryType.BolusWizard -> decodeBolusWizard(entry) PumpHistoryEntryType.BolusWizard512 -> decodeBolusWizard512(entry) PumpHistoryEntryType.Prime -> { decodePrime(entry) RecordDecodeStatus.OK } PumpHistoryEntryType.TempBasalCombined -> RecordDecodeStatus.Ignored PumpHistoryEntryType.None, PumpHistoryEntryType.UnknownBasePacket -> RecordDecodeStatus.Error else -> { aapsLogger.debug(LTag.PUMPBTCOMM, "Not supported: " + entry.entryType) RecordDecodeStatus.NotSupported } } } private fun decodeDailyTotals(entry: PumpHistoryEntry): RecordDecodeStatus { entry.addDecodedData("Raw Data", ByteUtil.getHex(entry.rawData)) val totals = DailyTotalsDTO(entry) entry.addDecodedData("Object", totals) return RecordDecodeStatus.OK } private fun decodeBasalProfile(entry: PumpHistoryEntry): RecordDecodeStatus { val basalProfile = BasalProfile(aapsLogger) basalProfile.setRawDataFromHistory(entry.body) entry.addDecodedData("Object", basalProfile) return RecordDecodeStatus.OK } private fun decodeChangeTime(entry: PumpHistoryEntry) { if (changeTimeRecord == null) return entry.displayableValue = entry.dateTimeString changeTimeRecord = null } private fun decodeBatteryActivity(entry: PumpHistoryEntry) { entry.displayableValue = if (entry.head[0] == 0.toByte()) "Battery Removed" else "Battery Replaced" } private fun decodeBasalProfileStart(entry: PumpHistoryEntry): RecordDecodeStatus { val body = entry.body val offset = body[0] * 1000 * 30 * 60 var rate: Float? = null val index = entry.head[0].toInt() if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { rate = body[1] * 0.025f } //LOG.info("Basal Profile Start: offset={}, rate={}, index={}, body_raw={}", offset, rate, index, body); return if (rate == null) { aapsLogger.warn(LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Basal Profile Start (ERROR): offset=%d, rate=%.3f, index=%d, body_raw=%s", offset, rate, index, ByteUtil.getHex(body))) RecordDecodeStatus.Error } else { entry.addDecodedData("Value", getFormattedFloat(rate, 3)) entry.displayableValue = getFormattedFloat(rate, 3) RecordDecodeStatus.OK } } private fun decodeBolusWizard(entry: PumpHistoryEntry): RecordDecodeStatus { val body = entry.body val dto = BolusWizardDTO() var bolusStrokes = 10.0f if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { // https://github.com/ps2/minimed_rf/blob/master/lib/minimed_rf/log_entries/bolus_wizard.rb#L102 bolusStrokes = 40.0f dto.carbs = ((body[1] and 0x0c.toByte()).toInt() shl 6) + body[0] dto.bloodGlucose = ((body[1] and 0x03).toInt() shl 8) + entry.head[0] dto.carbRatio = body[1] / 10.0f // carb_ratio (?) = (((self.body[2] & 0x07) << 8) + self.body[3]) / // 10.0s dto.insulinSensitivity = body[4].toFloat() dto.bgTargetLow = body[5].toInt() dto.bgTargetHigh = body[14].toInt() dto.correctionEstimate = (((body[9] and 0x38).toInt() shl 5) + body[6]) / bolusStrokes dto.foodEstimate = ((body[7].toInt() shl 8) + body[8]) / bolusStrokes dto.unabsorbedInsulin = ((body[10].toInt() shl 8) + body[11]) / bolusStrokes dto.bolusTotal = ((body[12].toInt() shl 8) + body[13]) / bolusStrokes } else { dto.bloodGlucose = (body.get(1) and 0x0F).toInt() shl 8 or entry.head.get(0).toInt() dto.carbs = body[0].toInt() dto.carbRatio = body[2].toFloat() dto.insulinSensitivity = body[3].toFloat() dto.bgTargetLow = body.get(4).toInt() dto.bgTargetHigh = body.get(12).toInt() dto.bolusTotal = body.get(11) / bolusStrokes dto.foodEstimate = body.get(6) / bolusStrokes dto.unabsorbedInsulin = body.get(9) / bolusStrokes dto.bolusTotal = body.get(11) / bolusStrokes dto.correctionEstimate = (body.get(7) + (body.get(5) and 0x0F)) / bolusStrokes } if (dto.bloodGlucose < 0) { dto.bloodGlucose = ByteUtil.convertUnsignedByteToInt(dto.bloodGlucose.toByte()) } dto.atechDateTime = entry.atechDateTime entry.addDecodedData("Object", dto) entry.displayableValue = dto.displayableValue return RecordDecodeStatus.OK } private fun decodeBolusWizard512(entry: PumpHistoryEntry): RecordDecodeStatus { val body = entry.body val dto = BolusWizardDTO() val bolusStrokes = 10.0f dto.bloodGlucose = (body.get(1) and 0x03).toInt() shl 8 or entry.head.get(0).toInt() dto.carbs = body.get(1).toInt() and 0xC shl 6 or body.get(0).toInt() // (int)body[0]; dto.carbRatio = body.get(2).toFloat() dto.insulinSensitivity = body.get(3).toFloat() dto.bgTargetLow = body.get(4).toInt() dto.foodEstimate = body.get(6) / 10.0f dto.correctionEstimate = (body.get(7) + (body.get(5) and 0x0F)) / bolusStrokes dto.unabsorbedInsulin = body.get(9) / bolusStrokes dto.bolusTotal = body.get(11) / bolusStrokes dto.bgTargetHigh = dto.bgTargetLow if (dto.bloodGlucose < 0) { dto.bloodGlucose = ByteUtil.convertUnsignedByteToInt(dto.bloodGlucose.toByte()) } dto.atechDateTime = entry.atechDateTime entry.addDecodedData("Object", dto) entry.displayableValue = dto.displayableValue return RecordDecodeStatus.OK } private fun decodeLowReservoir(entry: PumpHistoryEntry) { val amount = getUnsignedInt(entry.head.get(0)) * 1.0f / 10.0f * 2 entry.displayableValue = getFormattedValue(amount, 1) } private fun decodePrime(entry: PumpHistoryEntry) { val amount = ByteUtil.toInt(entry.head.get(2), entry.head.get(3)) / 10.0f val fixed = ByteUtil.toInt(entry.head.get(0), entry.head.get(1)) / 10.0f // amount = (double)(asUINT8(data[4]) << 2) / 40.0; // programmedAmount = (double)(asUINT8(data[2]) << 2) / 40.0; // primeType = programmedAmount == 0 ? "manual" : "fixed"; entry.addDecodedData("Amount", amount) entry.addDecodedData("FixedAmount", fixed) entry.displayableValue = ("Amount=" + getFormattedValue(amount, 2) + ", Fixed Amount=" + getFormattedValue(fixed, 2)) } private fun decodeChangeTempBasalType(entry: PumpHistoryEntry) { entry.addDecodedData("isPercent", ByteUtil.asUINT8(entry.getRawDataByIndex(0)) == 1) // index moved from 1 -> 0 } private fun decodeBgReceived(entry: PumpHistoryEntry) { entry.addDecodedData("amount", (ByteUtil.asUINT8(entry.getRawDataByIndex(0)) shl 3) + (ByteUtil.asUINT8(entry.getRawDataByIndex(3)) shr 5)) entry.addDecodedData("meter", ByteUtil.substring(entry.rawData, 6, 3)) // index moved from 1 -> 0 } private fun decodeCalBGForPH(entry: PumpHistoryEntry) { entry.addDecodedData("amount", (ByteUtil.asUINT8(entry.getRawDataByIndex(5)) and 0x80 shl 1) + ByteUtil.asUINT8(entry.getRawDataByIndex(0))) // index moved from 1 -> 0 } // private fun decodeNoDeliveryAlarm(entry: PumpHistoryEntry) { // //rawtype = asUINT8(data[1]); // // not sure if this is actually NoDelivery Alarm? // } override fun postProcess() {} override fun runPostDecodeTasks() { showStatistics() } private fun decodeBolus(entry: PumpHistoryEntry) { val bolus: BolusDTO? val data = entry.head if (MedtronicDeviceType.isSameDevice(medtronicUtil.medtronicPumpModel, MedtronicDeviceType.Medtronic_523andHigher)) { bolus = BolusDTO(atechDateTime = entry.atechDateTime, requestedAmount = ByteUtil.toInt(data.get(0), data.get(1)) / 40.0, deliveredAmount = ByteUtil.toInt(data.get(2), data.get(3)) / 40.0, duration = data.get(6) * 30) bolus.insulinOnBoard = ByteUtil.toInt(data.get(4), data.get(5)) / 40.0 } else { bolus = BolusDTO(atechDateTime = entry.atechDateTime, requestedAmount = ByteUtil.asUINT8(data.get(0)) / 10.0, deliveredAmount = ByteUtil.asUINT8(data.get(1)) / 10.0, duration = ByteUtil.asUINT8(data.get(2)) * 30) } bolus.bolusType = if (bolus.duration > 0) PumpBolusType.Extended else PumpBolusType.Normal entry.addDecodedData("Object", bolus) entry.displayableValue = bolus.displayableValue } fun decodeTempBasal(tbrPreviousRecord: PumpHistoryEntry, entry: PumpHistoryEntry) { var tbrRate: PumpHistoryEntry? = null var tbrDuration: PumpHistoryEntry? = null if (entry.entryType === PumpHistoryEntryType.TempBasalRate) { tbrRate = entry } else { tbrDuration = entry } if (tbrRate != null) { tbrDuration = tbrPreviousRecord } else { tbrRate = tbrPreviousRecord } val tbr = TempBasalPair( tbrRate.head.get(0), tbrRate.body.get(0), tbrDuration!!.head.get(0).toInt(), ByteUtil.asUINT8(tbrRate.datetime.get(4)) shr 3 == 0) entry.addDecodedData("Object", tbr) entry.displayableValue = tbr.description } private fun decodeDateTime(entry: PumpHistoryEntry) { if (entry.datetime.size == 0) { aapsLogger.warn(LTag.PUMPBTCOMM, "DateTime not set.") } val dt = entry.datetime if (entry.dateTimeLength == 5) { val seconds: Int = (dt.get(0) and 0x3F.toByte()).toInt() val minutes: Int = (dt.get(1) and 0x3F.toByte()).toInt() val hour: Int = (dt.get(2) and 0x1F).toInt() val month: Int = (dt.get(0).toInt() shr 4 and 0x0c) + (dt.get(1).toInt() shr 6 and 0x03) // ((dt[0] & 0xC0) >> 6) | ((dt[1] & 0xC0) >> 4); val dayOfMonth: Int = (dt.get(3) and 0x1F).toInt() val year = fix2DigitYear((dt.get(4) and 0x3F.toByte()).toInt()) // Assuming this is correct, need to verify. Otherwise this will be // a problem in 2016. entry.atechDateTime = DateTimeUtil.toATechDate(year, month, dayOfMonth, hour, minutes, seconds) } else if (entry.dateTimeLength == 2) { //val low = ByteUtil.asUINT8(dt.get(0)) and 0x1F val mhigh = ByteUtil.asUINT8(dt.get(0)) and 0xE0 shr 4 val mlow = ByteUtil.asUINT8(dt.get(1)) and 0x80 shr 7 val month = mhigh + mlow // int dayOfMonth = low + 1; val dayOfMonth: Int = (dt.get(0) and 0x1F).toInt() val year = 2000 + (ByteUtil.asUINT8(dt.get(1)) and 0x7F) var hour = 0 var minutes = 0 var seconds = 0 //LOG.debug("DT: {} {} {}", year, month, dayOfMonth); if (dayOfMonth == 32) { aapsLogger.warn( LTag.PUMPBTCOMM, String.format(Locale.ENGLISH, "Entry: Day 32 %s = [%s] %s", entry.entryType.name, ByteUtil.getHex(entry.rawData), entry)) } if (isEndResults(entry.entryType)) { hour = 23 minutes = 59 seconds = 59 } entry.atechDateTime = DateTimeUtil.toATechDate(year, month, dayOfMonth, hour, minutes, seconds) } else { aapsLogger.warn(LTag.PUMPBTCOMM, "Unknown datetime format: " + entry.dateTimeLength) } } private fun isEndResults(entryType: PumpHistoryEntryType?): Boolean { return entryType === PumpHistoryEntryType.EndResultTotals || entryType === PumpHistoryEntryType.DailyTotals515 || entryType === PumpHistoryEntryType.DailyTotals522 || entryType === PumpHistoryEntryType.DailyTotals523 } private fun fix2DigitYear(year: Int): Int { var yearInternal = year yearInternal += if (yearInternal > 90) { 1900 } else { 2000 } return yearInternal } companion object { private fun getFormattedValue(value: Float, decimals: Int): String { return String.format(Locale.ENGLISH, "%." + decimals + "f", value) } } }
agpl-3.0
403b2ed755d0eb7bd67e25e21eb7bcd4
45.962687
195
0.607683
4.528787
false
false
false
false
Maccimo/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ModuleOutputPackagingElementEntityImpl.kt
2
10955
package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableReferableWorkspaceEntity import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.referrersx import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ModuleOutputPackagingElementEntityImpl: ModuleOutputPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) @JvmField var _module: ModuleId? = null override val module: ModuleId? get() = _module override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ModuleOutputPackagingElementEntityData?): ModifiableWorkspaceEntityBase<ModuleOutputPackagingElementEntity>(), ModuleOutputPackagingElementEntity.Builder { constructor(): this(ModuleOutputPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ModuleOutputPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field ModuleOutputPackagingElementEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var module: ModuleId? get() = getEntityData().module set(value) { checkModificationAllowed() getEntityData().module = value changedProperty.add("module") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): ModuleOutputPackagingElementEntityData = result ?: super.getEntityData() as ModuleOutputPackagingElementEntityData override fun getEntityClass(): Class<ModuleOutputPackagingElementEntity> = ModuleOutputPackagingElementEntity::class.java } } class ModuleOutputPackagingElementEntityData : WorkspaceEntityData<ModuleOutputPackagingElementEntity>(), SoftLinkable { var module: ModuleId? = null override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() val optionalLink_module = module if (optionalLink_module != null) { result.add(optionalLink_module) } return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { val optionalLink_module = module if (optionalLink_module != null) { index.index(this, optionalLink_module) } } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val optionalLink_module = module if (optionalLink_module != null) { val removedItem_optionalLink_module = mutablePreviousSet.remove(optionalLink_module) if (!removedItem_optionalLink_module) { index.index(this, optionalLink_module) } } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false var module_data_optional = if (module != null) { val module___data = if (module!! == oldLink) { changed = true newLink as ModuleId } else { null } module___data } else { null } if (module_data_optional != null) { module = module_data_optional } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ModuleOutputPackagingElementEntity> { val modifiable = ModuleOutputPackagingElementEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ModuleOutputPackagingElementEntity { val entity = ModuleOutputPackagingElementEntityImpl() entity._module = module entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ModuleOutputPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ModuleOutputPackagingElementEntityData if (this.module != other.module) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ModuleOutputPackagingElementEntityData if (this.module != other.module) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + module.hashCode() return result } }
apache-2.0
8f2323bd586dfe9b527b3475c5a862a2
40.657795
220
0.644637
6.120112
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/junit/src/org/jetbrains/kotlin/idea/junit/KotlinMultiplatformJUnitRecognizer.kt
1
2635
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.junit import com.intellij.execution.JUnitRecognizer import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.asJava.elements.KtLightMethod import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.descriptors.TypeAliasDescriptor import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.caches.project.implementingDescriptors import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass import org.jetbrains.kotlin.resolve.descriptorUtil.classId import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.getDescriptorsFiltered class KotlinMultiplatformJUnitRecognizer : JUnitRecognizer() { override fun isTestAnnotated(method: PsiMethod): Boolean { if (method !is KtLightMethod) return false val origin = method.kotlinOrigin ?: return false if (!origin.module?.platform.isCommon()) return false val moduleDescriptor = origin.containingKtFile.findModuleDescriptor() val implModules = moduleDescriptor.implementingDescriptors if (implModules.isEmpty()) return false val methodDescriptor = origin.resolveToDescriptorIfAny() ?: return false return methodDescriptor.annotations.any { it.isExpectOfAnnotation("org.junit.Test", implModules) } } } private fun AnnotationDescriptor.isExpectOfAnnotation(fqName: String, implModules: Collection<ModuleDescriptor>): Boolean { val annotationClass = annotationClass ?: return false if (!annotationClass.isExpect) return false val classId = annotationClass.classId ?: return false val segments = classId.relativeClassName.pathSegments() return implModules .any { module -> module .getPackage(classId.packageFqName).memberScope .getDescriptorsFiltered(DescriptorKindFilter.CLASSIFIERS) { it == segments.first() } .filterIsInstance<TypeAliasDescriptor>() .any { it.classDescriptor?.fqNameSafe?.asString() == fqName } } }
apache-2.0
b6582618b08b2e5c0c13bd0d47487967
49.673077
158
0.779507
5.077071
false
false
false
false
Maccimo/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExternalSettingsImporter.kt
3
8012
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.service.project import com.google.gson.GsonBuilder import com.intellij.execution.BeforeRunTask import com.intellij.execution.BeforeRunTaskProvider import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.ProjectData import com.intellij.openapi.externalSystem.model.project.settings.ConfigurationData import com.intellij.openapi.externalSystem.service.execution.ExternalSystemBeforeRunTask import com.intellij.openapi.externalSystem.service.project.IdeModelsProvider import com.intellij.openapi.externalSystem.service.project.IdeModifiableModelsProvider import com.intellij.openapi.externalSystem.service.project.manage.ExternalProjectsManagerImpl import com.intellij.openapi.externalSystem.service.project.manage.ExternalSystemTaskActivator import com.intellij.openapi.externalSystem.service.project.settings.BeforeRunTaskImporter import com.intellij.openapi.externalSystem.service.project.settings.ConfigurationHandler import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.project.Project import com.intellij.project.stateStore import com.intellij.util.ObjectUtils.consumeIfCast import com.intellij.util.io.isDirectory import com.intellij.util.io.systemIndependentPath import org.jetbrains.plugins.gradle.execution.GradleBeforeRunTaskProvider import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.settings.GradleSettings import org.jetbrains.plugins.gradle.settings.TestRunner.* import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File import java.nio.file.Files class GradleBeforeRunTaskImporter: BeforeRunTaskImporter { override fun process(project: Project, modelsProvider: IdeModifiableModelsProvider, runConfiguration: RunConfiguration, beforeRunTasks: MutableList<BeforeRunTask<*>>, configurationData: MutableMap<String, Any>): MutableList<BeforeRunTask<*>> { val taskProvider = BeforeRunTaskProvider.getProvider(project, GradleBeforeRunTaskProvider.ID) ?: return beforeRunTasks val task = taskProvider.createTask(runConfiguration) ?: return beforeRunTasks task.taskExecutionSettings.apply { consumeIfCast(configurationData["taskName"], String::class.java) { taskNames = listOf(it) } consumeIfCast(configurationData["projectPath"], String::class.java) { externalProjectPath = it } } task.isEnabled = true val taskExists = beforeRunTasks.filterIsInstance<ExternalSystemBeforeRunTask>() .any { it.taskExecutionSettings.taskNames == task.taskExecutionSettings.taskNames && it.taskExecutionSettings.externalProjectPath == task.taskExecutionSettings.externalProjectPath } if (!taskExists) { beforeRunTasks.add(task) } return beforeRunTasks } override fun canImport(typeName: String): Boolean = "gradleTask" == typeName } class GradleTaskTriggersImporter : ConfigurationHandler { override fun apply(project: Project, modelsProvider: IdeModifiableModelsProvider, configuration: ConfigurationData) { val obj = configuration.find("taskTriggers") as? Map<*, *> ?: return val taskTriggerConfig = obj as Map<String, Collection<*>> val activator = ExternalProjectsManagerImpl.getInstance(project).taskActivator taskTriggerConfig.forEach { phaseName, tasks -> val phase = PHASE_MAP[phaseName] ?: return@forEach (tasks as Collection<Map<*, *>>).forEach { taskInfo -> val projectPath = taskInfo["projectPath"] val taskPath = taskInfo["taskPath"] if (projectPath is String && taskPath is String) { val newEntry = ExternalSystemTaskActivator.TaskActivationEntry(GradleConstants.SYSTEM_ID, phase, projectPath, taskPath) activator.removeTask(newEntry) activator.addTask(newEntry) } } } } companion object { private val PHASE_MAP = mapOf("beforeSync" to ExternalSystemTaskActivator.Phase.BEFORE_SYNC, "afterSync" to ExternalSystemTaskActivator.Phase.AFTER_SYNC, "beforeBuild" to ExternalSystemTaskActivator.Phase.BEFORE_COMPILE, "afterBuild" to ExternalSystemTaskActivator.Phase.AFTER_COMPILE, "beforeRebuild" to ExternalSystemTaskActivator.Phase.BEFORE_REBUILD, "afterRebuild" to ExternalSystemTaskActivator.Phase.AFTER_REBUILD) } } class ActionDelegateConfigImporter: ConfigurationHandler { override fun apply(project: Project, projectData: ProjectData?, modelsProvider: IdeModifiableModelsProvider, configuration: ConfigurationData) { val config = configuration.find("delegateActions") as? Map<String, *> ?: return val projectPath = projectData?.linkedExternalProjectPath ?: return val projectSettings = GradleSettings.getInstance(project).getLinkedProjectSettings(projectPath) ?: return consumeIfCast(config["delegateBuildRunToGradle"], java.lang.Boolean::class.java) { projectSettings.delegatedBuild = it.booleanValue() } consumeIfCast(config["testRunner"], String::class.java) { projectSettings.testRunner = (TEST_RUNNER_MAP[it] ?: return@consumeIfCast) } } companion object { private val TEST_RUNNER_MAP = mapOf( "PLATFORM" to PLATFORM, "GRADLE" to GRADLE, "CHOOSE_PER_TEST" to CHOOSE_PER_TEST ) } } class IDEAProjectFilesPostProcessor: ConfigurationHandler { override fun onSuccessImport(project: Project, projectData: ProjectData?, modelsProvider: IdeModelsProvider, configuration: ConfigurationData) { if (projectData == null) return val activator = ExternalProjectsManagerImpl.getInstance(project).taskActivator val taskActivationEntry = ExternalSystemTaskActivator.TaskActivationEntry(GradleConstants.SYSTEM_ID, ExternalSystemTaskActivator.Phase.AFTER_SYNC, projectData.linkedExternalProjectPath, "processIdeaSettings") activator.removeTask(taskActivationEntry) if (configuration.find("requiresPostprocessing") as? Boolean != true) { return } activator.addTask(taskActivationEntry) val f = File(projectData.linkedExternalProjectPath).toPath() val extProjectDir = if (f.isDirectory()) { f } else { f.parent } val dotIdeaDirPath = project.stateStore.projectFilePath.parent.systemIndependentPath val projectNode = ExternalSystemApiUtil.findProjectNode(project, projectData.owner, projectData.linkedExternalProjectPath) ?: return val moduleNodes = ExternalSystemApiUtil.getChildren(projectNode, ProjectKeys.MODULE) val sourceSetNodes = moduleNodes.flatMap { ExternalSystemApiUtil.getChildren(it, GradleSourceSetData.KEY) } val sourceSetsToImls = (moduleNodes + sourceSetNodes) .groupBy({ it.data.id }, { modelsProvider.findIdeModule(it.data)?.moduleFilePath }) .filterValues { it.isNotEmpty() } .mapValues { it.value.first() ?: "" } val layout = ProjectLayout(dotIdeaDirPath, sourceSetsToImls) val gson = GsonBuilder().setPrettyPrinting().create() Files.writeString(extProjectDir.resolve("layout.json"), gson.toJson(layout)) } class ProjectLayout(val ideaDirPath: String, val modulesMap: Map<String, String>) }
apache-2.0
3d9171a3459eb3905d3e5a580af8fcd1
47.563636
140
0.719296
5.199221
false
true
false
false
android/connectivity-samples
UwbRanging/app/src/main/java/com/google/apps/hellouwb/ui/send/SendViewModel.kt
1
4796
/* * * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.apps.hellouwb.ui.send import android.content.ContentResolver import android.net.Uri import androidx.core.net.toUri import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.google.apps.hellouwb.data.UwbRangingControlSource import com.google.apps.uwbranging.EndpointEvents import com.google.apps.uwbranging.UwbEndpoint import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import java.io.File private const val SEND_IMAGE_OP_CODE: Byte = 1 private const val RECEIVED_FILE_PATH = "received" class SendViewModel( private val uwbRangingControlSource: UwbRangingControlSource, private val contentResolver: ContentResolver ) : ViewModel() { private val _uiState: MutableStateFlow<SendUiState> = MutableStateFlow(SendUiState.InitialState) val uiState = _uiState.asStateFlow() private var sendJob: Job? = null private var receiveJob: Job? = null fun clear() { receiveJob?.cancel() receiveJob = startReceivingJob() sendJob?.cancel() sendJob = null _uiState.update { SendUiState.InitialState } } fun setSentUri(uri: Uri) { sendJob?.cancel() sendJob = null startSendingJob(uri)?.let { sendJob = it _uiState.update { SendUiState.SendingState(uri, null) } } } fun messageShown() { when (val state = _uiState.value) { is SendUiState.SendingState -> _uiState.update { state.copy(message = null) } else -> {} } } private fun startReceivingJob(): Job { return CoroutineScope(Dispatchers.IO).launch { uwbRangingControlSource .observeRangingResults() .filterIsInstance<EndpointEvents.EndpointMessage>() .filter { it.message[0] == SEND_IMAGE_OP_CODE } .collect { event -> onImageReceived(event.endpoint, event.message.sliceArray(1 until event.message.size)) } } } private fun onImageReceived(endpoint: UwbEndpoint, imageBytes: ByteArray) { receiveJob?.cancel() receiveJob = null val file = File.createTempFile(RECEIVED_FILE_PATH, null) contentResolver.openOutputStream(file.toUri())?.use { it.write(imageBytes) } _uiState.update { SendUiState.ReceivedState(endpoint, file.toUri()) } } private fun startSendingJob(uri: Uri): Job? { contentResolver.openInputStream(uri)?.use { inputStream -> val bytesToSend = byteArrayOf(SEND_IMAGE_OP_CODE) + inputStream.readBytes() val endpointsSent = mutableSetOf<UwbEndpoint>() return CoroutineScope(Dispatchers.IO).launch { uwbRangingControlSource .observeRangingResults() .filterNot { it.endpoint in endpointsSent } .filterIsInstance<EndpointEvents.PositionUpdated>() .collect { event -> event.position.azimuth?.let { azimuth -> if (azimuth.value > -5.0f && azimuth.value < 5.0f) { endpointsSent.add(event.endpoint) uwbRangingControlSource.sendOobMessage(event.endpoint, bytesToSend) val endpointDisplayName = event.endpoint.id.split("|")[0] _uiState.update { SendUiState.SendingState( uri, "Image has been sent to $endpointDisplayName" ) } } } } } } return null } init { clear() } companion object { fun provideFactory( uwbRangingControlSource: UwbRangingControlSource, contentResolver: ContentResolver ): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return SendViewModel(uwbRangingControlSource, contentResolver) as T } } } } sealed class SendUiState { data class SendingState(val sendImageUri: Uri, val message: String?) : SendUiState() data class ReceivedState(val endpoint: UwbEndpoint, val receivedImageUri: Uri) : SendUiState() object InitialState : SendUiState() }
apache-2.0
9c1839c7f48774132b31ab9654ef00a0
30.761589
98
0.685154
4.33243
false
false
false
false
android/renderscript-intrinsics-replacement-toolkit
test-app/src/main/java/com/google/android/renderscript_test/TimingTracker.kt
1
2423
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.renderscript_test class TimingTracker( private val numberOfIterations: Int = 1, private var numberOfIterationsToIgnore: Int = 0 ) { init { require(numberOfIterations > numberOfIterationsToIgnore) } private val timings = mutableMapOf<String, IntArray>() private var currentIteration: Int = 0 fun nextIteration() { currentIteration++ } fun <T> measure(name: String, workToTime: () -> T): T { val start = System.nanoTime() val t = workToTime() if (currentIteration >= numberOfIterationsToIgnore) { val end = System.nanoTime() val deltaInMicroseconds: Int = ((end - start) / 1000).toInt() val timing = timings.getOrPut(name) { IntArray(numberOfIterations - numberOfIterationsToIgnore) } timing[currentIteration - numberOfIterationsToIgnore] += deltaInMicroseconds } return t } fun report(): String { var minimum: Int = Int.MAX_VALUE for (timing in timings.values) { val m = timing.minOrNull() if (m != null && m < minimum) minimum = m } println(timings.map { (name, timing) -> name + ": " + timing.minOrNull() }.joinToString(separator = "\n")) var minimums = timings.map { (name, timing) -> name + ": " + timing.minOrNull() }.joinToString() var all = timings.map { (name, timing) -> name + ": " + timing.joinToString() }.joinToString() var normalized = timings.map { (name, timing) -> name + ": " + timing.joinToString { "%.2f".format(it.toFloat() / minimum) } } .joinToString() return "Minimums: $minimums\n\nAll: $all\n\nNormalized: $normalized\n" } }
apache-2.0
2ecb3fb368ed84ccc00b2f67e690d3aa
36.859375
121
0.624845
4.311388
false
false
false
false
nearbydelta/KoreanAnalyzer
kkma/src/main/kotlin/kr/bydelta/koala/kkma/dict.kt
1
6826
@file:JvmName("Util") @file:JvmMultifileClass package kr.bydelta.koala.kkma import kr.bydelta.koala.POS import kr.bydelta.koala.proc.CanCompileDict import kr.bydelta.koala.proc.DicEntry import org.snu.ids.kkma.dic.RawDicFileReader import org.snu.ids.kkma.dic.SimpleDicFileReader import org.snu.ids.kkma.dic.SimpleDicReader /** * 꼬꼬마 사용자사전을 실시간으로 반영하기 위한 Reader class 입니다. */ internal class UserDicReader : SimpleDicReader, Iterator<String?> { /** * 형태소 리스트. */ internal val morphemes = mutableListOf<String>() /** * 파일스트림 모사를 위한 현재위치 Marker. */ private var iterator: Iterator<String>? = morphemes.iterator() /** * 사전에 (형태소,품사) 리스트를 추가. * * @param map 추가할 (형태소,품사)리스트. */ operator fun plusAssign(map: List<Pair<String, String>>) { morphemes.addAll(map.map { "${it.first}/${it.second}" }) } /** * 사전 초기화 함수 */ override fun cleanup() {} /** * Returns `true` if the iteration has more elements. */ override fun hasNext(): Boolean = iterator?.hasNext() ?: false /** * Returns the next element in the iteration. */ override fun next(): String? = readLine() /** * 사전 1행씩 읽기 */ override fun readLine(): String? { if (iterator == null) reset() return if (iterator?.hasNext() == false) { null } else { iterator?.next() } } /** * 위치 초기화. (반복읽기를 위함.) */ fun reset() { iterator = morphemes.iterator() } } /** * 꼬꼬마 사용자사전을 제공하는 인터페이스입니다. * * @since 1.x */ object Dictionary : CanCompileDict { /** 원본사전의 어휘목록 **/ @JvmStatic private val systemDicByTag by lazy { org.snu.ids.kkma.dic.Dictionary.getInstance().asList.flatMap { it.filter { m -> m.tag != null } .map { m -> m.tag.toSejongPOS() to m.exp } // (품사, 표현식)으로 변환. }.groupBy { it.first }.mapValues { entry -> entry.value.map { it.second to it.first } } } /** 사용자사전 Reader **/ @JvmStatic private val userdic = UserDicReader() /** 사전 목록의 변화여부 **/ @JvmStatic private var isDicChanged = false /** * 사용자 사전에, (표면형,품사)의 여러 순서쌍을 추가합니다. * * @since 1.x * @param dict 추가할 (표면형, 품사)의 순서쌍들 (가변인자). 즉, [Pair]<[String], [POS]>들 */ override fun addUserDictionary(vararg dict: DicEntry) { if (dict.isNotEmpty()) { userdic += dict.mapNotNull { if (it.first.isNotEmpty()) it.first to it.second.fromSejongPOS() else null } isDicChanged = true } } /** * 사용자 사전에 등재된 모든 Item을 불러옵니다. * * @since 1.x * @return (형태소, 통합품사)의 Sequence. */ override fun getItems(): Set<DicEntry> = synchronized(this) { userdic.reset() userdic.asSequence().mapNotNull { val segments = it?.split('/') ?: emptyList() if (segments.size < 2) null else segments[0] to segments[1].toSejongPOS() }.toSet() } /** * 사전에 등재되어 있는지 확인하고, 사전에 없는단어만 반환합니다. * * @since 1.x * @param onlySystemDic 시스템 사전에서만 검색할지 결정합니다. * @param word 확인할 (형태소, 품사)들. * @return 사전에 없는 단어들, 즉, [Pair]<[String], [POS]>들. */ override fun getNotExists(onlySystemDic: Boolean, vararg word: DicEntry): Array<DicEntry> { val converted = word.map { Triple(it.first, it, it.second.fromSejongPOS()) } // Filter out existing morphemes! val (_, system) = if (onlySystemDic) Pair(emptyList(), converted) else converted.partition { userdic.morphemes.contains("${it.first}/${it.third}") } return system.groupBy { it.first }.flatMap { entry -> val (w, tags) = entry // Filter out existing morphemes! tags.filterNot { triple -> val mexp = org.snu.ids.kkma.dic.Dictionary.getInstance().getMExpression(w) mexp != null && triple.third in mexp.map { it.tag } }.map { it.second } }.toTypedArray() } /** * 원본 사전에 등재된 항목 중에서, 지정된 형태소의 항목만을 가져옵니다. (복합 품사 결합 형태는 제외) * * @since 1.x * @param filter 가져올 품사인지 판단하는 함수. * @return (형태소, 품사)의 Iterator. */ override fun getBaseEntries(filter: (POS) -> Boolean): Iterator<DicEntry> { return systemDicByTag.filterKeys(filter).flatMap { it.value }.iterator() } /** * 사전 다시읽기. * @since 1.x */ @JvmStatic internal fun reloadDic() { synchronized(userdic) { if (isDicChanged) { userdic.reset() org.snu.ids.kkma.dic.Dictionary.reload( listOf( SimpleDicFileReader("/dic/00nng.dic"), SimpleDicFileReader("/dic/01nnp.dic"), SimpleDicFileReader("/dic/02nnb.dic"), SimpleDicFileReader("/dic/03nr.dic"), SimpleDicFileReader("/dic/04np.dic"), SimpleDicFileReader("/dic/05comp.dic"), SimpleDicFileReader("/dic/06slang.dic"), SimpleDicFileReader("/dic/10verb.dic"), SimpleDicFileReader("/dic/11vx.dic"), SimpleDicFileReader("/dic/12xr.dic"), SimpleDicFileReader("/dic/20md.dic"), SimpleDicFileReader("/dic/21ma.dic"), SimpleDicFileReader("/dic/30ic.dic"), SimpleDicFileReader("/dic/40x.dic"), RawDicFileReader("/dic/50josa.dic"), RawDicFileReader("/dic/51eomi.dic"), RawDicFileReader("/dic/52raw.dic"), userdic ) ) isDicChanged = false } } } }
gpl-3.0
f1e43be606de3dc9ba4b3d4ff1eb655f
29.117647
98
0.513184
3.342764
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/util/ThrottleLiveData.kt
1
1165
package org.wordpress.android.util import androidx.lifecycle.MediatorLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class ThrottleLiveData<T> constructor( private val offset: Long = 100, private val coroutineScope: CoroutineScope, private val backgroundDispatcher: CoroutineDispatcher = Dispatchers.Default, private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main ) : MediatorLiveData<T>() { private var tempValue: T? = null private var currentJob: Job? = null override fun postValue(value: T) { if (tempValue == null || tempValue != value) { currentJob?.cancel() currentJob = coroutineScope.launch(backgroundDispatcher) { tempValue = value delay(offset) withContext(mainDispatcher) { tempValue = null super.postValue(value) } } } } }
gpl-2.0
b3a86b8ba98c13d17bdd7eb29ed4b05a
32.285714
80
0.677253
5.319635
false
false
false
false
android/architecture-components-samples
PagingWithNetworkSample/app/src/test-common/java/com/android/example/paging/pagingwithnetwork/repository/FakeRedditApi.kt
1
3071
/* * 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.repository import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost import retrofit2.http.Path import retrofit2.http.Query import java.io.IOException import kotlin.math.min /** * implements the RedditApi with controllable requests */ class FakeRedditApi : RedditApi { // subreddits keyed by name private val model = mutableMapOf<String, SubReddit>() var failureMsg: String? = null fun addPost(post: RedditPost) { val subreddit = model.getOrPut(post.subreddit) { SubReddit(items = arrayListOf()) } subreddit.items.add(post) } private fun findPosts( subreddit: String, limit: Int, after: String? = null, before: String? = null ): List<RedditApi.RedditChildrenResponse> { // only support paging forward if (before != null) return emptyList() val subReddit = findSubReddit(subreddit) val posts = subReddit.findPosts(limit, after) return posts.map { RedditApi.RedditChildrenResponse(it.copy()) } } private fun findSubReddit(subreddit: String) = model.getOrDefault(subreddit, SubReddit()) override suspend fun getTop( @Path("subreddit") subreddit: String, @Query("limit") limit: Int, @Query("after") after: String?, @Query("before") before: String? ): RedditApi.ListingResponse { failureMsg?.let { throw IOException(it) } val items = findPosts(subreddit, limit, after, before) val nextAfter = items.lastOrNull()?.data?.name return RedditApi.ListingResponse( RedditApi.ListingData( children = items, after = nextAfter, before = null ) ) } private class SubReddit(val items: MutableList<RedditPost> = arrayListOf()) { fun findPosts(limit: Int, after: String?): List<RedditPost> { if (after == null) { return items.subList(0, min(items.size, limit)) } val index = items.indexOfFirst { it.name == after } if (index == -1) { return emptyList() } val startPos = index + 1 return items.subList(startPos, min(items.size, startPos + limit)) } } }
apache-2.0
2805ea9522cbf2de26c197238cf67791
33.133333
81
0.639531
4.399713
false
false
false
false
blackwoodseven/kubernetes-node-slack-notifier
src/main/kotlin/com/blackwoodseven/kubernetes/node_watcher/KubernetesAPI.kt
1
2272
package com.blackwoodseven.kubernetes.node_watcher import mu.KotlinLogging import okhttp3.Credentials import okhttp3.OkHttpClient import okhttp3.Request import java.io.Reader import java.nio.charset.Charset import java.nio.file.FileSystem import java.nio.file.Files private val logger = KotlinLogging.logger {} class KubernetesAPI(private val hostname: String, username: String?, password: String?, fileSystem: FileSystem?) { private val client = OkHttpClient.Builder().addInterceptor { it.proceed( it.request().newBuilder() .addHeader("Authorization", buildAuthorizationString(username, password, fileSystem)) .build()) }.build() fun fetchNodeList(): NodeList { val initReq = Request.Builder() .url("https://$hostname/api/v1/nodes") .build() logger.info { "Requesting initial nodes..." } val response = client.newCall(initReq).execute() val body = response.body()?.string()!! return ResponseProcessor().parseNodeList(body) } fun fetchNodeChangeStream(resourceVersion: String): Reader? { val req = Request.Builder() .url("https://$hostname/api/v1/nodes?watch=true&resourceVersion=$resourceVersion") .build() logger.info { "Watching node changes..." } val resp = client.newCall(req).execute() return resp.body()?.charStream() } companion object { fun buildAuthorizationString(username: String?, password: String?, fileSystem: FileSystem?): String { return if (username != null && password != null) { Credentials.basic(username, password) } else if (fileSystem != null && Files.exists(fileSystem.getPath("/var/run/secrets/kubernetes.io/serviceaccount/token"))) { val tokenFile = fileSystem.getPath("/var/run/secrets/kubernetes.io/serviceaccount/token") val token = Files.readAllBytes(tokenFile).toString(Charset.forName("UTF-8")) "Bearer $token" } else { throw IllegalArgumentException("Authorization setup failed, you must provide either username/password, or a tokenfile") } } } }
apache-2.0
d0b1bf61b79f8c00c7bce5b5473b32a7
40.309091
135
0.639085
4.694215
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/SecondSampleEntityImpl.kt
1
6102
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import java.util.* import java.util.UUID import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class SecondSampleEntityImpl : SecondSampleEntity, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } override var intProperty: Int = 0 override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: SecondSampleEntityData?) : ModifiableWorkspaceEntityBase<SecondSampleEntity>(), SecondSampleEntity.Builder { constructor() : this(SecondSampleEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity SecondSampleEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as SecondSampleEntity this.entitySource = dataSource.entitySource this.intProperty = dataSource.intProperty if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var intProperty: Int get() = getEntityData().intProperty set(value) { checkModificationAllowed() getEntityData().intProperty = value changedProperty.add("intProperty") } override fun getEntityData(): SecondSampleEntityData = result ?: super.getEntityData() as SecondSampleEntityData override fun getEntityClass(): Class<SecondSampleEntity> = SecondSampleEntity::class.java } } class SecondSampleEntityData : WorkspaceEntityData<SecondSampleEntity>() { var intProperty: Int = 0 override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<SecondSampleEntity> { val modifiable = SecondSampleEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): SecondSampleEntity { val entity = SecondSampleEntityImpl() entity.intProperty = intProperty entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return SecondSampleEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return SecondSampleEntity(intProperty, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SecondSampleEntityData if (this.entitySource != other.entitySource) return false if (this.intProperty != other.intProperty) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as SecondSampleEntityData if (this.intProperty != other.intProperty) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + intProperty.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + intProperty.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
apache-2.0
dad28d04b73f1f921d3b36a252e2c4f6
30.947644
136
0.74156
5.497297
false
false
false
false
micolous/metrodroid
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/Station.kt
1
2864
/* * Station.kt * * Copyright (C) 2011 Eric Butler <[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 au.id.micolous.metrodroid.transit import au.id.micolous.metrodroid.multi.* import au.id.micolous.metrodroid.util.NumberUtils import au.id.micolous.metrodroid.util.Preferences @Parcelize class Station (val humanReadableId: String, val companyName: FormattedString? = null, val lineNames: List<FormattedString>? = emptyList(), private val stationNameRaw: FormattedString?, private val shortStationNameRaw: FormattedString? = null, val latitude: Float? = null, val longitude: Float? = null, val isUnknown: Boolean = false, val humanReadableLineIds: List<String> = emptyList(), private val attributes: MutableList<String> = mutableListOf()): Parcelable { fun getStationName(isShort: Boolean): FormattedString { var ret: FormattedString if (isShort) ret = shortStationNameRaw ?: stationNameRaw ?: Localizer.localizeFormatted(R.string.unknown_format, humanReadableId) else ret = stationNameRaw ?: shortStationNameRaw ?: Localizer.localizeFormatted(R.string.unknown_format, humanReadableId) if (showRawId() && stationNameRaw != null && stationNameRaw.unformatted != humanReadableId) ret += " [$humanReadableId]" for (attribute in attributes) ret += ", $attribute" return ret } val stationName: FormattedString? get() = getStationName(false) val shortStationName: FormattedString? get() = getStationName(true) fun hasLocation(): Boolean = (latitude != null && longitude != null) fun addAttribute(s: String): Station { attributes.add(s) return this } companion object { private fun showRawId() = Preferences.showRawStationIds fun unknown(id: String) = Station(humanReadableId = id, stationNameRaw = null, isUnknown = true) fun unknown(id: Int) = unknown(NumberUtils.intToHex(id)) fun nameOnly(name: String) = Station(stationNameRaw = FormattedString(name), humanReadableId = name) } }
gpl-3.0
22812a7018c76cb48f62c7f414ea4e8c
39.338028
128
0.674581
4.524487
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-7/app/src/main/java/dev/mfazio/pennydrop/adapters/PlayerSummaryAdapter.kt
4
1723
package dev.mfazio.pennydrop.adapters import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import dev.mfazio.pennydrop.R import dev.mfazio.pennydrop.types.PlayerSummary import dev.mfazio.pennydrop.databinding.PlayerSummaryListItemBinding class PlayerSummaryAdapter : ListAdapter<PlayerSummary, PlayerSummaryAdapter.PlayerSummaryViewHolder>( PlayerSummaryDiffCallback() ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayerSummaryViewHolder = PlayerSummaryViewHolder( DataBindingUtil.inflate( LayoutInflater.from(parent.context), R.layout.player_summary_list_item, parent, false ) ) override fun onBindViewHolder(viewHolder: PlayerSummaryViewHolder, position: Int) { viewHolder.bind(getItem(position)) } inner class PlayerSummaryViewHolder(private val binding: PlayerSummaryListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: PlayerSummary) { binding.apply { playerSummary = item executePendingBindings() } } } } private class PlayerSummaryDiffCallback : DiffUtil.ItemCallback<PlayerSummary>() { override fun areItemsTheSame(oldItem: PlayerSummary, newItem: PlayerSummary): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: PlayerSummary, newItem: PlayerSummary): Boolean = oldItem == newItem }
apache-2.0
8b1189d8b7caf3620281d2901d9ca94c
33.48
96
0.716193
5.285276
false
false
false
false
android/nowinandroid
lint/src/main/java/com/google/samples/apps/nowinandroid/lint/designsystem/DesignSystemDetector.kt
1
4786
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.lint.designsystem import com.android.tools.lint.client.api.UElementHandler import com.android.tools.lint.detector.api.Category import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Implementation import com.android.tools.lint.detector.api.Issue import com.android.tools.lint.detector.api.JavaContext import com.android.tools.lint.detector.api.Scope import com.android.tools.lint.detector.api.Severity import org.jetbrains.uast.UCallExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UQualifiedReferenceExpression /** * A detector that checks for incorrect usages of Compose Material APIs over equivalents in * the Now in Android design system module. */ @Suppress("UnstableApiUsage") class DesignSystemDetector : Detector(), Detector.UastScanner { override fun getApplicableUastTypes(): List<Class<out UElement>> { return listOf( UCallExpression::class.java, UQualifiedReferenceExpression::class.java ) } override fun createUastHandler(context: JavaContext): UElementHandler { return object : UElementHandler() { override fun visitCallExpression(node: UCallExpression) { val name = node.methodName ?: return val preferredName = METHOD_NAMES[name] ?: return reportIssue(context, node, name, preferredName) } override fun visitQualifiedReferenceExpression(node: UQualifiedReferenceExpression) { val name = node.receiver.asRenderString() val preferredName = RECEIVER_NAMES[name] ?: return reportIssue(context, node, name, preferredName) } } } companion object { @JvmField val ISSUE: Issue = Issue.create( id = "DesignSystem", briefDescription = "Design system", explanation = "This check highlights calls in code that use Compose Material " + "composables instead of equivalents from the Now in Android design system " + "module.", category = Category.CUSTOM_LINT_CHECKS, priority = 7, severity = Severity.ERROR, implementation = Implementation( DesignSystemDetector::class.java, Scope.JAVA_FILE_SCOPE ) ) // Unfortunately :lint is a Java module and thus can't depend on the :core-designsystem // Android module, so we can't use composable function references (eg. ::Button.name) // instead of hardcoded names. val METHOD_NAMES = mapOf( "MaterialTheme" to "NiaTheme", "Button" to "NiaFilledButton", "OutlinedButton" to "NiaOutlinedButton", "TextButton" to "NiaTextButton", "FilterChip" to "NiaFilterChip", "ElevatedFilterChip" to "NiaFilterChip", "DropdownMenu" to "NiaDropdownMenu", "NavigationBar" to "NiaNavigationBar", "NavigationBarItem" to "NiaNavigationBarItem", "NavigationRail" to "NiaNavigationRail", "NavigationRailItem" to "NiaNavigationRailItem", "TabRow" to "NiaTabRow", "Tab" to "NiaTab", "IconToggleButton" to "NiaToggleButton", "FilledIconToggleButton" to "NiaToggleButton", "FilledTonalIconToggleButton" to "NiaToggleButton", "OutlinedIconToggleButton" to "NiaToggleButton", "CenterAlignedTopAppBar" to "NiaTopAppBar", "SmallTopAppBar" to "NiaTopAppBar", "MediumTopAppBar" to "NiaTopAppBar", "LargeTopAppBar" to "NiaTopAppBar" ) val RECEIVER_NAMES = mapOf( "Icons" to "NiaIcons" ) fun reportIssue( context: JavaContext, node: UElement, name: String, preferredName: String ) { context.report( ISSUE, node, context.getLocation(node), "Using $name instead of $preferredName" ) } } }
apache-2.0
036cdf0d32c0ae7fa90e2e7528ef0867
38.883333
97
0.644588
4.923868
false
false
false
false
GunoH/intellij-community
java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/JavaSoftKeywordHighlighting.kt
8
2638
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.daemon.impl import com.intellij.codeHighlighting.TextEditorHighlightingPass import com.intellij.codeHighlighting.TextEditorHighlightingPassFactory import com.intellij.codeHighlighting.TextEditorHighlightingPassFactoryRegistrar import com.intellij.codeHighlighting.TextEditorHighlightingPassRegistrar import com.intellij.lang.java.lexer.JavaLexer import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import com.intellij.pom.java.LanguageLevel import com.intellij.psi.* internal class JavaSoftKeywordHighlightingPassFactory : TextEditorHighlightingPassFactory, TextEditorHighlightingPassFactoryRegistrar { override fun registerHighlightingPassFactory(registrar: TextEditorHighlightingPassRegistrar, project: Project) { registrar.registerTextEditorHighlightingPass(this, null, null, false, -1) } override fun createHighlightingPass(file: PsiFile, editor: Editor): TextEditorHighlightingPass? { return if (file is PsiJavaFile) JavaSoftKeywordHighlightingPass(file, editor.document) else null } } private class JavaSoftKeywordHighlightingPass(private val file: PsiJavaFile, document: Document) : TextEditorHighlightingPass(file.project, document) { private val results = mutableListOf<HighlightInfo>() override fun doCollectInformation(progress: ProgressIndicator) { if (file.name == PsiJavaModule.MODULE_INFO_FILE || file.languageLevel.isAtLeast(LanguageLevel.JDK_10)) { file.accept(JavaSoftKeywordHighlightingVisitor(results, file.languageLevel)) } } override fun doApplyInformationToEditor() { UpdateHighlightersUtil.setHighlightersToEditor(myProject, myDocument, 0, file.textLength, results, colorsScheme, id) } } private class JavaSoftKeywordHighlightingVisitor(private val results: MutableList<HighlightInfo>, private val level: LanguageLevel) : JavaRecursiveElementWalkingVisitor() { override fun visitKeyword(keyword: PsiKeyword) { if (JavaLexer.isSoftKeyword(keyword.node.chars, level)) { highlightAsKeyword(keyword) } else if (JavaTokenType.NON_SEALED_KEYWORD == keyword.tokenType) { highlightAsKeyword(keyword) } } private fun highlightAsKeyword(keyword: PsiKeyword) { val info = HighlightInfo.newHighlightInfo(JavaHighlightInfoTypes.JAVA_KEYWORD).range(keyword).create() if (info != null) { results += info } } }
apache-2.0
638a32bbbd3786172f83661b523d01a1
42.966667
140
0.805534
4.876155
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/actions/GitCheckoutActionGroup.kt
5
3421
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.actions import com.intellij.openapi.actionSystem.* import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsActions.ActionText import com.intellij.util.containers.ContainerUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.ui.VcsLogInternalDataKeys import git4idea.branch.GitBrancher import git4idea.i18n.GitBundle import git4idea.log.GitRefManager.LOCAL_BRANCH import git4idea.repo.GitRepository internal class GitCheckoutActionGroup : GitSingleCommitActionGroup(GitBundle.message("git.log.action.checkout.group"), false) { override fun getChildren(e: AnActionEvent, project: Project, repository: GitRepository, commit: CommitId): Array<AnAction> { val refNames = getRefNames(e, repository) val actions = ArrayList<AnAction>() for (refName in refNames) { actions.add(GitCheckoutAction(project, repository, refName, refName)) } val hasMultipleActions = actions.isNotEmpty() actions.add(getCheckoutRevisionAction(commit, hasMultipleActions)) val mainGroup = DefaultActionGroup(GitBundle.message("git.log.action.checkout.group"), actions) mainGroup.isPopup = hasMultipleActions return arrayOf(mainGroup) } private fun getCheckoutRevisionAction(commit: CommitId, useShortText: Boolean): AnAction { val hashString = commit.hash.toShortString() val checkoutRevisionText = if (useShortText) { GitBundle.message("git.log.action.checkout.revision.short.text", hashString) } else { GitBundle.message("git.log.action.checkout.revision.full.text", hashString) } val checkoutRevision = ActionManager.getInstance().getAction("Git.CheckoutRevision") return EmptyAction.wrap(checkoutRevision).also { it.templatePresentation.text = checkoutRevisionText } } private fun getRefNames(e: AnActionEvent, repository: GitRepository): List<String> { val refs = e.getData(VcsLogDataKeys.VCS_LOG_REFS) ?: emptyList() val localBranches = refs.filterTo(mutableListOf()) { it.type == LOCAL_BRANCH } e.getData(VcsLogInternalDataKeys.LOG_DATA)?.logProviders?.get(repository.root)?.let { provider -> ContainerUtil.sort(localBranches, provider.referenceManager.labelsOrderComparator) } val refNames = localBranches.map { it.name } val currentBranchName = repository.currentBranchName ?: return refNames return refNames.minus(currentBranchName) } } private fun checkout(project: Project, repository: GitRepository, hashOrRefName: String) { GitBrancher.getInstance(project).checkout(hashOrRefName, false, listOf(repository), null) } private class GitCheckoutAction(private val project: Project, private val repository: GitRepository, private val hashOrRefName: String, @ActionText actionText: String) : DumbAwareAction() { init { templatePresentation.setText(actionText, false) } override fun actionPerformed(e: AnActionEvent) { checkout(project, repository, hashOrRefName) } } class GitCheckoutRevisionAction : GitLogSingleCommitAction() { override fun actionPerformed(repository: GitRepository, commit: Hash) = checkout(repository.project, repository, commit.asString()) }
apache-2.0
45550fc500bfa9c4a7b0dfab5ffd5295
42.871795
133
0.755919
4.471895
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/FunctionUtils.kt
2
5669
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.inspections.collections import org.jetbrains.kotlin.builtins.DefaultBuiltIns import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.getFunctionalClassKind import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.inference.model.TypeVariableTypeConstructor import org.jetbrains.kotlin.resolve.calls.model.ReceiverKotlinCallArgument import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ResolvedLambdaAtom import org.jetbrains.kotlin.resolve.calls.model.unwrap import org.jetbrains.kotlin.resolve.calls.tower.NewResolvedCallImpl import org.jetbrains.kotlin.resolve.calls.tower.SubKotlinCallArgumentImpl import org.jetbrains.kotlin.resolve.calls.tower.receiverValue import org.jetbrains.kotlin.resolve.calls.util.getImplicitReceiverValue import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe import org.jetbrains.kotlin.resolve.descriptorUtil.isSubclassOf import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.utils.addToStdlib.safeAs fun KotlinType.isFunctionOfAnyKind() = constructor.declarationDescriptor?.getFunctionalClassKind() != null fun KotlinType?.isMap(builtIns: KotlinBuiltIns = DefaultBuiltIns.Instance): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.name.asString().endsWith("Map") && classDescriptor.isSubclassOf(builtIns.map) } fun KotlinType?.isIterable(builtIns: KotlinBuiltIns = DefaultBuiltIns.Instance): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.isListOrSet(builtIns) || classDescriptor.isSubclassOf(builtIns.iterable) } fun KotlinType?.isCollection(builtIns: KotlinBuiltIns = DefaultBuiltIns.Instance): Boolean { val classDescriptor = this?.constructor?.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.isListOrSet(builtIns) || classDescriptor.isSubclassOf(builtIns.collection) } private fun ClassDescriptor.isListOrSet(builtIns: KotlinBuiltIns): Boolean { val className = name.asString() return className.endsWith("List") && isSubclassOf(builtIns.list) || className.endsWith("Set") && isSubclassOf(builtIns.set) } fun KtCallExpression.isCalling(fqName: FqName, context: BindingContext? = null): Boolean { return isCalling(listOf(fqName), context) } fun KtCallExpression.isCalling(fqNames: List<FqName>, context: BindingContext? = null): Boolean { val calleeText = calleeExpression?.text ?: return false val targetFqNames = fqNames.filter { it.shortName().asString() == calleeText } if (targetFqNames.isEmpty()) return false val resolvedCall = getResolvedCall(context ?: safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)) ?: return false return targetFqNames.any { resolvedCall.isCalling(it) } } fun ResolvedCall<out CallableDescriptor>.isCalling(fqName: FqName): Boolean { return resultingDescriptor.fqNameSafe == fqName } fun ResolvedCall<*>.hasLastFunctionalParameterWithResult(context: BindingContext, predicate: (KotlinType) -> Boolean): Boolean { val lastParameter = resultingDescriptor.valueParameters.lastOrNull() ?: return false val lastArgument = valueArguments[lastParameter]?.arguments?.singleOrNull() ?: return false if (this is NewResolvedCallImpl<*>) { // TODO: looks like hack resolvedCallAtom.subResolvedAtoms?.firstOrNull { it is ResolvedLambdaAtom }.safeAs<ResolvedLambdaAtom>()?.let { lambdaAtom -> return lambdaAtom.unwrap().resultArgumentsInfo!!.nonErrorArguments.filterIsInstance<ReceiverKotlinCallArgument>().all { val type = it.receiverValue?.type?.let { type -> if (type.constructor is TypeVariableTypeConstructor) { it.safeAs<SubKotlinCallArgumentImpl>()?.valueArgument?.getArgumentExpression()?.getType(context) ?: type } else { type } } ?: return@all false predicate(type) } } } val functionalType = lastArgument.getArgumentExpression()?.getType(context) ?: return false // Both Function & KFunction must pass here if (!functionalType.isFunctionOfAnyKind()) return false val resultType = functionalType.arguments.lastOrNull()?.type ?: return false return predicate(resultType) } fun KtCallExpression.implicitReceiver(context: BindingContext): ImplicitReceiver? { return getResolvedCall(context)?.getImplicitReceiverValue() } fun KtCallExpression.receiverType(context: BindingContext): KotlinType? { return (getQualifiedExpressionForSelector())?.receiverExpression?.getResolvedCall(context)?.resultingDescriptor?.returnType ?: implicitReceiver(context)?.type }
apache-2.0
f20e9e3b4621c823b695dd4b19272bb8
52.990476
133
0.780737
5.075201
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/runner/KotlinMainMethodProvider.kt
1
3545
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeInsight.runner import com.intellij.codeInsight.runner.JavaMainMethodProvider import com.intellij.psi.PsiClass import com.intellij.psi.PsiMethod import org.jetbrains.kotlin.asJava.classes.KtLightClassBase import org.jetbrains.kotlin.asJava.classes.KtLightClassForFacadeBase import org.jetbrains.kotlin.asJava.classes.runReadAction import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.idea.base.codeInsight.KotlinMainFunctionDetector import org.jetbrains.kotlin.idea.base.codeInsight.hasMain import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.utils.addToStdlib.safeAs class KotlinMainMethodProvider: JavaMainMethodProvider { override fun isApplicable(clazz: PsiClass): Boolean { return clazz is KtLightClassBase } override fun hasMainMethod(clazz: PsiClass): Boolean { val lightClassBase = clazz.safeAs<KtLightClassBase>() val mainFunctionDetector = KotlinMainFunctionDetector.getInstance() if (lightClassBase is KtLightClassForFacadeBase) { return runReadAction { lightClassBase.files.any { mainFunctionDetector.hasMain(it) } } } val classOrObject = lightClassBase?.kotlinOrigin ?: return false return runReadAction { mainFunctionDetector.hasMain(classOrObject) } } override fun findMainInClass(clazz: PsiClass): PsiMethod? { val lightClassBase = clazz.safeAs<KtLightClassBase>() val mainFunctionDetector = KotlinMainFunctionDetector.getInstance() if (lightClassBase is KtLightClassForFacadeBase) { val files = lightClassBase.files for (file in files) { for (declaration in file.declarations) { when(declaration) { is KtNamedFunction -> if (runReadAction { mainFunctionDetector.isMain(declaration) }) { return declaration.toLightMethods().firstOrNull() } is KtClassOrObject -> findMainFunction(declaration, mainFunctionDetector)?.let { return it } } } } return null } val classOrObject = lightClassBase?.kotlinOrigin ?: return null return findMainFunction(classOrObject, mainFunctionDetector) } private fun findMainFunction( classOrObject: KtClassOrObject, mainFunctionDetector: KotlinMainFunctionDetector ): PsiMethod? { if (classOrObject is KtObjectDeclaration) { return findMainFunction(classOrObject, mainFunctionDetector) } for (companionObject in classOrObject.companionObjects) { findMainFunction(companionObject, mainFunctionDetector)?.let { return it } } return null } private fun findMainFunction(objectDeclaration: KtObjectDeclaration, mainFunctionDetector: KotlinMainFunctionDetector): PsiMethod? { if (objectDeclaration.isObjectLiteral()) return null val mainFunction = objectDeclaration.declarations.firstOrNull { it is KtNamedFunction && runReadAction { mainFunctionDetector.isMain(it) } } as? KtNamedFunction return mainFunction?.toLightMethods()?.firstOrNull() } }
apache-2.0
26d232a7d971e209bc84c950598930f7
45.051948
153
0.703808
5.811475
false
false
false
false
GunoH/intellij-community
plugins/repository-search/src/main/java/org/jetbrains/idea/reposearch/DependencySearchService.kt
2
7310
package org.jetbrains.idea.reposearch import com.intellij.openapi.Disposable import com.intellij.openapi.components.Service import com.intellij.openapi.components.service import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.progress.ProgressIndicatorProvider import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.util.ProgressWrapper import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.CollectionFactory import org.jetbrains.annotations.ApiStatus import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import org.jetbrains.concurrency.all import org.jetbrains.concurrency.resolvedPromise import org.jetbrains.idea.maven.onlinecompletion.model.MavenRepositoryArtifactInfo import java.util.* import java.util.concurrent.CompletableFuture import java.util.function.BiConsumer import java.util.function.Consumer typealias ResultConsumer = (RepositoryArtifactData) -> Unit @ApiStatus.Experimental @Service(Service.Level.PROJECT) class DependencySearchService(private val project: Project) : Disposable { private val executorService = AppExecutorUtil.createBoundedScheduledExecutorService("DependencySearch", 2) private val cache = CollectionFactory.createConcurrentWeakKeyWeakValueMap<String, CompletableFuture<Collection<RepositoryArtifactData>>>() private fun remoteProviders() = EP_NAME.extensionList.flatMap { it.getProviders(project) }.filter { !it.isLocal } private fun localProviders() = EP_NAME.extensionList.flatMap { it.getProviders(project) }.filter { it.isLocal } override fun dispose() { } private fun performSearch(cacheKey: String, parameters: SearchParameters, consumer: ResultConsumer, searchMethod: (DependencySearchProvider, ResultConsumer) -> Unit): Promise<Int> { if (parameters.useCache()) { val cachedValue = foundInCache(cacheKey, consumer) if (cachedValue != null) { return cachedValue } } val thisNewFuture = CompletableFuture<Collection<RepositoryArtifactData>>() val existingFuture = cache.putIfAbsent(cacheKey, thisNewFuture) if (existingFuture != null && parameters.useCache()) { return fillResultsFromCache(existingFuture, consumer) } val localResultSet: MutableSet<RepositoryArtifactData> = LinkedHashSet() localProviders().forEach { lp -> searchMethod(lp) { localResultSet.add(it) } } localResultSet.forEach(consumer) val remoteProviders = remoteProviders() if (parameters.isLocalOnly || remoteProviders.isEmpty()) { thisNewFuture.complete(localResultSet) return resolvedPromise(0) } val promises: MutableList<Promise<Void>> = ArrayList(remoteProviders.size) val resultSet = Collections.synchronizedSet(localResultSet) for (provider in remoteProviders) { val promise = AsyncPromise<Void>() promises.add(promise) val wrapper = ProgressWrapper.wrap(ProgressIndicatorProvider.getInstance().progressIndicator) executorService.submit { try { ProgressManager.getInstance().runProcess({ searchMethod(provider) { if (resultSet.add(it)) consumer(it) } promise.setResult(null) }, wrapper) } catch (e: Exception) { promise.setError(e) } } } return promises.all(resultSet, ignoreErrors = true).then { if (!resultSet.isEmpty() && existingFuture == null) { thisNewFuture.complete(resultSet) } return@then 1 } } fun suggestPrefix(groupId: String, artifactId: String, parameters: SearchParameters, consumer: Consumer<RepositoryArtifactData>) = suggestPrefix(groupId, artifactId, parameters) { consumer.accept(it) } fun suggestPrefix(groupId: String, artifactId: String, parameters: SearchParameters, consumer: ResultConsumer): Promise<Int> { val cacheKey = "_$groupId:$artifactId" return performSearch(cacheKey, parameters, consumer) { p, c -> p.suggestPrefix(groupId, artifactId).get() .forEach(c) // TODO A consumer here is used synchronously... } } fun fulltextSearch(searchString: String, parameters: SearchParameters, consumer: Consumer<RepositoryArtifactData>) = fulltextSearch(searchString, parameters) { consumer.accept(it) } fun fulltextSearch(searchString: String, parameters: SearchParameters, consumer: ResultConsumer): Promise<Int> { return performSearch(searchString, parameters, consumer) { p, c -> p.fulltextSearch(searchString).get() .forEach(c) // TODO A consumer here is used synchronously... } } fun getGroupIds(pattern: String?): Set<String>{ val result = mutableSetOf<String>() fulltextSearch(pattern ?: "", SearchParameters(true, true)) { if (it is MavenRepositoryArtifactInfo) { result.add(it.groupId) } } return result } fun getArtifactIds(groupId: String): Set<String>{ ProgressIndicatorProvider.checkCanceled() val result = mutableSetOf<String>() fulltextSearch("$groupId:", SearchParameters(true, true)) { if (it is MavenRepositoryArtifactInfo) { if (StringUtil.equals(groupId, it.groupId)) { result.add(it.artifactId) } } } return result } fun getVersions(groupId: String, artifactId: String): Set<String>{ ProgressIndicatorProvider.checkCanceled() val result = mutableSetOf<String>() fulltextSearch("$groupId:$artifactId", SearchParameters(true, true)) { if (it is MavenRepositoryArtifactInfo) { if (StringUtil.equals(groupId, it.groupId) && StringUtil.equals(artifactId, it.artifactId)) { for (item in it.items) { if (item.version != null) result.add(item.version!!) } } } } return result } private fun foundInCache(searchString: String, consumer: ResultConsumer): Promise<Int>? { val future = cache[searchString] if (future != null) { return fillResultsFromCache(future, consumer) } return null } private fun fillResultsFromCache(future: CompletableFuture<Collection<RepositoryArtifactData>>, consumer: ResultConsumer): AsyncPromise<Int> { val p: AsyncPromise<Int> = AsyncPromise() future.whenComplete( BiConsumer { r: Collection<RepositoryArtifactData>, e: Throwable? -> if (e != null) { p.setError(e) } else { r.forEach(consumer) p.setResult(null) } }) return p } companion object { @JvmField val EP_NAME = ExtensionPointName<DependencySearchProvidersFactory>("org.jetbrains.idea.reposearch.provider") @JvmStatic fun getInstance(project: Project): DependencySearchService = project.service() } fun clearCache() { cache.clear() } }
apache-2.0
e7e1316beeebe1f7c69fa33cba788048
35.014778
140
0.680164
4.955932
false
false
false
false
GunoH/intellij-community
python/src/com/jetbrains/python/testing/PySMTestProxyUtils.kt
7
1544
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.testing import com.intellij.execution.testframework.sm.runner.SMTestProxy import com.intellij.execution.testframework.sm.runner.states.TestStateInfo fun SMTestProxy.calculateAndReturnMagnitude(): TestStateInfo.Magnitude { if (!isLeaf) { var hasSkippedChildren = false var hasFailedChildren = false var hasErrorChildren = false var hasPassedChildren = false var hasTerminated = false children.forEach { child -> when (child.calculateAndReturnMagnitude()) { TestStateInfo.Magnitude.PASSED_INDEX -> hasPassedChildren = true TestStateInfo.Magnitude.SKIPPED_INDEX, TestStateInfo.Magnitude.IGNORED_INDEX -> hasSkippedChildren = true TestStateInfo.Magnitude.ERROR_INDEX -> hasErrorChildren = true TestStateInfo.Magnitude.RUNNING_INDEX, TestStateInfo.Magnitude.TERMINATED_INDEX -> hasTerminated = true TestStateInfo.Magnitude.FAILED_INDEX -> hasFailedChildren = true else -> hasPassedChildren = true } } when { hasTerminated -> setTerminated() hasErrorChildren -> setTestFailed("", null, true) // No text is provided because we do not want it to be duplicated for each node hasFailedChildren -> setTestFailed("", null, false) hasSkippedChildren && !hasPassedChildren -> setTestIgnored(null, null) else -> setFinished() } } return magnitudeInfo }
apache-2.0
240985b666c739408515141760629594
41.916667
140
0.733808
4.622754
false
true
false
false
binaryroot/AndroidArchitecture
app/src/androidTest/java/com/androidarchitecture/data/local/UserLocalApiTest.kt
1
1767
package com.androidarchitecture.data.local import android.arch.persistence.room.Room import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import com.androidarchitecture.data.local.user.UserLocalAPI import com.androidarchitecture.entity.User import org.junit.Assert.*; import org.junit.Before import org.junit.Test import org.junit.runner.RunWith /** * Created by binary on 6/3/17. */ @RunWith(AndroidJUnit4::class) class UserLocalApiTest { private lateinit var userLocalAPI: UserLocalAPI private lateinit var appDatabase: AppDatabase @Before fun createDB() { val context = InstrumentationRegistry.getTargetContext() appDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).build() userLocalAPI = appDatabase.userDao() } @Test fun testEmptyDB() { assertEquals(userLocalAPI.findById(0), null) } @Test fun testSaveUser() { val id = 2; val user = User(); user.uid = id; userLocalAPI.saveUser(user) assertEquals(userLocalAPI.findById(id)?.uid, id) } @Test fun testSaveUserByName() { val name = "Nazar"; val user = User(); user.firstName = name; userLocalAPI.saveUser(user) assertEquals(userLocalAPI.findByName(name)?.firstName, name) } @Test fun testSaveUserConflict() { val id = 2; val name = "binary" val secondName = "root" val user = User(); user.uid = id; user.firstName = name userLocalAPI.saveUser(user) user.firstName = secondName userLocalAPI.saveUser(user) assertEquals(userLocalAPI.findById(id)?.firstName, secondName) } }
mit
38173d1954b7e0b290b56b969eb8901e
25.787879
92
0.66893
4.19715
false
true
false
false
cfieber/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/CompleteStageHandlerTest.kt
1
41605
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.netflix.spectator.api.NoopRegistry import com.netflix.spinnaker.orca.ExecutionStatus.* import com.netflix.spinnaker.orca.events.StageComplete import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.fixture.stage import com.netflix.spinnaker.orca.fixture.task import com.netflix.spinnaker.orca.pipeline.DefaultStageDefinitionBuilderFactory import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilder import com.netflix.spinnaker.orca.pipeline.TaskNode import com.netflix.spinnaker.orca.pipeline.expressions.PipelineExpressionEvaluator import com.netflix.spinnaker.orca.pipeline.graph.StageGraphBuilder import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.model.Stage import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.util.ContextParameterProcessor import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.q.Message import com.netflix.spinnaker.q.Queue import com.netflix.spinnaker.spek.and import com.netflix.spinnaker.spek.but import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.* import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.jetbrains.spek.api.dsl.* import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import org.springframework.context.ApplicationEventPublisher object CompleteStageHandlerTest : SubjectSpek<CompleteStageHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() val publisher: ApplicationEventPublisher = mock() val clock = fixedClock() val registry = NoopRegistry() val contextParameterProcessor: ContextParameterProcessor = mock() val emptyStage = object : StageDefinitionBuilder {} val stageWithTaskAndAfterStages = object : StageDefinitionBuilder { override fun getType() = "stageWithTaskAndAfterStages" override fun taskGraph(stage: Stage, builder: TaskNode.Builder) { builder.withTask("dummy", DummyTask::class.java) } override fun afterStages(parent: Stage, graph: StageGraphBuilder) { graph.add { it.type = singleTaskStage.type it.name = "After Stage" it.context = mapOf("key" to "value") } } } val stageThatBlowsUpPlanningAfterStages = object : StageDefinitionBuilder { override fun getType() = "stageThatBlowsUpPlanningAfterStages" override fun taskGraph(stage: Stage, builder: TaskNode.Builder) { builder.withTask("dummy", DummyTask::class.java) } override fun afterStages(parent: Stage, graph: StageGraphBuilder) { throw RuntimeException("there is some problem actually") } } val stageWithNothingButAfterStages = object : StageDefinitionBuilder { override fun getType() = "stageWithNothingButAfterStages" override fun afterStages(parent: Stage, graph: StageGraphBuilder) { graph.add { it.type = singleTaskStage.type it.name = "After Stage" } } } subject(GROUP) { CompleteStageHandler( queue, repository, publisher, clock, contextParameterProcessor, registry, DefaultStageDefinitionBuilderFactory( singleTaskStage, multiTaskStage, stageWithSyntheticBefore, stageWithSyntheticAfter, stageWithParallelBranches, stageWithTaskAndAfterStages, stageThatBlowsUpPlanningAfterStages, stageWithSyntheticOnFailure, stageWithNothingButAfterStages, stageWithSyntheticOnFailure, emptyStage ) ) } fun resetMocks() = reset(queue, repository, publisher) describe("completing top level stages") { setOf(SUCCEEDED, FAILED_CONTINUE).forEach { taskStatus -> describe("when a stage's tasks complete with $taskStatus status") { and("it is already complete") { val pipeline = pipeline { stage { refId = "1" type = multiTaskStage.type multiTaskStage.plan(this) tasks[0].status = SUCCEEDED tasks[1].status = taskStatus tasks[2].status = SUCCEEDED status = taskStatus endTime = clock.instant().minusSeconds(2).toEpochMilli() } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("ignores the message") { verify(repository, never()).storeStage(any()) verifyZeroInteractions(queue) verifyZeroInteractions(publisher) } } and("it is the last stage") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = taskStatus status = RUNNING } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { assertThat(it.status).isEqualTo(taskStatus) assertThat(it.endTime).isEqualTo(clock.millis()) }) } it("completes the execution") { verify(queue).push(CompleteExecution(pipeline)) } it("does not emit any commands") { verify(queue, never()).push(any<RunTask>()) } it("publishes an event") { verify(publisher).publishEvent(check<StageComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.status).isEqualTo(taskStatus) }) } } and("there is a single downstream stage") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = taskStatus status = RUNNING } stage { refId = "2" requisiteStageRefIds = setOf("1") type = singleTaskStage.type } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { assertThat(it.status).isEqualTo(taskStatus) assertThat(it.endTime).isEqualTo(clock.millis()) }) } it("runs the next stage") { verify(queue).push(StartStage( message.executionType, message.executionId, message.application, pipeline.stages.last().id )) } it("does not run any tasks") { verify(queue, never()).push(any<RunTask>()) } } and("there are multiple downstream stages") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = taskStatus status = RUNNING } stage { refId = "2" requisiteStageRefIds = setOf("1") type = singleTaskStage.type } stage { refId = "3" requisiteStageRefIds = setOf("1") type = singleTaskStage.type } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("runs the next stages") { argumentCaptor<StartStage>().apply { verify(queue, times(2)).push(capture()) assertThat(allValues.map { it.stageId }.toSet()).isEqualTo(pipeline.stages[1..2].map { it.id }.toSet()) } } } and("there are parallel stages still running") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = taskStatus status = RUNNING } stage { refId = "2" type = singleTaskStage.type status = RUNNING } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("still signals completion of the execution") { verify(queue).push(CompleteExecution(pipeline)) } } setOf(CANCELED, TERMINAL, STOPPED).forEach { failureStatus -> and("there are parallel stages that failed") { val pipeline = pipeline { stage { refId = "1" type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = SUCCEEDED status = RUNNING } stage { refId = "2" type = singleTaskStage.type status = failureStatus } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("still signals completion of the execution") { verify(queue).push(CompleteExecution(pipeline)) } } } and("there are still synthetic stages to plan") { val pipeline = pipeline { stage { refId = "1" name = "wait" status = RUNNING type = stageWithTaskAndAfterStages.type stageWithTaskAndAfterStages.plan(this) tasks.first().status = taskStatus } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("adds a new AFTER_STAGE") { assertThat(pipeline.stages.map { it.type }).isEqualTo(listOf("stageWithTaskAndAfterStages", "singleTaskStage")) } it("starts the new AFTER_STAGE") { verify(queue).push(StartStage(message, pipeline.stages[1].id)) } it("does not update the status of the stage itself") { verify(repository, never()).storeStage(pipeline.stageById(message.stageId)) } it("does not signal completion of the execution") { verify(queue, never()).push(isA<CompleteExecution>()) } } and("planning synthetic stages throws an exception") { val pipeline = pipeline { stage { refId = "1" name = "wait" status = RUNNING type = stageThatBlowsUpPlanningAfterStages.type stageThatBlowsUpPlanningAfterStages.plan(this) tasks.first().status = taskStatus } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline assertThat(pipeline.stages.map { it.type }).isEqualTo(listOf(stageThatBlowsUpPlanningAfterStages.type)) } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("makes the stage TERMINAL") { assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL) } it("runs cancellation") { verify(queue).push(CancelStage(pipeline.stageById(message.stageId))) } it("signals completion of the execution") { verify(queue).push(CompleteExecution(pipeline)) } } } } given("a stage had no synthetics or tasks") { val pipeline = pipeline { application = "foo" stage { refId = "1" name = "empty" status = RUNNING type = emptyStage.type } stage { refId = "2" type = singleTaskStage.type name = "downstream" requisiteStageRefIds = setOf("1") } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) action("receiving the message") { subject.handle(message) } it("just marks the stage as SKIPPED") { verify(repository).storeStage(check { assertThat(it.id).isEqualTo(message.stageId) assertThat(it.status).isEqualTo(SKIPPED) }) } it("starts anything downstream") { verify(queue).push(StartStage(pipeline.stageByRef("2"))) } } setOf(TERMINAL, CANCELED).forEach { taskStatus -> describe("when a stage's task fails with $taskStatus status") { val pipeline = pipeline { stage { refId = "1" type = multiTaskStage.type multiTaskStage.plan(this) tasks[0].status = SUCCEEDED tasks[1].status = taskStatus tasks[2].status = NOT_STARTED status = RUNNING } stage { refId = "2" requisiteStageRefIds = listOf("1") type = singleTaskStage.type } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { assertThat(it.status).isEqualTo(taskStatus) assertThat(it.endTime).isEqualTo(clock.millis()) }) } it("does not run any downstream stages") { verify(queue, never()).push(isA<StartStage>()) } it("fails the execution") { verify(queue).push(CompleteExecution( message.executionType, message.executionId, message.application )) } it("runs the stage's cancellation routine") { verify(queue).push(CancelStage(message)) } it("publishes an event") { verify(publisher).publishEvent(check<StageComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.status).isEqualTo(taskStatus) }) } } } describe("when none of a stage's tasks ever started") { val pipeline = pipeline { stage { refId = "1" type = multiTaskStage.type multiTaskStage.plan(this) tasks[0].status = NOT_STARTED tasks[1].status = NOT_STARTED tasks[2].status = NOT_STARTED status = RUNNING } stage { refId = "2" requisiteStageRefIds = listOf("1") type = singleTaskStage.type } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { assertThat(it.status).isEqualTo(TERMINAL) assertThat(it.endTime).isEqualTo(clock.millis()) }) } it("does not run any downstream stages") { verify(queue, never()).push(isA<StartStage>()) } it("fails the execution") { verify(queue).push(CompleteExecution( message.executionType, message.executionId, message.application )) } it("runs the stage's cancellation routine") { verify(queue).push(CancelStage(message)) } it("publishes an event") { verify(publisher).publishEvent(check<StageComplete> { assertThat(it.executionType).isEqualTo(pipeline.type) assertThat(it.executionId).isEqualTo(pipeline.id) assertThat(it.stageId).isEqualTo(message.stageId) assertThat(it.status).isEqualTo(TERMINAL) }) } } given("a stage had no tasks or before stages") { but("does have after stages") { val pipeline = pipeline { stage { refId = "1" type = stageWithNothingButAfterStages.type status = RUNNING } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("plans and starts the after stages") { argumentCaptor<Message>().apply { verify(queue).push(capture()) firstValue.let { capturedMessage -> when (capturedMessage) { is StartStage -> pipeline.stageById(capturedMessage.stageId).apply { assertThat(parentStageId).isEqualTo(message.stageId) assertThat(name).isEqualTo("After Stage") } else -> fail("Expected a StartStage message but got a ${capturedMessage.javaClass.simpleName}") } } } } it("does not complete the pipeline") { verify(queue, never()).push(isA<CompleteExecution>()) } it("does not mark the stage as failed") { assertThat(pipeline.stageById(message.stageId).status).isEqualTo(RUNNING) } } } mapOf(STAGE_BEFORE to stageWithSyntheticBefore, STAGE_AFTER to stageWithSyntheticAfter).forEach { syntheticType, stageBuilder -> setOf(TERMINAL, CANCELED, STOPPED).forEach { failureStatus -> describe("when a $syntheticType synthetic stage completed with $failureStatus") { val pipeline = pipeline { stage { refId = "1" status = RUNNING type = stageBuilder.type if (syntheticType == STAGE_BEFORE) { stageBuilder.buildBeforeStages(this) } else { stageBuilder.buildAfterStages(this) } stageBuilder.plan(this) } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { pipeline .stages .first { it.syntheticStageOwner == syntheticType } .status = failureStatus whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { assertThat(it.status).isEqualTo(failureStatus) assertThat(it.endTime).isEqualTo(clock.millis()) }) } } } describe("when any $syntheticType synthetic stage completed with FAILED_CONTINUE") { val pipeline = pipeline { stage { refId = "1" status = RUNNING type = stageBuilder.type if (syntheticType == STAGE_BEFORE) { stageBuilder.buildBeforeStages(this) } else { stageBuilder.buildAfterStages(this) } stageBuilder.plan(this) } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { pipeline .stages .first { it.syntheticStageOwner == syntheticType } .status = FAILED_CONTINUE pipeline.stageById(message.stageId).tasks.forEach { it.status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { assertThat(it.status).isEqualTo(FAILED_CONTINUE) assertThat(it.endTime).isEqualTo(clock.millis()) }) } it("does not do anything silly like running the after stage again") { verify(queue, never()).push(isA<StartStage>()) } } } describe("when all after stages have completed successfully") { val pipeline = pipeline { stage { refId = "1" status = RUNNING type = stageWithSyntheticAfter.type stageWithSyntheticAfter.plan(this) stageWithSyntheticAfter.buildAfterStages(this) } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { pipeline .stages .filter { it.syntheticStageOwner == STAGE_AFTER } .forEach { it.status = SUCCEEDED } pipeline.stageById(message.stageId).tasks.forEach { it.status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("does not do anything silly like running the after stage again") { verify(queue, never()).push(isA<StartStage>()) } } given("after stages were planned but not run yet") { val pipeline = pipeline { stage { refId = "2" type = "deploy" name = "Deploy" status = RUNNING stage { refId = "2=1" type = "createServerGroup" name = "Deploy in us-west-2" status = RUNNING task { name = "determineSourceServerGroup" status = SUCCEEDED } stage { refId = "2=1>3" type = "applySourceServerGroupCapacity" name = "restoreMinCapacityFromSnapshot" syntheticStageOwner = STAGE_AFTER requisiteStageRefIds = setOf("2=1>2") } stage { refId = "2=1>2" type = "disableCluster" name = "disableCluster" syntheticStageOwner = STAGE_AFTER requisiteStageRefIds = setOf("2=1>1") } stage { refId = "2=1>1" type = "shrinkCluster" name = "shrinkCluster" syntheticStageOwner = STAGE_AFTER } } } } val message = CompleteStage(pipeline.stageByRef("2=1")) beforeGroup { whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving $message") { subject.handle(message) } it("starts the first after stage") { verify(queue).push(StartStage(pipeline.stageByRef("2=1>1"))) } } } describe("completing synthetic stages") { given("a synthetic stage's task completes with $SUCCEEDED") { and("it comes before its parent stage") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildBeforeStages(this) stageWithSyntheticBefore.buildTasks(this) } } and("there are more before stages") { val message = CompleteStage(pipeline.stageByRef("1<1")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING singleTaskStage.plan(this) tasks.first().status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("runs the next synthetic stage") { verify(queue).push(StartStage( pipeline.stageByRef("1<2") )) } } and("it is the last before stage") { val message = CompleteStage(pipeline.stageByRef("1<2")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING singleTaskStage.plan(this) tasks.first().status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("signals the parent stage to run") { verify(queue).push(ContinueParentStage( pipeline.stageByRef("1"), STAGE_BEFORE )) } } } and("it comes after its parent stage") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticAfter.type stageWithSyntheticAfter.buildBeforeStages(this) stageWithSyntheticAfter.buildTasks(this) stageWithSyntheticAfter.buildAfterStages(this) } } and("there are more after stages") { val message = CompleteStage(pipeline.stageByRef("1>1")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING singleTaskStage.plan(this) tasks.first().status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("runs the next synthetic stage") { verify(queue).push(StartStage( message.executionType, message.executionId, message.application, pipeline.stages.last().id )) } } and("it is the last after stage") { val message = CompleteStage(pipeline.stageByRef("1>2")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING singleTaskStage.plan(this) tasks.first().status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("tells the parent stage to continue") { verify(queue) .push(ContinueParentStage( pipeline.stageById(message.stageId).parent!!, STAGE_AFTER )) } } } given("a synthetic stage's task ends with $FAILED_CONTINUE status") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildBeforeStages(this) stageWithSyntheticBefore.plan(this) } } val message = CompleteStage(pipeline.stageByRef("1<1")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING singleTaskStage.plan(this) tasks.first().status = FAILED_CONTINUE } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } on("receiving the message") { subject.handle(message) } afterGroup(::resetMocks) it("rolls up to the parent stage") { verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id)) } } } setOf(TERMINAL, CANCELED).forEach { taskStatus -> given("a synthetic stage's task ends with $taskStatus status") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildBeforeStages(this) stageWithSyntheticBefore.plan(this) } } val message = CompleteStage(pipeline.stageByRef("1<1")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING singleTaskStage.plan(this) tasks.first().status = taskStatus } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } on("receiving the message") { subject.handle(message) } afterGroup(::resetMocks) it("rolls up to the parent stage") { verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id)) } it("runs the stage's cancel routine") { verify(queue).push(CancelStage(message)) } } } } describe("branching stages") { listOf(SUCCEEDED, FAILED_CONTINUE).forEach { status -> context("when one branch completes with $status") { val pipeline = pipeline { stage { refId = "1" name = "parallel" type = stageWithParallelBranches.type stageWithParallelBranches.buildBeforeStages(this) stageWithParallelBranches.buildTasks(this) } } val message = pipeline.stageByRef("1<1").let { completedSynthetic -> singleTaskStage.buildTasks(completedSynthetic) completedSynthetic.tasks.forEach { it.status = SUCCEEDED } CompleteStage(completedSynthetic) } beforeGroup { pipeline.stageById(message.stageId).status = RUNNING whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("signals the parent stage to try to run") { verify(queue) .push(ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)) } } given("all branches are complete") { val pipeline = pipeline { stage { refId = "1" name = "parallel" type = stageWithParallelBranches.type stageWithParallelBranches.buildBeforeStages(this) stageWithParallelBranches.buildTasks(this) } } pipeline.stages.filter { it.parentStageId != null }.forEach { singleTaskStage.buildTasks(it) it.tasks.forEach { it.status = SUCCEEDED } } val message = CompleteStage(pipeline.stageByRef("1<1")) beforeGroup { pipeline.stageById(message.stageId).status = RUNNING pipeline.stageByRef("1<2").status = SUCCEEDED pipeline.stageByRef("1<3").status = SUCCEEDED whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("signals the parent stage to try to run") { verify(queue) .push(ContinueParentStage(pipeline.stageByRef("1"), STAGE_BEFORE)) } } } } describe("surfacing expression evaluation errors") { fun exceptionErrors(stages: List<Stage>): List<*> = stages.flatMap { ((it.context["exception"] as Map<*, *>)["details"] as Map<*, *>)["errors"] as List<*> } given("an exception in the stage context") { val expressionError = "Expression foo failed for field bar" val existingException = "Existing error" val pipeline = pipeline { stage { refId = "1" name = "wait" context = mapOf( "exception" to mapOf("details" to mapOf("errors" to mutableListOf(existingException))), PipelineExpressionEvaluator.SUMMARY to mapOf("failedExpression" to listOf(mapOf("description" to expressionError, "level" to "ERROR"))) ) status = RUNNING type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = SUCCEEDED } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("should contain evaluation summary as well as the existing error") { val errors = exceptionErrors(pipeline.stages) assertThat(errors.size).isEqualTo(2) expressionError in errors existingException in errors } } given("no other exception errors in the stage context") { val expressionError = "Expression foo failed for field bar" val pipeline = pipeline { stage { refId = "1" name = "wait" context = mutableMapOf<String, Any>( PipelineExpressionEvaluator.SUMMARY to mapOf("failedExpression" to listOf(mapOf("description" to expressionError, "level" to "ERROR"))) ) status = RUNNING type = singleTaskStage.type singleTaskStage.plan(this) tasks.first().status = SUCCEEDED } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("should only contain evaluation error message") { val errors = exceptionErrors(pipeline.stages) assertThat(errors.size).isEqualTo(1) expressionError in errors } } } given("a stage ends with TERMINAL status") { and("it has not run its on failure stages yet") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticOnFailure.type stageWithSyntheticOnFailure.buildBeforeStages(this) stageWithSyntheticOnFailure.plan(this) } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING tasks.first().status = TERMINAL } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("plans the first 'OnFailure' stage") { val onFailureStage = pipeline.stages.first { it.name == "onFailure1" } verify(queue).push(StartStage(onFailureStage)) } it("does not (yet) update the stage status") { assertThat(pipeline.stageById(message.stageId).status).isEqualTo(RUNNING) } } and("it has already run its on failure stages") { val pipeline = pipeline { stage { refId = "1" type = stageWithSyntheticOnFailure.type stageWithSyntheticOnFailure.buildBeforeStages(this) stageWithSyntheticOnFailure.plan(this) stageWithSyntheticOnFailure.buildFailureStages(this) } } val message = CompleteStage(pipeline.stageByRef("1")) beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING tasks.first().status = TERMINAL } pipeline.stages.filter { it.parentStageId == message.stageId }.forEach { it.status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, message.executionId)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message again") { subject.handle(message) } it("does not re-plan any 'OnFailure' stages") { val onFailureStage = pipeline.stages.first { it.name == "onFailure1" } verify(queue, never()).push(StartStage(onFailureStage)) verify(queue).push(CancelStage(message)) } it("updates the stage status") { assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL) } } } describe("stage planning failure behavior") { given("a stage that failed to plan its before stages") { val pipeline = pipeline { stage { refId = "1" context = mutableMapOf<String, Any>("beforeStagePlanningFailed" to true) type = stageWithSyntheticOnFailure.type stageWithSyntheticOnFailure.buildFailureStages(this) } } val message = CompleteStage(pipeline.stageByRef("1")) and("it has not run its on failure stages yet") { beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message") { subject.handle(message) } it("plans the first on failure stage") { val onFailureStage = pipeline.stages.first { it.name == "onFailure1" } verify(queue).push(StartStage(onFailureStage)) } it("does not (yet) update the stage status") { assertThat(pipeline.stageById(message.stageId).status).isEqualTo(RUNNING) } } and("it has already run its on failure stages") { beforeGroup { pipeline.stageById(message.stageId).apply { status = RUNNING } pipeline.stages.filter { it.parentStageId == message.stageId }.forEach { it.status = SUCCEEDED } whenever(repository.retrieve(PIPELINE, pipeline.id)) doReturn pipeline } afterGroup(::resetMocks) on("receiving the message again") { subject.handle(message) } it("does not re-plan on failure stages") { val onFailureStage = pipeline.stages.first { it.name == "onFailure1" } verify(queue, never()).push(StartStage(onFailureStage)) verify(queue).push(CancelStage(message)) } it("updates the stage status") { assertThat(pipeline.stageById(message.stageId).status).isEqualTo(TERMINAL) } } } } })
apache-2.0
95a19bcfb8d557c781381b6bade9c393
30.025354
147
0.578704
5.154237
false
false
false
false
pureal-code/pureal-os
tests.traits/src/net/pureal/tests/traits/Vector3Specs.kt
1
960
package net.pureal.tests.traits.math import org.jetbrains.spek.api.* import net.pureal.traits.* class Vector3Specs : Spek() {init { given("a 3 vector") { val x = vector(1.5, -4, 3) on("getting the string repesentation") { val s = x.toString() it("should be correct") { shouldEqual(s, "vector(1.5, -4.0, 3.0)") } } } given("two unit 3 vectors in x- and z-direction") { val eX = vector(1, 0, 0) val eY = vector(0, 0, 1) on("getting the dot product of the two") { val p = eX * eY it("should be 0.") { shouldEqual(0.0, p) } } on("getting the cross product of the two") { val p = eX.crossProduct(eY) it("should be (0 -1 0)") { shouldEqual(vector(0, -1, 0), p) } } } } }
bsd-3-clause
ace6faf248f221368d4fade48431f196
20.904762
56
0.444792
3.692308
false
false
false
false
mdanielwork/intellij-community
plugins/stats-collector/log-events/src/com/intellij/stats/completion/events/LogEvent.kt
1
1785
/* * 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.stats.completion.events import com.intellij.stats.completion.Action import com.intellij.stats.completion.LogEventVisitor import com.intellij.stats.completion.LookupEntryInfo import com.intellij.stats.completion.ValidationStatus abstract class LogEvent( @Transient var userUid: String, @Transient var sessionUid: String, @Transient var actionType: Action, @Transient var timestamp: Long ) { @Transient var recorderId: String = "completion-stats" @Transient var recorderVersion: String = "5" @Transient var bucket: String = "-1" var validationStatus: ValidationStatus = ValidationStatus.UNKNOWN abstract fun accept(visitor: LogEventVisitor) } abstract class LookupStateLogData( userId: String, sessionId: String, action: Action, @JvmField var completionListIds: List<Int>, @JvmField var newCompletionListItems: List<LookupEntryInfo>, @JvmField var currentPosition: Int, timestamp: Long ) : LogEvent(userId, sessionId, action, timestamp) { @JvmField var originalCompletionType: String = "" @JvmField var originalInvokationCount: Int = -1 }
apache-2.0
ba4f77c2b1d21b9bb0854399c4aea51e
31.472727
75
0.730532
4.42928
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/feed/view/ListCardItemView.kt
1
6478
package org.wikipedia.feed.view import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.VisibleForTesting import androidx.appcompat.content.res.AppCompatResources import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.util.Pair import org.wikipedia.R import org.wikipedia.databinding.ViewListCardItemBinding import org.wikipedia.feed.model.Card import org.wikipedia.feed.mostread.MostReadArticles.ViewHistory import org.wikipedia.history.HistoryEntry import org.wikipedia.page.PageAvailableOfflineHandler.check import org.wikipedia.readinglist.LongPressMenu import org.wikipedia.readinglist.database.ReadingListPage import org.wikipedia.util.DeviceUtil import org.wikipedia.util.DimenUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.util.StringUtil import org.wikipedia.util.TransitionUtil import org.wikipedia.views.ViewUtil import kotlin.math.roundToInt class ListCardItemView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ConstraintLayout(context, attrs) { interface Callback { fun onSelectPage(card: Card, entry: HistoryEntry, openInNewBackgroundTab: Boolean) fun onSelectPage(card: Card, entry: HistoryEntry, sharedElements: Array<Pair<View, String>>) fun onAddPageToList(entry: HistoryEntry, addToDefault: Boolean) fun onMovePageToList(sourceReadingListId: Long, entry: HistoryEntry) } private val binding = ViewListCardItemBinding.inflate(LayoutInflater.from(context), this) private var card: Card? = null @get:VisibleForTesting var callback: Callback? = null private set @get:VisibleForTesting var historyEntry: HistoryEntry? = null private set init { isFocusable = true layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) val topBottomPadding = 16 setPadding(0, DimenUtil.roundedDpToPx(topBottomPadding.toFloat()), 0, DimenUtil.roundedDpToPx(topBottomPadding.toFloat())) DeviceUtil.setContextClickAsLongClick(this) background = AppCompatResources.getDrawable(getContext(), ResourceUtil.getThemedAttributeId(getContext(), R.attr.selectableItemBackground)) setOnClickListener { if (historyEntry != null && card != null) { callback?.onSelectPage(card!!, historyEntry!!, TransitionUtil.getSharedElements(context, binding.viewListCardItemImage)) } } setOnLongClickListener { view -> LongPressMenu(view, true, object : LongPressMenu.Callback { override fun onOpenLink(entry: HistoryEntry) { card?.let { callback?.onSelectPage(it, entry, false) } } override fun onOpenInNewTab(entry: HistoryEntry) { card?.let { callback?.onSelectPage(it, entry, true) } } override fun onAddRequest(entry: HistoryEntry, addToDefault: Boolean) { callback?.onAddPageToList(entry, addToDefault) } override fun onMoveRequest(page: ReadingListPage?, entry: HistoryEntry) { page?.let { callback?.onMovePageToList(it.listId, entry) } } }).show(historyEntry) false } } fun setCard(card: Card?): ListCardItemView { this.card = card return this } fun setCallback(callback: Callback?): ListCardItemView { this.callback = callback return this } fun setHistoryEntry(entry: HistoryEntry): ListCardItemView { historyEntry = entry setTitle(StringUtil.fromHtml(entry.title.displayText)) setSubtitle(entry.title.description) setImage(entry.title.thumbUrl) check(entry.title) { available -> setViewsGreyedOut(!available) } return this } @VisibleForTesting fun setImage(url: String?) { if (url == null) { binding.viewListCardItemImage.visibility = GONE } else { binding.viewListCardItemImage.visibility = VISIBLE ViewUtil.loadImageWithRoundedCorners(binding.viewListCardItemImage, url, true) } } @VisibleForTesting fun setTitle(text: CharSequence?) { binding.viewListCardItemTitle.text = text } @VisibleForTesting fun setSubtitle(text: CharSequence?) { binding.viewListCardItemSubtitle.text = text } fun setNumber(number: Int) { binding.viewListCardNumber.visibility = VISIBLE binding.viewListCardNumber.setNumber(number) } fun setPageViews(pageViews: Int) { binding.viewListCardItemPageviews.visibility = VISIBLE binding.viewListCardItemPageviews.text = getPageViewText(pageViews) } fun setGraphView(viewHistories: List<ViewHistory>) { val dataSet = mutableListOf<Float>() var i = viewHistories.size while (DEFAULT_VIEW_HISTORY_ITEMS > i++) { dataSet.add(0f) } dataSet.addAll(viewHistories.map { it.views }) binding.viewListCardItemGraph.visibility = VISIBLE binding.viewListCardItemGraph.setData(dataSet) } private fun getPageViewText(pageViews: Int): String { return when { pageViews < 1000 -> pageViews.toString() pageViews < 1000000 -> { context.getString( R.string.view_top_read_card_pageviews_k_suffix, (pageViews / 1000f).roundToInt() ) } else -> { context.getString( R.string.view_top_read_card_pageviews_m_suffix, (pageViews / 1000000f).roundToInt() ) } } } private fun setViewsGreyedOut(greyedOut: Boolean) { val alpha = if (greyedOut) 0.5f else 1.0f binding.viewListCardItemTitle.alpha = alpha binding.viewListCardItemSubtitle.alpha = alpha binding.viewListCardItemImage.alpha = alpha } companion object { private const val DEFAULT_VIEW_HISTORY_ITEMS = 5 } }
apache-2.0
a0e22c3b2a16aaedb2d644b25e34ff58
34.593407
136
0.652362
4.9375
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/objectToTopLevel/after/test.kt
39
454
package test inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block() class A { class X { } companion object { class Y fun foo(n: Int) {} val bar = 1 fun Int.extFoo(n: Int) {} val Int.extBar: Int get() = 1 } object O { class Y fun foo(n: Int) {} val bar = 1 fun Int.extFoo(n: Int) {} val Int.extBar: Int get() = 1 } }
apache-2.0
b60ccc24b7612070aff20bd208d43756
12.382353
75
0.453744
3.38806
false
false
false
false
phylame/jem
imabw/src/main/kotlin/jem/imabw/Settings.kt
1
6199
/* * Copyright 2015-2017 Peng Wan <[email protected]> * * This file is part of Jem. * * 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 jem.imabw import javafx.beans.binding.Bindings import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.scene.control.Dialog import javafx.scene.control.MenuItem import javafx.scene.control.SeparatorMenuItem import javafx.scene.control.TableView import jclp.io.exists import jclp.io.notExists import jclp.setting.getDouble import jclp.setting.getString import jclp.setting.settingsWith import mala.App import mala.AppSettings import mala.MalaSettings import mala.ixin.IxIn import mala.ixin.IxInSettings import java.nio.file.Files import java.nio.file.Paths object GeneralSettings : AppSettings() { var enableHistory by settingsWith(true, "app.history.enable") var historyLimit by settingsWith(24, "app.history.limit") var lastBookDir by settingsWith("", "app.history.bookDir") var lastImageDir by settingsWith("", "app.history.imageDir") } object UISettings : IxInSettings() { var stylesheetUri by settingsWith("", "ui.stylesheet.uri") var navigationBarVisible by settingsWith(true, "main.navigationBar.visible") var minCoverWidth by settingsWith(300.0, "dialog.attributes.minCoverWidth") fun restoreState(dialog: Dialog<*>, tagId: String) { with(dialog) { getDouble("dialog.$tagId.width")?.let { dialogPane.prefWidth = it } getDouble("dialog.$tagId.height")?.let { dialogPane.prefHeight = it } getDouble("dialog.$tagId.x")?.let { x = it } getDouble("dialog.$tagId.y")?.let { y = it } } } fun storeState(dialog: Dialog<*>, tagId: String) { with(dialog) { set("dialog.$tagId.width", dialogPane.width) set("dialog.$tagId.height", dialogPane.height) set("dialog.$tagId.x", x) set("dialog.$tagId.y", y) } } fun restoreState(table: TableView<*>, tagId: String) { table.columns.forEachIndexed { index, column -> getDouble("table.$tagId.column.$index")?.let { column.prefWidth = it } } } fun storeState(table: TableView<*>, tagId: String) { table.columns.forEachIndexed { index, column -> set("table.$tagId.column.$index", column.width) } } } object EditorSettings : MalaSettings("config/editor.ini") { var wrapText by settingsWith(false, "editor.wrapText") var showLineNumber by settingsWith(true, "editor.showLineNumber") } object JemSettings : MalaSettings("config/jem.ini") { var genres by settingsWith("", "jem.values.genres") var states by settingsWith(App.tr("jem.value.states"), "jem.values.states") var multipleAttrs by settingsWith("author;keywords;vendor;tag;subject;protagonist", "jem.values.multiple") fun getValue(name: String) = getString("jem.values.$name") } object History { private val file = Paths.get(App.home, "config/history.txt") private val paths = FXCollections.observableArrayList<String>() val latest get() = paths.firstOrNull() private var isModified = false init { IxIn.actionMap["clearHistory"]?.disableProperty?.bind(Bindings.isEmpty(paths)) paths.addListener(ListChangeListener { val items = IxIn.menuMap["menuHistory"]!!.items val isEmpty = items.size == 1 while (it.next()) { if (it.wasRemoved()) { for (path in it.removed) { items.removeIf { it.text == path } } if (items.size == 2) { // remove separator items.remove(0, 1) } } if (it.wasAdded()) { val paths = items.map { it.text } it.addedSubList.filter { it !in paths }.asReversed().mapIndexed { i, path -> if (i == 0 && isEmpty) { // insert separator items.add(0, SeparatorMenuItem()) } items.add(0, MenuItem(path).apply { setOnAction { Workbench.openFile(text) } }) } } } }) load() } fun remove(path: String) { if (GeneralSettings.enableHistory) { paths.remove(path) isModified = true } } fun insert(path: String) { if (GeneralSettings.enableHistory) { paths.remove(path) if (paths.size == GeneralSettings.historyLimit) { paths.remove(paths.size - 1, paths.size) } paths.add(0, path) isModified = true } } fun clear() { if (GeneralSettings.enableHistory) { paths.clear() isModified = true } } fun load() { if (GeneralSettings.enableHistory) { if (file.exists) { with(ReadLineTask(file)) { setOnSucceeded { paths += value hideProgress() } Imabw.submit(this) } } } } fun sync() { if (GeneralSettings.enableHistory && isModified) { if (file.notExists) { try { Files.createDirectories(file.parent) } catch (e: Exception) { App.error("cannot create directory for history", e) return } } Files.write(file, paths) } } }
apache-2.0
ed16085c23cce727ddcfe21f4319b3da
30.953608
110
0.587514
4.421541
false
false
false
false
JuliaSoboleva/SmartReceiptsLibrary
app/src/main/java/co/smartreceipts/android/model/impl/columns/receipts/AbstractExchangedPriceColumn.kt
2
2010
package co.smartreceipts.android.model.impl.columns.receipts import android.content.Context import co.smartreceipts.android.R import co.smartreceipts.android.model.ActualColumnDefinition import co.smartreceipts.android.model.Price import co.smartreceipts.android.model.Receipt import co.smartreceipts.android.model.factory.PriceBuilderFactory import co.smartreceipts.android.model.impl.columns.AbstractColumnImpl import co.smartreceipts.android.model.utils.ModelUtils import co.smartreceipts.core.sync.model.SyncState import java.util.* /** * Allows us to genericize how different prices are converted to a trip's base currency */ abstract class AbstractExchangedPriceColumn( id: Int, definition: ActualColumnDefinition, syncState: SyncState, private val localizedContext: Context, customOrderId: Long, uuid: UUID ) : AbstractColumnImpl<Receipt>(id, definition, syncState, customOrderId, uuid) { override fun getValue(rowItem: Receipt): String { val price = getPrice(rowItem) val exchangeRate = price.exchangeRate val baseCurrency = rowItem.trip.tripCurrency return if (exchangeRate.supportsExchangeRateFor(baseCurrency)) { ModelUtils.getDecimalFormattedValue(price.price.multiply(exchangeRate.getExchangeRate(baseCurrency)), baseCurrency.decimalPlaces) } else { localizedContext.getString(R.string.undefined) } } override fun getFooter(rows: List<Receipt>): String { return if (rows.isNotEmpty()) { val factory = PriceBuilderFactory() val prices = ArrayList<Price>(rows.size) for (receipt in rows) { factory.setCurrency(receipt.trip.tripCurrency) prices.add(getPrice(receipt)) } factory.setPrices(prices, rows[0].trip.tripCurrency) factory.build().decimalFormattedPrice } else { "" } } protected abstract fun getPrice(receipt: Receipt): Price }
agpl-3.0
20b20ab065abd3057cc38bb406c8d951
36.222222
141
0.713433
4.516854
false
false
false
false
Bugfry/exercism
exercism/kotlin/robot-name/src/main/kotlin/Robot.kt
2
836
import java.util.Random private object NameGenerator { val random: Random = Random() val used: MutableSet<String> = hashSetOf() private fun random_digit(): Char { return '0' + random.nextInt(10) } private fun random_letter(): Char { return 'A' + random.nextInt(26) } private fun next_unchecked(): String { return listOf(random_letter(), random_letter(), random_digit(), random_digit(), random_digit()).joinToString(separator="") } fun next(): String { var result = next_unchecked() while (used.contains(result)) { result = next_unchecked() } used.add(result) return result } } class Robot { var name: String = NameGenerator.next() get fun reset() { this.name = NameGenerator.next() } }
mit
3bef270e6cebcbf0c8326fec68e053d0
20.435897
60
0.587321
4.038647
false
false
false
false
apache/isis
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/to/Value.kt
2
3117
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.causeway.client.kroviz.to import kotlinx.serialization.* import kotlinx.serialization.builtins.nullable import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.jsonPrimitive /** * Custom data structure to handle 'untyped' value in Member, Property, Parameter * "value" can either be: * @Item 'null' * @Item Int with format "int" * @Item Long with format "utc-millisec" * @Item String * @Item Link */ @Serializable data class Value( //IMPROVE: make content immutable (again) and handle property edits e.g. via a wrapper @Contextual @SerialName("value") var content: Any? = null, ) : TransferObject { @ExperimentalSerializationApi @Serializer(forClass = Value::class) companion object : KSerializer<Value> { // @ExperimentalSerializationApi override fun deserialize(decoder: Decoder): Value { val nss = JsonElement.serializer().nullable val jse: JsonElement? = decoder.decodeNullableSerializableValue(nss)!! val result: Value = when { jse == null -> Value(null) isNumeric(jse) -> Value(jse.jsonPrimitive.content.toLong()) jse is JsonObject -> toLink(jse) else -> toString(jse) } return result } private fun toString(jse: JsonElement): Value { val s = jse.jsonPrimitive.content return Value(s) } private fun toLink(jse: JsonElement): Value { val linkStr = jse.toString() val link = Json.decodeFromString<Link>(linkStr) return Value(link) } private fun isNumeric(jse: JsonElement): Boolean { return try { jse.jsonPrimitive.content.toLong() true } catch (nfe: NumberFormatException) { false } catch (ie: IllegalArgumentException) { false } } override fun serialize(encoder: Encoder, value: Value) { TODO("Not yet implemented") } } }
apache-2.0
8472b357d7fe38036beec7dfed03cc8b
34.022472
90
0.654155
4.478448
false
false
false
false
JetBrains/intellij-community
platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffMainUI.kt
1
17255
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.diff.tools.combined import com.intellij.CommonBundle import com.intellij.diff.DiffContext import com.intellij.diff.DiffManagerEx import com.intellij.diff.DiffTool import com.intellij.diff.FrameDiffTool import com.intellij.diff.FrameDiffTool.DiffViewer import com.intellij.diff.actions.impl.OpenInEditorAction import com.intellij.diff.impl.DiffRequestProcessor.getToolOrderFromSettings import com.intellij.diff.impl.DiffRequestProcessor.notifyMessage import com.intellij.diff.impl.DiffSettingsHolder.DiffSettings import com.intellij.diff.impl.ui.DiffToolChooser import com.intellij.diff.impl.ui.DifferencesLabel import com.intellij.diff.tools.util.DiffDataKeys import com.intellij.diff.tools.util.PrevNextDifferenceIterable import com.intellij.diff.tools.util.base.DiffViewerBase import com.intellij.diff.tools.util.base.DiffViewerListener import com.intellij.diff.util.DiffUserDataKeys import com.intellij.diff.util.DiffUserDataKeysEx import com.intellij.diff.util.DiffUtil import com.intellij.ide.impl.DataManagerImpl import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl import com.intellij.openapi.diff.DiffBundle import com.intellij.openapi.diff.impl.DiffUsageTriggerCollector import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.popup.JBPopupFactory import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy import com.intellij.ui.GuiUtils import com.intellij.ui.JBColor import com.intellij.ui.JBSplitter import com.intellij.ui.components.JBPanelWithEmptyText import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.mac.touchbar.Touchbar import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.ui.JBUI import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.annotations.NonNls import java.awt.BorderLayout import java.awt.Component import java.awt.Container import java.awt.Dimension import java.lang.Boolean.getBoolean import javax.swing.JComponent import javax.swing.JPanel import javax.swing.JProgressBar import javax.swing.SwingUtilities import kotlin.math.max class CombinedDiffMainUI(private val model: CombinedDiffModel, goToChangeFactory: () -> AnAction?) : Disposable { private val ourDisposable = Disposer.newCheckedDisposable().also { Disposer.register(this, it) } private val context: DiffContext = model.context private val settings = DiffSettings.getSettings(context.getUserData(DiffUserDataKeys.PLACE)) private val combinedToolOrder = arrayListOf<CombinedDiffTool>() private val leftToolbarGroup = DefaultActionGroup() private val rightToolbarGroup = DefaultActionGroup() private val popupActionGroup = DefaultActionGroup() private val touchbarActionGroup = DefaultActionGroup() private val panel: JPanel private val mainPanel = MyMainPanel() private val contentPanel = Wrapper() private val topPanel: JPanel private val leftToolbar: ActionToolbar private val rightToolbar: ActionToolbar private val leftToolbarWrapper: Wrapper private val rightToolbarWrapper: Wrapper private val diffInfoWrapper: Wrapper private val toolbarStatusPanel = Wrapper() private val progressBar = MyProgressBar() private val diffToolChooser: MyDiffToolChooser private val combinedViewer get() = context.getUserData(COMBINED_DIFF_VIEWER_KEY) // // Global, shortcuts only navigation actions // private val openInEditorAction = object : OpenInEditorAction() { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = false } } private val prevFileAction = object : CombinedPrevChangeAction(context) { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = false } } private val nextFileAction = object : CombinedNextChangeAction(context) { override fun update(e: AnActionEvent) { super.update(e) e.presentation.isVisible = false } } private val prevDifferenceAction = object : CombinedPrevDifferenceAction(settings, context) { override fun getDifferenceIterable(e: AnActionEvent): PrevNextDifferenceIterable? { return combinedViewer?.scrollSupport?.currentPrevNextIterable ?: super.getDifferenceIterable(e) } } private val nextDifferenceAction = object : CombinedNextDifferenceAction(settings, context) { override fun getDifferenceIterable(e: AnActionEvent): PrevNextDifferenceIterable? { return combinedViewer?.scrollSupport?.currentPrevNextIterable ?: super.getDifferenceIterable(e) } } private val goToChangeAction = goToChangeFactory() private val differencesLabel by lazy { MyDifferencesLabel(goToChangeAction) } init { Touchbar.setActions(mainPanel, touchbarActionGroup) updateAvailableDiffTools() diffToolChooser = MyDiffToolChooser() leftToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.DIFF_TOOLBAR, leftToolbarGroup, true) context.putUserData(DiffUserDataKeysEx.LEFT_TOOLBAR, leftToolbar) leftToolbar.layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY leftToolbar.targetComponent = mainPanel leftToolbarWrapper = Wrapper(leftToolbar.component) rightToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.DIFF_RIGHT_TOOLBAR, rightToolbarGroup, true) rightToolbar.layoutPolicy = ActionToolbar.NOWRAP_LAYOUT_POLICY rightToolbar.targetComponent = mainPanel rightToolbarWrapper = Wrapper(JBUI.Panels.simplePanel(rightToolbar.component)) panel = JBUI.Panels.simplePanel(mainPanel) diffInfoWrapper = Wrapper() topPanel = buildTopPanel() topPanel.border = JBUI.Borders.customLine(JBColor.border(), 0, 0, 1, 0) val bottomContentSplitter = JBSplitter(true, "CombinedDiff.BottomComponentSplitter", 0.8f) bottomContentSplitter.firstComponent = contentPanel mainPanel.add(topPanel, BorderLayout.NORTH) mainPanel.add(bottomContentSplitter, BorderLayout.CENTER) mainPanel.isFocusTraversalPolicyProvider = true mainPanel.focusTraversalPolicy = MyFocusTraversalPolicy() val bottomPanel = context.getUserData(DiffUserDataKeysEx.BOTTOM_PANEL) if (bottomPanel != null) bottomContentSplitter.secondComponent = bottomPanel if (bottomPanel is Disposable) Disposer.register(ourDisposable, bottomPanel) contentPanel.setContent(DiffUtil.createMessagePanel(CommonBundle.getLoadingTreeNodeText())) } @RequiresEdt fun setContent(viewer: DiffViewer) { clear() contentPanel.setContent(viewer.component) val toolbarComponents = viewer.init() val diffInfo = toolbarComponents.diffInfo if (diffInfo != null) { diffInfoWrapper.setContent(diffInfo.component) } else { diffInfoWrapper.setContent(null) } buildToolbar(toolbarComponents.toolbarActions) buildActionPopup(toolbarComponents.popupActions) toolbarStatusPanel.setContent(toolbarComponents.statusPanel) } fun getPreferredFocusedComponent(): JComponent? { val component = leftToolbar.component return if (component.isShowing) component else null } fun getComponent(): JComponent = panel @RequiresEdt fun startProgress() = progressBar.startProgress() @RequiresEdt fun stopProgress() = progressBar.stopProgress() fun isUnified() = diffToolChooser.getActiveTool() is CombinedUnifiedDiffTool fun isFocusedInWindow(): Boolean { return DiffUtil.isFocusedComponentInWindow(contentPanel) || DiffUtil.isFocusedComponentInWindow(leftToolbar.component) || DiffUtil.isFocusedComponentInWindow(rightToolbar.component) } fun isWindowFocused(): Boolean { val window = SwingUtilities.getWindowAncestor(panel) return window != null && window.isFocused } fun requestFocusInWindow() { DiffUtil.requestFocusInWindow(getPreferredFocusedComponent()) } private fun buildActionPopup(viewerActions: List<AnAction?>?) { collectPopupActions(viewerActions) DiffUtil.registerAction(ShowActionGroupPopupAction(), mainPanel) } private fun collectPopupActions(viewerActions: List<AnAction?>?) { popupActionGroup.removeAll() DiffUtil.addActionBlock(popupActionGroup, diffToolChooser) DiffUtil.addActionBlock(popupActionGroup, viewerActions) } private fun buildToolbar(viewerActions: List<AnAction?>?) { collectToolbarActions(viewerActions) (leftToolbar as ActionToolbarImpl).clearPresentationCache() leftToolbar.updateActionsImmediately() DiffUtil.recursiveRegisterShortcutSet(leftToolbarGroup, mainPanel, null) (rightToolbar as ActionToolbarImpl).clearPresentationCache() rightToolbar.updateActionsImmediately() DiffUtil.recursiveRegisterShortcutSet(rightToolbarGroup, mainPanel, null) } private fun collectToolbarActions(viewerActions: List<AnAction?>?) { leftToolbarGroup.removeAll() val navigationActions= ArrayList<AnAction>(collectNavigationActions()) rightToolbarGroup.add(diffToolChooser) DiffUtil.addActionBlock(leftToolbarGroup, navigationActions) DiffUtil.addActionBlock(rightToolbarGroup, viewerActions, false) val contextActions = context.getUserData(DiffUserDataKeys.CONTEXT_ACTIONS) DiffUtil.addActionBlock(leftToolbarGroup, contextActions) if (SystemInfo.isMac) { // collect touchbar actions touchbarActionGroup.removeAll() touchbarActionGroup.addAll(CombinedPrevDifferenceAction(settings, context), CombinedNextDifferenceAction(settings, context), OpenInEditorAction(), Separator.getInstance(), CombinedPrevChangeAction(context), CombinedNextChangeAction(context)) if (SHOW_VIEWER_ACTIONS_IN_TOUCHBAR && viewerActions != null) { touchbarActionGroup.addAll(viewerActions) } } } private fun collectNavigationActions(): List<AnAction> { return listOfNotNull(prevDifferenceAction, nextDifferenceAction, differencesLabel, openInEditorAction, prevFileAction, nextFileAction) } private fun buildTopPanel(): BorderLayoutPanel { val rightPanel = JBUI.Panels.simplePanel(rightToolbarWrapper).addToLeft(progressBar) val topPanel = JBUI.Panels.simplePanel(diffInfoWrapper).addToLeft(leftToolbarWrapper).addToRight(rightPanel) GuiUtils.installVisibilityReferent(topPanel, leftToolbar.component) GuiUtils.installVisibilityReferent(topPanel, rightToolbar.component) return topPanel } internal fun notifyMessage(e: AnActionEvent, next: Boolean) { notifyMessage(e, contentPanel, next) } private fun clear() { toolbarStatusPanel.setContent(null) contentPanel.setContent(null) diffInfoWrapper.setContent(null) leftToolbarGroup.removeAll() rightToolbarGroup.removeAll() popupActionGroup.removeAll() ActionUtil.clearActions(mainPanel) } private fun moveToolOnTop(tool: CombinedDiffTool) { if (combinedToolOrder.remove(tool)) { combinedToolOrder.add(0, tool) updateToolOrderSettings(combinedToolOrder) } } private fun updateToolOrderSettings(toolOrder: List<DiffTool>) { val savedOrder = arrayListOf<String>() for (tool in toolOrder) { savedOrder.add(tool.javaClass.canonicalName) } settings.diffToolsOrder = savedOrder } private fun updateAvailableDiffTools() { combinedToolOrder.clear() val availableCombinedDiffTools = DiffManagerEx.getInstance().diffTools.filterIsInstance<CombinedDiffTool>() combinedToolOrder.addAll(getToolOrderFromSettings(settings, availableCombinedDiffTools).filterIsInstance<CombinedDiffTool>()) } override fun dispose() { if (ourDisposable.isDisposed) return UIUtil.invokeLaterIfNeeded { if (ourDisposable.isDisposed) return@invokeLaterIfNeeded clear() } } fun countDifferences(blockId: CombinedBlockId, viewer: DiffViewer) { differencesLabel.countDifferences(blockId, viewer) } private inner class MyDifferencesLabel(goToChangeAction: AnAction?) : DifferencesLabel(goToChangeAction, leftToolbar.component) { private val loadedDifferences = hashMapOf<Int, Int>() override fun getFileCount(): Int = combinedViewer?.diffBlocks?.size ?: 0 override fun getTotalDifferences(): Int = calculateTotalDifferences() fun countDifferences(blockId: CombinedBlockId, childViewer: DiffViewer) { val combinedViewer = combinedViewer ?: return val index = combinedViewer.diffBlocksPositions[blockId] ?: return loadedDifferences[index] = 1 if (childViewer is DiffViewerBase) { val listener = object : DiffViewerListener() { override fun onAfterRediff() { loadedDifferences[index] = if (childViewer is DifferencesCounter) childViewer.getTotalDifferences() else 1 } } childViewer.addListener(listener) Disposer.register(childViewer, Disposable { childViewer.removeListener(listener) }) } } private fun calculateTotalDifferences(): Int = loadedDifferences.values.sum() } private inner class MyDiffToolChooser : DiffToolChooser(context.project) { private val availableTools = arrayListOf<CombinedDiffTool>().apply { addAll(DiffManagerEx.getInstance().diffTools.filterIsInstance<CombinedDiffTool>()) } private var activeTool: CombinedDiffTool = combinedToolOrder.firstOrNull() ?: availableTools.first() override fun onSelected(project: Project, diffTool: DiffTool) { val combinedDiffTool = diffTool as? CombinedDiffTool ?: return DiffUsageTriggerCollector.logToggleDiffTool(project, diffTool, context.getUserData(DiffUserDataKeys.PLACE)) activeTool = combinedDiffTool moveToolOnTop(diffTool) model.reload() } override fun getTools(): List<FrameDiffTool> = availableTools.toList() override fun getActiveTool(): DiffTool = activeTool override fun getForcedDiffTool(): DiffTool? = null } private inner class MyMainPanel : JBPanelWithEmptyText(BorderLayout()), DataProvider { override fun getPreferredSize(): Dimension { val windowSize = DiffUtil.getDefaultDiffPanelSize() val size = super.getPreferredSize() return Dimension(max(windowSize.width, size.width), max(windowSize.height, size.height)) } override fun getData(dataId: @NonNls String): Any? { val data = DataManagerImpl.getDataProviderEx(contentPanel.targetComponent)?.getData(dataId) if (data != null) return data return when { OpenInEditorAction.KEY.`is`(dataId) -> OpenInEditorAction() DiffDataKeys.DIFF_REQUEST.`is`(dataId) -> model.getCurrentRequest() CommonDataKeys.PROJECT.`is`(dataId) -> context.project PlatformCoreDataKeys.HELP_ID.`is`(dataId) -> { if (context.getUserData(DiffUserDataKeys.HELP_ID) != null) { context.getUserData(DiffUserDataKeys.HELP_ID) } else { "reference.dialogs.diff.file" } } DiffDataKeys.DIFF_CONTEXT.`is`(dataId) -> context else -> model.getCurrentRequest()?.getUserData(DiffUserDataKeys.DATA_PROVIDER)?.getData(dataId) ?: context.getUserData(DiffUserDataKeys.DATA_PROVIDER)?.getData(dataId) } } } private inner class ShowActionGroupPopupAction : DumbAwareAction() { init { ActionUtil.copyFrom(this, "Diff.ShowSettingsPopup") } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun update(e: AnActionEvent) { e.presentation.isEnabled = popupActionGroup.childrenCount > 0 } override fun actionPerformed(e: AnActionEvent) { val popup = JBPopupFactory.getInstance().createActionGroupPopup(DiffBundle.message("diff.actions"), popupActionGroup, e.dataContext, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false) popup.showInCenterOf(panel) } } private inner class MyFocusTraversalPolicy : IdeFocusTraversalPolicy() { override fun getDefaultComponent(focusCycleRoot: Container): Component? { val component: JComponent = getPreferredFocusedComponent() ?: return null return getPreferredFocusedComponent(component, this) } override fun getProject() = context.project } private class MyProgressBar : JProgressBar() { private var progressCount = 0 init { isIndeterminate = true isVisible = false } fun startProgress() { progressCount++ isVisible = true } fun stopProgress() { progressCount-- assert(progressCount >= 0) { "Progress count $progressCount cannot be negative" } if (progressCount == 0) isVisible = false } } companion object { private val SHOW_VIEWER_ACTIONS_IN_TOUCHBAR = getBoolean("touchbar.diff.show.viewer.actions") } }
apache-2.0
a411a9a5957d37d680e7573a77ff5bf9
36.839912
138
0.757867
4.803731
false
false
false
false