content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package com.example.presentation.utils.annotations annotation class ActivityScope
CleanArchExample/presentation/src/main/kotlin/com/example/presentation/utils/annotations/ActivityScope.kt
2676662556
/* * Copyright 2015 Christian Basler * * 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 ch.dissem.bitmessage.server import ch.dissem.bitmessage.entity.BitmessageAddress import com.google.zxing.WriterException import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel import com.google.zxing.qrcode.encoder.Encoder import com.google.zxing.qrcode.encoder.QRCode import org.slf4j.LoggerFactory import java.io.ByteArrayOutputStream import java.io.File import java.io.FileWriter import java.nio.file.Files import java.util.* object Utils { private val LOG = LoggerFactory.getLogger(Utils::class.java) fun readOrCreateList(filename: String, content: String): MutableSet<String> { val file = File(filename).apply { if (!exists()) { if (createNewFile()) { FileWriter(this).use { fw -> fw.write(content) } } } } return readList(file) } fun saveList(filename: String, content: Collection<String>) { FileWriter(filename).use { fw -> content.forEach { l -> fw.write(l) fw.write(System.lineSeparator()) } } } fun readList(file: File) = Files.readAllLines(file.toPath()) .map { it.trim { it <= ' ' } } .filter { it.startsWith("BM-") } .toMutableSet() fun getURL(address: BitmessageAddress, includeKey: Boolean): String { val attributes = mutableListOf<String>() if (address.alias != null) { attributes.add("label=${address.alias}") } if (includeKey) { address.pubkey?.let { pubkey -> val out = ByteArrayOutputStream() pubkey.writer().writeUnencrypted(out) attributes.add("pubkey=${Base64.getUrlEncoder().encodeToString(out.toByteArray())}") } } return if (attributes.isEmpty()) { "bitmessage:${address.address}" } else { "bitmessage:${address.address}?${attributes.joinToString(separator = "&")}" } } fun qrCode(address: BitmessageAddress): String { val code: QRCode try { code = Encoder.encode(getURL(address, false), ErrorCorrectionLevel.L, null) } catch (e: WriterException) { LOG.error(e.message, e) return "" } val matrix = code.matrix val result = StringBuilder() for (i in 0..1) { for (j in 0 until matrix.width + 8) { result.append('█') } result.append('\n') } run { var i = 0 while (i < matrix.height) { result.append("████") for (j in 0 until matrix.width) { if (matrix.get(i, j) > 0) { if (matrix.height > i + 1 && matrix.get(i + 1, j) > 0) { result.append(' ') } else { result.append('▄') } } else { if (matrix.height > i + 1 && matrix.get(i + 1, j) > 0) { result.append('▀') } else { result.append('█') } } } result.append("████\n") i += 2 } } for (i in 0..1) { for (j in 0 until matrix.width + 8) { result.append('█') } result.append('\n') } return result.toString() } fun zero(nonce: ByteArray) = nonce.none { it.toInt() != 0 } }
src/main/kotlin/ch/dissem/bitmessage/server/Utils.kt
969376521
package com.rpkit.skills.bukkit.skills interface RPKSkillType { val name: String }
bukkit/rpk-skill-lib-bukkit/src/main/kotlin/com/rpkit/skills/bukkit/skills/RPKSkillType.kt
599891215
package com.rpkit.blocklog.bukkit.block import com.rpkit.characters.bukkit.character.RPKCharacter import com.rpkit.players.bukkit.profile.RPKMinecraftProfile import com.rpkit.players.bukkit.profile.RPKProfile import org.bukkit.Material class RPKBlockChangeImpl( override var id: Int = 0, override val blockHistory: RPKBlockHistory, override val time: Long, override val profile: RPKProfile?, override val minecraftProfile: RPKMinecraftProfile?, override val character: RPKCharacter?, override val from: Material, override val to: Material, override val reason: String ) : RPKBlockChange
bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/block/RPKBlockChangeImpl.kt
3379624293
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.coroutine import com.mongodb.MongoCommandException import com.mongodb.MongoNamespace import com.mongodb.ReadConcern import com.mongodb.ReadPreference import com.mongodb.WriteConcern import com.mongodb.bulk.BulkWriteResult import com.mongodb.client.model.BulkWriteOptions import com.mongodb.client.model.CountOptions import com.mongodb.client.model.CreateIndexOptions import com.mongodb.client.model.DeleteOptions import com.mongodb.client.model.DropIndexOptions import com.mongodb.client.model.EstimatedDocumentCountOptions import com.mongodb.client.model.FindOneAndDeleteOptions import com.mongodb.client.model.FindOneAndReplaceOptions import com.mongodb.client.model.FindOneAndUpdateOptions import com.mongodb.client.model.IndexModel import com.mongodb.client.model.IndexOptions import com.mongodb.client.model.InsertManyOptions import com.mongodb.client.model.InsertOneOptions import com.mongodb.client.model.RenameCollectionOptions import com.mongodb.client.model.ReplaceOptions import com.mongodb.client.model.UpdateOptions import com.mongodb.client.model.WriteModel import com.mongodb.client.result.DeleteResult import com.mongodb.client.result.InsertManyResult import com.mongodb.client.result.InsertOneResult import com.mongodb.client.result.UpdateResult import com.mongodb.reactivestreams.client.ClientSession import com.mongodb.reactivestreams.client.MongoCollection import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitSingle import org.bson.BsonDocument import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson import org.litote.kmongo.EMPTY_BSON import org.litote.kmongo.SetTo import org.litote.kmongo.and import org.litote.kmongo.ascending import org.litote.kmongo.excludeId import org.litote.kmongo.fields import org.litote.kmongo.include import org.litote.kmongo.path import org.litote.kmongo.reactivestreams.map import org.litote.kmongo.set import org.litote.kmongo.util.KMongoUtil import org.litote.kmongo.util.KMongoUtil.EMPTY_JSON import org.litote.kmongo.util.KMongoUtil.extractId import org.litote.kmongo.util.KMongoUtil.idFilterQuery import org.litote.kmongo.util.KMongoUtil.setModifier import org.litote.kmongo.util.KMongoUtil.toBson import org.litote.kmongo.util.KMongoUtil.toBsonModifier import org.litote.kmongo.util.PairProjection import org.litote.kmongo.util.SingleProjection import org.litote.kmongo.util.TripleProjection import org.litote.kmongo.util.UpdateConfiguration import org.litote.kmongo.util.pairProjectionCodecRegistry import org.litote.kmongo.util.singleProjectionCodecRegistry import org.litote.kmongo.util.tripleProjectionCodecRegistry import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 /** * Gets coroutine version of [MongoCollection]. */ val <T : Any> MongoCollection<T>.coroutine: CoroutineCollection<T> get() = CoroutineCollection(this) /** * A wrapper around [MongoCollection]. * Provides coroutine methods for [Reactive Streams driver](https://mongodb.github.io/mongo-java-driver-reactivestreams/). */ class CoroutineCollection<T : Any>(val collection: MongoCollection<T>) { /** * Gets the namespace of this collection. * * @return the namespace */ val namespace: MongoNamespace get() = collection.namespace /** * Get the class of documents stored in this collection. * * @return the class */ val documentClass: Class<T> get() = collection.documentClass /** * Get the codec registry for the MongoCollection. * * @return the [org.bson.codecs.configuration.CodecRegistry] */ val codecRegistry: CodecRegistry get() = collection.codecRegistry /** * Get the read preference for the MongoCollection. * * @return the [com.mongodb.ReadPreference] */ val readPreference: ReadPreference get() = collection.readPreference /** * Get the write concern for the MongoCollection. * * @return the [com.mongodb.WriteConcern] */ val writeConcern: WriteConcern get() = collection.writeConcern /** * Get the read concern for the MongoCollection. * * @return the [com.mongodb.ReadConcern] * @mongodb.server.release 3.2 * @since 1.2 */ val readConcern: ReadConcern get() = collection.readConcern /** * Create a new MongoCollection instance with a different default class to cast any documents returned from the database into.. * * @param <NewT> The type that the new collection will encode documents from and decode documents to * @return a new MongoCollection instance with the different default class */ inline fun <reified NewT : Any> withDocumentClass(): CoroutineCollection<NewT> = collection.withDocumentClass(NewT::class.java).coroutine /** * Create a new MongoCollection instance with a different codec registry. * * @param codecRegistry the new [org.bson.codecs.configuration.CodecRegistry] for the collection * @return a new MongoCollection instance with the different codec registry */ fun withCodecRegistry(codecRegistry: CodecRegistry): CoroutineCollection<T> = collection.withCodecRegistry(codecRegistry).coroutine /** * Create a new MongoCollection instance with a different read preference. * * @param readPreference the new [com.mongodb.ReadPreference] for the collection * @return a new MongoCollection instance with the different readPreference */ fun withReadPreference(readPreference: ReadPreference): CoroutineCollection<T> = collection.withReadPreference(readPreference).coroutine /** * Create a new MongoCollection instance with a different write concern. * * @param writeConcern the new [com.mongodb.WriteConcern] for the collection * @return a new MongoCollection instance with the different writeConcern */ fun withWriteConcern(writeConcern: WriteConcern): CoroutineCollection<T> = collection.withWriteConcern(writeConcern).coroutine /** * Create a new MongoCollection instance with a different read concern. * * @param readConcern the new [ReadConcern] for the collection * @return a new MongoCollection instance with the different ReadConcern * @mongodb.server.release 3.2 * @since 1.2 */ fun withReadConcern(readConcern: ReadConcern): CoroutineCollection<T> = collection.withReadConcern(readConcern).coroutine /** * Gets an estimate of the count of documents in a collection using collection metadata. * * @param options the options describing the count * @since 1.9 */ suspend fun estimatedDocumentCount(options: EstimatedDocumentCountOptions = EstimatedDocumentCountOptions()): Long = collection.estimatedDocumentCount(options).awaitSingle() /** * Counts the number of documents in the collection according to the given options. * * * * Note: When migrating from `count()` to `countDocuments()` the following query operators must be replaced: * * <pre> * * +-------------+--------------------------------+ * | Operator | Replacement | * +=============+================================+ * | $where | $expr | * +-------------+--------------------------------+ * | $near | $geoWithin with $center | * +-------------+--------------------------------+ * | $nearSphere | $geoWithin with $centerSphere | * +-------------+--------------------------------+ </pre> * * * @param filter the query filter * @param options the options describing the count * @since 1.9 */ suspend fun countDocuments(filter: Bson = EMPTY_BSON, options: CountOptions = CountOptions()): Long = collection.countDocuments(filter, options).awaitSingle() /** * Counts the number of documents in the collection according to the given options. * * * * Note: When migrating from `count()` to `countDocuments()` the following query operators must be replaced: * * <pre> * * +-------------+--------------------------------+ * | Operator | Replacement | * +=============+================================+ * | $where | $expr | * +-------------+--------------------------------+ * | $near | $geoWithin with $center | * +-------------+--------------------------------+ * | $nearSphere | $geoWithin with $centerSphere | * +-------------+--------------------------------+ </pre> * * * @param clientSession the client session with which to associate this operation * @param filter the query filter * @param options the options describing the count * @mongodb.server.release 3.6 * @since 1.9 */ suspend fun countDocuments( clientSession: ClientSession, filter: Bson = EMPTY_BSON, options: CountOptions = CountOptions() ): Long = collection.countDocuments(clientSession, filter, options).awaitSingle() /** * Gets the distinct values of the specified field name. * * @param fieldName the field name * @param filter the query filter * @param <T> the target type of the iterable. * @mongodb.driver.manual reference/command/distinct/ Distinct */ inline fun <reified T : Any> distinct( fieldName: String, filter: Bson = EMPTY_BSON ): CoroutineDistinctPublisher<T> = collection.distinct(fieldName, filter, T::class.java).coroutine /** * Gets the distinct values of the specified field name. * * @param clientSession the client session with which to associate this operation * @param fieldName the field name * @param filter the query filter * @param <T> the target type of the iterable. * @mongodb.driver.manual reference/command/distinct/ Distinct * @mongodb.server.release 3.6 * @since 1.7 */ inline fun <reified T : Any> distinct( clientSession: ClientSession, fieldName: String, filter: Bson ): CoroutineDistinctPublisher<T> = collection.distinct(clientSession, fieldName, filter, T::class.java).coroutine /** * Finds all documents in the collection. * * @param filter the query filter * @mongodb.driver.manual tutorial/query-documents/ Find */ fun find(filter: Bson = EMPTY_BSON): CoroutineFindPublisher<T> = collection.find(filter).coroutine /** * Finds all documents in the collection. * * @param filter the query filter * @param <T> the target document type of the iterable. * @mongodb.driver.manual tutorial/query-documents/ Find */ inline fun <reified T : Any> findAndCast(filter: Bson = EMPTY_BSON): CoroutineFindPublisher<T> = collection.find(filter, T::class.java).coroutine /** * Finds all documents in the collection. * * @param clientSession the client session with which to associate this operation * @param filter the query filter * @mongodb.driver.manual tutorial/query-documents/ Find * @mongodb.server.release 3.6 * @since 1.7 */ fun find(clientSession: ClientSession, filter: Bson = EMPTY_BSON): CoroutineFindPublisher<T> = collection.find(clientSession, filter).coroutine /** * Finds all documents in the collection. * * @param clientSession the client session with which to associate this operation * @param filter the query filter * @param <T> the target document type of the iterable. * @mongodb.driver.manual tutorial/query-documents/ Find * @mongodb.server.release 3.6 * @since 1.7 */ inline fun <reified T : Any> findAndCast( clientSession: ClientSession, filter: Bson ): CoroutineFindPublisher<T> = collection.find(clientSession, filter, T::class.java).coroutine /** * Aggregates documents according to the specified aggregation pipeline. * * @param pipeline the aggregate pipeline * @param <T> the target document type of the iterable. * @return a publisher containing the result of the aggregation operation * @mongodb.driver.manual aggregation/ Aggregation */ inline fun <reified T : Any> aggregate(pipeline: List<Bson>): CoroutineAggregatePublisher<T> = collection.aggregate(pipeline, T::class.java).coroutine /** * Aggregates documents according to the specified aggregation pipeline. * * @param clientSession the client session with which to associate this operation * @param pipeline the aggregate pipeline * @param <T> the target document type of the iterable. * @return a publisher containing the result of the aggregation operation * @mongodb.driver.manual aggregation/ Aggregation * @mongodb.server.release 3.6 * @since 1.7 */ inline fun <reified T : Any> aggregate( clientSession: ClientSession, pipeline: List<Bson> ): CoroutineAggregatePublisher<T> = collection.aggregate(clientSession, pipeline, T::class.java).coroutine /** * Creates a change stream for this collection. * * @param pipeline the aggregation pipeline to apply to the change stream * @param <T> the target document type of the iterable. * @return the change stream iterable * @mongodb.driver.manual reference/operator/aggregation/changeStream $changeStream * @since 1.6 */ inline fun <reified T : Any> watch(pipeline: List<Bson> = emptyList()): CoroutineChangeStreamPublisher<T> = collection.watch(pipeline, T::class.java).coroutine /** * Creates a change stream for this collection. * * @param clientSession the client session with which to associate this operation * @param pipeline the aggregation pipeline to apply to the change stream * @param <T> the target document type of the iterable. * @return the change stream iterable * @mongodb.driver.manual reference/operator/aggregation/changeStream $changeStream * @mongodb.server.release 3.6 * @since 1.7 */ inline fun <reified T : Any> watch( clientSession: ClientSession, pipeline: List<Bson> ): CoroutineChangeStreamPublisher<T> = collection.watch(clientSession, pipeline, T::class.java).coroutine /** * Aggregates documents according to the specified map-reduce function. * * @param mapFunction A JavaScript function that associates or "maps" a value with a key and emits the key and value pair. * @param reduceFunction A JavaScript function that "reduces" to a single object all the values associated with a particular key. * @param <T> the target document type of the iterable. * @return a publisher containing the result of the map-reduce operation * @mongodb.driver.manual reference/command/mapReduce/ map-reduce */ inline fun <reified T : Any> mapReduce( mapFunction: String, reduceFunction: String ): CoroutineMapReducePublisher<T> = collection.mapReduce(mapFunction, reduceFunction, T::class.java).coroutine /** * Aggregates documents according to the specified map-reduce function. * * @param clientSession the client session with which to associate this operation * @param mapFunction A JavaScript function that associates or "maps" a value with a key and emits the key and value pair. * @param reduceFunction A JavaScript function that "reduces" to a single object all the values associated with a particular key. * @param <T> the target document type of the iterable. * @return a publisher containing the result of the map-reduce operation * @mongodb.driver.manual reference/command/mapReduce/ map-reduce * @mongodb.server.release 3.6 * @since 1.7 */ inline fun <reified T : Any> mapReduce( clientSession: ClientSession, mapFunction: String, reduceFunction: String ): CoroutineMapReducePublisher<T> = collection.mapReduce(clientSession, mapFunction, reduceFunction, T::class.java).coroutine /** * Executes a mix of inserts, updates, replaces, and deletes. * * @param requests the writes to execute * @param options the options to apply to the bulk write operation * @return the BulkWriteResult */ suspend fun bulkWrite( requests: List<WriteModel<out T>>, options: BulkWriteOptions = BulkWriteOptions() ): BulkWriteResult = collection.bulkWrite(requests, options).awaitSingle() /** * Executes a mix of inserts, updates, replaces, and deletes. * * @param clientSession the client session with which to associate this operation * @param requests the writes to execute * @param options the options to apply to the bulk write operation * @return the BulkWriteResult * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun bulkWrite( clientSession: ClientSession, requests: List<WriteModel<out T>>, options: BulkWriteOptions = BulkWriteOptions() ): BulkWriteResult = collection.bulkWrite(clientSession, requests, options).awaitSingle() /** * Inserts the provided document. If the document is missing an identifier, the driver should generate one. * * @param document the document to insert * @param options the options to apply to the operation * com.mongodb.DuplicateKeyException or com.mongodb.MongoException * @since 1.2 */ suspend fun insertOne(document: T, options: InsertOneOptions = InsertOneOptions()): InsertOneResult = collection.insertOne(document, options).awaitSingle() /** * Inserts the provided document. If the document is missing an identifier, the driver should generate one. * * @param clientSession the client session with which to associate this operation * @param document the document to insert * @param options the options to apply to the operation * com.mongodb.DuplicateKeyException or com.mongodb.MongoException * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun insertOne( clientSession: ClientSession, document: T, options: InsertOneOptions = InsertOneOptions() ): InsertOneResult = collection.insertOne(clientSession, document, options).awaitSingle() /** * Inserts a batch of documents. The preferred way to perform bulk inserts is to use the BulkWrite API. However, when talking with a * server &lt; 2.6, using this method will be faster due to constraints in the bulk API related to error handling. * * @param documents the documents to insert * @param options the options to apply to the operation * com.mongodb.DuplicateKeyException or com.mongodb.MongoException */ suspend fun insertMany(documents: List<T>, options: InsertManyOptions = InsertManyOptions()): InsertManyResult = collection.insertMany(documents, options).awaitSingle() /** * Inserts a batch of documents. The preferred way to perform bulk inserts is to use the BulkWrite API. However, when talking with a * server &lt; 2.6, using this method will be faster due to constraints in the bulk API related to error handling. * * @param clientSession the client session with which to associate this operation * @param documents the documents to insert * @param options the options to apply to the operation * com.mongodb.DuplicateKeyException or com.mongodb.MongoException * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun insertMany( clientSession: ClientSession, documents: List<T>, options: InsertManyOptions = InsertManyOptions() ): InsertManyResult = collection.insertMany(clientSession, documents, options).awaitSingle() /** * Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not * modified. * * @param filter the query filter to apply the the delete operation * @param options the options to apply to the delete operation * @return the DeleteResult or an com.mongodb.MongoException * @since 1.5 */ suspend fun deleteOne(filter: Bson, options: DeleteOptions = DeleteOptions()): DeleteResult = collection.deleteOne(filter, options).awaitSingle() /** * Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not * modified. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the delete operation * @param options the options to apply to the delete operation * @return the DeleteResult or an com.mongodb.MongoException * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun deleteOne( clientSession: ClientSession, filter: Bson, options: DeleteOptions = DeleteOptions() ): DeleteResult = collection.deleteOne(clientSession, filter, options).awaitSingle() /** * Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified. * * @param filter the query filter to apply the the delete operation * @param options the options to apply to the delete operation * @return the DeleteResult or an com.mongodb.MongoException * @since 1.5 */ suspend fun deleteMany(filter: Bson, options: DeleteOptions = DeleteOptions()): DeleteResult = collection.deleteMany(filter, options).awaitSingle() /** * Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the delete operation * @param options the options to apply to the delete operation * @return the DeleteResult or an com.mongodb.MongoException * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun deleteMany( clientSession: ClientSession, filter: Bson, options: DeleteOptions = DeleteOptions() ): DeleteResult = collection.deleteMany(clientSession, filter, options).awaitSingle() /** * Replace a document in the collection according to the specified arguments. * * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the replace operation * @return he UpdateResult * @mongodb.driver.manual tutorial/modify-documents/#replace-the-document Replace * @since 1.8 */ suspend fun replaceOne(filter: Bson, replacement: T, options: ReplaceOptions = ReplaceOptions()): UpdateResult = collection.replaceOne(filter, replacement, options).awaitSingle() /** * Replace a document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the replace operation * @return the UpdateResult * @mongodb.driver.manual tutorial/modify-documents/#replace-the-document Replace * @mongodb.server.release 3.6 * @since 1.8 */ suspend fun replaceOne( clientSession: ClientSession, filter: Bson, replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = collection.replaceOne(clientSession, filter, replacement, options).awaitSingle() /** * Update a single document in the collection according to the specified arguments. * * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. * @param options the options to apply to the update operation * @return the UpdateResult * @mongodb.driver.manual tutorial/modify-documents/ Updates * @mongodb.driver.manual reference/operator/update/ Update Operators */ suspend fun updateOne(filter: Bson, update: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult = collection.updateOne(filter, update, options).awaitSingle() /** * Update a single document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. * @param options the options to apply to the update operation * @return the UpdateResult * @mongodb.driver.manual tutorial/modify-documents/ Updates * @mongodb.driver.manual reference/operator/update/ Update Operators * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun updateOne( clientSession: ClientSession, filter: Bson, update: Bson, options: UpdateOptions = UpdateOptions() ): UpdateResult = collection.updateOne(clientSession, filter, update, options).awaitSingle() /** * Update all documents in the collection according to the specified arguments. * * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. * @param options the options to apply to the update operation * @return the UpdateResult * @mongodb.driver.manual tutorial/modify-documents/ Updates * @mongodb.driver.manual reference/operator/update/ Update Operators */ suspend fun updateMany(filter: Bson, update: Bson, options: UpdateOptions = UpdateOptions()): UpdateResult = collection.updateMany(filter, update, options).awaitSingle() /** * Update all documents in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. * @param options the options to apply to the update operation * @return the UpdateResult * @mongodb.driver.manual tutorial/modify-documents/ Updates * @mongodb.driver.manual reference/operator/update/ Update Operators * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun updateMany( clientSession: ClientSession, filter: Bson, update: Bson, options: UpdateOptions = UpdateOptions() ): UpdateResult = collection.updateMany(clientSession, filter, update, options).awaitSingle() /** * Atomically find a document and remove it. * * @param filter the query filter to find the document with * @param options the options to apply to the operation * @return the document that was removed. If no documents matched the query filter, then null will be * returned */ suspend fun findOneAndDelete(filter: Bson, options: FindOneAndDeleteOptions = FindOneAndDeleteOptions()): T? = collection.findOneAndDelete(filter, options).awaitFirstOrNull() /** * Atomically find a document and remove it. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to find the document with * @param options the options to apply to the operation * @return a publisher with a single element the document that was removed. If no documents matched the query filter, then null will be * returned * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun findOneAndDelete( clientSession: ClientSession, filter: Bson, options: FindOneAndDeleteOptions = FindOneAndDeleteOptions() ): T? = collection.findOneAndDelete(clientSession, filter, options).awaitFirstOrNull() /** * Atomically find a document and replace it. * * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * @return the document that was replaced. Depending on the value of the `returnOriginal` * property, this will either be the document as it was before the update or as it is after the update. If no documents matched the * query filter, then null will be returned */ suspend fun findOneAndReplace( filter: Bson, replacement: T, options: FindOneAndReplaceOptions = FindOneAndReplaceOptions() ): T? = collection.findOneAndReplace(filter, replacement, options).awaitFirstOrNull() /** * Atomically find a document and replace it. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * @return the document that was replaced. Depending on the value of the `returnOriginal` * property, this will either be the document as it was before the update or as it is after the update. If no documents matched the * query filter, then null will be returned * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun findOneAndReplace( clientSession: ClientSession, filter: Bson, replacement: T, options: FindOneAndReplaceOptions = FindOneAndReplaceOptions() ): T? = collection.findOneAndReplace(clientSession, filter, replacement, options).awaitFirstOrNull() /** * Atomically find a document and update it. * * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. * @param options the options to apply to the operation * @return the document that was updated. Depending on the value of the `returnOriginal` * property, this will either be the document as it was before the update or as it is after the update. If no documents matched the * query filter, then null will be returned */ suspend fun findOneAndUpdate( filter: Bson, update: Bson, options: FindOneAndUpdateOptions = FindOneAndUpdateOptions() ): T? = collection.findOneAndUpdate(filter, update, options).awaitFirstOrNull() /** * Atomically find a document and update it. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter, which may not be null. * @param update a document describing the update, which may not be null. The update to apply must include only update operators. * @param options the options to apply to the operation * @return a publisher with a single element the document that was updated. Depending on the value of the `returnOriginal` * property, this will either be the document as it was before the update or as it is after the update. If no documents matched the * query filter, then null will be returned * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun findOneAndUpdate( clientSession: ClientSession, filter: Bson, update: Bson, options: FindOneAndUpdateOptions = FindOneAndUpdateOptions() ): T? = collection.findOneAndUpdate(clientSession, filter, update, options).awaitFirstOrNull() /** * Drops this collection from the Database. * * @mongodb.driver.manual reference/command/drop/ Drop Collection */ suspend fun drop() = collection.drop().awaitFirstOrNull() /** * Drops this collection from the Database. * * @param clientSession the client session with which to associate this operation * @mongodb.driver.manual reference/command/drop/ Drop Collection * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun drop(clientSession: ClientSession) = collection.drop(clientSession).awaitFirstOrNull() /** * Creates an index. * * @param key an object describing the index key(s), which may not be null. * @param options the options for the index * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/method/db.collection.ensureIndex Ensure Index */ suspend fun createIndex(key: Bson, options: IndexOptions = IndexOptions()): String = collection.createIndex(key, options).awaitSingle() /** * Creates an index. * * @param clientSession the client session with which to associate this operation * @param key an object describing the index key(s), which may not be null. * @param options the options for the index * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/method/db.collection.ensureIndex Ensure Index * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun createIndex(clientSession: ClientSession, key: Bson, options: IndexOptions = IndexOptions()): String = collection.createIndex(clientSession, key, options).awaitSingle() /** * Create multiple indexes. * * @param indexes the list of indexes * @param createIndexOptions options to use when creating indexes * @return a list of elements indicating index creation operation completion * @mongodb.driver.manual reference/command/createIndexes Create indexes * @mongodb.server.release 2.6 * @since 1.7 */ suspend fun createIndexes( indexes: List<IndexModel>, createIndexOptions: CreateIndexOptions = CreateIndexOptions() ): List<String> = collection.createIndexes(indexes, createIndexOptions).toList() /** * Create multiple indexes. * * @param clientSession the client session with which to associate this operation * @param indexes the list of indexes * @param createIndexOptions options to use when creating indexes * @return a list of elements indicating index creation operation completion * @mongodb.driver.manual reference/command/createIndexes Create indexes * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun createIndexes( clientSession: ClientSession, indexes: List<IndexModel>, createIndexOptions: CreateIndexOptions = CreateIndexOptions() ): List<String> = collection.createIndexes(clientSession, indexes, createIndexOptions).toList() /** * Get all the indexes in this collection. * * @param <T> the target document type of the iterable. * @return the fluent list indexes interface * @mongodb.driver.manual reference/command/listIndexes/ listIndexes */ inline fun <reified T : Any> listIndexes(): CoroutineListIndexesPublisher<T> = collection.listIndexes(T::class.java).coroutine /** * Get all the indexes in this collection. * * @param clientSession the client session with which to associate this operation * @param <T> the target document type of the iterable. * @return the fluent list indexes interface * @mongodb.driver.manual reference/command/listIndexes/ listIndexes * @mongodb.server.release 3.6 * @since 1.7 */ inline fun <reified T : Any> listIndexes( clientSession: ClientSession ): CoroutineListIndexesPublisher<T> = collection.listIndexes(clientSession, T::class.java).coroutine /** * Drops the given index. * * @param indexName the name of the index to remove * @param dropIndexOptions options to use when dropping indexes * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes * @since 1.7 */ suspend fun dropIndex(indexName: String, dropIndexOptions: DropIndexOptions = DropIndexOptions()) = collection.dropIndex(indexName, dropIndexOptions).awaitFirstOrNull() /** * Drops the index given the keys used to create it. * * @param keys the keys of the index to remove * @param dropIndexOptions options to use when dropping indexes * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes * @since 1.7 */ suspend fun dropIndex(keys: Bson, dropIndexOptions: DropIndexOptions = DropIndexOptions()) = collection.dropIndex(keys, dropIndexOptions).awaitFirstOrNull() /** * Drops the given index. * * @param clientSession the client session with which to associate this operation * @param indexName the name of the index to remove * @param dropIndexOptions options to use when dropping indexes * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun dropIndex( clientSession: ClientSession, indexName: String, dropIndexOptions: DropIndexOptions = DropIndexOptions() ) = collection.dropIndex(clientSession, indexName, dropIndexOptions).awaitFirstOrNull() /** * Drops the index given the keys used to create it. * * @param clientSession the client session with which to associate this operation * @param keys the keys of the index to remove * @param dropIndexOptions options to use when dropping indexes * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/command/dropIndexes/ Drop indexes * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun dropIndex( clientSession: ClientSession, keys: Bson, dropIndexOptions: DropIndexOptions = DropIndexOptions() ) = collection.dropIndex(clientSession, keys, dropIndexOptions).awaitFirstOrNull() /** * Drop all the indexes on this collection, except for the default on _id. * * @param dropIndexOptions options to use when dropping indexes * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes * @since 1.7 */ suspend fun dropIndexes(dropIndexOptions: DropIndexOptions = DropIndexOptions()) = collection.dropIndexes(dropIndexOptions).awaitFirstOrNull() /** * Drop all the indexes on this collection, except for the default on _id. * * @param clientSession the client session with which to associate this operation * @param dropIndexOptions options to use when dropping indexes * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/command/dropIndexes/ Drop Indexes * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun dropIndexes( clientSession: ClientSession, dropIndexOptions: DropIndexOptions = DropIndexOptions() ) = collection.dropIndexes(clientSession, dropIndexOptions).awaitFirstOrNull() /** * Rename the collection with oldCollectionName to the newCollectionName. * * @param newCollectionNamespace the name the collection will be renamed to * @param options the options for renaming a collection * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/commands/renameCollection Rename collection */ suspend fun renameCollection( newCollectionNamespace: MongoNamespace, options: RenameCollectionOptions = RenameCollectionOptions() ) = collection.renameCollection(newCollectionNamespace, options).awaitFirstOrNull() /** * Rename the collection with oldCollectionName to the newCollectionName. * * @param clientSession the client session with which to associate this operation * @param newCollectionNamespace the name the collection will be renamed to * @param options the options for renaming a collection * @return a single element indicating when the operation has completed * @mongodb.driver.manual reference/commands/renameCollection Rename collection * @mongodb.server.release 3.6 * @since 1.7 */ suspend fun renameCollection( clientSession: ClientSession, newCollectionNamespace: MongoNamespace, options: RenameCollectionOptions = RenameCollectionOptions() ) = collection.renameCollection(clientSession, newCollectionNamespace, options).awaitFirstOrNull() /** KMongo extensions **/ /** * Counts the number of documents in the collection according to the given options. * * @param filter the query filter * @return count of filtered collection */ suspend fun countDocuments(filter: String, options: CountOptions = CountOptions()): Long = countDocuments(toBson(filter), options) /** * Counts the number of documents in the collection according to the given options. * * @param clientSession the client session with which to associate this operation * @param filter the query filter * @param options optional parameter, the options describing the count * @return count of filtered collection */ suspend fun countDocuments( clientSession: ClientSession, filter: String, options: CountOptions = CountOptions() ): Long = countDocuments(clientSession, toBson(filter), options) /** * Gets the distinct values of the specified field name. * * @param fieldName the field name * @param filter the query filter * @param <Type> the target type of the iterable */ inline fun <reified Type : Any> distinct( fieldName: String, filter: String ): CoroutineDistinctPublisher<Type> = distinct(fieldName, toBson(filter)) /** * Gets the distinct values of the specified field. * * @param field the field * @param filter the query filter * @param <Type> the target type of the iterable. */ inline fun <reified Type : Any> distinct( field: KProperty1<T, Type>, filter: Bson = EMPTY_BSON ): CoroutineDistinctPublisher<Type> = distinct(field.path(), filter) /** * Finds all documents that match the filter in the collection. * * @param filter the query filter * @return the find iterable interface */ fun find(filter: String): CoroutineFindPublisher<T> = find(toBson(filter)) /** * Finds all documents in the collection. * * @param filters the query filters * @return the find iterable interface */ fun find(vararg filters: Bson?): CoroutineFindPublisher<T> = find(and(*filters)) /** * Finds the first document that match the filter in the collection. * * @param filter the query filter */ suspend fun findOne(filter: String = KMongoUtil.EMPTY_JSON): T? = find(filter).first() /** * Finds the first document that match the filter in the collection. * * @param clientSession the client session with which to associate this operation * @param filter the query filter */ suspend fun findOne( clientSession: ClientSession, filter: String = KMongoUtil.EMPTY_JSON ): T? = find(clientSession, toBson(filter)).first() /** * Finds the first document that match the filter in the collection. * * @param filter the query filter */ suspend fun findOne(filter: Bson): T? = find(filter).first() /** * Finds the first document that match the filter in the collection. * * @param clientSession the client session with which to associate this operation * @param filter the query filter */ suspend fun findOne(clientSession: ClientSession, filter: Bson = EMPTY_BSON): T? = find(clientSession, filter).first() /** * Finds the first document that match the filters in the collection. * * @param filters the query filters * @return the first item returned or null */ suspend fun findOne(vararg filters: Bson?): T? = find(*filters).first() /** * Finds the document that match the id parameter. * * @param id the object id */ suspend fun findOneById(id: Any): T? = findOne(idFilterQuery(id)) /** * Finds the document that match the id parameter. * * @param id the object id * @param clientSession the client session with which to associate this operation */ suspend fun findOneById(id: Any, clientSession: ClientSession): T? { return findOne(clientSession, idFilterQuery(id)) } /** * Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not * modified. * * @param filter the query filter to apply the the delete operation * * @return the result of the remove one operation */ suspend fun deleteOne( filter: String, deleteOptions: DeleteOptions = DeleteOptions() ): DeleteResult = deleteOne(toBson(filter), deleteOptions) /** * Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not * modified. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the delete operation * * @return the result of the remove one operation */ suspend fun deleteOne( clientSession: ClientSession, filter: String, deleteOptions: DeleteOptions = DeleteOptions() ): DeleteResult = deleteOne(clientSession, toBson(filter), deleteOptions) /** * Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not * modified. * * @param filters the query filters to apply the the delete operation * * @return the result of the remove one operation */ suspend fun deleteOne( vararg filters: Bson?, deleteOptions: DeleteOptions = DeleteOptions() ): DeleteResult = deleteOne(and(*filters), deleteOptions) /** * Removes at most one document from the collection that matches the given filter. If no documents match, the collection is not * modified. * @param clientSession the client session with which to associate this operation * @param filters the query filters to apply the the delete operation * * @return the result of the remove one operation */ suspend fun deleteOne( clientSession: ClientSession, vararg filters: Bson?, deleteOptions: DeleteOptions = DeleteOptions() ): DeleteResult = deleteOne(clientSession, and(*filters), deleteOptions) /** * Removes at most one document from the id parameter. If no documents match, the collection is not * modified. * * @param id the object id */ suspend fun deleteOneById(id: Any): DeleteResult = deleteOne(idFilterQuery(id)) /** * Removes at most one document from the id parameter. If no documents match, the collection is not * modified. * * @param clientSession the client session with which to associate this operation * @param id the object id */ suspend fun deleteOneById(clientSession: ClientSession, id: Any): DeleteResult = deleteOne(clientSession, idFilterQuery(id)) /** * Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified. * @param filter the query filter to apply the the delete operation * @param options the options to apply to the delete operation * * @return the result of the remove many operation */ suspend fun deleteMany( filter: String = EMPTY_JSON, options: DeleteOptions = DeleteOptions() ): DeleteResult = deleteMany(toBson(filter), options) /** * Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the delete operation * @param options the options to apply to the delete operation * * @return the result of the remove many operation */ suspend fun deleteMany( clientSession: ClientSession, filter: String = EMPTY_JSON, options: DeleteOptions = DeleteOptions() ): DeleteResult = deleteMany(clientSession, toBson(filter), options) /** * Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified. * * @param filters the query filters to apply the the delete operation * @param options the options to apply to the delete operation * * @return the result of the remove many operation */ suspend fun deleteMany( vararg filters: Bson?, options: DeleteOptions = DeleteOptions() ): DeleteResult = deleteMany(and(*filters), options) /** * Removes all documents from the collection that match the given query filter. If no documents match, the collection is not modified. * * @param clientSession the client session with which to associate this operation * @param filters the query filters to apply the the delete operation * @param options the options to apply to the delete operation * * @return the result of the remove many operation */ suspend fun deleteMany( clientSession: ClientSession, vararg filters: Bson?, options: DeleteOptions = DeleteOptions() ): DeleteResult = deleteMany(clientSession, and(*filters), options) /** * Save the document. * If the document has no id field, or if the document has a null id value, insert the document. * Otherwise, call [replaceOneById] with upsert true. * * @param document the document to save */ suspend fun save(document: T): UpdateResult? { val id = KMongoUtil.getIdValue(document) return if (id != null) { replaceOneById(id, document, ReplaceOptions().upsert(true)) } else { insertOne(document) null } } /** * Save the document. * If the document has no id field, or if the document has a null id value, insert the document. * Otherwise, call [replaceOneById] with upsert true. * * @param clientSession the client session with which to associate this operation * @param document the document to save */ suspend fun save(clientSession: ClientSession, document: T): UpdateResult? { val id = KMongoUtil.getIdValue(document) return if (id != null) { replaceOneById(clientSession, id, document, ReplaceOptions().upsert(true)) } else { insertOne(clientSession, document) null } } /** * Replace a document in the collection according to the specified arguments. * * @param id the object id * @param replacement the replacement document * @param options the options to apply to the replace operation * * @return the result of the replace one operation */ suspend fun <T : Any> replaceOneById( id: Any, replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = replaceOneWithoutId<T>(idFilterQuery(id), replacement, options) /** * Replace a document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param id the object id * @param replacement the replacement document * @param options the options to apply to the replace operation * * @return the result of the replace one operation */ suspend fun replaceOneById( clientSession: ClientSession, id: Any, replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = replaceOneWithoutId(clientSession, idFilterQuery(id), replacement, options) /** * Replace a document in the collection according to the specified arguments. * * @param filter the query filter to apply to the replace operation * @param replacement the replacement document * @param options the options to apply to the replace operation * * @return the result of the replace one operation */ suspend fun replaceOne( filter: String, replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = replaceOne(toBson(filter), replacement, options) /** * Replace a document in the collection according to the specified arguments. * The id of the provided document is not used, in order to avoid updated id error. * You may have to use [UpdateResult.getUpsertedId] in order to retrieve the generated id. * * @param filter the query filter to apply to the replace operation * @param replacement the replacement document * @param options the options to apply to the replace operation * * @return the result of the replace one operation */ suspend fun <T : Any> replaceOneWithoutId( filter: Bson, replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = withDocumentClass<BsonDocument>().replaceOne( filter, KMongoUtil.filterIdToBson(replacement), options ) /** * Replace a document in the collection according to the specified arguments. * The id of the provided document is not used, in order to avoid updated id error. * You may have to use [UpdateResult.getUpsertedId] in order to retrieve the generated id. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply to the replace operation * @param replacement the replacement document * @param options the options to apply to the replace operation * * @return the result of the replace one operation */ suspend fun replaceOneWithoutId( clientSession: ClientSession, filter: Bson, replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = withDocumentClass<BsonDocument>().replaceOne( clientSession, filter, KMongoUtil.filterIdToBson(replacement), options ) /** * Update a single document in the collection according to the specified arguments. * * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param options the options to apply to the update operation * * @return the result of the update one operation */ suspend fun updateOne( filter: String, update: String, options: UpdateOptions = UpdateOptions() ): UpdateResult = updateOne(toBson(filter), toBson(update), options) /** * Update a single document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param options the options to apply to the update operation * * @return the result of the update one operation */ suspend fun updateOne( clientSession: ClientSession, filter: String, update: String, options: UpdateOptions = UpdateOptions() ): UpdateResult = updateOne( clientSession, toBson(filter), toBson(update), options ) /** * Update a single document in the collection according to the specified arguments. * * @param filter a document describing the query filter * @param update the update object * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend fun updateOne( filter: String, update: Any, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOne(toBson(filter), setModifier(update, updateOnlyNotNullProperties), options) /** * Update a single document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter * @param update the update object * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend fun updateOne( clientSession: ClientSession, filter: String, update: Any, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOne( clientSession, toBson(filter), setModifier(update, updateOnlyNotNullProperties), options ) /** * Update a single document in the collection according to the specified arguments. * * @param filter a document describing the query filter * @param target the update object - must have an non null id * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend fun updateOne( filter: Bson, target: T, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOne(filter, toBsonModifier(target, updateOnlyNotNullProperties), options) /** * Update a single document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter * @param target the update object - must have an non null id * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend fun updateOne( clientSession: ClientSession, filter: Bson, target: T, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOne(clientSession, filter, toBsonModifier(target, updateOnlyNotNullProperties), options) /** * Update a single document in the collection according to the specified arguments. * * @param id the object id * @param update the update object * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend fun updateOneById( id: Any, update: Any, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOne( idFilterQuery(id), toBsonModifier(update, updateOnlyNotNullProperties), options ) /** * Update a single document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param id the object id * @param update the update object * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend fun updateOneById( clientSession: ClientSession, id: Any, update: Any, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOne( clientSession, idFilterQuery(id), toBsonModifier(update, updateOnlyNotNullProperties), options ) /** * Update all documents in the collection according to the specified arguments. * * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param updateOptions the options to apply to the update operation * * @return the result of the update many operation */ suspend fun updateMany( filter: String, update: String, updateOptions: UpdateOptions = UpdateOptions() ): UpdateResult = updateMany(toBson(filter), toBson(update), updateOptions) /** * Update all documents in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param updateOptions the options to apply to the update operation * * @return the result of the update many operation */ suspend fun updateMany( clientSession: ClientSession, filter: String, update: String, updateOptions: UpdateOptions = UpdateOptions() ): UpdateResult = updateMany( clientSession, toBson(filter), toBson(update), updateOptions ) /** * Update all documents in the collection according to the specified arguments. * * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param updateOptions the options to apply to the update operation * * @return the result of the update many operation */ suspend fun updateMany( filter: Bson, vararg updates: SetTo<*>, updateOptions: UpdateOptions = UpdateOptions() ): UpdateResult = updateMany(filter, set(*updates), updateOptions) /** * Update all documents in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param updateOptions the options to apply to the update operation * * @return the result of the update many operation */ suspend fun updateMany( clientSession: ClientSession, filter: Bson, vararg updates: SetTo<*>, updateOptions: UpdateOptions = UpdateOptions() ): UpdateResult = updateMany(clientSession, filter, set(*updates), updateOptions) /** * Atomically find a document and remove it. * * @param filter the query filter to find the document with * @param options the options to apply to the operation * * @return the document that was removed. If no documents matched the query filter, then null will be returned */ suspend fun findOneAndDelete( filter: String, options: FindOneAndDeleteOptions = FindOneAndDeleteOptions() ): T? = findOneAndDelete(toBson(filter), options) /** * Atomically find a document and remove it. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to find the document with * @param options the options to apply to the operation * * @return the document that was removed. If no documents matched the query filter, then null will be returned */ suspend fun findOneAndDelete( clientSession: ClientSession, filter: String, options: FindOneAndDeleteOptions = FindOneAndDeleteOptions() ): T? = findOneAndDelete(clientSession, toBson(filter), options) /** * Atomically find a document and replace it. * * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * * @return the document that was replaced. Depending on the value of the `returnOriginal` property, this will either be the * document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be * returned */ suspend fun findOneAndReplace( filter: String, replacement: T, options: FindOneAndReplaceOptions = FindOneAndReplaceOptions() ): T? = findOneAndReplace(toBson(filter), replacement, options) /** * Atomically find a document and replace it. * * @param clientSession the client session with which to associate this operation * @param filter the query filter to apply the the replace operation * @param replacement the replacement document * @param options the options to apply to the operation * * @return the document that was replaced. Depending on the value of the `returnOriginal` property, this will either be the * document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be * returned */ suspend fun findOneAndReplace( clientSession: ClientSession, filter: String, replacement: T, options: FindOneAndReplaceOptions = FindOneAndReplaceOptions() ): T? = findOneAndReplace( clientSession, toBson(filter), replacement, options ) /** * Atomically find a document and update it. * * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param options the options to apply to the operation * * @return the document that was updated. Depending on the value of the `returnOriginal` property, this will either be the * document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be * returned */ suspend fun findOneAndUpdate( filter: String, update: String, options: FindOneAndUpdateOptions = FindOneAndUpdateOptions() ): T? = findOneAndUpdate(toBson(filter), toBson(update), options) /** * Atomically find a document and update it. * * @param clientSession the client session with which to associate this operation * @param filter a document describing the query filter * @param update a document describing the update. The update to apply must include only update operators. * @param options the options to apply to the operation * * @return the document that was updated. Depending on the value of the `returnOriginal` property, this will either be the * document as it was before the update or as it is after the update. If no documents matched the query filter, then null will be * returned */ suspend fun findOneAndUpdate( clientSession: ClientSession, filter: String, update: String, options: FindOneAndUpdateOptions = FindOneAndUpdateOptions() ): T? = findOneAndUpdate( clientSession, toBson(filter), toBson(update), options ) /** * Creates an index. If successful, the callback will be executed with the name of the created index as the result. * * @param key an object describing the index key(s) * @param options the options for the index * @return the index name */ suspend fun createIndex( key: String, options: IndexOptions = IndexOptions() ): String = createIndex(toBson(key), options) /** * Create an index with the given keys and options. * If the creation of the index is not doable because an index with the same keys but with different [IndexOptions] * already exists, then drop the existing index and create a new one. * * @param keys an object describing the index key(s) * @param indexOptions the options for the index * @return the index name */ suspend fun ensureIndex( keys: String, indexOptions: IndexOptions = IndexOptions() ): String? = try { createIndex(keys, indexOptions) } catch (e: MongoCommandException) { //there is an exception if the parameters of an existing index are changed. //then drop the index and create a new one dropIndex(keys) createIndex(keys, indexOptions) } /** * Create an index with the given keys and options. * If the creation of the index is not doable because an index with the same keys but with different [IndexOptions] * already exists, then drop the existing index and create a new one. * * @param keys an object describing the index key(s) * @param indexOptions the options for the index * @return the index name */ suspend fun ensureIndex( keys: Bson, indexOptions: IndexOptions = IndexOptions() ): String? = try { createIndex(keys, indexOptions) } catch (e: MongoCommandException) { //there is an exception if the parameters of an existing index are changed. //then drop the index and create a new one dropIndex(keys) createIndex(keys, indexOptions) } /** * Create an index with the given keys and options. * If the creation of the index is not doable because an index with the same keys but with different [IndexOptions] * already exists, then drop the existing index and create a new one. * * @param properties the properties, which must contain at least one * @param indexOptions the options for the index * @return the index name */ suspend fun ensureIndex( vararg properties: KProperty<*>, indexOptions: IndexOptions = IndexOptions() ): String? = ensureIndex(ascending(*properties), indexOptions) /** * Create an [IndexOptions.unique] index with the given keys and options. * If the creation of the index is not doable because an index with the same keys but with different [IndexOptions] * already exists, then drop the existing index and create a new one. * * @param properties the properties, which must contain at least one * @param indexOptions the options for the index * @return the index name */ suspend fun ensureUniqueIndex( vararg properties: KProperty<*>, indexOptions: IndexOptions = IndexOptions() ): String? = ensureIndex(ascending(*properties), indexOptions.unique(true)) /** * Executes a mix of inserts, updates, replaces, and deletes. * * @param requests the writes to execute * @param options the options to apply to the bulk write operation * * @return the result of the bulk write */ suspend inline fun bulkWrite( vararg requests: WriteModel<T>, options: BulkWriteOptions = BulkWriteOptions() ): BulkWriteResult = bulkWrite(requests.toList(), options) } //extensions /** * Inserts the provided document. If the document is missing an identifier, the driver should generate one. * * @param document the document to insert * @param options the options to apply to the operation */ suspend inline fun <reified T : Any> CoroutineCollection<T>.insertOne( document: String, options: InsertOneOptions = InsertOneOptions() ): InsertOneResult = withDocumentClass<BsonDocument>().insertOne( toBson(document, T::class), options ) /** * Inserts the provided document. If the document is missing an identifier, the driver should generate one. * @param clientSession the client session with which to associate this operation * @param document the document to insert * @param options the options to apply to the operation */ suspend inline fun <reified T : Any> CoroutineCollection<T>.insertOne( clientSession: ClientSession, document: String, options: InsertOneOptions = InsertOneOptions() ): InsertOneResult = withDocumentClass<BsonDocument>().insertOne( clientSession, toBson(document, T::class), options ) /** * Replace a document in the collection according to the specified arguments. * * @param replacement the document to replace - must have an non null id * @param options the options to apply to the replace operation * * @return the result of the replace one operation */ suspend inline fun <reified T : Any> CoroutineCollection<T>.replaceOne( replacement: T, options: ReplaceOptions = ReplaceOptions() ): UpdateResult = replaceOneById(extractId(replacement, T::class), replacement, options) /** * Update a single document in the collection according to the specified arguments. * * @param target the update object - must have an non null id * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend inline fun <reified T : Any> CoroutineCollection<T>.updateOne( target: T, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult = updateOneById(extractId(target, T::class), target, options, updateOnlyNotNullProperties) /** * Update a single document in the collection according to the specified arguments. * * @param clientSession the client session with which to associate this operation * @param target the update object - must have an non null id * @param options the options to apply to the update operation * @param updateOnlyNotNullProperties if true do not change null properties * * @return the result of the update one operation */ suspend inline fun <reified T : Any> CoroutineCollection<T>.updateOne( clientSession: ClientSession, target: T, options: UpdateOptions = UpdateOptions(), updateOnlyNotNullProperties: Boolean = UpdateConfiguration.updateOnlyNotNullProperties ): UpdateResult { return updateOneById( clientSession, extractId(target, T::class), target, options, updateOnlyNotNullProperties ) } /** * Executes a mix of inserts, updates, replaces, and deletes. * * @param clientSession the client session with which to associate this operation * @param requests the writes to execute * @param options the options to apply to the bulk write operation * * @return the result of the bulk write */ suspend inline fun <reified T : Any> CoroutineCollection<T>.bulkWrite( clientSession: ClientSession, vararg requests: String, options: BulkWriteOptions = BulkWriteOptions() ): BulkWriteResult = withDocumentClass<BsonDocument>().bulkWrite( clientSession, KMongoUtil.toWriteModel( requests, codecRegistry, T::class ), options ) /** * Executes a mix of inserts, updates, replaces, and deletes. * * @param requests the writes to execute * @param options the options to apply to the bulk write operation * * @return the result of the bulk write */ suspend inline fun <reified T : Any> CoroutineCollection<T>.bulkWrite( vararg requests: String, options: BulkWriteOptions = BulkWriteOptions() ): BulkWriteResult = withDocumentClass<BsonDocument>().bulkWrite( KMongoUtil.toWriteModel( requests, codecRegistry, T::class ), options ) /** * Aggregates documents according to the specified aggregation pipeline. If the pipeline ends with a $out stage, the returned * iterable will be a query of the collection that the aggregation was written to. Note that in this case the pipeline will be * executed even if the iterable is never iterated. * * @param pipeline the aggregate pipeline * @param <T> the target document type of the iterable */ inline fun <reified T : Any> CoroutineCollection<*>.aggregate(vararg pipeline: String): CoroutineAggregatePublisher<T> = aggregate(KMongoUtil.toBsonList(pipeline, codecRegistry)) /** * Aggregates documents according to the specified aggregation pipeline. If the pipeline ends with a $out stage, the returned * iterable will be a query of the collection that the aggregation was written to. Note that in this case the pipeline will be * executed even if the iterable is never iterated. * * @param pipeline the aggregate pipeline * @param <T> the target document type of the iterable */ inline fun <reified T : Any> CoroutineCollection<*>.aggregate(vararg pipeline: Bson): CoroutineAggregatePublisher<T> = aggregate(pipeline.toList()) /** * Returns the specified field for all matching documents. * * @param property the property to return * @param query the optional find query * @param options the optional [CoroutineFindPublisher] modifiers * @return a property value CoroutineFindPublisher */ inline fun <reified F : Any> CoroutineCollection<*>.projection( property: KProperty<F?>, query: Bson = EMPTY_BSON, options: (CoroutineFindPublisher<SingleProjection<F>>) -> CoroutineFindPublisher<SingleProjection<F>> = { it } ): CoroutineFindPublisher<F> = CoroutineFindPublisher( withDocumentClass<SingleProjection<F>>() .withCodecRegistry(singleProjectionCodecRegistry(property.path(), F::class, codecRegistry)) .find(query) .let { options(it) } .projection(fields(excludeId(), include(property))) .publisher .map { it?.field } ) /** * Returns the specified two fields for all matching documents. * * @param property1 the first property to return * @param property2 the second property to return * @param query the optional find query * @param options the optional [CoroutineFindPublisher] modifiers * @return a pair of property values CoroutineFindPublisher */ inline fun <reified F1 : Any, reified F2 : Any> CoroutineCollection<*>.projection( property1: KProperty<F1?>, property2: KProperty<F2?>, query: Bson = EMPTY_BSON, options: (CoroutineFindPublisher<PairProjection<F1, F2>>) -> CoroutineFindPublisher<PairProjection<F1, F2>> = { it } ): CoroutineFindPublisher<Pair<F1?, F2?>> = CoroutineFindPublisher( withDocumentClass<PairProjection<F1, F2>>() .withCodecRegistry( pairProjectionCodecRegistry( property1.path(), F1::class, property2.path(), F2::class, codecRegistry ) ) .find(query) .let { options(it) } .projection(fields(excludeId(), include(property1), include(property2))) .publisher .map { it?.field1 to it?.field2 } ) /** * Returns the specified three fields for all matching documents. * * @param property1 the first property to return * @param property2 the second property to return * @param property3 the third property to return * @param query the optional find query * @param options the optional [CoroutineFindPublisher] modifiers * @return a triple of property values CoroutineFindPublisher */ inline fun <reified F1 : Any, reified F2 : Any, reified F3 : Any> CoroutineCollection<*>.projection( property1: KProperty<F1?>, property2: KProperty<F2?>, property3: KProperty<F3?>, query: Bson = EMPTY_BSON, options: (CoroutineFindPublisher<TripleProjection<F1, F2, F3>>) -> CoroutineFindPublisher<TripleProjection<F1, F2, F3>> = { it } ): CoroutineFindPublisher<Triple<F1?, F2?, F3?>> = CoroutineFindPublisher( withDocumentClass<TripleProjection<F1, F2, F3>>() .withCodecRegistry( tripleProjectionCodecRegistry( property1.path(), F1::class, property2.path(), F2::class, property3.path(), F3::class, codecRegistry ) ) .find(query) .let { options(it) } .projection(fields(excludeId(), include(property1), include(property2), include(property3))) .publisher .map { Triple(it?.field1, it?.field2, it?.field3) } )
kmongo-coroutine-core/src/main/kotlin/org/litote/kmongo/coroutine/CoroutineCollection.kt
1874428702
package com.squareup.sqldelight.intellij.lang import com.squareup.sqldelight.core.lang.SqlDelightFileType import com.squareup.sqldelight.intellij.SqlDelightFixtureTestCase import org.jetbrains.kotlin.idea.util.application.executeWriteCommand class SqlDelightImportOptimizerTest : SqlDelightFixtureTestCase() { fun testImportOptimizer() { myFixture.configureByText( SqlDelightFileType, """ |import java.lang.Integer; |import kotlin.collections.List; |import org.jetbrains.annotations.Nullable; | |CREATE TABLE hockeyPlayer ( | id INTEGER NOT NULL PRIMARY KEY, | first_name TEXT NOT NULL, | last_name TEXT AS @Nullable String NOT NULL, | list TEXT AS List<Int> |); """.trimMargin() ) project.executeWriteCommand("") { SqlDelightImportOptimizer().processFile(myFixture.file).run() } myFixture.checkResult( """ |import kotlin.collections.List; |import org.jetbrains.annotations.Nullable; | |CREATE TABLE hockeyPlayer ( | id INTEGER NOT NULL PRIMARY KEY, | first_name TEXT NOT NULL, | last_name TEXT AS @Nullable String NOT NULL, | list TEXT AS List<Int> |); """.trimMargin() ) } }
sqldelight-idea-plugin/src/test/kotlin/com/squareup/sqldelight/intellij/lang/SqlDelightImportOptimizerTest.kt
1898442616
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"). * See LICENSE in the project root for license information. */ package jetbrains.buildServer.rust import com.github.zafarkhaja.semver.Version import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.openapi.diagnostic.Logger import jetbrains.buildServer.SimpleCommandLineProcessRunner import jetbrains.buildServer.agent.* import jetbrains.buildServer.util.EventDispatcher import jetbrains.buildServer.util.StringUtil import java.io.File /** * Determines tool location. */ abstract class AbstractToolProvider( toolsRegistry: ToolProvidersRegistry, events: EventDispatcher<AgentLifeCycleListener>, private val configName: String, private val configPath: String, private val configExecutableName: String ): AgentLifeCycleAdapter(), ToolProvider { private val LOG = Logger.getInstance(AbstractToolProvider::class.java.name) private val VERSION_PATTERN = Regex("^$configName[\\s-]([^\\s]+)", RegexOption.IGNORE_CASE) private val PATH_PATTERN = Regex("^.*$configName(\\.(exe))?$", RegexOption.IGNORE_CASE) init { toolsRegistry.registerToolProvider(this) events.addListener(this) } override fun beforeAgentConfigurationLoaded(agent: BuildAgent) { LOG.info("Locating $configName tool") findToolPath()?.let { LOG.info("Found $configName at ${it.first}") agent.configuration.apply { addConfigurationParameter(configPath, it.first) addConfigurationParameter(configName, it.second.toString()) } } } override fun supports(toolName: String): Boolean { return configName.equals(toolName, true) } override fun getPath(toolName: String): String { if (!supports(toolName)) throw ToolCannotBeFoundException("Unsupported tool $toolName") findToolPath()?.let { return it.first } throw ToolCannotBeFoundException(""" Unable to locate tool $toolName in system. Please make sure to add it in the PATH variable """.trimIndent()) } override fun getPath(toolName: String, build: AgentRunningBuild, runner: BuildRunnerContext): String { if (runner.isVirtualContext) { return configExecutableName } return build.agentConfiguration.configurationParameters[configPath] ?: getPath(toolName) } /** * Returns a first matching file in the list of directories. * * @return first matching file. */ private fun findToolPath(): Pair<String, Version>? { val paths = LinkedHashSet<String>().apply { System.getenv(CargoConstants.ENV_CARGO_HOME)?.let { this.add(it + File.separatorChar + "bin") } this.addAll(StringUtil.splitHonorQuotes(System.getenv("PATH"), File.pathSeparatorChar)) add(System.getProperty("user.home") + File.separatorChar + ".cargo" + File.separatorChar + "bin") } return paths.mapNotNull { File(it).listFiles() } .flatMap { it.map { it.absolutePath } } .filter { PATH_PATTERN.matches(it) } .mapNotNull { try { val commandLine = getVersionCommandLine(it) val result = SimpleCommandLineProcessRunner.runCommand(commandLine, byteArrayOf()) val version = VERSION_PATTERN.find(result.stdout)?.destructured?.component1() ?: result.stdout it to Version.valueOf(version) } catch (e: Throwable) { LOG.warnAndDebugDetails("Failed to parse $configName version: ${e.message}", e) null } }.maxBy { it.second } } private fun getVersionCommandLine(toolPath: String): GeneralCommandLine { val commandLine = GeneralCommandLine() commandLine.exePath = toolPath commandLine.addParameter("--version") return commandLine } }
plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/AbstractToolProvider.kt
1964832591
package org.evomaster.core.search.service import com.google.inject.Inject import org.evomaster.core.EMConfig import java.nio.charset.Charset import javax.annotation.PostConstruct import java.io.PrintStream class SearchStatusUpdater : SearchListener{ @Inject private lateinit var time: SearchTimeController @Inject private lateinit var config: EMConfig @Inject private lateinit var archive: Archive<*> private var passed = "-1" private var lastUpdateMS = 0L private var lastCoverageComputation = 0 private var coverage = 0 private var extra = "" private val utf8 = Charset.forName("UTF-8") private val p = String(byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x92.toByte(), 0xA9.toByte()), utf8) private val u = String(byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0xA6.toByte(), 0x84.toByte()), utf8) private val r = String(byteArrayOf(0xF0.toByte(), 0x9F.toByte(), 0x8C.toByte(), 0x88.toByte()), utf8) private var first = true /* Make sure that, when we print, we are using UTF-8 and not the default encoding */ private val out = PrintStream(System.out, true, "UTF-8") @PostConstruct fun postConstruct(){ if(config.showProgress) { time.addListener(this) } } override fun newActionEvaluated() { val percentageInt = (time.percentageUsedBudget() * 100).toInt() val current = String.format("%.3f", time.percentageUsedBudget() * 100) if(first){ println() if(config.e_u1f984){ println() } first = false } val delta = System.currentTimeMillis() - lastUpdateMS //writing on console is I/O, which is expensive. So, can't do it too often if(current != passed && delta > 500){ lastUpdateMS += delta passed = current if(percentageInt - lastCoverageComputation > 0){ lastCoverageComputation = percentageInt //this is not too expensive, but still computation. so we do it only at each 1% coverage = archive.numberOfCoveredTargets() } if(config.e_u1f984){ upLineAndErase() } val avgTimeAndSize = time.computeExecutedIndividualTimeStatistics() val avgTime = String.format("%.1f", avgTimeAndSize.first) val avgSize = String.format("%.1f",avgTimeAndSize.second) upLineAndErase() println("* Consumed search budget: $passed%;" + " covered targets: $coverage;" + " time per test: ${avgTime}ms ($avgSize actions)") if(config.e_u1f984){ updateExtra() out.println(extra) } } } private fun updateExtra(){ if(extra.isBlank() || extra.length > 22){ //going more than a line makes thing very complicated... :( extra = u } else { extra = p + r + extra } } /* Using: ANSI/VT100 Terminal Control Escape Sequences http://www.termsys.demon.co.uk/vtansi.htm Note: unfortunately, many terminals do not support saving/restoring the cursor :( ie, following does not work for example in GitBash: print("\u001b[u") print("\u001b[s") */ private fun eraseLine(){ print("\u001b[2K") // erase line } private fun moveUp(){ print("\u001b[1A") // move up by 1 line } private fun upLineAndErase(){ moveUp() eraseLine() } }
core/src/main/kotlin/org/evomaster/core/search/service/SearchStatusUpdater.kt
3197258702
package org.evomaster.core.output import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* internal class LinesTest { @Test fun isCurrentACommentLine() { val lines = Lines() lines.add("foo") assertFalse(lines.isCurrentACommentLine()) lines.add("bar // bar") assertFalse(lines.isCurrentACommentLine()) lines.add(" // Hello There!!! ... ") assertTrue(lines.isCurrentACommentLine()) } }
core/src/test/kotlin/org/evomaster/core/output/LinesTest.kt
3578690644
package com.foo.rest.examples.spring.openapi.v3.expectations open class GenericObject open class ExampleObject( var ident: Int? = null, var name : String? = "Unnamed", var description : String? = "Indescribable" ) : GenericObject() { fun setId(id: Int? = null){ ident = id } fun getId() : Int{ return when (ident) { null -> 0 else -> ident!! } } } open class OtherExampleObject( var id : Int? = null, var namn : String? = "Unnamed", var category : String = "None" ): GenericObject()
e2e-tests/spring-rest-openapi-v3/src/main/kotlin/com/foo/rest/examples/spring/openapi/v3/expectations/ExpectationObjects.kt
1231156925
package org.evomaster.core.search.gene.optional import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.OutputFormat import org.evomaster.core.search.gene.Gene import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.service.AdaptiveParameterControl import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.MutationWeightControl import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy import org.slf4j.Logger import org.slf4j.LoggerFactory /** * A gene that holds many potenial genes (genotype) but * only one is active at any time (phenotype). The list * of gene choices cannot be empty. */ class ChoiceGene<T>( name: String, private val geneChoices: List<T>, activeChoice: Int = 0 ) : CompositeFixedGene(name, geneChoices) where T : Gene { companion object { private val log: Logger = LoggerFactory.getLogger(ChoiceGene::class.java) } var activeGeneIndex: Int = activeChoice private set init { if (geneChoices.isEmpty()) { throw IllegalArgumentException("The list of gene choices cannot be empty") } if (activeChoice < 0 || activeChoice >= geneChoices.size) { throw IllegalArgumentException("Active choice must be between 0 and ${geneChoices.size - 1}") } } override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { activeGeneIndex = randomness.nextInt(geneChoices.size) /* Even the non-selected genes need to be randomized, otherwise could be let in a inconsistent state */ if(!initialized){ geneChoices .filter { it.isMutable() } .forEach { it.randomize(randomness, tryToForceNewValue) } } else { val g = geneChoices[activeGeneIndex] if(g.isMutable()){ g.randomize(randomness, tryToForceNewValue) } } } /** * TODO This method must be implemented to reflect usage * of the selectionStrategy and the additionalGeneMutationInfo */ override fun mutablePhenotypeChildren(): List<Gene> { return listOf(geneChoices[activeGeneIndex]) } override fun <T> getWrappedGene(klass: Class<T>) : T? where T : Gene{ if(this.javaClass == klass){ return this as T } return geneChoices[activeGeneIndex].getWrappedGene(klass) } override fun shallowMutate(randomness: Randomness, apc: AdaptiveParameterControl, mwc: MutationWeightControl, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo?): Boolean { // TODO // select another disjunction based on impact // if (enableAdaptiveGeneMutation || selectionStrategy == SubsetGeneSelectionStrategy.ADAPTIVE_WEIGHT){ // additionalGeneMutationInfo?:throw IllegalStateException("") // if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is DisjunctionListRxGeneImpact){ // val candidates = disjunctions.filterIndexed { index, _ -> index != activeDisjunction } // val impacts = candidates.map { // additionalGeneMutationInfo.impact.disjunctions[disjunctions.indexOf(it)] // } // // val selected = mwc.selectSubGene( // candidateGenesToMutate = candidates, // impacts = impacts, // targets = additionalGeneMutationInfo.targets, // forceNotEmpty = true, // adaptiveWeight = true // ) // activeDisjunction = disjunctions.indexOf(randomness.choose(selected)) // return true // } // //throw IllegalArgumentException("mismatched gene impact") // } //activate the next disjunction activeGeneIndex = (activeGeneIndex + 1) % geneChoices.size return true } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { return randomness.nextBoolean(0.1) //TODO check for proper value } /** * Returns the value of the active gene as a printable string */ override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return geneChoices[activeGeneIndex] .getValueAsPrintableString(previousGenes, mode, targetFormat, extraCheck) } /** * Returns the value of the active gene as a raw string */ override fun getValueAsRawString(): String { return geneChoices[activeGeneIndex] .getValueAsRawString() } /** * Copies the value of the other gene. The other gene * has to be a [ChoiceGene] with the same number * of gene choices. The value of each gene choice * is also copied. */ override fun copyValueFrom(other: Gene) { if (other !is ChoiceGene<*>) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } else if (geneChoices.size != other.geneChoices.size) { throw IllegalArgumentException("Cannot copy value from another choice gene with ${other.geneChoices.size} choices (current gene has ${geneChoices.size} choices)") } else { this.activeGeneIndex = other.activeGeneIndex for (i in geneChoices.indices) { this.geneChoices[i].copyValueFrom(other.geneChoices[i]) } } } /** * Checks that the other gene is another ChoiceGene, * the active gene index is the same, and the gene choices are the same. */ override fun containsSameValueAs(other: Gene): Boolean { if (other !is ChoiceGene<*>) { throw IllegalArgumentException("Invalid gene type ${other.javaClass}") } if (this.activeGeneIndex != other.activeGeneIndex) { return false } return this.geneChoices[activeGeneIndex] .containsSameValueAs(other.geneChoices[activeGeneIndex]) } /** * Binds this gene to another [ChoiceGene<T>] with the same number of * gene choices, one gene choice to the corresponding gene choice in * the other gene. */ override fun bindValueBasedOn(gene: Gene): Boolean { if (gene is ChoiceGene<*> && gene.geneChoices.size == geneChoices.size) { var result = true geneChoices.indices.forEach { i -> val r = geneChoices[i].bindValueBasedOn(gene.geneChoices[i]) if (!r) LoggingUtil.uniqueWarn(log, "cannot bind disjunctions (name: ${geneChoices[i].name}) at index $i") result = result && r } activeGeneIndex = gene.activeGeneIndex return result } LoggingUtil.uniqueWarn(log, "cannot bind ChoiceGene with ${gene::class.java.simpleName}") return false } /** * Returns a copy of this gene choice by copying * all gene choices. */ override fun copyContent(): Gene = ChoiceGene( name, activeChoice = this.activeGeneIndex, geneChoices = this.geneChoices.map { it.copy() }.toList() ) /** * Checks that the active gene is the one locally valid */ override fun isLocallyValid() = geneChoices.all { it.isLocallyValid() } override fun isPrintable() = this.geneChoices[activeGeneIndex].isPrintable() }
core/src/main/kotlin/org/evomaster/core/search/gene/optional/ChoiceGene.kt
3755076731
/* * Copyright (C) 2004-2018 Savoir-faire Linux Inc. * * Author: Hadrien De Sousa <[email protected]> * Author: Adrien Béraud <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package cx.ring.tv.contact import cx.ring.utils.ConversationPath import ezvcard.VCard import io.reactivex.rxjava3.core.Scheduler import net.jami.daemon.Blob import net.jami.services.ConversationFacade import net.jami.model.Call import net.jami.model.Uri import net.jami.mvp.RootPresenter import net.jami.services.AccountService import net.jami.services.VCardService import net.jami.smartlist.ConversationItemViewModel import net.jami.utils.VCardUtils.vcardToString import javax.inject.Inject import javax.inject.Named class TVContactPresenter @Inject constructor( private val mAccountService: AccountService, private val mConversationService: ConversationFacade, @param:Named("UiScheduler") private val mUiScheduler: Scheduler, private val mVCardService: VCardService ) : RootPresenter<TVContactView>() { private var mAccountId: String? = null private var mUri: Uri? = null fun setContact(path: ConversationPath) { mAccountId = path.accountId mUri = path.conversationUri mCompositeDisposable.clear() mCompositeDisposable.add(mConversationService.observeConversation(path.accountId, path.conversationUri, true) .observeOn(mUiScheduler) .subscribe { c: ConversationItemViewModel -> view?.showContact(c) }) } fun contactClicked() { mAccountService.getAccount(mAccountId)?.let { account -> val conversation = account.getByUri(mUri)!! val conf = conversation.currentCall val call = conf?.firstCall if (call != null && call.callStatus !== Call.CallStatus.INACTIVE && call.callStatus !== Call.CallStatus.FAILURE) { view?.goToCallActivity(conf.id) } else { if (conversation.isSwarm) { view?.callContact(account.accountId, conversation.uri, conversation.contact!!.uri) } else { view?.callContact(account.accountId, conversation.uri, conversation.uri) } } } } fun onAddContact() { mAccountId?.let { accountId -> mUri?.let { uri -> sendTrustRequest(accountId, uri) } } view?.switchToConversationView() } private fun sendTrustRequest(accountId: String, conversationUri: Uri) { val conversation = mAccountService.getAccount(accountId)!!.getByUri(conversationUri) mVCardService.loadSmallVCardWithDefault(accountId, VCardService.MAX_SIZE_REQUEST) .subscribe({ vCard: VCard -> mAccountService.sendTrustRequest(conversation!!, conversationUri, Blob.fromString(vcardToString(vCard))) }) { mAccountService.sendTrustRequest(conversation!!, conversationUri, null) } } fun acceptTrustRequest() { mConversationService.acceptRequest(mAccountId!!, mUri!!) view?.switchToConversationView() } fun refuseTrustRequest() { mConversationService.discardRequest(mAccountId!!, mUri!!) view?.finishView() } fun blockTrustRequest() { mConversationService.discardRequest(mAccountId!!, mUri!!) mAccountService.removeContact(mAccountId!!, mUri!!.rawRingId, true) view?.finishView() } }
ring-android/app/src/main/java/cx/ring/tv/contact/TVContactPresenter.kt
1358686449
package com.buildServer.rest.agent import com.buildServer.rest.common.RestCallType import com.buildServer.rest.common.RestCallType.* import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_ALLOWED_HTTP_CODES import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_ALLOWED_HTTP_HEADERS import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_CALL_TYPE import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_ENDPOINT import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_GROOVY_SCRIPT import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_REQUEST_PARAMS import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_REQUEST_PASSWORD import com.buildServer.rest.common.RestRunnerConstants.REST_RUNNER_REQUEST_USERNAME import jetbrains.buildServer.agent.AgentRunningBuild import jetbrains.buildServer.agent.BuildFinishedStatus import jetbrains.buildServer.agent.BuildRunnerContext import jetbrains.buildServer.agent.NullBuildProgressLogger import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.mockito.BDDMockito.given import org.springframework.beans.factory.annotation.Value import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.junit4.SpringRunner /** * @author Dmitry Zhuravlev * Date: 19.10.2016 */ @RunWith(SpringRunner::class) @RestAgentTest class RestCallBuildProcessTest { @Value("\${server.port}") lateinit var port: Integer @MockBean lateinit private var buildRunnerContext: BuildRunnerContext @MockBean lateinit private var testAgentRunningBuild: AgentRunningBuild private fun setupBuildRunnerContext(resource: String, callType: RestCallType, userName: String? = null, password: String? = null, expectedHttpCodes: String = "", expectedHttpHeaders: String = "", params: Set<Pair<String, String>> = emptySet(), responseProcessorGroovyScript: String = "") { given(buildRunnerContext.runnerParameters).willReturn( mapOf( REST_RUNNER_ENDPOINT to "http://localhost:$port/$resource", REST_RUNNER_CALL_TYPE to callType.name, REST_RUNNER_REQUEST_USERNAME to userName, REST_RUNNER_REQUEST_PASSWORD to password, REST_RUNNER_ALLOWED_HTTP_CODES to expectedHttpCodes, REST_RUNNER_ALLOWED_HTTP_HEADERS to expectedHttpHeaders, REST_RUNNER_REQUEST_PARAMS to params.map { pair -> "${pair.first}=${pair.second}" }.joinToString(), REST_RUNNER_GROOVY_SCRIPT to responseProcessorGroovyScript )) given(testAgentRunningBuild.buildLogger).willReturn(NullBuildProgressLogger()) given(buildRunnerContext.build).willReturn(testAgentRunningBuild) } @Test fun testGet404() { setupBuildRunnerContext( resource = "404", callType = GET, expectedHttpCodes = "400, 404", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testPost404() { setupBuildRunnerContext( resource = "404", callType = POST, expectedHttpCodes = "400, 404", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testPut404() { setupBuildRunnerContext( resource = "404", callType = PUT, expectedHttpCodes = "400, 404", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testDelete404() { setupBuildRunnerContext( resource = "404", callType = DELETE, expectedHttpCodes = "400, 404", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testFailGet404() { setupBuildRunnerContext( resource = "404", callType = GET, expectedHttpCodes = "400, 201", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_FAILED, buildProcessStatus) } @Test fun testFailPost404() { setupBuildRunnerContext( resource = "404", callType = POST, expectedHttpCodes = "400, 201", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_FAILED, buildProcessStatus) } @Test fun testFailPut404() { setupBuildRunnerContext( resource = "404", callType = PUT, expectedHttpCodes = "400, 201", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_FAILED, buildProcessStatus) } @Test fun testFailDelete404() { setupBuildRunnerContext( resource = "404", callType = DELETE, expectedHttpCodes = "400, 201", expectedHttpHeaders = """Content-Length=306, Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_FAILED, buildProcessStatus) } @Test fun testGet200WithoutExpected() { setupBuildRunnerContext( resource = "200", callType = GET ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testGet200() { setupBuildRunnerContext( resource = "200", callType = GET, expectedHttpCodes = "201, 200", expectedHttpHeaders = """Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testFailGet200() { setupBuildRunnerContext( resource = "200", callType = GET, expectedHttpCodes = "201, 200", expectedHttpHeaders = """Content-Type=text/html;charset=UTF-9""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_FAILED, buildProcessStatus) } @Test fun testCallGETWithParam() { setupBuildRunnerContext( resource = "GETWithParam", params = setOf( "param" to "value" ), callType = GET, expectedHttpCodes = "200", expectedHttpHeaders = """Content-Length=5""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testCallPOSTWithParam() { setupBuildRunnerContext( resource = "POSTWithParam", params = setOf( "param" to "value" ), callType = POST, expectedHttpCodes = "200", expectedHttpHeaders = """Content-Length=5""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testCallGetUser() { val groovyScriptBody = """ def parser = new groovy.json.JsonSlurper() def user = parser.parseText("${'$'}response") user.name == 'Dmitry' && headers['Content-Type'][0] == 'application/json;charset=UTF-8' """ setupBuildRunnerContext( resource = "user", callType = GET, expectedHttpCodes = "200", responseProcessorGroovyScript = groovyScriptBody, expectedHttpHeaders = """Content-Type=application/json;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testFailCallGetUser() { val groovyScriptBody = """ def parser = new groovy.json.JsonSlurper() def user = parser.parseText("${'$'}response") user.name == 'John' """ setupBuildRunnerContext( resource = "user", callType = GET, expectedHttpCodes = "200", responseProcessorGroovyScript = groovyScriptBody, expectedHttpHeaders = """Content-Type=application/json;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_FAILED, buildProcessStatus) } @Test fun testGetSecuredEndpoint() { setupBuildRunnerContext( resource = "secured", callType = GET, userName = "user", password = "e90468c9-b001-42e2-94e1-a1416ecb95ca", expectedHttpCodes = "200", expectedHttpHeaders = """Content-Type=application/json;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } @Test fun testGetSecuredWithoutAuthEndpoint() { setupBuildRunnerContext( resource = "secured", callType = GET, expectedHttpCodes = "401", expectedHttpHeaders = """Content-Type=text/html;charset=UTF-8""" ) val build = RestCallBuildProcess(buildRunnerContext).apply { start() } val buildProcessStatus = build.waitFor() assertEquals(BuildFinishedStatus.FINISHED_SUCCESS, buildProcessStatus) } }
rest-runner-agent/src/test/kotlin/com/buildServer/rest/agent/RestCallBuildProcessTest.kt
366567227
package org.xwiki.android.sync.activities import android.accounts.Account import android.accounts.AccountManager import android.app.Activity import android.content.ComponentName import android.content.ContentResolver import android.content.Context import android.content.Intent import android.net.ConnectivityManager import android.net.Uri import android.os.Bundle import android.provider.ContactsContract import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.AdapterView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.work.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.xwiki.android.sync.* import org.xwiki.android.sync.R import org.xwiki.android.sync.ViewModel.SyncSettingsViewModel import org.xwiki.android.sync.ViewModel.SyncSettingsViewModelFactory import org.xwiki.android.sync.activities.Notifications.NotificationsActivity import org.xwiki.android.sync.bean.ObjectSummary import org.xwiki.android.sync.bean.SearchResults.CustomObjectsSummariesContainer import org.xwiki.android.sync.bean.XWikiGroup import org.xwiki.android.sync.contactdb.UserAccount import org.xwiki.android.sync.contactdb.clearOldAccountContacts import org.xwiki.android.sync.databinding.ActivitySyncSettingsBinding import org.xwiki.android.sync.notifications.NotificationWorker import org.xwiki.android.sync.rest.BaseApiManager import org.xwiki.android.sync.utils.GroupsListChangeListener import org.xwiki.android.sync.utils.getAppVersionName import rx.android.schedulers.AndroidSchedulers import rx.functions.Action1 import rx.schedulers.Schedulers import java.util.* import java.util.concurrent.TimeUnit /** * Tag which will be used for logging. */ private val TAG = SyncSettingsActivity::class.java.simpleName /** * Open market with application page. * * @param context Context to know where from to open market */ private fun openAppMarket(context: Context) { val rateIntent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.packageName)) var marketFound = false // find all applications able to handle our rateIntent val otherApps = context.packageManager.queryIntentActivities(rateIntent, 0) for (otherApp in otherApps) { // look for Google Play application if (otherApp.activityInfo.applicationInfo.packageName == "com.android.vending") { val otherAppActivity = otherApp.activityInfo val componentName = ComponentName( otherAppActivity.applicationInfo.packageName, otherAppActivity.name ) rateIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED rateIntent.component = componentName context.startActivity(rateIntent) marketFound = true break } } // if GooglePlay not present on device, open web browser if (!marketFound) { val webIntent = Intent( Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + context.packageName) ) context.startActivity(webIntent) } } class SyncSettingsActivity : AppCompatActivity(), GroupsListChangeListener { /** * DataBinding for accessing layout variables. */ lateinit var binding : ActivitySyncSettingsBinding /** * Adapter for groups */ private lateinit var mGroupAdapter: GroupListAdapter /** * Adapter for users. */ private lateinit var mUsersAdapter: UserListAdapter /** * List of received groups. */ private val groups: MutableList<XWikiGroup> = mutableListOf() /** * List of received all users. */ private val allUsers: MutableList<ObjectSummary> = mutableListOf() /** * Currently chosen sync type. */ private var chosenSyncType: Int? = SYNC_TYPE_NO_NEED_SYNC /** * Flag of currently loading groups. */ @Volatile private var groupsAreLoading: Boolean = false /** * Flag of currently loading all users. */ @Volatile private var allUsersAreLoading: Boolean = false private lateinit var currentUserAccountName : String private lateinit var currentUserAccountType : String private lateinit var userAccount : UserAccount private lateinit var syncSettingsViewModel: SyncSettingsViewModel private lateinit var apiManager: BaseApiManager private var selectedStrings = ArrayList<String>() private lateinit var context: LifecycleOwner private lateinit var layoutManager: LinearLayoutManager private var isLoading = false private var initialUsersListLoading = true private var currentPage = 0 private var lastVisiblePosition = 0 private lateinit var toolbar: androidx.appcompat.widget.Toolbar private lateinit var dataSavingCheckbox: MenuItem /** * Init all views and other activity objects * * @param savedInstanceState * * @since 1.0 */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) context = this binding = DataBindingUtil.setContentView(this, R.layout.activity_sync_settings) binding.versionCheck.text = String.format( getString(R.string.versionTemplate), getAppVersionName(this) ) val extras = intent.extras currentUserAccountName = if (extras ?.get("account") != null) { val intentAccount : Account = extras.get("account") as Account intentAccount.name } else { intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME) ?: error("Can't get account name from intent - it is absent") } toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) mGroupAdapter = GroupListAdapter(groups, this) mUsersAdapter = UserListAdapter(allUsers, this) layoutManager = binding.recyclerView.layoutManager as LinearLayoutManager binding.recyclerView.adapter = mUsersAdapter binding.recyclerView.addOnScrollListener(recyclerViewOnScrollListener) binding.selectSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { binding.syncTypeGetErrorContainer.visibility = View.GONE when(position) { 0 -> { if (allUsers.isEmpty() && allUsersAreLoading) { binding.syncTypeGetErrorContainer.visibility = View.VISIBLE } } 1 -> { if (groups.isEmpty()) { binding.syncTypeGetErrorContainer.visibility = View.VISIBLE } } 2 -> { binding.syncTypeGetErrorContainer.visibility = View.GONE } } if (userAccount.syncType == position) { binding.nextButton.alpha = 0.8F } else { binding.nextButton.alpha = 1F } chosenSyncType = position initialUsersListLoading = true currentPage = 0 updateListView(false) } override fun onNothingSelected(parent: AdapterView<*>) {} } binding.rvChangeSelectedAccount.setOnClickListener { val intent : Intent = Intent(this, SelectAccountActivity::class.java) startActivityForResult(intent, 1000) } binding.btTryAgain.setOnClickListener { appCoroutineScope.launch { when(chosenSyncType) { SYNC_TYPE_ALL_USERS -> {loadAllUsers()} SYNC_TYPE_SELECTED_GROUPS -> {loadSyncGroups()} } } } binding.versionCheck.setOnClickListener { v -> openAppMarket(v.context) } binding.nextButton.setOnClickListener { syncSettingComplete(it) } initData() callNotificationWorker() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.sync_setting_view_menu, menu) dataSavingCheckbox = menu!!.findItem(R.id.action_data_saving) if (appContext.dataSaverModeEnabled) { dataSavingCheckbox.setChecked(true) } else { dataSavingCheckbox.setChecked(false) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_data_saving -> { if (item.isChecked) { item.setChecked(false) appContext.dataSaverModeEnabled = false } else { item.setChecked(true) appContext.dataSaverModeEnabled = true } true } R.id.action_notifications -> { if (this.hasNetworkConnection()) { val intent = Intent(this, NotificationsActivity::class.java) intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, currentUserAccountName) startActivity(intent) } else Toast.makeText(applicationContext, R.string.error_no_internet, Toast.LENGTH_SHORT).show() true } else -> super.onOptionsItemSelected(item) } } private val recyclerViewOnScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) { super.onScrollStateChanged(recyclerView, newState) if (newState == RecyclerView.SCROLL_STATE_IDLE) { val totalItemCount = layoutManager.itemCount if (!isLoading && layoutManager.findLastCompletelyVisibleItemPosition() >= totalItemCount/2) { lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition() loadMoreUsers() } } } } // TODO:: Test case for pagination of loading MoreUsers private fun loadMoreUsers () { isLoading = true showLoadMoreProgressBar() apiManager.xwikiServicesApi.getAllUsersListByOffset(currentPage, PAGE_SIZE) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( Action1 { if (it.objectSummaries.isNotEmpty()) { currentPage += PAGE_SIZE allUsers.addAll(it.objectSummaries) updateListView(true) syncSettingsViewModel.updateAllUsersCache( allUsers, userAccount.id ) } initialUsersListLoading = false allUsersAreLoading = false isLoading = false hideLoadMoreProgressBar() }, Action1 { allUsersAreLoading = false isLoading = false hideLoadMoreProgressBar() } ) } fun scrollToCurrentPosition() { if (!initialUsersListLoading) { binding.recyclerView.scrollToPosition(lastVisiblePosition - 3) } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, intent) if (requestCode == 1000) { if (resultCode == Activity.RESULT_OK) { if (data != null) { currentUserAccountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME) currentUserAccountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE) binding.tvSelectedSyncAcc.text = currentUserAccountName binding.tvSelectedSyncType.text = currentUserAccountType currentPage = 0 initData() } } } } private fun hideRecyclerView() { runOnUiThread{ enableShimmer() binding.syncTypeGetErrorContainer.visibility = View.GONE binding.recyclerView.visibility = View.GONE } } //this progress bar appears when more data is loaded into recycler view private fun showLoadMoreProgressBar() { runOnUiThread { binding.loadMoreProgressBar.visibility = View.VISIBLE } } private fun hideLoadMoreProgressBar() { runOnUiThread { binding.loadMoreProgressBar.visibility = View.INVISIBLE } } private fun showRecyclerView() { runOnUiThread { disableShimmer() binding.recyclerView.visibility = View.VISIBLE } } /** * Load data to groups and all users lists. * * @since 0.4 */ private fun initData() { if (!intent.getBooleanExtra("Test", false)) { hideRecyclerView() } appCoroutineScope.launch { userAccount = userAccountsRepo.findByAccountName(currentUserAccountName) ?: return@launch chosenSyncType = userAccount.syncType apiManager = resolveApiManager(userAccount) selectedStrings.clear() selectedStrings = userAccount.selectedGroupsList as ArrayList<String> withContext(Dispatchers.Main) { binding.tvSelectedSyncAcc.text = userAccount.accountName binding.tvSelectedSyncType.text = userAccount.serverAddress syncSettingsViewModel = ViewModelProviders.of( this@SyncSettingsActivity, SyncSettingsViewModelFactory (application) ).get(SyncSettingsViewModel::class.java) chosenSyncType = userAccount.syncType } initSyncList() } } // TODO:: Test case for both allUsers and SyncGroups private fun initSyncList () { loadSyncGroups() loadAllUsers() } // Initial loading of all users. private fun loadAllUsers() { allUsersAreLoading = true val users = syncSettingsViewModel.getAllUsersCache(userAccount.id) ?: emptyList() if (users.isEmpty()) { hideRecyclerView() } else { allUsers.clear() allUsers.addAll(users) updateListView(false) } apiManager.xwikiServicesApi.getAllUsersListByOffset( currentPage, PAGE_SIZE) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { summaries -> val objectSummary = summaries.objectSummaries if (objectSummary.isNullOrEmpty()) { runOnUiThread { binding.syncTypeGetErrorContainer.visibility = View.VISIBLE showRecyclerView() } } else { currentPage = PAGE_SIZE runOnUiThread { binding.syncTypeGetErrorContainer.visibility = View.GONE } allUsersAreLoading = false allUsers.clear() allUsers.addAll(summaries.objectSummaries) syncSettingsViewModel.updateAllUsersCache( summaries.objectSummaries, userAccount.id ) updateListView(true) } }, { allUsersAreLoading = false runOnUiThread { Toast.makeText( this@SyncSettingsActivity, R.string.cantGetAllUsers, Toast.LENGTH_SHORT ).show() if (allUsers.size <= 0) { binding.syncTypeGetErrorContainer.visibility = View.VISIBLE } } showRecyclerView() } ) } private fun loadSyncGroups() { val groupsCache = syncSettingsViewModel.getGroupsCache(userAccount.id) ?: emptyList() if (groupsCache.isEmpty()) { hideRecyclerView() } else { groups.clear() groups.addAll(groupsCache) updateListView(false) } groupsAreLoading = true apiManager.xwikiServicesApi.availableGroups( LIMIT_MAX_SYNC_USERS ) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { xWikiGroupCustomSearchResultContainer -> groupsAreLoading = false val searchResults = xWikiGroupCustomSearchResultContainer.searchResults showRecyclerView() if (searchResults.isNullOrEmpty()) { runOnUiThread { if (chosenSyncType == SYNC_TYPE_SELECTED_GROUPS) { binding.syncTypeGetErrorContainer.visibility = View.VISIBLE } } } else { runOnUiThread { binding.syncTypeGetErrorContainer.visibility = View.GONE } groups.clear() groups.addAll(searchResults) syncSettingsViewModel.updateGroupsCache( searchResults, userAccount.id ) updateListView(false) } }, { groupsAreLoading = false runOnUiThread { Toast.makeText( this@SyncSettingsActivity, R.string.cantGetGroups, Toast.LENGTH_SHORT ).show() if (groups.size <= 0) { binding.syncTypeGetErrorContainer.visibility = View.VISIBLE } } showRecyclerView() } ) } // Load all users at once, does not support pagination. private fun updateSyncAllUsers() { val users = syncSettingsViewModel.getAllUsersCache(userAccount.id) ?: emptyList() if (users.isEmpty()) { allUsersAreLoading = true apiManager.xwikiServicesApi.allUsersPreview .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( Action1<CustomObjectsSummariesContainer<ObjectSummary>> { summaries -> runOnUiThread { binding.syncTypeGetErrorContainer.visibility = View.GONE } allUsersAreLoading = false allUsers.clear() allUsers.addAll(summaries.objectSummaries) syncSettingsViewModel.updateAllUsersCache( summaries.objectSummaries, userAccount.id ) updateListView(true) }, Action1<Throwable> { allUsersAreLoading = false runOnUiThread { Toast.makeText( this@SyncSettingsActivity, R.string.cantGetAllUsers, Toast.LENGTH_SHORT ).show() binding.syncTypeGetErrorContainer.visibility = View.VISIBLE } showRecyclerView() } ) } else { allUsers.clear() allUsers.addAll(users) updateListView(false) } } /** * @return true if currently selected to sync groups or false otherwise */ private fun syncGroups(): Boolean { return chosenSyncType == SYNC_TYPE_SELECTED_GROUPS } /** * @return true if currently selected to sync all users or false otherwise */ private fun syncAllUsers(): Boolean { return chosenSyncType == SYNC_TYPE_ALL_USERS } /** * @return true if currently selected to sync not or false otherwise */ private fun syncNothing(): Boolean { return chosenSyncType == SYNC_TYPE_NO_NEED_SYNC } /** * Update list view and hide/show view from [.getListViewContainer] */ private fun updateListView(hideProgressBar: Boolean) { appCoroutineScope.launch(Dispatchers.Main) { if (syncNothing()) { binding.recyclerView.visibility = View.GONE disableShimmer() } else { binding.recyclerView.visibility = View.VISIBLE if (syncGroups()) { binding.recyclerView.adapter = mGroupAdapter mGroupAdapter.refresh(groups, userAccount.selectedGroupsList) } else { binding.recyclerView.adapter = mUsersAdapter mUsersAdapter.refresh(allUsers) } binding.recyclerView.layoutManager?.scrollToPosition(0) mUsersAdapter.refresh(allUsers) if (hideProgressBar) { showRecyclerView() } } } } /** * Save settings of synchronization. */ fun syncSettingComplete(v: View) { val oldSyncType = userAccount.syncType if (oldSyncType == chosenSyncType && !syncGroups()) { binding.nextButton.alpha = 0.8F Toast.makeText(this, "Nothing has changed since your last sync", Toast.LENGTH_SHORT).show() return } val mAccountManager = AccountManager.get(applicationContext) val availableAccounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE) var account: Account = availableAccounts[0] for (acc in availableAccounts) { if (acc.name.equals(currentUserAccountName)) { account = acc } } clearOldAccountContacts( contentResolver, account ) //if has changes, set sync if (syncNothing()) { userAccount.syncType = SYNC_TYPE_NO_NEED_SYNC userAccount.selectedGroupsList = mutableListOf() userAccount.let { syncSettingsViewModel.updateUser(it) } setSync(false) finish() } else if (syncAllUsers()) { userAccount.syncType = SYNC_TYPE_ALL_USERS userAccount.selectedGroupsList = mutableListOf() userAccount.let { syncSettingsViewModel.updateUser(it) } setSync(true) finish() } else if (syncGroups()) { //compare to see if there are some changes. if (oldSyncType == chosenSyncType && compareSelectGroups()) { Toast.makeText(this, "Nothing has changed since your last sync", Toast.LENGTH_SHORT).show() return } userAccount.selectedGroupsList.clear() userAccount.selectedGroupsList.addAll(mGroupAdapter.saveSelectedGroups()) userAccount.syncType = SYNC_TYPE_SELECTED_GROUPS appCoroutineScope.launch { userAccountsRepo.updateAccount(userAccount) setSync(true) finish() } } } /** * Enable/disable synchronization depending on syncEnabled. * * @param syncEnabled Flag to enable (if true) / disable (if false) synchronization */ private fun setSync(syncEnabled: Boolean) { val mAccountManager = AccountManager.get(applicationContext) val availableAccounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE) var account : Account = availableAccounts[0] for (acc in availableAccounts) { if (acc.name.equals(currentUserAccountName)) { account = acc } } if (syncEnabled) { mAccountManager.setUserData(account, SYNC_MARKER_KEY, null) ContentResolver.cancelSync(account, ContactsContract.AUTHORITY) ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1) ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true) ContentResolver.addPeriodicSync( account, ContactsContract.AUTHORITY, Bundle.EMPTY, SYNC_INTERVAL.toLong() ) ContentResolver.requestSync(account, ContactsContract.AUTHORITY, Bundle.EMPTY) } else { ContentResolver.cancelSync(account, ContactsContract.AUTHORITY) ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0) } } /** * @return true if old list equal to new list of groups */ private fun compareSelectGroups(): Boolean { //new val newList = mGroupAdapter.selectGroups //old val oldList = userAccount.selectedGroupsList if (newList.isEmpty() && oldList.isEmpty()) { return false } if (newList.size != oldList.size) { return false } else { for (item in newList) { if (!oldList.contains(item.id)) { return false } } return true } } override fun onChangeListener() { if (compareSelectGroups()) { binding.nextButton.alpha = 0.8F } else { binding.nextButton.alpha = 1F } } fun Context.hasNetworkConnection(): Boolean { val cm = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return cm.activeNetworkInfo?.isConnected ?: false } private fun callNotificationWorker() { val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .setRequiresCharging(false) .build() val workData = Data.Builder().putString("username", currentUserAccountName).build() val request: PeriodicWorkRequest.Builder = PeriodicWorkRequest.Builder(NotificationWorker::class.java, 15, TimeUnit.MINUTES) .setConstraints(constraints) .setInputData(workData) val workRequest: PeriodicWorkRequest = request.build() WorkManager.getInstance(applicationContext) .enqueueUniquePeriodicWork("XwikiNotificationTag", ExistingPeriodicWorkPolicy.KEEP, workRequest) } override fun onResume() { super.onResume() binding.shimmerSyncUsers.startShimmer() } override fun onPause() { binding.shimmerSyncUsers.stopShimmer() super.onPause() } private fun enableShimmer() { binding.shimmerSyncUsers.startShimmer() binding.shimmerSyncUsers.visibility = View.VISIBLE } private fun disableShimmer() { binding.shimmerSyncUsers.stopShimmer() binding.shimmerSyncUsers.visibility = View.GONE } }
app/src/main/java/org/xwiki/android/sync/activities/SyncSettingsActivity.kt
1671471556
package org.klips.dsl enum class ActivationFilter { AssertOnly, RetireOnly, Both }
src/main/java/org/klips/dsl/ActivationFilter.kt
1057916525
package com.github.sybila.checker.operator import com.github.sybila.checker.Channel import com.github.sybila.checker.CheckerStats import com.github.sybila.checker.Operator import com.github.sybila.checker.eval import com.github.sybila.checker.map.mutable.HashStateMap import com.github.sybila.huctl.DirectionFormula class ExistsNextOperator<out Params: Any>( timeFlow: Boolean, direction: DirectionFormula, inner: Operator<Params>, partition: Channel<Params> ) : LazyOperator<Params>(partition, { val storage = (0 until partitionCount).map { newLocalMutableMap(it) } val i = inner.compute() CheckerStats.setOperator("ExistsNext") //distribute data from inner formula for ((state, value) in i.entries()) { for ((predecessor, dir, bound) in state.predecessors(timeFlow)) { if (direction.eval(dir)) { val witness = value and bound if (witness.canSat()) { storage[predecessor.owner()].setOrUnion(predecessor, witness) } } } } //gather data from everyone else val received = mapReduce(storage.prepareTransmission(partitionId)) received?.forEach { storage[partitionId].setOrUnion(it.first, it.second) } storage[partitionId] }) class AllNextOperator<out Params : Any>( timeFlow: Boolean, direction: DirectionFormula, inner: Operator<Params>, partition: Channel<Params> ) : LazyOperator<Params>(partition, { val satisfied = (0 until partitionCount).map { HashStateMap(ff) } val candidates = (0 until partitionCount).map { newLocalMutableMap(it) } val mySatisfied = satisfied[partitionId] val myCandidates = candidates[partitionId] val i = inner.compute() CheckerStats.setOperator("AllNext") //distribute data so that everyone sees their successors that are satisfied in the inner formula //and also mark all such states as candidates (candidate essentially means EX phi holds) for ((state, value) in i.entries()) { for ((predecessor, dir, bound) in state.predecessors(timeFlow)) { if (direction.eval(dir)) { //if direction is false, predecessor will be false for the entire bound val candidate = value and bound if (candidate.canSat()) { satisfied[predecessor.owner()].setOrUnion(state, candidate) candidates[predecessor.owner()].setOrUnion(predecessor, candidate) } } } } mapReduce(satisfied.prepareTransmission(partitionId))?.forEach { mySatisfied.setOrUnion(it.first, it.second) } mapReduce(candidates.prepareTransmission(partitionId))?.forEach { myCandidates.setOrUnion(it.first, it.second) } val result = newLocalMutableMap(partitionId) for ((state, value) in candidates[partitionId].entries()) { var witness = value for ((successor, dir, bound) in state.successors(timeFlow)) { if (!witness.canSat()) break //fail fast if (!direction.eval(dir)) { witness = witness and bound.not() } else { //either the transition is not there (bound.not()) or successor is satisfied witness = witness and (mySatisfied[successor] or bound.not()) } } if (witness.canSat()) result.setOrUnion(state, witness) } result })
src/main/kotlin/com/github/sybila/checker/operator/NextOperator.kt
2037428181
package com.natpryce.hamkrest.should import com.natpryce.hamkrest.anyElement import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.isWithin import com.natpryce.hamkrest.present import com.natpryce.hamkrest.startsWith import org.junit.Test class ShouldExtension { @Test fun can_extend_an_object() { "Banana" shouldMatch startsWith("Ban") 42 shouldMatch isWithin(1..99) } @Test fun matches_with_function() { "Banana" shouldMatch ::isAYellowFruitName 42 shouldMatch ::isTheAnswer } @Test fun matches_subtypes() { listOf(1, 2, 3, 4) shouldMatch anyElement(equalTo(3)) } @Test fun can_name_asserted_value() { try { 42 describedAs "bob" shouldMatch equalTo(63) } catch (e: AssertionError) { assertThat(e.message, present(startsWith("bob: "))) } } @Test fun is_type_safe() { // 42 shouldMatch startsWith("Ban") // Doesn't compile // Integer(42) shouldMatch startsWith("Ban") // Doesn't compile } @Test fun not_extend_an_object() { "Banana" shouldNotMatch startsWith("App") 42 shouldNotMatch isWithin(1..10) } @Test fun not_matches_with_function() { "Apple" shouldNotMatch ::isAYellowFruitName 666 shouldNotMatch ::isTheAnswer } @Test fun not_matches_subtypes() { listOf(1, 2, 4) shouldNotMatch anyElement(equalTo(3)) } } private fun isAYellowFruitName(name: String) = name.toLowerCase() in listOf("banana", "lemon", "hippophae") private fun isTheAnswer(a: Int) = a == 42
src/test/kotlin/com/natpryce/hamkrest/should/should_extension.kt
631014746
package org.profit.main import org.profit.ProfitServer import org.profit.config.spring.AppSpringConfig import org.springframework.context.annotation.AnnotationConfigApplicationContext class CommandLine protected constructor() { private fun addShutdownHook(server: ProfitServer) { val shutdownHook = Runnable { server.stop() } // Add shutdown hook val runtime = Runtime.getRuntime() runtime.addShutdownHook(Thread(shutdownHook)) } @Throws(Exception::class) protected fun getConfiguration(args: Array<String>): ProfitServer? { var server: ProfitServer? = null if (args.size == 0) { println("Using default configuration.") val ctx = AnnotationConfigApplicationContext(AppSpringConfig::class.java) //ctx.registerShutdownHook(); server = ProfitServer() } return server } companion object { @JvmStatic fun main(args: Array<String>) { val cli = CommandLine() try { // Get configuration val server = cli.getConfiguration(args) ?: return // Start the server server.start() cli.addShutdownHook(server) } catch (e: Exception) { e.printStackTrace() } } } }
src/main/java/org/profit/main/CommandLine.kt
922359948
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package jp.nephy.penicillin.core.auth /** * Represents OAuth authorization type. */ enum class AuthorizationType { /** * Corresponding to OAuth 1.0a. */ OAuth1a, /** * Corresponding to OAuth 2. */ OAuth2, /** * Corresponding to OAuth 2 with request token. */ OAuth2RequestToken, /** * No authorization needed. */ None }
src/main/kotlin/jp/nephy/penicillin/core/auth/AuthorizationType.kt
2498989423
package org.toml.ide import com.intellij.lexer.Lexer import com.intellij.openapi.editor.DefaultLanguageHighlighterColors import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.openapi.fileTypes.SyntaxHighlighterBase import com.intellij.psi.tree.IElementType import gnu.trove.THashMap import org.toml.lang.core.lexer.TomlLexer import org.toml.lang.core.psi.TomlTypes class TomlHighlighter : SyntaxHighlighterBase() { override fun getHighlightingLexer(): Lexer = TomlLexer() override fun getTokenHighlights(tokenType: IElementType?): Array<out TextAttributesKey> = pack(tokenType?.let { tokenMap[it] }) private val tokenMap: Map<IElementType, TextAttributesKey> = makeTokenMap() } private fun makeTokenMap(): Map<IElementType, TextAttributesKey> { val result = THashMap<IElementType, TextAttributesKey>() result[TomlTypes.KEY] = TextAttributesKey.createTextAttributesKey("TOML_KEY", DefaultLanguageHighlighterColors.KEYWORD) result[TomlTypes.COMMENT] = TextAttributesKey.createTextAttributesKey("TOML_COMMENT", DefaultLanguageHighlighterColors.LINE_COMMENT) result[TomlTypes.STRING] = TextAttributesKey.createTextAttributesKey("TOML_STRING", DefaultLanguageHighlighterColors.STRING) result[TomlTypes.NUMBER] = TextAttributesKey.createTextAttributesKey("TOML_NUMBER", DefaultLanguageHighlighterColors.NUMBER) result[TomlTypes.BOOLEAN] = TextAttributesKey.createTextAttributesKey("TOML_BOOLEAN", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL) result[TomlTypes.DATE] = TextAttributesKey.createTextAttributesKey("TOML_DATE", DefaultLanguageHighlighterColors.PREDEFINED_SYMBOL) return result; }
src/main/kotlin/org/toml/ide/TomlHighlighter.kt
3371364133
package edu.kit.iti.formal.automation.plcopenxml import edu.kit.iti.formal.util.CodeWriter import org.jdom2.Element /** * * @author Alexander Weigl * @version 1 (22.07.18) */ open class DataTypeExtractor(val datatypes: List<Element>, val writer: CodeWriter, val translator: List<XMLTranslator> = listOf(EnumTranslator, StructTranslator)) { fun run() { if (datatypes.isNotEmpty()) { writer.printf("TYPE").increaseIndent() datatypes.forEach { translate(it) } writer.decreaseIndent().nl().printf("END_TYPE").nl().nl() } } private fun translate(e: Element) { translator.forEach { if (it.isCapableOf(e)) it.translate(e, writer) } } }
xml/src/main/kotlin/edu/kit/iti/formal/automation/plcopenxml/datatypes.kt
3003288424
/* * Copyright 2020 Andrey Mukamolov * * 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.bookcrossing.mobile.util import com.bookcrossing.mobile.models.BookUri import com.bookcrossing.mobile.util.ValidationResult.Invalid import com.bookcrossing.mobile.util.ValidationResult.OK import org.junit.Assert.assertTrue import org.junit.Test class BookUriSchemeRuleTest { private val rule = BookUriSchemeRule() @Test fun `correct scheme`() { val bookUri = BookUri(null, "bookcrossing", null, null) assertTrue(rule.check(bookUri) is OK) } @Test fun `case insensitive scheme`() { val bookUri = BookUri(PACKAGE_NAME.toUpperCase(), "BOOKCROSSING", null, null) assertTrue(rule.check(bookUri) is OK) } @Test fun `incorrect scheme`() { val bookUri = BookUri(null, "test", null, null) assertTrue(rule.check(bookUri) is Invalid) } @Test fun `null scheme`() { val bookUri = BookUri(null, null, null, null) assertTrue(rule.check(bookUri) is Invalid) } }
app/src/test/java/com/bookcrossing/mobile/util/BookUriSchemeRuleTest.kt
396854030
package com.battlelancer.seriesguide.modules import com.battlelancer.seriesguide.backend.HexagonTools import com.battlelancer.seriesguide.shows.tools.AddUpdateShowTools import com.battlelancer.seriesguide.shows.tools.GetShowTools import com.battlelancer.seriesguide.shows.tools.ShowTools2 import com.battlelancer.seriesguide.sync.HexagonShowSync import com.battlelancer.seriesguide.sync.SgSyncAdapter import com.battlelancer.seriesguide.comments.TraktCommentsLoader import com.battlelancer.seriesguide.movies.tools.MovieTools import com.battlelancer.seriesguide.shows.tools.AddShowTask import com.battlelancer.seriesguide.shows.search.discover.TraktAddLoader import com.uwetrottmann.tmdb2.Tmdb import com.uwetrottmann.tmdb2.services.MoviesService import com.uwetrottmann.tmdb2.services.PeopleService import com.uwetrottmann.trakt5.TraktV2 import com.uwetrottmann.trakt5.services.Sync import com.uwetrottmann.trakt5.services.Users import dagger.Component import javax.inject.Singleton /** * WARNING: for Dagger2 to work with kapt, this interface has to be in Kotlin. */ @Singleton @Component( modules = [ AppModule::class, HttpClientModule::class, TmdbModule::class, TraktModule::class ] ) interface ServicesComponent { fun hexagonTools(): HexagonTools fun hexagonShowSync(): HexagonShowSync fun moviesService(): MoviesService fun movieTools(): MovieTools fun peopleService(): PeopleService? fun showTools(): ShowTools2 fun addUpdateShowTools(): AddUpdateShowTools fun getShowTools(): GetShowTools fun tmdb(): Tmdb fun trakt(): TraktV2 fun traktSync(): Sync? fun traktUsers(): Users? fun inject(addShowTask: AddShowTask) fun inject(sgSyncAdapter: SgSyncAdapter) fun inject(traktAddLoader: TraktAddLoader) fun inject(traktCommentsLoader: TraktCommentsLoader) }
app/src/main/java/com/battlelancer/seriesguide/modules/ServicesComponent.kt
1837607243
/******************************************************************************* * * * Copyright (C) 2017 by Max Lv <[email protected]> * * Copyright (C) 2017 by Mygod Studio <[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.github.shadowsocks.plugin import android.app.Activity import android.content.Intent /** * Base class for configuration activity. A configuration activity is started when user wishes to configure the * selected plugin. To create a configuration activity, extend this class, implement abstract methods, invoke * `saveChanges(options)` and `discardChanges()` when appropriate, and add it to your manifest like this: * * <pre class="prettyprint">&lt;manifest&gt; * ... * &lt;application&gt; * ... * &lt;activity android:name=".ConfigureActivity"&gt; * &lt;intent-filter&gt; * &lt;action android:name="com.github.shadowsocks.plugin.ACTION_CONFIGURE"/&gt; * &lt;category android:name="android.intent.category.DEFAULT"/&gt; * &lt;data android:scheme="plugin" * android:host="com.github.shadowsocks" * android:path="/$PLUGIN_ID"/&gt; * &lt;/intent-filter&gt; * &lt;/activity&gt; * ... * &lt;/application&gt; *&lt;/manifest&gt;</pre> */ abstract class ConfigurationActivity : OptionsCapableActivity() { /** * Equivalent to setResult(RESULT_CANCELED). */ fun discardChanges() = setResult(Activity.RESULT_CANCELED) /** * Equivalent to setResult(RESULT_OK, args_with_correct_format). * * @param options PluginOptions to save. */ fun saveChanges(options: PluginOptions) = setResult(Activity.RESULT_OK, Intent().putExtra(PluginContract.EXTRA_OPTIONS, options.toString())) /** * Finish this activity and request manual editor to pop up instead. */ fun fallbackToManualEditor() { setResult(PluginContract.RESULT_FALLBACK) finish() } }
plugin/src/main/java/com/github/shadowsocks/plugin/ConfigurationActivity.kt
312185039
package ca.josephroque.bowlingcompanion.leagues import android.content.ContentValues import android.content.Context import android.content.DialogInterface import android.database.Cursor import android.database.sqlite.SQLiteDatabase import android.os.Parcel import android.support.v7.app.AlertDialog import android.support.v7.preference.PreferenceManager import android.util.Log import android.widget.NumberPicker import ca.josephroque.bowlingcompanion.R import ca.josephroque.bowlingcompanion.bowlers.Bowler import ca.josephroque.bowlingcompanion.common.interfaces.INameAverage import ca.josephroque.bowlingcompanion.common.interfaces.KParcelable import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator import ca.josephroque.bowlingcompanion.common.interfaces.readBoolean import ca.josephroque.bowlingcompanion.common.interfaces.writeBoolean import ca.josephroque.bowlingcompanion.database.Annihilator import ca.josephroque.bowlingcompanion.database.Contract.GameEntry import ca.josephroque.bowlingcompanion.database.Contract.LeagueEntry import ca.josephroque.bowlingcompanion.database.Contract.SeriesEntry import ca.josephroque.bowlingcompanion.database.DatabaseManager import ca.josephroque.bowlingcompanion.games.Game import ca.josephroque.bowlingcompanion.scoring.Average import ca.josephroque.bowlingcompanion.series.Series import ca.josephroque.bowlingcompanion.utils.BCError import ca.josephroque.bowlingcompanion.utils.Preferences import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.async import java.lang.ref.WeakReference import java.text.SimpleDateFormat import java.util.Date import java.util.Locale /** * Copyright (C) 2018 Joseph Roque * * A single League, which has a set of series. */ data class League( val bowler: Bowler, override val id: Long, override val name: String, override val average: Double, val isEvent: Boolean, val gamesPerSeries: Int, val additionalPinfall: Int, val additionalGames: Int, val gameHighlight: Int, val seriesHighlight: Int ) : INameAverage, KParcelable { private var _isDeleted: Boolean = false override val isDeleted: Boolean get() = _isDeleted val isPractice: Boolean get() = name == PRACTICE_LEAGUE_NAME // MARK: Constructors private constructor(p: Parcel): this( bowler = p.readParcelable<Bowler>(Bowler::class.java.classLoader)!!, id = p.readLong(), name = p.readString()!!, average = p.readDouble(), isEvent = p.readBoolean(), gamesPerSeries = p.readInt(), additionalPinfall = p.readInt(), additionalGames = p.readInt(), gameHighlight = p.readInt(), seriesHighlight = p.readInt() ) constructor(league: League): this( bowler = league.bowler, id = league.id, name = league.name, average = league.average, isEvent = league.isEvent, gamesPerSeries = league.gamesPerSeries, additionalPinfall = league.additionalPinfall, additionalGames = league.additionalGames, gameHighlight = league.gameHighlight, seriesHighlight = league.seriesHighlight ) // MARK: Parcelable override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeParcelable(bowler, 0) writeLong(id) writeString(name) writeDouble(average) writeBoolean(isEvent) writeInt(gamesPerSeries) writeInt(additionalPinfall) writeInt(additionalGames) writeInt(gameHighlight) writeInt(seriesHighlight) } // MARK: League fun fetchSeries(context: Context): Deferred<MutableList<Series>> { return Series.fetchAll(context, this) } fun createNewSeries(context: Context, openDatabase: SQLiteDatabase? = null, numberOfPracticeGamesOverride: Int? = null): Deferred<Pair<Series?, BCError?>> { val numberOfGames = if (isPractice) { numberOfPracticeGamesOverride ?: gamesPerSeries } else { gamesPerSeries } return async(CommonPool) { return@async Series.save( context = context, league = this@League, id = -1, date = Date(), numberOfGames = numberOfGames, scores = IntArray(numberOfGames).toList(), matchPlay = ByteArray(numberOfGames).toList(), openDatabase = openDatabase ).await() } } // MARK: IDeletable override fun markForDeletion(): League { val newInstance = League(this) newInstance._isDeleted = true return newInstance } override fun cleanDeletion(): League { val newInstance = League(this) newInstance._isDeleted = false return newInstance } override fun delete(context: Context): Deferred<Unit> { return async(CommonPool) { if (id < 0) { return@async } Annihilator.instance.delete( weakContext = WeakReference(context), tableName = LeagueEntry.TABLE_NAME, whereClause = "${LeagueEntry._ID}=?", whereArgs = arrayOf(id.toString()) ) } } companion object { @Suppress("unused") private const val TAG = "League" @Suppress("unused") @JvmField val CREATOR = parcelableCreator(::League) private val REGEX_NAME = Bowler.REGEX_NAME @Deprecated("Replaced with PRACTICE_LEAGUE_NAME") const val OPEN_LEAGUE_NAME = "Open" const val PRACTICE_LEAGUE_NAME = "Practice" const val MAX_NUMBER_OF_GAMES = 20 const val MIN_NUMBER_OF_GAMES = 1 const val DEFAULT_NUMBER_OF_GAMES = 1 const val DEFAULT_GAME_HIGHLIGHT = 300 val DEFAULT_SERIES_HIGHLIGHT = intArrayOf(250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500, 2750, 3000, 3250, 3500, 3750, 4000, 4250, 4500, 4750, 5000) enum class Sort { Alphabetically, LastModified; companion object { private val map = Sort.values().associateBy(Sort::ordinal) fun fromInt(type: Int) = map[type] } } fun showPracticeGamesPicker(context: Context, completionHandler: (Int) -> Unit) { val numberPicker = NumberPicker(context) numberPicker.maxValue = League.MAX_NUMBER_OF_GAMES numberPicker.minValue = 1 numberPicker.wrapSelectorWheel = false val listener = DialogInterface.OnClickListener { dialog, which -> if (which == DialogInterface.BUTTON_POSITIVE) { completionHandler(numberPicker.value) } dialog.dismiss() } AlertDialog.Builder(context) .setTitle(R.string.how_many_practice_games) .setView(numberPicker) .setPositiveButton(R.string.bowl, listener) .setNegativeButton(R.string.cancel, listener) .create() .show() } private fun isLeagueNameValid(name: String): Boolean = REGEX_NAME.matches(name) private fun nameMatchesPracticeLeague(name: String): Boolean = PRACTICE_LEAGUE_NAME.toLowerCase().equals(name.toLowerCase()) private fun isLeagueNameUnique(context: Context, name: String, id: Long = -1): Deferred<Boolean> { return async(CommonPool) { val database = DatabaseManager.getReadableDatabase(context).await() var cursor: Cursor? = null try { cursor = database.query( LeagueEntry.TABLE_NAME, arrayOf(LeagueEntry.COLUMN_LEAGUE_NAME), "${LeagueEntry.COLUMN_LEAGUE_NAME}=? AND ${LeagueEntry._ID}!=?", arrayOf(name, id.toString()), "", "", "" ) if ((cursor?.count ?: 0) > 0) { return@async false } } finally { if (cursor != null && !cursor.isClosed) { cursor.close() } } true } } private fun validateSavePreconditions( context: Context, id: Long, name: String, isEvent: Boolean, gamesPerSeries: Int, additionalPinfall: Int, additionalGames: Int, gameHighlight: Int, seriesHighlight: Int ): Deferred<BCError?> { return async(CommonPool) { val errorTitle = if (isEvent) R.string.issue_saving_event else R.string.issue_saving_league val errorMessage: Int? if (nameMatchesPracticeLeague(name)) { errorMessage = R.string.error_league_name_is_practice } else if (!isLeagueNameValid(name)) { errorMessage = if (isEvent) R.string.error_event_name_invalid else R.string.error_league_name_invalid } else if (!isLeagueNameUnique(context, name, id).await()) { errorMessage = R.string.error_league_name_in_use } else if (name == PRACTICE_LEAGUE_NAME) { errorMessage = R.string.error_cannot_edit_practice_league } else if ( (isEvent && (additionalPinfall != 0 || additionalGames != 0)) || (additionalPinfall < 0 || additionalGames < 0) || (additionalPinfall > 0 && additionalGames == 0) || (additionalPinfall.toDouble() / additionalGames.toDouble() > 450) ) { errorMessage = R.string.error_league_additional_info_unbalanced } else if ( gameHighlight < 0 || gameHighlight > Game.MAX_SCORE || seriesHighlight < 0 || seriesHighlight > Game.MAX_SCORE * gamesPerSeries ) { errorMessage = R.string.error_league_highlight_invalid } else if (gamesPerSeries < MIN_NUMBER_OF_GAMES || gamesPerSeries > MAX_NUMBER_OF_GAMES) { errorMessage = R.string.error_league_number_of_games_invalid } else { errorMessage = null } return@async if (errorMessage != null) { BCError(errorTitle, errorMessage, BCError.Severity.Warning) } else { null } } } fun save( context: Context, bowler: Bowler, id: Long, name: String, isEvent: Boolean, gamesPerSeries: Int, additionalPinfall: Int, additionalGames: Int, gameHighlight: Int, seriesHighlight: Int, average: Double = 0.0 ): Deferred<Pair<League?, BCError?>> { return if (id < 0) { createNewAndSave(context, bowler, name, isEvent, gamesPerSeries, additionalPinfall, additionalGames, gameHighlight, seriesHighlight) } else { update(context, bowler, id, name, average, isEvent, gamesPerSeries, additionalPinfall, additionalGames, gameHighlight, seriesHighlight) } } private fun createNewAndSave( context: Context, bowler: Bowler, name: String, isEvent: Boolean, gamesPerSeries: Int, additionalPinfall: Int, additionalGames: Int, gameHighlight: Int, seriesHighlight: Int ): Deferred<Pair<League?, BCError?>> { return async(CommonPool) { val error = validateSavePreconditions( context = context, id = -1, name = name, isEvent = isEvent, gamesPerSeries = gamesPerSeries, additionalPinfall = additionalPinfall, additionalGames = additionalGames, gameHighlight = gameHighlight, seriesHighlight = seriesHighlight ).await() if (error != null) { return@async Pair(null, error) } val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA) val currentDate = dateFormat.format(Date()) val values = ContentValues().apply { put(LeagueEntry.COLUMN_LEAGUE_NAME, name) put(LeagueEntry.COLUMN_DATE_MODIFIED, currentDate) put(LeagueEntry.COLUMN_BOWLER_ID, bowler.id) put(LeagueEntry.COLUMN_ADDITIONAL_PINFALL, additionalPinfall) put(LeagueEntry.COLUMN_ADDITIONAL_GAMES, additionalGames) put(LeagueEntry.COLUMN_NUMBER_OF_GAMES, gamesPerSeries) put(LeagueEntry.COLUMN_IS_EVENT, isEvent) put(LeagueEntry.COLUMN_GAME_HIGHLIGHT, gameHighlight) put(LeagueEntry.COLUMN_SERIES_HIGHLIGHT, seriesHighlight) } val league: League val database = DatabaseManager.getWritableDatabase(context).await() database.beginTransaction() try { val leagueId = database.insert(LeagueEntry.TABLE_NAME, null, values) league = League( bowler = bowler, id = leagueId, name = name, average = 0.0, isEvent = isEvent, gamesPerSeries = gamesPerSeries, additionalPinfall = additionalPinfall, additionalGames = additionalGames, gameHighlight = gameHighlight, seriesHighlight = seriesHighlight ) if (league.id != -1L && isEvent) { /* * If the new entry is an event, its series is also created at this time * since there is only a single series to an event */ val (series, seriesError) = league.createNewSeries(context, database).await() if (seriesError != null || (series?.id ?: -1L) == -1L) { throw IllegalStateException("Series was not saved.") } } database.setTransactionSuccessful() } catch (ex: Exception) { Log.e(TAG, "Could not create a new league") return@async Pair( null, BCError(R.string.error_saving_league, R.string.error_league_not_saved) ) } finally { database.endTransaction() } Pair(league, null) } } fun update( context: Context, bowler: Bowler, id: Long, name: String, average: Double, isEvent: Boolean, gamesPerSeries: Int, additionalPinfall: Int, additionalGames: Int, gameHighlight: Int, seriesHighlight: Int ): Deferred<Pair<League?, BCError?>> { return async(CommonPool) { val error = validateSavePreconditions( context = context, id = id, name = name, isEvent = isEvent, gamesPerSeries = gamesPerSeries, additionalPinfall = additionalPinfall, additionalGames = additionalGames, gameHighlight = gameHighlight, seriesHighlight = seriesHighlight ).await() if (error != null) { return@async Pair(null, error) } val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CANADA) val currentDate = dateFormat.format(Date()) val values = ContentValues().apply { put(LeagueEntry.COLUMN_LEAGUE_NAME, name) put(LeagueEntry.COLUMN_ADDITIONAL_PINFALL, additionalPinfall) put(LeagueEntry.COLUMN_ADDITIONAL_GAMES, additionalGames) put(LeagueEntry.COLUMN_GAME_HIGHLIGHT, gameHighlight) put(LeagueEntry.COLUMN_SERIES_HIGHLIGHT, seriesHighlight) put(LeagueEntry.COLUMN_DATE_MODIFIED, currentDate) } val database = DatabaseManager.getWritableDatabase(context).await() database.beginTransaction() try { database.update(LeagueEntry.TABLE_NAME, values, LeagueEntry._ID + "=?", arrayOf(id.toString())) database.setTransactionSuccessful() } catch (ex: Exception) { Log.e(TAG, "Error updating league/event details ($name, $additionalPinfall, $additionalGames)", ex) } finally { database.endTransaction() } Pair(League( bowler = bowler, id = id, name = name, average = average, isEvent = isEvent, gamesPerSeries = gamesPerSeries, additionalPinfall = additionalPinfall, additionalGames = additionalGames, gameHighlight = gameHighlight, seriesHighlight = seriesHighlight ), null) } } fun fetchAll( context: Context, bowler: Bowler, includeLeagues: Boolean = true, includeEvents: Boolean = false ): Deferred<MutableList<League>> { return async(CommonPool) { val leagues: MutableList<League> = ArrayList() val database = DatabaseManager.getReadableDatabase(context).await() val preferences = PreferenceManager.getDefaultSharedPreferences(context) val sortBy = Sort.fromInt(preferences.getInt(Preferences.LEAGUE_SORT_ORDER, Sort.Alphabetically.ordinal)) val orderQueryBy = if (sortBy == Sort.Alphabetically) { "ORDER BY league.${LeagueEntry.COLUMN_LEAGUE_NAME} " } else { "ORDER BY league.${LeagueEntry.COLUMN_DATE_MODIFIED} DESC " } val rawLeagueEventQuery = ("SELECT " + "league.${LeagueEntry._ID} AS lid, " + "${LeagueEntry.COLUMN_LEAGUE_NAME}, " + "${LeagueEntry.COLUMN_IS_EVENT}, " + "${LeagueEntry.COLUMN_ADDITIONAL_PINFALL}, " + "${LeagueEntry.COLUMN_ADDITIONAL_GAMES}, " + "${LeagueEntry.COLUMN_GAME_HIGHLIGHT}, " + "${LeagueEntry.COLUMN_SERIES_HIGHLIGHT}, " + "${LeagueEntry.COLUMN_NUMBER_OF_GAMES}, " + "${GameEntry.COLUMN_SCORE} " + "FROM ${LeagueEntry.TABLE_NAME} AS league " + "LEFT JOIN ${SeriesEntry.TABLE_NAME} AS series " + "ON league.${LeagueEntry._ID}=series.${SeriesEntry.COLUMN_LEAGUE_ID} " + "LEFT JOIN ${GameEntry.TABLE_NAME} AS game " + "ON series.${SeriesEntry._ID}=game.${GameEntry.COLUMN_SERIES_ID} " + "WHERE ${LeagueEntry.COLUMN_BOWLER_ID}=? " + orderQueryBy) val cursor = database.rawQuery(rawLeagueEventQuery, arrayOf(bowler.id.toString())) var lastId: Long = -1 var leagueNumberOfGames = 0 var leagueTotal = 0 fun isCurrentLeagueEvent(cursor: Cursor): Boolean { return cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_IS_EVENT)) == 1 } fun buildLeagueFromCursor(cursor: Cursor): League { val id = cursor.getLong(cursor.getColumnIndex("lid")) val name = cursor.getString(cursor.getColumnIndex(LeagueEntry.COLUMN_LEAGUE_NAME)) val additionalPinfall = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_ADDITIONAL_PINFALL)) val additionalGames = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_ADDITIONAL_GAMES)) val gameHighlight = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_GAME_HIGHLIGHT)) val seriesHighlight = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_SERIES_HIGHLIGHT)) val gamesPerSeries = cursor.getInt(cursor.getColumnIndex(LeagueEntry.COLUMN_NUMBER_OF_GAMES)) val average = Average.getAdjustedAverage(leagueTotal, leagueNumberOfGames, additionalPinfall, additionalGames) val isEvent = isCurrentLeagueEvent(cursor) return League( bowler, id, name, average, isEvent, gamesPerSeries, additionalPinfall, additionalGames, gameHighlight, seriesHighlight ) } if (cursor.moveToFirst()) { while (!cursor.isAfterLast) { val newId = cursor.getLong(cursor.getColumnIndex("lid")) if (newId != lastId && lastId != -1L) { cursor.moveToPrevious() val isEvent = isCurrentLeagueEvent(cursor) if ((includeEvents && isEvent) || (includeLeagues && !isEvent)) { leagues.add(buildLeagueFromCursor(cursor)) } leagueTotal = 0 leagueNumberOfGames = 0 cursor.moveToNext() } val score = cursor.getShort(cursor.getColumnIndex(GameEntry.COLUMN_SCORE)) if (score > 0) { leagueTotal += score.toInt() leagueNumberOfGames++ } lastId = newId cursor.moveToNext() } cursor.moveToPrevious() val isEvent = isCurrentLeagueEvent(cursor) if ((includeEvents && isEvent) || (includeLeagues && !isEvent)) { leagues.add(buildLeagueFromCursor(cursor)) } } cursor.close() leagues } } } }
app/src/main/java/ca/josephroque/bowlingcompanion/leagues/League.kt
1212102933
/* * ************************************************************************************************* * Copyright 2017 Universum Studios * ************************************************************************************************* * 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 universum.studios.gradle.github.task.specification import org.gradle.api.Task /** * Class describing a simple task used by the GitHub Release plugin. * * @author Martin Albedinsky * @since 1.0 * * @property type Type of the task. * @property name Name of the task. * @property description Description of the task. * @property dependsOn List of the tasks that the plugin task depends on. * @constructor Creates a new instance of TaskSpecification with the specified name and description. */ data class TaskSpecification<T : Task> ( val group: String = TaskSpecification.GROUP, val type: Class<T>, val name: String, val description: String = "", val dependsOn: List<Task> = emptyList()) { /** */ companion object Contract { /** * Name of the **group** property of a task. */ const val TASK_GROUP = "group" /** * Name of the **type** property of a task. */ const val TASK_TYPE = "type" /** * Name of the **name** property of a task. */ const val TASK_NAME = "name" /** * Name of the **description** property of a task. */ const val TASK_DESCRIPTION = "description" /** * Name of the **dependsOn** property of a task. */ const val TASK_DEPENDS_ON = "dependsOn" /** * Name of the group where all Gradle tasks provided by the GitHub plugin are placed by * default. */ const val GROUP = "github" } }
plugin/src/core/kotlin/universum/studios/gradle/github/task/specification/TaskSpecification.kt
1688675493
package com.floor13.game.screens import com.badlogic.gdx.Gdx import com.badlogic.gdx.ScreenAdapter import com.badlogic.gdx.scenes.scene2d.Stage import com.badlogic.gdx.utils.viewport.ExtendViewport import com.badlogic.gdx.InputMultiplexer import com.badlogic.gdx.InputAdapter import com.badlogic.gdx.Input import com.floor13.game.core.World import com.floor13.game.actors.MapActor import com.floor13.game.actors.CreatureActor import com.floor13.game.core.actions.MoveAction import com.floor13.game.core.actions.OpenDoorAction import com.floor13.game.core.Position import com.floor13.game.core.creatures.Creature import com.floor13.game.core.map.Door class GameScreen(val world: World) : ScreenAdapter() { val levelStage = Stage(ExtendViewport( Gdx.graphics.width.toFloat(), Gdx.graphics.height.toFloat() )) val hudStage = Stage() // TODO: pick viewport val mapScroller = object: InputAdapter() { var x = 0 var y = 0 override fun touchDown(x: Int, y: Int, pointer: Int, button: Int): Boolean { this.x = x this.y = y return true } override fun touchDragged(x: Int, y: Int, pointer: Int): Boolean { val dx = this.x - x val dy = this.y - y this.x = x this.y = y levelStage.camera.translate(dx.toFloat(), -dy.toFloat(), 0f) return true } } val keyboardProcessor = object: InputAdapter() { fun scheduleMoveOrDoorOpening(position: Position) { val tile = world.currentFloor[position] val action = if (tile is Door && !tile.opened) { OpenDoorAction(world, world.mainCharacter, position) } else { MoveAction(world, world.mainCharacter, position) } if (action.isValid) world.mainCharacter.nextAction = action } override fun keyUp(keycode: Int) = when (keycode) { Input.Keys.UP -> { scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(0, 1)) true } Input.Keys.DOWN -> { scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(0, -1)) true } Input.Keys.RIGHT -> { scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(1, 0)) true } Input.Keys.LEFT -> { scheduleMoveOrDoorOpening(world.mainCharacter.position.translated(-1, 0)) true } else -> false } } private val creatureActors = mutableMapOf<Creature, CreatureActor>() init { levelStage.addActor(MapActor(world.currentFloor)) for (creature in world.creatures) { val actor = CreatureActor(creature) levelStage.addActor(actor) creatureActors.put(creature, actor) } Gdx.input.inputProcessor = InputMultiplexer( mapScroller, keyboardProcessor ) levelStage.camera.position.x = world.mainCharacter.position.x * 64f levelStage.camera.position.y = world.mainCharacter.position.y * 64f } override fun render(delta: Float) { while (world.mainCharacter.nextAction != null) { for (action in world.tick()) when (action) { is MoveAction -> { creatureActors[action.creature]?.updateBounds() ?: Gdx.app.error(TAG, "Invalid creature in move action") } } cameraFollowPlayer() } levelStage.act(delta) levelStage.draw() } companion object { val TAG = GameScreen::class.java.simpleName } fun cameraFollowPlayer() { // TODO: check val cameraX = levelStage.camera.position.x val cameraY = levelStage.camera.position.y val playerX = world.mainCharacter.position.x * 64f val playerY = world.mainCharacter.position.y * 64f val maxDistance = 64f if (cameraX > playerX) { if (cameraX - playerX > maxDistance) levelStage.camera.translate(-64f, 0f, 0f) } else { if (playerX - cameraX > maxDistance) levelStage.camera.translate(64f, 0f, 0f) } if (cameraY > playerY) { if (cameraY - playerY > maxDistance) levelStage.camera.translate(0f, -64f, 0f) } else { if (playerY - cameraY > maxDistance) levelStage.camera.translate(0f, 64f, 0f) } } }
core/src/com/floor13/game/screens/GameScreen.kt
335792545
package com.fuyoul.sanwenseller.bean.others import com.fuyoul.sanwenseller.bean.MultBaseBean import com.fuyoul.sanwenseller.configs.Code /** * @author: chen * @CreatDate: 2017\10\27 0027 * @Desc: */ class MultDialogBean : MultBaseBean { override fun itemType(): Int = Code.VIEWTYPE_MULTDIALOG var title = "" }
app/src/main/java/com/fuyoul/sanwenseller/bean/others/MultDialogBean.kt
2940989649
package com.zj.example.kotlin.advancefunction import java.io.BufferedReader import java.io.FileReader /** * use用于Closeable对象, 可以在使用完后自动关闭 * * Created by zhengjiong * date: 2017/9/30 11:30 */ fun main(vararg args: String) { //UseExample().test1() UseExample().test2() } class UseExample { /** * use用于Closeable对象, 可以在使用完后自动关闭,遇到异常也可以自动关闭 */ fun test1() { BufferedReader(FileReader("LICENSE")).use { bufferedReader: BufferedReader -> while (true) { /** * message不为空打印出来, 为空跳出循环 */ /*val message = bufferedReader.readLine() println(message?.toString()) message?.let { println(message) } ?: break*/ /** * 上面那样写太复杂,可以这样写 */ var line = bufferedReader.readLine() ?: break println(line) } } } fun test2() { BufferedReader(FileReader("LICENSE")).use { //只有一个参数的时候参数名为it可以不用写 while (true) { /** * 这里必须加it, 因为还有一个宝鸡函数也叫readLine */ var line = it.readLine() ?: break println(line) } } } }
src/main/kotlin/com/zj/example/kotlin/advancefunction/16.高阶函数-use.kt
154900130
package net.junzz.app.lcg data class CreateItemDO(var key: String = "", var value: String = "")
app/src/main/kotlin/net/junzz/app/lcg/CreateItemDO.kt
913901066
package com.droibit.quickly.data.repository.appinfo import android.os.Parcel import android.os.Parcelable import com.github.gfx.android.orma.annotation.Column import com.github.gfx.android.orma.annotation.PrimaryKey import com.github.gfx.android.orma.annotation.Setter import com.github.gfx.android.orma.annotation.Table @Table data class AppInfo @Setter constructor( @PrimaryKey val packageName: String, @Column val name: String, @Column val versionName: String, @Column val versionCode: Int, @Column val icon: Int, // resource Id @Column val preInstalled: Boolean, @Column val lastUpdateTime: Long) : Parcelable { companion object { @JvmField val CREATOR: Parcelable.Creator<AppInfo> = object : Parcelable.Creator<AppInfo> { override fun createFromParcel(source: Parcel): AppInfo = AppInfo(source) override fun newArray(size: Int): Array<AppInfo?> = arrayOfNulls(size) } } val lowerName: String by lazy { name.toLowerCase() } val lowerPackageName: String by lazy { packageName.toLowerCase() } constructor(source: Parcel) : this( source.readString(), source.readString(), source.readString(), source.readInt(), source.readInt(), 1 == source.readInt(), source.readLong() ) override fun describeContents() = 0 override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(packageName) dest.writeString(name) dest.writeString(versionName) dest.writeInt(versionCode) dest.writeInt(icon) dest.writeInt((if (preInstalled) 1 else 0)) dest.writeLong(lastUpdateTime) } }
app/src/main/kotlin/com/droibit/quickly/data/repository/appinfo/AppInfo.kt
2473265695
package de.maibornwolff.codecharta.importer.gitlogparser.parser import de.maibornwolff.codecharta.importer.gitlogparser.input.Modification import de.maibornwolff.codecharta.importer.gitlogparser.input.metrics.MetricsFactory import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.time.OffsetDateTime class LogLineParserTest { private val metricsFactory = mockk<MetricsFactory>() @BeforeEach fun setup() { every { metricsFactory.createMetrics() } returns emptyList() } @Test fun parseCommit() { // given val parserStrategy = mockk<LogParserStrategy>() val author = "An Author" val commitDate = OffsetDateTime.now() val filenames = listOf("src/Main.java", "src/Util.java") val input = emptyList<String>() every { parserStrategy.parseAuthor(any()) } returns author every { parserStrategy.parseDate(any()) } returns commitDate every { parserStrategy.parseModifications(input) } returns filenames.map { Modification(it) } every { parserStrategy.parseIsMergeCommit(input) } returns false val parser = LogLineParser(parserStrategy, metricsFactory) // when val commit = parser.parseCommit(input) // then assertThat(commit.author).isEqualTo(author) assertThat(commit.fileNameList).isEqualTo(filenames) assertThat(commit.commitDate).isEqualTo(commitDate) } }
analysis/import/GitLogParser/src/test/kotlin/de/maibornwolff/codecharta/importer/gitlogparser/parser/LogLineParserTest.kt
4070710339
@file:JsModule("canvas") @file:JsNonModule package nodecanvas import net.perfectdreams.loritta.common.utils.image.Canvas import kotlin.js.Promise external fun createCanvas(width: Int, height: Int): Canvas external fun loadImage(path: String): Promise<dynamic>
common/src/jsMain/kotlin/nodecanvas/Canvas.kt
1514078285
package com.angcyo.uiview.widget import android.content.Context import android.util.AttributeSet import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.getColor import com.angcyo.uiview.kotlin.getDimensionPixelOffset import com.angcyo.uiview.resources.ResUtil import com.angcyo.uiview.skin.SkinHelper /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述: * 创建人员:Robi * 创建时间:2017/09/12 17:16 * 修改人员:Robi * 修改时间:2017/09/12 17:16 * 修改备注: * Version: 1.0.0 */ open class StatusButton(context: Context, attributeSet: AttributeSet? = null) : Button(context, attributeSet) { companion object { /**正常状态, 灰色背景, 黑色字体*/ val STATUS_NORMAL = 1 /**主体颜色字体, 白色字体*/ val STATUS_PRESS = 2 val STATUS_CHECK = 3 val STATUS_ENABLE = 4 /**消极*/ val STATUS_DISABLE = 5 } var buttonStatus = STATUS_NORMAL set(value) { field = value refreshButton() } init { } override fun initView() { super.initView() isClickable = false buttonStatus = STATUS_NORMAL } private fun refreshButton() { when (buttonStatus) { STATUS_NORMAL -> { setTextColor(getColor(R.color.base_text_color)) background = ResUtil.createDrawable(getColor(R.color.default_base_line), getDimensionPixelOffset(R.dimen.base_round_little_radius).toFloat()) } STATUS_DISABLE -> { setTextColor(getColor(R.color.base_white)) background = ResUtil.createDrawable(getColor(R.color.base_text_color_dark), getDimensionPixelOffset(R.dimen.base_round_little_radius).toFloat()) } STATUS_PRESS, STATUS_CHECK, STATUS_ENABLE -> { setTextColor(getColor(R.color.base_white)) background = ResUtil.createDrawable(SkinHelper.getSkin().themeSubColor, getDimensionPixelOffset(R.dimen.base_round_little_radius).toFloat()) } } } }
uiview/src/main/java/com/angcyo/uiview/widget/StatusButton.kt
2848595587
package uk.co.appsbystudio.geoshare.friends.manager.pages.pending import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import uk.co.appsbystudio.geoshare.friends.manager.FriendsManager import uk.co.appsbystudio.geoshare.utils.firebase.AddFriendsInfo import uk.co.appsbystudio.geoshare.utils.firebase.FirebaseHelper class FriendsPendingInteractorImpl: FriendsPendingInteractor { private var requestRef: DatabaseReference? = null private lateinit var requestListener: ChildEventListener override fun getRequests(listener: FriendsPendingInteractor.OnFirebaseListener) { val user = FirebaseAuth.getInstance().currentUser if (user != null) { requestRef = FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user.uid}") requestRef?.keepSynced(true) requestListener = object : ChildEventListener { override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) { listener.add(dataSnapshot.key, dataSnapshot.getValue(AddFriendsInfo::class.java)) //TODO: Get name first! } override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) { } override fun onChildRemoved(dataSnapshot: DataSnapshot) { listener.remove(dataSnapshot.key, dataSnapshot.getValue(AddFriendsInfo::class.java)) } override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) { } override fun onCancelled(databaseError: DatabaseError) { listener.error(databaseError.message) } } requestRef?.addChildEventListener(requestListener) } } override fun acceptRequest(uid: String) { FriendsManager.pendingUid.remove(uid) val user = FirebaseAuth.getInstance().currentUser FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.FRIENDS}/${user?.uid}/$uid").setValue(true) FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.FRIENDS}/$uid/${user?.uid}").setValue(true) FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid").removeValue() FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}").removeValue() } override fun rejectRequest(uid: String) { FriendsManager.pendingUid.remove(uid) val user = FirebaseAuth.getInstance().currentUser FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid").removeValue() FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}").removeValue() FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/${user?.uid}/$uid").removeValue() FirebaseDatabase.getInstance().reference.child("${FirebaseHelper.PENDING}/$uid/${user?.uid}").removeValue() } override fun removeListener() { requestRef?.removeEventListener(requestListener) } }
mobile/src/main/java/uk/co/appsbystudio/geoshare/friends/manager/pages/pending/FriendsPendingInteractorImpl.kt
4157592419
package com.github.christophpickl.kpotpourri.common.time import com.github.christophpickl.kpotpourri.common.numbers.format /** * Create a readable representation of milliseconds in a given format. */ fun Long.timify(format: MsTimification) = format.timify(this) /** * Available formats for milliseconds representation. */ enum class MsTimification { /** * Format as "1.234 seconds". */ Seconds { override fun timify(ms: Long) = (ms / 1000.0).format(3) + " seconds" }, /** * Format as "1 minute and 23 seconds". */ MinutesAndSeconds { override fun timify(ms: Long): String { val totalSeconds = (ms / 1000.0).toInt() val mins = (totalSeconds / 60) val secs = totalSeconds - (mins * 60) val pluralSeconds = if (secs == 1) "" else "s" val pluralMinutes = if (mins == 1) "" else "s" return "$mins minute$pluralMinutes and $secs second$pluralSeconds" } } ; internal abstract fun timify(ms: Long): String }
common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/time/time.kt
2954791733
/** * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.5.1-pre.0 * Contact: [email protected] * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.openapitools.client.models import com.squareup.moshi.Json /** * * * @param classes * @param propertyClass */ data class ClassesByClass ( @Json(name = "classes") val classes: kotlin.collections.List<kotlin.String>? = null, @Json(name = "_class") val propertyClass: kotlin.String? = null )
clients/kotlin/generated/src/main/kotlin/org/openapitools/client/models/ClassesByClass.kt
2334263084
package com.sksamuel.kotest.matchers.collections import io.kotest.assertions.shouldFail import io.kotest.assertions.throwables.shouldNotThrow import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.WordSpec import io.kotest.matchers.collections.atLeastSize import io.kotest.matchers.collections.atMostSize import io.kotest.matchers.collections.beEmpty import io.kotest.matchers.collections.beLargerThan import io.kotest.matchers.collections.beSameSizeAs import io.kotest.matchers.collections.beSmallerThan import io.kotest.matchers.collections.contain import io.kotest.matchers.collections.containAll import io.kotest.matchers.collections.containDuplicates import io.kotest.matchers.collections.containExactly import io.kotest.matchers.collections.containExactlyInAnyOrder import io.kotest.matchers.collections.containNoNulls import io.kotest.matchers.collections.containNull import io.kotest.matchers.collections.containOnlyNulls import io.kotest.matchers.collections.containsInOrder import io.kotest.matchers.collections.endWith import io.kotest.matchers.collections.haveElementAt import io.kotest.matchers.collections.haveSize import io.kotest.matchers.collections.monotonicallyDecreasing import io.kotest.matchers.collections.monotonicallyDecreasingWith import io.kotest.matchers.collections.monotonicallyIncreasing import io.kotest.matchers.collections.monotonicallyIncreasingWith import io.kotest.matchers.collections.shouldBeEmpty import io.kotest.matchers.collections.shouldBeIn import io.kotest.matchers.collections.shouldBeLargerThan import io.kotest.matchers.collections.shouldBeMonotonicallyDecreasing import io.kotest.matchers.collections.shouldBeMonotonicallyDecreasingWith import io.kotest.matchers.collections.shouldBeMonotonicallyIncreasing import io.kotest.matchers.collections.shouldBeMonotonicallyIncreasingWith import io.kotest.matchers.collections.shouldBeOneOf import io.kotest.matchers.collections.shouldBeSameSizeAs import io.kotest.matchers.collections.shouldBeSingleton import io.kotest.matchers.collections.shouldBeSmallerThan import io.kotest.matchers.collections.shouldBeSorted import io.kotest.matchers.collections.shouldBeSortedWith import io.kotest.matchers.collections.shouldBeStrictlyDecreasing import io.kotest.matchers.collections.shouldBeStrictlyDecreasingWith import io.kotest.matchers.collections.shouldBeStrictlyIncreasing import io.kotest.matchers.collections.shouldBeStrictlyIncreasingWith import io.kotest.matchers.collections.shouldContain import io.kotest.matchers.collections.shouldContainAll import io.kotest.matchers.collections.shouldContainAnyOf import io.kotest.matchers.collections.shouldContainDuplicates import io.kotest.matchers.collections.shouldContainExactly import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder import io.kotest.matchers.collections.shouldContainNoNulls import io.kotest.matchers.collections.shouldContainNull import io.kotest.matchers.collections.shouldContainOnlyNulls import io.kotest.matchers.collections.shouldEndWith import io.kotest.matchers.collections.shouldExist import io.kotest.matchers.collections.shouldHaveAtLeastSize import io.kotest.matchers.collections.shouldHaveAtMostSize import io.kotest.matchers.collections.shouldHaveElementAt import io.kotest.matchers.collections.shouldHaveSingleElement import io.kotest.matchers.collections.shouldHaveSize import io.kotest.matchers.collections.shouldNotBeEmpty import io.kotest.matchers.collections.shouldNotBeIn import io.kotest.matchers.collections.shouldNotBeMonotonicallyDecreasing import io.kotest.matchers.collections.shouldNotBeMonotonicallyDecreasingWith import io.kotest.matchers.collections.shouldNotBeMonotonicallyIncreasing import io.kotest.matchers.collections.shouldNotBeMonotonicallyIncreasingWith import io.kotest.matchers.collections.shouldNotBeOneOf import io.kotest.matchers.collections.shouldNotBeSingleton import io.kotest.matchers.collections.shouldNotBeSorted import io.kotest.matchers.collections.shouldNotBeSortedWith import io.kotest.matchers.collections.shouldNotBeStrictlyDecreasing import io.kotest.matchers.collections.shouldNotBeStrictlyDecreasingWith import io.kotest.matchers.collections.shouldNotBeStrictlyIncreasing import io.kotest.matchers.collections.shouldNotBeStrictlyIncreasingWith import io.kotest.matchers.collections.shouldNotContainAll import io.kotest.matchers.collections.shouldNotContainAnyOf import io.kotest.matchers.collections.shouldNotContainDuplicates import io.kotest.matchers.collections.shouldNotContainExactly import io.kotest.matchers.collections.shouldNotContainExactlyInAnyOrder import io.kotest.matchers.collections.shouldNotContainNoNulls import io.kotest.matchers.collections.shouldNotContainNull import io.kotest.matchers.collections.shouldNotContainOnlyNulls import io.kotest.matchers.collections.shouldNotEndWith import io.kotest.matchers.collections.shouldNotHaveElementAt import io.kotest.matchers.collections.shouldNotHaveSize import io.kotest.matchers.collections.shouldNotStartWith import io.kotest.matchers.collections.shouldStartWith import io.kotest.matchers.collections.singleElement import io.kotest.matchers.collections.sorted import io.kotest.matchers.collections.startWith import io.kotest.matchers.collections.strictlyDecreasing import io.kotest.matchers.collections.strictlyDecreasingWith import io.kotest.matchers.collections.strictlyIncreasing import io.kotest.matchers.collections.strictlyIncreasingWith import io.kotest.matchers.should import io.kotest.matchers.throwable.shouldHaveMessage import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldHave import io.kotest.matchers.shouldNot import io.kotest.matchers.shouldNotBe import io.kotest.matchers.shouldNotHave import java.util.ArrayList import java.util.Comparator class CollectionMatchersTest : WordSpec() { val countdown = (10 downTo 0).toList() val asc = { a: Int, b: Int -> a - b } val desc = { a: Int, b: Int -> b - a } init { "a descending non-empty list" should { "fail to ascend" { shouldFail { countdown.shouldBeSortedWith(asc) } } "descend" { countdown.shouldBeSortedWith(desc) } "not ascend" { countdown.shouldNotBeSortedWith(asc) } "fail not to descend" { shouldFail { countdown.shouldNotBeSortedWith(desc) } } } "sortedWith" should { val items = listOf( 1 to "I", 2 to "II", 4 to "IV", 5 to "V", 6 to "VI", 9 to "IX", 10 to "X" ) "work on non-Comparable given a Comparator" { items.shouldBeSortedWith(Comparator { a, b -> asc(a.first, b.first) }) } "work on non-Comparable given a compare function" { items.shouldBeSortedWith { a, b -> asc(a.first, b.first) } } } "haveElementAt" should { "test that a collection contains the specified element at the given index" { listOf("a", "b", "c") should haveElementAt(1, "b") listOf("a", "b", "c") shouldNot haveElementAt(1, "c") listOf("a", "b", null) should haveElementAt(2, null) listOf("a", "b", "c").shouldHaveElementAt(1, "b") listOf("a", "b", "c").shouldNotHaveElementAt(1, "c") listOf("a", "b", null).shouldHaveElementAt(2, null) } "support type inference for subtypes of collection" { val tests = listOf( TestSealed.Test1("test1"), TestSealed.Test2(2) ) tests should haveElementAt(0, TestSealed.Test1("test1")) tests.shouldHaveElementAt(1, TestSealed.Test2(2)) } } "containNull()" should { "test that a collection contains at least one null" { listOf(1, 2, null) should containNull() listOf(null) should containNull() listOf(1, 2) shouldNot containNull() listOf(1, 2, null).shouldContainNull() listOf(null).shouldContainNull() listOf(1, 2).shouldNotContainNull() } } "sorted" should { "test that a collection is sorted" { listOf(1, 2, 3, 4) shouldBe sorted<Int>() shouldThrow<AssertionError> { listOf(2, 1) shouldBe sorted<Int>() } listOf(1, 2, 6, 9).shouldBeSorted() shouldThrow<AssertionError> { listOf(2, 1).shouldBeSorted() }.message.shouldBe("List [2,1] should be sorted. Element 2 at index 0 was greater than element 1") shouldThrow<AssertionError> { listOf(1, 2, 3).shouldNotBeSorted() }.message.shouldBe("List [1,2,3] should not be sorted") } } "shouldBeIncreasing" should { "test that a collection is monotonically increasing" { listOf(1, 2, 2, 3) shouldBe monotonicallyIncreasing<Int>() listOf(6, 5) shouldNotBe monotonicallyIncreasing<Int>() listOf(1, 2, 2, 3).shouldBeMonotonicallyIncreasing() listOf(6, 5).shouldNotBeMonotonicallyIncreasing() } "test that a collection is monotonically increasing according to comparator" { val comparator = Comparator(desc) listOf(3, 2, 2, 1) shouldBe monotonicallyIncreasingWith(comparator) listOf(5, 6) shouldNotBe monotonicallyIncreasingWith(comparator) listOf(3, 2, 2, 1).shouldBeMonotonicallyIncreasingWith(comparator) listOf(5, 6).shouldNotBeMonotonicallyIncreasingWith(comparator) } "test that a collection is strictly increasing" { listOf(1, 2, 3) shouldBe strictlyIncreasing<Int>() listOf(1, 2, 2, 3) shouldNotBe strictlyIncreasing<Int>() listOf(6, 5) shouldNotBe strictlyIncreasing<Int>() listOf(1, 2, 3).shouldBeStrictlyIncreasing() listOf(1, 2, 2, 3).shouldNotBeStrictlyIncreasing() listOf(6, 5).shouldNotBeStrictlyIncreasing() } "test that a collection is strictly increasing according to comparator" { val comparator = Comparator(desc) listOf(3, 2, 1) shouldBe strictlyIncreasingWith(comparator) listOf(3, 2, 2, 1) shouldNotBe strictlyIncreasingWith(comparator) listOf(5, 6) shouldNotBe strictlyIncreasingWith(comparator) listOf(3, 2, 1).shouldBeStrictlyIncreasingWith(comparator) listOf(3, 2, 2, 1).shouldNotBeStrictlyIncreasingWith(comparator) listOf(5, 6).shouldNotBeStrictlyIncreasingWith(comparator) } } "shouldBeDecreasing" should { "test that a collection is monotonically decreasing" { listOf(3, 2, 2, -4) shouldBe monotonicallyDecreasing<Int>() listOf(5, 6) shouldNotBe monotonicallyDecreasing<Int>() listOf(3, 2, 2, -4).shouldBeMonotonicallyDecreasing() listOf(5, 6).shouldNotBeMonotonicallyDecreasing() } "test that a collection is monotonically decreasing according to comparator" { val comparator = Comparator(desc) listOf(-4, 2, 2, 3) shouldBe monotonicallyDecreasingWith(comparator) listOf(6, 5) shouldNotBe monotonicallyDecreasingWith(comparator) listOf(-4, 2, 2, 3).shouldBeMonotonicallyDecreasingWith(comparator) listOf(6, 5).shouldNotBeMonotonicallyDecreasingWith(comparator) } "test that a collection is strictly decreasing" { listOf(3, 2, -4) shouldBe strictlyDecreasing<Int>() listOf(3, 2, 2, -4) shouldNotBe strictlyDecreasing<Int>() listOf(5, 6) shouldNotBe strictlyDecreasing<Int>() listOf(3, 2, -4).shouldBeStrictlyDecreasing() listOf(3, 2, 2, -4).shouldNotBeStrictlyDecreasing() listOf(5, 6).shouldNotBeStrictlyDecreasing() } "test that a collection is strictly decreasing according to comparator" { val comparator = Comparator(desc) listOf(-4, 2, 3) shouldBe strictlyDecreasingWith(comparator) listOf(-4, 2, 2, 3) shouldNotBe strictlyDecreasingWith(comparator) listOf(6, 5) shouldNotBe strictlyDecreasingWith(comparator) listOf(-4, 2, 3).shouldBeStrictlyDecreasingWith(comparator) listOf(-4, 2, 2, 3).shouldNotBeStrictlyDecreasingWith(comparator) listOf(6, 5).shouldNotBeStrictlyDecreasingWith(comparator) } } "haveDuplicates" should { "test that a collection is unique" { listOf(1, 2, 3, 3) should containDuplicates() listOf(1, 2, 3, 4) shouldNot containDuplicates() listOf(1, 2, 3, 3).shouldContainDuplicates() listOf(1, 2, 3, 4).shouldNotContainDuplicates() } } "singleElement" should { "test that a collection contains a single given element" { listOf(1) shouldBe singleElement(1) listOf(1).shouldHaveSingleElement(1) shouldThrow<AssertionError> { listOf(1) shouldBe singleElement(2) } shouldThrow<AssertionError> { listOf(1, 2) shouldBe singleElement(2) } } } "singleElement with predicate" should { "test that a collection contains a single element by given predicate" { listOf(1) shouldHave singleElement { e -> e == 1} listOf(1).shouldHaveSingleElement { e -> e == 1} shouldThrow<AssertionError> { listOf(1) shouldHave singleElement { e -> e == 2} } shouldThrow<AssertionError> { listOf(2, 2) shouldHave singleElement { e -> e == 2 } } } } "should contain element" should { "test that a collection contains an element" { val col = listOf(1, 2, 3) col should contain(2) shouldThrow<AssertionError> { col should contain(4) } } } "shouldBeLargerThan" should { "test that a collection is larger than another collection" { val col1 = listOf(1, 2, 3) val col2 = setOf(1, 2, 3, 4) col2.shouldBeLargerThan(col1) col2 should beLargerThan(col1) col1 shouldNot beLargerThan(col2) shouldThrow<AssertionError> { col1.shouldBeLargerThan(col2) }.message shouldBe "Collection of size 3 should be larger than collection of size 4" } } "shouldBeSmallerThan" should { "test that a collection is smaller than another collection" { val col1 = listOf(1, 2, 3) val col2 = setOf(1, 2, 3, 4) col1.shouldBeSmallerThan(col2) col1 should beSmallerThan(col2) col2 shouldNot beSmallerThan(col1) shouldThrow<AssertionError> { col2.shouldBeSmallerThan(col1) }.message shouldBe "Collection of size 4 should be smaller than collection of size 3" } } "shouldBeSameSizeAs" should { "test that a collection is the same size as another collection" { val col1 = listOf(1, 2, 3) val col2 = setOf(1, 2, 3) val col3 = listOf(1, 2, 3, 4) col1.shouldBeSameSizeAs(col2) col1 should beSameSizeAs(col2) col1 shouldNot beSameSizeAs(col3) shouldThrow<AssertionError> { col1.shouldBeSameSizeAs(col3) }.message shouldBe "Collection of size 3 should be the same size as collection of size 4" } } "haveSize" should { "test that a collection has a certain size" { val col1 = listOf(1, 2, 3) col1 should haveSize(3) col1.shouldHaveSize(3) shouldThrow<AssertionError> { col1 should haveSize(2) } val col2 = emptyList<String>() col2 should haveSize(0) shouldThrow<AssertionError> { col2 should haveSize(1) } listOf(1, 2, 3).shouldNotHaveSize(1) listOf(1, 2, 3).shouldNotHaveSize(4) shouldThrow<AssertionError> { listOf(1, 2, 3).shouldNotHaveSize(3) }.message.shouldBe("Collection should not have size 3") } } "should be singleton" should { "pass for collection with a single element" { listOf(1).shouldBeSingleton() } "fail for collection with 0 elements" { shouldThrow<AssertionError> { listOf<Int>().shouldBeSingleton() } } "fail for collection with 2+ elements" { shouldThrow<AssertionError> { listOf(1, 2).shouldBeSingleton() } shouldThrow<AssertionError> { listOf(1, 2, 3, 4).shouldBeSingleton() } } } "should be singleton with block" should { "pass for collection with a single element" { listOf(1).shouldBeSingleton { it shouldBe 1 } } "fail for collection with 0 elements" { shouldThrow<AssertionError> { listOf<Int>().shouldBeSingleton { it shouldBe 1 } } } "fail for collection with a single incorrect elements" { shouldThrow<AssertionError> { listOf(2).shouldBeSingleton { it shouldBe 1 } } } "fail for collection with 2+ elements" { shouldThrow<AssertionError> { listOf(1, 2).shouldBeSingleton { it shouldBe 1} } shouldThrow<AssertionError> { listOf(1, 2, 3, 4).shouldBeSingleton { it shouldBe 1} } } } "should not be singleton" should { "pass for collection with 0 elements" { listOf<Int>().shouldNotBeSingleton() } "pass for collection with 2+ elements" { listOf(1, 2).shouldNotBeSingleton() listOf(1, 2, 3, 4).shouldNotBeSingleton() } "fail for collection with a single element" { shouldThrow<AssertionError> { listOf(1).shouldNotBeSingleton() } } } "shouldExist" should { "test that a collection contains at least one element that matches a predicate" { val list = listOf(1, 2, 3) list.shouldExist { it == 2 } } } "shouldHaveAtLeastSize" should { "test that a collection has at least a certain number of elements" { val list = listOf(1, 2, 3) list.shouldHaveAtLeastSize(2) list shouldHave atLeastSize(2) val set = setOf(1, 2, 3) set.shouldHaveAtLeastSize(3) set shouldHave atLeastSize(3) shouldThrow<AssertionError> { list.shouldHaveAtLeastSize(4) }.message shouldBe "Collection should contain at least 4 elements" shouldThrow<AssertionError> { list shouldHave atLeastSize(4) }.message shouldBe "Collection should contain at least 4 elements" shouldThrow<AssertionError> { list shouldNotHave atLeastSize(2) }.message.shouldBe("Collection should contain less than 2 elements") } } "shouldHaveAtMostSize" should { "test that a collection has at least a certain number of elements" { val list = listOf(1, 2, 3) list.shouldHaveAtMostSize(3) list shouldHave atMostSize(3) list.shouldHaveAtMostSize(4) list shouldHave atMostSize(4) val set = setOf(1, 2, 3) set.shouldHaveAtMostSize(3) set shouldHave atMostSize(3) set.shouldHaveAtMostSize(4) set shouldHave atMostSize(4) shouldThrow<AssertionError> { list.shouldHaveAtMostSize(2) }.message shouldBe "Collection should contain at most 2 elements" shouldThrow<AssertionError> { list shouldHave atMostSize(2) }.message shouldBe "Collection should contain at most 2 elements" shouldThrow<AssertionError> { list shouldNotHave atMostSize(4) }.message.shouldBe("Collection should contain more than 4 elements") } } "contain" should { "test that a collection contains element x" { val col = listOf(1, 2, 3) shouldThrow<AssertionError> { col should contain(4) } col should contain(2) } "support type inference for subtypes of collection" { val tests = listOf( TestSealed.Test1("test1"), TestSealed.Test2(2) ) tests should contain(TestSealed.Test1("test1")) tests.shouldContain(TestSealed.Test2(2)) } "print errors unambiguously" { shouldThrow<AssertionError> { listOf<Any>(1, 2).shouldContain(listOf<Any>(1L, 2L)) }.message shouldBe "Collection should contain element [1L, 2L]; listing some elements [1, 2]" } } "containExactly" should { "test that a collection contains given elements exactly" { val actual = listOf(1, 2, 3) emptyList<Int>() should containExactly() actual should containExactly(1, 2, 3) actual.shouldContainExactly(1, 2, 3) actual.shouldContainExactly(linkedSetOf(1, 2, 3)) actual shouldNot containExactly(1, 2) actual.shouldNotContainExactly(3, 2, 1) actual.shouldNotContainExactly(listOf(5, 6, 7)) shouldThrow<AssertionError> { actual should containExactly(1, 2) } shouldThrow<AssertionError> { actual should containExactly(1, 2, 3, 4) } shouldThrow<AssertionError> { actual.shouldContainExactly(3, 2, 1) } } "print errors unambiguously" { shouldThrow<AssertionError> { listOf<Any>(1L, 2L).shouldContainExactly(listOf<Any>(1, 2)) }.message shouldBe "Collection should be exactly [1, 2] but was [1L, 2L]" } } "containExactlyInAnyOrder" should { "test that a collection contains given elements exactly in any order" { val actual = listOf(1, 2, 3) actual should containExactlyInAnyOrder(1, 2, 3) actual.shouldContainExactlyInAnyOrder(3, 2, 1) actual.shouldContainExactlyInAnyOrder(linkedSetOf(2, 1, 3)) actual shouldNot containExactlyInAnyOrder(1, 2) actual.shouldNotContainExactlyInAnyOrder(1, 2, 3, 4) actual.shouldNotContainExactlyInAnyOrder(listOf(5, 6, 7)) actual.shouldNotContainExactlyInAnyOrder(1, 1, 1) actual.shouldNotContainExactlyInAnyOrder(listOf(2, 2, 3)) actual.shouldNotContainExactlyInAnyOrder(listOf(1, 1, 2, 3)) val actualDuplicates = listOf(1,1,2) actualDuplicates.shouldContainExactlyInAnyOrder(1,2,1) actualDuplicates.shouldContainExactlyInAnyOrder(2,1,1) actualDuplicates.shouldNotContainExactlyInAnyOrder(1,2) actualDuplicates.shouldNotContainExactlyInAnyOrder(1,2,2) actualDuplicates.shouldNotContainExactlyInAnyOrder(1,1,2,2) actualDuplicates.shouldNotContainExactlyInAnyOrder(1,2,7) shouldThrow<AssertionError> { actual should containExactlyInAnyOrder(1, 2) } shouldThrow<AssertionError> { actual should containExactlyInAnyOrder(1, 2, 3, 4) } shouldThrow<AssertionError> { actual should containExactlyInAnyOrder(1,1,1) } shouldThrow<AssertionError> { actual should containExactlyInAnyOrder(1,1,2,3) } shouldThrow<AssertionError> { actualDuplicates should containExactlyInAnyOrder(1,2,2) } } "print errors unambiguously" { shouldThrow<AssertionError> { listOf<Any>(1L, 2L).shouldContainExactlyInAnyOrder(listOf<Any>(1, 2)) }.message shouldBe "Collection should contain [1, 2] in any order, but was [1L, 2L]" } } "empty" should { "test that a collection contains an element" { val col = listOf(1, 2, 3) shouldThrow<AssertionError> { col should beEmpty() }.message.shouldBe("Collection should be empty but contained [1, 2, 3]") shouldThrow<AssertionError> { col.shouldBeEmpty() }.message.shouldBe("Collection should be empty but contained [1, 2, 3]") listOf(1, 2, 3).shouldNotBeEmpty() ArrayList<String>() should beEmpty() } } "containNoNulls" should { "test that a collection contains zero nulls" { emptyList<String>() should containNoNulls() listOf(1, 2, 3) should containNoNulls() listOf(null, null, null) shouldNot containNoNulls() listOf(1, null, null) shouldNot containNoNulls() emptyList<String>().shouldContainNoNulls() listOf(1, 2, 3).shouldContainNoNulls() listOf(null, null, null).shouldNotContainNoNulls() listOf(1, null, null).shouldNotContainNoNulls() shouldThrow<AssertionError> { listOf(null, null, null).shouldContainNoNulls() }.message.shouldBe("Collection should not contain nulls") shouldThrow<AssertionError> { listOf(1, 2, 3).shouldNotContainNoNulls() }.message.shouldBe("Collection should have at least one null") } "support type inference for subtypes of collection" { val tests = listOf( TestSealed.Test1("test1"), TestSealed.Test2(2) ) tests should containNoNulls() tests.shouldContainNoNulls() } } "containOnlyNulls" should { "test that a collection contains only nulls" { emptyList<String>() should containOnlyNulls() listOf(null, null, null) should containOnlyNulls() listOf(1, null, null) shouldNot containOnlyNulls() listOf(1, 2, 3) shouldNot containOnlyNulls() listOf(null, 1, 2, 3).shouldNotContainOnlyNulls() listOf(1, 2, 3).shouldNotContainOnlyNulls() listOf(null, null, null).shouldContainOnlyNulls() } } "containInOrder" should { "test that a collection contains the same elements in the given order, duplicates permitted" { val col = listOf(1, 1, 2, 2, 3, 3) col should containsInOrder(1, 2, 3) col should containsInOrder(1) shouldThrow<AssertionError> { col should containsInOrder(1, 2, 6) } shouldThrow<AssertionError> { col should containsInOrder(4) } shouldThrow<AssertionError> { col should containsInOrder(2, 1, 3) } } "work with unsorted collections" { val actual = listOf(5, 3, 1, 2, 4, 2) actual should containsInOrder(3, 2, 2) } "print errors unambiguously" { shouldThrow<AssertionError> { listOf<Number>(1L, 2L) should containsInOrder(listOf<Number>(1, 2)) }.message shouldBe "[1L, 2L] did not contain the elements [1, 2] in order" } } "containsAll" should { "test that a collection contains all the elements but in any order" { val col = listOf(1, 2, 3, 4, 5) col should containAll(1, 2, 3) col should containAll(3, 2, 1) col should containAll(5, 1) col should containAll(1, 5) col should containAll(1) col should containAll(5) col.shouldContainAll(1, 2, 3) col.shouldContainAll(3, 1) col.shouldContainAll(3) col.shouldNotContainAll(6) col.shouldNotContainAll(1, 6) col.shouldNotContainAll(6, 1) shouldThrow<AssertionError> { col should containAll(1, 2, 6) } shouldThrow<AssertionError> { col should containAll(6) } shouldThrow<AssertionError> { col should containAll(0, 1, 2) } shouldThrow<AssertionError> { col should containAll(3, 2, 0) } } "print errors unambiguously" { shouldThrow<AssertionError> { listOf<Number>(1, 2).shouldContainAll(listOf<Number>(1L, 2L)) }.message shouldBe "Collection should contain all of 1L, 2L but missing 1L, 2L" } } "startWith" should { "test that a list starts with the given collection" { val col = listOf(1, 2, 3, 4, 5) col.shouldStartWith(listOf(1)) col.shouldStartWith(listOf(1, 2)) col.shouldNotStartWith(listOf(2, 3)) col.shouldNotStartWith(listOf(4, 5)) col.shouldNotStartWith(listOf(1, 3)) } "print errors unambiguously" { shouldThrow<AssertionError> { listOf(1L, 2L) should startWith(listOf(1L, 3L)) }.message shouldBe "List should start with [1L, 3L]" } } "endWith" should { "test that a list ends with the given collection" { val col = listOf(1, 2, 3, 4, 5) col.shouldEndWith(listOf(5)) col.shouldEndWith(listOf(4, 5)) col.shouldNotEndWith(listOf(2, 3)) col.shouldNotEndWith(listOf(3, 5)) col.shouldNotEndWith(listOf(1, 2)) } "print errors unambiguously" { shouldThrow<AssertionError> { listOf(1L, 2L) should endWith(listOf(1L, 3L)) }.message shouldBe "List should end with [1L, 3L]" } } "Be one of" should { "Pass when the element instance is in the list" { val foo = Foo("Bar") val list = listOf(foo) foo shouldBeOneOf list } "Fail when the element instance is not in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Booz") val list = listOf(foo1) shouldThrow<AssertionError> { foo2.shouldBeOneOf(list) } } "Fail when there's an equal element, but not the same instance in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Bar") val list = listOf(foo1) shouldThrow<AssertionError> { foo2 shouldBeOneOf list } } "Fail when the list is empty" { val foo = Foo("Bar") val list = emptyList<Foo>() shouldThrow<AssertionError> { foo shouldBeOneOf list } } } "Be one of (negative)" should { "Fail when the element instance is in the list" { val foo = Foo("Bar") val list = listOf(foo) shouldThrow<AssertionError> { foo shouldNotBeOneOf list } } "Pass when the element instance is not in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Booz") val list = listOf(foo1) foo2.shouldNotBeOneOf(list) } "Pass when there's an equal element, but not the same instance in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Bar") val list = listOf(foo1) foo2 shouldNotBeOneOf list } "Fail when the list is empty" { val foo = Foo("Bar") val list = emptyList<Foo>() shouldThrow<AssertionError> { foo shouldNotBeOneOf list } } } "Contain any" should { "Fail when the list is empty" { shouldThrow<AssertionError> { listOf(1, 2, 3).shouldContainAnyOf(emptyList()) }.shouldHaveMessage("Asserting content on empty collection. Use Collection.shouldBeEmpty() instead.") } "Pass when one element is in the list" { listOf(1, 2, 3).shouldContainAnyOf(1) } "Pass when all elements are in the list" { listOf(1, 2, 3).shouldContainAnyOf(1, 2, 3) } "Fail when no element is in the list" { shouldThrow<AssertionError> { listOf(1, 2, 3).shouldContainAnyOf(4) } } } "Contain any (negative)" should { "Fail when the list is empty" { shouldThrow<AssertionError> { listOf(1, 2, 3).shouldNotContainAnyOf(emptyList()) }.shouldHaveMessage("Asserting content on empty collection. Use Collection.shouldBeEmpty() instead.") } "Pass when no element is present in the list" { listOf(1, 2, 3).shouldNotContainAnyOf(4) } "Fail when one element is in the list" { shouldThrow<AssertionError> { listOf(1, 2, 3).shouldNotContainAnyOf(1) } } "Fail when all elements are in the list" { shouldThrow<AssertionError> { listOf(1, 2, 3).shouldNotContainAnyOf(1, 2, 3) } } } "Be in" should { "Pass when the element is in the list" { val foo = Foo("Bar") val list = listOf(foo) foo shouldBeIn list } "Fail when the element is not in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Booz") val list = listOf(foo1) shouldThrow<AssertionError> { foo2.shouldBeIn(list) } } "Pass when there's an equal element, but not the same instance in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Bar") val list = listOf(foo1) shouldNotThrow<AssertionError>{ foo2 shouldBeIn list } } "Pass when there's an equal element, but not the same instance in the array" { val foo1 = Foo("Bar") val foo2 = Foo("Bar") val list = arrayOf(foo1) shouldNotThrow<AssertionError>{ foo2 shouldBeIn list } } "Fail when the list is empty" { val foo = Foo("Bar") val list = emptyList<Foo>() shouldThrow<AssertionError> { foo shouldBeIn list } } } "Be in (negative)" should { "Fail when the element is in the list" { val foo = Foo("Bar") val list = listOf(foo) shouldThrow<AssertionError> { foo shouldNotBeIn list } } "Pass when the element is not in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Booz") val list = listOf(foo1) shouldNotThrow<AssertionError> { foo2.shouldNotBeIn(list) } } "Fail when there's an equal element, but not the same instance in the list" { val foo1 = Foo("Bar") val foo2 = Foo("Bar") val list = listOf(foo1) shouldThrow<AssertionError>{ foo2 shouldNotBeIn list } } "Fail when the list is empty" { val foo = Foo("Bar") val list = emptyList<Foo>() shouldThrow<AssertionError> { foo shouldNotBeIn list } } } } } private data class Foo(val bar: String) sealed class TestSealed { data class Test1(val value: String) : TestSealed() data class Test2(val value: Int) : TestSealed() }
kotest-assertions/src/jvmTest/kotlin/com/sksamuel/kotest/matchers/collections/CollectionMatchersTest.kt
1909031086
package org.openapitools.api import org.openapitools.model.Queue import io.swagger.v3.oas.annotations.* import io.swagger.v3.oas.annotations.enums.* import io.swagger.v3.oas.annotations.media.* import io.swagger.v3.oas.annotations.responses.* import io.swagger.v3.oas.annotations.security.* import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.validation.annotation.Validated import org.springframework.web.context.request.NativeWebRequest import org.springframework.beans.factory.annotation.Autowired import javax.validation.Valid import javax.validation.constraints.DecimalMax import javax.validation.constraints.DecimalMin import javax.validation.constraints.Email import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size import kotlin.collections.List import kotlin.collections.Map @RestController @Validated @RequestMapping("\${api.base-path:}") class QueueApiController() { @Operation( summary = "", operationId = "getQueue", description = "Retrieve queue details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved queue details", content = [Content(schema = Schema(implementation = Queue::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/queue/api/json"], produces = ["application/json"] ) fun getQueue(): ResponseEntity<Queue> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } @Operation( summary = "", operationId = "getQueueItem", description = "Retrieve queued item details", responses = [ ApiResponse(responseCode = "200", description = "Successfully retrieved queued item details", content = [Content(schema = Schema(implementation = Queue::class))]), ApiResponse(responseCode = "401", description = "Authentication failed - incorrect username and/or password"), ApiResponse(responseCode = "403", description = "Jenkins requires authentication - please set username and password") ], security = [ SecurityRequirement(name = "jenkins_auth") ] ) @RequestMapping( method = [RequestMethod.GET], value = ["/queue/item/{number}/api/json"], produces = ["application/json"] ) fun getQueueItem(@Parameter(description = "Queue number", required = true) @PathVariable("number") number: kotlin.String): ResponseEntity<Queue> { return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) } }
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/api/QueueApiController.kt
1534127065
package com.ruuvi.station.settings.ui import androidx.lifecycle.ViewModel import com.ruuvi.station.app.locale.LocaleType import com.ruuvi.station.app.preferences.PreferencesRepository import com.ruuvi.station.settings.domain.AppSettingsInteractor class AppSettingsLocaleViewModel( private val appSettingsInteractor: AppSettingsInteractor, private val preferencesRepository: PreferencesRepository ) : ViewModel() { fun getAllTLocales():Array<LocaleType> = appSettingsInteractor.getAllLocales() fun getLocale() = preferencesRepository.getLocale() fun setLocale(locale: String) { preferencesRepository.setLocale(locale) } }
app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsLocaleViewModel.kt
1070695023
package com.jiangkang.tools.utils import android.content.Context import android.hardware.Sensor import android.hardware.SensorManager import com.jiangkang.tools.King.applicationContext /** * Created by jiangkang on 2017/12/4. * description: */ object SensorUtils { /* * 判断设备是否支持计步器 * */ val isSupportStepSensor: Boolean get() { val sensorManager = applicationContext!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager val counterSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER) val detectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR) return counterSensor != null || detectorSensor != null } }
tools/src/main/java/com/jiangkang/tools/utils/SensorUtils.kt
3368433140
/* * Copyright 2017 Sascha Peilicke * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.saschpe.socialfragment.app import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.saschpe.socialfragment.R import kotlinx.android.synthetic.main.activity_main.* import saschpe.android.socialfragment.app.SocialFragment class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) // Set up social fragment val fragment = SocialFragment.Builder() // Mandatory .setApplicationId("saschpe.alphaplus") // Optional .setApplicationName("Alpha+ Player") .setContactEmailAddress("[email protected]") .setFacebookGroup("466079123741258") .setGithubProject("saschpe/android-social-fragment") .setGitlabProject("saschpe") .setTwitterProfile("saschpe") // Visual customization .setHeaderTextAppearance(R.style.TextAppearance_MaterialComponents_Headline6) .setHeaderTextColor(R.color.accent) .setIconTint(android.R.color.white) .build() // Attach it supportFragmentManager.beginTransaction() .replace(R.id.fragment_placeholder, fragment) .commit() } }
social-fragment-example/src/main/java/com/example/saschpe/socialfragment/app/MainActivity.kt
1130441761
/* * Copyright @ 2018 - 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.nlj.transform.node.debug import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.transform.node.Node import org.jitsi.nlj.transform.node.NodePlugin class BufferTracePlugin { companion object : NodePlugin { override fun observe(after: Node, packetInfo: PacketInfo) { println( "array trace @${after.name}: ${System.identityHashCode(packetInfo.packet.buffer)} " + "offset ${packetInfo.packet.offset} length ${packetInfo.packet.length}" ) } } }
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/debug/BufferTracePlugin.kt
3360836685
/* * Copyright @ 2018 - 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.nlj.transform.node.outgoing import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.rtp.RtpExtensionType import org.jitsi.nlj.transform.node.ModifierNode import org.jitsi.nlj.util.ReadOnlyStreamInformationStore import org.jitsi.rtp.rtp.RtpPacket /** * Strip all hop-by-hop header extensions. Currently this leaves only ssrc-audio-level and video-orientation. */ class HeaderExtStripper( streamInformationStore: ReadOnlyStreamInformationStore ) : ModifierNode("Strip header extensions") { private var retainedExts: Set<Int> = emptySet() init { retainedExtTypes.forEach { rtpExtensionType -> streamInformationStore.onRtpExtensionMapping(rtpExtensionType) { it?.let { retainedExts = retainedExts.plus(it) } } } } override fun modify(packetInfo: PacketInfo): PacketInfo { val rtpPacket = packetInfo.packetAs<RtpPacket>() rtpPacket.removeHeaderExtensionsExcept(retainedExts) return packetInfo } override fun trace(f: () -> Unit) = f.invoke() companion object { private val retainedExtTypes: Set<RtpExtensionType> = setOf( RtpExtensionType.SSRC_AUDIO_LEVEL, RtpExtensionType.VIDEO_ORIENTATION ) } }
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/outgoing/HeaderExtStripper.kt
4058563073
package block.decoration import com.cout970.magneticraft.block.BlockFallingBase import com.cout970.magneticraft.item.ItemWoodChip import com.cout970.magneticraft.misc.fuel.IFuel import net.minecraft.block.Block import net.minecraft.util.EnumFacing import net.minecraft.util.math.BlockPos import net.minecraft.world.IBlockAccess object BlockWoodChip : BlockFallingBase("block_wood_chip"), IFuel<Block> { override fun getBurnTime(): Int = ItemWoodChip.getBurnTime() * 10 override fun getFlammability(access: IBlockAccess, pos: BlockPos, facing: EnumFacing): Int = 10 override fun getFireSpreadSpeed(access: IBlockAccess, pos: BlockPos, facing: EnumFacing): Int = 25 }
ignore/test/block/decoration/BlockWoodChip.kt
2880719572
/* * Copyright 2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl.execution import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class LinePreservingSubstringTest { @Test fun `given a range starting after the first line, it should return a substring prefixed by blank lines`() { val original = """ // line 1 // line 2 buildscript { // line 4 } """.replaceIndent() val begin = original.indexOf("buildscript") val end = original.indexOf("}") assertThat( original.linePreservingSubstring(begin..end), equalTo(""" buildscript { // line 4 }""".replaceIndent()) ) } @Test fun `given a range starting on the first line, it should return it undecorated`() { val original = """ buildscript { // line 2 } """.replaceIndent() val begin = original.indexOf("buildscript") val end = original.indexOf("}") assertThat( original.linePreservingSubstring(begin..end), equalTo(""" buildscript { // line 2 }""".replaceIndent()) ) } @Test fun `given ranges linePreservingBlankRange should blank lines`() { val original = """ |// line 1 |// line 2 |buildscript { | // line 4 |} |// line 6 |plugins { | // line 8 |} |// line 10 """.trimMargin() val buildscriptRange = original.indexOf("buildscript")..original.indexOf("}") val pluginsRange = original.indexOf("plugins")..original.lastIndexOf("}") assertThat( original.linePreservingBlankRanges(listOf(buildscriptRange, pluginsRange)), equalTo(""" |// line 1 |// line 2 | | | |// line 6 | | | |// line 10 """.trimMargin())) } }
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/execution/LinePreservingSubstringTest.kt
560161563
package com.waz.zclient.core.network import android.content.Context import com.waz.zclient.core.extension.networkInfo /** * Class which returns information about the network connection state. */ class NetworkHandler(private val context: Context) { val isConnected get() = context.networkInfo?.isConnected }
app/src/main/kotlin/com/waz/zclient/core/network/NetworkHandler.kt
4062027499
/* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mockwebserver3 import java.util.concurrent.TimeUnit import mockwebserver3.internal.duplex.DuplexResponseBody import okhttp3.Headers import okhttp3.WebSocketListener import okhttp3.internal.addHeaderLenient import okhttp3.internal.http2.Settings import okio.Buffer /** A scripted response to be replayed by the mock web server. */ class MockResponse : Cloneable { var inTunnel = false private set var informationalResponses: List<MockResponse> = listOf() private set /** Returns the HTTP response line, such as "HTTP/1.1 200 OK". */ @set:JvmName("status") var status: String = "" val code: Int get() { val statusParts = status.split(' ', limit = 3) require(statusParts.size >= 2) { "Unexpected status: $status" } return statusParts[1].toInt() } val message: String get() { val statusParts = status.split(' ', limit = 3) require(statusParts.size >= 2) { "Unexpected status: $status" } return statusParts[2] } private var headersBuilder = Headers.Builder() private var trailersBuilder = Headers.Builder() /** The HTTP headers, such as "Content-Length: 0". */ @set:JvmName("headers") var headers: Headers get() = headersBuilder.build() set(value) { this.headersBuilder = value.newBuilder() } @set:JvmName("trailers") var trailers: Headers get() = trailersBuilder.build() set(value) { this.trailersBuilder = value.newBuilder() } private var body: Buffer? = null var throttleBytesPerPeriod: Long = Long.MAX_VALUE private set private var throttlePeriodAmount = 1L private var throttlePeriodUnit = TimeUnit.SECONDS @set:JvmName("socketPolicy") var socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN /** * Sets the [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) to be * returned when resetting the stream. * This is only valid with [SocketPolicy.RESET_STREAM_AT_START] and * [SocketPolicy.DO_NOT_READ_REQUEST_BODY]. */ @set:JvmName("http2ErrorCode") var http2ErrorCode: Int = -1 private var bodyDelayAmount = 0L private var bodyDelayUnit = TimeUnit.MILLISECONDS private var headersDelayAmount = 0L private var headersDelayUnit = TimeUnit.MILLISECONDS private var promises = mutableListOf<PushPromise>() var settings: Settings = Settings() private set var webSocketListener: WebSocketListener? = null private set var duplexResponseBody: DuplexResponseBody? = null private set val isDuplex: Boolean get() = duplexResponseBody != null /** Returns the streams the server will push with this response. */ val pushPromises: List<PushPromise> get() = promises /** Creates a new mock response with an empty body. */ init { setResponseCode(200) setHeader("Content-Length", 0L) } public override fun clone(): MockResponse { val result = super.clone() as MockResponse result.headersBuilder = headersBuilder.build().newBuilder() result.promises = promises.toMutableList() return result } @JvmName("-deprecated_getStatus") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "status"), level = DeprecationLevel.ERROR) fun getStatus(): String = status /** * Sets the status and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [status] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setStatus(status: String) = apply { this.status = status } fun setResponseCode(code: Int): MockResponse { val reason = when (code) { in 100..199 -> "Informational" in 200..299 -> "OK" in 300..399 -> "Redirection" in 400..499 -> "Client Error" in 500..599 -> "Server Error" else -> "Mock Response" } return apply { status = "HTTP/1.1 $code $reason" } } /** * Removes all HTTP headers including any "Content-Length" and "Transfer-encoding" headers that * were added by default. */ fun clearHeaders() = apply { headersBuilder = Headers.Builder() } /** * Adds [header] as an HTTP header. For well-formed HTTP [header] should contain a * name followed by a colon and a value. */ fun addHeader(header: String) = apply { headersBuilder.add(header) } /** * Adds a new header with the name and value. This may be used to add multiple headers with the * same name. */ fun addHeader(name: String, value: Any) = apply { headersBuilder.add(name, value.toString()) } /** * Adds a new header with the name and value. This may be used to add multiple headers with the * same name. Unlike [addHeader] this does not validate the name and * value. */ fun addHeaderLenient(name: String, value: Any) = apply { addHeaderLenient(headersBuilder, name, value.toString()) } /** * Removes all headers named [name], then adds a new header with the name and value. */ fun setHeader(name: String, value: Any) = apply { removeHeader(name) addHeader(name, value) } /** Removes all headers named [name]. */ fun removeHeader(name: String) = apply { headersBuilder.removeAll(name) } /** Returns a copy of the raw HTTP payload. */ fun getBody(): Buffer? = body?.clone() fun setBody(body: Buffer) = apply { setHeader("Content-Length", body.size) this.body = body.clone() // Defensive copy. } /** Sets the response body to the UTF-8 encoded bytes of [body]. */ fun setBody(body: String): MockResponse = setBody(Buffer().writeUtf8(body)) fun setBody(duplexResponseBody: DuplexResponseBody) = apply { this.duplexResponseBody = duplexResponseBody } /** * Sets the response body to [body], chunked every [maxChunkSize] bytes. */ fun setChunkedBody(body: Buffer, maxChunkSize: Int) = apply { removeHeader("Content-Length") headersBuilder.add(CHUNKED_BODY_HEADER) val bytesOut = Buffer() while (!body.exhausted()) { val chunkSize = minOf(body.size, maxChunkSize.toLong()) bytesOut.writeHexadecimalUnsignedLong(chunkSize) bytesOut.writeUtf8("\r\n") bytesOut.write(body, chunkSize) bytesOut.writeUtf8("\r\n") } bytesOut.writeUtf8("0\r\n") // Last chunk. Trailers follow! this.body = bytesOut } /** * Sets the response body to the UTF-8 encoded bytes of [body], * chunked every [maxChunkSize] bytes. */ fun setChunkedBody(body: String, maxChunkSize: Int): MockResponse = setChunkedBody(Buffer().writeUtf8(body), maxChunkSize) @JvmName("-deprecated_getHeaders") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "headers"), level = DeprecationLevel.ERROR) fun getHeaders(): Headers = headers /** * Sets the headers and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [headers] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setHeaders(headers: Headers) = apply { this.headers = headers } @JvmName("-deprecated_getTrailers") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "trailers"), level = DeprecationLevel.ERROR) fun getTrailers(): Headers = trailers /** * Sets the trailers and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [trailers] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setTrailers(trailers: Headers) = apply { this.trailers = trailers } @JvmName("-deprecated_getSocketPolicy") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "socketPolicy"), level = DeprecationLevel.ERROR) fun getSocketPolicy(): SocketPolicy = socketPolicy /** * Sets the socket policy and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [socketPolicy] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setSocketPolicy(socketPolicy: SocketPolicy) = apply { this.socketPolicy = socketPolicy } @JvmName("-deprecated_getHttp2ErrorCode") @Deprecated( message = "moved to var", replaceWith = ReplaceWith(expression = "http2ErrorCode"), level = DeprecationLevel.ERROR) fun getHttp2ErrorCode(): Int = http2ErrorCode /** * Sets the HTTP/2 error code and returns this. * * This was deprecated in OkHttp 4.0 in favor of the [http2ErrorCode] val. In OkHttp 4.3 it is * un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains * deprecated). */ fun setHttp2ErrorCode(http2ErrorCode: Int) = apply { this.http2ErrorCode = http2ErrorCode } /** * Throttles the request reader and response writer to sleep for the given period after each * series of [bytesPerPeriod] bytes are transferred. Use this to simulate network behavior. */ fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit) = apply { throttleBytesPerPeriod = bytesPerPeriod throttlePeriodAmount = period throttlePeriodUnit = unit } fun getThrottlePeriod(unit: TimeUnit): Long = unit.convert(throttlePeriodAmount, throttlePeriodUnit) /** * Set the delayed time of the response body to [delay]. This applies to the response body * only; response headers are not affected. */ fun setBodyDelay(delay: Long, unit: TimeUnit) = apply { bodyDelayAmount = delay bodyDelayUnit = unit } fun getBodyDelay(unit: TimeUnit): Long = unit.convert(bodyDelayAmount, bodyDelayUnit) fun setHeadersDelay(delay: Long, unit: TimeUnit) = apply { headersDelayAmount = delay headersDelayUnit = unit } fun getHeadersDelay(unit: TimeUnit): Long = unit.convert(headersDelayAmount, headersDelayUnit) /** * When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this attaches a * pushed stream to this response. */ fun withPush(promise: PushPromise) = apply { promises.add(promise) } /** * When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this pushes * [settings] before writing the response. */ fun withSettings(settings: Settings) = apply { this.settings = settings } /** * Attempts to perform a web socket upgrade on the connection. * This will overwrite any previously set status or body. */ fun withWebSocketUpgrade(listener: WebSocketListener) = apply { status = "HTTP/1.1 101 Switching Protocols" setHeader("Connection", "Upgrade") setHeader("Upgrade", "websocket") body = null webSocketListener = listener } /** * Configures this response to be served as a response to an HTTP CONNECT request, either for * doing HTTPS through an HTTP proxy, or HTTP/2 prior knowledge through an HTTP proxy. * * When a new connection is received, all in-tunnel responses are served before the connection is * upgraded to HTTPS or HTTP/2. */ fun inTunnel() = apply { removeHeader("Content-Length") inTunnel = true } /** * Adds an HTTP 1xx response to precede this response. Note that this response's * [headers delay][setHeadersDelay] applies after this response is transmitted. Set a * headers delay on that response to delay its transmission. */ fun addInformationalResponse(response: MockResponse) = apply { informationalResponses += response } fun add100Continue() = apply { addInformationalResponse( MockResponse() .setResponseCode(100) ) } override fun toString(): String = status companion object { private const val CHUNKED_BODY_HEADER = "Transfer-encoding: chunked" } }
mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt
1220096100
/* * Copyright (c) 2021 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.calendar import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import jp.toastkid.lib.tab.OnBackCloseableTabUiFragment import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.FragmentCalendarBinding /** * @author toastkidjp */ class CalendarFragment : Fragment(), OnBackCloseableTabUiFragment { private lateinit var binding: FragmentCalendarBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) binding = DataBindingUtil.inflate(inflater, R.layout.fragment_calendar, container, false) return binding.root } }
app/src/main/java/jp/toastkid/yobidashi/calendar/CalendarFragment.kt
2485425916
/* * MUCtool Web Toolkit * * Copyright 2019 Alexander Orlov <[email protected]>. All rights reserved. * * 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/>. */ //@file:JsQualifier("mylib.pkg2") //@file:JsModule("Whois") package net.loxal.muctool.whois import org.w3c.dom.HTMLDListElement import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLElement import org.w3c.dom.HTMLInputElement import org.w3c.dom.events.Event import org.w3c.xhr.XMLHttpRequest import kotlin.browser.document import kotlin.browser.window import kotlin.js.Json import kotlin.js.Promise private fun main() { document.addEventListener("InitContainer", { Whois() }) document.addEventListener("DOMContentLoaded", { Whois() }) } class Whois { private fun clearPreviousWhoisView() { (document.getElementById("whois") as HTMLDivElement).innerHTML = "" } private val isDebugView = window.location.search.contains("debug-view") private fun log(msg: Any?) { if (isDebugView) { println(msg) } } private fun traverse(dlE: HTMLDListElement, obj: Json = JSON.parse(""), process: () -> HTMLElement) { fun process(dlE: HTMLDListElement, key: String, value: String, jsonEntryEnd: String): Promise<HTMLElement> { fun showAsQueryIpAddress(key: String, value: String) { if (key === "ip") { ipAddressContainer.value = value } } val dtE = document.createElement("dt") as HTMLElement dtE.setAttribute("style", "display: inline-block; text-indent: 1em;") val ddE = document.createElement("dd") as HTMLElement ddE.setAttribute("style", "display: inline-block; text-indent: -2.5em;") dtE.textContent = "\"$key\":" showAsQueryIpAddress(key, value) if (jsTypeOf(value) !== "object") { val ddEcontent: String = if (jsTypeOf(value) === "string") { "\"$value\"" } else { value } ddE.textContent = "$ddEcontent$jsonEntryEnd" } dlE.appendChild(dtE) dlE.appendChild(ddE) val blockBreak = document.createElement("dd") as HTMLElement blockBreak.setAttribute("style", "display: block;") dlE.appendChild(blockBreak) return Promise.resolve(ddE) } val beginContainer = document.createElement("dt") as HTMLElement beginContainer.textContent = "{" dlE.appendChild(beginContainer) log(obj) val objEntries = js("Object.entries(obj);") as Array<Array<String>> log(objEntries) objEntries.forEachIndexed { index, entry: Array<dynamic> -> val parentDdE: Promise<HTMLElement> = process(dlE, entry[0] as String, entry[1], if (objEntries.size == index + 1) "" else ",") if (entry[1] !== null && jsTypeOf(entry[1]) === "object") { val subDl = document.createElement("dl") as HTMLDListElement parentDdE.then { element: HTMLElement -> element.appendChild(subDl) traverse(subDl, entry[1], process) } } } val endContainer = document.createElement("dd") as HTMLElement endContainer.setAttribute("style", "display: block; text-indent: -3.0em;") endContainer.textContent = "}" dlE.appendChild(endContainer) } private fun whoisLookup(ipAddress: String = ""): XMLHttpRequest { val xhr = XMLHttpRequest() xhr.open("GET", "$apiUrl/whois?clientId=f5c88067-88f8-4a5b-b43e-bf0e10a8b857&queryIP=$ipAddress") xhr.send() return xhr } @JsName("autoWhoisOnEntry") internal fun autoWhoisOnEntry() { whoisLookup().onload = { val whoisResponse: XMLHttpRequest = it.target as XMLHttpRequest if (whoisResponse.status.equals(200)) { showWhois(whoisResponse) } else { whoisCustomWithDefaultFallback() } } } private var ipAddressContainer: HTMLInputElement = document.getElementById("ipAddress") as HTMLInputElement @JsName("whoisCustomWithDefaultFallback") internal fun whoisCustomWithDefaultFallback() { val ipAddress = ipAddressContainer.value whoisLookup(ipAddress).onload = { val whoisIpResponse: XMLHttpRequest = it.target as XMLHttpRequest if (whoisIpResponse.status.equals(200)) { showWhois(whoisIpResponse) } else { whoisDefault() } } } private fun whoisDefault() { ipAddressContainer.value = demoIPv6 ipAddressContainer.dispatchEvent(Event("change")) (document.getElementById("status") as HTMLDivElement).textContent = "Your IP address was not found. Another, known IP address was used." } private fun showWhois(whoisRequest: XMLHttpRequest) { val whoisInfo = JSON.parse<Json>(whoisRequest.responseText) clearPreviousWhoisView() val whoisContainer = document.createElement("dl") as HTMLDListElement (document.getElementById("whois") as HTMLDivElement).appendChild(whoisContainer) traverse(whoisContainer, whoisInfo, js("whois.net.loxal.muctool.whois.process")) } companion object Whois { internal const val apiUrl = "https://api.muctool.de" const val demoIPv6 = "2001:a61:346c:8e00:41ff:1b13:28d4:1" } init { ipAddressContainer.addEventListener("change", { whoisCustomWithDefaultFallback() }) autoWhoisOnEntry() } }
whois/src/main/kotlin/net/loxal/muctool/whois/main.kt
3979872144
package shark import okio.BufferedSink import okio.Okio import shark.HprofRecord.HeapDumpEndRecord import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.BooleanArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ByteArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.CharArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.DoubleArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.FloatArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.IntArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.LongArrayDump import shark.HprofRecord.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.ShortArrayDump import shark.StreamingRecordReaderAdapter.Companion.asStreamingRecordReader import java.io.File /** * Converts a Hprof file to another file with all primitive arrays replaced with arrays of zeroes, * which can be useful to remove PII. Char arrays are handled slightly differently because 0 would * be the null character so instead these become arrays of '?'. */ class HprofPrimitiveArrayStripper { /** * @see HprofPrimitiveArrayStripper */ fun stripPrimitiveArrays( inputHprofFile: File, /** * Optional output file. Defaults to a file in the same directory as [inputHprofFile], with * the same name and "-stripped" prepended before the ".hprof" extension. If the file extension * is not ".hprof", then "-stripped" is added at the end of the file. */ outputHprofFile: File = File( inputHprofFile.parent, inputHprofFile.name.replace( ".hprof", "-stripped.hprof" ).let { if (it != inputHprofFile.name) it else inputHprofFile.name + "-stripped" }) ): File { stripPrimitiveArrays( hprofSourceProvider = FileSourceProvider(inputHprofFile), hprofSink = Okio.buffer(Okio.sink(outputHprofFile.outputStream())) ) return outputHprofFile } /** * @see HprofPrimitiveArrayStripper */ fun stripPrimitiveArrays( hprofSourceProvider: StreamingSourceProvider, hprofSink: BufferedSink ) { val header = hprofSourceProvider.openStreamingSource().use { HprofHeader.parseHeaderOf(it) } val reader = StreamingHprofReader.readerFor(hprofSourceProvider, header).asStreamingRecordReader() HprofWriter.openWriterFor( hprofSink, hprofHeader = header ) .use { writer -> reader.readRecords(setOf(HprofRecord::class), OnHprofRecordListener { _, record -> // HprofWriter automatically emits HeapDumpEndRecord, because it flushes // all continuous heap dump sub records as one heap dump record. if (record is HeapDumpEndRecord) { return@OnHprofRecordListener } writer.write( when (record) { is BooleanArrayDump -> BooleanArrayDump( record.id, record.stackTraceSerialNumber, BooleanArray(record.array.size) ) is CharArrayDump -> CharArrayDump( record.id, record.stackTraceSerialNumber, CharArray(record.array.size) { '?' } ) is FloatArrayDump -> FloatArrayDump( record.id, record.stackTraceSerialNumber, FloatArray(record.array.size) ) is DoubleArrayDump -> DoubleArrayDump( record.id, record.stackTraceSerialNumber, DoubleArray(record.array.size) ) is ByteArrayDump -> ByteArrayDump( record.id, record.stackTraceSerialNumber, ByteArray(record.array.size) { // Converts to '?' in UTF-8 for byte backed strings 63 } ) is ShortArrayDump -> ShortArrayDump( record.id, record.stackTraceSerialNumber, ShortArray(record.array.size) ) is IntArrayDump -> IntArrayDump( record.id, record.stackTraceSerialNumber, IntArray(record.array.size) ) is LongArrayDump -> LongArrayDump( record.id, record.stackTraceSerialNumber, LongArray(record.array.size) ) else -> { record } } ) }) } } }
shark-hprof/src/main/java/shark/HprofPrimitiveArrayStripper.kt
2959841492
package com.s13g.aoc.aoc2021 import com.s13g.aoc.Result import com.s13g.aoc.Solver /** * --- Day 15: Chiton --- * https://adventofcode.com/2021/day/15 */ class Day15 : Solver { override fun solve(lines: List<String>): Result { val width = lines[0].length val height = lines.size val data = IntArray(lines.size * lines[0].length) for (y in lines.indices) { for (x in lines[y].indices) { data[width * y + x] = lines[y][x].toString().toInt() } } val partA = Board(data, width, height).calc() val partB = Board(expandForPartB(data, width, height), width * 5, height * 5).calc() return Result("$partA", "$partB") } private fun expandForPartB(data: IntArray, width: Int, height: Int): IntArray { val newData = IntArray(width * height * 5 * 5) var idx = 0 for (y in 0 until height) { for (i in 0..4) { for (x in 0 until width) newData[idx++] = roundIt(data[y * width + x] + i) } } val newWidth = width * 5 for (i in 1..4) { for (y in 0 until height) { for (x in 0 until newWidth) newData[idx++] = roundIt(newData[y * newWidth + x] + i) } } return newData } private fun roundIt(num: Int) = if (num >= 10) num - 9 else num private class Board(val data: IntArray, val width: Int, val height: Int) { // Index (width/height) and cheapest cost. val visited = mutableMapOf<Int, Int>() var activeRoutes = mutableSetOf<Route>() val goal = idxAt(width - 1, height - 1) fun calc(): Int { activeRoutes.add(Route(0, 0)) visited[0] = 0 while (activeRoutes.count { it.lastIdx != goal } > 0) { for (route in activeRoutes.toList()) { if (route.lastIdx == goal) continue activeRoutes.remove(route) if (costAt(route.lastIdx) < route.cost) continue val end = route.lastIdx val options = findNextOptions(end) for (opt in options) { val totalCost = data[opt] + route.cost if (costAt(opt) > totalCost) { activeRoutes.add(Route(opt, totalCost)) visited[opt] = totalCost } } } } return activeRoutes.sortedBy { it.cost }.first().cost } fun costAt(pos: Int) = if (visited.containsKey(pos)) visited[pos]!! else Int.MAX_VALUE fun idxAt(x: Int, y: Int) = y * width + x fun findNextOptions(pos: Int): Set<Int> { val x = pos % width val y = pos / width val result = mutableSetOf<Int>() if (x > 0) result.add(idxAt(x - 1, y)) if (x < width - 1) result.add(idxAt(x + 1, y)) if (y > 0) result.add(idxAt(x, y - 1)) if (y < height - 1) result.add(idxAt(x, y + 1)) return result } } private data class Route(val lastIdx: Int, val cost: Int); }
kotlin/src/com/s13g/aoc/aoc2021/Day15.kt
503023516
package `in`.shabhushan.cp_trials.dsbook.methods.`decrease-and-conquer` import java.util.Stack fun isCelebrity( matrix: Array<Array<Int>> ): Int { val stack = Stack<Int>() matrix.indices.forEach { index -> stack.push(index) } while (stack.size != 1) { val a = stack.pop() val b = stack.pop() // if A knows B, A is not the celebrity if (matrix[a][b] == 1) { stack.push(b) } else { stack.push(a) } } // Only one left at this point val celebrity = stack.pop() matrix.indices.forEach { personIndex -> // if celebrity knows the person or person doesn't know celebrity if (personIndex != celebrity && (matrix[celebrity][personIndex] == 1 || matrix[personIndex][celebrity] == 0)) return -1 } return celebrity }
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/dsbook/methods/decrease-and-conquer/celebrityProblem.kt
2270347889
package net.dinkla.raytracer.objects import net.dinkla.raytracer.math.* import net.dinkla.raytracer.objects.compound.Compound class Box(var p0: Point3D, a: Vector3D, b: Vector3D, c: Vector3D) : Compound() { // private var p1: Point3D // private get // val boundingBox by lazy { // // } init { // point at the "top left front" //Rectangle rBottom = new Rectangle(p0, b, a); val rBottom = Rectangle(p0, a, b, true) val rTop = Rectangle(p0.plus(c), a, b) val rFront = Rectangle(p0, a, c) // Rectangle rBehind = new Rectangle(p0.plus(b), c, a); val rBehind = Rectangle(p0.plus(b), a, c, true) // Rectangle rLeft = new Rectangle(p0, c, b); val rLeft = Rectangle(p0, b, c, true) val rRight = Rectangle(p0.plus(a), b, c) objects.add(rBottom) objects.add(rTop) objects.add(rBehind) objects.add(rLeft) objects.add(rRight) objects.add(rFront) val p1 = p0 + a + b + c boundingBox = BBox(p0, p1) } }
src/main/kotlin/net/dinkla/raytracer/objects/Box.kt
729196701
package app.lawnchair import android.content.Context import android.content.pm.PackageManager import android.service.notification.StatusBarNotification import app.lawnchair.util.checkPackagePermission import com.android.launcher3.notification.NotificationListener import com.android.launcher3.util.MainThreadInitializedObject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class NotificationManager(@Suppress("UNUSED_PARAMETER") context: Context) { private val scope = MainScope() private val notificationsMap = mutableMapOf<String, StatusBarNotification>() private val _notifications = MutableStateFlow(emptyList<StatusBarNotification>()) val notifications: Flow<List<StatusBarNotification>> get() = _notifications fun onNotificationPosted(sbn: StatusBarNotification) { notificationsMap[sbn.key] = sbn onChange() } fun onNotificationRemoved(sbn: StatusBarNotification) { notificationsMap.remove(sbn.key) onChange() } fun onNotificationFullRefresh() { scope.launch(Dispatchers.IO) { val tmpMap = NotificationListener.getInstanceIfConnected() ?.activeNotifications?.associateBy { it.key } withContext(Dispatchers.Main) { notificationsMap.clear() if (tmpMap != null) { notificationsMap.putAll(tmpMap) } onChange() } } } private fun onChange() { _notifications.value = notificationsMap.values.toList() } companion object { @JvmField val INSTANCE = MainThreadInitializedObject(::NotificationManager) } } private const val PERM_SUBSTITUTE_APP_NAME = "android.permission.SUBSTITUTE_NOTIFICATION_APP_NAME" private const val EXTRA_SUBSTITUTE_APP_NAME = "android.substName" fun StatusBarNotification.getAppName(context: Context): CharSequence { val subName = notification.extras.getString(EXTRA_SUBSTITUTE_APP_NAME) if (subName != null) { if (context.checkPackagePermission(packageName, PERM_SUBSTITUTE_APP_NAME)) { return subName } } return context.getAppName(packageName) } fun Context.getAppName(name: String): CharSequence { try { return packageManager.getApplicationLabel( packageManager.getApplicationInfo(name, PackageManager.GET_META_DATA)) } catch (ignored: PackageManager.NameNotFoundException) { } return name }
lawnchair/src/app/lawnchair/NotificationManager.kt
2841897248
package net.yslibrary.monotweety.appdata.user.local import com.pushtorefresh.storio3.sqlite.queries.DeleteQuery import com.pushtorefresh.storio3.sqlite.queries.InsertQuery import com.pushtorefresh.storio3.sqlite.queries.Query import com.pushtorefresh.storio3.sqlite.queries.UpdateQuery class UserTable { companion object { const val TABLE = "user" const val COLUMN_ID = "id" const val COLUMN_NAME = "name" const val COLUMN_SCREEN_NAME = "screen_name" const val COLUMN_PROFILE_IMAGE_URL = "profile_image_url" const val COLUMN__UPDATED_AT = "_updated_at" const val CREATE_TABLE = "CREATE TABLE $TABLE(" + "$COLUMN_ID INTEGER NOT NULL PRIMARY KEY, " + "$COLUMN_NAME TEXT NOT NULL, " + "$COLUMN_SCREEN_NAME TEXT NOT NULL, " + "$COLUMN_PROFILE_IMAGE_URL TEXT NOT NULL, " + "$COLUMN__UPDATED_AT INTEGER NOT NULL" + ");" fun queryById(id: Long) = Query.builder() .table(TABLE) .where("$COLUMN_ID = ?") .whereArgs(id) .build() fun deleteById(id: Long) = DeleteQuery.builder() .table(TABLE) .where("$COLUMN_ID = ?") .whereArgs(id) .build() fun insertQuery() = InsertQuery.builder() .table(TABLE) .build() fun updateById(id: Long) = UpdateQuery.builder() .table(TABLE) .where("$COLUMN_ID = ?") .whereArgs(id) .build() } }
app/src/main/java/net/yslibrary/monotweety/appdata/user/local/UserTable.kt
2311298765
package com.bachhuberdesign.deckbuildergwent.features.stattrack import android.database.Cursor import com.bachhuberdesign.deckbuildergwent.util.getIntFromColumn import com.bachhuberdesign.deckbuildergwent.util.getLongFromColumn import com.bachhuberdesign.deckbuildergwent.util.getStringFromColumn import io.reactivex.functions.Function import rx.functions.Func1 import java.util.* /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ data class Match(var id: Int = 0, var deckId: Int = 0, var outcome: Int = 0, var opponentFaction: Int = 0, var opponentLeader: Int = 0, var notes: String = "", var playedDate: Date = Date(), var createdDate: Date = Date(), var lastUpdate: Date = Date()) { companion object { @JvmStatic val TAG: String = Match::class.java.name const val TABLE = "matches" const val ID = "_id" const val DECK_ID = "deck_id" const val OUTCOME = "outcome" const val OPPONENT_FACTION = "opponent_faction" const val OPPONENT_LEADER = "opponent_leader" const val NOTES = "notes" const val PLAYED_DATE = "played_date" const val CREATED_DATE = "created_date" const val LAST_UPDATE = "last_update" val MAPPER = Function<Cursor, Match> { cursor -> val match = Match() match.id = cursor.getIntFromColumn(Match.ID) match.deckId = cursor.getIntFromColumn(Match.DECK_ID) match.outcome = cursor.getIntFromColumn(Match.OUTCOME) match.opponentFaction = cursor.getIntFromColumn(Match.OPPONENT_FACTION) match.opponentLeader = cursor.getIntFromColumn(Match.OPPONENT_LEADER) match.notes = cursor.getStringFromColumn(Match.NOTES) match.playedDate = Date(cursor.getLongFromColumn(Match.PLAYED_DATE)) match.createdDate = Date(cursor.getLongFromColumn(Match.CREATED_DATE)) match.lastUpdate = Date(cursor.getLongFromColumn(Match.LAST_UPDATE)) match } val MAP1 = Func1<Cursor, Match> { cursor -> val match = Match() match.id = cursor.getIntFromColumn(Match.ID) match.deckId = cursor.getIntFromColumn(Match.DECK_ID) match.outcome = cursor.getIntFromColumn(Match.OUTCOME) match.opponentFaction = cursor.getIntFromColumn(Match.OPPONENT_FACTION) match.opponentLeader = cursor.getIntFromColumn(Match.OPPONENT_LEADER) match.notes = cursor.getStringFromColumn(Match.NOTES) match.playedDate = Date(cursor.getLongFromColumn(Match.PLAYED_DATE)) match.createdDate = Date(cursor.getLongFromColumn(Match.CREATED_DATE)) match.lastUpdate = Date(cursor.getLongFromColumn(Match.LAST_UPDATE)) match } } }
app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/stattrack/Match.kt
1929547171
/* * Copyright (c) 2018 Ha Duy Trung * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.hidroh.materialistic.data.android import io.github.hidroh.materialistic.DataModule import io.github.hidroh.materialistic.data.LocalCache import io.github.hidroh.materialistic.data.MaterialisticDatabase import rx.Observable import rx.Scheduler import javax.inject.Inject import javax.inject.Named class Cache @Inject constructor( private val database: MaterialisticDatabase, private val savedStoriesDao: MaterialisticDatabase.SavedStoriesDao, private val readStoriesDao: MaterialisticDatabase.ReadStoriesDao, private val readableDao: MaterialisticDatabase.ReadableDao, @Named(DataModule.MAIN_THREAD) private val mainScheduler: Scheduler) : LocalCache { override fun getReadability(itemId: String?) = readableDao.selectByItemId(itemId)?.content override fun putReadability(itemId: String?, content: String?) { readableDao.insert(MaterialisticDatabase.Readable(itemId, content)) } override fun isViewed(itemId: String?) = readStoriesDao.selectByItemId(itemId) != null override fun setViewed(itemId: String?) { readStoriesDao.insert(MaterialisticDatabase.ReadStory(itemId)) Observable.just(itemId) .map { database.createReadUri(it) } .observeOn(mainScheduler) .subscribe { database.setLiveValue(it) } } override fun isFavorite(itemId: String?) = savedStoriesDao.selectByItemId(itemId) != null }
app/src/main/java/io/github/hidroh/materialistic/data/android/Cache.kt
3972204348
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi.ext import org.rust.lang.core.psi.RsBlockFields import org.rust.lang.core.psi.RsFieldDecl import org.rust.lang.core.psi.RsTupleFieldDecl import org.rust.lang.core.psi.RsTupleFields interface RsFieldsOwner { val blockFields: RsBlockFields? val tupleFields: RsTupleFields? } val RsFieldsOwner.namedFields: List<RsFieldDecl> get() = blockFields?.fieldDeclList.orEmpty() val RsFieldsOwner.positionalFields: List<RsTupleFieldDecl> get() = tupleFields?.tupleFieldDeclList.orEmpty()
src/main/kotlin/org/rust/lang/core/psi/ext/RsFieldsOwner.kt
725246995
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.screen import com.badlogic.gdx.Gdx import com.badlogic.gdx.InputMultiplexer import com.badlogic.gdx.InputProcessor import com.badlogic.gdx.Screen import com.badlogic.gdx.graphics.Camera import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.OrthographicCamera import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.utils.Disposable import com.jupiter.europa.screen.overlay.Overlay import com.jupiter.ganymede.event.Listener import com.jupiter.ganymede.property.Property import java.util.LinkedHashSet /** * @author Nathan Templon */ public abstract class OverlayableScreen : Screen, InputProcessor { // Fields public val overlayCamera: Camera private val overlays = LinkedHashSet<Overlay>() public val multiplexer: InputMultiplexer = InputMultiplexer() public val overlayBatch: Batch = SpriteBatch() private val tint = Property(Color.WHITE) public fun getOverlays(): Set<Overlay> { return this.overlays } public fun getTint(): Color { return this.tint.get() ?: Color.WHITE } public fun setTint(tint: Color) { this.tint.set(tint) } init { this.overlayCamera = OrthographicCamera(Gdx.graphics.getWidth().toFloat(), Gdx.graphics.getHeight().toFloat()) } // Public Methods override fun show() { } override fun hide() { } override fun dispose() { for (overlay in this.overlays) { if (overlay is Disposable) { overlay.dispose() } } } override fun resize(width: Int, height: Int) { this.overlayCamera.viewportWidth = width.toFloat() this.overlayCamera.viewportHeight = height.toFloat() this.overlayCamera.update() } public fun renderOverlays() { this.overlayCamera.update() this.overlayBatch.setProjectionMatrix(this.overlayCamera.combined) this.overlayBatch.begin() for (overlay in this.overlays) { overlay.render() } this.overlayBatch.end() } public fun addOverlay(overlay: Overlay) { this.overlays.add(overlay) this.multiplexer.addProcessor(0, overlay) overlay.added(this) } public fun removeOverlay(overlay: Overlay): Boolean { val wasPresent = this.overlays.remove(overlay) if (wasPresent) { this.multiplexer.removeProcessor(overlay) overlay.removed() } return wasPresent } public fun addTintChangedListener(listener: Listener<Property.PropertyChangedArgs<Color>>): Boolean { return this.tint.addPropertyChangedListener(listener) } public fun addTintChangedListener(listener: (Property.PropertyChangedArgs<Color>) -> Unit): Boolean = this.tint.addPropertyChangedListener(listener) public fun removeTintChangedListener(listener: Listener<Property.PropertyChangedArgs<Color>>): Boolean { return this.tint.removePropertyChangedListener(listener) } // InputProcessor Implementation override fun keyDown(i: Int): Boolean { return this.multiplexer.keyDown(i) } override fun keyUp(i: Int): Boolean { return this.multiplexer.keyUp(i) } override fun keyTyped(c: Char): Boolean { return this.multiplexer.keyTyped(c) } override fun touchDown(i: Int, i1: Int, i2: Int, i3: Int): Boolean { return this.multiplexer.touchDown(i, i1, i2, i3) } override fun touchUp(i: Int, i1: Int, i2: Int, i3: Int): Boolean { return this.multiplexer.touchUp(i, i1, i2, i3) } override fun touchDragged(i: Int, i1: Int, i2: Int): Boolean { return this.multiplexer.touchDragged(i, i1, i2) } override fun mouseMoved(i: Int, i1: Int): Boolean { return this.multiplexer.mouseMoved(i, i1) } override fun scrolled(i: Int): Boolean { return this.multiplexer.scrolled(i) } }
core/src/com/jupiter/europa/screen/OverlayableScreen.kt
1181068924
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.duplicates.bookmark import android.content.Context import com.github.duplicates.DuplicateFindTask import com.github.duplicates.DuplicateFindTaskListener import com.github.duplicates.DuplicateItemType /** * Task to find duplicate bookmarks. * * @author moshe.w */ class BookmarkFindTask<L : DuplicateFindTaskListener<BookmarkItem, BookmarkViewHolder>>( context: Context, listener: L ) : DuplicateFindTask<BookmarkItem, BookmarkViewHolder, L>( DuplicateItemType.BOOKMARK, context, listener ) { override fun createProvider(context: Context): BookmarkProvider { return BookmarkProvider(context) } override fun createAdapter(): BookmarkAdapter { return BookmarkAdapter() } override fun createComparator(): BookmarkComparator { return BookmarkComparator() } }
duplicates-android/app/src/main/java/com/github/duplicates/bookmark/BookmarkFindTask.kt
2910399961
// Build a map from the customer name to the customer fun Shop.nameToCustomerMap(): Map<String, Customer> = TODO() // Build a map from the customer to their city fun Shop.customerToCityMap(): Map<Customer, City> = TODO() // Build a map from the customer name to their city fun Shop.customerNameToCityMap(): Map<String, City> = TODO()
kotlin-koans/Collections/Associate/src/Task.kt
1547312815
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore.schemeManager import com.intellij.configurationStore.LOG import com.intellij.configurationStore.SchemeNameToFileName import com.intellij.configurationStore.StateStorageManagerImpl import com.intellij.configurationStore.StreamProvider import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.SettingsSavingComponent import com.intellij.openapi.components.impl.stores.IProjectStore import com.intellij.openapi.components.stateStore import com.intellij.openapi.options.Scheme import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.options.SchemeProcessor import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.CompoundRuntimeException import org.jetbrains.annotations.TestOnly import java.nio.file.Path import java.nio.file.Paths const val ROOT_CONFIG = "\$ROOT_CONFIG$" sealed class SchemeManagerFactoryBase : SchemeManagerFactory(), SettingsSavingComponent { private val managers = ContainerUtil.createLockFreeCopyOnWriteList<SchemeManagerImpl<Scheme, Scheme>>() protected open val componentManager: ComponentManager? = null protected open fun createFileChangeSubscriber(): ((schemeManager: SchemeManagerImpl<*, *>) -> Unit)? = null final override fun <T : Any, MutableT : T> create(directoryName: String, processor: SchemeProcessor<T, MutableT>, presentableName: String?, roamingType: RoamingType, schemeNameToFileName: SchemeNameToFileName, streamProvider: StreamProvider?, directoryPath: Path?, isAutoSave: Boolean): SchemeManager<T> { val path = checkPath(directoryName) val manager = SchemeManagerImpl(path, processor, streamProvider ?: (componentManager?.stateStore?.storageManager as? StateStorageManagerImpl)?.compoundStreamProvider, directoryPath ?: pathToFile(path), roamingType, presentableName, schemeNameToFileName, if (streamProvider != null && streamProvider.isApplicable(path, roamingType)) null else createFileChangeSubscriber()) if (isAutoSave) { @Suppress("UNCHECKED_CAST") managers.add(manager as SchemeManagerImpl<Scheme, Scheme>) } return manager } override fun dispose(schemeManager: SchemeManager<*>) { managers.remove(schemeManager) } open fun checkPath(originalPath: String): String { fun error(message: String) { // as error because it is not a new requirement if (ApplicationManager.getApplication().isUnitTestMode) throw AssertionError(message) else LOG.error(message) } when { originalPath.contains('\\') -> error("Path must be system-independent, use forward slash instead of backslash") originalPath.isEmpty() -> error("Path must not be empty") } return originalPath } abstract fun pathToFile(path: String): Path fun process(processor: (SchemeManagerImpl<Scheme, Scheme>) -> Unit) { for (manager in managers) { try { processor(manager) } catch (e: Throwable) { LOG.error("Cannot reload settings for ${manager.javaClass.name}", e) } } } final override fun save() { val errors = SmartList<Throwable>() for (registeredManager in managers) { try { registeredManager.save(errors) } catch (e: Throwable) { errors.add(e) } } CompoundRuntimeException.throwIfNotEmpty(errors) } @Suppress("unused") private class ApplicationSchemeManagerFactory : SchemeManagerFactoryBase() { override val componentManager: ComponentManager get() = ApplicationManager.getApplication() override fun checkPath(originalPath: String): String { var path = super.checkPath(originalPath) if (path.startsWith(ROOT_CONFIG)) { path = path.substring(ROOT_CONFIG.length + 1) val message = "Path must not contains ROOT_CONFIG macro, corrected: $path" if (ApplicationManager.getApplication().isUnitTestMode) throw AssertionError(message) else LOG.warn(message) } return path } override fun pathToFile(path: String) = Paths.get(ApplicationManager.getApplication().stateStore.storageManager.expandMacros( ROOT_CONFIG), path)!! } @Suppress("unused") private class ProjectSchemeManagerFactory(private val project: Project) : SchemeManagerFactoryBase() { override val componentManager = project override fun createFileChangeSubscriber(): ((schemeManager: SchemeManagerImpl<*, *>) -> Unit)? { return { schemeManager -> @Suppress("UNCHECKED_CAST") project.messageBus.connect().subscribe(VirtualFileManager.VFS_CHANGES, SchemeFileTracker(schemeManager as SchemeManagerImpl<Any, Any>, project)) } } override fun pathToFile(path: String): Path { val projectFileDir = (project.stateStore as? IProjectStore)?.projectConfigDir if (projectFileDir == null) { return Paths.get(project.basePath, ".$path") } else { return Paths.get(projectFileDir, path) } } } @TestOnly class TestSchemeManagerFactory(private val basePath: Path) : SchemeManagerFactoryBase() { override fun pathToFile(path: String) = basePath.resolve(path)!! } }
platform/configuration-store-impl/src/schemeManager/SchemeManagerFactoryImpl.kt
1349693765
package ro.cluj.totemz.utils import kotlinx.coroutines.experimental.channels.* import kotlinx.coroutines.experimental.launch import kotlin.reflect.jvm.internal.impl.javax.inject.Inject import kotlin.reflect.jvm.internal.impl.javax.inject.Singleton /** * You can use like this. * val channel = EventBus().asChannel<ItemChangeAction>() * launch (UI){ * for(action in channel){ * // You can use item * action.item * } * } */ @Singleton class EventBus @Inject constructor() { val bus: BroadcastChannel<Any> = ConflatedBroadcastChannel() fun send(o: Any) { launch { bus.send(o) } } inline fun <reified T> asChannel(): ReceiveChannel<T> { return bus.openSubscription().filter { it is T }.map { it as T } } }
app/src/main/java/ro/cluj/totemz/utils/EventBus.kt
1606550003
package com.balanza.android.harrypotter.data.character.retrofit.mapper import com.balanza.android.harrypotter.data.character.retrofit.model.CharacterBasicRetrofit import com.balanza.android.harrypotter.data.character.retrofit.model.CharacterDetail import com.balanza.android.harrypotter.data.character.retrofit.model.CharacterDetailApi import com.balanza.android.harrypotter.domain.model.character.CharacterBasic import com.balanza.android.harrypotter.domain.model.factory.HouseFactory /** * Created by balanza on 15/02/17. */ class CharacterMapperImp : CharacterMapper { override fun charactersApiToCharactersModel(charactersApi: List<CharacterBasicRetrofit>): List<CharacterBasic> { val listCharacter = charactersApi.map { singleCharacterApiToCharacterModel(it) } return listCharacter } override fun characterApiToCharacterModel( characterDetailApi: CharacterDetailApi): CharacterDetail = CharacterDetail( characterDetailApi.characterId, characterDetailApi.name, characterDetailApi.last_name, characterDetailApi.birth, characterDetailApi.gender, HouseFactory.createHouse(characterDetailApi.house), characterDetailApi.wand_description, characterDetailApi.patronus) private fun singleCharacterApiToCharacterModel(characterApi: CharacterBasicRetrofit) = CharacterBasic(characterApi.characterId, characterApi.name, HouseFactory.createHouse(characterApi.houseId), characterApi.imageUrl) }
app/src/main/java/com/balanza/android/harrypotter/data/character/retrofit/mapper/CharacterMapperImp.kt
386274072
package glimpse.models import glimpse.Angle import glimpse.Vector import glimpse.test.GlimpseSpec import glimpse.translationMatrix class ModelTransformationSpec : GlimpseSpec() { init { "Model translation" should { "give results consistent with sum of vectors" { forAll(vectors, vectors) { vector, translation -> Model(mesh { }).transform { translate(translation) }.transformation() * vector isRoughly vector + translation } forAll(vectors, vectors) { vector, translation -> Model(mesh { }).transform(translationMatrix(translation)).transformation() * vector isRoughly vector + translation } } "change over time" { var translation = Vector.X_UNIT val model = Model(mesh { }).transform { translate(translation) } model.transformation() * Vector.NULL shouldBeRoughly Vector.X_UNIT translation = Vector.Z_UNIT model.transformation() * Vector.NULL shouldBeRoughly Vector.Z_UNIT } "keep mesh transformation changes over time" { var translation = Vector.X_UNIT val model = mesh { }.transform { translate(translation) }.transform { translate(Vector.Y_UNIT) } model.transformation() * Vector.NULL shouldBeRoughly Vector(1f, 1f, 0f) translation = Vector.Z_UNIT model.transformation() * Vector.NULL shouldBeRoughly Vector(0f, 1f, 1f) } } "Composition of a translation and a rotation" should { "first translate and then rotate" { Model(mesh { }).transform { translate(Vector.X_UNIT) rotateZ(Angle.RIGHT) }.transformation() * Vector.X_UNIT shouldBeRoughly Vector.Y_UNIT * 2f } } "Composition of a rotation and a translation" should { "first rotate and then translate" { Model(mesh { }).transform { rotateZ(Angle.RIGHT) translate(Vector.X_UNIT) }.transformation() * Vector.X_UNIT shouldBeRoughly Vector.Y_UNIT + Vector.X_UNIT } } "Composition of a translation and a scaling" should { "first translate and then scale" { Model(mesh { }).transform { translate(Vector.X_UNIT) scale(2f) }.transformation() * Vector.X_UNIT shouldBeRoughly Vector.X_UNIT * 4f } } "Composition of a scaling and a translation" should { "first scale and then translate" { Model(mesh { }).transform { scale(2f) translate(Vector.X_UNIT) }.transformation() * Vector.X_UNIT shouldBeRoughly Vector.X_UNIT * 3f } } } }
api/src/test/kotlin/glimpse/models/ModelTransformationSpec.kt
1183764487
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.gms.chimera import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.content.Intent import android.database.Cursor import android.database.MatrixCursor import android.net.Uri import android.os.Bundle import android.util.Log import androidx.core.os.bundleOf import org.microg.gms.DummyService import org.microg.gms.common.GmsService import org.microg.gms.common.RemoteListenerProxy class ServiceProvider : ContentProvider() { override fun onCreate(): Boolean { Log.d(TAG, "onCreate") return true } override fun call(method: String, arg: String?, extras: Bundle?): Bundle? { when (method) { "serviceIntentCall" -> { val serviceAction = extras?.getString("serviceActionBundleKey") ?: return null val ourServiceAction = GmsService.byAction(serviceAction)?.takeIf { it.SERVICE_ID > 0 }?.ACTION val context = context!! val intent = Intent(ourServiceAction).apply { `package` = context.packageName } val resolveInfo = context.packageManager.resolveService(intent, 0) if (resolveInfo != null) { intent.setClassName(resolveInfo.serviceInfo.packageName, resolveInfo.serviceInfo.name) } else { intent.setClass(context, DummyService::class.java) } Log.d(TAG, "$method: $serviceAction -> $intent") return bundleOf( "serviceResponseIntentKey" to intent ) } else -> { Log.d(TAG, "$method: $arg, $extras") return super.call(method, arg, extras) } } } override fun query(uri: Uri, projection: Array<out String>?, selection: String?, selectionArgs: Array<out String>?, sortOrder: String?): Cursor? { val cursor = MatrixCursor(COLUMNS) Log.d(TAG, "query: $uri") return cursor } override fun insert(uri: Uri, values: ContentValues?): Uri? { Log.d(TAG, "insert: $uri, $values") return uri } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int { Log.d(TAG, "update: $uri, $values, $selection, $selectionArgs") return 0 } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int { Log.d(TAG, "delete: $uri, $selection, $selectionArgs") return 0 } override fun getType(uri: Uri): String { Log.d(TAG, "getType: $uri") return "vnd.android.cursor.item/com.google.android.gms.chimera" } companion object { private const val TAG = "ChimeraServiceProvider" private val COLUMNS = arrayOf("version", "apkPath", "loaderPath", "apkDescStr") } }
play-services-core/src/main/kotlin/org/microg/gms/chimera/ServiceProvider.kt
1652981381
package me.panpf.sketch.sample.util import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.Animation object AnimationUtils { /** * 将给定视图渐渐显示出来(view.setVisibility(View.VISIBLE)) * @param view 被处理的视图 * * * @param durationMillis 持续时间,毫秒 * * * @param isBanClick 在执行动画的过程中是否禁止点击 * * * @param animationListener 动画监听器 */ @JvmStatic @JvmOverloads fun visibleViewByAlpha(view: View, durationMillis: Long = 400, isBanClick: Boolean = true, animationListener: Animation.AnimationListener? = null) { if (view.visibility != View.VISIBLE) { view.visibility = View.VISIBLE val showAlphaAnimation = getShowAlphaAnimation(durationMillis) showAlphaAnimation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { if (isBanClick) { view.isClickable = false } animationListener?.onAnimationStart(animation) } override fun onAnimationRepeat(animation: Animation) { animationListener?.onAnimationRepeat(animation) } override fun onAnimationEnd(animation: Animation) { if (isBanClick) { view.isClickable = true } animationListener?.onAnimationEnd(animation) } }) view.startAnimation(showAlphaAnimation) } } /** * 将给定视图渐渐隐去最后从界面中移除(view.setVisibility(View.GONE)) * @param view 被处理的视图 * * * @param durationMillis 持续时间,毫秒 * * * @param isBanClick 在执行动画的过程中是否禁止点击 * * * @param animationListener 动画监听器 */ @JvmStatic @JvmOverloads fun goneViewByAlpha(view: View, durationMillis: Long = 400, isBanClick: Boolean = true, animationListener: Animation.AnimationListener? = null) { if (view.visibility != View.GONE) { val hiddenAlphaAnimation = getHiddenAlphaAnimation(durationMillis) hiddenAlphaAnimation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { if (isBanClick) { view.isClickable = false } animationListener?.onAnimationStart(animation) } override fun onAnimationRepeat(animation: Animation) { animationListener?.onAnimationRepeat(animation) } override fun onAnimationEnd(animation: Animation) { if (isBanClick) { view.isClickable = true } view.visibility = View.GONE animationListener?.onAnimationEnd(animation) } }) view.startAnimation(hiddenAlphaAnimation) } } /** * 将给定视图渐渐隐去最后从界面中移除(view.setVisibility(View.GONE)) * @param view 被处理的视图 * * * @param durationMillis 持续时间,毫秒 * * * @param isBanClick 在执行动画的过程中是否禁止点击 * * * @param animationListener 动画监听器 */ @JvmStatic @JvmOverloads fun invisibleViewByAlpha(view: View, durationMillis: Long = 400, isBanClick: Boolean = true, animationListener: Animation.AnimationListener? = null) { if (view.visibility != View.INVISIBLE) { val hiddenAlphaAnimation = getHiddenAlphaAnimation(durationMillis) hiddenAlphaAnimation.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(animation: Animation) { if (isBanClick) { view.isClickable = false } animationListener?.onAnimationStart(animation) } override fun onAnimationRepeat(animation: Animation) { animationListener?.onAnimationRepeat(animation) } override fun onAnimationEnd(animation: Animation) { if (isBanClick) { view.isClickable = true } view.visibility = View.INVISIBLE animationListener?.onAnimationEnd(animation) } }) view.startAnimation(hiddenAlphaAnimation) } } /** * 获取一个由完全显示变为不可见的透明度渐变动画 * @param durationMillis 持续时间 * * * @param animationListener 动画监听器 * * * @return 一个由完全显示变为不可见的透明度渐变动画 */ @JvmStatic @JvmOverloads fun getHiddenAlphaAnimation(durationMillis: Long, animationListener: Animation.AnimationListener? = null): AlphaAnimation { return getAlphaAnimation(1.0f, 0.0f, durationMillis, animationListener) } /** * 获取一个透明度渐变动画 * @param fromAlpha 开始时的透明度 * * * @param toAlpha 结束时的透明度都 * * * @param durationMillis 持续时间 * * * @param animationListener 动画监听器 * * * @return 一个透明度渐变动画 */ @JvmStatic fun getAlphaAnimation(fromAlpha: Float, toAlpha: Float, durationMillis: Long, animationListener: Animation.AnimationListener?): AlphaAnimation { val alphaAnimation = AlphaAnimation(fromAlpha, toAlpha) alphaAnimation.duration = durationMillis if (animationListener != null) { alphaAnimation.setAnimationListener(animationListener) } return alphaAnimation } /** * 获取一个由不可见变为完全显示的透明度渐变动画 * @param durationMillis 持续时间 * * * @return 一个由不可见变为完全显示的透明度渐变动画 */ @JvmStatic fun getShowAlphaAnimation(durationMillis: Long): AlphaAnimation { return getAlphaAnimation(0.0f, 1.0f, durationMillis, null) } }
sample/src/main/java/me/panpf/sketch/sample/util/AnimationUtils.kt
1860703808
package com.wisnia.videooo.authentication.permission enum class PermissionState { ALLOW, DENY, NONE }
core/src/main/kotlin/com/wisnia/videooo/authentication/permission/PermissionState.kt
2037947963
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.navigation import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.staticCompositionLocalOf import androidx.hilt.navigation.compose.hiltViewModel import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.receiveAsFlow val LocalNavigator = staticCompositionLocalOf<Navigator> { error("No LocalNavigator given") } @Composable fun NavigatorHost( viewModel: NavigatorViewModel = hiltViewModel(), content: @Composable () -> Unit ) { CompositionLocalProvider(LocalNavigator provides viewModel.navigator, content = content) } sealed class NavigationEvent(open val route: String) { object Back : NavigationEvent("Back") data class Destination(override val route: String) : NavigationEvent(route) } class Navigator { private val navigationQueue = Channel<NavigationEvent>(Channel.CONFLATED) fun navigate(route: String) { navigationQueue.trySend(NavigationEvent.Destination(route)) } fun back() { navigationQueue.trySend(NavigationEvent.Back) } val queue = navigationQueue.receiveAsFlow() }
modules/navigation/src/main/java/tm/alashow/navigation/Navigator.kt
1442329480
/* Copyright (c) 2021 Tarek Mohamed Abdalla <[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.utils import androidx.annotation.CallSuper import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentFactory import androidx.fragment.app.FragmentManager /** * A factory that enable extending another [FragmentFactory]. * * This should be useful if you want to add extra instantiations without overriding the instantiations in an old factory */ abstract class ExtendedFragmentFactory : FragmentFactory { private var mBaseFactory: FragmentFactory? = null /** * Create an extended factory from a base factory */ constructor(baseFactory: FragmentFactory) { mBaseFactory = baseFactory } /** * Create a factory with no base, you can assign a base factory later using [.setBaseFactory] */ constructor() {} /** * Typically you want to return the result of a super call as the last result, so if the passed class couldn't be * instantiated by the extending factory, the base factory should instantiate it. */ @CallSuper override fun instantiate(classLoader: ClassLoader, className: String): Fragment { return mBaseFactory?.instantiate(classLoader, className) ?: super.instantiate(classLoader, className) } /** * Sets a base factory to be used as a fallback */ fun setBaseFactory(baseFactory: FragmentFactory?) { mBaseFactory = baseFactory } /** * Attaches the factory to an activity by setting the current activity fragment factory as the base factory * and updating the activity with the extended factory */ inline fun <reified F : ExtendedFragmentFactory?> attachToActivity(activity: AppCompatActivity): F { return attachToFragmentManager<ExtendedFragmentFactory>(activity.supportFragmentManager) as F } /** * Attaches the factory to a fragment manager by setting the current fragment factory as the base factory * and updating the fragment manager with the extended factory */ fun <F : ExtendedFragmentFactory?> attachToFragmentManager(fragmentManager: FragmentManager): F { mBaseFactory = fragmentManager.fragmentFactory fragmentManager.fragmentFactory = this @Suppress("UNCHECKED_CAST") return this as F } }
AnkiDroid/src/main/java/com/ichi2/utils/ExtendedFragmentFactory.kt
1702472861
package de.tfelix.bestia.worldgen.io import de.tfelix.bestia.worldgen.MapGeneratorMaster import de.tfelix.bestia.worldgen.message.WorkstateMessage /** * This class can be used for local map generation purposes. There is no over * the wire transport of the messages. They are delivered to the same process * onto the same machine. Usually this is only used for local testing or if only * small maps should be generated. * * @author Thomas Felix */ class LocalMasterConnector( private val master: MapGeneratorMaster ) : MasterConnector { override fun sendMaster(workstateMessage: WorkstateMessage) { master.consumeNodeMessage(workstateMessage) } }
src/main/kotlin/de/tfelix/bestia/worldgen/io/LocalMasterConnector.kt
214533741
/* * Copyright (c) 2020 David Allison <[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.testutils class MutableTime : MockTime { private var mFrozen = false constructor(time: Long) : super(time) constructor(time: Long, step: Int) : super(time, step) constructor( year: Int, month: Int, date: Int, hourOfDay: Int, minute: Int, second: Int, milliseconds: Int, step: Int ) : super(year, month, date, hourOfDay, minute, second, milliseconds, step) fun getInternalTimeMs() = time fun setFrozen(value: Boolean) { mFrozen = value } override fun intTimeMS(): Long { return if (mFrozen) { super.time } else { super.intTimeMS() } } }
AnkiDroid/src/test/java/com/ichi2/testutils/MutableTime.kt
2568861292
/* * Copyright (C) 2019 Johannes Donath <[email protected]> * and other copyright owners as documented in the project's IP log. * * 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 tv.dotstart.beacon.ui.config import javafx.beans.InvalidationListener import javafx.beans.property.BooleanProperty import javafx.beans.property.SimpleBooleanProperty import javafx.collections.FXCollections import javafx.collections.ObservableList import tv.dotstart.beacon.ui.BeaconUiMetadata import tv.dotstart.beacon.config.storage.Config import tv.dotstart.beacon.core.delegate.logManager import tv.dotstart.beacon.ui.delegate.property import tv.dotstart.beacon.ui.util.ErrorReporter import java.io.OutputStream import java.net.URI import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardOpenOption /** * Represents the current user configuration. * * This object provides a more accessible wrapper for the configuration representation provided in * the spec package. * * @author [Johannes Donath](mailto:[email protected]) */ class Configuration(root: Path) { /** * Identifies the location of the configuration file which will persistently store all data * managed by this type. */ private val file = root.resolve("config.dat") /** * Loading flag to prevent repeated persistence when loading configuration files. */ private var loading = false /** * Identifies whether a different version of the application was running prior to this execution * thus requiring migration in some modules. */ var migration: Boolean = false private set /** * Exposes an index of user specified repository URLs which are to be pulled upon application * initialization (or manual repository refresh). */ val userRepositoryIndex: ObservableList<URI> = FXCollections.observableArrayList() /** * Identifies whether the application shall be reduced to a tray icon when iconified instead of * staying on the task bar. */ val iconifyToTrayProperty: BooleanProperty = SimpleBooleanProperty(true) /** * @see iconifyToTrayProperty */ var iconifyToTray by property(iconifyToTrayProperty) companion object { private val logger by logManager() private val currentVersion = Config.Version.V1_1 } init { val listener = InvalidationListener { this.persist() } this.userRepositoryIndex.addListener(listener) this.iconifyToTrayProperty.addListener(listener) } /** * Loads a configuration file from disk. */ fun load() { this.loading = true try { logger.info("Loading user configuration file") if (!Files.exists(this.file)) { logger.info("No prior configuration file located - Assuming defaults") this.persist() return } val serialized = Files.newInputStream(this.file).use { Config.UserConfiguration.parseFrom(it) } logger.info("Configuration version: ${serialized.version}") if (serialized.version == Config.Version.UNRECOGNIZED) { logger.warn("Incompatible save file - Changes to settings may overwrite existing data") return } this.migration = serialized.applicationVersion != BeaconUiMetadata.version || serialized.version != currentVersion if (this.migration) { logger.warn( "Migration from version ${serialized.applicationVersion} (config ${serialized.version}) in progress") } this.userRepositoryIndex.setAll(serialized.repositoryList .map { URI.create(it) } .toList()) logger.info("Discovered ${this.userRepositoryIndex.size} user repositories") this.iconifyToTray = serialized.iconifyToTray logger.info("Iconify to tray: $iconifyToTray") when (serialized.version) { Config.Version.V1_0 -> { logger.warn( "Forcefully enabling iconify to tray functionality due to configuration upgrade") this.iconifyToTray = true } else -> logger.info("No configuration parameter migration required") } ErrorReporter.trace("config", "Configuration loaded", data = mapOf( "config_version" to serialized.version, "previous_application_version" to serialized.applicationVersion )) } finally { this.loading = false } this.persist() } /** * Persists the configuration back to disk. */ fun persist() { if (this.loading) { logger.debug("Currently loading configuration file - Ignoring persist request") return } logger.info("Persisting user configuration to disk") val serialized = Config.UserConfiguration.newBuilder() .setVersion(currentVersion) .setApplicationVersion(BeaconUiMetadata.version) .addAllRepository(this.userRepositoryIndex .map(URI::toString) .toList()) .setIconifyToTray(this.iconifyToTray) .build() Files.newOutputStream(this.file, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING) .use<OutputStream?, Unit>(serialized::writeTo) ErrorReporter.trace("config", "Configuration persisted", data = mapOf( "config_version" to currentVersion )) } }
ui/src/main/kotlin/tv/dotstart/beacon/ui/config/Configuration.kt
2525216157
package io.gitlab.arturbosch.detekt.formatting.wrappers import com.pinterest.ktlint.ruleset.standard.NoSemicolonsRule import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.formatting.FormattingRule /** * See <a href="https://ktlint.github.io/#rule-semi">ktlint-website</a> for documentation. * * @active since v1.0.0 * @autoCorrect since v1.0.0 */ class NoSemicolons(config: Config) : FormattingRule(config) { override val wrapping = NoSemicolonsRule() override val issue = issueFor("Detects semicolons") }
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/wrappers/NoSemicolons.kt
2684625159
/* * Copyright 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 org.jetbrains.anko import android.content.SharedPreferences /** * Opens the [SharedPreferences.Editor], applies the [modifer] to it and then applies the changes asynchronously */ @Deprecated(message = "Use the Android KTX version", replaceWith = ReplaceWith("edit(modifier)", "androidx.core.content.edit")) inline fun SharedPreferences.apply(modifier: SharedPreferences.Editor.() -> Unit) { val editor = this.edit() editor.modifier() editor.apply() } /** * Opens the [SharedPreferences.Editor], applies the [modifer] to it and then applies the changes synchronously */ @Deprecated(message = "Use the Android KTX version", replaceWith = ReplaceWith("edit(true, modifier)", "androidx.core.content.edit")) inline fun SharedPreferences.commit(modifier: SharedPreferences.Editor.() -> Unit) { val editor = this.edit() editor.modifier() editor.commit() }
anko/library/static/commons/src/main/java/SharedPreferences.kt
3437318448
package jgappsandgames.smartreminderslite.utility // Android OS import android.app.Activity import android.os.VibrationEffect // Anko import org.jetbrains.anko.vibrator // Save import jgappsandgames.smartreminderssave.utility.hasOreo @Suppress("DEPRECATION") fun vibrate(activity: Activity) { if (activity.vibrator.hasVibrator()) { if (hasOreo()) activity.vibrator.vibrate(VibrationEffect.createOneShot(100, VibrationEffect.DEFAULT_AMPLITUDE)) else activity.vibrator.vibrate(100) } }
app/src/main/java/jgappsandgames/smartreminderslite/utility/SDKUtility.kt
1720435305
package com.byagowi.persiancalendar.ui.preferences.interfacecalendar import android.Manifest import android.content.pm.PackageManager import android.os.Bundle import androidx.core.app.ActivityCompat import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SwitchPreferenceCompat import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.ui.preferences.interfacecalendar.calendarsorder.CalendarPreferenceDialog import com.byagowi.persiancalendar.utils.askForCalendarPermission class InterfaceCalendarFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.preferences_interface_calendar) findPreference<ListPreference>("Theme")?.summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() findPreference<ListPreference>("WeekStart")?.summaryProvider = ListPreference.SimpleSummaryProvider.getInstance() val switchPreference = findPreference<SwitchPreferenceCompat>("showDeviceCalendarEvents") val activity = activity ?: return switchPreference?.setOnPreferenceChangeListener { _, _ -> if (ActivityCompat.checkSelfPermission( activity, Manifest.permission.READ_CALENDAR ) != PackageManager.PERMISSION_GRANTED ) { askForCalendarPermission(activity) switchPreference.isChecked = false } else { switchPreference.isChecked = !switchPreference.isChecked } false } } override fun onPreferenceTreeClick(preference: Preference?): Boolean = if (preference?.key == "calendars_priority") { parentFragmentManager.apply { CalendarPreferenceDialog().show(this, "CalendarPreferenceDialog") } true } else super.onPreferenceTreeClick(preference) }
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/preferences/interfacecalendar/InterfaceCalendarFragment.kt
494663082
package org.mifos.mobile.models.accounts.savings import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize import org.mifos.mobile.models.client.DepositType import java.util.ArrayList /** * @author Vishwajeet * @since 22/06/16 */ @Parcelize data class SavingsWithAssociations( @SerializedName("id") var id: Long? = null, @SerializedName("accountNo") var accountNo: String, @SerializedName("depositType") var depositType: DepositType? = null, @SerializedName("externalId") var externalId: String, @SerializedName("clientId") var clientId: Int? = null, @SerializedName("clientName") var clientName: String, @SerializedName("savingsProductId") var savingsProductId: Int? = null, @SerializedName("savingsProductName") var savingsProductName: String, @SerializedName("fieldOfficerId") var fieldOfficerId: Int? = null, @SerializedName("status") var status: Status, @SerializedName("timeline") var timeline: TimeLine, @SerializedName("currency") var currency: Currency, @SerializedName("nominalAnnualInterestRate") internal var nominalAnnualInterestRate: Double? = null, @SerializedName("minRequiredOpeningBalance") var minRequiredOpeningBalance: Double? = null, @SerializedName("lockinPeriodFrequency") var lockinPeriodFrequency: Double? = null, @SerializedName("withdrawalFeeForTransfers") var withdrawalFeeForTransfers: Boolean? = null, @SerializedName("allowOverdraft") var allowOverdraft: Boolean? = null, @SerializedName("enforceMinRequiredBalance") var enforceMinRequiredBalance: Boolean? = null, @SerializedName("withHoldTax") var withHoldTax: Boolean? = null, @SerializedName("lastActiveTransactionDate") var lastActiveTransactionDate: List<Int>, @SerializedName("isDormancyTrackingActive") var dormancyTrackingActive: Boolean? = null, @SerializedName("summary") var summary: Summary, @SerializedName("transactions") var transactions: List<Transactions> = ArrayList() ) : Parcelable { fun isRecurring() : Boolean { return this.depositType != null && this.depositType!!.isRecurring() } fun setNominalAnnualInterestRate(nominalAnnualInterestRate: Double?) { this.nominalAnnualInterestRate = nominalAnnualInterestRate } fun getNominalAnnualInterestRate(): Double { return nominalAnnualInterestRate!! } fun setNominalAnnualInterestRate(nominalAnnualInterestRate: Double) { this.nominalAnnualInterestRate = nominalAnnualInterestRate } }
app/src/main/java/org/mifos/mobile/models/accounts/savings/SavingsWithAssociations.kt
271745223
package com.hendraanggrian.openpss.api import com.hendraanggrian.openpss.data.Page import com.hendraanggrian.openpss.nosql.StringId import com.hendraanggrian.openpss.schema.Customer import com.hendraanggrian.openpss.schema.Customers import com.hendraanggrian.openpss.schema.Employee import io.ktor.client.request.get import io.ktor.client.request.post import io.ktor.http.HttpMethod interface CustomersApi : Api { suspend fun getCustomers(search: CharSequence, page: Int, count: Int): Page<Customer> = client.get { apiUrl(Customers.schemaName) parameters( "search" to search, "page" to page, "count" to count ) } suspend fun addCustomer(customer: Customer): Customer = client.post { apiUrl(Customers.schemaName) jsonBody(customer) } suspend fun getCustomer(id: StringId<*>): Customer = client.get { apiUrl("${Customers.schemaName}/$id") } suspend fun editCustomer(login: Employee, id: StringId<*>, customer: Customer): Boolean = client.requestStatus(HttpMethod.Put) { apiUrl("${Customers.schemaName}/$id") jsonBody(customer) parameters("login" to login.name) } suspend fun addContact(id: StringId<*>, contact: Customer.Contact): Customer.Contact = client.post { apiUrl("${Customers.schemaName}/$id/${Customers.Contacts.schemaName}") jsonBody(contact) } suspend fun deleteContact( login: Employee, id: StringId<*>, contact: Customer.Contact ): Boolean = client.requestStatus(HttpMethod.Delete) { apiUrl("${Customers.schemaName}/$id/${Customers.Contacts.schemaName}") jsonBody(contact) parameters("employee" to login.name) } }
openpss-client/src/com/hendraanggrian/openpss/api/CustomersApi.kt
3288065032
package cn.xiaoniaojun.secondhandtoy.mvvm.V.ui.activity import android.animation.ArgbEvaluator import android.animation.ValueAnimator import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Build import android.os.Bundle import android.os.Handler import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.support.v7.widget.CardView import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager import android.view.animation.Animation import android.view.animation.AnimationUtils import android.view.animation.Transformation import android.widget.EditText import android.widget.ImageView import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import cn.xiaoniaojun.secondhandtoy.R import it.sephiroth.android.library.easing.Back import it.sephiroth.android.library.easing.EasingManager class LoginActivity : AppCompatActivity() { private var rootLayout: ViewGroup? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_main_login) rootLayout = findViewById(R.id.main_container) as ViewGroup val email = findViewById(R.id.email) as EditText val password = findViewById(R.id.password) as EditText val emailS = findViewById(R.id.email_singup) as EditText val passwordS = findViewById(R.id.password_singup) as EditText val passwordC = findViewById(R.id.password_confirm) as EditText val tvLogin = findViewById(R.id.login_tv) as TextView tvLogin.setOnClickListener { val intent = Intent(this@LoginActivity, HomeActivity::class.java) startActivity(intent) finish() } // 为输入框聚焦事件设置动画 val focuslistene = View.OnFocusChangeListener { v, hasFocus -> if (hasFocus) { animateOnFocus(v) } else { animateOnFocusLost(v) } } email.onFocusChangeListener = focuslistene password.onFocusChangeListener = focuslistene emailS.onFocusChangeListener = focuslistene passwordS.onFocusChangeListener = focuslistene passwordC.onFocusChangeListener = focuslistene } fun showSingUp(view: View) { val animationCircle = findViewById(R.id.animation_circle) as CardView val animationFirstArist = findViewById(R.id.animation_first_arist) val animationSecondArist = findViewById(R.id.animation_second_arist) val animationSquare = findViewById(R.id.animation_square) val squareParent = animationSquare.parent as LinearLayout val animationTV = findViewById(R.id.animation_tv) as TextView val twitterImageView = findViewById(R.id.twitter_img) as ImageView val instagramImageView = findViewById(R.id.instagram_img) as ImageView val facebokImageView = findViewById(R.id.facebook_img) as ImageView val singupFormContainer = findViewById(R.id.signup_form_container) val loginFormContainer = findViewById(R.id.login_form_container) val backgroundColor = ContextCompat.getColor(this, R.color.colorPrimary) val singupTV = findViewById(R.id.singup_big_tv) as TextView val scale = resources.displayMetrics.density val circle_curr_margin = (82 * scale + 0.5f).toInt() val circle_target_margin = rootLayout!!.width - (70 * scale + 0.5f).toInt() val first_curr_width = (120 * scale + 0.5f).toInt() val first_target_width = (rootLayout!!.height * 1.3).toInt() val first_curr_height = (70 * scale + 0.5f).toInt() val first_target_height = rootLayout!!.width val first_curr_margin = (40 * scale + 0.5f).toInt() val first_target_margin = (35 * scale + 0.5f).toInt() val first_expand_margin = first_curr_margin - first_target_height val square_target_width = rootLayout!!.width val square_target_height = (80 * scale + 0.5f).toInt() val tv_curr_x = findViewById(R.id.singup_tv).x + findViewById(R.id.singup_button).x val tv_curr_y = findViewById(R.id.singup_tv).y + findViewById(R.id.buttons_container).y + findViewById(R.id.singup_container).y val tv_target_x = findViewById(R.id.singup_big_tv).x val tv_target_y = findViewById(R.id.singup_big_tv).y val tv_curr_size = 16f val tv_target_size = 56f val tv_curr_color = Color.parseColor("#ffffff") val tv_target_color = Color.parseColor("#ccffffff") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = ContextCompat.getColor(this, R.color.colorAccentDark) } squareParent.gravity = Gravity.END animationTV.setText(R.string.sign_up) val a = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { var diff_margin = circle_curr_margin - circle_target_margin var margin = circle_target_margin + (diff_margin - diff_margin * interpolatedTime).toInt() val params_circle = animationCircle.layoutParams as RelativeLayout.LayoutParams params_circle.setMargins(0, 0, margin, (40 * scale + 0.5f).toInt()) animationCircle.requestLayout() //---------------------------------------------------------- // 1号变换块 // 宽度变为高度 val diff_width = first_curr_width - first_target_width val width = first_target_width + (diff_width - diff_width * interpolatedTime).toInt() val diff_height = first_curr_height - first_target_height val height = first_target_height + (diff_height - (diff_height - first_target_margin) * interpolatedTime).toInt() diff_margin = first_curr_margin - first_expand_margin margin = first_expand_margin + (diff_margin - diff_margin * interpolatedTime).toInt() val margin_r = (-(first_target_width - rootLayout!!.width) * interpolatedTime).toInt() val params_first = animationFirstArist.layoutParams as RelativeLayout.LayoutParams params_first.setMargins(0, 0, margin_r, margin) params_first.width = width params_first.height = height animationFirstArist.requestLayout() animationFirstArist.pivotX = 0f animationFirstArist.pivotY = 0f animationFirstArist.rotation = -90 * interpolatedTime //----------------------------------------------------------- margin = first_curr_margin + (first_target_margin * interpolatedTime).toInt() val params_second = animationSecondArist.layoutParams as RelativeLayout.LayoutParams params_second.setMargins(0, 0, margin_r, margin) params_second.width = width animationSecondArist.requestLayout() animationSecondArist.pivotX = 0f animationSecondArist.pivotY = animationSecondArist.height.toFloat() animationSecondArist.rotation = 90 * interpolatedTime animationSquare.layoutParams.width = (square_target_width.toDouble() * interpolatedTime.toDouble() * 1.4).toInt() animationSquare.requestLayout() val diff_x = tv_curr_x - tv_target_x val x = tv_target_x + (diff_x - diff_x * interpolatedTime) val diff_y = tv_curr_y - tv_target_y val y = tv_target_y + (diff_y - diff_y * interpolatedTime) animationTV.x = x animationTV.y = y animationTV.requestLayout() // 变换社交图标颜色 if (interpolatedTime >= 0.2f && interpolatedTime < 0.3f) { twitterImageView.setImageResource(R.drawable.ic_qq_pink) } else if (interpolatedTime >= 0.45f && interpolatedTime < 0.55f) { instagramImageView.setImageResource(R.drawable.ic_wechat_pink) } else if (interpolatedTime >= 0.65f && interpolatedTime < 0.75f) { facebokImageView.setImageResource(R.drawable.ic_weibo_pink) } singupFormContainer.alpha = interpolatedTime loginFormContainer.alpha = 1 - interpolatedTime } override fun willChangeBounds(): Boolean { return true } } a.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(arg0: Animation) { findViewById(R.id.singup_container).visibility = View.INVISIBLE animationFirstArist.visibility = View.VISIBLE animationSecondArist.visibility = View.VISIBLE animationSquare.visibility = View.VISIBLE animationTV.visibility = View.VISIBLE singupFormContainer.visibility = View.VISIBLE animationFirstArist.bringToFront() squareParent.bringToFront() animationSecondArist.bringToFront() animationCircle.bringToFront() findViewById(R.id.buttons_container).bringToFront() singupFormContainer.bringToFront() singupTV.bringToFront() animationTV.bringToFront() animationFirstArist.setBackgroundColor(backgroundColor) animationSecondArist.setBackgroundColor(backgroundColor) animationCircle.setCardBackgroundColor(backgroundColor) animationSquare.setBackgroundColor(backgroundColor) } override fun onAnimationRepeat(arg0: Animation) {} override fun onAnimationEnd(arg0: Animation) { Handler().postDelayed({ animationFirstArist.visibility = View.GONE animationSecondArist.visibility = View.GONE animationTV.visibility = View.GONE animationSquare.visibility = View.GONE findViewById(R.id.singup_big_tv).visibility = View.VISIBLE }, 100) rootLayout!!.setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorPrimary)) (animationSquare.parent as View).setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorPrimary)) findViewById(R.id.login_form_container).visibility = View.GONE findViewById(R.id.login_tv).visibility = View.GONE showLoginButton() } }) val a2 = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { animationSquare.layoutParams.height = (square_target_height.toDouble() * interpolatedTime.toDouble() * 1.4).toInt() animationSquare.requestLayout() } override fun willChangeBounds(): Boolean { return true } } val a3 = ValueAnimator.ofFloat(tv_curr_size, tv_target_size) a3.addUpdateListener { animation -> val animatedValue = animation.animatedValue as Float animationTV.textSize = animatedValue } val a4 = ValueAnimator.ofInt(tv_curr_color, tv_target_color) a4.setEvaluator(ArgbEvaluator()) a4.addUpdateListener { animation -> val animatedValue = animation.animatedValue as Int animationTV.setTextColor(animatedValue) } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { val a5 = ValueAnimator.ofInt(Color.argb(255, 249, 164, 221), Color.argb(255, 19, 26, 86)) a5.setEvaluator(ArgbEvaluator()) a5.addUpdateListener { animation -> val animatedValue = animation.animatedValue as Int rootLayout!!.setBackgroundColor(animatedValue) (animationSquare.parent as View).setBackgroundColor(animatedValue) } a5.duration = 400 a5.start() } a.duration = 400 a2.duration = 172 a3.duration = 400 a4.duration = 400 a4.start() a3.start() animationSquare.startAnimation(a2) animationCircle.startAnimation(a) singupFormContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_form)) } fun showLogIn(view: View) { val animationCircle = findViewById(R.id.animation_circle) as CardView val animationFirstArist = findViewById(R.id.animation_first_arist) val animationSecondArist = findViewById(R.id.animation_second_arist) val animationSquare = findViewById(R.id.animation_square) val squareParent = animationSquare.parent as LinearLayout val animationTV = findViewById(R.id.animation_tv) as TextView val twitterImageView = findViewById(R.id.twitter_img) as ImageView val instagramImageView = findViewById(R.id.instagram_img) as ImageView val facebokImageView = findViewById(R.id.facebook_img) as ImageView val singupFormContainer = findViewById(R.id.signup_form_container) val loginFormContainer = findViewById(R.id.login_form_container) val loginTV = findViewById(R.id.login_tv) as TextView val backgrounColor = ContextCompat.getColor(this, R.color.colorAccent) val scale = resources.displayMetrics.density val circle_curr_margin = rootLayout!!.width - (view.width.toFloat() - view.x - animationCircle.width.toFloat()).toInt() val circle_target_margin = 0 val first_curr_width = (108 * scale + 0.5f).toInt() val first_target_width = rootLayout!!.height * 2 val first_curr_height = (70 * scale + 0.5f).toInt() val first_target_height = rootLayout!!.width val first_curr_margin = (40 * scale + 0.5f).toInt() val first_target_margin = (35 * scale + 0.5f).toInt() val first_expand_margin = first_curr_margin - first_target_height val first_curr_margin_r = rootLayout!!.width - first_curr_width val square_target_width = rootLayout!!.width val square_target_height = (80 * scale + 0.5f).toInt() val tv_curr_x = findViewById(R.id.login_small_tv).x + findViewById(R.id.login_button).x val tv_curr_y = findViewById(R.id.login_small_tv).y + findViewById(R.id.buttons_container).y + findViewById(R.id.login_container).y val tv_target_x = findViewById(R.id.login_tv).x val tv_target_y = findViewById(R.id.login_tv).y val tv_curr_size = 16f val tv_target_size = 56f val tv_curr_color = Color.parseColor("#ffffff") val tv_target_color = Color.parseColor("#ccffffff") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val window = window window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimaryDark) } squareParent.gravity = Gravity.START animationTV.setText(R.string.log_in) val a = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { var diff_margin = circle_curr_margin - circle_target_margin var margin = circle_target_margin + (diff_margin - diff_margin * interpolatedTime).toInt() val params_circle = animationCircle.layoutParams as RelativeLayout.LayoutParams params_circle.setMargins(0, 0, margin, (40 * scale + 0.5f).toInt()) animationCircle.requestLayout() val diff_width = first_curr_width - first_target_width val width = first_target_width + (diff_width - diff_width * interpolatedTime).toInt() val diff_height = first_curr_height - first_target_height val height = first_target_height + (diff_height - (diff_height - first_target_margin) * interpolatedTime).toInt() diff_margin = first_curr_margin - first_expand_margin margin = first_expand_margin + (diff_margin - diff_margin * interpolatedTime).toInt() val margin_r = first_curr_margin_r - (first_curr_margin_r * interpolatedTime).toInt() val margin_l = if (rootLayout!!.width - width < 0) rootLayout!!.width - width else 0 val params_first = animationFirstArist.layoutParams as RelativeLayout.LayoutParams params_first.setMargins(margin_l, 0, margin_r, margin) params_first.width = width params_first.height = height animationFirstArist.requestLayout() animationFirstArist.pivotX = animationFirstArist.width.toFloat() animationFirstArist.pivotY = 0f animationFirstArist.rotation = 90 * interpolatedTime margin = first_curr_margin + (first_target_margin * interpolatedTime).toInt() val params_second = animationSecondArist.layoutParams as RelativeLayout.LayoutParams params_second.setMargins(0, 0, margin_r, margin) params_second.width = width animationSecondArist.requestLayout() animationSecondArist.pivotX = animationSecondArist.width.toFloat() animationSecondArist.pivotY = animationSecondArist.height.toFloat() animationSecondArist.rotation = -(90 * interpolatedTime) animationSquare.layoutParams.width = (square_target_width * interpolatedTime).toInt() animationSquare.requestLayout() val diff_x = tv_curr_x - tv_target_x val x = tv_target_x + (diff_x - diff_x * interpolatedTime) val diff_y = tv_curr_y - tv_target_y val y = tv_target_y + (diff_y - diff_y * interpolatedTime) animationTV.x = x animationTV.y = y animationTV.requestLayout() if (interpolatedTime >= 0.2f && interpolatedTime < 0.3f) { facebokImageView.setImageResource(R.drawable.ic_qq_blue) } else if (interpolatedTime >= 0.45f && interpolatedTime < 0.55f) { instagramImageView.setImageResource(R.drawable.ic_wechat_blue) } else if (interpolatedTime >= 0.65f && interpolatedTime < 0.75f) { twitterImageView.setImageResource(R.drawable.ic_weibo_blue) } loginFormContainer.alpha = interpolatedTime singupFormContainer.alpha = 1 - interpolatedTime } override fun willChangeBounds(): Boolean { return true } } a.setAnimationListener(object : Animation.AnimationListener { override fun onAnimationStart(arg0: Animation) { animationFirstArist.setBackgroundColor(backgrounColor) animationSecondArist.setBackgroundColor(backgrounColor) animationSquare.setBackgroundColor(backgrounColor) animationFirstArist.visibility = View.VISIBLE findViewById(R.id.login_container).visibility = View.INVISIBLE animationSecondArist.visibility = View.VISIBLE animationSquare.visibility = View.VISIBLE animationTV.visibility = View.VISIBLE loginFormContainer.visibility = View.VISIBLE loginTV.visibility = View.INVISIBLE animationFirstArist.bringToFront() squareParent.bringToFront() animationSecondArist.bringToFront() animationCircle.bringToFront() findViewById(R.id.buttons_container).bringToFront() loginFormContainer.bringToFront() loginTV.bringToFront() animationTV.bringToFront() } override fun onAnimationRepeat(arg0: Animation) {} override fun onAnimationEnd(arg0: Animation) { Handler().postDelayed({ animationFirstArist.visibility = View.GONE animationSecondArist.visibility = View.GONE animationTV.visibility = View.GONE animationSquare.visibility = View.GONE findViewById(R.id.login_tv).visibility = View.VISIBLE findViewById(R.id.login_tv).bringToFront() }, 100) rootLayout!!.setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorAccent)) (animationSquare.parent as View).setBackgroundColor(ContextCompat.getColor(this@LoginActivity, R.color.colorAccent)) findViewById(R.id.signup_form_container).visibility = View.GONE findViewById(R.id.singup_big_tv).visibility = View.GONE showSignUpButton() } }) val a2 = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { animationSquare.layoutParams.height = (square_target_height * interpolatedTime).toInt() animationSquare.requestLayout() } override fun willChangeBounds(): Boolean { return true } } val a3 = ValueAnimator.ofFloat(tv_curr_size, tv_target_size) a3.addUpdateListener { animation -> val animatedValue = animation.animatedValue as Float animationTV.textSize = animatedValue } val a4 = ValueAnimator.ofInt(tv_curr_color, tv_target_color) a4.setEvaluator(ArgbEvaluator()) a4.addUpdateListener { animation -> val animatedValue = animation.animatedValue as Int animationTV.setTextColor(animatedValue) } if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) { val a5 = ValueAnimator.ofInt(Color.argb(255, 19, 26, 86), Color.argb(255, 249, 164, 221)) a5.setEvaluator(ArgbEvaluator()) a5.addUpdateListener { animation -> val animatedValue = animation.animatedValue as Int rootLayout!!.setBackgroundColor(animatedValue) (animationSquare.parent as View).setBackgroundColor(animatedValue) } a5.duration = 400 a5.start() } a.duration = 400 a2.duration = 172 a3.duration = 400 a4.duration = 400 a4.start() a3.start() animationSquare.startAnimation(a2) animationCircle.startAnimation(a) loginFormContainer.startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_form_reverse)) } private fun showLoginButton() { val singupButton = findViewById(R.id.singup_button) as CardView val loginButton = findViewById(R.id.login_button) loginButton.visibility = View.VISIBLE loginButton.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) findViewById(R.id.login_container).visibility = View.VISIBLE val scale = resources.displayMetrics.density val curr_singup_margin = (-35 * scale + 0.5f).toInt() val target_singup_margin = -singupButton.width val curr_login_margin = -loginButton.measuredWidth val target_login_margin = (-35 * scale + 0.5f).toInt() val manager = EasingManager(object : EasingManager.EasingCallback { override fun onEasingValueChanged(value: Double, oldValue: Double) { var diff_margin = curr_singup_margin - target_singup_margin var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt() var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(0, 0, margin, 0) singupButton.requestLayout() diff_margin = curr_login_margin - target_login_margin margin = target_login_margin + (diff_margin - diff_margin * value).toInt() layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams layoutParams.leftMargin = margin loginButton.requestLayout() } override fun onEasingStarted(value: Double) { var diff_margin = curr_singup_margin - target_singup_margin var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt() var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(0, 0, margin, 0) singupButton.requestLayout() diff_margin = curr_login_margin - target_login_margin margin = target_login_margin + (diff_margin - diff_margin * value).toInt() layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(margin, 0, 0, 0) loginButton.requestLayout() } override fun onEasingFinished(value: Double) { var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(0, 0, target_singup_margin, 0) singupButton.requestLayout() layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(target_login_margin, 0, 0, 0) loginButton.requestLayout() singupButton.visibility = View.GONE } }) manager.start(Back::class.java, EasingManager.EaseType.EaseOut, 0.0, 1.0, 600) } private fun showSignUpButton() { val singupButton = findViewById(R.id.singup_button) as CardView val loginButton = findViewById(R.id.login_button) singupButton.visibility = View.VISIBLE singupButton.measure(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT) findViewById(R.id.singup_container).visibility = View.VISIBLE val scale = resources.displayMetrics.density val curr_singup_margin = -singupButton.width val target_singup_margin = (-35 * scale + 0.5f).toInt() val curr_login_margin = (-35 * scale + 0.5f).toInt() val target_login_margin = -loginButton.measuredWidth val manager = EasingManager(object : EasingManager.EasingCallback { override fun onEasingValueChanged(value: Double, oldValue: Double) { var diff_margin = curr_singup_margin - target_singup_margin var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt() var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(0, 0, margin, 0) singupButton.requestLayout() diff_margin = curr_login_margin - target_login_margin margin = target_login_margin + (diff_margin - diff_margin * value).toInt() layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams layoutParams.leftMargin = margin loginButton.requestLayout() } override fun onEasingStarted(value: Double) { var diff_margin = curr_singup_margin - target_singup_margin var margin = target_singup_margin + (diff_margin - diff_margin * value).toInt() var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(0, 0, margin, 0) singupButton.requestLayout() diff_margin = curr_login_margin - target_login_margin margin = target_login_margin + (diff_margin - diff_margin * value).toInt() layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(margin, 0, 0, 0) loginButton.requestLayout() } override fun onEasingFinished(value: Double) { var layoutParams = singupButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(0, 0, target_singup_margin, 0) singupButton.requestLayout() layoutParams = loginButton.layoutParams as LinearLayout.LayoutParams layoutParams.setMargins(target_login_margin, 0, 0, 0) loginButton.requestLayout() loginButton.visibility = View.GONE } }) manager.start(Back::class.java, EasingManager.EaseType.EaseOut, 0.0, 1.0, 600) } private fun animateOnFocus(v: View) { val first_container = v.parent as CardView val second_container = first_container.parent as CardView val first_curr_radius = resources.getDimension(R.dimen.first_card_radius).toInt() val first_target_radius = resources.getDimension(R.dimen.first_card_radius_on_focus).toInt() val second_curr_radius = resources.getDimension(R.dimen.second_card_radius).toInt() val second_target_radius = resources.getDimension(R.dimen.second_card_radius_on_focus).toInt() val first_curr_color = ContextCompat.getColor(this, android.R.color.transparent) val first_target_color = (rootLayout!!.background as ColorDrawable).color val second_curr_color = ContextCompat.getColor(this, R.color.backgroundEditText) val second_target_color = ContextCompat.getColor(this, android.R.color.white) val first_anim = ValueAnimator() first_anim.setIntValues(first_curr_color, first_target_color) first_anim.setEvaluator(ArgbEvaluator()) first_anim.addUpdateListener { animation -> first_container.setCardBackgroundColor(animation.animatedValue as Int) } val second_anim = ValueAnimator() second_anim.setIntValues(second_curr_color, second_target_color) second_anim.setEvaluator(ArgbEvaluator()) second_anim.addUpdateListener { animation -> second_container.setCardBackgroundColor(animation.animatedValue as Int) } val a = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { var diff_radius = first_curr_radius - first_target_radius var radius = first_target_radius + (diff_radius * (1 - interpolatedTime)).toInt() first_container.radius = radius.toFloat() first_container.requestLayout() diff_radius = second_curr_radius - second_target_radius radius = second_target_radius + (diff_radius * (1 - interpolatedTime)).toInt() second_container.radius = radius.toFloat() second_container.requestLayout() } override fun willChangeBounds(): Boolean { return true } } a.duration = 200 first_anim.duration = 200 second_anim.duration = 200 first_anim.start() second_anim.start() first_container.startAnimation(a) } private fun animateOnFocusLost(v: View) { val first_container = v.parent as CardView val second_container = first_container.parent as CardView val first_curr_radius = resources.getDimension(R.dimen.first_card_radius_on_focus).toInt() val first_target_radius = resources.getDimension(R.dimen.first_card_radius).toInt() val second_curr_radius = resources.getDimension(R.dimen.second_card_radius_on_focus).toInt() val second_target_radius = resources.getDimension(R.dimen.second_card_radius).toInt() val first_curr_color = (rootLayout!!.background as ColorDrawable).color val first_target_color = ContextCompat.getColor(this, android.R.color.transparent) val second_curr_color = ContextCompat.getColor(this, android.R.color.white) val second_target_color = ContextCompat.getColor(this, R.color.backgroundEditText) val first_anim = ValueAnimator() first_anim.setIntValues(first_curr_color, first_target_color) first_anim.setEvaluator(ArgbEvaluator()) first_anim.addUpdateListener { animation -> first_container.setCardBackgroundColor(animation.animatedValue as Int) } val second_anim = ValueAnimator() second_anim.setIntValues(second_curr_color, second_target_color) second_anim.setEvaluator(ArgbEvaluator()) second_anim.addUpdateListener { animation -> second_container.setCardBackgroundColor(animation.animatedValue as Int) } val a = object : Animation() { override fun applyTransformation(interpolatedTime: Float, t: Transformation) { var diff_radius = first_curr_radius - first_target_radius var radius = first_target_radius + (diff_radius - diff_radius * interpolatedTime).toInt() first_container.radius = radius.toFloat() first_container.requestLayout() diff_radius = second_curr_radius - second_target_radius radius = second_target_radius + (diff_radius - diff_radius * interpolatedTime).toInt() second_container.radius = radius.toFloat() second_container.requestLayout() } override fun willChangeBounds(): Boolean { return true } } a.duration = 200 first_anim.duration = 200 second_anim.duration = 200 first_anim.start() second_anim.start() first_container.startAnimation(a) } }
app/src/main/java/cn/xiaoniaojun/secondhandtoy/mvvm/V/ui/activity/LoginActivity.kt
2723496564
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.type import org.lanternpowered.server.network.packet.Packet /** * Send between the client and server to keep the connection * alive and to determine the ping. * * @param time The time the message was sent */ data class KeepAlivePacket(val time: Long) : Packet
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/type/KeepAlivePacket.kt
1925088327
package org.brightify.reactant.core.util /** * @author <a href="mailto:[email protected]">Filip Dolnik</a> */ @Suppress("FunctionName") fun <T> Style(closure: T.() -> Unit): T.() -> Unit { return closure }
Core/src/main/kotlin/org/brightify/reactant/core/util/Style.kt
1187393008
/* * Copyright (C) 2018 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.entitymapper import android.database.Cursor import net.simonvt.cathode.common.data.MappedCursorLiveData import net.simonvt.cathode.common.database.getBoolean import net.simonvt.cathode.common.database.getFloat import net.simonvt.cathode.common.database.getInt import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.common.database.getStringOrNull import net.simonvt.cathode.entity.Season import net.simonvt.cathode.provider.DatabaseContract.SeasonColumns object SeasonMapper : MappedCursorLiveData.CursorMapper<Season> { override fun map(cursor: Cursor): Season? { return if (cursor.moveToFirst()) mapSeason(cursor) else null } fun mapSeason(cursor: Cursor): Season { val id = cursor.getLong(SeasonColumns.ID) val showId = cursor.getLong(SeasonColumns.SHOW_ID) val season = cursor.getInt(SeasonColumns.SEASON) val tvdbId = cursor.getInt(SeasonColumns.TVDB_ID) val tmdbId = cursor.getInt(SeasonColumns.TMDB_ID) val tvrageId = cursor.getLong(SeasonColumns.TVRAGE_ID) val userRating = cursor.getInt(SeasonColumns.USER_RATING) val ratedAt = cursor.getLong(SeasonColumns.RATED_AT) val rating = cursor.getFloat(SeasonColumns.RATING) val votes = cursor.getInt(SeasonColumns.VOTES) val hiddenWatched = cursor.getBoolean(SeasonColumns.HIDDEN_WATCHED) val hiddenCollected = cursor.getBoolean(SeasonColumns.HIDDEN_COLLECTED) val watchedCount = cursor.getInt(SeasonColumns.WATCHED_COUNT) val airdateCount = cursor.getInt(SeasonColumns.AIRDATE_COUNT) val inCollectionCount = cursor.getInt(SeasonColumns.IN_COLLECTION_COUNT) val inWatchlistCount = cursor.getInt(SeasonColumns.IN_WATCHLIST_COUNT) val showTitle = cursor.getStringOrNull(SeasonColumns.SHOW_TITLE) val airedCount = cursor.getInt(SeasonColumns.AIRED_COUNT) val unairedCount = cursor.getInt(SeasonColumns.UNAIRED_COUNT) val watchedAiredCount = cursor.getInt(SeasonColumns.WATCHED_AIRED_COUNT) val collectedAiredCount = cursor.getInt(SeasonColumns.COLLECTED_AIRED_COUNT) val episodeCount = cursor.getInt(SeasonColumns.EPISODE_COUNT) return Season( id, showId, season, tvdbId, tmdbId, tvrageId, userRating, ratedAt, rating, votes, hiddenWatched, hiddenCollected, watchedCount, airdateCount, inCollectionCount, inWatchlistCount, showTitle, airedCount, unairedCount, watchedAiredCount, collectedAiredCount, episodeCount ) } val projection = arrayOf( SeasonColumns.ID, SeasonColumns.SHOW_ID, SeasonColumns.SEASON, SeasonColumns.TVDB_ID, SeasonColumns.TMDB_ID, SeasonColumns.TVRAGE_ID, SeasonColumns.USER_RATING, SeasonColumns.RATED_AT, SeasonColumns.RATING, SeasonColumns.VOTES, SeasonColumns.HIDDEN_WATCHED, SeasonColumns.HIDDEN_COLLECTED, SeasonColumns.WATCHED_COUNT, SeasonColumns.AIRDATE_COUNT, SeasonColumns.IN_COLLECTION_COUNT, SeasonColumns.IN_WATCHLIST_COUNT, SeasonColumns.SHOW_TITLE, SeasonColumns.AIRED_COUNT, SeasonColumns.UNAIRED_COUNT, SeasonColumns.WATCHED_AIRED_COUNT, SeasonColumns.COLLECTED_AIRED_COUNT, SeasonColumns.EPISODE_COUNT ) }
cathode/src/main/java/net/simonvt/cathode/entitymapper/SeasonMapper.kt
967287940
// Copyright 2021 [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 avb.blob import avb.alg.Algorithms import cfig.helper.CryptoHelper import cfig.helper.Helper import cc.cfig.io.Struct import org.slf4j.LoggerFactory import java.nio.file.Files import java.nio.file.Paths import java.security.MessageDigest import java.security.PrivateKey data class AuthBlob( var offset: Long = 0, var size: Long = 0, var hash: String? = null, var signature: String? = null ) { companion object { fun calcHash( header_data_blob: ByteArray, aux_data_blob: ByteArray, algorithm_name: String ): ByteArray { val alg = Algorithms.get(algorithm_name)!! return if (alg.name == "NONE") { log.debug("calc hash: NONE") byteArrayOf() } else { MessageDigest.getInstance(CryptoHelper.Hasher.pyAlg2java(alg.hash_name)).apply { update(header_data_blob) update(aux_data_blob) }.digest().apply { log.debug("calc hash = " + Helper.toHexString(this)) } } } private fun calcSignature(hash: ByteArray, algorithm_name: String): ByteArray { val alg = Algorithms.get(algorithm_name)!! return if (alg.name == "NONE") { byteArrayOf() } else { val k = CryptoHelper.KeyBox.parse4(Files.readAllBytes(Paths.get(alg.defaultKey.replace(".pem", ".pk8")))) CryptoHelper.Signer.rawRsa(k.key as PrivateKey, Helper.join(alg.padding, hash)) } } fun createBlob( header_data_blob: ByteArray, aux_data_blob: ByteArray, algorithm_name: String ): ByteArray { val alg = Algorithms.get(algorithm_name)!! val authBlockSize = Helper.round_to_multiple((alg.hash_num_bytes + alg.signature_num_bytes).toLong(), 64) if (0L == authBlockSize) { log.info("No auth blob for algorithm " + alg.name) return byteArrayOf() } //hash & signature val binaryHash = calcHash(header_data_blob, aux_data_blob, algorithm_name) val binarySignature = calcSignature(binaryHash, algorithm_name) val authData = Helper.join(binaryHash, binarySignature) return Helper.join(authData, Struct("${authBlockSize - authData.size}x").pack(0)) } private val log = LoggerFactory.getLogger(AuthBlob::class.java) } }
bbootimg/src/main/kotlin/avb/blob/AuthBlob.kt
4046593046
package nl.hannahsten.texifyidea.intentions import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiFile import nl.hannahsten.texifyidea.psi.LatexDisplayMath import nl.hannahsten.texifyidea.psi.LatexInlineMath import nl.hannahsten.texifyidea.util.* import nl.hannahsten.texifyidea.util.files.isLatexFile /** * @author Hannah Schellekens */ open class LatexInlineDisplayToggle : TexifyIntentionBase("Toggle inline/display math mode") { override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { if (editor == null || file == null || !file.isLatexFile()) { return false } val element = file.findElementAt(editor.caretModel.offset) ?: return false return element.hasParent(LatexInlineMath::class) || element.hasParent(LatexDisplayMath::class) } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { if (editor == null || file == null || !file.isLatexFile()) { return } val element = file.findElementAt(editor.caretModel.offset) ?: return val inline = element.parentOfType(LatexInlineMath::class) if (inline != null) { applyForInlineMath(editor, inline) } else { applyForDisplayMath(editor, element.parentOfType(LatexDisplayMath::class) ?: return) } } private fun applyForInlineMath(editor: Editor, inline: LatexInlineMath) { val document = editor.document val indent = document.lineIndentationByOffset(inline.textOffset) val endLength = inline.inlineMathEnd?.textLength ?: 0 val text = inline.text.trimRange(inline.inlineMathStart.textLength, endLength).trim() runWriteAction { val extra = if (document.getText(TextRange.from(inline.endOffset(), 1)) == " ") { 1 } else 0 val result = "\n\\[\n $text\n\\]\n".replace("\n", "\n$indent") document.replaceString(inline.textOffset, inline.endOffset() + extra, result) editor.caretModel.moveToOffset(inline.textOffset + result.length) } } private fun applyForDisplayMath(editor: Editor, display: LatexDisplayMath) { val document = editor.document val indent = document.lineIndentationByOffset(display.textOffset) val whitespace = indent.length + 1 val text = display.text.trimRange(2, 2).trim() runWriteAction { val leading = if (document.getText(TextRange.from(display.textOffset - whitespace - 1, 1)) != " ") " " else "" val trailing = if (document.getText(TextRange.from(display.endOffset() + whitespace, 1)) != " ") " " else "" val result = "$leading${'$'}$text${'$'}$trailing" .replace("\n", " ") .replace(Regex("\\s+"), " ") document.replaceString(display.textOffset - whitespace, display.endOffset() + whitespace, result) } } }
src/nl/hannahsten/texifyidea/intentions/LatexInlineDisplayToggle.kt
2154680483
package nl.hannahsten.texifyidea.inspections.latex.probablebugs import nl.hannahsten.texifyidea.file.LatexFileType import nl.hannahsten.texifyidea.inspections.TexifyInspectionTestBase import nl.hannahsten.texifyidea.testutils.writeCommand class LatexRequiredExtensionInspectionTest : TexifyInspectionTestBase(LatexRequiredExtensionInspection()) { fun testWarning() { myFixture.configureByText( LatexFileType, """ \addbibresource{<error descr="File argument should include the extension">test</error>} """.trimIndent() ) myFixture.checkHighlighting() } fun testNoWarning() { myFixture.configureByText( LatexFileType, """ \addbibresource{test.bib} """.trimIndent() ) myFixture.checkHighlighting() } fun testQuickfix() { myFixture.configureByText( LatexFileType, """ \addbibresource{test} """.trimIndent() ) val quickFixes = myFixture.getAllQuickFixes() assertEquals(1, quickFixes.size) writeCommand(myFixture.project) { quickFixes.first().invoke(myFixture.project, myFixture.editor, myFixture.file) } myFixture.checkResult( """ \addbibresource{test.bib} """.trimIndent() ) } }
test/nl/hannahsten/texifyidea/inspections/latex/probablebugs/LatexRequiredExtensionInspectionTest.kt
3378391869
package com.duopoints.android.fragments.points import android.net.Uri import com.duopoints.android.fragments.points.models.GivePointsEventDetails import com.duopoints.android.rest.models.points.PointType import com.duopoints.android.rest.models.points.PointTypeCategory interface GivePointsListener { fun pointUpdated(selectedCategory: PointTypeCategory?, pointType: PointType) fun mediaUpdated(mediaUris: List<Uri>?) fun eventDetailsUpdated(eventDetails: GivePointsEventDetails?) }
app/src/main/java/com/duopoints/android/fragments/points/GivePointsListener.kt
3746923108
package cases @Suppress("unused") class TooManyFunctions { fun f1() { println() } fun f2() { println() } fun f3() { println() } fun f4() { println() } fun f5() { println() } fun f6() { println() } fun f7() { println() } fun f8() { println() } fun f9() { println() } fun f10() { println() } fun f11() { println() } fun f12() { println() } fun f13() { println() } fun f14() { println() } fun f15() { println() } fun f16() { println() } }
detekt-rules/src/test/resources/cases/TooManyFunctions.kt
1921363740
package io.gitlab.arturbosch.detekt.api import org.jetbrains.kotlin.psi.KtFile @Suppress("EmptyFunctionBlock") abstract class BaseRule(protected val context: Context = DefaultContext()) : DetektVisitor(), Context by context { open val id: String = javaClass.simpleName /** * Before starting visiting kotlin elements, a check is performed if this rule should be triggered. * Pre- and post-visit-hooks are executed before/after the visiting process. */ fun visitFile(root: KtFile) { if (visitCondition(root)) { clearFindings() preVisit(root) visit(root) postVisit(root) } } open fun visit(root: KtFile) { root.accept(this) } abstract fun visitCondition(root: KtFile): Boolean /** * Could be overridden by subclasses to specify a behaviour which should be done before * visiting kotlin elements. */ protected open fun postVisit(root: KtFile) { } /** * Could be overridden by subclasses to specify a behaviour which should be done after * visiting kotlin elements. */ protected open fun preVisit(root: KtFile) { } }
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/BaseRule.kt
1532752879
package voice.common.compose import androidx.compose.runtime.Immutable import java.io.File @Immutable data class ImmutableFile(val file: File)
common/src/main/kotlin/voice/common/compose/ImmutableFile.kt
2522060595
package bob.clean.domain.manager import bob.clean.domain.interactor.UseCase import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import io.reactivex.Scheduler import io.reactivex.schedulers.Schedulers import org.junit.Before import org.junit.Test import java.util.concurrent.TimeUnit import kotlin.test.assertTrue class AsyncUseCaseImplTest { val param = "params" val result = "result" val useCase = mock<UseCase<String, String>>() val scheduler: Scheduler = Schedulers.trampoline() val asyncUseCase = AsyncUseCaseImpl(scheduler, useCase) @Before fun setup() { whenever(useCase.execute(param)).thenReturn(result) } @Test fun testDelegation() { asyncUseCase.execute(param) verify(useCase).execute(param) } @Test fun testAsync() { val observer = TestObserver() asyncUseCase.asyncExecute(param, observer) val testObserver = observer.testObserver testObserver.awaitDone(5, TimeUnit.SECONDS) testObserver.assertNoTimeout() verify(useCase).execute(param) testObserver.assertValue(result) testObserver.assertComplete() } @Test fun testDispose() { val observer = TestObserver() asyncUseCase.asyncExecute(param, observer) observer.testObserver.awaitDone(5, TimeUnit.SECONDS).assertNoTimeout() asyncUseCase.dispose() assertTrue(observer.isDisposed) } }
domain/src/test/kotlin/bob/clean/domain/manager/AsyncUseCaseImplTest.kt
653903330
package io.aconite.client import io.aconite.Request import io.aconite.Response /** * Accepts request and transform it into response. * Can some how use inner acceptor to process request. */ interface ClientRequestAcceptor { companion object { operator fun invoke(accept: suspend (url: String, request: Request) -> Response) = object: ClientRequestAcceptor { override suspend fun accept(url: String, request: Request) = accept(url, request) } } interface Factory<out C> { fun create(inner: ClientRequestAcceptor, configurator: C.() -> Unit): ClientRequestAcceptor } suspend fun accept(url: String, request: Request): Response }
aconite-client/src/io/aconite/client/ClientRequestAcceptor.kt
3018026662
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.mlkit.md import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.OnCanceledListener import com.google.android.gms.tasks.OnCompleteListener import com.google.android.gms.tasks.OnFailureListener import com.google.android.gms.tasks.OnSuccessListener import java.util.concurrent.Executor /** * Quality-of-life helper to allow using trailing lambda syntax for adding a success listener to a * [Task]. */ fun <TResult> Task<TResult>.addOnSuccessListener(executor: Executor, listener: (TResult) -> Unit): Task<TResult> { return addOnSuccessListener(executor, OnSuccessListener(listener)) } /** * Quality-of-life helper to allow using trailing lambda syntax for adding a failure listener to a * [Task]. */ fun <TResult> Task<TResult>.addOnFailureListener(executor: Executor, listener: (Exception) -> Unit): Task<TResult> { return addOnFailureListener(executor, OnFailureListener(listener)) } /** * Quality-of-life helper to allow using trailing lambda syntax for adding a completion listener to * a [Task]. */ fun <TResult> Task<TResult>.addOnCompleteListener(executor: Executor, listener: (Task<TResult>) -> Unit): Task<TResult> { return addOnCompleteListener(executor, OnCompleteListener(listener)) } /** * Quality-of-life helper to allow using trailing lambda syntax for adding a cancellation listener * to a [Task]. */ fun <TResult> Task<TResult>.addOnCanceledListener(executor: Executor, listener: () -> Unit): Task<TResult> { return addOnCanceledListener(executor, OnCanceledListener(listener)) }
android/material-showcase/app/src/main/java/com/google/mlkit/md/TaskExt.kt
2485938839
package com.github.salomonbrys.kotson import com.google.gson.JsonArray import com.google.gson.JsonElement import com.google.gson.JsonObject import java.math.BigDecimal import java.math.BigInteger import java.util.* import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty operator fun JsonObject.getValue(thisRef: Any?, property: KProperty<*>): JsonElement = obj[property.name] operator fun JsonObject.setValue(thisRef: Any?, property: KProperty<*>, value: JsonElement) { obj[property.name] = value } class JsonObjectDelegate<T : Any>(private val _obj: JsonObject, private val _get: (JsonElement) -> T, private val _set: (T) -> JsonElement, private val _key: String? = null, private val _default: (() -> T)? = null) : ReadWriteProperty<Any?, T> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): T { val element = _obj[_key ?: property.name] if(element === null) { val default = _default if (default === null) throw NoSuchElementException("'$_key' not found") else return default.invoke() } return _get(element) } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { _obj[_key ?: property.name] = _set(value) } } class NullableJsonObjectDelegate<T: Any?>(private val _obj: JsonObject, private val _get: (JsonElement) -> T?, private val _set: (T?) -> JsonElement, private val _key: String? = null, private val _default: (() -> T)? = null) : ReadWriteProperty<Any?, T?> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): T? { val element = _obj[_key ?: property.name] if (element === null) return _default?.invoke() return _get(element) } override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T?) { _obj[_key ?: property.name] = _set(value) } } class JsonArrayDelegate<T: Any>(private val _array: JsonArray, private val _index: Int, private val _get: (JsonElement) -> T, private val _set: (T) -> JsonElement) : ReadWriteProperty<Any?, T> { override operator fun getValue(thisRef: Any?, property: KProperty<*>): T = _get(_array[_index]) override operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { _array[_index] = _set(value) } } val JsonElement.byString : JsonObjectDelegate<String> get() = JsonObjectDelegate(this.obj, { it.string }, { it.toJson() } ) val JsonElement.byBool : JsonObjectDelegate<Boolean> get() = JsonObjectDelegate(this.obj, { it.bool }, { it.toJson() } ) val JsonElement.byByte : JsonObjectDelegate<Byte> get() = JsonObjectDelegate(this.obj, { it.byte }, { it.toJson() } ) val JsonElement.byChar : JsonObjectDelegate<Char> get() = JsonObjectDelegate(this.obj, { it.char }, { it.toJson() } ) val JsonElement.byShort : JsonObjectDelegate<Short> get() = JsonObjectDelegate(this.obj, { it.short }, { it.toJson() } ) val JsonElement.byInt : JsonObjectDelegate<Int> get() = JsonObjectDelegate(this.obj, { it.int }, { it.toJson() } ) val JsonElement.byLong : JsonObjectDelegate<Long> get() = JsonObjectDelegate(this.obj, { it.long }, { it.toJson() } ) val JsonElement.byFloat : JsonObjectDelegate<Float> get() = JsonObjectDelegate(this.obj, { it.float }, { it.toJson() } ) val JsonElement.byDouble : JsonObjectDelegate<Double> get() = JsonObjectDelegate(this.obj, { it.double }, { it.toJson() } ) val JsonElement.byNumber : JsonObjectDelegate<Number> get() = JsonObjectDelegate(this.obj, { it.number }, { it.toJson() } ) val JsonElement.byBigInteger : JsonObjectDelegate<BigInteger> get() = JsonObjectDelegate(this.obj, { it.bigInteger }, { it.toJson() } ) val JsonElement.byBigDecimal : JsonObjectDelegate<BigDecimal> get() = JsonObjectDelegate(this.obj, { it.bigDecimal }, { it.toJson() } ) val JsonElement.byArray : JsonObjectDelegate<JsonArray> get() = JsonObjectDelegate(this.obj, { it.array }, { it } ) val JsonElement.byObject : JsonObjectDelegate<JsonObject> get() = JsonObjectDelegate(this.obj, { it.obj }, { it } ) fun JsonElement.byString ( key: String? = null, default: ( () -> String )? = null ) : JsonObjectDelegate<String> = JsonObjectDelegate(this.obj, { it.string }, { it.toJson() }, key, default ) fun JsonElement.byBool ( key: String? = null, default: ( () -> Boolean )? = null ) : JsonObjectDelegate<Boolean> = JsonObjectDelegate(this.obj, { it.bool }, { it.toJson() }, key, default ) fun JsonElement.byByte ( key: String? = null, default: ( () -> Byte )? = null ) : JsonObjectDelegate<Byte> = JsonObjectDelegate(this.obj, { it.byte }, { it.toJson() }, key, default ) fun JsonElement.byChar ( key: String? = null, default: ( () -> Char )? = null ) : JsonObjectDelegate<Char> = JsonObjectDelegate(this.obj, { it.char }, { it.toJson() }, key, default ) fun JsonElement.byShort ( key: String? = null, default: ( () -> Short )? = null ) : JsonObjectDelegate<Short> = JsonObjectDelegate(this.obj, { it.short }, { it.toJson() }, key, default ) fun JsonElement.byInt ( key: String? = null, default: ( () -> Int )? = null ) : JsonObjectDelegate<Int> = JsonObjectDelegate(this.obj, { it.int }, { it.toJson() }, key, default ) fun JsonElement.byLong ( key: String? = null, default: ( () -> Long )? = null ) : JsonObjectDelegate<Long> = JsonObjectDelegate(this.obj, { it.long }, { it.toJson() }, key, default ) fun JsonElement.byFloat ( key: String? = null, default: ( () -> Float )? = null ) : JsonObjectDelegate<Float> = JsonObjectDelegate(this.obj, { it.float }, { it.toJson() }, key, default ) fun JsonElement.byDouble ( key: String? = null, default: ( () -> Double )? = null ) : JsonObjectDelegate<Double> = JsonObjectDelegate(this.obj, { it.double }, { it.toJson() }, key, default ) fun JsonElement.byNumber ( key: String? = null, default: ( () -> Number )? = null ) : JsonObjectDelegate<Number> = JsonObjectDelegate(this.obj, { it.number }, { it.toJson() }, key, default ) fun JsonElement.byBigInteger ( key: String? = null, default: ( () -> BigInteger )? = null ) : JsonObjectDelegate<BigInteger> = JsonObjectDelegate(this.obj, { it.bigInteger }, { it.toJson() }, key, default ) fun JsonElement.byBigDecimal ( key: String? = null, default: ( () -> BigDecimal )? = null ) : JsonObjectDelegate<BigDecimal> = JsonObjectDelegate(this.obj, { it.bigDecimal }, { it.toJson() }, key, default ) fun JsonElement.byArray ( key: String? = null, default: ( () -> JsonArray )? = null ) : JsonObjectDelegate<JsonArray> = JsonObjectDelegate(this.obj, { it.array }, { it }, key, default ) fun JsonElement.byObject ( key: String? = null, default: ( () -> JsonObject )? = null ) : JsonObjectDelegate<JsonObject> = JsonObjectDelegate(this.obj, { it.obj }, { it }, key, default ) val JsonElement.byNullableString : NullableJsonObjectDelegate<String?> get() = NullableJsonObjectDelegate(this.obj, { it.string }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableBool : NullableJsonObjectDelegate<Boolean?> get() = NullableJsonObjectDelegate(this.obj, { it.bool }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableByte : NullableJsonObjectDelegate<Byte?> get() = NullableJsonObjectDelegate(this.obj, { it.byte }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableChar : NullableJsonObjectDelegate<Char?> get() = NullableJsonObjectDelegate(this.obj, { it.char }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableShort : NullableJsonObjectDelegate<Short?> get() = NullableJsonObjectDelegate(this.obj, { it.short }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableInt : NullableJsonObjectDelegate<Int?> get() = NullableJsonObjectDelegate(this.obj, { it.int }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableLong : NullableJsonObjectDelegate<Long?> get() = NullableJsonObjectDelegate(this.obj, { it.long }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableFloat : NullableJsonObjectDelegate<Float?> get() = NullableJsonObjectDelegate(this.obj, { it.float }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableDouble : NullableJsonObjectDelegate<Double?> get() = NullableJsonObjectDelegate(this.obj, { it.double }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableNumber : NullableJsonObjectDelegate<Number?> get() = NullableJsonObjectDelegate(this.obj, { it.number }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableBigInteger : NullableJsonObjectDelegate<BigInteger?> get() = NullableJsonObjectDelegate(this.obj, { it.bigInteger }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableBigDecimal : NullableJsonObjectDelegate<BigDecimal?> get() = NullableJsonObjectDelegate(this.obj, { it.bigDecimal }, { it?.toJson() ?: jsonNull } ) val JsonElement.byNullableArray : NullableJsonObjectDelegate<JsonArray?> get() = NullableJsonObjectDelegate(this.obj, { it.array }, { it ?: jsonNull } ) val JsonElement.byNullableObject : NullableJsonObjectDelegate<JsonObject?> get() = NullableJsonObjectDelegate(this.obj, { it.obj }, { it ?: jsonNull } ) fun JsonElement.byNullableString (key: String? = null, default: ( () -> String )? = null) : NullableJsonObjectDelegate<String?> = NullableJsonObjectDelegate(this.obj, { it.string }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableBool (key: String? = null, default: ( () -> Boolean )? = null) : NullableJsonObjectDelegate<Boolean?> = NullableJsonObjectDelegate(this.obj, { it.bool }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableByte (key: String? = null, default: ( () -> Byte )? = null) : NullableJsonObjectDelegate<Byte?> = NullableJsonObjectDelegate(this.obj, { it.byte }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableChar (key: String? = null, default: ( () -> Char )? = null) : NullableJsonObjectDelegate<Char?> = NullableJsonObjectDelegate(this.obj, { it.char }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableShort (key: String? = null, default: ( () -> Short )? = null) : NullableJsonObjectDelegate<Short?> = NullableJsonObjectDelegate(this.obj, { it.short }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableInt (key: String? = null, default: ( () -> Int )? = null) : NullableJsonObjectDelegate<Int?> = NullableJsonObjectDelegate(this.obj, { it.int }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableLong (key: String? = null, default: ( () -> Long )? = null) : NullableJsonObjectDelegate<Long?> = NullableJsonObjectDelegate(this.obj, { it.long }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableFloat (key: String? = null, default: ( () -> Float )? = null) : NullableJsonObjectDelegate<Float?> = NullableJsonObjectDelegate(this.obj, { it.float }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableDouble (key: String? = null, default: ( () -> Double )? = null) : NullableJsonObjectDelegate<Double?> = NullableJsonObjectDelegate(this.obj, { it.double }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableNumber (key: String? = null, default: ( () -> Number )? = null) : NullableJsonObjectDelegate<Number?> = NullableJsonObjectDelegate(this.obj, { it.number }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableBigInteger (key: String? = null, default: ( () -> BigInteger )? = null) : NullableJsonObjectDelegate<BigInteger?> = NullableJsonObjectDelegate(this.obj, { it.bigInteger }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableBigDecimal (key: String? = null, default: ( () -> BigDecimal )? = null) : NullableJsonObjectDelegate<BigDecimal?> = NullableJsonObjectDelegate(this.obj, { it.bigDecimal }, { it?.toJson() ?: jsonNull }, key, default ) fun JsonElement.byNullableArray (key: String? = null, default: ( () -> JsonArray )? = null) : NullableJsonObjectDelegate<JsonArray?> = NullableJsonObjectDelegate(this.obj, { it.array }, { it ?: jsonNull }, key, default ) fun JsonElement.byNullableObject (key: String? = null, default: ( () -> JsonObject )? = null) : NullableJsonObjectDelegate<JsonObject?> = NullableJsonObjectDelegate(this.obj, { it.obj }, { it ?: jsonNull }, key, default ) fun JsonElement.byString (index: Int) : JsonArrayDelegate<String> = JsonArrayDelegate(this.array, index, { it.string }, { it.toJson() } ) fun JsonElement.byBool (index: Int) : JsonArrayDelegate<Boolean> = JsonArrayDelegate(this.array, index, { it.bool }, { it.toJson() } ) fun JsonElement.byByte (index: Int) : JsonArrayDelegate<Byte> = JsonArrayDelegate(this.array, index, { it.byte }, { it.toJson() } ) fun JsonElement.byChar (index: Int) : JsonArrayDelegate<Char> = JsonArrayDelegate(this.array, index, { it.char }, { it.toJson() } ) fun JsonElement.byShort (index: Int) : JsonArrayDelegate<Short> = JsonArrayDelegate(this.array, index, { it.short }, { it.toJson() } ) fun JsonElement.byInt (index: Int) : JsonArrayDelegate<Int> = JsonArrayDelegate(this.array, index, { it.int }, { it.toJson() } ) fun JsonElement.byLong (index: Int) : JsonArrayDelegate<Long> = JsonArrayDelegate(this.array, index, { it.long }, { it.toJson() } ) fun JsonElement.byFloat (index: Int) : JsonArrayDelegate<Float> = JsonArrayDelegate(this.array, index, { it.float }, { it.toJson() } ) fun JsonElement.byDouble (index: Int) : JsonArrayDelegate<Double> = JsonArrayDelegate(this.array, index, { it.double }, { it.toJson() } ) fun JsonElement.byNumber (index: Int) : JsonArrayDelegate<Number> = JsonArrayDelegate(this.array, index, { it.number }, { it.toJson() } ) fun JsonElement.byBigInteger (index: Int) : JsonArrayDelegate<BigInteger> = JsonArrayDelegate(this.array, index, { it.bigInteger }, { it.toJson() } ) fun JsonElement.byBigDecimal (index: Int) : JsonArrayDelegate<BigDecimal> = JsonArrayDelegate(this.array, index, { it.bigDecimal }, { it.toJson() } ) fun JsonElement.byArray (index: Int) : JsonArrayDelegate<JsonArray> = JsonArrayDelegate(this.array, index, { it.array }, { it } ) fun JsonElement.byObject (index: Int) : JsonArrayDelegate<JsonObject> = JsonArrayDelegate(this.array, index, { it.obj }, { it } )
src/main/kotlin/com/github/salomonbrys/kotson/Properties.kt
1107911211
package org.videolan.vlc.util import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ExtensionsTests { @Test fun getResolutionClass() { Assert.assertEquals("720p", generateResolutionClass(1280, 536)) Assert.assertEquals("720p", generateResolutionClass(1280, 720)) Assert.assertEquals("SD", generateResolutionClass(848, 480)) Assert.assertEquals("4K", generateResolutionClass(3840, 2160)) Assert.assertEquals("SD", generateResolutionClass(640, 352)) Assert.assertEquals("1080p", generateResolutionClass(1920, 1080)) Assert.assertEquals("SD", generateResolutionClass(480, 272)) Assert.assertEquals("SD", generateResolutionClass(720, 576)) Assert.assertEquals("1080p", generateResolutionClass(2048, 1024)) Assert.assertEquals("SD", generateResolutionClass(712, 480)) Assert.assertEquals("SD", generateResolutionClass(716, 480)) } }
application/vlc-android/test/org/videolan/vlc/util/UtilTests.kt
1011108669
package de.thm.arsnova.service.authservice.handler import de.thm.arsnova.service.authservice.model.RoomAccess import de.thm.arsnova.service.authservice.model.RoomAccessEntry import de.thm.arsnova.service.authservice.model.RoomAccessSyncTracker import de.thm.arsnova.service.authservice.model.command.RequestRoomAccessSyncCommand import de.thm.arsnova.service.authservice.model.command.SyncRoomAccessCommand import de.thm.arsnova.service.authservice.model.event.RoomAccessSyncRequest import de.thm.arsnova.service.authservice.persistence.RoomAccessRepository import de.thm.arsnova.service.authservice.persistence.RoomAccessSyncTrackerRepository import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.ArgumentCaptor import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.junit.jupiter.MockitoExtension import org.springframework.amqp.rabbit.core.RabbitTemplate import java.util.Optional @ExtendWith(MockitoExtension::class) class RoomAccessHandlerTest { @Mock private lateinit var rabbitTemplate: RabbitTemplate @Mock private lateinit var roomAccessRepository: RoomAccessRepository @Mock private lateinit var roomAccessSyncTrackerRepository: RoomAccessSyncTrackerRepository private lateinit var roomAccessHandler: RoomAccessHandler val SOME_ROOM_ID = "23e7c082c533e49963b96d7a0500105f" val SOME_REV = "1-93b09a4699769e6abd3bf5b2ff341e5d" val SOME_NEWER_REV = "2-93b09a4699769e6abd3bf5b2ff341e5e" val SOME_EVEN_NEWER_REV = "3-93b09a4699769e6abd3bf5b2ff341e5f" val SOME_USER_ID = "23e7c082c533e49963b96d7a05000d0e" val SOME_OTHER_USER_ID = "aaaac082c533e49963b96d7a05000d0f" val SOME_MODERATOR_ID = "bbbbc082c533e49963b96d7a05000d0f" val CREATOR_STRING = "CREATOR" val EXECUTIVE_MODERATOR_STRING = "EXECUTIVE_MODERATOR" @BeforeEach fun setUp() { roomAccessHandler = RoomAccessHandler(rabbitTemplate, roomAccessRepository, roomAccessSyncTrackerRepository) } @Test fun testStartSyncOnCommand() { val command = RequestRoomAccessSyncCommand( SOME_ROOM_ID, 2 ) val expected = RoomAccessSyncRequest( SOME_ROOM_ID ) Mockito.`when`(roomAccessSyncTrackerRepository.findById(command.roomId)) .thenReturn( Optional.of( RoomAccessSyncTracker( SOME_ROOM_ID, SOME_REV ) ) ) val keyCaptor = ArgumentCaptor.forClass(String::class.java) val eventCaptor = ArgumentCaptor.forClass(RoomAccessSyncRequest::class.java) roomAccessHandler.handleRequestRoomAccessSyncCommand(command) verify(rabbitTemplate, times(1)) .convertAndSend(keyCaptor.capture(), eventCaptor.capture()) assertEquals(keyCaptor.value, "backend.event.room.access.sync.request") assertEquals(eventCaptor.value, expected) } @Test fun testHandleSyncRoomAccessCommand() { val command = SyncRoomAccessCommand( SOME_NEWER_REV, SOME_ROOM_ID, listOf( RoomAccessEntry(SOME_OTHER_USER_ID, CREATOR_STRING) ) ) val expectedDelete = RoomAccess( SOME_ROOM_ID, SOME_USER_ID, SOME_REV, CREATOR_STRING, null, null ) val expectedCreate = RoomAccess( SOME_ROOM_ID, SOME_OTHER_USER_ID, SOME_NEWER_REV, CREATOR_STRING, null, null ) val expectedTracker = RoomAccessSyncTracker( SOME_ROOM_ID, SOME_NEWER_REV ) Mockito.`when`(roomAccessSyncTrackerRepository.findById(command.roomId)) .thenReturn( Optional.of( RoomAccessSyncTracker( SOME_ROOM_ID, SOME_REV ) ) ) Mockito.`when`(roomAccessSyncTrackerRepository.save(expectedTracker)) .thenReturn(expectedTracker) Mockito.`when`(roomAccessRepository.findByRoomId(command.roomId)) .thenReturn( listOf( // Do not delete this one RoomAccess( SOME_ROOM_ID, SOME_MODERATOR_ID, SOME_EVEN_NEWER_REV, EXECUTIVE_MODERATOR_STRING, null, null ), // This is old and should get deleted expectedDelete ) ) roomAccessHandler.handleSyncRoomAccessCommand(command) verify(roomAccessRepository, times(1)).deleteAll(listOf(expectedDelete)) verify(roomAccessRepository, times(1)).saveAll(listOf(expectedCreate)) verify(roomAccessSyncTrackerRepository, times(1)).save(expectedTracker) } @Test fun testDoNotUpdateOnOldInfo() { val command = SyncRoomAccessCommand( SOME_REV, SOME_ROOM_ID, listOf( RoomAccessEntry(SOME_USER_ID, CREATOR_STRING) ) ) val trackerCaptor = ArgumentCaptor.forClass(RoomAccessSyncTracker::class.java) verify(roomAccessSyncTrackerRepository, times(0)).save(trackerCaptor.capture()) } }
authz/src/test/kotlin/de/thm/arsnova/service/authservice/handler/RoomAccessHandlerTest.kt
450824670
package com.ternaryop.photoshelf.core.prefs import android.content.SharedPreferences const val PREF_PHOTOSHELF_APIKEY = "photoshelfApikey" val SharedPreferences.photoShelfApikey: String get() = getString(PREF_PHOTOSHELF_APIKEY, null) ?: ""
core/src/main/java/com/ternaryop/photoshelf/core/prefs/ApikeyPrefsExt.kt
1450982092
package io.gitlab.arturbosch.detekt.rules.style import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.api.SplitPattern import io.gitlab.arturbosch.detekt.api.config import io.gitlab.arturbosch.detekt.api.internal.ActiveByDefault import io.gitlab.arturbosch.detekt.api.internal.Configuration import io.gitlab.arturbosch.detekt.rules.parentsOfTypeUntil import io.gitlab.arturbosch.detekt.rules.yieldStatementsSkippingGuardClauses import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtNameReferenceExpression import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtReturnExpression import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getParentOfType /** * Restrict the number of return methods allowed in methods. * * Having many exit points in a function can be confusing and impacts readability of the * code. * * <noncompliant> * fun foo(i: Int): String { * when (i) { * 1 -> return "one" * 2 -> return "two" * else -> return "other" * } * } * </noncompliant> * * <compliant> * fun foo(i: Int): String { * return when (i) { * 1 -> "one" * 2 -> "two" * else -> "other" * } * } * </compliant> */ @ActiveByDefault(since = "1.0.0") class ReturnCount(config: Config = Config.empty) : Rule(config) { override val issue = Issue( javaClass.simpleName, Severity.Style, "Restrict the number of return statements in methods.", Debt.TEN_MINS ) @Configuration("define the maximum number of return statements allowed per function") private val max: Int by config(2) @Configuration("define functions to be ignored by this check") private val excludedFunctions: SplitPattern by config("equals") { SplitPattern(it) } @Configuration("if labeled return statements should be ignored") private val excludeLabeled: Boolean by config(false) @Configuration("if labeled return from a lambda should be ignored") private val excludeReturnFromLambda: Boolean by config(true) @Configuration("if true guard clauses at the beginning of a method should be ignored") private val excludeGuardClauses: Boolean by config(false) override fun visitNamedFunction(function: KtNamedFunction) { super.visitNamedFunction(function) if (!shouldBeIgnored(function)) { val numberOfReturns = countReturnStatements(function) if (numberOfReturns > max) { report( CodeSmell( issue, Entity.atName(function), "Function ${function.name} has $numberOfReturns return statements " + "which exceeds the limit of $max." ) ) } } } private fun shouldBeIgnored(function: KtNamedFunction) = excludedFunctions.contains(function.name) private fun countReturnStatements(function: KtNamedFunction): Int { fun KtReturnExpression.isExcluded(): Boolean = when { excludeLabeled && labeledExpression != null -> true excludeReturnFromLambda && isNamedReturnFromLambda() -> true else -> false } val statements = if (excludeGuardClauses) { function.yieldStatementsSkippingGuardClauses<KtReturnExpression>() } else { function.bodyBlockExpression?.statements?.asSequence().orEmpty() } return statements.flatMap { it.collectDescendantsOfType<KtReturnExpression>().asSequence() } .filterNot { it.isExcluded() } .count { it.getParentOfType<KtNamedFunction>(true) == function } } private fun KtReturnExpression.isNamedReturnFromLambda(): Boolean { val label = this.labeledExpression if (label != null) { return this.parentsOfTypeUntil<KtCallExpression, KtNamedFunction>() .map { it.calleeExpression } .filterIsInstance<KtNameReferenceExpression>() .map { it.text } .any { it in label.text } } return false } }
detekt-rules-style/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/style/ReturnCount.kt
4025841860
package cz.vhromada.catalog.rest import cz.vhromada.common.account.AccountConfiguration import cz.vhromada.common.account.service.AccountService import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Import import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.crypto.password.PasswordEncoder /** * A class represents Spring configuration for security. * * @author Vladimir Hromada */ @Configuration @EnableWebSecurity @Import(AccountConfiguration::class) class CatalogSecurityConfiguration : WebSecurityConfigurerAdapter() { @Autowired private lateinit var service: AccountService @Autowired private lateinit var encoder: PasswordEncoder override fun configure(auth: AuthenticationManagerBuilder) { auth.userDetailsService(service).passwordEncoder(encoder) } override fun configure(http: HttpSecurity) { http.authorizeRequests() .anyRequest().hasAnyRole("ADMIN", "USER") http.httpBasic() http.csrf().disable() } }
src/main/kotlin/cz/vhromada/catalog/rest/CatalogSecurityConfiguration.kt
1960628134