repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
myunusov/maxur-mserv | maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/service/jackson/ObjectMapperProvider.kt | 1 | 1554 | package org.maxur.mserv.frame.service.jackson
import com.fasterxml.jackson.annotation.JsonAutoDetect
import com.fasterxml.jackson.annotation.PropertyAccessor
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule
import com.fasterxml.jackson.module.paranamer.ParanamerModule
import dk.nykredit.jackson.dataformat.hal.JacksonHALModule
/**
* Factory for [ObjectMapper] instance.
*
* @author Maxim Yunusov
* @version 1.0
* @since <pre>26.08.2017</pre>
*/
object ObjectMapperProvider {
/** Instance of [ObjectMapper]. */
@JvmStatic
val objectMapper = config(jacksonObjectMapper())
/** Configure [ObjectMapper] instance */
fun config(mapper: ObjectMapper): ObjectMapper = mapper.apply { configuration() }
private fun ObjectMapper.configuration() {
setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE)
setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
registerModule(Jdk8Module())
registerModule(ParanamerModule())
registerModule(JavaTimeModule())
registerModule(JacksonHALModule())
registerModule(ParameterNamesModule())
}
}
| apache-2.0 |
DuckDeck/AndroidDemo | app/src/main/java/stan/androiddemo/project/petal/Module/UserInfo/PetalUserLikeFragment.kt | 1 | 7082 | package stan.androiddemo.project.petal.Module.UserInfo
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.StaggeredGridLayoutManager
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import com.chad.library.adapter.base.BaseViewHolder
import com.facebook.drawee.view.SimpleDraweeView
import org.greenrobot.eventbus.EventBus
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.UI.BasePetalRecyclerFragment
import stan.androiddemo.project.petal.API.ListPinsBean
import stan.androiddemo.project.petal.API.UserAPI
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnPinsFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.PinsMainInfo
import stan.androiddemo.tool.CompatUtils
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
/**
* A simple [Fragment] subclass.
*/
class PetalUserLikeFragment : BasePetalRecyclerFragment<PinsMainInfo>() {
private var isMe: Boolean = false
var mLimit = Config.LIMIT
var maxId = 0
private var mListener: OnPinsFragmentInteractionListener? = null
override fun getTheTAG(): String { return this.toString() }
companion object {
fun newInstance(key:String):PetalUserLikeFragment{
val fragment = PetalUserLikeFragment()
val bundle = Bundle()
bundle.putString("key",key)
fragment.arguments = bundle
return fragment
}
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (context is OnPinsFragmentInteractionListener){
mListener = context
}
if (context is PetalUserInfoActivity){
isMe = context.isMe
}
}
override fun getLayoutManager(): RecyclerView.LayoutManager {
return StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
}
override fun getItemLayoutId(): Int {
return R.layout.petal_cardview_image_item
}
override fun itemLayoutConvert(helper: BaseViewHolder, t: PinsMainInfo) {
val img = helper.getView<SimpleDraweeView>(R.id.img_card_main)
val txtGather = helper.getView<TextView>(R.id.txt_card_gather)
var txtLike = helper.getView<TextView>(R.id.txt_card_like)
val linearlayoutTitleInfo = helper.getView<LinearLayout>(R.id.linearLayout_image_title_info)
//只能在这里设置TextView的drawable了
txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_favorite_black_18dp,R.color.tint_list_grey),null,null,null)
txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_camera_black_18dp,R.color.tint_list_grey),null,null,null)
val imgUrl = String.format(mUrlGeneralFormat,t.file!!.key)
img.aspectRatio = t.imgRatio
helper.getView<FrameLayout>(R.id.frame_layout_card_image).setOnClickListener {
EventBus.getDefault().postSticky(t)
mListener?.onClickPinsItemImage(t,it)
}
linearlayoutTitleInfo.setOnClickListener {
EventBus.getDefault().postSticky(t)
mListener?.onClickPinsItemText(t,it)
}
txtGather.setOnClickListener {
//不做like操作了,
t.repin_count ++
txtGather.text = t.repin_count.toString()
txtGather.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_favorite_black_18dp,R.color.tint_list_pink),null,null,null)
}
txtLike.setOnClickListener {
//不做like操作了,
t.like_count ++
helper.setText(R.id.txt_card_like,t.like_count.toString())
txtLike.setCompoundDrawablesRelativeWithIntrinsicBounds(CompatUtils.getTintListDrawable(context,
R.drawable.ic_camera_black_18dp,R.color.tint_list_pink),null,null,null)
}
if (t.raw_text.isNullOrEmpty() && t.like_count <= 0 && t.repin_count <= 0){
linearlayoutTitleInfo.visibility = View.GONE
}
else{
linearlayoutTitleInfo.visibility = View.VISIBLE
if (!t.raw_text.isNullOrEmpty()){
helper.getView<TextView>(R.id.txt_card_title).text = t.raw_text!!
helper.getView<TextView>(R.id.txt_card_title).visibility = View.VISIBLE
}
else{
helper.getView<TextView>(R.id.txt_card_title).visibility = View.GONE
}
helper.setText(R.id.txt_card_gather,t.repin_count.toString())
helper.setText(R.id.txt_card_like,t.like_count.toString())
}
var imgType = t.file?.type
if (!imgType.isNullOrEmpty()){
if (imgType!!.toLowerCase().contains("gif") ) {
helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.VISIBLE
}
else{
helper.getView<ImageButton>(R.id.imgbtn_card_gif).visibility = View.INVISIBLE
}
}
ImageLoadBuilder.Start(context,img,imgUrl).setProgressBarImage(progressLoading).build()
}
override fun requestListData(page: Int): Subscription {
val request = RetrofitClient.createService(UserAPI::class.java)
var result : Observable<ListPinsBean>
if (page == 0){
result = request.httpsUserLikePinsRx(mAuthorization!!,mKey,mLimit)
}
else{
result = request.httpsUserLikePinsMaxRx(mAuthorization!!,mKey,maxId, mLimit)
}
return result.map { it.pins }.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object: Subscriber<List<PinsMainInfo>>(){
override fun onCompleted() {
}
override fun onError(e: Throwable?) {
e?.printStackTrace()
loadError()
checkException(e)
}
override fun onNext(t: List<PinsMainInfo>?) {
if (t == null){
loadError()
return
}
if( t!!.size > 0 ){
maxId = t!!.last()!!.pin_id
}
loadSuccess(t!!)
if (t!!.size < mLimit){
setNoMoreData()
}
}
})
}
}
| mit |
sksamuel/ktest | kotest-assertions/kotest-assertions-core/src/commonMain/kotlin/io/kotest/matchers/collections/decreasing.kt | 1 | 6138 | package io.kotest.matchers.collections
import io.kotest.assertions.show.show
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
fun <T : Comparable<T>> Iterable<T>.shouldBeMonotonicallyDecreasing(): Iterable<T> {
toList().shouldBeMonotonicallyDecreasing()
return this
}
fun <T : Comparable<T>> Array<T>.shouldBeMonotonicallyDecreasing(): Array<T> {
asList().shouldBeMonotonicallyDecreasing()
return this
}
fun <T : Comparable<T>> List<T>.shouldBeMonotonicallyDecreasing(): List<T> {
this should beMonotonicallyDecreasing()
return this
}
fun <T : Comparable<T>> Iterable<T>.shouldNotBeMonotonicallyDecreasing(): Iterable<T> {
toList().shouldNotBeMonotonicallyDecreasing()
return this
}
fun <T : Comparable<T>> Array<T>.shouldNotBeMonotonicallyDecreasing(): Array<T> {
asList().shouldNotBeMonotonicallyDecreasing()
return this
}
fun <T : Comparable<T>> List<T>.shouldNotBeMonotonicallyDecreasing(): List<T> {
this shouldNot beMonotonicallyDecreasing<T>()
return this
}
fun <T> List<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): List<T> {
this should beMonotonicallyDecreasingWith(comparator)
return this
}
fun <T> Iterable<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Iterable<T> {
toList().shouldBeMonotonicallyDecreasingWith(comparator)
return this
}
fun <T> Array<T>.shouldBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Array<T> {
asList().shouldBeMonotonicallyDecreasingWith(comparator)
return this
}
fun <T> List<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): List<T> {
this shouldNot beMonotonicallyDecreasingWith(comparator)
return this
}
fun <T> Iterable<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Iterable<T> {
toList().shouldNotBeMonotonicallyDecreasingWith(comparator)
return this
}
fun <T> Array<T>.shouldNotBeMonotonicallyDecreasingWith(comparator: Comparator<in T>): Array<T> {
asList().shouldNotBeMonotonicallyDecreasingWith(comparator)
return this
}
fun <T : Comparable<T>> Iterable<T>.shouldBeStrictlyDecreasing() = toList().shouldBeStrictlyDecreasing()
fun <T : Comparable<T>> List<T>.shouldBeStrictlyDecreasing() = this should beStrictlyDecreasing<T>()
fun <T : Comparable<T>> Iterable<T>.shouldNotBeStrictlyDecreasing() = toList().shouldNotBeStrictlyDecreasing()
fun <T : Comparable<T>> List<T>.shouldNotBeStrictlyDecreasing() = this shouldNot beStrictlyDecreasing<T>()
fun <T> List<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) =
this should beStrictlyDecreasingWith(comparator)
fun <T> Iterable<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>) =
toList().shouldBeStrictlyDecreasingWith(comparator)
fun <T> Array<T>.shouldBeStrictlyDecreasingWith(comparator: Comparator<in T>): Array<T> {
asList().shouldBeStrictlyDecreasingWith(comparator)
return this
}
fun <T> List<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) =
this shouldNot beStrictlyDecreasingWith(comparator)
fun <T> Iterable<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) =
toList().shouldNotBeStrictlyDecreasingWith(comparator)
fun <T> Array<T>.shouldNotBeStrictlyDecreasingWith(comparator: Comparator<in T>) =
asList().shouldNotBeStrictlyDecreasingWith(comparator)
fun <T : Comparable<T>> beMonotonicallyDecreasing(): Matcher<List<T>> = monotonicallyDecreasing()
fun <T : Comparable<T>> monotonicallyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> {
override fun test(value: List<T>): MatcherResult {
return testMonotonicallyDecreasingWith(value) { a, b -> a.compareTo(b) }
}
}
fun <T> beMonotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> =
monotonicallyDecreasingWith(comparator)
fun <T> monotonicallyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {
override fun test(value: List<T>): MatcherResult {
return testMonotonicallyDecreasingWith(value, comparator)
}
}
private fun <T> testMonotonicallyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {
val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) < 0 }
val snippet = value.show().value
val elementMessage = when (failure) {
null -> ""
else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not monotonically decreased from previous element."
}
return MatcherResult(
failure == null,
{ "List [$snippet] should be monotonically decreasing$elementMessage" },
{ "List [$snippet] should not be monotonically decreasing" }
)
}
fun <T : Comparable<T>> beStrictlyDecreasing(): Matcher<List<T>> = strictlyDecreasing()
fun <T : Comparable<T>> strictlyDecreasing(): Matcher<List<T>> = object : Matcher<List<T>> {
override fun test(value: List<T>): MatcherResult {
return testStrictlyDecreasingWith(value) { a, b -> a.compareTo(b) }
}
}
fun <T> beStrictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> =
strictlyDecreasingWith(comparator)
fun <T> strictlyDecreasingWith(comparator: Comparator<in T>): Matcher<List<T>> = object : Matcher<List<T>> {
override fun test(value: List<T>): MatcherResult {
return testStrictlyDecreasingWith(value, comparator)
}
}
private fun <T> testStrictlyDecreasingWith(value: List<T>, comparator: Comparator<in T>): MatcherResult {
val failure = value.zipWithNext().withIndex().find { (_, pair) -> comparator.compare(pair.first, pair.second) <= 0 }
val snippet = value.show().value
val elementMessage = when (failure) {
null -> ""
else -> ". Element ${failure.value.second} at index ${failure.index + 1} was not strictly decreased from previous element."
}
return MatcherResult(
failure == null,
{ "List [$snippet] should be strictly decreasing$elementMessage" },
{ "List [$snippet] should not be strictly decreasing" }
)
}
| mit |
kirimin/mitsumine | app/src/main/java/me/kirimin/mitsumine/feed/FeedUseCase.kt | 1 | 2531 | package me.kirimin.mitsumine.feed
import android.content.Context
import android.preference.PreferenceManager
import me.kirimin.mitsumine.R
import me.kirimin.mitsumine._common.database.FeedDAO
import me.kirimin.mitsumine._common.database.NGWordDAO
import me.kirimin.mitsumine._common.domain.model.Feed
import me.kirimin.mitsumine._common.domain.enums.Category
import me.kirimin.mitsumine._common.domain.enums.Type
import me.kirimin.mitsumine._common.network.repository.BookmarkCountRepository
import me.kirimin.mitsumine._common.network.repository.EntryRepository
import me.kirimin.mitsumine._common.network.repository.FeedRepository
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import javax.inject.Inject
class FeedUseCase @Inject
constructor(val context: Context,
val feedRepository: FeedRepository,
val entryRepository: EntryRepository,
val bookmarkCountRepository: BookmarkCountRepository) {
val isUseBrowserSettingEnable: Boolean
get() = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_use_browser_to_comment_list), false)
val isShareWithTitleSettingEnable: Boolean
get() = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_is_share_with_title), false)
val ngWordList: List<String>
get() = NGWordDAO.findAll()
var isFirstBoot
get() = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.key_is_first_boot), true)
set(value) = PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(context.getString(R.string.key_is_first_boot), value).apply()
fun requestMainFeed(category: Category, type: Type) = feedRepository.requestFeed(category, type)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())!!
fun requestKeywordFeed(keyword: String) = feedRepository.requestKeywordFeed(keyword)
fun requestUserFeed(user: String) = feedRepository.requestUserFeed(user)
fun requestReadFeed() = feedRepository.requestReadFeed()
fun requestReadLatterFeed() = feedRepository.requestReadLatterFeed()
fun requestTagList(url: String) = entryRepository.requestEntryInfo(url).map { it.tagListString }!!
fun requestBookmarkCount(url: String) = bookmarkCountRepository.requestBookmarkCount(url)
fun saveFeed(feed: Feed) {
FeedDAO.save(feed)
}
} | apache-2.0 |
aosp-mirror/platform_frameworks_support | room/compiler/src/main/kotlin/androidx/room/processor/ProcessorErrors.kt | 1 | 26729 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.RawQuery
import androidx.room.Update
import androidx.room.ext.RoomTypeNames
import androidx.room.ext.SupportDbTypeNames
import androidx.room.parser.SQLTypeAffinity
import androidx.room.vo.CustomTypeConverter
import androidx.room.vo.Field
import com.squareup.javapoet.TypeName
object ProcessorErrors {
private fun String.trim(): String {
return this.trimIndent().replace("\n", " ")
}
val MISSING_QUERY_ANNOTATION = "Query methods must be annotated with ${Query::class.java}"
val MISSING_INSERT_ANNOTATION = "Insertion methods must be annotated with ${Insert::class.java}"
val MISSING_DELETE_ANNOTATION = "Deletion methods must be annotated with ${Delete::class.java}"
val MISSING_UPDATE_ANNOTATION = "Update methods must be annotated with ${Update::class.java}"
val MISSING_RAWQUERY_ANNOTATION = "RawQuery methods must be annotated with" +
" ${RawQuery::class.java}"
val INVALID_ON_CONFLICT_VALUE = "On conflict value must be one of @OnConflictStrategy values."
val INVALID_INSERTION_METHOD_RETURN_TYPE = "Methods annotated with @Insert can return either" +
" void, long, Long, long[], Long[] or List<Long>."
val TRANSACTION_REFERENCE_DOCS = "https://developer.android.com/reference/android/arch/" +
"persistence/room/Transaction.html"
fun insertionMethodReturnTypeMismatch(definedReturn: TypeName,
expectedReturnTypes: List<TypeName>): String {
return "Method returns $definedReturn but it should return one of the following: `" +
expectedReturnTypes.joinToString(", ") + "`. If you want to return the list of" +
" row ids from the query, your insertion method can receive only 1 parameter."
}
val ABSTRACT_METHOD_IN_DAO_MISSING_ANY_ANNOTATION = "Abstract method in DAO must be annotated" +
" with ${Query::class.java} AND ${Insert::class.java}"
val INVALID_ANNOTATION_COUNT_IN_DAO_METHOD = "An abstract DAO method must be" +
" annotated with one and only one of the following annotations: " +
DaoProcessor.PROCESSED_ANNOTATIONS.joinToString(",") {
it.java.simpleName
}
val CANNOT_RESOLVE_RETURN_TYPE = "Cannot resolve return type for %s"
val CANNOT_USE_UNBOUND_GENERICS_IN_QUERY_METHODS = "Cannot use unbound generics in query" +
" methods. It must be bound to a type through base Dao class."
val CANNOT_USE_UNBOUND_GENERICS_IN_INSERTION_METHODS = "Cannot use unbound generics in" +
" insertion methods. It must be bound to a type through base Dao class."
val CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS = "Cannot use unbound fields in entities."
val CANNOT_USE_UNBOUND_GENERICS_IN_DAO_CLASSES = "Cannot use unbound generics in Dao classes." +
" If you are trying to create a base DAO, create a normal class, extend it with type" +
" params then mark the subclass with @Dao."
val CANNOT_FIND_GETTER_FOR_FIELD = "Cannot find getter for field."
val CANNOT_FIND_SETTER_FOR_FIELD = "Cannot find setter for field."
val MISSING_PRIMARY_KEY = "An entity must have at least 1 field annotated with @PrimaryKey"
val AUTO_INCREMENTED_PRIMARY_KEY_IS_NOT_INT = "If a primary key is annotated with" +
" autoGenerate, its type must be int, Integer, long or Long."
val AUTO_INCREMENT_EMBEDDED_HAS_MULTIPLE_FIELDS = "When @PrimaryKey annotation is used on a" +
" field annotated with @Embedded, the embedded class should have only 1 field."
fun multiplePrimaryKeyAnnotations(primaryKeys: List<String>): String {
return """
You cannot have multiple primary keys defined in an Entity. If you
want to declare a composite primary key, you should use @Entity#primaryKeys and
not use @PrimaryKey. Defined Primary Keys:
${primaryKeys.joinToString(", ")}""".trim()
}
fun primaryKeyColumnDoesNotExist(columnName: String, allColumns: List<String>): String {
return "$columnName referenced in the primary key does not exists in the Entity." +
" Available column names:${allColumns.joinToString(", ")}"
}
val DAO_MUST_BE_AN_ABSTRACT_CLASS_OR_AN_INTERFACE = "Dao class must be an abstract class or" +
" an interface"
val DATABASE_MUST_BE_ANNOTATED_WITH_DATABASE = "Database must be annotated with @Database"
val DAO_MUST_BE_ANNOTATED_WITH_DAO = "Dao class must be annotated with @Dao"
fun daoMustHaveMatchingConstructor(daoName: String, dbName: String): String {
return """
$daoName needs to have either an empty constructor or a constructor that takes
$dbName as its only parameter.
""".trim()
}
val ENTITY_MUST_BE_ANNOTATED_WITH_ENTITY = "Entity class must be annotated with @Entity"
val DATABASE_ANNOTATION_MUST_HAVE_LIST_OF_ENTITIES = "@Database annotation must specify list" +
" of entities"
val COLUMN_NAME_CANNOT_BE_EMPTY = "Column name cannot be blank. If you don't want to set it" +
", just remove the @ColumnInfo annotation or use @ColumnInfo.INHERIT_FIELD_NAME."
val ENTITY_TABLE_NAME_CANNOT_BE_EMPTY = "Entity table name cannot be blank. If you don't want" +
" to set it, just remove the tableName property."
val CANNOT_BIND_QUERY_PARAMETER_INTO_STMT = "Query method parameters should either be a" +
" type that can be converted into a database column or a List / Array that contains" +
" such type. You can consider adding a Type Adapter for this."
val QUERY_PARAMETERS_CANNOT_START_WITH_UNDERSCORE = "Query/Insert method parameters cannot " +
"start with underscore (_)."
val CANNOT_FIND_QUERY_RESULT_ADAPTER = "Not sure how to convert a Cursor to this method's " +
"return type"
val INSERTION_DOES_NOT_HAVE_ANY_PARAMETERS_TO_INSERT = "Method annotated with" +
" @Insert but does not have any parameters to insert."
val DELETION_MISSING_PARAMS = "Method annotated with" +
" @Delete but does not have any parameters to delete."
val UPDATE_MISSING_PARAMS = "Method annotated with" +
" @Update but does not have any parameters to update."
val TRANSACTION_METHOD_MODIFIERS = "Method annotated with @Transaction must not be " +
"private, final, or abstract. It can be abstract only if the method is also" +
" annotated with @Query."
val TRANSACTION_MISSING_ON_RELATION = "The return value includes a Pojo with a @Relation." +
" It is usually desired to annotate this method with @Transaction to avoid" +
" possibility of inconsistent results between the Pojo and its relations. See " +
TRANSACTION_REFERENCE_DOCS + " for details."
val CANNOT_FIND_ENTITY_FOR_SHORTCUT_QUERY_PARAMETER = "Type of the parameter must be a class " +
"annotated with @Entity or a collection/array of it."
val DB_MUST_EXTEND_ROOM_DB = "Classes annotated with @Database should extend " +
RoomTypeNames.ROOM_DB
val LIVE_DATA_QUERY_WITHOUT_SELECT = "LiveData return type can only be used with SELECT" +
" queries."
val OBSERVABLE_QUERY_NOTHING_TO_OBSERVE = "Observable query return type (LiveData, Flowable" +
", DataSource, DataSourceFactory etc) can only be used with SELECT queries that" +
" directly or indirectly (via @Relation, for example) access at least one table. For" +
" @RawQuery, you should specify the list of tables to be observed via the" +
" observedEntities field."
val RECURSIVE_REFERENCE_DETECTED = "Recursive referencing through @Embedded and/or @Relation " +
"detected: %s"
private val TOO_MANY_MATCHING_GETTERS = "Ambiguous getter for %s. All of the following " +
"match: %s. You can @Ignore the ones that you don't want to match."
fun tooManyMatchingGetters(field: Field, methodNames: List<String>): String {
return TOO_MANY_MATCHING_GETTERS.format(field, methodNames.joinToString(", "))
}
private val TOO_MANY_MATCHING_SETTERS = "Ambiguous setter for %s. All of the following " +
"match: %s. You can @Ignore the ones that you don't want to match."
fun tooManyMatchingSetter(field: Field, methodNames: List<String>): String {
return TOO_MANY_MATCHING_SETTERS.format(field, methodNames.joinToString(", "))
}
val CANNOT_FIND_COLUMN_TYPE_ADAPTER = "Cannot figure out how to save this field into" +
" database. You can consider adding a type converter for it."
val CANNOT_FIND_STMT_BINDER = "Cannot figure out how to bind this field into a statement."
val CANNOT_FIND_CURSOR_READER = "Cannot figure out how to read this field from a cursor."
private val MISSING_PARAMETER_FOR_BIND = "Each bind variable in the query must have a" +
" matching method parameter. Cannot find method parameters for %s."
fun missingParameterForBindVariable(bindVarName: List<String>): String {
return MISSING_PARAMETER_FOR_BIND.format(bindVarName.joinToString(", "))
}
private val UNUSED_QUERY_METHOD_PARAMETER = "Unused parameter%s: %s"
fun unusedQueryMethodParameter(unusedParams: List<String>): String {
return UNUSED_QUERY_METHOD_PARAMETER.format(
if (unusedParams.size > 1) "s" else "",
unusedParams.joinToString(","))
}
private val DUPLICATE_TABLES = "Table name \"%s\" is used by multiple entities: %s"
fun duplicateTableNames(tableName: String, entityNames: List<String>): String {
return DUPLICATE_TABLES.format(tableName, entityNames.joinToString(", "))
}
val DELETION_METHODS_MUST_RETURN_VOID_OR_INT = "Deletion methods must either return void or" +
" return int (the number of deleted rows)."
val UPDATE_METHODS_MUST_RETURN_VOID_OR_INT = "Update methods must either return void or" +
" return int (the number of updated rows)."
val DAO_METHOD_CONFLICTS_WITH_OTHERS = "Dao method has conflicts."
fun duplicateDao(dao: TypeName, methodNames: List<String>): String {
return """
All of these functions [${methodNames.joinToString(", ")}] return the same DAO
class [$dao].
A database can use a DAO only once so you should remove ${methodNames.size - 1} of
these conflicting DAO methods. If you are implementing any of these to fulfill an
interface, don't make it abstract, instead, implement the code that calls the
other one.
""".trim()
}
fun pojoMissingNonNull(pojoTypeName: TypeName, missingPojoFields: List<String>,
allQueryColumns: List<String>): String {
return """
The columns returned by the query does not have the fields
[${missingPojoFields.joinToString(",")}] in $pojoTypeName even though they are
annotated as non-null or primitive.
Columns returned by the query: [${allQueryColumns.joinToString(",")}]
""".trim()
}
fun cursorPojoMismatch(pojoTypeName: TypeName,
unusedColumns: List<String>, allColumns: List<String>,
unusedFields: List<Field>, allFields: List<Field>): String {
val unusedColumnsWarning = if (unusedColumns.isNotEmpty()) {
"""
The query returns some columns [${unusedColumns.joinToString(", ")}] which are not
use by $pojoTypeName. You can use @ColumnInfo annotation on the fields to specify
the mapping.
""".trim()
} else {
""
}
val unusedFieldsWarning = if (unusedFields.isNotEmpty()) {
"""
$pojoTypeName has some fields
[${unusedFields.joinToString(", ") { it.columnName }}] which are not returned by the
query. If they are not supposed to be read from the result, you can mark them with
@Ignore annotation.
""".trim()
} else {
""
}
return """
$unusedColumnsWarning
$unusedFieldsWarning
You can suppress this warning by annotating the method with
@SuppressWarnings(RoomWarnings.CURSOR_MISMATCH).
Columns returned by the query: ${allColumns.joinToString(", ")}.
Fields in $pojoTypeName: ${allFields.joinToString(", ") { it.columnName }}.
""".trim()
}
val TYPE_CONVERTER_UNBOUND_GENERIC = "Cannot use unbound generics in Type Converters."
val TYPE_CONVERTER_BAD_RETURN_TYPE = "Invalid return type for a type converter."
val TYPE_CONVERTER_MUST_RECEIVE_1_PARAM = "Type converters must receive 1 parameter."
val TYPE_CONVERTER_EMPTY_CLASS = "Class is referenced as a converter but it does not have any" +
" converter methods."
val TYPE_CONVERTER_MISSING_NOARG_CONSTRUCTOR = "Classes that are used as TypeConverters must" +
" have no-argument public constructors."
val TYPE_CONVERTER_MUST_BE_PUBLIC = "Type converters must be public."
fun duplicateTypeConverters(converters: List<CustomTypeConverter>): String {
return "Multiple methods define the same conversion. Conflicts with these:" +
" ${converters.joinToString(", ") { it.toString() }}"
}
// TODO must print field paths.
val POJO_FIELD_HAS_DUPLICATE_COLUMN_NAME = "Field has non-unique column name."
fun pojoDuplicateFieldNames(columnName: String, fieldPaths: List<String>): String {
return "Multiple fields have the same columnName: $columnName." +
" Field names: ${fieldPaths.joinToString(", ")}."
}
fun embeddedPrimaryKeyIsDropped(entityQName: String, fieldName: String): String {
return "Primary key constraint on $fieldName is ignored when being merged into " +
entityQName
}
val INDEX_COLUMNS_CANNOT_BE_EMPTY = "List of columns in an index cannot be empty"
fun indexColumnDoesNotExist(columnName: String, allColumns: List<String>): String {
return "$columnName referenced in the index does not exists in the Entity." +
" Available column names:${allColumns.joinToString(", ")}"
}
fun duplicateIndexInEntity(indexName: String): String {
return "There are multiple indices with name $indexName. This happen if you've declared" +
" the same index multiple times or different indices have the same name. See" +
" @Index documentation for details."
}
fun duplicateIndexInDatabase(indexName: String, indexPaths: List<String>): String {
return "There are multiple indices with name $indexName. You should rename " +
"${indexPaths.size - 1} of these to avoid the conflict:" +
"${indexPaths.joinToString(", ")}."
}
fun droppedEmbeddedFieldIndex(fieldPath: String, grandParent: String): String {
return "The index will be dropped when being merged into $grandParent" +
"($fieldPath). You must re-declare it in $grandParent if you want to index this" +
" field in $grandParent."
}
fun droppedEmbeddedIndex(entityName: String, fieldPath: String, grandParent: String): String {
return "Indices defined in $entityName will be dropped when it is merged into" +
" $grandParent ($fieldPath). You can re-declare them in $grandParent."
}
fun droppedSuperClassIndex(childEntity: String, superEntity: String): String {
return "Indices defined in $superEntity will NOT be re-used in $childEntity. If you want" +
" to inherit them, you must re-declare them in $childEntity." +
" Alternatively, you can set inheritSuperIndices to true in the @Entity annotation."
}
fun droppedSuperClassFieldIndex(fieldName: String, childEntity: String,
superEntity: String): String {
return "Index defined on field `$fieldName` in $superEntity will NOT be re-used in" +
" $childEntity. " +
"If you want to inherit it, you must re-declare it in $childEntity." +
" Alternatively, you can set inheritSuperIndices to true in the @Entity annotation."
}
val RELATION_NOT_COLLECTION = "Fields annotated with @Relation must be a List or Set."
fun relationCannotFindEntityField(entityName: String, columnName: String,
availableColumns: List<String>): String {
return "Cannot find the child entity column `$columnName` in $entityName." +
" Options: ${availableColumns.joinToString(", ")}"
}
fun relationCannotFindParentEntityField(entityName: String, columnName: String,
availableColumns: List<String>): String {
return "Cannot find the parent entity column `$columnName` in $entityName." +
" Options: ${availableColumns.joinToString(", ")}"
}
val RELATION_IN_ENTITY = "Entities cannot have relations."
val CANNOT_FIND_TYPE = "Cannot find type."
fun relationAffinityMismatch(parentColumn: String, childColumn: String,
parentAffinity: SQLTypeAffinity?,
childAffinity: SQLTypeAffinity?): String {
return """
The affinity of parent column ($parentColumn : $parentAffinity) does not match the type
affinity of the child column ($childColumn : $childAffinity).
""".trim()
}
val CANNOT_USE_MORE_THAN_ONE_POJO_FIELD_ANNOTATION = "A field can be annotated with only" +
" one of the following:" + PojoProcessor.PROCESSED_ANNOTATIONS.joinToString(",") {
it.java.simpleName
}
fun relationBadProject(entityQName: String, missingColumnNames: List<String>,
availableColumnNames: List<String>): String {
return """
$entityQName does not have the following columns: ${missingColumnNames.joinToString(",")}.
Available columns are: ${availableColumnNames.joinToString(",")}
""".trim()
}
val MISSING_SCHEMA_EXPORT_DIRECTORY = "Schema export directory is not provided to the" +
" annotation processor so we cannot export the schema. You can either provide" +
" `room.schemaLocation` annotation processor argument OR set exportSchema to false."
val INVALID_FOREIGN_KEY_ACTION = "Invalid foreign key action. It must be one of the constants" +
" defined in ForeignKey.Action"
fun foreignKeyNotAnEntity(className: String): String {
return """
Classes referenced in Foreign Key annotations must be @Entity classes. $className is not
an entity
""".trim()
}
val FOREIGN_KEY_CANNOT_FIND_PARENT = "Cannot find parent entity class."
fun foreignKeyChildColumnDoesNotExist(columnName: String, allColumns: List<String>): String {
return "($columnName) referenced in the foreign key does not exists in the Entity." +
" Available column names:${allColumns.joinToString(", ")}"
}
fun foreignKeyParentColumnDoesNotExist(parentEntity: String,
missingColumn: String,
allColumns: List<String>): String {
return "($missingColumn) does not exist in $parentEntity. Available columns are" +
" ${allColumns.joinToString(",")}"
}
val FOREIGN_KEY_EMPTY_CHILD_COLUMN_LIST = "Must specify at least 1 column name for the child"
val FOREIGN_KEY_EMPTY_PARENT_COLUMN_LIST = "Must specify at least 1 column name for the parent"
fun foreignKeyColumnNumberMismatch(
childColumns: List<String>, parentColumns: List<String>): String {
return """
Number of child columns in foreign key must match number of parent columns.
Child reference has ${childColumns.joinToString(",")} and parent reference has
${parentColumns.joinToString(",")}
""".trim()
}
fun foreignKeyMissingParentEntityInDatabase(parentTable: String, childEntity: String): String {
return """
$parentTable table referenced in the foreign keys of $childEntity does not exist in
the database. Maybe you forgot to add the referenced entity in the entities list of
the @Database annotation?""".trim()
}
fun foreignKeyMissingIndexInParent(parentEntity: String, parentColumns: List<String>,
childEntity: String, childColumns: List<String>): String {
return """
$childEntity has a foreign key (${childColumns.joinToString(",")}) that references
$parentEntity (${parentColumns.joinToString(",")}) but $parentEntity does not have
a unique index on those columns nor the columns are its primary key.
SQLite requires having a unique constraint on referenced parent columns so you must
add a unique index to $parentEntity that has
(${parentColumns.joinToString(",")}) column(s).
""".trim()
}
fun foreignKeyMissingIndexInChildColumns(childColumns: List<String>): String {
return """
(${childColumns.joinToString(",")}) column(s) reference a foreign key but
they are not part of an index. This may trigger full table scans whenever parent
table is modified so you are highly advised to create an index that covers these
columns.
""".trim()
}
fun foreignKeyMissingIndexInChildColumn(childColumn: String): String {
return """
$childColumn column references a foreign key but it is not part of an index. This
may trigger full table scans whenever parent table is modified so you are highly
advised to create an index that covers this column.
""".trim()
}
fun shortcutEntityIsNotInDatabase(database: String, dao: String, entity: String): String {
return """
$dao is part of $database but this entity is not in the database. Maybe you forgot
to add $entity to the entities section of the @Database?
""".trim()
}
val MISSING_ROOM_GUAVA_ARTIFACT = "To use Guava features, you must add `guava`" +
" artifact from Room as a dependency. androidx.room:guava:<version>"
val MISSING_ROOM_RXJAVA2_ARTIFACT = "To use RxJava2 features, you must add `rxjava2`" +
" artifact from Room as a dependency. androidx.room:rxjava2:<version>"
fun ambigiousConstructor(
pojo: String, paramName: String, matchingFields: List<String>): String {
return """
Ambiguous constructor. The parameter ($paramName) in $pojo matches multiple fields:
[${matchingFields.joinToString(",")}]. If you don't want to use this constructor,
you can annotate it with @Ignore. If you want Room to use this constructor, you can
rename the parameters to exactly match the field name to fix the ambiguity.
""".trim()
}
val MISSING_POJO_CONSTRUCTOR = """
Entities and Pojos must have a usable public constructor. You can have an empty
constructor or a constructor whose parameters match the fields (by name and type).
""".trim()
val TOO_MANY_POJO_CONSTRUCTORS = """
Room cannot pick a constructor since multiple constructors are suitable. Try to annotate
unwanted constructors with @Ignore.
""".trim()
val TOO_MANY_POJO_CONSTRUCTORS_CHOOSING_NO_ARG = """
There are multiple good constructors and Room will pick the no-arg constructor.
You can use the @Ignore annotation to eliminate unwanted constructors.
""".trim()
val RELATION_CANNOT_BE_CONSTRUCTOR_PARAMETER = """
Fields annotated with @Relation cannot be constructor parameters. These values are
fetched after the object is constructed.
""".trim()
val PAGING_SPECIFY_DATA_SOURCE_TYPE = "For now, Room only supports PositionalDataSource class."
fun primaryKeyNull(field: String): String {
return "You must annotate primary keys with @NonNull. \"$field\" is nullable. SQLite " +
"considers this a " +
"bug and Room does not allow it. See SQLite docs for details: " +
"https://www.sqlite.org/lang_createtable.html"
}
val INVALID_COLUMN_NAME = "Invalid column name. Room does not allow using ` or \" in column" +
" names"
val INVALID_TABLE_NAME = "Invalid table name. Room does not allow using ` or \" in table names"
val RAW_QUERY_BAD_PARAMS = "RawQuery methods should have 1 and only 1 parameter with type" +
" String or SupportSQLiteQuery"
val RAW_QUERY_BAD_RETURN_TYPE = "RawQuery methods must return a non-void type."
fun rawQueryBadEntity(typeName: TypeName): String {
return """
observedEntities field in RawQuery must either reference a class that is annotated
with @Entity or it should reference a Pojo that either contains @Embedded fields that
are annotated with @Entity or @Relation fields.
$typeName does not have these properties, did you mean another class?
""".trim()
}
val RAW_QUERY_STRING_PARAMETER_REMOVED = "RawQuery does not allow passing a string anymore." +
" Please use ${SupportDbTypeNames.QUERY}."
}
| apache-2.0 |
koma-im/koma | src/main/kotlin/link/continuum/desktop/gui/icon/avatar/initial.kt | 1 | 3768 | package link.continuum.desktop.gui.icon.avatar
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.CornerRadii
import javafx.scene.paint.Color
import javafx.scene.text.Text
import link.continuum.desktop.gui.*
import link.continuum.desktop.util.debugAssertUiThread
import mu.KotlinLogging
import java.util.*
import kotlin.streams.toList
private val logger = KotlinLogging.logger {}
class InitialIcon(
) {
private val radii = CornerRadii( 0.2, true)
private val charL = Text().apply {
fill = Color.WHITE
}
private val charR = Text().apply { fill = Color.WHITE }
private val charC = Text().apply { fill = Color.WHITE }
private val two = HBox().apply {
style {
fontSize = 1.em
}
alignment = Pos.CENTER
vbox {
alignment = Pos.CENTER_RIGHT
add(charL)
}
vbox {
style {
prefWidth = 0.1.em
}
}
vbox {
alignment = Pos.CENTER_LEFT
add(charR)
}
}
private val one = HBox().apply {
alignment = Pos.CENTER
children.add(charC)
style { fontSize = 1.8.em }
}
val root = StackPane().apply {
style = avStyle
}
fun show() {
debugAssertUiThread()
this.root.isManaged = true
this.root.isVisible = true
}
fun hide() {
this.root.isManaged = false
this.root.isVisible = false
}
fun updateColor(color: Color) {
debugAssertUiThread()
root.background = backgrounds.computeIfAbsent(color) {
logger.debug { "initial icon $charL $charR $color" }
Background(BackgroundFill(it, radii, Insets.EMPTY))
}
}
fun updateItem(charL: String, charR: String, color: Color) {
updateColor(color)
updateCharPair(charL, charR)
}
fun updateCharPair(charL: String, charR: String) {
debugAssertUiThread()
this.charL.text = charL
this.charR.text = charR
root.children.setAll(two)
}
fun updateCenter(char: String, color: Color) {
updateColor(color)
updateCharSingle(char)
}
fun updateCharSingle(char: String) {
debugAssertUiThread()
charC.text = char
root.children.setAll(one)
}
fun updateString(input: String) {
val (c1, c2) = extractKeyChar(input)
if (c2 != null) {
updateCharPair(c1, c2)
} else {
updateCharSingle(c1)
}
}
fun updateItem(input: String, color: Color) {
val (c1, c2) = extractKeyChar(input)
if (c2 != null) {
updateItem(c1, c2, color)
} else {
updateCenter(c1, color)
}
}
companion object {
private val backgrounds = WeakHashMap<Color, Background>()
private val avStyle = StyleBuilder().apply {
val s = 2.em
prefHeight = s
prefWidth = s
fontFamily = GenericFontFamily.sansSerif
}.toString()
}
}
internal fun extractKeyChar(input: String): Pair<String, String?> {
val trim = input.replace("(IRC)", "").trim()
val cps = trim.codePoints().toList()
val ideo = cps.find { Character.isIdeographic(it) }
if (ideo != null) {
return String(Character.toChars(ideo)) to null
}
val first = cps.firstOrNull()?.let { String(Character.toChars(it)) } ?: ""
val i2 = cps.indexOfFirst { Character.isSpaceChar(it) }.let { if (it < 0) null else it + 1} ?: 1
val second = cps.getOrNull(i2)?.let { String(Character.toChars(it)) }
return first to second
}
| gpl-3.0 |
atlarge-research/opendc-simulator | opendc-stdlib/src/main/kotlin/com/atlarge/opendc/simulator/Helpers.kt | 1 | 1927 | package com.atlarge.opendc.simulator
import kotlin.coroutines.experimental.intrinsics.suspendCoroutineOrReturn
/**
* Try to find the [Context] instance associated with the [Process] in the call chain which has (indirectly) invoked the
* caller of this method.
*
* Note however that this method does not guarantee type-safety as this method allows the user to cast to a context
* with different generic type arguments.
*
* @return The context that has been found or `null` if this method is not called in a simulation context.
*/
suspend fun <S, M> contextOrNull(): Context<S, M>? = suspendCoroutineOrReturn { it.context[Context] }
/**
* Find the [Context] instance associated with the [Process] in the call chain which has (indirectly) invoked the
* caller of this method.
*
* Note however that this method does not guarantee type-safety as this method allows the user to cast to a context
* with different generic type arguments.
*
* @throws IllegalStateException if the context cannot be found.
* @return The context that has been found.
*/
suspend fun <S, M> context(): Context<S, M> =
contextOrNull() ?: throw IllegalStateException("The suspending call does not have an associated process context")
/**
* Try to find the untyped [Context] instance associated with the [Process] in the call chain which has (indirectly)
* invoked the caller of this method.
*
* @return The untyped context that has been found or `null` if this method is not called in a simulation context.
*/
suspend fun untypedContextOrNull(): Context<*, *>? = contextOrNull<Any?, Any?>()
/**
* Find the [Context] instance associated with the [Process] in the call chain which has (indirectly) invoked the
* caller of this method.
*
* @throws IllegalStateException if the context cannot be found.
* @return The untyped context that has been found.
*/
suspend fun untypedContext(): Context<*, *> = context<Any?, Any?>()
| mit |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/reader/Decoder.kt | 1 | 2696 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.legacy.reader
import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Html
import android.text.Spanned
import android.text.TextUtils
import android.webkit.WebSettings
import jp.hazuki.yuzubrowser.core.utility.log.Logger
import jp.hazuki.yuzubrowser.core.utility.utils.ImageUtils
import jp.hazuki.yuzubrowser.download.getImage
import jp.hazuki.yuzubrowser.legacy.reader.snacktory.HtmlFetcher
import okhttp3.OkHttpClient
import java.util.*
fun OkHttpClient.decodeToReaderData(context: Context, url: String, userAgent: String?): ReaderData? {
val fetcher = HtmlFetcher()
if (userAgent.isNullOrEmpty()) {
fetcher.userAgent = WebSettings.getDefaultUserAgent(context)
} else {
fetcher.userAgent = userAgent
}
fetcher.referrer = url
val locale = Locale.getDefault()
val language = locale.language + "-" + locale.country
if (language.length >= 5) {
fetcher.language = language
}
try {
val result = fetcher.fetchAndExtract(this, url, 2500, true)
if (!TextUtils.isEmpty(result.text)) {
val html: Spanned = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(result.text, Html.FROM_HTML_MODE_LEGACY, Html.ImageGetter { getImage(context, it, url, userAgent) }, null)
} else {
@Suppress("DEPRECATION")
Html.fromHtml(result.text, Html.ImageGetter { getImage(context, it, url, userAgent) }, null)
}
return ReaderData(result.title, html)
}
} catch (e: Exception) {
e.printStackTrace()
} catch (e: OutOfMemoryError) {
System.gc()
Logger.w("reader", e, "Out of memory")
}
return null
}
private fun OkHttpClient.getImage(context: Context, imageUrl: String, url: String, userAgent: String?): Drawable {
val drawable = ImageUtils.getDrawable(context, getImage(imageUrl, userAgent, url))
return drawable ?: ColorDrawable(0)
}
| apache-2.0 |
hazuki0x0/YuzuBrowser | module/bookmark/src/main/java/jp/hazuki/yuzubrowser/bookmark/view/BookmarkActivity.kt | 1 | 2737 | /*
* Copyright (C) 2017-2019 Hazuki
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jp.hazuki.yuzubrowser.bookmark.view
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.MenuItem
import android.view.WindowInsets
import android.view.WindowManager
import androidx.fragment.app.commit
import dagger.hilt.android.AndroidEntryPoint
import jp.hazuki.bookmark.R
import jp.hazuki.yuzubrowser.ui.INTENT_EXTRA_MODE_FULLSCREEN
import jp.hazuki.yuzubrowser.ui.INTENT_EXTRA_MODE_ORIENTATION
import jp.hazuki.yuzubrowser.ui.app.LongPressFixActivity
import jp.hazuki.yuzubrowser.ui.settings.AppPrefs
@AndroidEntryPoint
class BookmarkActivity : LongPressFixActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_base)
val intent = intent
var pickMode = false
var itemId: Long = -1
var fullscreen = AppPrefs.fullscreen.get()
var orientation = AppPrefs.oritentation.get()
if (intent != null) {
pickMode = Intent.ACTION_PICK == intent.action
itemId = intent.getLongExtra("id", -1)
fullscreen = intent.getBooleanExtra(INTENT_EXTRA_MODE_FULLSCREEN, fullscreen)
orientation = intent.getIntExtra(INTENT_EXTRA_MODE_ORIENTATION, orientation)
}
if (fullscreen) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.insetsController?.hide(WindowInsets.Type.statusBars())
} else {
@Suppress("DEPRECATION")
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
}
requestedOrientation = orientation
supportFragmentManager.commit {
replace(R.id.container, BookmarkFragment(pickMode, itemId))
}
}
override fun onBackKeyLongPressed() {
finish()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
android.R.id.home -> {
finish()
return true
}
}
return super.onOptionsItemSelected(item)
}
}
| apache-2.0 |
seventhroot/elysium | bukkit/rpk-player-lib-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKIRCProfileProvider.kt | 1 | 475 | package com.rpkit.players.bukkit.profile
import com.rpkit.core.service.ServiceProvider
import org.pircbotx.User
interface RPKIRCProfileProvider: ServiceProvider {
fun getIRCProfile(id: Int): RPKIRCProfile?
fun getIRCProfile(user: User): RPKIRCProfile?
fun getIRCProfiles(profile: RPKProfile): List<RPKIRCProfile>
fun addIRCProfile(profile: RPKIRCProfile)
fun updateIRCProfile(profile: RPKIRCProfile)
fun removeIRCProfile(profile: RPKIRCProfile)
} | apache-2.0 |
samthor/intellij-community | platform/diff-impl/tests/com/intellij/diff/comparison/CharComparisonUtilTest.kt | 17 | 7101 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diff.comparison
public class CharComparisonUtilTest : ComparisonUtilTestBase() {
public fun testEqualStrings() {
chars {
("" - "")
("" - "").default()
testAll()
}
chars {
("x" - "x")
(" " - " ").default()
testAll()
}
chars {
("x_y_z_" - "x_y_z_")
(" " - " ").default()
testAll()
}
chars {
("_" - "_")
(" " - " ").default()
testAll()
}
chars {
("xxx" - "xxx")
(" " - " ").default()
testAll()
}
chars {
("xyz" - "xyz")
(" " - " ").default()
testAll()
}
chars {
(".x!" - ".x!")
(" " - " ").default()
testAll()
}
}
public fun testTrivialCases() {
chars {
("x" - "")
("-" - "").default()
testAll()
}
chars {
("" - "x")
("" - "-").default()
testAll()
}
chars {
("x" - "y")
("-" - "-").default()
testAll()
}
chars {
("x_" - "")
("--" - "").default()
("- " - "").ignore()
testAll()
}
chars {
("" - "x_")
("" - "--").default()
("" - "- ").ignore()
testAll()
}
chars {
("x_" - "y_")
("- " - "- ").default()
testAll()
}
chars {
("_x" - "_y")
(" -" - " -").default()
testAll()
}
}
public fun testSimpleCases() {
chars {
("xyx" - "xxx")
(" - " - " - ").default()
testAll()
}
chars {
("xyyx" - "xmx")
(" -- " - " - ").default()
testAll()
}
chars {
("xyy" - "yyx")
("- " - " -").default()
testAll()
}
chars {
("x!!" - "!!x")
("- " - " -").default()
testAll()
}
chars {
("xyx" - "xx")
(" - " - " ").default()
testAll()
}
chars {
("xx" - "xyx")
(" " - " - ").default()
testAll()
}
chars {
("!..." - "...!")
("- " - " -").default()
testAll()
}
}
public fun testWhitespaceChangesOnly() {
chars {
(" x y z " - "xyz")
("- - - -" - " ").default()
(" " - " ").ignore()
testAll()
}
chars {
("xyz" - " x y z ")
(" " - "- - - -").default()
(" " - " ").ignore()
testAll()
}
chars {
("x " - "x")
(" -" - " ").default()
(" " - " ").ignore()
testAll()
}
chars {
("x" - " x")
(" " - "- ").default()
(" " - " ").ignore()
testAll()
}
chars {
(" x " - "x")
("- -" - " ").default()
(" " - " ").ignore()
testAll()
}
chars {
("x" - " x ")
(" " - "- -").default()
(" " - " ").ignore()
testAll()
}
}
public fun testWhitespaceChanges() {
chars {
(" x " - "z")
("---" - "-").default()
(" - " - "-").ignore()
testAll()
}
chars {
("x" - " z ")
("-" - "---").default()
("-" - " - ").ignore()
testAll()
}
chars {
(" x" - "z\t")
("--" - "--").default()
(" -" - "- ").ignore()
testAll()
}
chars {
("x " - "\tz")
("--" - "--").default()
("- " - " -").ignore()
testAll()
}
}
public fun testIgnoreInnerWhitespaces() {
chars {
("x z y" - "xmn")
(" ----" - " --").default()
(" ---" - " --").ignore()
testAll()
}
chars {
("x y z " - "x y m ")
(" - " - " - ").default()
testAll()
}
chars {
("x y z" - "x y m ")
(" -" - " --").default()
(" -" - " - ").ignore()
testAll()
}
chars {
(" x y z" - " m y z")
(" - " - " - ").default()
testAll()
}
chars {
("x y z" - " m y z")
("- " - "-- ").default()
("- " - " - ").ignore()
testAll()
}
chars {
("x y z" - "x m z")
(" - " - " - ").default()
testAll()
}
chars {
("x y z" - "x z")
(" - " - " ").default()
testAll()
}
chars {
("x z" - "x m z")
(" " - " - ").default()
testAll()
}
chars {
("x z" - "x n m z")
(" " - " --- ").default()
testAll()
}
}
public fun testEmptyRangePositions() {
chars {
("x y" - "x zy")
default(ins(2, 2, 1))
testAll()
}
chars {
("x y" - "xz y")
default(ins(1, 1, 1))
testAll()
}
chars {
("x y z" - "x z")
default(del(2, 2, 1))
testAll()
}
chars {
("x z" - "x m z")
default(ins(2, 2, 1))
testAll()
}
chars {
("xyx" - "xx")
default(del(1, 1, 1))
testAll()
}
chars {
("xx" - "xyx")
default(ins(1, 1, 1))
testAll()
}
chars {
("xy" - "x")
default(del(1, 1, 1))
testAll()
}
chars {
("x" - "xy")
default(ins(1, 1, 1))
testAll()
}
}
public fun testAlgorithmSpecific() {
// This is a strange example: "ignore whitespace" produces lesser matching, than "Default".
// This is fine, as the main goal of "ignore whitespaces" is to reduce 'noise' of diff, and 1 change is better than 3 changes
// So we actually "ignore" whitespaces during comparison, rather than "mark all whitespaces as matched".
chars {
("x y z" - "xX Zz")
(" - " - " - - ").default()
(" - " - " -------- ").ignore()
testAll()
}
}
public fun testNonDeterministicCases() {
chars {
("x" - " ")
ignore(del(0, 0, 1))
testIgnore()
}
chars {
(" " - "x")
ignore(ins(0, 0, 1))
testIgnore()
}
chars {
("x .. z" - "x y .. z")
(" " - " -- ").default()
(" " - " - ").ignore()
default(ins(2, 2, 2))
ignore(ins(2, 2, 1))
testAll()
}
chars {
(" x _ y _ z " - "x z")
("- ------ -" - " ").default()
(" - " - " ").ignore()
default(del(0, 0, 1), del(3, 2, 6), del(10, 3, 1))
ignore(del(5, 2, 1))
testAll()
}
chars {
("x z" - " x _ y _ z ")
(" " - "- ------ -").default()
(" " - " - ").ignore()
default(ins(0, 0, 1), ins(2, 3, 6), ins(3, 10, 1))
ignore(ins(2, 5, 1))
testAll()
}
}
}
| apache-2.0 |
dtretyakov/teamcity-rust | plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/RustupToolchainBuildService.kt | 1 | 2616 | /*
* 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 jetbrains.buildServer.RunBuildException
import jetbrains.buildServer.agent.ToolCannotBeFoundException
import jetbrains.buildServer.agent.runner.BuildServiceAdapter
import jetbrains.buildServer.agent.runner.ProcessListener
import jetbrains.buildServer.agent.runner.ProcessListenerAdapter
import jetbrains.buildServer.agent.runner.ProgramCommandLine
import jetbrains.buildServer.rust.logging.BlockListener
/**
* Rustup runner service.
*/
class RustupToolchainBuildService(private val action: String) : BuildServiceAdapter() {
val errors = arrayListOf<String>()
var foundVersion: String? = null
val version: String
get() = foundVersion ?: runnerParameters[CargoConstants.PARAM_TOOLCHAIN]!!
override fun makeProgramCommandLine(): ProgramCommandLine {
val toolchainVersion = runnerParameters[CargoConstants.PARAM_TOOLCHAIN]!!.trim()
val rustupPath = getPath(CargoConstants.RUSTUP_CONFIG_NAME)
return createProgramCommandline(rustupPath, arrayListOf("toolchain", action, toolchainVersion))
}
private fun getPath(toolName: String): String {
try {
return getToolPath(toolName)
} catch (e: ToolCannotBeFoundException) {
val buildException = RunBuildException(e)
buildException.isLogStacktrace = false
throw buildException
}
}
override fun isCommandLineLoggingEnabled() = false
override fun getListeners(): MutableList<ProcessListener> {
return arrayListOf<ProcessListener>().apply {
val blockName = "$action toolchain: ${runnerParameters[CargoConstants.PARAM_TOOLCHAIN]}"
this.add(BlockListener(blockName, logger))
this.add(object : ProcessListenerAdapter() {
override fun onStandardOutput(text: String) {
processOutput(text)
}
override fun onErrorOutput(text: String) {
processOutput(text)
}
})
}
}
fun processOutput(text: String) {
if (text.startsWith("error:")) {
errors.add(text)
}
toolchainVersion.matchEntire(text)?.let {
foundVersion = it.groupValues.last()
}
logger.message(text)
}
companion object {
val toolchainVersion = Regex("info: syncing channel updates for '([^']+)'")
}
}
| apache-2.0 |
dmitryustimov/weather-kotlin | app/src/main/java/ru/ustimov/weather/content/ImageLoader.kt | 1 | 317 | package ru.ustimov.weather.content
import android.support.design.widget.TabLayout
import android.widget.ImageView
import ru.ustimov.weather.content.data.Country
interface ImageLoader {
fun loadCountryFlag(country: Country, imageView: ImageView)
fun loadCountryFlag(country: Country, tab: TabLayout.Tab)
} | apache-2.0 |
rfcx/rfcx-guardian-android | role-guardian/src/main/java/org/rfcx/guardian/guardian/manager/PreferenceManager.kt | 1 | 3041 | package org.rfcx.guardian.guardian.manager
import android.content.Context
import android.content.SharedPreferences
import java.util.*
class PreferenceManager(context: Context){
private var sharedPreferences: SharedPreferences
companion object {
@Volatile
private var INSTANCE: PreferenceManager? = null
fun getInstance(context: Context): PreferenceManager =
INSTANCE ?: synchronized(this) {
INSTANCE ?: PreferenceManager(context).also { INSTANCE = it }
}
private const val PREFERENCES_NAME = "Rfcx.Guardian"
private const val PREFIX = "org.rfcx.guardian:"
const val ID_TOKEN = "${PREFIX}ID_TOKEN"
const val ACCESS_TOKEN = "${PREFIX}ACCESS_TOKEN"
const val REFRESH_TOKEN = "${PREFIX}REFRESH_TOKEN"
const val USER_GUID = "${PREFIX}USER_GUID"
const val EMAIL = "${PREFIX}EMAIL"
const val NICKNAME = "${PREFIX}NICKNAME"
const val ROLES = "${PREFIX}ROLES"
const val ACCESSIBLE_SITES = "${PREFIX}ACCESSIBLE_SITES"
const val DEFAULT_SITE = "${PREFIX}SITE"
const val TOKEN_EXPIRED_AT = "${PREFIX}EXPIRED_AT"
}
init {
sharedPreferences = context.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE)
}
fun getBoolean(key: String, defaultValue: Boolean = false): Boolean {
return sharedPreferences.getBoolean(key, defaultValue)
}
fun putBoolean(key: String, value: Boolean) {
sharedPreferences.edit().putBoolean(key, value).apply()
}
fun getString(key: String, defValue: String): String {
return sharedPreferences.getString(key, defValue) ?: defValue
}
fun getString(key: String): String? {
return sharedPreferences.getString(key, null)
}
fun putString(key: String, value: String) {
sharedPreferences.edit().putString(key, value).apply()
}
fun getDate(key: String): Date? {
val secondsSinceEpoch = sharedPreferences.getLong(key, 0L)
if (secondsSinceEpoch == 0L) {
return null
}
return Date(secondsSinceEpoch)
}
fun putDate(key: String, date: Date) {
sharedPreferences.edit().putLong(key, date.time).apply()
}
fun getLong(key: String, defValue: Long): Long {
return sharedPreferences.getLong(key, defValue)
}
fun putLong(key: String, long: Long) {
sharedPreferences.edit().putLong(key, long).apply()
}
fun getStringSet(key: String): Set<String> {
return sharedPreferences.getStringSet(key, setOf()) ?: setOf()
}
fun putStringSet(key: String, value: Set<String>) {
sharedPreferences.edit().putStringSet(key, value).apply()
}
fun remove(key: String) {
sharedPreferences.edit().remove(key).apply()
}
fun clear() {
sharedPreferences.edit().clear().apply()
}
fun isTokenExpired(): Boolean{
return System.currentTimeMillis() > getLong(TOKEN_EXPIRED_AT, 0L)
}
}
| apache-2.0 |
michaelengland/FlipTheSwitch-Android | fliptheswitch-gradle/src/main/kotlin/com/github/michaelengland/fliptheswitch/gradle/CreateFeaturesTask.kt | 1 | 552 | package com.github.michaelengland.fliptheswitch.gradle
import com.github.michaelengland.fliptheswitch.Feature
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.TaskAction
import java.io.File
open class CreateFeaturesTask : DefaultTask() {
var features: List<Feature> = listOf()
@get:OutputDirectory
var buildDirectory: File? = null
@TaskAction
fun createFeatures() {
buildDirectory?.mkdirs()
FeaturesWriter(features).build().writeTo(buildDirectory)
}
}
| apache-2.0 |
evant/silent-support | silent-support/src/main/java/me/tatarka/silentsupport/SupportCompat.kt | 1 | 480 | package me.tatarka.silentsupport
import java.io.File
data class SupportCompat(val file: File, val version: String) {
companion object {
fun fromClasspath(classpath: Collection<File>): SupportCompat? {
val file = classpath.find { it.name.matches(Regex("support-compat-[0-9.]+\\.aar")) } ?: return null
val version = Regex(".*-([0-9.]+)\\.aar").find(file.name)!!.groupValues[1]
return SupportCompat(file, version)
}
}
}
| apache-2.0 |
cretz/asmble | compiler/src/main/kotlin/asmble/compile/jvm/ClsContext.kt | 1 | 6143 | package asmble.compile.jvm
import asmble.ast.Node
import asmble.util.Either
import asmble.util.Logger
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import org.objectweb.asm.tree.ClassNode
import org.objectweb.asm.tree.MethodInsnNode
import org.objectweb.asm.tree.MethodNode
import java.util.*
data class ClsContext(
val packageName: String,
val className: String,
val mod: Node.Module,
val cls: ClassNode = ClassNode().also { it.name = (packageName.replace('.', '/') + "/$className").trimStart('/') },
val mem: Mem = ByteBufferMem,
val modName: String? = null,
val reworker: InsnReworker = InsnReworker,
val logger: Logger = Logger.Print(Logger.Level.OFF),
val funcBuilder: FuncBuilder = FuncBuilder,
val syntheticFuncBuilder: SyntheticFuncBuilder = SyntheticFuncBuilder,
val checkTruncOverflow: Boolean = true,
val nonAdjacentMemAccessesRequiringLocalVar: Int = 3,
val eagerFailLargeMemOffset: Boolean = true,
val preventMemIndexOverflow: Boolean = false,
val accurateNanBits: Boolean = true,
val checkSignedDivIntegerOverflow: Boolean = true,
val jumpTableChunkSize: Int = 5000,
val includeBinary: Boolean = false
) : Logger by logger {
val importFuncs: List<Node.Import> by lazy { mod.imports.filter { it.kind is Node.Import.Kind.Func } }
val importGlobals: List<Node.Import> by lazy { mod.imports.filter { it.kind is Node.Import.Kind.Global } }
val thisRef = TypeRef(Type.getObjectType((packageName.replace('.', '/') + "/$className").trimStart('/')))
val hasMemory: Boolean by lazy {
mod.memories.isNotEmpty() || mod.imports.any { it.kind is Node.Import.Kind.Memory }
}
val hasTable: Boolean by lazy {
mod.tables.isNotEmpty() || mod.imports.any { it.kind is Node.Import.Kind.Table }
}
val dedupedFuncNames: Map<Int, String>? by lazy {
// Consider all exports as seen
val seen = mod.exports.flatMap { export ->
when {
export.kind == Node.ExternalKind.FUNCTION -> listOf(export.field.javaIdent)
// Just to make it easy, consider all globals as having setters
export.kind == Node.ExternalKind.GLOBAL ->
export.field.javaIdent.capitalize().let { listOf("get$it", "set$it") }
else -> listOf("get" + export.field.javaIdent.capitalize())
}
}.toMutableSet()
mod.names?.funcNames?.toList()?.sortedBy { it.first }?.map { (index, origName) ->
var name = origName.javaIdent
var nameIndex = 0
while (!seen.add(name)) name = origName.javaIdent + (nameIndex++)
index to name
}?.toMap()
}
fun assertHasMemory() { if (!hasMemory) throw CompileErr.UnknownMemory(0) }
fun typeAtIndex(index: Int) = mod.types.getOrNull(index) ?: throw CompileErr.UnknownType(index)
fun funcAtIndex(index: Int) = importFuncs.getOrNull(index).let {
when (it) {
null -> Either.Right(mod.funcs.getOrNull(index - importFuncs.size) ?: throw CompileErr.UnknownFunc(index))
else -> Either.Left(it)
}
}
fun funcTypeAtIndex(index: Int) = funcAtIndex(index).let {
when (it) {
is Either.Left -> typeAtIndex((it.v.kind as Node.Import.Kind.Func).typeIndex)
is Either.Right -> it.v.type
}
}
fun globalAtIndex(index: Int) = importGlobals.getOrNull(index).let {
when (it) {
null ->
Either.Right(mod.globals.getOrNull(index - importGlobals.size) ?:
throw CompileErr.UnknownGlobal(index))
else ->
Either.Left(it)
}
}
fun importGlobalGetterFieldName(index: Int) = "import\$get" + globalName(index)
fun importGlobalSetterFieldName(index: Int) = "import\$set" + globalName(index)
fun globalName(index: Int) = "\$global$index"
fun funcName(index: Int) = dedupedFuncNames?.get(index) ?: "\$func$index"
private fun syntheticFunc(
nameSuffix: String,
fn: SyntheticFuncBuilder.(ClsContext, String) -> MethodNode
): MethodInsnNode {
val name = "\$\$$nameSuffix"
val method =
cls.methods.find { (it as MethodNode).name == name }?.let { it as MethodNode } ?:
fn(syntheticFuncBuilder, this, name).also { cls.methods.add(it) }
return MethodInsnNode(Opcodes.INVOKESTATIC, thisRef.asmName, method.name, method.desc, false)
}
val truncAssertF2SI get() = syntheticFunc("assertF2SI", SyntheticFuncBuilder::buildF2SIAssertion)
val truncAssertF2UI get() = syntheticFunc("assertF2UI", SyntheticFuncBuilder::buildF2UIAssertion)
val truncAssertF2SL get() = syntheticFunc("assertF2SL", SyntheticFuncBuilder::buildF2SLAssertion)
val truncAssertF2UL get() = syntheticFunc("assertF2UL", SyntheticFuncBuilder::buildF2ULAssertion)
val truncAssertD2SI get() = syntheticFunc("assertD2SI", SyntheticFuncBuilder::buildD2SIAssertion)
val truncAssertD2UI get() = syntheticFunc("assertD2UI", SyntheticFuncBuilder::buildD2UIAssertion)
val truncAssertD2SL get() = syntheticFunc("assertD2SL", SyntheticFuncBuilder::buildD2SLAssertion)
val truncAssertD2UL get() = syntheticFunc("assertD2UL", SyntheticFuncBuilder::buildD2ULAssertion)
val divAssertI get() = syntheticFunc("assertIDiv", SyntheticFuncBuilder::buildIDivAssertion)
val divAssertL get() = syntheticFunc("assertLDiv", SyntheticFuncBuilder::buildLDivAssertion)
val indirectBootstrap get() = syntheticFunc("indirectBootstrap", SyntheticFuncBuilder::buildIndirectBootstrap)
// Builds a method that takes an int and returns a depth int
fun largeTableJumpCall(table: Node.Instr.BrTable): MethodInsnNode {
val namePrefix = "largeTable" + UUID.randomUUID().toString().replace("-", "")
val methods = syntheticFuncBuilder.buildLargeTableJumps(this, namePrefix, table)
cls.methods.addAll(methods)
return methods.first().let { method ->
MethodInsnNode(Opcodes.INVOKESTATIC, thisRef.asmName, method.name, method.desc, false)
}
}
} | mit |
NephyProject/Penicillin | src/main/kotlin/jp/nephy/penicillin/endpoints/directmessages/List.kt | 1 | 2547 | /*
* 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.
*/
@file:Suppress("UNUSED", "PublicApiImplicitType")
package jp.nephy.penicillin.endpoints.directmessages
import jp.nephy.penicillin.core.request.action.JsonObjectApiAction
import jp.nephy.penicillin.core.request.parameters
import jp.nephy.penicillin.core.session.get
import jp.nephy.penicillin.endpoints.DirectMessages
import jp.nephy.penicillin.endpoints.Option
import jp.nephy.penicillin.endpoints.directMessageDeprecatedMessage
import jp.nephy.penicillin.models.DirectMessage
/**
* Abolished endpoint.
*
* @param options Optional. Custom parameters of this request.
* @receiver [DirectMessages] endpoint instance.
* @return [JsonObjectApiAction] for [DirectMessage] model.
*/
@Deprecated(directMessageDeprecatedMessage, replaceWith = ReplaceWith("directMessageEvent.list", "jp.nephy.penicillin.endpoints.directMessageEvent", "jp.nephy.penicillin.endpoints.directmessages.events.list"))
fun DirectMessages.list(
sinceId: Long? = null,
maxId: Long? = null,
count: Int? = null,
includeEntities: Boolean? = null,
skipStatus: Boolean? = null,
vararg options: Option
) = client.session.get("/1.1/direct_messages.json") {
parameters(
"since_id" to sinceId,
"max_id" to maxId,
"count" to count,
"include_entities" to includeEntities,
"skip_status" to skipStatus,
*options
)
}.jsonArray<DirectMessage>()
| mit |
mniami/android.kotlin.benchmark | app/src/main/java/guideme/volunteers/ui/fragments/genericlist/GenericObservableProvider.kt | 2 | 172 | package guideme.volunteers.ui.fragments.genericlist
import io.reactivex.Observable
interface GenericObservableProvider {
val observable : Observable<GenericItem<*>>
} | apache-2.0 |
UweTrottmann/SeriesGuide | app/src/test/java/com/battlelancer/seriesguide/thetvdbapi/ImageToolsTest.kt | 1 | 2244 | package com.battlelancer.seriesguide.thetvdbapi
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import com.battlelancer.seriesguide.EmptyTestApplication
import com.battlelancer.seriesguide.util.ImageTools
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(application = EmptyTestApplication::class)
class ImageToolsTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
@Test
fun posterUrl() {
// Note: TMDB image paths start with / whereas TVDB paths do not.
val tmdbUrl = ImageTools.tmdbOrTvdbPosterUrl("/example.jpg", context)
val tmdbUrlOriginal = ImageTools.tmdbOrTvdbPosterUrl("/example.jpg", context, true)
val tvdbUrl = ImageTools.tmdbOrTvdbPosterUrl("posters/example.jpg", context)
println("TMDB URL: $tmdbUrl")
println("TMDB original URL: $tmdbUrlOriginal")
println("TVDB URL: $tvdbUrl")
assertThat(tmdbUrl).isNotEmpty()
assertThat(tmdbUrl).endsWith("https://image.tmdb.org/t/p/w154/example.jpg")
assertThat(tmdbUrlOriginal).isNotEmpty()
assertThat(tmdbUrlOriginal).endsWith("https://image.tmdb.org/t/p/original/example.jpg")
assertThat(tvdbUrl).isNotEmpty()
assertThat(tvdbUrl).endsWith("https://artworks.thetvdb.com/banners/posters/example.jpg")
}
@Test
fun posterUrl_withLegacyCachePath() {
val url = ImageTools.tmdbOrTvdbPosterUrl("_cache/posters/example.jpg", context)
println("TVDB legacy URL: $url")
assertThat(url).isNotEmpty()
assertThat(url).endsWith("https://www.thetvdb.com/banners/_cache/posters/example.jpg")
}
@Test
fun posterUrlOrResolve() {
val url = ImageTools.posterUrlOrResolve(null, 42, null, context)
assertThat(url).isNotEmpty()
assertThat(url).isEqualTo("showtmdb://42")
val urlLang = ImageTools.posterUrlOrResolve(null, 42, "de", context)
assertThat(urlLang).isNotEmpty()
assertThat(urlLang).isEqualTo("showtmdb://42?language=de")
}
}
| apache-2.0 |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/stats/StatsFragment.kt | 1 | 14985 | package com.battlelancer.seriesguide.stats
import android.os.Bundle
import android.text.format.DateUtils
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.view.MenuProvider
import androidx.core.view.isGone
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.preference.PreferenceManager
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.databinding.FragmentStatsBinding
import com.battlelancer.seriesguide.settings.DisplaySettings
import com.battlelancer.seriesguide.util.ShareUtils
import com.battlelancer.seriesguide.util.copyTextToClipboardOnLongClick
import java.text.NumberFormat
/**
* Displays some statistics about the users show database, e.g. number of shows, episodes, share of
* watched episodes, etc.
*/
class StatsFragment : Fragment() {
private var binding: FragmentStatsBinding? = null
private val model by viewModels<StatsViewModel>()
private var currentStats: Stats? = null
private var hasFinalValues: Boolean = false
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentStatsBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val binding = binding!!
binding.errorView.visibility = View.GONE
binding.errorView.setButtonClickListener { loadStats() }
// set some views invisible so they can be animated in once stats are computed
binding.textViewShowsFinished.visibility = View.INVISIBLE
binding.progressBarShowsFinished.visibility = View.INVISIBLE
binding.textViewShowsWithNextEpisode.visibility = View.INVISIBLE
binding.progressBarShowsWithNextEpisode.visibility = View.INVISIBLE
binding.textViewShowsContinuing.visibility = View.INVISIBLE
binding.progressBarShowsContinuing.visibility = View.INVISIBLE
binding.textViewEpisodesWatched.visibility = View.INVISIBLE
binding.progressBarEpisodesWatched.visibility = View.INVISIBLE
binding.textViewEpisodesRuntime.visibility = View.INVISIBLE
binding.textViewMoviesWatchlist.visibility = View.INVISIBLE
binding.textViewMoviesWatchlistRuntime.visibility = View.INVISIBLE
binding.progressBarMoviesWatched.visibility = View.INVISIBLE
binding.textViewMoviesWatched.visibility = View.INVISIBLE
binding.textViewMoviesWatchedRuntime.visibility = View.INVISIBLE
binding.progressBarMoviesCollection.visibility = View.INVISIBLE
binding.textViewMoviesCollection.visibility = View.INVISIBLE
binding.textViewMoviesCollectionRuntime.visibility = View.INVISIBLE
// set up long-press to copy text to clipboard (d-pad friendly vs text selection)
binding.textViewShows.copyTextToClipboardOnLongClick()
binding.textViewShowsFinished.copyTextToClipboardOnLongClick()
binding.textViewShowsWithNextEpisode.copyTextToClipboardOnLongClick()
binding.textViewShowsContinuing.copyTextToClipboardOnLongClick()
binding.textViewEpisodes.copyTextToClipboardOnLongClick()
binding.textViewEpisodesWatched.copyTextToClipboardOnLongClick()
binding.textViewEpisodesRuntime.copyTextToClipboardOnLongClick()
binding.textViewMovies.copyTextToClipboardOnLongClick()
binding.textViewMoviesWatchlist.copyTextToClipboardOnLongClick()
binding.textViewMoviesWatchlistRuntime.copyTextToClipboardOnLongClick()
binding.textViewMoviesWatched.copyTextToClipboardOnLongClick()
binding.textViewMoviesWatchedRuntime.copyTextToClipboardOnLongClick()
binding.textViewMoviesCollection.copyTextToClipboardOnLongClick()
binding.textViewMoviesCollectionRuntime.copyTextToClipboardOnLongClick()
model.statsData.observe(viewLifecycleOwner) { this.handleStatsUpdate(it) }
requireActivity().addMenuProvider(
optionsMenuProvider,
viewLifecycleOwner,
Lifecycle.State.RESUMED
)
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
private val optionsMenuProvider = object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
menuInflater.inflate(R.menu.stats_menu, menu)
menu.findItem(R.id.menu_action_stats_filter_specials).isChecked =
DisplaySettings.isHidingSpecials(requireContext())
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
when (menuItem.itemId) {
R.id.menu_action_stats_share -> {
shareStats()
return true
}
R.id.menu_action_stats_filter_specials -> {
PreferenceManager.getDefaultSharedPreferences(requireContext()).edit()
.putBoolean(DisplaySettings.KEY_HIDE_SPECIALS, !menuItem.isChecked)
.apply()
requireActivity().invalidateOptionsMenu()
loadStats()
return true
}
else -> return false
}
}
}
private fun loadStats() {
model.hideSpecials.value = DisplaySettings.isHidingSpecials(requireContext())
}
private fun handleStatsUpdate(event: StatsUpdateEvent) {
if (!isAdded) {
return
}
currentStats = event.stats
hasFinalValues = event.finalValues
updateStats(event.stats, event.finalValues, event.successful)
}
private fun updateStats(
stats: Stats, hasFinalValues: Boolean,
successful: Boolean
) {
val binding = binding ?: return
// display error if not all stats could be calculated
binding.errorView.isGone = successful
val format = NumberFormat.getIntegerInstance()
// all shows
binding.textViewShows.text = format.format(stats.shows.toLong())
// shows finished
binding.progressBarShowsFinished.apply {
max = stats.shows
progress = stats.showsFinished
visibility = View.VISIBLE
}
binding.textViewShowsFinished.apply {
text = getString(
R.string.shows_finished,
format.format(stats.showsFinished.toLong())
)
visibility = View.VISIBLE
}
// shows with next episodes
binding.progressBarShowsWithNextEpisode.apply {
max = stats.shows
progress = stats.showsWithNextEpisodes
visibility = View.VISIBLE
}
binding.textViewShowsWithNextEpisode.apply {
text = getString(
R.string.shows_with_next,
format.format(stats.showsWithNextEpisodes.toLong())
)
visibility = View.VISIBLE
}
// continuing shows
binding.progressBarShowsContinuing.apply {
max = stats.shows
progress = stats.showsContinuing
visibility = View.VISIBLE
}
binding.textViewShowsContinuing.text = getString(
R.string.shows_continuing,
format.format(stats.showsContinuing.toLong())
)
binding.textViewShowsContinuing.visibility = View.VISIBLE
// all episodes
binding.textViewEpisodes.text = format.format(stats.episodes.toLong())
// watched episodes
binding.progressBarEpisodesWatched.max = stats.episodes
binding.progressBarEpisodesWatched.progress = stats.episodesWatched
binding.progressBarEpisodesWatched.visibility = View.VISIBLE
binding.textViewEpisodesWatched.text = getString(
R.string.episodes_watched,
format.format(stats.episodesWatched.toLong())
)
binding.textViewEpisodesWatched.visibility = View.VISIBLE
// episode runtime
var watchedDuration = getTimeDuration(stats.episodesWatchedRuntime)
if (!hasFinalValues) {
// showing minimum (= not the final value)
watchedDuration = "> $watchedDuration"
}
binding.textViewEpisodesRuntime.text = watchedDuration
binding.textViewEpisodesRuntime.visibility = View.VISIBLE
binding.progressBarEpisodesRuntime.visibility = if (successful)
if (hasFinalValues) View.GONE else View.VISIBLE
else
View.GONE
// movies
binding.textViewMovies.text = format.format(stats.movies.toLong())
// watched movies
binding.progressBarMoviesWatched.apply {
max = stats.movies
progress = stats.moviesWatched
visibility = View.VISIBLE
}
binding.textViewMoviesWatched.apply {
text = getString(
R.string.movies_watched_format,
format.format(stats.moviesWatched.toLong())
)
visibility = View.VISIBLE
}
binding.textViewMoviesWatchedRuntime.apply {
text = getTimeDuration(stats.moviesWatchedRuntime)
visibility = View.VISIBLE
}
// movies in watchlist
binding.textViewMoviesWatchlist.apply {
text = getString(
R.string.movies_on_watchlist,
format.format(stats.moviesWatchlist.toLong())
)
visibility = View.VISIBLE
}
binding.textViewMoviesWatchlistRuntime.apply {
text = getTimeDuration(stats.moviesWatchlistRuntime)
visibility = View.VISIBLE
}
// movies in collection
binding.progressBarMoviesCollection.apply {
max = stats.movies
progress = stats.moviesCollection
visibility = View.VISIBLE
}
binding.textViewMoviesCollection.apply {
text = getString(R.string.stats_in_collection_format, stats.moviesCollection)
visibility = View.VISIBLE
}
binding.textViewMoviesCollectionRuntime.apply {
text = getTimeDuration(stats.moviesCollectionRuntime)
visibility = View.VISIBLE
}
}
private fun getTimeDuration(duration: Long): String {
var durationCalc = duration
val days = durationCalc / DateUtils.DAY_IN_MILLIS
durationCalc %= DateUtils.DAY_IN_MILLIS
val hours = durationCalc / DateUtils.HOUR_IN_MILLIS
durationCalc %= DateUtils.HOUR_IN_MILLIS
val minutes = durationCalc / DateUtils.MINUTE_IN_MILLIS
val result = StringBuilder()
if (days != 0L) {
result.append(
resources.getQuantityString(
R.plurals.days_plural, days.toInt(),
days.toInt()
)
)
}
if (hours != 0L) {
if (days != 0L) {
result.append(" ")
}
result.append(
resources.getQuantityString(
R.plurals.hours_plural, hours.toInt(),
hours.toInt()
)
)
}
if (minutes != 0L || days == 0L && hours == 0L) {
if (days != 0L || hours != 0L) {
result.append(" ")
}
result.append(
resources.getQuantityString(
R.plurals.minutes_plural,
minutes.toInt(),
minutes.toInt()
)
)
}
return result.toString()
}
private fun shareStats() {
val currentStats = this.currentStats ?: return
val format = NumberFormat.getIntegerInstance()
val shows = format.format(currentStats.shows.toLong())
val showsWithNext = getString(
R.string.shows_with_next,
format.format(currentStats.showsWithNextEpisodes.toLong())
)
val showsContinuing = getString(
R.string.shows_continuing,
format.format(currentStats.showsContinuing.toLong())
)
val showsFinished = getString(
R.string.shows_finished,
format.format(currentStats.showsFinished.toLong())
)
val episodes = format.format(currentStats.episodes.toLong())
val episodesWatched = getString(
R.string.episodes_watched,
format.format(currentStats.episodesWatched.toLong())
)
val showStats =
"${getString(R.string.app_name)} ${getString(R.string.statistics)}\n\n" +
"${getString(R.string.shows)}\n" +
"$shows\n" +
"$showsWithNext\n" +
"$showsContinuing\n" +
"$showsFinished\n\n" +
"${getString(R.string.episodes)}\n" +
"$episodes\n" +
"$episodesWatched\n"
val statsString = StringBuilder(showStats)
if (currentStats.episodesWatchedRuntime != 0L) {
var watchedDuration = getTimeDuration(currentStats.episodesWatchedRuntime)
if (!hasFinalValues) {
// showing minimum (= not the final value)
watchedDuration = "> $watchedDuration"
}
statsString.append("$watchedDuration\n")
}
statsString.append("\n")
// movies
val movies = format.format(currentStats.movies.toLong())
val moviesWatchlist = getString(
R.string.movies_on_watchlist,
format.format(currentStats.moviesWatchlist.toLong())
)
val moviesWatched = getString(
R.string.movies_watched_format,
format.format(currentStats.moviesWatched.toLong())
)
val moviesCollection = getString(
R.string.stats_in_collection_format,
currentStats.moviesCollection
)
val moviesWatchlistRuntime = getTimeDuration(currentStats.moviesWatchlistRuntime)
val moviesWatchedRuntime = getTimeDuration(currentStats.moviesWatchedRuntime)
val moviesCollectionRuntime = getTimeDuration(currentStats.moviesCollectionRuntime)
val movieStats = "${getString(R.string.movies)}\n" +
"$movies\n" +
"$moviesWatched\n" +
"$moviesWatchedRuntime\n" +
"$moviesWatchlist\n" +
"$moviesWatchlistRuntime\n" +
"$moviesCollection\n" +
"$moviesCollectionRuntime\n"
statsString.append(movieStats)
ShareUtils.startShareIntentChooser(activity, statsString.toString(), R.string.share)
}
}
| apache-2.0 |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/news/NewsFeedViewModel.kt | 1 | 1635 | package com.github.premnirmal.ticker.news
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.github.premnirmal.ticker.model.FetchResult
import com.github.premnirmal.ticker.network.NewsProvider
import com.github.premnirmal.ticker.news.NewsFeedItem.ArticleNewsFeed
import com.github.premnirmal.ticker.news.NewsFeedItem.TrendingStockNewsFeed
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class NewsFeedViewModel @Inject constructor(
private val newsProvider: NewsProvider
): ViewModel() {
val newsFeed: LiveData<FetchResult<List<NewsFeedItem>>>
get() = _newsFeed
private val _newsFeed = MutableLiveData<FetchResult<List<NewsFeedItem>>>()
fun fetchNews(forceRefresh: Boolean = false) {
viewModelScope.launch {
val news = newsProvider.fetchMarketNews(useCache = !forceRefresh)
val trending = newsProvider.fetchTrendingStocks(useCache = !forceRefresh)
if (news.wasSuccessful) {
val data = ArrayList<NewsFeedItem>()
withContext(Dispatchers.Default) {
data.addAll(news.data.map { ArticleNewsFeed(it) })
if (trending.wasSuccessful) {
val taken = trending.data.take(6)
data.add(0, TrendingStockNewsFeed(taken))
}
}
_newsFeed.value = FetchResult.success(data)
} else {
_newsFeed.value = FetchResult.failure(news.error)
}
}
}
} | gpl-3.0 |
wizardofos/Protozoo | server/repo/src/main/kotlin/org/protozoo/server/repo/RepoResource.kt | 1 | 2362 | package org.protozoo.server.repo
import org.osgi.service.component.annotations.*
import org.protozoo.server.api.RestService
import org.protozoo.system.repo.Repository
import javax.ws.rs.GET
import javax.ws.rs.OPTIONS
import javax.ws.rs.Produces
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
/**
* This REST service represents the Protozoo
* component repository and only gets activated
* when the reference can be resolved
*/
@Component(
name = "RepositoryResource",
service = arrayOf(RestService),
scope = ServiceScope.PROTOTYPE,
enabled = true,
immediate = false
)
@Produces(MediaType.APPLICATION_JSON)
class RepoResource : RestService {
private var repo: Repository? = null
@GET
fun getAll(): Response {
println("Components: " + this + ", " + this.repo)
if (repo != null) {
return Response
.ok()
.entity(repo?.getAll())
.header("Access-Control-Allow-Origin", "*")
.build()
} else {
return Response
.serverError()
.entity("Repository not initialized")
.build()
}
}
@OPTIONS
fun getCors(): Response {
return Response
.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE")
.header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Content-Type")
.header("Access-Control-Max-Age", 86400)
.type("text/plain")
.build()
}
@Activate
fun activate() {
println("Repository resource activated " + this)
}
@Deactivate
fun deactivate() {
println("Repository resource deactivated " + this)
}
@Reference(
name = "repo",
service = Repository::class,
policy = ReferencePolicy.DYNAMIC
)
fun bindRepo(repo: Repository) {
println("Bind repository resource " + this)
println("Setting reference to repository " + repo)
this.repo = repo
}
fun unbindRepo(repo: Repository) {
println("Unbind repository resource " + this)
this.repo = repo
}
} | mit |
RP-Kit/RPKit | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/discord/DiscordMessageCallback.kt | 1 | 135 | package com.rpkit.chat.bukkit.discord
fun interface DiscordMessageCallback {
operator fun invoke(discordMessage: DiscordMessage)
} | apache-2.0 |
arcao/Geocaching4Locus | app/src/main/java/com/arcao/feedback/collector/ConstantsCollector.kt | 1 | 936 | package com.arcao.feedback.collector
import java.util.Arrays
class ConstantsCollector(private val source: Class<*>, private val prefix: String) : Collector() {
override val name: String
get() = "$prefix CONSTANTS"
override suspend fun collect(): String {
val result = StringBuilder()
source.fields.forEach { field ->
result.append(field.name).append("=")
try {
result.append(
when (val value = field.get(null)) {
is Array<*> -> Arrays.toString(value)
else -> value?.toString()
}
)
} catch (e: IllegalArgumentException) {
result.append("N/A")
} catch (e: IllegalAccessException) {
result.append("N/A")
}
result.append("\n")
}
return result.toString()
}
}
| gpl-3.0 |
RP-Kit/RPKit | bukkit/rpk-classes-bukkit/src/main/kotlin/com/rpkit/classes/bukkit/listener/RPKCharacterSwitchListener.kt | 1 | 1117 | package com.rpkit.classes.bukkit.listener
import com.rpkit.characters.bukkit.event.character.RPKBukkitCharacterSwitchEvent
import com.rpkit.classes.bukkit.classes.RPKClassService
import com.rpkit.core.service.Services
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
class RPKCharacterSwitchListener : Listener {
@EventHandler
fun onCharacterSwitch(event: RPKBukkitCharacterSwitchEvent) {
val classService = Services[RPKClassService::class.java] ?: return
val newCharacter = event.character
if (newCharacter != null) {
val `class` = classService.loadClass(newCharacter).join()
if (`class` != null) {
classService.loadExperience(newCharacter, `class`).join()
}
}
val oldCharacter = event.fromCharacter
if (oldCharacter != null) {
val `class` = classService.getClass(oldCharacter).join()
if (`class` != null) {
classService.unloadExperience(oldCharacter, `class`)
}
classService.unloadClass(oldCharacter)
}
}
} | apache-2.0 |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/gpaCalculator/fragment/ModuleListFragment.kt | 1 | 8851 | package com.itachi1706.cheesecakeutilities.modules.gpaCalculator.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseReference
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.AddModuleActivity
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.GpaCalcFirebaseUtils
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.GpaRecyclerAdapter
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.MainViewActivity
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaInstitution
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaModule
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaRecycler
import com.itachi1706.cheesecakeutilities.modules.gpaCalculator.objects.GpaScoring
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.cheesecakeutilities.util.FirebaseValueEventListener
import com.itachi1706.helperlib.helpers.LogHelper
/**
* Semester List View
*/
class ModuleListFragment : BaseGpaFragment() {
private val state = MainViewActivity.STATE_MODULE
private val modules: ArrayList<GpaModule> = ArrayList()
private var selectedInstitutionString: String? = null
private var selectedInstitutionType: String? = null
private var selectedSemesterKey: String? = null
private var selectedInstitution: GpaInstitution? = null
private var scoreObject: GpaScoring? = null
override fun getLogTag(): String { return TAG }
override fun getState(): Int { return state }
override fun evaluateToCont(v: View): Boolean {
selectedInstitutionString = arguments?.getString("selection")
selectedSemesterKey = arguments?.getString("semester")
if (selectedInstitutionString == null || selectedSemesterKey == null) {
LogHelper.e(TAG, "Institution/Semester not selected!")
Snackbar.make(v, "An error has occurred. (Institution/Semester not found)", Snackbar.LENGTH_LONG).show()
callback?.goBack()
return false
}
selectedInstitutionType = arguments?.getString("type")
return true
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val v = super.onCreateView(inflater, container, savedInstanceState)
adapter.setOnClickListener(View.OnClickListener { view ->
val viewHolder = view.tag as GpaRecyclerAdapter.GpaViewHolder
val pos = viewHolder.adapterPosition
val moduleSelected = modules[pos]
// FUTURE_TODO: Maybe swap edit to a screen with all the module information
startActivity(Intent(context, AddModuleActivity::class.java).apply {
putExtra("userid", callback?.getUserId())
putExtra("institute", selectedInstitutionString)
putExtra("key", selectedSemesterKey)
putExtra("editmode", moduleSelected.courseCode)
})
})
adapter.setOnCreateContextMenuListener(View.OnCreateContextMenuListener { menu, view, _ ->
// Get selected institution
val viewHolder = view.tag as GpaRecyclerAdapter.GpaViewHolder
if (!initContextSelectMode(viewHolder.adapterPosition)) return@OnCreateContextMenuListener // Do nothing
menu.setHeaderTitle("${moduleContextSel!!.name} [${moduleContextSel!!.courseCode}]")
activity?.menuInflater?.inflate(R.menu.context_menu_editdelete, menu)
})
// Get institution name to update title
selectedInstitution = callback?.getInstitution()
updateActionBar()
return v
}
private var moduleContextSel: GpaModule? = null
override fun onContextItemSelected(item: MenuItem): Boolean {
LogHelper.d(TAG, "Context Item Selected")
if (moduleContextSel == null) return false
return when (item.itemId) {
R.id.menu_edit -> edit(null)
R.id.menu_delete -> delete(null)
else -> super.onContextItemSelected(item)
}
}
override fun initContextSelectMode(position: Int): Boolean {
moduleContextSel = modules[position]
if (moduleContextSel == null) return false
return true
}
override fun edit(position: Int?): Boolean {
if (position != null) if (!initContextSelectMode(position)) return false
startActivity(Intent(context, AddModuleActivity::class.java).apply {
putExtra("userid", callback?.getUserId())
putExtra("institute", selectedInstitutionString)
putExtra("key", selectedSemesterKey)
putExtra("editmode", moduleContextSel!!.courseCode)
})
return true
}
override fun delete(position: Int?): Boolean {
if (position != null) if (!initContextSelectMode(position)) return false
val moduleToDelete = moduleContextSel!!.copy()
val data = getPath() ?: return false
data.child(moduleToDelete.courseCode).removeValue()
Snackbar.make(view!!, "Module Deleted", Snackbar.LENGTH_LONG).setAction("Undo") { v ->
data.child(moduleToDelete.courseCode).setValue(moduleToDelete)
Snackbar.make(v, "Delete undone", Snackbar.LENGTH_SHORT).show()
}.show()
return true
}
private fun getPath(): DatabaseReference? {
return callback?.getUserData()?.child(selectedInstitutionString!!)?.child(GpaCalcFirebaseUtils.FB_REC_SEMESTER)
?.child(selectedSemesterKey!!)?.child(GpaCalcFirebaseUtils.FB_REC_MODULE)
}
override fun onStart() {
super.onStart()
if (selectedInstitutionString == null) return // Don't do anything, an error had occurred already
scoreObject = callback?.getScoreMap()!![selectedInstitutionType]
updateActionBar()
LogHelper.i(TAG, "Registering Module Firebase DB Listener")
listener = getPath()?.addValueEventListener(object: FirebaseValueEventListener(TAG, "loadModuleList"){
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (callback?.getCurrentState() != state) return
LogHelper.i(TAG, "Processing updated modules...")
modules.clear()
if (!dataSnapshot.hasChildren()) return
dataSnapshot.children.forEach {
modules.add(it.getValue(GpaModule::class.java)!!)
}
LogHelper.i(TAG, "Number of Modules ($selectedInstitutionString:$selectedSemesterKey): ${modules.size}")
modules.sortBy { it.courseCode }
modulesProcessAndUpdate()
}
})
}
private fun modulesProcessAndUpdate() {
val list: ArrayList<GpaRecycler> = ArrayList()
modules.forEach {
val score = when {
it.gradeTier == -1 -> "-"
scoreObject == null -> "???"
it.passFail -> scoreObject!!.passtier!![it.gradeTier].name
else -> scoreObject!!.gradetier[it.gradeTier].name
}
val finalGrade = if (it.gradeTier == -1) "???" else if (!it.passFail) scoreObject!!.gradetier[it.gradeTier].value.toString() else
if (scoreObject!!.passtier!![it.gradeTier].value > 0) "P" else "F"
list.add(GpaRecycler(it.name, if (scoreObject?.type == "gpa") "${it.courseCode} | Credits: ${it.credits} ${selectedInstitution?.creditName}" else it.courseCode,
grade=score, gradeColor = GpaCalcFirebaseUtils.getGpaColor(finalGrade, scoreObject, context), color = it.color))
}
updateActionBar()
adapter.update(list)
adapter.notifyDataSetChanged()
}
private fun updateActionBar() {
LogHelper.d(TAG, "updateActionBar()")
var subtitle: String? = null
var title: String? = null
if (scoreObject != null) {
subtitle = if (selectedInstitution != null) "${selectedInstitution!!.semester[selectedSemesterKey]?.name} | " else "Unknown Semester | "
subtitle += if (scoreObject!!.type == "count") "Score" else "GPA"
subtitle += ": ${if (selectedInstitution != null) selectedInstitution!!.semester[selectedSemesterKey]?.gpa else "Unknown"}"
}
if (selectedInstitution != null) title = "${selectedInstitution!!.name} (${selectedInstitution!!.shortName})"
callback?.updateActionBar(title, subtitle)
}
companion object {
private const val TAG = "GpaCalcModuleList"
}
}
| mit |
shchurov/gitter-kotlin-client | app/src/test/kotlin/com/github/shchurov/gitterclient/unit_tests/tests/CheckAuthInteractorTest.kt | 1 | 1146 | package com.github.shchurov.gitterclient.unit_tests.tests
import com.github.shchurov.gitterclient.data.preferences.Preferences
import com.github.shchurov.gitterclient.domain.interactors.CheckAuthInteractor
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.runners.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class CheckAuthInteractorTest {
private lateinit var interactor: CheckAuthInteractor
@Mock private lateinit var preferences: Preferences
@Before
fun setUp() {
interactor = CheckAuthInteractor(preferences)
}
@Test
fun testAuthorized() {
`when`(preferences.getGitterAccessToken())
.thenReturn("access_token")
val real = interactor.isAuthorized()
assertTrue(real)
}
@Test
fun notAuthorized() {
`when`(preferences.getGitterAccessToken())
.thenReturn(null)
val real = interactor.isAuthorized()
assertFalse(real)
}
} | apache-2.0 |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/explore/depictions/parent/PageableParentDepictionsDataSourceTest.kt | 6 | 1084 | package fr.free.nrw.commons.explore.depictions.parent
import com.nhaarman.mockitokotlin2.whenever
import depictedItem
import fr.free.nrw.commons.explore.paging.LiveDataConverter
import fr.free.nrw.commons.mwapi.OkHttpJsonApiClient
import io.reactivex.Single
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class PageableParentDepictionsDataSourceTest {
@Mock
lateinit var okHttpJsonApiClient: OkHttpJsonApiClient
@Mock
lateinit var liveDataConverter: LiveDataConverter
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
}
@Test
fun `loadFunction loads from api`() {
val dataSource =
PageableParentDepictionsDataSource(liveDataConverter, okHttpJsonApiClient)
dataSource.onQueryUpdated("test")
whenever(okHttpJsonApiClient.getParentDepictions("test", 0, 1))
.thenReturn(Single.just(listOf(depictedItem())))
Assert.assertEquals(dataSource.loadFunction(1, 0), listOf(depictedItem()))
}
}
| apache-2.0 |
quarck/CalendarNotification | app/src/main/java/com/github/quarck/calnotify/notification/NotificationActionSnoozeService.kt | 1 | 4736 | //
// Calendar Notifications Plus
// Copyright (C) 2016 Sergey Parshin ([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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.notification
import android.app.IntentService
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.widget.Toast
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.R
import com.github.quarck.calnotify.Settings
import com.github.quarck.calnotify.app.ApplicationController
import com.github.quarck.calnotify.logs.DevLog
import com.github.quarck.calnotify.textutils.EventFormatter
//import com.github.quarck.calnotify.logs.Logger
import com.github.quarck.calnotify.ui.UINotifier
class DisplayToast(private val context: Context, internal var text: String) : Runnable {
override fun run() {
Toast.makeText(context, text, Toast.LENGTH_LONG).show()
}
}
class NotificationActionSnoozeService : IntentService("NotificationActionSnoozeService") {
var handler = Handler()
override fun onHandleIntent(intent: Intent?) {
DevLog.debug(LOG_TAG, "onHandleIntent")
if (intent != null) {
val isSnoozeAll = intent.getBooleanExtra(Consts.INTENT_SNOOZE_ALL_KEY, false)
val isSnoozeAllCollapsed = intent.getBooleanExtra(Consts.INTENT_SNOOZE_ALL_COLLAPSED_KEY, false)
if (isSnoozeAll){
DevLog.info(LOG_TAG, "Snooze all from notification request")
val snoozeDelay = intent.getLongExtra(Consts.INTENT_SNOOZE_PRESET, Settings(this).snoozePresets[0])
if (ApplicationController.snoozeAllEvents(this, snoozeDelay, false, true) != null) {
DevLog.info(LOG_TAG, "all visible snoozed by $snoozeDelay")
onSnoozedBy(snoozeDelay)
}
UINotifier.notify(this, true)
}
else if (isSnoozeAllCollapsed) {
DevLog.info(LOG_TAG, "Snooze all collapsed from notification request")
val snoozeDelay = intent.getLongExtra(Consts.INTENT_SNOOZE_PRESET, Settings(this).snoozePresets[0])
if (ApplicationController.snoozeAllCollapsedEvents(this, snoozeDelay, false, true) != null) {
DevLog.info(LOG_TAG, "all collapsed snoozed by $snoozeDelay")
onSnoozedBy(snoozeDelay)
}
UINotifier.notify(this, true)
}
else {
val notificationId = intent.getIntExtra(Consts.INTENT_NOTIFICATION_ID_KEY, -1)
val eventId = intent.getLongExtra(Consts.INTENT_EVENT_ID_KEY, -1)
val instanceStartTime = intent.getLongExtra(Consts.INTENT_INSTANCE_START_TIME_KEY, -1)
val snoozeDelay = intent.getLongExtra(Consts.INTENT_SNOOZE_PRESET, Settings(this).snoozePresets[0])
if (notificationId != -1 && eventId != -1L && instanceStartTime != -1L) {
if (ApplicationController.snoozeEvent(this, eventId, instanceStartTime, snoozeDelay) != null) {
DevLog.info(LOG_TAG, "event $eventId / $instanceStartTime snoozed by $snoozeDelay")
onSnoozedBy(snoozeDelay)
}
UINotifier.notify(this, true)
} else {
DevLog.error(LOG_TAG, "notificationId=$notificationId, eventId=$eventId, or type is null")
}
}
}
else {
DevLog.error(LOG_TAG, "Intent is null!")
}
ApplicationController.cleanupEventReminder(this)
}
private fun onSnoozedBy(duration: Long) {
val formatter = EventFormatter(this)
val format = getString(R.string.event_snoozed_by)
val text = String.format(format, formatter.formatTimeDuration(duration, 60L))
handler.post(DisplayToast(this, text))
}
companion object {
private const val LOG_TAG = "NotificationActionSnoozeService"
}
}
| gpl-3.0 |
ujpv/intellij-rust | src/main/kotlin/org/rust/utils/Utils.kt | 1 | 2686 | package org.rust.utils
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.component1
import com.intellij.openapi.util.component2
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import com.intellij.util.download.DownloadableFileService
import kotlin.reflect.KProperty
/**
* Helper disposing [d] upon completing the execution of the [block]
*
* @d Target `Disposable` to be disposed upon completion of the @block
* @block Target block to be run prior to disposal of @d
*/
fun <T> using(d: Disposable, block: () -> T): T {
try {
return block()
} finally {
d.dispose()
}
}
/**
* Helper disposing [d] upon completing the execution of the [block] (under the [d])
*
* @d Target `Disposable` to be disposed upon completion of the @block
* @block Target block to be run prior to disposal of @d
*/
fun <D : Disposable, T> usingWith(d: D, block: (D) -> T): T {
try {
return block(d)
} finally {
d.dispose()
}
}
/**
* Cached value invalidated on any PSI modification
*/
fun <E : PsiElement, T> psiCached(provider: E.() -> CachedValueProvider<T>): PsiCacheDelegate<E, T> = PsiCacheDelegate(provider)
class PsiCacheDelegate<E : PsiElement, T>(val provider: E.() -> CachedValueProvider<T>) {
operator fun getValue(element: E, property: KProperty<*>): T {
return CachedValuesManager.getCachedValue(element, element.provider())
}
}
/**
* Extramarital son of `sequenceOf` & `listOfNotNull`
*/
fun <T : Any> sequenceOfNotNull(vararg elements: T): Sequence<T> = listOfNotNull(*elements).asSequence()
fun <T : Any> sequenceOfNotNull(element: T?): Sequence<T> = if (element != null) sequenceOf(element) else emptySequence()
/**
* Downloads file residing at [url] with the name [fileName] and saves it to [destination] folder
*/
fun download(url: String, fileName: String, destination: VirtualFile): VirtualFile? {
val downloadService = DownloadableFileService.getInstance()
val downloader = downloadService.createDownloader(listOf(downloadService.createFileDescription(url, fileName)), fileName)
val downloadTo = VfsUtilCore.virtualToIoFile(destination)
val (file, @Suppress("UNUSED_VARIABLE") d) = downloader.download(downloadTo).single()
return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file)
}
/**
* XXX
*/
fun <T> safely(run: () -> T, finally: () -> Unit): T = usingWith(Disposable { finally() }) { run() }
| mit |
CPRTeam/CCIP-Android | app/src/main/java/app/opass/ccip/util/ConfScheduleDeserializer.kt | 1 | 2539 | package app.opass.ccip.util
import app.opass.ccip.model.*
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.reflect.TypeToken
import org.intellij.lang.annotations.Language
import java.lang.reflect.Type
class ConfScheduleDeserializer : JsonDeserializer<ConfSchedule> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext): ConfSchedule? {
json ?: return null
val obj = json.asJsonObject
if (obj.size() == 0) return null
val speakers = deserializeList<Speaker>(obj["speakers"], context)
val sessionTypes = deserializeList<SessionType>(obj["session_types"], context)
val rooms = deserializeList<Room>(obj["rooms"], context)
val sessionTags = deserializeList<SessionTag>(obj["tags"], context)
val sessions = deserializeList<SessionTemp>(obj["sessions"], context).map { session ->
Session(
id = session.id,
type = sessionTypes.find { session.type == it.id },
room = rooms.find { session.room == it.id }!!,
speakers = session.speakers.mapNotNull { id -> speakers.find { it.id == id } },
tags = session.tags.mapNotNull { id -> sessionTags.find { it.id == id } },
start = session.start,
end = session.end,
zh = session.zh,
en = session.en,
qa = session.qa,
slide = session.slide,
broadcast = session.broadcast,
coWrite = session.coWrite,
live = session.live,
record = session.record,
language = session.language
)
}
return ConfSchedule(sessions, speakers, sessionTypes, rooms, sessionTags)
}
private inline fun <reified T> deserializeList(json: JsonElement, context: JsonDeserializationContext): List<T> {
return context.deserialize(json, TypeToken.getParameterized(List::class.java, T::class.java).type)
}
}
data class SessionTemp(
val id: String,
val type: String,
val room: String,
val start: String,
val end: String,
val zh: Zh,
val en: En,
val speakers: List<String>,
val tags: List<String>,
val qa: String?,
val slide: String?,
val broadcast: List<String>?,
val coWrite: String?,
val live: String?,
val record: String?,
val language: String?
)
| gpl-3.0 |
JakeWharton/RxBinding | rxbinding/src/main/java/com/jakewharton/rxbinding4/view/ViewVisibilityConsumer.kt | 1 | 968 | @file:JvmName("RxView")
@file:JvmMultifileClass
package com.jakewharton.rxbinding4.view
import androidx.annotation.CheckResult
import android.view.View
import io.reactivex.rxjava3.functions.Consumer
/**
* An action which sets the visibility property of `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe to free this
* reference.
*
* @param visibilityWhenFalse Visibility to set on a `false` value (`View.INVISIBLE` or
* `View.GONE`).
*/
@CheckResult
@JvmOverloads
fun View.visibility(visibilityWhenFalse: Int = View.GONE): Consumer<in Boolean> {
require(visibilityWhenFalse != View.VISIBLE) {
"Setting visibility to VISIBLE when false would have no effect."
}
require(visibilityWhenFalse == View.INVISIBLE || visibilityWhenFalse == View.GONE) {
"Must set visibility to INVISIBLE or GONE when false."
}
return Consumer { value -> visibility = if (value) View.VISIBLE else visibilityWhenFalse }
}
| apache-2.0 |
salmans/razor-kotlin | src/test/java/chase/TestHelper.kt | 1 | 2502 | package chase
import formula.geometric
import formula.parseTheory
import kotlin.test.assertEquals
import kotlin.test.fail
// Elements
val e_0 = Element(0)
val e_1 = Element(1)
val e_2 = Element(2)
val e_3 = Element(3)
val e_4 = Element(4)
val e_5 = Element(5)
val e_6 = Element(6)
val e_7 = Element(7)
val e_8 = Element(8)
val e_9 = Element(9)
// Witness Constants
val _a = WitnessConst("a")
val _a1 = WitnessConst("a1")
val _a2 = WitnessConst("a2")
val _a3 = WitnessConst("a3")
val _a4 = WitnessConst("a4")
val _b = WitnessConst("b")
val _b1 = WitnessConst("b1")
val _b2 = WitnessConst("b2")
val _b3 = WitnessConst("b3")
val _b4 = WitnessConst("b4")
val _c = WitnessConst("c")
val _c1 = WitnessConst("c1")
val _c2 = WitnessConst("c2")
val _c3 = WitnessConst("c3")
val _c4 = WitnessConst("c4")
val _d = WitnessConst("d")
val _d1 = WitnessConst("d1")
val _d2 = WitnessConst("d2")
val _d3 = WitnessConst("d3")
val _d4 = WitnessConst("d4")
// Relations
val _E = Rel("E")
val _P = Rel("P")
val _Q = Rel("Q")
val _R = Rel("R")
val _S = Rel("S")
const val CORE_TEST_COUNT = 42
const val BOUNDED_TEST_COUNT = 2
const val STRESS_TEST_COUNT = 0
fun assertFailure(errorMessage: String, func: () -> Unit) {
try {
func()
fail("error expected!")
} catch (e: Exception) {
assertEquals(errorMessage, e.message)
}
}
fun solveBasic(source: String): List<Model> {
val geometricTheory = source.parseTheory().geometric()
val sequents = geometricTheory.formulas.map { BasicSequent(it) }
val evaluator = BasicEvaluator()
val selector = TopDownSelector(sequents)
val strategy = FIFOStrategy<BasicSequent>().apply { add(StrategyNode(BasicModel(), selector)) }
return solveAll(strategy, evaluator, null)
}
fun solveDomainBoundedBasic(source: String, bound: Int): List<Model> {
val geometricTheory = source.parseTheory().geometric()
val sequents = geometricTheory.formulas.map { BasicSequent(it) }
val bounder = DomainSizeBounder(bound)
val evaluator = BasicEvaluator()
val selector = TopDownSelector(sequents)
val strategy = FIFOStrategy<BasicSequent>().apply { add(StrategyNode(BasicModel(), selector)) }
return solveAll(strategy, evaluator, bounder)
}
fun printModels(models: List<Model>): String {
return models.joinToString(separator = "\n-- -- -- -- -- -- -- -- -- --\n") { it ->
it.toString() + it.getDomain().joinToString(prefix = "\n", separator = "\n") { e -> "${it.witness(e).joinToString()} -> $e" }
}
} | bsd-3-clause |
LorittaBot/Loritta | web/dashboard/spicy-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/dashboard/frontend/utils/Modal.kt | 1 | 243 | package net.perfectdreams.loritta.cinnamon.dashboard.frontend.utils
import androidx.compose.runtime.Composable
data class Modal(
val title: String,
val body: @Composable () -> (Unit),
val buttons: List<@Composable () -> (Unit)>
) | agpl-3.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/tables/ServerConfigs.kt | 1 | 3085 | package net.perfectdreams.loritta.morenitta.tables
import net.perfectdreams.loritta.morenitta.utils.exposed.array
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.AutoroleConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.EconomyConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.EventLogConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.InviteBlockerConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.LevelConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.MiscellaneousConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.ModerationConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.StarboardConfigs
import net.perfectdreams.loritta.morenitta.tables.servers.moduleconfigs.WelcomerConfigs
import org.jetbrains.exposed.sql.LongColumnType
import org.jetbrains.exposed.sql.ReferenceOption
import org.jetbrains.exposed.sql.TextColumnType
object ServerConfigs : SnowflakeTable() {
val commandPrefix = text("prefix").default("+")
val localeId = text("locale_id").default("default")
val deleteMessageAfterCommand = bool("delete_message_after_command").default(false)
val warnOnMissingPermission = bool("warn_on_missing_permission").default(false)
val warnOnUnknownCommand = bool("warn_on_unknown_command").default(false)
val blacklistedChannels = array<Long>("blacklisted_channels", LongColumnType()).default(arrayOf())
val warnIfBlacklisted = bool("warn_if_blacklisted").default(false)
val blacklistedWarning = text("blacklisted_warning").nullable()
val disabledCommands = array<String>("disabled_commands", TextColumnType()).default(arrayOf())
// val donationKey = optReference("donation_key", DonationKeys)
val donationConfig = optReference("donation_config", DonationConfigs, onDelete = ReferenceOption.CASCADE).index()
val economyConfig = optReference("economy_config", EconomyConfigs, onDelete = ReferenceOption.CASCADE).index()
val levelConfig = optReference("level_config", LevelConfigs, onDelete = ReferenceOption.CASCADE).index()
val starboardConfig = optReference("starboard_config", StarboardConfigs, onDelete = ReferenceOption.CASCADE).index()
val miscellaneousConfig = optReference("miscellaneous_config", MiscellaneousConfigs, onDelete = ReferenceOption.CASCADE).index()
val eventLogConfig = optReference("event_log_config", EventLogConfigs, onDelete = ReferenceOption.CASCADE).index()
val autoroleConfig = optReference("autorole_config", AutoroleConfigs, onDelete = ReferenceOption.CASCADE).index()
val inviteBlockerConfig = optReference("invite_blocker_config", InviteBlockerConfigs, onDelete = ReferenceOption.CASCADE).index()
val welcomerConfig = optReference("welcomer_config", WelcomerConfigs, onDelete = ReferenceOption.CASCADE).index()
val moderationConfig = optReference("moderation_config", ModerationConfigs, onDelete = ReferenceOption.CASCADE).index()
val migrationVersion = integer("migration_version").default(0)
} | agpl-3.0 |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/modules/AutomodModule.kt | 1 | 10732 | package net.perfectdreams.loritta.morenitta.modules
import com.github.benmanes.caffeine.cache.Caffeine
import com.google.common.collect.EvictingQueue
import com.google.common.collect.Queues
import dev.kord.common.entity.Snowflake
import net.perfectdreams.loritta.morenitta.commands.vanilla.administration.AdminUtils
import net.perfectdreams.loritta.morenitta.commands.vanilla.administration.BanCommand
import net.perfectdreams.loritta.morenitta.dao.Profile
import net.perfectdreams.loritta.morenitta.dao.ServerConfig
import net.perfectdreams.loritta.morenitta.events.LorittaMessageEvent
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.morenitta.utils.LorittaPermission
import net.perfectdreams.loritta.morenitta.utils.LorittaUser
import net.perfectdreams.loritta.morenitta.utils.config.EnvironmentType
import net.perfectdreams.loritta.common.locale.BaseLocale
import mu.KotlinLogging
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.User
import net.perfectdreams.loritta.morenitta.LorittaBot
import org.apache.commons.text.similarity.LevenshteinDistance
import java.util.*
import java.util.concurrent.TimeUnit
class AutomodModule(val loritta: LorittaBot) : MessageReceivedModule {
companion object {
val MESSAGES = Caffeine.newBuilder().expireAfterWrite(5L, TimeUnit.MINUTES).build<String, Queue<Message>>().asMap()
const val FRESH_ACCOUNT_TIMEOUT = 604_800_000L
var ANTIRAID_ENABLED = true
var SIMILAR_MESSAGE_MULTIPLIER = 0.0020
var SIMILARITY_THRESHOLD = 7
var IN_ROW_SAME_USER_SIMILAR_SCORE = 0.064
var IN_ROW_DIFFERENT_USER_SIMILAR_SCORE = 0.056
var DISTANCE_MULTIPLIER = 0.02
var ATTACHED_IMAGE_SCORE = 0.015
var SAME_LINK_SCORE = 0.005
var SIMILAR_SAME_AUTHOR_MESSAGE_MULTIPLIER = 0.024
var NO_AVATAR_SCORE = 0.04
var MUTUAL_GUILDS_MULTIPLIER = 0.01
var FRESH_ACCOUNT_DISCORD_MULTIPLIER = 0.00000000004
var FRESH_ACCOUNT_JOINED_MULTIPLIER = 0.00000000013
var QUEUE_SIZE = 50
var BAN_THRESHOLD = 0.75
val COMMON_EMOTES = listOf(
";-;",
";w;",
"uwu",
"owo",
"-.-",
"'-'",
"'='",
";=;",
"-w-",
"e.e",
"e_e",
"p-p",
"q-q",
"p-q",
"q-p",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"oi",
"olá",
"oie",
"oin",
"eu"
)
private val logger = KotlinLogging.logger {}
}
override suspend fun matches(event: LorittaMessageEvent, lorittaUser: LorittaUser, lorittaProfile: Profile?, serverConfig: ServerConfig, locale: BaseLocale): Boolean {
if (lorittaUser.hasPermission(LorittaPermission.BYPASS_AUTO_MOD))
return false
return true
}
override suspend fun handle(event: LorittaMessageEvent, lorittaUser: LorittaUser, lorittaProfile: Profile?, serverConfig: ServerConfig, locale: BaseLocale): Boolean {
if (ANTIRAID_ENABLED && (loritta.config.loritta.antiRaidIds.contains(Snowflake(event.channel.id))) && loritta.config.loritta.environment == EnvironmentType.CANARY) {
val messages = MESSAGES.getOrPut(event.textChannel!!.id) { Queues.synchronizedQueue(EvictingQueue.create<Message>(50)) }
fun calculateRaidingPercentage(wrapper: Message): Double {
var content = wrapper.contentRaw.toLowerCase()
for (emote in AutomodModule.COMMON_EMOTES)
content = content.replace(emote, "")
val pattern = Constants.HTTP_URL_PATTERN
val matcher = pattern.matcher(wrapper.contentRaw)
val urlsDetected = mutableSetOf<String>()
while (matcher.find())
urlsDetected.add(matcher.group(0))
val raider = wrapper.author
var raidingPercentage = 0.0
val verySimilarMessages = mutableListOf<Message>()
var streamFloodCounter = 0
messageLoop@for ((index, message) in messages.reversed().withIndex()) {
val distanceMultiplier = ((AutomodModule.QUEUE_SIZE - index) * AutomodModule.DISTANCE_MULTIPLIER)
if (message.contentRaw.isNotBlank()) {
var compareContent = message.contentRaw.toLowerCase()
for (emote in AutomodModule.COMMON_EMOTES)
compareContent = compareContent.replace(emote, "")
val contentIsBlank = compareContent.isBlank()
val withoutEmoteBlankMultiplier = if (contentIsBlank) 0.3 else 1.0
if (0 > streamFloodCounter)
streamFloodCounter = 0
val isStreamFlood = 3 > streamFloodCounter
val threshold = LevenshteinDistance.getDefaultInstance().apply(compareContent.toLowerCase(), content.toLowerCase())
if (3 >= threshold && wrapper.author.id == message.author.id) { // Vamos melhorar caso exista alguns "one person raider"
verySimilarMessages.add(message)
}
if (5 >= threshold && isStreamFlood) { // Vamos aumentar os pontos caso sejam mensagens parecidas em seguida
// threshold = 0..5
// vamos aumentar as chances caso o conteúdo seja similar
// 0 == * 1
// 1 == * 0.75
// etc
// 5 - 0 = 5
// 5 - 1 = 4
val similarityMultiplier = (5 - Math.min(5, threshold))
raidingPercentage += if (wrapper.author.id == message.author.id) {
AutomodModule.IN_ROW_SAME_USER_SIMILAR_SCORE
} else {
AutomodModule.IN_ROW_DIFFERENT_USER_SIMILAR_SCORE
} * distanceMultiplier * withoutEmoteBlankMultiplier * (similarityMultiplier * 0.2)
// analysis(analysis, "+ Stream Flood (mesmo usuário: ${(wrapper.author.id == message.author.id)}) - Valor atual é $raidingPercentage")
streamFloodCounter--
} else {
streamFloodCounter++
}
val similarMessageScore = distanceMultiplier * AutomodModule.SIMILAR_MESSAGE_MULTIPLIER * (Math.max(0, AutomodModule.SIMILARITY_THRESHOLD - threshold))
raidingPercentage += similarMessageScore
}
if (wrapper.attachments.isNotEmpty() && message.attachments.isNotEmpty()) {
raidingPercentage += AutomodModule.ATTACHED_IMAGE_SCORE * distanceMultiplier
// analysis(analysis, "+ Possui attachments ~ ${AutomodModule.ATTACHED_IMAGE_SCORE} - Valor atual é $raidingPercentage")
// println(">>> ${wrapper.author.id}: ATTACHED_IMAGE_SCORE ${raidingPercentage}")
}
val matcher2 = pattern.matcher(wrapper.contentRaw)
while (matcher2.find()) {
if (urlsDetected.contains(matcher2.group(0))) {
// analysis(analysis, "+ Mesmo link ~ ${AutomodModule.SAME_LINK_SCORE} - Valor atual é $raidingPercentage")
raidingPercentage += distanceMultiplier * AutomodModule.SAME_LINK_SCORE
continue@messageLoop
}
}
}
val similarSameAuthorScore = AutomodModule.SIMILAR_SAME_AUTHOR_MESSAGE_MULTIPLIER * verySimilarMessages.size
// analysis(analysis, "+ similarSameAuthorScore é $similarSameAuthorScore - Valor atual é $raidingPercentage")
raidingPercentage += similarSameAuthorScore
// Caso o usuário não tenha avatar
if (wrapper.author.avatarUrl == null) {
raidingPercentage += AutomodModule.NO_AVATAR_SCORE
// analysis(analysis, "+ Usuário não possui avatar, então iremos adicionar ${AutomodModule.NO_AVATAR_SCORE} a porcentagem - Valor atual é $raidingPercentage")
}
// Caso o usuário esteja em poucos servidores compartilhados, a chance de ser raider é maior
val nonMutualGuildsScore = AutomodModule.MUTUAL_GUILDS_MULTIPLIER * Math.max(5 - raider.mutualGuilds.size, 1)
// analysis(analysis, "+ nonMutualGuildsScore é $nonMutualGuildsScore - Valor atual é $raidingPercentage")
raidingPercentage += nonMutualGuildsScore
// Conta nova no Discord
val newAccountScore = AutomodModule.FRESH_ACCOUNT_DISCORD_MULTIPLIER * Math.max(0, AutomodModule.FRESH_ACCOUNT_TIMEOUT - (System.currentTimeMillis() - wrapper.author.timeCreated.toInstant().toEpochMilli()))
// analysis(analysis, "+ newAccountScore é $nonMutualGuildsScore - Valor atual é $raidingPercentage")
raidingPercentage += newAccountScore
// Conta nova que entrou no servidor
val member = event.member
if (member != null) {
val recentlyJoinedScore = AutomodModule.FRESH_ACCOUNT_JOINED_MULTIPLIER * Math.max(0, AutomodModule.FRESH_ACCOUNT_TIMEOUT - (System.currentTimeMillis() - member.timeJoined.toInstant().toEpochMilli()))
// analysis(analysis, "+ recentlyJoinedScore é $recentlyJoinedScore - Valor atual é $raidingPercentage")
raidingPercentage += recentlyJoinedScore
}
return raidingPercentage
}
val raidingPercentage = calculateRaidingPercentage(event.message)
logger.info("[${event.guild!!.name} -> ${event.channel.name}] ${event.author.id} (${raidingPercentage}% chance de ser raider: ${event.message.contentRaw}")
if (raidingPercentage >= 0.5) {
logger.warn("[${event.guild.name} -> ${event.channel.name}] ${event.author.id} (${raidingPercentage}% chance de ser raider (CHANCE ALTA DEMAIS!): ${event.message.contentRaw}")
}
if (raidingPercentage >= BAN_THRESHOLD) {
logger.info("Aplicando punimentos em ${event.guild.name} -> ${event.channel.name}, causado por ${event.author.id}!")
val settings = AdminUtils.retrieveModerationInfo(loritta, serverConfig)
synchronized(event.guild) {
val alreadyBanned = mutableListOf<User>()
for (storedMessage in messages) {
if (!event.guild.isMember(event.author) || alreadyBanned.contains(storedMessage.author)) // O usuário já pode estar banido
continue
val percentage = calculateRaidingPercentage(storedMessage)
if (percentage >= BAN_THRESHOLD) {
alreadyBanned.add(storedMessage.author)
if (event.guild.selfMember.canInteract(event.member!!)) {
logger.info("Punindo ${storedMessage.author.id} em ${event.guild.name} -> ${event.channel.name} por tentativa de raid! ($percentage%)!")
BanCommand.ban(loritta, settings, event.guild, event.guild.selfMember.user, locale, storedMessage.author, "Tentativa de Raid (Spam/Flood)! Que feio, para que fazer isto? Vá procurar algo melhor para fazer em vez de incomodar outros servidores. ᕙ(⇀‸↼‶)ᕗ", false, 7)
}
}
}
if (!event.guild.isMember(event.author) || alreadyBanned.contains(event.author)) // O usuário já pode estar banido
return true
if (event.guild.selfMember.canInteract(event.member!!)) {
logger.info("Punindo ${event.author.id} em ${event.guild.name} -> ${event.channel.name} por tentativa de raid! ($raidingPercentage%)!")
BanCommand.ban(loritta, settings, event.guild, event.guild.selfMember.user, locale, event.author, "Tentativa de Raid (Spam/Flood)! Que feio, para que fazer isto? Vá procurar algo melhor para fazer em vez de incomodar outros servidores. ᕙ(⇀‸↼‶)ᕗ", false, 7)
}
}
return true
}
messages.add(event.message)
}
return false
}
} | agpl-3.0 |
chrsep/Kingfish | app/src/main/java/com/directdev/portal/models/SessionModel.kt | 1 | 1516 | package com.directdev.portal.models
import com.squareup.moshi.Json
import io.realm.RealmObject
open class SessionModel(
@Json(name = "CLASS_SECTION")
open var classId: String = "N/A", //"LB02"
@Json(name = "COURSE_TITLE_LONG")
open var courseName: String = "N/A", //"Character Building: Agama"
@Json(name = "CRSE_CODE")
open var courseId: String = "N/A", //""COMP6060""
@Json(name = "START_DT")
open var date: String = "N/A", //""2014-09-23 00:00:00.000""
@Json(name = "LOCATION")
open var locationId: String = "N/A", //""COMP6060""
@Json(name = "LOCATION_DESCR")
open var locationName: String = "N/A", //""COMP6060""
@Json(name = "MEETING_TIME_START")
open var startTime: String = "N/A", //""COMP6060""
@Json(name = "MEETING_TIME_END")
open var endTime: String = "N/A", //""COMP6060""
@Json(name = "N_DELIVERY_MODE")
open var deliveryMode: String = "N/A", //""COMP6060""
@Json(name = "N_WEEK_SESSION")
open var weekCount: String = "N/A", //""COMP6060""
@Json(name = "ROOM")
open var room: String = "N/A", //""COMP6060""
@Json(name = "SSR_COMPONENT")
open var typeId: String = "N/A", //""COMP6060""
@Json(name = "SSR_DESCR")
open var typeName: String = "N/A", //""COMP6060""
@Json(name = "SessionIDNum")
open var sessionCount: String = "N/A" //""COMP6060""
) : RealmObject()
| gpl-3.0 |
NoodleMage/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/HistoryLastReadPutResolver.kt | 6 | 2298 | package eu.kanade.tachiyomi.data.database.resolvers
import android.content.ContentValues
import android.support.annotation.NonNull
import com.pushtorefresh.storio.sqlite.StorIOSQLite
import com.pushtorefresh.storio.sqlite.operations.put.PutResult
import com.pushtorefresh.storio.sqlite.queries.Query
import com.pushtorefresh.storio.sqlite.queries.UpdateQuery
import eu.kanade.tachiyomi.data.database.inTransactionReturn
import eu.kanade.tachiyomi.data.database.mappers.HistoryPutResolver
import eu.kanade.tachiyomi.data.database.models.History
import eu.kanade.tachiyomi.data.database.tables.HistoryTable
class HistoryLastReadPutResolver : HistoryPutResolver() {
/**
* Updates last_read time of chapter
*/
override fun performPut(@NonNull db: StorIOSQLite, @NonNull history: History): PutResult = db.inTransactionReturn {
val updateQuery = mapToUpdateQuery(history)
val cursor = db.lowLevel().query(Query.builder()
.table(updateQuery.table())
.where(updateQuery.where())
.whereArgs(updateQuery.whereArgs())
.build())
val putResult: PutResult
try {
if (cursor.count == 0) {
val insertQuery = mapToInsertQuery(history)
val insertedId = db.lowLevel().insert(insertQuery, mapToContentValues(history))
putResult = PutResult.newInsertResult(insertedId, insertQuery.table())
} else {
val numberOfRowsUpdated = db.lowLevel().update(updateQuery, mapToUpdateContentValues(history))
putResult = PutResult.newUpdateResult(numberOfRowsUpdated, updateQuery.table())
}
} finally {
cursor.close()
}
putResult
}
/**
* Creates update query
* @param obj history object
*/
override fun mapToUpdateQuery(obj: History) = UpdateQuery.builder()
.table(HistoryTable.TABLE)
.where("${HistoryTable.COL_CHAPTER_ID} = ?")
.whereArgs(obj.chapter_id)
.build()
/**
* Create content query
* @param history object
*/
fun mapToUpdateContentValues(history: History) = ContentValues(1).apply {
put(HistoryTable.COL_LAST_READ, history.last_read)
}
}
| apache-2.0 |
rectangle-dbmi/Realtime-Port-Authority | app/src/main/java/rectangledbmi/com/pittsburghrealtimetracker/selection/Route.kt | 1 | 3278 | package rectangledbmi.com.pittsburghrealtimetracker.selection
import android.graphics.Color
/**
* This is the object container that contains all information of the buses
*
* Created by epicstar on 9/5/14.
*
* @author Jeremy Jao
* @author Michael Antonacci
*/
class Route
/**
* The main route constructor
* @param route the route number
* @param routeInfo the route info
* @param routeColor the color of the route as an int
*/
(
/**
* This is the route number
*/
val route: String?,
/**
* This is the route's general 3 word summary
*/
val routeInfo: String?,
/**
* This is the color of the route as an int
*/
var routeColor: Int,
/**
* Position of the route in the list
*
* @since 43
*/
private val listPosition: Int,
/**
* Whether or not the route is selected
*/
var isSelected: Boolean) {
/**
* Gets the int color as a hex string from:
* http://stackoverflow.com/questions/4506708/android-convert-color-int-to-hexa-string
*
* @return color as hex-string
*/
val colorAsString: String
get() = String.format("#%06X", 0xFFFFFF and routeColor)
/**
* The non-null constructor of the route and color as a string or hex-string
* @param route the route number
* @param routeInfo the route info
* @param routeColor the color of the route as a string or string-hex
*/
constructor(route: String, routeInfo: String, routeColor: String, listPosition: Int, isSelected: Boolean) : this(route, routeInfo, Color.parseColor(routeColor), listPosition, isSelected)
/**
* Copy constructor for Route objects
* @param route
*/
constructor(route: Route) : this(route.route, route.routeInfo, route.routeColor, route.listPosition, route.isSelected)
/**
* set the route color if a String is fed
* @param routeColor the route color as a String
*/
fun setRouteColor(routeColor: String) {
this.routeColor = Color.parseColor(routeColor)
}
/**
*
* @return true if state is changed to selected
* @since 58
*/
private fun selectRoute(): Boolean {
if (!isSelected) {
isSelected = true
return true
}
return false
}
/**
*
* @return true if state is changed to deselected
* @since 58
*/
private fun deselectRoute(): Boolean {
if (isSelected) {
isSelected = false
return true
}
return false
}
/**
* Toggles the selection to change the state of the route's selection.
*
* @return true if the route becomes selected; false if it becomes unselected
* @since 58
*/
@Suppress("LiftReturnOrAssignment")
fun toggleSelection(): Boolean {
if (isSelected) {
deselectRoute()
return false
} else {
selectRoute()
return true
}
}
/**
* Auto-Generated by Android Studio
* @return String of Route
*/
override fun toString(): String = "$route - $routeInfo\ncolor: $routeColor - $colorAsString"
}
| gpl-3.0 |
cketti/okhttp | okhttp/src/main/kotlin/okhttp3/Cache.kt | 1 | 26484 | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3
import java.io.Closeable
import java.io.File
import java.io.Flushable
import java.io.IOException
import java.security.cert.Certificate
import java.security.cert.CertificateEncodingException
import java.security.cert.CertificateException
import java.security.cert.CertificateFactory
import java.util.NoSuchElementException
import java.util.TreeSet
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.internal.EMPTY_HEADERS
import okhttp3.internal.cache.CacheRequest
import okhttp3.internal.cache.CacheStrategy
import okhttp3.internal.cache.DiskLruCache
import okhttp3.internal.closeQuietly
import okhttp3.internal.concurrent.TaskRunner
import okhttp3.internal.http.HttpMethod
import okhttp3.internal.http.StatusLine
import okhttp3.internal.io.FileSystem
import okhttp3.internal.platform.Platform
import okhttp3.internal.toLongOrDefault
import okio.Buffer
import okio.BufferedSink
import okio.BufferedSource
import okio.ByteString.Companion.decodeBase64
import okio.ByteString.Companion.encodeUtf8
import okio.ByteString.Companion.toByteString
import okio.ForwardingSink
import okio.ForwardingSource
import okio.Sink
import okio.Source
import okio.buffer
/**
* Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and
* bandwidth.
*
* ## Cache Optimization
*
* To measure cache effectiveness, this class tracks three statistics:
*
* * **[Request Count:][requestCount]** the number of HTTP requests issued since this cache was
* created.
* * **[Network Count:][networkCount]** the number of those requests that required network use.
* * **[Hit Count:][hitCount]** the number of those requests whose responses were served by the
* cache.
*
* Sometimes a request will result in a conditional cache hit. If the cache contains a stale copy of
* the response, the client will issue a conditional `GET`. The server will then send either
* the updated response if it has changed, or a short 'not modified' response if the client's copy
* is still valid. Such responses increment both the network count and hit count.
*
* The best way to improve the cache hit rate is by configuring the web server to return cacheable
* responses. Although this client honors all [HTTP/1.1 (RFC 7234)][rfc_7234] cache headers, it
* doesn't cache partial responses.
*
* ## Force a Network Response
*
* In some situations, such as after a user clicks a 'refresh' button, it may be necessary to skip
* the cache, and fetch data directly from the server. To force a full refresh, add the `no-cache`
* directive:
*
* ```
* Request request = new Request.Builder()
* .cacheControl(new CacheControl.Builder().noCache().build())
* .url("http://publicobject.com/helloworld.txt")
* .build();
* ```
*
* If it is only necessary to force a cached response to be validated by the server, use the more
* efficient `max-age=0` directive instead:
*
* ```
* Request request = new Request.Builder()
* .cacheControl(new CacheControl.Builder()
* .maxAge(0, TimeUnit.SECONDS)
* .build())
* .url("http://publicobject.com/helloworld.txt")
* .build();
* ```
*
* ## Force a Cache Response
*
* Sometimes you'll want to show resources if they are available immediately, but not otherwise.
* This can be used so your application can show *something* while waiting for the latest data to be
* downloaded. To restrict a request to locally-cached resources, add the `only-if-cached`
* directive:
*
* ```
* Request request = new Request.Builder()
* .cacheControl(new CacheControl.Builder()
* .onlyIfCached()
* .build())
* .url("http://publicobject.com/helloworld.txt")
* .build();
* Response forceCacheResponse = client.newCall(request).execute();
* if (forceCacheResponse.code() != 504) {
* // The resource was cached! Show it.
* } else {
* // The resource was not cached.
* }
* ```
*
* This technique works even better in situations where a stale response is better than no response.
* To permit stale cached responses, use the `max-stale` directive with the maximum staleness in
* seconds:
*
* ```
* Request request = new Request.Builder()
* .cacheControl(new CacheControl.Builder()
* .maxStale(365, TimeUnit.DAYS)
* .build())
* .url("http://publicobject.com/helloworld.txt")
* .build();
* ```
*
* The [CacheControl] class can configure request caching directives and parse response caching
* directives. It even offers convenient constants [CacheControl.FORCE_NETWORK] and
* [CacheControl.FORCE_CACHE] that address the use cases above.
*
* [rfc_7234]: http://tools.ietf.org/html/rfc7234
*/
class Cache internal constructor(
directory: File,
maxSize: Long,
fileSystem: FileSystem
) : Closeable, Flushable {
internal val cache = DiskLruCache(
fileSystem = fileSystem,
directory = directory,
appVersion = VERSION,
valueCount = ENTRY_COUNT,
maxSize = maxSize,
taskRunner = TaskRunner.INSTANCE
)
// read and write statistics, all guarded by 'this'.
internal var writeSuccessCount = 0
internal var writeAbortCount = 0
private var networkCount = 0
private var hitCount = 0
private var requestCount = 0
val isClosed: Boolean
get() = cache.isClosed()
/** Create a cache of at most [maxSize] bytes in [directory]. */
constructor(directory: File, maxSize: Long) : this(directory, maxSize, FileSystem.SYSTEM)
internal fun get(request: Request): Response? {
val key = key(request.url)
val snapshot: DiskLruCache.Snapshot = try {
cache[key] ?: return null
} catch (_: IOException) {
return null // Give up because the cache cannot be read.
}
val entry: Entry = try {
Entry(snapshot.getSource(ENTRY_METADATA))
} catch (_: IOException) {
snapshot.closeQuietly()
return null
}
val response = entry.response(snapshot)
if (!entry.matches(request, response)) {
response.body?.closeQuietly()
return null
}
return response
}
internal fun put(response: Response): CacheRequest? {
val requestMethod = response.request.method
if (HttpMethod.invalidatesCache(response.request.method)) {
try {
remove(response.request)
} catch (_: IOException) {
// The cache cannot be written.
}
return null
}
if (requestMethod != "GET") {
// Don't cache non-GET responses. We're technically allowed to cache HEAD requests and some
// POST requests, but the complexity of doing so is high and the benefit is low.
return null
}
if (response.hasVaryAll()) {
return null
}
val entry = Entry(response)
var editor: DiskLruCache.Editor? = null
try {
editor = cache.edit(key(response.request.url)) ?: return null
entry.writeTo(editor)
return RealCacheRequest(editor)
} catch (_: IOException) {
abortQuietly(editor)
return null
}
}
@Throws(IOException::class)
internal fun remove(request: Request) {
cache.remove(key(request.url))
}
internal fun update(cached: Response, network: Response) {
val entry = Entry(network)
val snapshot = (cached.body as CacheResponseBody).snapshot
var editor: DiskLruCache.Editor? = null
try {
editor = snapshot.edit() ?: return // edit() returns null if snapshot is not current.
entry.writeTo(editor)
editor.commit()
} catch (_: IOException) {
abortQuietly(editor)
}
}
private fun abortQuietly(editor: DiskLruCache.Editor?) {
// Give up because the cache cannot be written.
try {
editor?.abort()
} catch (_: IOException) {
}
}
/**
* Initialize the cache. This will include reading the journal files from the storage and building
* up the necessary in-memory cache information.
*
* The initialization time may vary depending on the journal file size and the current actual
* cache size. The application needs to be aware of calling this function during the
* initialization phase and preferably in a background worker thread.
*
* Note that if the application chooses to not call this method to initialize the cache. By
* default, OkHttp will perform lazy initialization upon the first usage of the cache.
*/
@Throws(IOException::class)
fun initialize() {
cache.initialize()
}
/**
* Closes the cache and deletes all of its stored values. This will delete all files in the cache
* directory including files that weren't created by the cache.
*/
@Throws(IOException::class)
fun delete() {
cache.delete()
}
/**
* Deletes all values stored in the cache. In-flight writes to the cache will complete normally,
* but the corresponding responses will not be stored.
*/
@Throws(IOException::class)
fun evictAll() {
cache.evictAll()
}
/**
* Returns an iterator over the URLs in this cache. This iterator doesn't throw
* `ConcurrentModificationException`, but if new responses are added while iterating, their URLs
* will not be returned. If existing responses are evicted during iteration, they will be absent
* (unless they were already returned).
*
* The iterator supports [MutableIterator.remove]. Removing a URL from the iterator evicts the
* corresponding response from the cache. Use this to evict selected responses.
*/
@Throws(IOException::class)
fun urls(): MutableIterator<String> {
return object : MutableIterator<String> {
private val delegate: MutableIterator<DiskLruCache.Snapshot> = cache.snapshots()
private var nextUrl: String? = null
private var canRemove = false
override fun hasNext(): Boolean {
if (nextUrl != null) return true
canRemove = false // Prevent delegate.remove() on the wrong item!
while (delegate.hasNext()) {
try {
delegate.next().use { snapshot ->
val metadata = snapshot.getSource(ENTRY_METADATA).buffer()
nextUrl = metadata.readUtf8LineStrict()
return true
}
} catch (_: IOException) {
// We couldn't read the metadata for this snapshot; possibly because the host filesystem
// has disappeared! Skip it.
}
}
return false
}
override fun next(): String {
if (!hasNext()) throw NoSuchElementException()
val result = nextUrl!!
nextUrl = null
canRemove = true
return result
}
override fun remove() {
check(canRemove) { "remove() before next()" }
delegate.remove()
}
}
}
@Synchronized fun writeAbortCount(): Int = writeAbortCount
@Synchronized fun writeSuccessCount(): Int = writeSuccessCount
@Throws(IOException::class)
fun size(): Long = cache.size()
/** Max size of the cache (in bytes). */
fun maxSize(): Long = cache.maxSize
@Throws(IOException::class)
override fun flush() {
cache.flush()
}
@Throws(IOException::class)
override fun close() {
cache.close()
}
@get:JvmName("directory") val directory: File
get() = cache.directory
@JvmName("-deprecated_directory")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "directory"),
level = DeprecationLevel.ERROR)
fun directory(): File = cache.directory
@Synchronized internal fun trackResponse(cacheStrategy: CacheStrategy) {
requestCount++
if (cacheStrategy.networkRequest != null) {
// If this is a conditional request, we'll increment hitCount if/when it hits.
networkCount++
} else if (cacheStrategy.cacheResponse != null) {
// This response uses the cache and not the network. That's a cache hit.
hitCount++
}
}
@Synchronized internal fun trackConditionalCacheHit() {
hitCount++
}
@Synchronized fun networkCount(): Int = networkCount
@Synchronized fun hitCount(): Int = hitCount
@Synchronized fun requestCount(): Int = requestCount
private inner class RealCacheRequest internal constructor(
private val editor: DiskLruCache.Editor
) : CacheRequest {
private val cacheOut: Sink = editor.newSink(ENTRY_BODY)
private val body: Sink
internal var done = false
init {
this.body = object : ForwardingSink(cacheOut) {
@Throws(IOException::class)
override fun close() {
synchronized(this@Cache) {
if (done) return
done = true
writeSuccessCount++
}
super.close()
editor.commit()
}
}
}
override fun abort() {
synchronized(this@Cache) {
if (done) return
done = true
writeAbortCount++
}
cacheOut.closeQuietly()
try {
editor.abort()
} catch (_: IOException) {
}
}
override fun body(): Sink = body
}
private class Entry {
private val url: String
private val varyHeaders: Headers
private val requestMethod: String
private val protocol: Protocol
private val code: Int
private val message: String
private val responseHeaders: Headers
private val handshake: Handshake?
private val sentRequestMillis: Long
private val receivedResponseMillis: Long
private val isHttps: Boolean get() = url.startsWith("https://")
/**
* Reads an entry from an input stream. A typical entry looks like this:
*
* ```
* http://google.com/foo
* GET
* 2
* Accept-Language: fr-CA
* Accept-Charset: UTF-8
* HTTP/1.1 200 OK
* 3
* Content-Type: image/png
* Content-Length: 100
* Cache-Control: max-age=600
* ```
*
* A typical HTTPS file looks like this:
*
* ```
* https://google.com/foo
* GET
* 2
* Accept-Language: fr-CA
* Accept-Charset: UTF-8
* HTTP/1.1 200 OK
* 3
* Content-Type: image/png
* Content-Length: 100
* Cache-Control: max-age=600
*
* AES_256_WITH_MD5
* 2
* base64-encoded peerCertificate[0]
* base64-encoded peerCertificate[1]
* -1
* TLSv1.2
* ```
*
* The file is newline separated. The first two lines are the URL and the request method. Next
* is the number of HTTP Vary request header lines, followed by those lines.
*
* Next is the response status line, followed by the number of HTTP response header lines,
* followed by those lines.
*
* HTTPS responses also contain SSL session information. This begins with a blank line, and then
* a line containing the cipher suite. Next is the length of the peer certificate chain. These
* certificates are base64-encoded and appear each on their own line. The next line contains the
* length of the local certificate chain. These certificates are also base64-encoded and appear
* each on their own line. A length of -1 is used to encode a null array. The last line is
* optional. If present, it contains the TLS version.
*/
@Throws(IOException::class)
internal constructor(rawSource: Source) {
try {
val source = rawSource.buffer()
url = source.readUtf8LineStrict()
requestMethod = source.readUtf8LineStrict()
val varyHeadersBuilder = Headers.Builder()
val varyRequestHeaderLineCount = readInt(source)
for (i in 0 until varyRequestHeaderLineCount) {
varyHeadersBuilder.addLenient(source.readUtf8LineStrict())
}
varyHeaders = varyHeadersBuilder.build()
val statusLine = StatusLine.parse(source.readUtf8LineStrict())
protocol = statusLine.protocol
code = statusLine.code
message = statusLine.message
val responseHeadersBuilder = Headers.Builder()
val responseHeaderLineCount = readInt(source)
for (i in 0 until responseHeaderLineCount) {
responseHeadersBuilder.addLenient(source.readUtf8LineStrict())
}
val sendRequestMillisString = responseHeadersBuilder[SENT_MILLIS]
val receivedResponseMillisString = responseHeadersBuilder[RECEIVED_MILLIS]
responseHeadersBuilder.removeAll(SENT_MILLIS)
responseHeadersBuilder.removeAll(RECEIVED_MILLIS)
sentRequestMillis = sendRequestMillisString?.toLong() ?: 0L
receivedResponseMillis = receivedResponseMillisString?.toLong() ?: 0L
responseHeaders = responseHeadersBuilder.build()
if (isHttps) {
val blank = source.readUtf8LineStrict()
if (blank.isNotEmpty()) {
throw IOException("expected \"\" but was \"$blank\"")
}
val cipherSuiteString = source.readUtf8LineStrict()
val cipherSuite = CipherSuite.forJavaName(cipherSuiteString)
val peerCertificates = readCertificateList(source)
val localCertificates = readCertificateList(source)
val tlsVersion = if (!source.exhausted()) {
TlsVersion.forJavaName(source.readUtf8LineStrict())
} else {
TlsVersion.SSL_3_0
}
handshake = Handshake.get(tlsVersion, cipherSuite, peerCertificates, localCertificates)
} else {
handshake = null
}
} finally {
rawSource.close()
}
}
internal constructor(response: Response) {
this.url = response.request.url.toString()
this.varyHeaders = response.varyHeaders()
this.requestMethod = response.request.method
this.protocol = response.protocol
this.code = response.code
this.message = response.message
this.responseHeaders = response.headers
this.handshake = response.handshake
this.sentRequestMillis = response.sentRequestAtMillis
this.receivedResponseMillis = response.receivedResponseAtMillis
}
@Throws(IOException::class)
fun writeTo(editor: DiskLruCache.Editor) {
editor.newSink(ENTRY_METADATA).buffer().use { sink ->
sink.writeUtf8(url).writeByte('\n'.toInt())
sink.writeUtf8(requestMethod).writeByte('\n'.toInt())
sink.writeDecimalLong(varyHeaders.size.toLong()).writeByte('\n'.toInt())
for (i in 0 until varyHeaders.size) {
sink.writeUtf8(varyHeaders.name(i))
.writeUtf8(": ")
.writeUtf8(varyHeaders.value(i))
.writeByte('\n'.toInt())
}
sink.writeUtf8(StatusLine(protocol, code, message).toString()).writeByte('\n'.toInt())
sink.writeDecimalLong((responseHeaders.size + 2).toLong()).writeByte('\n'.toInt())
for (i in 0 until responseHeaders.size) {
sink.writeUtf8(responseHeaders.name(i))
.writeUtf8(": ")
.writeUtf8(responseHeaders.value(i))
.writeByte('\n'.toInt())
}
sink.writeUtf8(SENT_MILLIS)
.writeUtf8(": ")
.writeDecimalLong(sentRequestMillis)
.writeByte('\n'.toInt())
sink.writeUtf8(RECEIVED_MILLIS)
.writeUtf8(": ")
.writeDecimalLong(receivedResponseMillis)
.writeByte('\n'.toInt())
if (isHttps) {
sink.writeByte('\n'.toInt())
sink.writeUtf8(handshake!!.cipherSuite.javaName).writeByte('\n'.toInt())
writeCertList(sink, handshake.peerCertificates)
writeCertList(sink, handshake.localCertificates)
sink.writeUtf8(handshake.tlsVersion.javaName).writeByte('\n'.toInt())
}
}
}
@Throws(IOException::class)
private fun readCertificateList(source: BufferedSource): List<Certificate> {
val length = readInt(source)
if (length == -1) return emptyList() // OkHttp v1.2 used -1 to indicate null.
try {
val certificateFactory = CertificateFactory.getInstance("X.509")
val result = ArrayList<Certificate>(length)
for (i in 0 until length) {
val line = source.readUtf8LineStrict()
val bytes = Buffer()
bytes.write(line.decodeBase64()!!)
result.add(certificateFactory.generateCertificate(bytes.inputStream()))
}
return result
} catch (e: CertificateException) {
throw IOException(e.message)
}
}
@Throws(IOException::class)
private fun writeCertList(sink: BufferedSink, certificates: List<Certificate>) {
try {
sink.writeDecimalLong(certificates.size.toLong()).writeByte('\n'.toInt())
for (i in 0 until certificates.size) {
val bytes = certificates[i].encoded
val line = bytes.toByteString().base64()
sink.writeUtf8(line).writeByte('\n'.toInt())
}
} catch (e: CertificateEncodingException) {
throw IOException(e.message)
}
}
fun matches(request: Request, response: Response): Boolean {
return url == request.url.toString() &&
requestMethod == request.method &&
varyMatches(response, varyHeaders, request)
}
fun response(snapshot: DiskLruCache.Snapshot): Response {
val contentType = responseHeaders["Content-Type"]
val contentLength = responseHeaders["Content-Length"]
val cacheRequest = Request.Builder()
.url(url)
.method(requestMethod, null)
.headers(varyHeaders)
.build()
return Response.Builder()
.request(cacheRequest)
.protocol(protocol)
.code(code)
.message(message)
.headers(responseHeaders)
.body(CacheResponseBody(snapshot, contentType, contentLength))
.handshake(handshake)
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(receivedResponseMillis)
.build()
}
companion object {
/** Synthetic response header: the local time when the request was sent. */
private val SENT_MILLIS = "${Platform.get().getPrefix()}-Sent-Millis"
/** Synthetic response header: the local time when the response was received. */
private val RECEIVED_MILLIS = "${Platform.get().getPrefix()}-Received-Millis"
}
}
private class CacheResponseBody internal constructor(
internal val snapshot: DiskLruCache.Snapshot,
private val contentType: String?,
private val contentLength: String?
) : ResponseBody() {
private val bodySource: BufferedSource
init {
val source = snapshot.getSource(ENTRY_BODY)
bodySource = object : ForwardingSource(source) {
@Throws(IOException::class)
override fun close() {
snapshot.close()
super.close()
}
}.buffer()
}
override fun contentType(): MediaType? = contentType?.toMediaTypeOrNull()
override fun contentLength(): Long = contentLength?.toLongOrDefault(-1L) ?: -1L
override fun source(): BufferedSource = bodySource
}
companion object {
private const val VERSION = 201105
private const val ENTRY_METADATA = 0
private const val ENTRY_BODY = 1
private const val ENTRY_COUNT = 2
@JvmStatic
fun key(url: HttpUrl): String = url.toString().encodeUtf8().md5().hex()
@Throws(IOException::class)
internal fun readInt(source: BufferedSource): Int {
try {
val result = source.readDecimalLong()
val line = source.readUtf8LineStrict()
if (result < 0L || result > Integer.MAX_VALUE || line.isNotEmpty()) {
throw IOException("expected an int but was \"$result$line\"")
}
return result.toInt()
} catch (e: NumberFormatException) {
throw IOException(e.message)
}
}
/**
* Returns true if none of the Vary headers have changed between [cachedRequest] and
* [newRequest].
*/
fun varyMatches(
cachedResponse: Response,
cachedRequest: Headers,
newRequest: Request
): Boolean {
return cachedResponse.headers.varyFields().none {
cachedRequest.values(it) != newRequest.headers(it)
}
}
/** Returns true if a Vary header contains an asterisk. Such responses cannot be cached. */
fun Response.hasVaryAll() = "*" in headers.varyFields()
/**
* Returns the names of the request headers that need to be checked for equality when caching.
*/
private fun Headers.varyFields(): Set<String> {
var result: MutableSet<String>? = null
for (i in 0 until size) {
if (!"Vary".equals(name(i), ignoreCase = true)) {
continue
}
val value = value(i)
if (result == null) {
result = TreeSet(String.CASE_INSENSITIVE_ORDER)
}
for (varyField in value.split(',')) {
result.add(varyField.trim())
}
}
return result ?: emptySet()
}
/**
* Returns the subset of the headers in this's request that impact the content of this's body.
*/
fun Response.varyHeaders(): Headers {
// Use the request headers sent over the network, since that's what the response varies on.
// Otherwise OkHttp-supplied headers like "Accept-Encoding: gzip" may be lost.
val requestHeaders = networkResponse!!.request.headers
val responseHeaders = headers
return varyHeaders(requestHeaders, responseHeaders)
}
/**
* Returns the subset of the headers in [requestHeaders] that impact the content of the
* response's body.
*/
private fun varyHeaders(requestHeaders: Headers, responseHeaders: Headers): Headers {
val varyFields = responseHeaders.varyFields()
if (varyFields.isEmpty()) return EMPTY_HEADERS
val result = Headers.Builder()
for (i in 0 until requestHeaders.size) {
val fieldName = requestHeaders.name(i)
if (fieldName in varyFields) {
result.add(fieldName, requestHeaders.value(i))
}
}
return result.build()
}
}
}
| apache-2.0 |
STUDIO-apps/GeoShare_Android | mobile/src/main/java/uk/co/appsbystudio/geoshare/utils/ui/SeekBarTextIndicator.kt | 1 | 455 | package uk.co.appsbystudio.geoshare.utils.ui
import android.content.Context
import android.graphics.drawable.Drawable
import android.support.v7.widget.AppCompatSeekBar
import android.util.AttributeSet
class SeekBarTextIndicator(context: Context, attrs: AttributeSet) : AppCompatSeekBar(context, attrs) {
private var mThumb: Drawable? = null
override fun setThumb(thumb: Drawable) {
super.setThumb(thumb)
mThumb = thumb
}
}
| apache-2.0 |
christophpickl/kpotpourri | logback4k/logback.kt | 1 | 6582 | /*
package com.github.christophpickl.kpotpourri.logback
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.Appender
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy
import ch.qos.logback.core.rolling.TriggeringPolicyBase
import ch.qos.logback.core.status.InfoStatus
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.testng.ITestContext
import org.testng.ITestListener
import org.testng.ITestNGListener
import org.testng.ITestResult
import org.testng.annotations.BeforeSuite
import org.testng.annotations.Listeners
import org.testng.annotations.Test
import java.io.File
abstract class BaseLogConfigurator {
protected val defaultPattern = "%-43(%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread]) [%-5level] %logger{42} - %msg%n"
protected val context: LoggerContext
private var yetConfigured = false
init {
context = LoggerFactory.getILoggerFactory() as LoggerContext
}
protected fun consoleAppender(name: String,
pattern: String = defaultPattern,
withAppender: ((ConsoleAppender<ILoggingEvent>) -> Unit)? = null): Appender<ILoggingEvent> {
val appender = ConsoleAppender<ILoggingEvent>()
appender.context = context
appender.name = name
appender.encoder = patternLayout(pattern)
if (withAppender != null) {
withAppender(appender)
}
appender.start()
return appender
}
protected fun fileAppender(name: String, filename: String, filenamePattern: String): Appender<ILoggingEvent> {
val appender = RollingFileAppender<ILoggingEvent>()
appender.file = filename
// http://logback.qos.ch/manual/appenders.html#TimeBasedRollingPolicy
// http://www.programcreek.com/java-api-examples/index.php?api=ch.qos.logback.core.rolling.TimeBasedRollingPolicy
val rollingPolicy = TimeBasedRollingPolicy<ILoggingEvent>()
rollingPolicy.context = context
rollingPolicy.setParent(appender)
rollingPolicy.fileNamePattern = filenamePattern
rollingPolicy.maxHistory = 14 // two weeks
rollingPolicy.start()
appender.rollingPolicy = rollingPolicy
val triggeringPolicy = RollOncePerSessionTriggeringPolicy<ILoggingEvent>()
triggeringPolicy.start()
appender.triggeringPolicy = triggeringPolicy
appender.isAppend = true
appender.context = context
appender.name = name
appender.encoder = patternLayout()
appender.start()
return appender
}
// or: "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
protected fun patternLayout(pattern: String = defaultPattern): PatternLayoutEncoder {
val layout = PatternLayoutEncoder()
layout.context = context
layout.pattern = pattern
layout.start()
return layout
}
fun configureLog() {
if (yetConfigured) {
println("Log configurator '${javaClass.simpleName}' has been already activated. " +
"(Usually happens because of manually enabling log in tests and by testng suites)")
return
}
yetConfigured = true
val status = context.statusManager
status.add(InfoStatus("Setting up log configuration.", context))
val logger = context.getLogger(Logger.ROOT_LOGGER_NAME)
logger.detachAndStopAllAppenders()
configureInternal(logger)
}
abstract protected fun configureInternal(logger: ch.qos.logback.classic.Logger)
protected fun changeLevel(packageName: String, level: ch.qos.logback.classic.Level) {
context.getLogger(packageName).level = level
}
}
// http://stackoverflow.com/questions/2492022/how-to-roll-the-log-file-on-startup-in-logback
private class RollOncePerSessionTriggeringPolicy<E> : TriggeringPolicyBase<E>() {
private var doRolling: Boolean = true
override fun isTriggeringEvent(activeFile: File, event: E): Boolean {
// roll the first time when the event gets called
if (doRolling) {
doRolling = false
return true
}
return false
}
}
@Test
@Listeners(LogTestListener::class)
class TestLogger : BaseLogConfigurator() {
override fun configureInternal(logger: ch.qos.logback.classic.Logger) {
logger.level = Level.ALL
arrayOf(
"org.apache",
"org.springframework",
"org.flywaydb"
).forEach { changeLevel(it, Level.WARN) }
logger.addAppender(consoleAppender("Gadsu-ConsoleAppender", "%d{HH:mm:ss} [%-5level] %logger{42} - %msg%n"))
}
@BeforeSuite
fun initLogging() {
configureLog()
}
}
class LogTestListener : ITestNGListener, ITestListener {
private val log = LoggerFactory.getLogger(javaClass)
override fun onTestStart(result: ITestResult) {
logTest("START", result)
}
override fun onTestSuccess(result: ITestResult) {
logTest("SUCCESS", result)
}
override fun onTestSkipped(result: ITestResult) {
// copy and paste ;)
log.warn("======> {} - {}#{}", "SKIP", result.testClass.realClass.simpleName, result.method.methodName)
}
override fun onTestFailure(result: ITestResult) {
logTest("FAIL", result)
}
override fun onStart(context: ITestContext) {
log.info("Test Suite STARTED")
}
override fun onFinish(context: ITestContext) {
log.info("Test Suite FINISHED")
}
override fun onTestFailedButWithinSuccessPercentage(result: ITestResult) { }
private fun logTest(label: String, result: ITestResult) {
log.info("======> {} - {}#{}", label, result.testClass.realClass.simpleName, result.method.methodName)
}
}
class LogTestEnablerListener : ITestNGListener, ITestListener {
override fun onStart(context: ITestContext) {
TestLogger().configureLog()
}
override fun onFinish(context: ITestContext) { }
override fun onTestStart(result: ITestResult) { }
override fun onTestSuccess(result: ITestResult) { }
override fun onTestSkipped(result: ITestResult) { }
override fun onTestFailure(result: ITestResult) { }
override fun onTestFailedButWithinSuccessPercentage(result: ITestResult) { }
}
*/
| apache-2.0 |
HelloHuDi/usb-with-serial-port | usbserialport/src/main/java/com/hd/serialport/utils/L.kt | 1 | 813 | package com.hd.serialport.utils
import android.util.Log
import com.hd.serialport.BuildConfig
/**
* Created by hd on 2017/5/8.
*
*/
object L {
var allowLog = BuildConfig.DEBUG
private val TAG = "usb-serial-port"
fun i(i: String) {
i(TAG, i)
}
fun d(d: String) {
d(TAG, d)
}
fun w(w: String) {
w(TAG, w)
}
fun e(e: String) {
e(TAG, e)
}
fun i(tag: String?, i: String) {
if (allowLog)
Log.i(tag ?: TAG, i)
}
fun d(tag: String?, d: String) {
if (allowLog)
Log.d(tag ?: TAG, d)
}
fun w(tag: String?, w: String) {
if (allowLog)
Log.w(tag ?: TAG, w)
}
fun e(tag: String?, e: String) {
if (allowLog)
Log.e(tag ?: TAG, e)
}
}
| apache-2.0 |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/google/GoogleDiscoveryCompleter.kt | 1 | 1762 | package com.baulsupp.okurl.services.google
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.CompletionMappings
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.util.ClientException
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import okhttp3.HttpUrl
import java.util.logging.Level
import java.util.logging.Logger
class GoogleDiscoveryCompleter(
private val discoveryRegistry: DiscoveryRegistry,
private val discoveryDocPaths: List<String>
) : ApiCompleter {
private val mappings = CompletionMappings()
init {
mappings.withVariable("userId") { listOf("me") }
}
override suspend fun prefixUrls(): UrlList {
throw UnsupportedOperationException()
}
override suspend fun siteUrls(url: HttpUrl, tokenSet: Token): UrlList = coroutineScope {
val futures = discoveryDocPaths.map {
async {
discoveryRegistry.load(it, tokenSet).urls
}
}.mapNotNull {
try {
it.await()
} catch (e: ClientException) {
logger.log(Level.FINE, "failed getting siteUrls for $url", e)
null
} catch (e: CancellationException) {
logger.log(Level.FINE, "timeout for $url", e)
null
}
}.flatten()
mappings.replaceVariables(UrlList(UrlList.Match.SITE, futures))
}
companion object {
private val logger = Logger.getLogger(GoogleDiscoveryCompleter::class.java.name)
fun forApis(
discoveryRegistry: DiscoveryRegistry,
discoveryDocPaths: List<String>
): GoogleDiscoveryCompleter {
return GoogleDiscoveryCompleter(discoveryRegistry, discoveryDocPaths)
}
}
}
| apache-2.0 |
Ph1b/MaterialAudiobookPlayer | playback/src/main/kotlin/de/ph1b/audiobook/playback/player/OnlyAudioRenderersFactory.kt | 1 | 1187 | package de.ph1b.audiobook.playback.player
import android.content.Context
import android.os.Handler
import com.google.android.exoplayer2.Renderer
import com.google.android.exoplayer2.RenderersFactory
import com.google.android.exoplayer2.audio.AudioRendererEventListener
import com.google.android.exoplayer2.audio.MediaCodecAudioRenderer
import com.google.android.exoplayer2.mediacodec.MediaCodecSelector
import com.google.android.exoplayer2.metadata.MetadataOutput
import com.google.android.exoplayer2.text.TextOutput
import com.google.android.exoplayer2.video.VideoRendererEventListener
import javax.inject.Inject
class OnlyAudioRenderersFactory
@Inject constructor(
private val context: Context
) : RenderersFactory {
override fun createRenderers(
eventHandler: Handler,
videoRendererEventListener: VideoRendererEventListener,
audioRendererEventListener: AudioRendererEventListener,
textRendererOutput: TextOutput,
metadataRendererOutput: MetadataOutput
): Array<Renderer> {
return arrayOf(
MediaCodecAudioRenderer(
context,
MediaCodecSelector.DEFAULT,
eventHandler,
audioRendererEventListener,
)
)
}
}
| lgpl-3.0 |
MaTriXy/PermissionsDispatcher | test/src/test/java/permissions/dispatcher/test/ActivityWithOnNeverAskAgainPermissionsDispatcherTest.kt | 1 | 5951 | package permissions.dispatcher.test
import android.content.pm.PackageManager
import android.os.Process
import android.support.v4.app.ActivityCompat
import android.support.v4.app.AppOpsManagerCompat
import android.support.v4.content.PermissionChecker
import org.junit.After
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mockito
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
@Suppress("IllegalIdentifier")
@RunWith(PowerMockRunner::class)
@PrepareForTest(ActivityCompat::class, PermissionChecker::class, AppOpsManagerCompat::class, Process::class)
class ActivityWithOnNeverAskAgainPermissionsDispatcherTest {
private lateinit var activity: ActivityWithOnNeverAskAgain
companion object {
private var requestCode = 0
@BeforeClass
@JvmStatic
fun setUpForClass() {
requestCode = getRequestCameraConstant(ActivityWithOnNeverAskAgainPermissionsDispatcher::class.java)
}
}
@Before
fun setUp() {
activity = Mockito.mock(ActivityWithOnNeverAskAgain::class.java)
PowerMockito.mockStatic(ActivityCompat::class.java)
PowerMockito.mockStatic(PermissionChecker::class.java)
PowerMockito.mockStatic(Process::class.java)
PowerMockito.mockStatic(AppOpsManagerCompat::class.java)
}
@After
fun tearDown() {
clearCustomManufacture()
clearCustomSdkInt()
}
@Test
fun `already granted call the method`() {
mockCheckSelfPermission(true)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `not granted does not call the method`() {
mockCheckSelfPermission(false)
mockShouldShowRequestPermissionRationaleActivity(true)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `the method is called if verifyPermission is true`() {
ActivityWithOnNeverAskAgainPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_GRANTED))
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `the method is not called if verifyPermission is false`() {
ActivityWithOnNeverAskAgainPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `show never ask method is call if verifyPermission is false and shouldShowRequestPermissionRationale is false`() {
mockShouldShowRequestPermissionRationaleActivity(false)
ActivityWithOnNeverAskAgainPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode, intArrayOf(PackageManager.PERMISSION_DENIED))
Mockito.verify(activity, Mockito.times(1)).showNeverAskForCamera()
}
@Test
fun `no the method call if request code is not related to the library`() {
ActivityWithOnNeverAskAgainPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode + 1000, null)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `no never ask method call if request code is not related to the library`() {
ActivityWithOnNeverAskAgainPermissionsDispatcher.onRequestPermissionsResult(activity, requestCode + 1000, null)
Mockito.verify(activity, Mockito.times(0)).showNeverAskForCamera()
}
@Test
fun `xiaomi device permissionToOp returns null grant permission`() {
testForXiaomi()
mockPermissionToOp(null)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `xiaomi device grant permission`() {
testForXiaomi()
mockPermissionToOp("")
mockNoteOp(AppOpsManagerCompat.MODE_ALLOWED)
mockCheckSelfPermission(true)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
@Test
fun `xiaomi noteOp returns not allowed value should not call the method`() {
testForXiaomi()
mockPermissionToOp("")
mockNoteOp(AppOpsManagerCompat.MODE_IGNORED)
mockCheckSelfPermission(true)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `xiaomi noteOp returns allowed but checkSelfPermission not allowed value should not call the method`() {
testForXiaomi()
mockPermissionToOp("")
mockNoteOp(AppOpsManagerCompat.MODE_ALLOWED)
mockCheckSelfPermission(false)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `blow M follows checkSelfPermissions result false`() {
overwriteCustomSdkInt(22)
mockCheckSelfPermission(false)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(0)).showCamera()
}
@Test
fun `blow M follows checkSelfPermissions result true`() {
overwriteCustomSdkInt(22)
mockCheckSelfPermission(true)
ActivityWithOnNeverAskAgainPermissionsDispatcher.showCameraWithPermissionCheck(activity)
Mockito.verify(activity, Mockito.times(1)).showCamera()
}
} | apache-2.0 |
toastkidjp/Jitte | app/src/test/java/jp/toastkid/yobidashi/browser/webview/factory/WebViewClientFactoryTest.kt | 1 | 1874 | /*
* 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.browser.webview.factory
import android.webkit.WebView
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.unmockkAll
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.browser.BrowserHeaderViewModel
import jp.toastkid.yobidashi.browser.FaviconApplier
import jp.toastkid.yobidashi.browser.LoadingViewModel
import jp.toastkid.yobidashi.browser.block.AdRemover
import jp.toastkid.rss.suggestion.RssAddingSuggestion
import org.junit.After
import org.junit.Before
import org.junit.Test
class WebViewClientFactoryTest {
@InjectMockKs
private lateinit var webViewClientFactory: WebViewClientFactory
@MockK
private lateinit var contentViewModel: ContentViewModel
@MockK
private lateinit var adRemover: AdRemover
@MockK
private lateinit var faviconApplier: FaviconApplier
@MockK
private lateinit var preferenceApplier: PreferenceApplier
@MockK
private lateinit var browserHeaderViewModel: BrowserHeaderViewModel
@MockK
private lateinit var rssAddingSuggestion: RssAddingSuggestion
@MockK
private lateinit var loadingViewModel: LoadingViewModel
@MockK
private lateinit var currentView: () -> WebView
@Before
fun setUp() {
MockKAnnotations.init(this)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun invoke() {
webViewClientFactory.invoke()
}
} | epl-1.0 |
astromme/classify-handwritten-characters | android/app/src/main/java/com/dokibo/characterclassification/DrawCharacterView.kt | 1 | 3988 | package com.dokibo.characterclassification
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import androidx.core.content.res.ResourcesCompat
private const val STROKE_WIDTH = 40f
class DrawCharacterView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : View(context, attrs, defStyle) {
private lateinit var extraCanvas: Canvas
private lateinit var extraBitmap: Bitmap
private val backgroundColor = ResourcesCompat.getColor(resources, R.color.white, null)
private val drawColor = ResourcesCompat.getColor(resources, R.color.black, null)
private val paint = Paint().apply {
color = drawColor
isAntiAlias = true
isDither = true
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
strokeWidth = STROKE_WIDTH
}
private var strokes: MutableList<Path> = mutableListOf(Path())
private val currentPath: Path
get() { return strokes.last() }
private var motionTouchEventX = 0f
private var motionTouchEventY = 0f
private var currentX = 0f
private var currentY = 0f
private val touchTolerance = ViewConfiguration.get(context).scaledTouchSlop
private val onDrawingUpdatedListeners: MutableList<(bitmap: Bitmap) -> Unit?> = mutableListOf()
fun setOnDrawingUpdatedListener(listener: (bitmap: Bitmap) -> Unit?) {
onDrawingUpdatedListeners.add(listener)
}
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
if (::extraBitmap.isInitialized) extraBitmap.recycle()
extraBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
extraCanvas = Canvas(extraBitmap)
extraCanvas.drawColor(backgroundColor)
strokes = mutableListOf(Path())
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.drawBitmap(extraBitmap, 0f, 0f, null)
}
override fun onTouchEvent(event: MotionEvent): Boolean {
motionTouchEventX = event.x
motionTouchEventY = event.y
when (event.action) {
MotionEvent.ACTION_DOWN -> touchStart()
MotionEvent.ACTION_MOVE -> touchMove()
MotionEvent.ACTION_UP -> touchUp()
}
return true
}
private fun touchStart() {
// TODO: handle multi-touch
currentPath.moveTo(motionTouchEventX, motionTouchEventY)
currentX = motionTouchEventX
currentY = motionTouchEventY
}
private fun touchMove() {
val dx = Math.abs(motionTouchEventX - currentX)
val dy = Math.abs(motionTouchEventY - currentY)
if (dx >= touchTolerance || dy >= touchTolerance) {
currentPath.quadTo(
currentX, currentY,
(motionTouchEventX + currentX) / 2, (motionTouchEventY + currentY) / 2)
currentX = motionTouchEventX
currentY = motionTouchEventY
extraCanvas.drawPath(currentPath, paint)
}
invalidate()
}
private fun touchUp() {
// finish the path by adding a new one
strokes.add(Path())
onDrawingUpdatedListeners.forEach {
it(extraBitmap)
}
}
fun undoStroke() {
Log.d("DrawCharacterView", "Strokes: ${strokes.size} ${strokes}")
if (strokes.size < 2) {
return
}
strokes.removeAt(strokes.size - 2)
extraCanvas.drawColor(backgroundColor)
for (path in strokes) {
extraCanvas.drawPath(path, paint)
}
invalidate()
onDrawingUpdatedListeners.forEach {
it(extraBitmap)
}
}
} | mit |
toastkidjp/Jitte | app/src/main/java/jp/toastkid/yobidashi/editor/usecase/MenuActionInvokerUseCase.kt | 1 | 6255 | /*
* 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.editor.usecase
import android.content.Context
import android.net.Uri
import android.widget.EditText
import androidx.annotation.IdRes
import androidx.core.net.toUri
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.input.Inputs
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.search.SearchCategory
import jp.toastkid.search.UrlFactory
import jp.toastkid.yobidashi.R
import jp.toastkid.yobidashi.editor.CurrentLineDuplicatorUseCase
import jp.toastkid.yobidashi.editor.ListHeadAdder
import jp.toastkid.yobidashi.editor.OrderedListHeadAdder
import jp.toastkid.yobidashi.editor.StringSurroundingUseCase
import jp.toastkid.yobidashi.editor.TableConverter
import jp.toastkid.yobidashi.libs.clip.Clipboard
import jp.toastkid.yobidashi.libs.speech.SpeechMaker
/**
* @author toastkidjp
*/
class MenuActionInvokerUseCase(
private val editText: EditText,
private val speechMaker: SpeechMaker?,
private val browserViewModel: BrowserViewModel?,
private val contentViewModel: ContentViewModel?,
private val listHeadAdder: ListHeadAdder = ListHeadAdder()
) {
operator fun invoke(@IdRes itemId: Int, text: String): Boolean {
val context = editText.context
when (itemId) {
R.id.context_edit_insert_as_plain -> {
val primary = Clipboard.getPrimary(context)
if (primary.isNullOrEmpty()) {
return true
}
editText.text.insert(editText.selectionStart, primary)
return true
}
R.id.context_edit_paste_as_quotation -> {
contentViewModel ?: return true
PasteAsQuotationUseCase(editText, contentViewModel).invoke()
return true
}
R.id.context_edit_paste_url_with_title -> {
contentViewModel ?: return true
LinkFormInsertionUseCase(
editText,
contentViewModel
).invoke()
return true
}
R.id.context_edit_horizontal_rule -> {
editText.text.insert(
editText.selectionStart,
"----${System.lineSeparator()}"
)
return true
}
R.id.context_edit_duplicate_current_line -> {
CurrentLineDuplicatorUseCase().invoke(editText)
return true
}
R.id.context_edit_select_current_line -> {
CurrentLineSelectionUseCase().invoke(editText)
return true
}
R.id.context_edit_speech -> {
val speechText = if (text.isBlank()) editText.text.toString() else text
speechMaker?.invoke(speechText)
return true
}
R.id.context_edit_add_order -> {
OrderedListHeadAdder().invoke(editText)
return true
}
R.id.context_edit_unordered_list -> {
listHeadAdder(editText, "-")
return true
}
R.id.context_edit_task_list -> {
listHeadAdder(editText, "- [ ]")
return true
}
R.id.context_edit_convert_to_table -> {
TableConverter().invoke(editText)
return true
}
R.id.context_edit_add_quote -> {
listHeadAdder(editText, ">")
return true
}
R.id.context_edit_code_block -> {
CodeBlockUseCase().invoke(editText, text)
return true
}
R.id.context_edit_double_quote -> {
StringSurroundingUseCase()(editText, '"')
return true
}
R.id.context_edit_bold -> {
StringSurroundingUseCase()(editText, "**")
return true
}
R.id.context_edit_italic -> {
StringSurroundingUseCase()(editText, "*")
return true
}
R.id.context_edit_strikethrough -> {
StringSurroundingUseCase()(editText, "~~")
return true
}
R.id.context_edit_url_open_new -> {
browserViewModel?.open(text.toUri())
return true
}
R.id.context_edit_url_open_background -> {
browserViewModel?.openBackground(text.toUri())
return true
}
R.id.context_edit_url_preview -> {
browserViewModel?.preview(text.toUri())
Inputs.hideKeyboard(editText)
return true
}
R.id.context_edit_preview_search -> {
browserViewModel?.preview(makeSearchResultUrl(context, text))
return true
}
R.id.context_edit_web_search -> {
browserViewModel?.open(makeSearchResultUrl(context, text))
return true
}
R.id.context_edit_delete_line -> {
CurrentLineDeletionUseCase().invoke(editText)
return true
}
R.id.context_edit_count -> {
TextCountUseCase().invoke(editText, contentViewModel)
return true
}
R.id.context_edit_insert_thousand_separator -> {
ThousandSeparatorInsertionUseCase().invoke(editText, text)
return true
}
else -> Unit
}
return false
}
private fun makeSearchResultUrl(context: Context, text: String): Uri = UrlFactory().invoke(
PreferenceApplier(context).getDefaultSearchEngine()
?: SearchCategory.getDefaultCategoryName(),
text
)
} | epl-1.0 |
square/leakcanary | shark-android/src/main/java/shark/AndroidServices.kt | 2 | 941 | package shark
object AndroidServices {
val HeapGraph.aliveAndroidServiceObjectIds: List<Long>
get() {
return context.getOrPut(AndroidServices::class.java.name) {
val activityThreadClass = findClassByName("android.app.ActivityThread")!!
val currentActivityThread = activityThreadClass
.readStaticField("sCurrentActivityThread")!!
.valueAsInstance!!
val mServices = currentActivityThread["android.app.ActivityThread", "mServices"]!!
.valueAsInstance!!
val servicesArray = mServices["android.util.ArrayMap", "mArray"]!!.valueAsObjectArray!!
servicesArray.readElements()
.filterIndexed { index, heapValue ->
// ArrayMap<IBinder, Service>
// even: key, odd: value
index % 2 == 1
&& heapValue.isNonNullReference
}
.map { it.asNonNullObjectId!! }
.toList()
}
}
} | apache-2.0 |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/bugreport/KatbinService.kt | 1 | 714 | package app.lawnchair.bugreport
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import retrofit2.http.Body
import retrofit2.http.POST
interface KatbinService {
@POST("api/paste")
suspend fun upload(@Body body: KatbinUploadBody): KatbinUploadResult
companion object {
fun create(): KatbinService = Retrofit.Builder()
.baseUrl("https://katb.in/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create()
}
}
data class KatbinUploadBody(
val paste: KatbinPaste
)
data class KatbinPaste(
val content: String
)
data class KatbinUploadResult(
val id: String
)
| gpl-3.0 |
DenverM80/ds3_autogen | ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/request/IdsPayloadRequestGenerator.kt | 1 | 1377 | /*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.generators.request
import com.spectralogic.ds3autogen.api.models.Arguments
import com.spectralogic.ds3autogen.go.models.request.Variable
class IdsPayloadRequestGenerator : RequestPayloadGenerator() {
/**
* Retrieves the ids request payload
*/
override fun getPayloadConstructorArg(): Arguments {
return Arguments("[]string", "ids")
}
/**
* Retrieves the struct assignment for the ids request payload
*/
override fun getStructAssignmentVariable(): Variable {
return Variable("content", "buildIdListPayload(ids)")
}
} | apache-2.0 |
xfournet/intellij-community | python/src/com/jetbrains/python/codeInsight/stdlib/PyNamedTuplesTypeProvider.kt | 1 | 14575 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.stdlib
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import com.intellij.psi.util.QualifiedName
import com.intellij.util.ArrayUtil
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyCallExpressionNavigator
import com.jetbrains.python.psi.impl.stubs.PyNamedTupleStubImpl
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.resolve.fromFoothold
import com.jetbrains.python.psi.resolve.resolveTopLevelMember
import com.jetbrains.python.psi.stubs.PyNamedTupleStub
import com.jetbrains.python.psi.types.*
import one.util.streamex.StreamEx
import java.util.*
import java.util.stream.Collectors
private typealias NTFields = LinkedHashMap<String, PyNamedTupleType.FieldTypeAndDefaultValue>
private typealias ImmutableNTFields = Map<String, PyNamedTupleType.FieldTypeAndDefaultValue>
class PyNamedTuplesTypeProvider : PyTypeProviderBase() {
override fun getReferenceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyType? {
return getNamedTupleTypeForResolvedCallee(referenceTarget, context, anchor)
}
override fun getReferenceExpressionType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? {
val fieldTypeForNamedTuple = getFieldTypeForNamedTupleAsTarget(referenceExpression, context)
if (fieldTypeForNamedTuple != null) {
return fieldTypeForNamedTuple
}
val namedTupleTypeForCallee = getNamedTupleTypeForCallee(referenceExpression, context)
if (namedTupleTypeForCallee != null) {
return namedTupleTypeForCallee
}
val namedTupleReplaceType = getNamedTupleReplaceType(referenceExpression, context)
if (namedTupleReplaceType != null) {
return namedTupleReplaceType
}
return null
}
override fun getCallType(function: PyFunction, callSite: PyCallSiteExpression?, context: TypeEvalContext): Ref<PyType?>? {
if (callSite != null && function.qualifiedName == PyTypingTypeProvider.NAMEDTUPLE + "._make") {
val receiverType = callSite.getReceiver(function)?.let { context.getType(it) }
if (receiverType is PyInstantiableType<*> && isNamedTuple(receiverType, context)) {
return Ref.create(receiverType.toInstance())
}
}
return null
}
companion object {
fun isNamedTuple(type: PyType?, context: TypeEvalContext): Boolean {
if (type is PyNamedTupleType) return true
val isNT = { t: PyClassLikeType? -> t is PyNamedTupleType || t != null && PyTypingTypeProvider.NAMEDTUPLE == t.classQName }
return type is PyClassLikeType && type.getAncestorTypes(context).any(isNT)
}
fun isTypingNamedTupleDirectInheritor(cls: PyClass, context: TypeEvalContext): Boolean {
val isTypingNT = { type: PyClassLikeType? ->
type != null && type !is PyNamedTupleType && PyTypingTypeProvider.NAMEDTUPLE == type.classQName
}
return cls.getSuperClassTypes(context).any(isTypingNT)
}
internal fun getNamedTupleTypeForResolvedCallee(referenceTarget: PsiElement,
context: TypeEvalContext,
anchor: PsiElement?): PyNamedTupleType? {
return when {
referenceTarget is PyFunction && anchor is PyCallExpression -> getNamedTupleFunctionType(referenceTarget, context, anchor)
referenceTarget is PyTargetExpression -> getNamedTupleTypeForTarget(referenceTarget, context)
else -> null
}
}
internal fun getNamedTupleReplaceType(referenceTarget: PsiElement, context: TypeEvalContext, anchor: PsiElement?): PyCallableType? {
if (referenceTarget is PyFunction &&
anchor is PyCallExpression &&
PyTypingTypeProvider.NAMEDTUPLE == referenceTarget.containingClass?.qualifiedName) {
val callee = anchor.callee as? PyReferenceExpression ?: return null
return getNamedTupleReplaceType(callee, context)
}
return null
}
private fun getFieldTypeForNamedTupleAsTarget(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyType? {
val qualifierNTType = referenceExpression.qualifier?.let { context.getType(it) } as? PyNamedTupleType ?: return null
return qualifierNTType.fields[referenceExpression.name]?.type
}
private fun getNamedTupleTypeForCallee(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyNamedTupleType? {
if (PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) == null) return null
val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context)
val resolveResults = referenceExpression.getReference(resolveContext).multiResolve(false)
for (element in PyUtil.filterTopPriorityResults(resolveResults)) {
if (element is PyTargetExpression) {
val result = getNamedTupleTypeForTarget(element, context)
if (result != null) {
return result
}
}
if (element is PyClass) {
val result = getNamedTupleTypeForTypingNTInheritorAsCallee(element, context)
if (result != null) {
return result
}
}
if (element is PyTypedElement) {
val type = context.getType(element)
if (type is PyClassLikeType) {
val superClassTypes = type.getSuperClassTypes(context)
val superNTType = superClassTypes.asSequence().filterIsInstance<PyNamedTupleType>().firstOrNull()
if (superNTType != null) {
return superNTType
}
}
}
}
return null
}
private fun getNamedTupleReplaceType(referenceExpression: PyReferenceExpression, context: TypeEvalContext): PyCallableType? {
val call = PyCallExpressionNavigator.getPyCallExpressionByCallee(referenceExpression) ?: return null
val qualifier = referenceExpression.qualifier
if (qualifier != null && "_replace" == referenceExpression.referencedName) {
val qualifierType = context.getType(qualifier) as? PyClassLikeType ?: return null
val namedTupleType = StreamEx
.of<PyType>(qualifierType)
.append(qualifierType.getSuperClassTypes(context))
.select(PyNamedTupleType::class.java)
.findFirst()
.orElse(null)
if (namedTupleType != null) {
return if (namedTupleType.isTyped) createTypedNamedTupleReplaceType(referenceExpression, namedTupleType.fields, qualifierType)
else createUntypedNamedTupleReplaceType(call, namedTupleType.fields, qualifierType, context)
}
if (qualifierType is PyClassType) {
val cls = qualifierType.pyClass
if (isTypingNamedTupleDirectInheritor(cls, context)) {
return createTypedNamedTupleReplaceType(referenceExpression, collectTypingNTInheritorFields(cls, context), qualifierType)
}
}
}
return null
}
private fun getNamedTupleFunctionType(function: PyFunction, context: TypeEvalContext, call: PyCallExpression): PyNamedTupleType? {
if (ArrayUtil.contains(function.qualifiedName, PyNames.COLLECTIONS_NAMEDTUPLE_PY2, PyNames.COLLECTIONS_NAMEDTUPLE_PY3) ||
PyUtil.isInit(function) && PyTypingTypeProvider.NAMEDTUPLE == function.containingClass?.qualifiedName) {
return getNamedTupleTypeFromAST(call, context, PyNamedTupleType.DefinitionLevel.NT_FUNCTION)
}
return null
}
private fun getNamedTupleTypeForTarget(target: PyTargetExpression, context: TypeEvalContext): PyNamedTupleType? {
val stub = target.stub
return if (stub != null) {
getNamedTupleTypeFromStub(target,
stub.getCustomStub(PyNamedTupleStub::class.java),
context,
PyNamedTupleType.DefinitionLevel.NEW_TYPE)
}
else getNamedTupleTypeFromAST(target, context, PyNamedTupleType.DefinitionLevel.NEW_TYPE)
}
private fun getNamedTupleTypeForTypingNTInheritorAsCallee(cls: PyClass, context: TypeEvalContext): PyNamedTupleType? {
if (isTypingNamedTupleDirectInheritor(cls, context)) {
val name = cls.name ?: return null
val typingNT = resolveTopLevelMember(QualifiedName.fromDottedString(PyTypingTypeProvider.NAMEDTUPLE), fromFoothold(cls))
val tupleClass = typingNT as? PyClass ?: return null
return PyNamedTupleType(tupleClass,
name,
collectTypingNTInheritorFields(cls, context),
PyNamedTupleType.DefinitionLevel.NEW_TYPE,
true)
}
return null
}
private fun getNamedTupleTypeFromStub(referenceTarget: PsiElement,
stub: PyNamedTupleStub?,
context: TypeEvalContext,
definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? {
if (stub == null) return null
val typingNT = resolveTopLevelMember(QualifiedName.fromDottedString(PyTypingTypeProvider.NAMEDTUPLE), fromFoothold(referenceTarget))
val tupleClass = typingNT as? PyClass ?: return null
val fields = stub.fields
return PyNamedTupleType(tupleClass,
stub.name,
parseNamedTupleFields(referenceTarget, fields, context),
definitionLevel,
fields.values.any { it.isPresent },
referenceTarget as? PyTargetExpression)
}
private fun getNamedTupleTypeFromAST(expression: PyTargetExpression,
context: TypeEvalContext,
definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? {
return if (context.maySwitchToAST(expression)) {
getNamedTupleTypeFromStub(expression, PyNamedTupleStubImpl.create(expression), context, definitionLevel)
}
else null
}
private fun createTypedNamedTupleReplaceType(anchor: PsiElement, fields: ImmutableNTFields, resultType: PyType): PyCallableType {
val parameters = mutableListOf<PyCallableParameter>()
val elementGenerator = PyElementGenerator.getInstance(anchor.project)
parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter()))
val ellipsis = elementGenerator.createEllipsis()
for ((name, typeAndValue) in fields) {
parameters.add(PyCallableParameterImpl.nonPsi(name, typeAndValue.type, typeAndValue.defaultValue ?: ellipsis))
}
return PyCallableTypeImpl(parameters, resultType)
}
private fun createUntypedNamedTupleReplaceType(call: PyCallExpression,
fields: ImmutableNTFields,
resultType: PyType,
context: TypeEvalContext): PyCallableType {
val parameters = mutableListOf<PyCallableParameter>()
val elementGenerator = PyElementGenerator.getInstance(call.project)
parameters.add(PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter()))
val ellipsis = elementGenerator.createEllipsis()
fields.keys.mapTo(parameters) { PyCallableParameterImpl.nonPsi(it, null, ellipsis) }
return if (resultType is PyNamedTupleType) {
val newFields = mutableMapOf<String?, PyType?>()
for (argument in call.arguments) {
if (argument is PyKeywordArgument) {
val value = argument.valueExpression
if (value != null) {
newFields[argument.keyword] = context.getType(value)
}
}
}
PyCallableTypeImpl(parameters, resultType.clarifyFields(newFields))
}
else PyCallableTypeImpl(parameters, resultType)
}
private fun collectTypingNTInheritorFields(cls: PyClass, context: TypeEvalContext): NTFields {
val fields = mutableListOf<PyTargetExpression>()
cls.processClassLevelDeclarations { element, _ ->
if (element is PyTargetExpression && element.annotationValue != null) {
fields.add(element)
}
true
}
val ellipsis = PyElementGenerator.getInstance(cls.project).createEllipsis()
val toNTFields = Collectors.toMap<PyTargetExpression, String, PyNamedTupleType.FieldTypeAndDefaultValue, NTFields>(
{ it.name },
{ field ->
val value = when {
context.maySwitchToAST(field) -> field.findAssignedValue()
field.hasAssignedValue() -> ellipsis
else -> null
}
PyNamedTupleType.FieldTypeAndDefaultValue(context.getType(field), value)
},
{ _, v2 -> v2 },
{ NTFields() })
return fields.stream().collect(toNTFields)
}
private fun getNamedTupleTypeFromAST(expression: PyCallExpression,
context: TypeEvalContext,
definitionLevel: PyNamedTupleType.DefinitionLevel): PyNamedTupleType? {
return if (context.maySwitchToAST(expression)) {
getNamedTupleTypeFromStub(expression, PyNamedTupleStubImpl.create(expression), context, definitionLevel)
}
else null
}
private fun parseNamedTupleFields(anchor: PsiElement, fields: Map<String, Optional<String>>, context: TypeEvalContext): NTFields {
val result = NTFields()
for ((name, type) in fields) {
result[name] = parseNamedTupleField(anchor, type.orElse(null), context)
}
return result
}
private fun parseNamedTupleField(anchor: PsiElement,
type: String?,
context: TypeEvalContext): PyNamedTupleType.FieldTypeAndDefaultValue {
if (type == null) return PyNamedTupleType.FieldTypeAndDefaultValue(null, null)
val pyType = Ref.deref(PyTypingTypeProvider.getStringBasedType(type, anchor, context))
return PyNamedTupleType.FieldTypeAndDefaultValue(pyType, null)
}
}
} | apache-2.0 |
Kotlin/dokka | plugins/base/src/test/kotlin/translators/JavadocInheritedDocTagsTest.kt | 1 | 8650 | package translators
import org.jetbrains.dokka.links.DRI
import org.jetbrains.dokka.links.PointingToDeclaration
import org.jetbrains.dokka.model.DModule
import org.jetbrains.dokka.model.doc.*
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstance
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.jetbrains.dokka.model.doc.Deprecated as DokkaDeprecatedTag
import org.jetbrains.dokka.model.doc.Throws as DokkaThrowsTag
class JavadocInheritedDocTagsTest : BaseAbstractTest() {
@Suppress("DEPRECATION") // for includeNonPublic
private val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src/main/java")
includeNonPublic = true
}
}
}
private fun performTagsTest(test: (DModule) -> Unit) {
testInline(
"""
|/src/main/java/sample/Superclass.java
|package sample;
|/**
|* @author super author
|*/
|class Superclass {
| /**
| * Sample super method
| *
| * @return super string
| * @throws RuntimeException super throws
| * @see java.lang.String super see
| * @deprecated super deprecated
| */
| public String test(){
| return "";
| }
|
| /**
| *
| * @param xd String superclass
| * @param asd Integer superclass
| */
| public void test2(String xd, Integer asd){
| }
|}
|/src/main/java/sample/Subclass.java
|package sample;
|/**
|* @author Ja, {@inheritDoc}
|*/
|class Subclass extends Superclass {
|/**
| * Sample sub method. {@inheritDoc}
| *
| * @return "sample string". {@inheritDoc}
| * @throws RuntimeException because i can, {@inheritDoc}
| * @throws IllegalStateException this should be it {@inheritDoc}
| * @see java.lang.String string, {@inheritDoc}
| * @deprecated do not use, {@inheritDoc}
| */
| @Override
| public String test() {
| return super.test();
| }
|
| /**
| *
| * @param asd2 integer subclass, {@inheritDoc}
| * @param xd2 string subclass, {@inheritDoc}
| */
| public void test2(String xd2, Integer asd2){
| }
|}
""".trimIndent(), configuration
) {
documentablesMergingStage = test
}
}
@Test
fun `work with return`() {
performTagsTest { module ->
val function = module.findFunction("sample", "Subclass", "test")
val renderedTag = function.documentation.values.first().children.firstIsInstance<Return>()
val expectedTag = Return(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("\"sample string\". super string"))
)
),
name = "MARKDOWN_FILE"
)
)
assertEquals(expectedTag, renderedTag)
}
}
@Test
fun `work with throws`() {
performTagsTest { module ->
val function = module.findFunction("sample", "Subclass", "test")
val renderedTag =
function.documentation.values.first().children.first { it is DokkaThrowsTag && it.name == "java.lang.RuntimeException" }
val expectedTag = DokkaThrowsTag(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("because i can, super throws"))
)
),
name = "MARKDOWN_FILE"
),
"java.lang.RuntimeException",
DRI("java.lang", "RuntimeException", target = PointingToDeclaration)
)
assertEquals(expectedTag, renderedTag)
}
}
@Test
fun `work with throws when exceptions are different`() {
performTagsTest { module ->
val function = module.findFunction("sample", "Subclass", "test")
val renderedTag =
function.documentation.values.first().children.first { it is DokkaThrowsTag && it.name == "java.lang.IllegalStateException" }
val expectedTag = DokkaThrowsTag(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("this should be it"))
)
),
name = "MARKDOWN_FILE"
),
"java.lang.IllegalStateException",
DRI("java.lang", "IllegalStateException", target = PointingToDeclaration)
)
assertEquals(expectedTag, renderedTag)
}
}
@Test
fun `work with deprecated`() {
performTagsTest { module ->
val function = module.findFunction("sample", "Subclass", "test")
val renderedTag = function.documentation.values.first().children.firstIsInstance<DokkaDeprecatedTag>()
val expectedTag = DokkaDeprecatedTag(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("do not use, Sample super method"))
)
),
name = "MARKDOWN_FILE"
),
)
assertEquals(expectedTag, renderedTag)
}
}
@Test
fun `work with see also`() {
performTagsTest { module ->
val function = module.findFunction("sample", "Subclass", "test")
val renderedTag = function.documentation.values.first().children.firstIsInstance<See>()
val expectedTag = See(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("string,"))
)
),
name = "MARKDOWN_FILE"
),
"java.lang.String",
DRI("java.lang", "String")
)
assertEquals(expectedTag, renderedTag)
}
}
@Test
fun `work with author`() {
performTagsTest { module ->
val classlike = module.findClasslike("sample", "Subclass")
val renderedTag = classlike.documentation.values.first().children.firstIsInstance<Author>()
val expectedTag = Author(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("Ja, super author"))
)
),
name = "MARKDOWN_FILE"
),
)
assertEquals(expectedTag, renderedTag)
}
}
@Test
fun `work with params`() {
performTagsTest { module ->
val function = module.findFunction("sample", "Subclass", "test2")
val (asdTag, xdTag) = function.documentation.values.first().children.filterIsInstance<Param>()
.sortedBy { it.name }
val expectedAsdTag = Param(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("integer subclass, Integer superclass"))
)
),
name = "MARKDOWN_FILE"
),
"asd2"
)
val expectedXdTag = Param(
CustomDocTag(
children = listOf(
P(
children = listOf(Text("string subclass, String superclass"))
)
),
name = "MARKDOWN_FILE"
),
"xd2"
)
assertEquals(expectedAsdTag, asdTag)
assertEquals(expectedXdTag, xdTag)
}
}
} | apache-2.0 |
Kotlin/dokka | integration-tests/gradle/projects/it-multimodule-0/moduleA/moduleD/src/main/kotlin/org/jetbrains/dokka/it/moduleD/ModuleC.kt | 1 | 118 | package org.jetbrains.dokka.it.moduleD
@Suppress("unused")
class ModuleD {
fun undocumentedPublicFunction() {}
}
| apache-2.0 |
googleapis/gax-kotlin | examples-android/app/src/main/java/com/google/api/kgax/examples/grpc/SpeechStreamingActivity.kt | 1 | 5309 | /*
* Copyright 2018 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.api.kgax.examples.grpc
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.test.espresso.idling.CountingIdlingResource
import android.support.v4.app.ActivityCompat
import android.util.Log
import com.google.api.kgax.examples.grpc.util.AudioEmitter
import com.google.api.kgax.grpc.StreamingCall
import com.google.api.kgax.grpc.StubFactory
import com.google.cloud.speech.v1.RecognitionConfig
import com.google.cloud.speech.v1.SpeechGrpc
import com.google.cloud.speech.v1.StreamingRecognitionConfig
import com.google.cloud.speech.v1.StreamingRecognizeRequest
import com.google.cloud.speech.v1.StreamingRecognizeResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlin.coroutines.CoroutineContext
private const val TAG = "APITest"
private const val REQUEST_RECORD_AUDIO_PERMISSION = 200
private val PERMISSIONS = arrayOf(Manifest.permission.RECORD_AUDIO)
/**
* Kotlin example showcasing streaming APIs using KGax with gRPC and the Google Speech API.
*/
@ExperimentalCoroutinesApi
class SpeechStreamingActivity : AbstractExampleActivity<SpeechGrpc.SpeechStub>(
CountingIdlingResource("SpeechStreaming")
) {
lateinit var job: Job
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
private var permissionToRecord = false
private val audioEmitter: AudioEmitter = AudioEmitter()
private var streams: SpeechStreams? = null
override val factory = StubFactory(
SpeechGrpc.SpeechStub::class, "speech.googleapis.com", 443
)
override val stub by lazy {
applicationContext.resources.openRawResource(R.raw.sa).use {
factory.fromServiceAccount(
it,
listOf("https://www.googleapis.com/auth/cloud-platform")
)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// get permissions
ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_RECORD_AUDIO_PERMISSION)
}
override fun onResume() {
super.onResume()
job = Job()
// kick-off recording process, if we're allowed
if (permissionToRecord) {
launch { streams = transcribe() }
}
}
override fun onPause() {
super.onPause()
// ensure mic data stops
launch {
audioEmitter.stop()
streams?.responses?.cancel()
job.cancel()
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
when (requestCode) {
REQUEST_RECORD_AUDIO_PERMISSION ->
permissionToRecord = grantResults[0] == PackageManager.PERMISSION_GRANTED
}
if (!permissionToRecord) {
Log.e(TAG, "No permission to record - please grant and retry!")
finish()
}
}
private suspend fun transcribe(): SpeechStreams {
// start streaming the data to the server and collect responses
val streams = stub.prepare {
withInitialRequest(StreamingRecognizeRequest.newBuilder().apply {
streamingConfig = StreamingRecognitionConfig.newBuilder().apply {
config = RecognitionConfig.newBuilder().apply {
languageCode = "en-US"
encoding = RecognitionConfig.AudioEncoding.LINEAR16
sampleRateHertz = 16000
}.build()
interimResults = false
singleUtterance = false
}.build()
}.build())
}.executeStreaming { it::streamingRecognize }
// monitor the input stream and send requests as audio data becomes available
launch(Dispatchers.IO) {
for (bytes in audioEmitter.start(this)) {
streams.requests.send(
StreamingRecognizeRequest.newBuilder().apply {
audioContent = bytes
}.build()
)
}
}
// handle incoming responses
launch(Dispatchers.Main) {
for (response in streams.responses) {
updateUIWithExampleResult(response.toString())
}
}
return streams
}
}
private typealias SpeechStreams = StreamingCall<StreamingRecognizeRequest, StreamingRecognizeResponse>
| apache-2.0 |
kibotu/RecyclerViewPresenter | lib/src/main/java/net/kibotu/android/recyclerviewpresenter/cirkle/MutableCircularList.kt | 1 | 5624 | /*
* MIT License
*
* Copyright (c) 2017 Todd Ginsberg
*
* 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 net.kibotu.android.recyclerviewpresenter.cirkle
import kotlin.math.absoluteValue
/**
* Implementation of a Circularly-addressable [kotlin.collections.MutableList], allowing negative
* indexes and positive indexes that are larger than the size of the List.
*/
class MutableCircularList<T>(private val list: MutableList<T>) : MutableList<T> by list {
/**
* Add the [element] at the specified [index].
*
* If the [index] is negative it is interpreted as an offset from the end of
* the list. If the [index] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.add
*/
override fun add(index: Int, element: T) =
list.add(index.safely(), element)
/**
* Add all of the [elements] starting at the specified [index].
*
* If the [index] is negative it is interpreted as an offset from the end of
* the list. If the [index] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.addAll
*/
override fun addAll(index: Int, elements: Collection<T>): Boolean =
list.addAll(index.safely(), elements)
/**
* Get the element at the specified [index].
*
* If the [index] is negative it is interpreted as an offset from the end of
* the list. If the [index] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.get
*/
override operator fun get(index: Int): T =
list[index.safely()]
/**
* Get a [kotlin.collections.ListIterator] starting at the specified [index]
*
* If the [index] is negative it is interpreted as an offset from the end of
* the list. If the [index] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.listIterator
*/
override fun listIterator(index: Int): MutableListIterator<T> =
list.listIterator(index.safely())
/**
* Remove the element at the specified [index].
*
* If the [index] is negative it is interpreted as an offset from the end of
* the list. If the [index] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.removeAt
*/
override fun removeAt(index: Int): T =
list.removeAt(index.safely())
/**
* Replace the existing element at the specified [index] with the given [element].
*
* If the [index] is negative it is interpreted as an offset from the end of
* the list. If the [index] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.set
*/
override fun set(index: Int, element: T): T =
list.set(index.safely(), element)
/**
* Get a List bound by [fromIndex] inclusive to [toIndex] exclusive
*
* If [fromIndex] or [toIndex] is negative they are interpreted as an offset from the end of
* the list. If the [fromIndex] or [toIndex] is positive and beyond the bounds of the underlying list,
* it wraps around again from the start of the list.
*
* @sample samples.Cirkle.MutableCircularList.subList
*/
override fun subList(fromIndex: Int, toIndex: Int): MutableList<T> {
val result = mutableListOf<T>()
var rest = (toIndex - fromIndex).absoluteValue
val list = if (toIndex < fromIndex)
list.asReversed()
else
list
while (rest > 0) {
if (rest > list.size) {
result.addAll(list.subList(0, list.size))
rest -= list.size
} else {
result.addAll(list.subList(0, rest))
rest = 0
}
}
return result
}
/**
* Returns a String representation of the object.
*/
override fun toString(): String =
list.toString()
private fun Int.safely(): Int =
if (this < 0) (this % lastIndex + lastIndex) % lastIndex
else this % lastIndex
} | apache-2.0 |
google/ksp | gradle-plugin/src/main/kotlin/com/google/devtools/ksp/gradle/KspSubplugin.kt | 1 | 43840 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
package com.google.devtools.ksp.gradle
import com.google.devtools.ksp.gradle.model.builder.KspModelBuilder
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.UnknownTaskException
import org.gradle.api.artifacts.Configuration
import org.gradle.api.attributes.Attribute
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.FileCollection
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Property
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderFactory
import org.gradle.api.tasks.*
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.compile.JavaCompile
import org.gradle.language.jvm.tasks.ProcessResources
import org.gradle.process.CommandLineArgumentProvider
import org.gradle.process.ExecOperations
import org.gradle.tooling.provider.model.ToolingModelBuilderRegistry
import org.gradle.util.GradleVersion
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
import org.gradle.workers.WorkerExecutor
import org.jetbrains.kotlin.cli.common.arguments.*
import org.jetbrains.kotlin.config.ApiVersion
import org.jetbrains.kotlin.gradle.dsl.*
import org.jetbrains.kotlin.gradle.internal.CompilerArgumentsContributor
import org.jetbrains.kotlin.gradle.internal.compilerArgumentsConfigurationFlags
import org.jetbrains.kotlin.gradle.internal.kapt.incremental.*
import org.jetbrains.kotlin.gradle.plugin.*
import org.jetbrains.kotlin.gradle.plugin.mpp.*
import org.jetbrains.kotlin.gradle.targets.js.ir.*
import org.jetbrains.kotlin.gradle.tasks.*
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
import org.jetbrains.kotlin.gradle.tasks.configuration.AbstractKotlinCompileConfig
import org.jetbrains.kotlin.gradle.utils.klibModuleName
import org.jetbrains.kotlin.incremental.ChangedFiles
import org.jetbrains.kotlin.incremental.destinationAsFile
import org.jetbrains.kotlin.incremental.isJavaFile
import org.jetbrains.kotlin.incremental.isKotlinFile
import org.jetbrains.kotlin.utils.addToStdlib.ifNotEmpty
import java.io.File
import java.nio.file.Paths
import java.util.concurrent.Callable
import javax.inject.Inject
import kotlin.reflect.KProperty1
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "EXPOSED_PARAMETER_TYPE")
internal class Configurator : AbstractKotlinCompileConfig<AbstractKotlinCompile<*>> {
constructor (
compilation: KotlinCompilation<*>,
kotlinCompile: AbstractKotlinCompile<*>
) : super(KotlinCompilationInfo(compilation)) {
configureTask { task ->
if (task is KspTaskJvm) {
// Assign ownModuleName different from kotlin compilation to
// work around https://github.com/google/ksp/issues/647
// This will not be necessary once https://youtrack.jetbrains.com/issue/KT-45777 lands
task.ownModuleName.value(kotlinCompile.ownModuleName.map { "$it-ksp" })
(compilation.compilerOptions.options as? KotlinJvmCompilerOptions)?.let {
task.compilerOptions.noJdk.value(it.noJdk)
}
}
if (task is KspTaskJS) {
val libraryCacheService = project.rootProject.gradle.sharedServices.registerIfAbsent(
Kotlin2JsCompile.LibraryFilterCachingService::class.java.canonicalName +
"_${Kotlin2JsCompile.LibraryFilterCachingService::class.java.classLoader.hashCode()}",
Kotlin2JsCompile.LibraryFilterCachingService::class.java
) {}
task.compilerOptions.moduleName.convention(kotlinCompile.ownModuleName.map { "$it-ksp" })
task.libraryCache.set(libraryCacheService).also { task.libraryCache.disallowChanges() }
task.pluginClasspath.setFrom(objectFactory.fileCollection())
task.outputFileProperty.value(
task.destinationDirectory.flatMap { dir ->
if (task.compilerOptions.outputFile.orNull != null) {
task.compilerOptions.outputFile.map { File(it) }
} else {
task.compilerOptions.moduleName.map { name ->
dir.file(name + compilation.platformType.fileExtension).asFile
}
}
}
)
task.enhancedFreeCompilerArgs.value(
(kotlinCompile as Kotlin2JsCompile).compilerOptions.freeCompilerArgs.map { freeArgs ->
freeArgs.toMutableList().apply {
commonJsAdditionalCompilerFlags(compilation)
}
}
).disallowChanges()
}
}
}
// copied from upstream.
protected fun MutableList<String>.commonJsAdditionalCompilerFlags(
compilation: KotlinCompilation<*>
) {
if (contains(DISABLE_PRE_IR) &&
!contains(PRODUCE_UNZIPPED_KLIB) &&
!contains(PRODUCE_ZIPPED_KLIB)
) {
add(PRODUCE_UNZIPPED_KLIB)
}
if (contains(PRODUCE_JS) ||
contains(PRODUCE_UNZIPPED_KLIB) ||
contains(PRODUCE_ZIPPED_KLIB)
) {
// Configure FQ module name to avoid cyclic dependencies in klib manifests (see KT-36721).
val baseName = if (compilation.isMain()) {
project.name
} else {
"${project.name}_${compilation.compilationName}"
}
if (none { it.startsWith(KLIB_MODULE_NAME) }) {
add("$KLIB_MODULE_NAME=${project.klibModuleName(baseName)}")
}
}
}
}
class KspGradleSubplugin @Inject internal constructor(private val registry: ToolingModelBuilderRegistry) :
KotlinCompilerPluginSupportPlugin {
companion object {
const val KSP_PLUGIN_ID = "com.google.devtools.ksp.symbol-processing"
const val KSP_API_ID = "symbol-processing-api"
const val KSP_COMPILER_PLUGIN_ID = "symbol-processing"
const val KSP_GROUP_ID = "com.google.devtools.ksp"
const val KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME = "kspPluginClasspath"
@JvmStatic
fun getKspOutputDir(project: Project, sourceSetName: String, target: String) =
File(project.project.buildDir, "generated/ksp/$target/$sourceSetName")
@JvmStatic
fun getKspClassOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "classes")
@JvmStatic
fun getKspJavaOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "java")
@JvmStatic
fun getKspKotlinOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "kotlin")
@JvmStatic
fun getKspResourceOutputDir(project: Project, sourceSetName: String, target: String) =
File(getKspOutputDir(project, sourceSetName, target), "resources")
@JvmStatic
fun getKspCachesDir(project: Project, sourceSetName: String, target: String) =
File(project.project.buildDir, "kspCaches/$target/$sourceSetName")
@JvmStatic
private fun getSubpluginOptions(
project: Project,
kspExtension: KspExtension,
classpath: Configuration,
sourceSetName: String,
target: String,
isIncremental: Boolean,
allWarningsAsErrors: Boolean,
commandLineArgumentProviders: ListProperty<CommandLineArgumentProvider>,
): List<SubpluginOption> {
val options = mutableListOf<SubpluginOption>()
options += SubpluginOption("classOutputDir", getKspClassOutputDir(project, sourceSetName, target).path)
options += SubpluginOption("javaOutputDir", getKspJavaOutputDir(project, sourceSetName, target).path)
options += SubpluginOption("kotlinOutputDir", getKspKotlinOutputDir(project, sourceSetName, target).path)
options += SubpluginOption(
"resourceOutputDir",
getKspResourceOutputDir(project, sourceSetName, target).path
)
options += SubpluginOption("cachesDir", getKspCachesDir(project, sourceSetName, target).path)
options += SubpluginOption("kspOutputDir", getKspOutputDir(project, sourceSetName, target).path)
options += SubpluginOption("incremental", isIncremental.toString())
options += SubpluginOption(
"incrementalLog",
project.findProperty("ksp.incremental.log")?.toString() ?: "false"
)
options += SubpluginOption("projectBaseDir", project.project.projectDir.canonicalPath)
options += SubpluginOption("allWarningsAsErrors", allWarningsAsErrors.toString())
options += FilesSubpluginOption("apclasspath", classpath.toList())
// Turn this on by default to work KT-30172 around. It is off by default in the compiler plugin.
options += SubpluginOption(
"returnOkOnError",
project.findProperty("ksp.return.ok.on.error")?.toString() ?: "true"
)
kspExtension.apOptions.forEach {
options += SubpluginOption("apoption", "${it.key}=${it.value}")
}
commandLineArgumentProviders.get().forEach {
val argument = it.asArguments().joinToString("")
if (!argument.matches(Regex("\\S+=\\S+"))) {
throw IllegalArgumentException("KSP apoption does not match \\S+=\\S+: $argument")
}
options += SubpluginOption("apoption", argument)
}
return options
}
}
private lateinit var kspConfigurations: KspConfigurations
override fun apply(target: Project) {
target.extensions.create("ksp", KspExtension::class.java)
kspConfigurations = KspConfigurations(target)
registry.register(KspModelBuilder())
}
override fun isApplicable(kotlinCompilation: KotlinCompilation<*>): Boolean {
val project = kotlinCompilation.target.project
val kspVersion = ApiVersion.parse(KSP_KOTLIN_BASE_VERSION)!!
val kotlinVersion = ApiVersion.parse(project.getKotlinPluginVersion())!!
// Check version and show warning by default.
val noVersionCheck = project.findProperty("ksp.version.check")?.toString()?.toBoolean() == false
if (!noVersionCheck) {
if (kspVersion < kotlinVersion) {
project.logger.warn(
"ksp-$KSP_VERSION is too old for kotlin-$kotlinVersion. " +
"Please upgrade ksp or downgrade kotlin-gradle-plugin to $KSP_KOTLIN_BASE_VERSION."
)
}
if (kspVersion > kotlinVersion) {
project.logger.warn(
"ksp-$KSP_VERSION is too new for kotlin-$kotlinVersion. " +
"Please upgrade kotlin-gradle-plugin to $KSP_KOTLIN_BASE_VERSION."
)
}
}
return true
}
override fun applyToCompilation(kotlinCompilation: KotlinCompilation<*>): Provider<List<SubpluginOption>> {
val project = kotlinCompilation.target.project
val kotlinCompileProvider: TaskProvider<AbstractKotlinCompileTool<*>> =
project.locateTask(kotlinCompilation.compileKotlinTaskName) ?: return project.provider { emptyList() }
val javaCompile = findJavaTaskForKotlinCompilation(kotlinCompilation)?.get()
val kspExtension = project.extensions.getByType(KspExtension::class.java)
val kspConfigurations = kspConfigurations.find(kotlinCompilation)
val nonEmptyKspConfigurations = kspConfigurations.filter { it.allDependencies.isNotEmpty() }
if (nonEmptyKspConfigurations.isEmpty()) {
return project.provider { emptyList() }
}
if (kotlinCompileProvider.name == "compileKotlinMetadata") {
return project.provider { emptyList() }
}
val target = kotlinCompilation.target.name
val sourceSetName = kotlinCompilation.defaultSourceSet.name
val classOutputDir = getKspClassOutputDir(project, sourceSetName, target)
val javaOutputDir = getKspJavaOutputDir(project, sourceSetName, target)
val kotlinOutputDir = getKspKotlinOutputDir(project, sourceSetName, target)
val resourceOutputDir = getKspResourceOutputDir(project, sourceSetName, target)
val kspOutputDir = getKspOutputDir(project, sourceSetName, target)
val kspClasspathCfg = project.configurations.maybeCreate(KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME)
project.dependencies.add(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME,
"$KSP_GROUP_ID:$KSP_API_ID:$KSP_VERSION"
)
project.dependencies.add(
KSP_PLUGIN_CLASSPATH_CONFIGURATION_NAME,
"$KSP_GROUP_ID:$KSP_COMPILER_PLUGIN_ID:$KSP_VERSION"
)
if (javaCompile != null) {
val generatedJavaSources = javaCompile.project.fileTree(javaOutputDir)
generatedJavaSources.include("**/*.java")
javaCompile.source(generatedJavaSources)
javaCompile.classpath += project.files(classOutputDir)
}
assert(kotlinCompileProvider.name.startsWith("compile"))
val kspTaskName = kotlinCompileProvider.name.replaceFirst("compile", "ksp")
val kotlinCompileTask = kotlinCompileProvider.get()
fun configureAsKspTask(kspTask: KspTask, isIncremental: Boolean) {
// depends on the processor; if the processor changes, it needs to be reprocessed.
val processorClasspath = project.configurations.maybeCreate("${kspTaskName}ProcessorClasspath")
.extendsFrom(*nonEmptyKspConfigurations.toTypedArray())
kspTask.processorClasspath.from(processorClasspath)
kspTask.dependsOn(processorClasspath.buildDependencies)
kspTask.commandLineArgumentProviders.addAll(kspExtension.commandLineArgumentProviders)
kspTask.options.addAll(
kspTask.project.provider {
getSubpluginOptions(
project,
kspExtension,
processorClasspath,
sourceSetName,
target,
isIncremental,
kspExtension.allWarningsAsErrors,
kspTask.commandLineArgumentProviders
)
}
)
kspTask.destination = kspOutputDir
kspTask.blockOtherCompilerPlugins = kspExtension.blockOtherCompilerPlugins
kspTask.apOptions.value(kspExtension.arguments).disallowChanges()
kspTask.kspCacheDir.fileValue(getKspCachesDir(project, sourceSetName, target)).disallowChanges()
if (kspExtension.blockOtherCompilerPlugins) {
kspTask.overridePluginClasspath.from(kspClasspathCfg)
}
kspTask.isKspIncremental = isIncremental
}
fun configureAsAbstractKotlinCompileTool(kspTask: AbstractKotlinCompileTool<*>) {
kspTask.destinationDirectory.set(kspOutputDir)
kspTask.outputs.dirs(
kotlinOutputDir,
javaOutputDir,
classOutputDir,
resourceOutputDir
)
if (kspExtension.allowSourcesFromOtherPlugins) {
val deps = kotlinCompileTask.dependsOn.filterNot {
(it as? TaskProvider<*>)?.name == kspTaskName ||
(it as? Task)?.name == kspTaskName
}
kspTask.dependsOn(deps)
kspTask.setSource(kotlinCompileTask.sources)
if (kotlinCompileTask is KotlinCompile) {
kspTask.setSource(kotlinCompileTask.javaSources)
}
} else {
kotlinCompilation.allKotlinSourceSets.forEach { sourceSet ->
kspTask.setSource(sourceSet.kotlin)
}
if (kotlinCompilation is KotlinCommonCompilation) {
kspTask.setSource(kotlinCompilation.defaultSourceSet.kotlin)
}
}
// Don't support binary generation for non-JVM platforms yet.
// FIXME: figure out how to add user generated libraries.
if (kspTask is KspTaskJvm) {
kotlinCompilation.output.classesDirs.from(classOutputDir)
}
}
val kspTaskProvider = when (kotlinCompileTask) {
is AbstractKotlinCompile<*> -> {
val kspTaskClass = when (kotlinCompileTask) {
is KotlinCompile -> KspTaskJvm::class.java
is Kotlin2JsCompile -> KspTaskJS::class.java
is KotlinCompileCommon -> KspTaskMetadata::class.java
else -> return project.provider { emptyList() }
}
val isIncremental = project.findProperty("ksp.incremental")?.toString()?.toBoolean() ?: true
project.tasks.register(kspTaskName, kspTaskClass) { kspTask ->
configureAsKspTask(kspTask, isIncremental)
configureAsAbstractKotlinCompileTool(kspTask)
kspTask.libraries.setFrom(kotlinCompileTask.project.files(Callable { kotlinCompileTask.libraries }))
kspTask.configureCompilation(
kotlinCompilation,
kotlinCompileTask,
)
}
}
is KotlinNativeCompile -> {
val kspTaskClass = KspTaskNative::class.java
project.tasks.register(kspTaskName, kspTaskClass, kotlinCompileTask.compilation).apply {
configure { kspTask ->
kspTask.onlyIf {
kspTask.konanTarget.enabledOnCurrentHost
}
configureAsKspTask(kspTask, false)
configureAsAbstractKotlinCompileTool(kspTask)
// KotlinNativeCompile computes -Xplugin=... from compilerPluginClasspath.
if (kspExtension.blockOtherCompilerPlugins) {
kspTask.compilerPluginClasspath = kspClasspathCfg
} else {
kspTask.compilerPluginClasspath =
kspClasspathCfg + kotlinCompileTask.compilerPluginClasspath!!
kspTask.compilerPluginOptions.addPluginArgument(kotlinCompileTask.compilerPluginOptions)
}
kspTask.commonSources.from(kotlinCompileTask.commonSources)
val kspOptions = kspTask.options.get().flatMap { listOf("-P", it.toArg()) }
kspTask.compilerOptions.freeCompilerArgs.value(
kspOptions + kotlinCompileTask.compilerOptions.freeCompilerArgs.get()
)
kspTask.doFirst {
kspOutputDir.deleteRecursively()
}
}
}
}
else -> return project.provider { emptyList() }
}
(kotlinCompileTask as? AbstractKotlinCompile<*>)?.let {
Configurator(kotlinCompilation, kotlinCompileTask as AbstractKotlinCompile<*>)
.execute(kspTaskProvider as TaskProvider<AbstractKotlinCompile<*>>)
}
kotlinCompileProvider.configure { kotlinCompile ->
kotlinCompile.dependsOn(kspTaskProvider)
kotlinCompile.setSource(kotlinOutputDir, javaOutputDir)
when (kotlinCompile) {
is AbstractKotlinCompile<*> -> kotlinCompile.libraries.from(project.files(classOutputDir))
// is KotlinNativeCompile -> TODO: support binary generation?
}
}
val processResourcesTaskName =
(kotlinCompilation as? KotlinCompilationWithResources)?.processResourcesTaskName ?: "processResources"
project.locateTask<ProcessResources>(processResourcesTaskName)?.let { provider ->
provider.configure { resourcesTask ->
resourcesTask.dependsOn(kspTaskProvider)
resourcesTask.from(resourceOutputDir)
}
}
if (kotlinCompilation is KotlinJvmAndroidCompilation) {
AndroidPluginIntegration.registerGeneratedSources(
project = project,
kotlinCompilation = kotlinCompilation,
kspTaskProvider = kspTaskProvider as TaskProvider<KspTaskJvm>,
javaOutputDir = javaOutputDir,
kotlinOutputDir = kotlinOutputDir,
classOutputDir = classOutputDir,
resourcesOutputDir = project.files(resourceOutputDir)
)
}
return project.provider { emptyList() }
}
override fun getCompilerPluginId() = KSP_PLUGIN_ID
override fun getPluginArtifact(): SubpluginArtifact =
SubpluginArtifact(
groupId = "com.google.devtools.ksp",
artifactId = KSP_COMPILER_PLUGIN_ID,
version = KSP_VERSION
)
override fun getPluginArtifactForNative(): SubpluginArtifact? =
SubpluginArtifact(
groupId = "com.google.devtools.ksp",
artifactId = KSP_COMPILER_PLUGIN_ID,
version = KSP_VERSION
)
val apiArtifact = "com.google.devtools.ksp:symbol-processing-api:$KSP_VERSION"
}
private val artifactType = Attribute.of("artifactType", String::class.java)
// Copied from kotlin-gradle-plugin, because they are internal.
internal inline fun <reified T : Task> Project.locateTask(name: String): TaskProvider<T>? =
try {
tasks.withType(T::class.java).named(name)
} catch (e: UnknownTaskException) {
null
}
// Copied from kotlin-gradle-plugin, because they are internal.
internal fun findJavaTaskForKotlinCompilation(compilation: KotlinCompilation<*>): TaskProvider<out JavaCompile>? =
when (compilation) {
is KotlinJvmAndroidCompilation -> compilation.compileJavaTaskProvider
is KotlinWithJavaCompilation<*, *> -> compilation.compileJavaTaskProvider
is KotlinJvmCompilation -> compilation.compileJavaTaskProvider // may be null for Kotlin-only JVM target in MPP
else -> null
}
interface KspTask : Task {
@get:Internal
val options: ListProperty<SubpluginOption>
@get:Nested
val commandLineArgumentProviders: ListProperty<CommandLineArgumentProvider>
@get:OutputDirectory
var destination: File
@get:Optional
@get:Classpath
val overridePluginClasspath: ConfigurableFileCollection
@get:Input
var blockOtherCompilerPlugins: Boolean
@get:Input
val apOptions: MapProperty<String, String>
@get:Classpath
val processorClasspath: ConfigurableFileCollection
/**
* Output directory that contains caches necessary to support incremental annotation processing.
*/
@get:LocalState
val kspCacheDir: DirectoryProperty
@get:Input
var isKspIncremental: Boolean
fun configureCompilation(
kotlinCompilation: KotlinCompilation<*>,
kotlinCompile: AbstractKotlinCompile<*>,
)
}
@CacheableTask
abstract class KspTaskJvm @Inject constructor(
workerExecutor: WorkerExecutor,
objectFactory: ObjectFactory
) : KotlinCompile(
objectFactory.newInstance(KotlinJvmCompilerOptionsDefault::class.java),
workerExecutor,
objectFactory
),
KspTask {
@get:PathSensitive(PathSensitivity.NONE)
@get:Optional
@get:InputFiles
@get:Incremental
abstract val classpathStructure: ConfigurableFileCollection
@get:Input
var isIntermoduleIncremental: Boolean = false
override fun configureCompilation(
kotlinCompilation: KotlinCompilation<*>,
kotlinCompile: AbstractKotlinCompile<*>,
) {
kotlinCompile as KotlinCompile
val providerFactory = kotlinCompile.project.providers
compileKotlinArgumentsContributor.set(
providerFactory.provider {
kotlinCompile.compilerArgumentsContributor
}
)
isIntermoduleIncremental =
(project.findProperty("ksp.incremental.intermodule")?.toString()?.toBoolean() ?: true) &&
isKspIncremental
if (isIntermoduleIncremental) {
val classStructureIfIncremental = project.configurations.detachedConfiguration(
project.dependencies.create(project.files(project.provider { kotlinCompile.libraries }))
)
maybeRegisterTransform(project)
classpathStructure.from(
classStructureIfIncremental.incoming.artifactView { viewConfig ->
viewConfig.attributes.attribute(artifactType, CLASS_STRUCTURE_ARTIFACT_TYPE)
}.files
).disallowChanges()
classpathSnapshotProperties.useClasspathSnapshot.value(true).disallowChanges()
} else {
classpathSnapshotProperties.useClasspathSnapshot.value(false).disallowChanges()
}
// Used only in incremental compilation and is not applicable to KSP.
useKotlinAbiSnapshot.value(false)
}
private fun maybeRegisterTransform(project: Project) {
// Use the same flag with KAPT, so as to share the same transformation in case KAPT and KSP are both enabled.
if (!project.extensions.extraProperties.has("KaptStructureTransformAdded")) {
val transformActionClass =
if (GradleVersion.current() >= GradleVersion.version("5.4"))
StructureTransformAction::class.java
else
StructureTransformLegacyAction::class.java
project.dependencies.registerTransform(transformActionClass) { transformSpec ->
transformSpec.from.attribute(artifactType, "jar")
transformSpec.to.attribute(artifactType, CLASS_STRUCTURE_ARTIFACT_TYPE)
}
project.dependencies.registerTransform(transformActionClass) { transformSpec ->
transformSpec.from.attribute(artifactType, "directory")
transformSpec.to.attribute(artifactType, CLASS_STRUCTURE_ARTIFACT_TYPE)
}
project.extensions.extraProperties["KaptStructureTransformAdded"] = true
}
}
// Reuse Kapt's infrastructure to compute affected names in classpath.
// This is adapted from KaptTask.findClasspathChanges.
private fun findClasspathChanges(
changes: ChangedFiles,
): KaptClasspathChanges {
val cacheDir = kspCacheDir.asFile.get()
cacheDir.mkdirs()
val allDataFiles = classpathStructure.files
val changedFiles = (changes as? ChangedFiles.Known)?.let { it.modified + it.removed }?.toSet() ?: allDataFiles
val loadedPrevious = ClasspathSnapshot.ClasspathSnapshotFactory.loadFrom(cacheDir)
val previousAndCurrentDataFiles = lazy { loadedPrevious.getAllDataFiles() + allDataFiles }
val allChangesRecognized = changedFiles.all {
val extension = it.extension
if (extension.isEmpty() || extension == "kt" || extension == "java" || extension == "jar" ||
extension == "class"
) {
return@all true
}
// if not a directory, Java source file, jar, or class, it has to be a structure file, in order to understand changes
it in previousAndCurrentDataFiles.value
}
val previousSnapshot = if (allChangesRecognized) {
loadedPrevious
} else {
ClasspathSnapshot.ClasspathSnapshotFactory.getEmptySnapshot()
}
val currentSnapshot =
ClasspathSnapshot.ClasspathSnapshotFactory.createCurrent(
cacheDir,
libraries.files.toList(),
processorClasspath.files.toList(),
allDataFiles
)
val classpathChanges = currentSnapshot.diff(previousSnapshot, changedFiles)
if (classpathChanges is KaptClasspathChanges.Unknown || changes is ChangedFiles.Unknown) {
clearIncCache()
cacheDir.mkdirs()
}
currentSnapshot.writeToCache()
return classpathChanges
}
@get:Internal
internal abstract val compileKotlinArgumentsContributor:
Property<CompilerArgumentsContributor<K2JVMCompilerArguments>>
init {
// kotlinc's incremental compilation isn't compatible with symbol processing in a few ways:
// * It doesn't consider private / internal changes when computing dirty sets.
// * It compiles iteratively; Sources can be compiled in different rounds.
incremental = false
// Mute a warning from ScriptingGradleSubplugin, which tries to get `sourceSetName` before this task is
// configured.
sourceSetName.set("main")
}
override fun setupCompilerArgs(
args: K2JVMCompilerArguments,
defaultsOnly: Boolean,
ignoreClasspathResolutionErrors: Boolean,
) {
// Start with / copy from kotlinCompile.
compileKotlinArgumentsContributor.get().contributeArguments(
args,
compilerArgumentsConfigurationFlags(
defaultsOnly,
ignoreClasspathResolutionErrors
)
)
(compilerOptions as KotlinJvmCompilerOptionsDefault).fillCompilerArguments(args)
if (blockOtherCompilerPlugins) {
args.blockOtherPlugins(overridePluginClasspath)
}
args.addPluginOptions(options.get())
args.destinationAsFile = destination
args.allowNoSourceFiles = true
args.useK2 = false
}
// Overrding an internal function is hacky.
// TODO: Ask upstream to open it.
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "EXPOSED_PARAMETER_TYPE")
fun `callCompilerAsync$kotlin_gradle_plugin_common`(
args: K2JVMCompilerArguments,
kotlinSources: Set<File>,
inputChanges: InputChanges,
taskOutputsBackup: TaskOutputsBackup?
) {
val changedFiles = getChangedFiles(inputChanges, incrementalProps)
if (isKspIncremental) {
if (isIntermoduleIncremental) {
// findClasspathChanges may clear caches, if there are
// 1. unknown changes, or
// 2. changes in annotation processors.
val classpathChanges = findClasspathChanges(changedFiles)
args.addChangedClasses(classpathChanges)
} else {
if (changedFiles.hasNonSourceChange()) {
clearIncCache()
}
}
} else {
clearIncCache()
}
args.addChangedFiles(changedFiles)
super.callCompilerAsync(args, kotlinSources, inputChanges, taskOutputsBackup)
}
override fun skipCondition(): Boolean = sources.isEmpty && javaSources.isEmpty
override val incrementalProps: List<FileCollection>
get() = listOf(
sources,
javaSources,
commonSourceSet,
classpathSnapshotProperties.classpath,
classpathSnapshotProperties.classpathSnapshot
)
@get:InputFiles
@get:SkipWhenEmpty
@get:IgnoreEmptyDirectories
@get:PathSensitive(PathSensitivity.RELATIVE)
override val sources: FileCollection = super.sources.filter {
!destination.isParentOf(it)
}
@get:InputFiles
@get:SkipWhenEmpty
@get:IgnoreEmptyDirectories
@get:PathSensitive(PathSensitivity.RELATIVE)
override val javaSources: FileCollection = super.javaSources.filter {
!destination.isParentOf(it)
}
}
@CacheableTask
abstract class KspTaskJS @Inject constructor(
objectFactory: ObjectFactory,
workerExecutor: WorkerExecutor
) : Kotlin2JsCompile(
objectFactory.newInstance(KotlinJsCompilerOptionsDefault::class.java),
objectFactory,
workerExecutor
),
KspTask {
private val backendSelectionArgs = listOf(
"-Xir-only",
"-Xir-produce-js",
"-Xir-produce-klib-dir",
"-Xir-produce-klib-file"
)
override fun configureCompilation(
kotlinCompilation: KotlinCompilation<*>,
kotlinCompile: AbstractKotlinCompile<*>,
) {
kotlinCompile as Kotlin2JsCompile
val providerFactory = kotlinCompile.project.providers
compileKotlinArgumentsContributor.set(
providerFactory.provider {
kotlinCompile.abstractKotlinCompileArgumentsContributor
}
)
}
@get:Internal
internal abstract val compileKotlinArgumentsContributor:
Property<CompilerArgumentsContributor<K2JSCompilerArguments>>
init {
// kotlinc's incremental compilation isn't compatible with symbol processing in a few ways:
// * It doesn't consider private / internal changes when computing dirty sets.
// * It compiles iteratively; Sources can be compiled in different rounds.
incremental = false
}
override fun setupCompilerArgs(
args: K2JSCompilerArguments,
defaultsOnly: Boolean,
ignoreClasspathResolutionErrors: Boolean,
) {
// Start with / copy from kotlinCompile.
compileKotlinArgumentsContributor.get().contributeArguments(
args,
compilerArgumentsConfigurationFlags(
defaultsOnly,
ignoreClasspathResolutionErrors
)
)
(compilerOptions as KotlinJsCompilerOptionsDefault).fillCompilerArguments(args)
if (blockOtherCompilerPlugins) {
args.blockOtherPlugins(overridePluginClasspath)
}
args.addPluginOptions(options.get())
args.outputFile = File(destination, "dummyOutput.js").canonicalPath
args.useK2 = false
args.outputDir = destination.canonicalPath
}
// Overrding an internal function is hacky.
// TODO: Ask upstream to open it.
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "EXPOSED_PARAMETER_TYPE")
fun `callCompilerAsync$kotlin_gradle_plugin_common`(
args: K2JSCompilerArguments,
kotlinSources: Set<File>,
inputChanges: InputChanges,
taskOutputsBackup: TaskOutputsBackup?
) {
val changedFiles = getChangedFiles(inputChanges, incrementalProps)
if (!isKspIncremental || changedFiles.hasNonSourceChange()) {
clearIncCache()
} else {
args.addChangedFiles(changedFiles)
}
args.freeArgs = enhancedFreeCompilerArgs.get()
super.callCompilerAsync(args, kotlinSources, inputChanges, taskOutputsBackup)
}
// Overrding an internal function is hacky.
// TODO: Ask upstream to open it.
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "EXPOSED_PARAMETER_TYPE")
fun `isIncrementalCompilationEnabled$kotlin_gradle_plugin_common`(): Boolean = false
@get:InputFiles
@get:SkipWhenEmpty
@get:IgnoreEmptyDirectories
@get:PathSensitive(PathSensitivity.RELATIVE)
override val sources: FileCollection = super.sources.filter {
!destination.isParentOf(it)
}
}
@CacheableTask
abstract class KspTaskMetadata @Inject constructor(
workerExecutor: WorkerExecutor,
objectFactory: ObjectFactory
) : KotlinCompileCommon(
objectFactory.newInstance(KotlinMultiplatformCommonCompilerOptionsDefault::class.java),
workerExecutor,
objectFactory
),
KspTask {
override fun configureCompilation(
kotlinCompilation: KotlinCompilation<*>,
kotlinCompile: AbstractKotlinCompile<*>,
) {
kotlinCompile as KotlinCompileCommon
val providerFactory = kotlinCompile.project.providers
compileKotlinArgumentsContributor.set(
providerFactory.provider {
kotlinCompile.abstractKotlinCompileArgumentsContributor
}
)
}
@get:Internal
internal abstract val compileKotlinArgumentsContributor:
Property<CompilerArgumentsContributor<K2MetadataCompilerArguments>>
init {
// kotlinc's incremental compilation isn't compatible with symbol processing in a few ways:
// * It doesn't consider private / internal changes when computing dirty sets.
// * It compiles iteratively; Sources can be compiled in different rounds.
incremental = false
}
override fun setupCompilerArgs(
args: K2MetadataCompilerArguments,
defaultsOnly: Boolean,
ignoreClasspathResolutionErrors: Boolean,
) {
// Start with / copy from kotlinCompile.
compileKotlinArgumentsContributor.get().contributeArguments(
args,
compilerArgumentsConfigurationFlags(
defaultsOnly,
ignoreClasspathResolutionErrors
)
)
(compilerOptions as KotlinMultiplatformCommonCompilerOptionsDefault).fillCompilerArguments(args)
if (blockOtherCompilerPlugins) {
args.blockOtherPlugins(overridePluginClasspath)
}
args.addPluginOptions(options.get())
args.destination = destination.canonicalPath
val classpathList = libraries.files.filter { it.exists() }.toMutableList()
args.classpath = classpathList.joinToString(File.pathSeparator)
args.friendPaths = friendPaths.files.map { it.absolutePath }.toTypedArray()
args.refinesPaths = refinesMetadataPaths.map { it.absolutePath }.toTypedArray()
args.expectActualLinker = true
args.useK2 = false
}
// Overrding an internal function is hacky.
// TODO: Ask upstream to open it.
@Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER", "EXPOSED_PARAMETER_TYPE")
fun `callCompilerAsync$kotlin_gradle_plugin_common`(
args: K2MetadataCompilerArguments,
kotlinSources: Set<File>,
inputChanges: InputChanges,
taskOutputsBackup: TaskOutputsBackup?
) {
val changedFiles = getChangedFiles(inputChanges, incrementalProps)
if (!isKspIncremental || changedFiles.hasNonSourceChange()) {
clearIncCache()
} else {
args.addChangedFiles(changedFiles)
}
super.callCompilerAsync(args, kotlinSources, inputChanges, taskOutputsBackup)
}
@get:InputFiles
@get:SkipWhenEmpty
@get:IgnoreEmptyDirectories
@get:PathSensitive(PathSensitivity.RELATIVE)
override val sources: FileCollection = super.sources.filter {
!destination.isParentOf(it)
}
}
@CacheableTask
abstract class KspTaskNative @Inject internal constructor(
compilation: KotlinCompilationInfo,
objectFactory: ObjectFactory,
providerFactory: ProviderFactory,
execOperations: ExecOperations
) : KotlinNativeCompile(compilation, objectFactory, providerFactory, execOperations), KspTask {
override val compilerOptions: KotlinCommonCompilerOptions =
objectFactory.newInstance(KotlinMultiplatformCommonCompilerOptionsDefault::class.java)
override fun configureCompilation(
kotlinCompilation: KotlinCompilation<*>,
kotlinCompile: AbstractKotlinCompile<*>,
) = Unit
@get:InputFiles
@get:SkipWhenEmpty
@get:IgnoreEmptyDirectories
@get:PathSensitive(PathSensitivity.RELATIVE)
override val sources: FileCollection = super.sources.filter {
!destination.isParentOf(it)
}
}
// This forces rebuild.
private fun KspTask.clearIncCache() {
kspCacheDir.get().asFile.deleteRecursively()
}
private fun ChangedFiles.hasNonSourceChange(): Boolean {
if (this !is ChangedFiles.Known)
return true
return !(this.modified + this.removed).all {
it.isKotlinFile(listOf("kt")) || it.isJavaFile()
}
}
fun CommonCompilerArguments.addChangedClasses(changed: KaptClasspathChanges) {
if (changed is KaptClasspathChanges.Known) {
changed.names.map { it.replace('/', '.').replace('$', '.') }.ifNotEmpty {
addPluginOptions(listOf(SubpluginOption("changedClasses", joinToString(":"))))
}
}
}
fun SubpluginOption.toArg() = "plugin:${KspGradleSubplugin.KSP_PLUGIN_ID}:$key=$value"
fun CommonCompilerArguments.addPluginOptions(options: List<SubpluginOption>) {
pluginOptions = (options.map { it.toArg() } + pluginOptions!!).toTypedArray()
}
fun CommonCompilerArguments.addChangedFiles(changedFiles: ChangedFiles) {
if (changedFiles is ChangedFiles.Known) {
val options = mutableListOf<SubpluginOption>()
changedFiles.modified.filter { it.isKotlinFile(listOf("kt")) || it.isJavaFile() }.ifNotEmpty {
options += SubpluginOption("knownModified", map { it.path }.joinToString(File.pathSeparator))
}
changedFiles.removed.filter { it.isKotlinFile(listOf("kt")) || it.isJavaFile() }.ifNotEmpty {
options += SubpluginOption("knownRemoved", map { it.path }.joinToString(File.pathSeparator))
}
options.ifNotEmpty { addPluginOptions(this) }
}
}
private fun CommonCompilerArguments.blockOtherPlugins(kspPluginClasspath: FileCollection) {
pluginClasspaths = kspPluginClasspath.map { it.canonicalPath }.toTypedArray()
pluginOptions = arrayOf()
}
// TODO: Move into dumpArgs after the compiler supports local function in inline functions.
private inline fun <reified T : CommonCompilerArguments> T.toPair(property: KProperty1<T, *>): Pair<String, String> {
@Suppress("UNCHECKED_CAST")
val value = (property as KProperty1<T, *>).get(this)
return property.name to if (value is Array<*>)
value.asList().toString()
else
value.toString()
}
@Suppress("unused")
internal inline fun <reified T : CommonCompilerArguments> dumpArgs(args: T): Map<String, String> {
@Suppress("UNCHECKED_CAST")
val argumentProperties =
args::class.members.mapNotNull { member ->
(member as? KProperty1<T, *>)?.takeIf { it.annotations.any { ann -> ann is Argument } }
}
return argumentProperties.associate(args::toPair).toSortedMap()
}
internal fun File.isParentOf(childCandidate: File): Boolean {
val parentPath = Paths.get(this.absolutePath).normalize()
val childCandidatePath = Paths.get(childCandidate.absolutePath).normalize()
return childCandidatePath.startsWith(parentPath)
}
| apache-2.0 |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/fragment/MergeRequestDiscussionFragment.kt | 2 | 6487 | package com.commit451.gitlab.fragment
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.commit451.addendum.design.snackbar
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.AttachActivity
import com.commit451.gitlab.adapter.BaseAdapter
import com.commit451.gitlab.api.response.FileUploadResponse
import com.commit451.gitlab.event.MergeRequestChangedEvent
import com.commit451.gitlab.extension.mapResponseSuccessResponse
import com.commit451.gitlab.extension.with
import com.commit451.gitlab.model.api.MergeRequest
import com.commit451.gitlab.model.api.Note
import com.commit451.gitlab.model.api.Project
import com.commit451.gitlab.navigation.TransitionFactory
import com.commit451.gitlab.util.LoadHelper
import com.commit451.gitlab.view.SendMessageView
import com.commit451.gitlab.viewHolder.NoteViewHolder
import com.commit451.teleprinter.Teleprinter
import kotlinx.android.synthetic.main.fragment_merge_request_discussion.*
import kotlinx.android.synthetic.main.progress_fullscreen.*
import org.greenrobot.eventbus.Subscribe
import timber.log.Timber
/**
* Shows the discussion of a merge request
*/
class MergeRequestDiscussionFragment : BaseFragment() {
companion object {
private const val KEY_PROJECT = "project"
private const val KEY_MERGE_REQUEST = "merge_request"
private const val REQUEST_ATTACH = 1
fun newInstance(project: Project, mergeRequest: MergeRequest): MergeRequestDiscussionFragment {
val fragment = MergeRequestDiscussionFragment()
val args = Bundle()
args.putParcelable(KEY_PROJECT, project)
args.putParcelable(KEY_MERGE_REQUEST, mergeRequest)
fragment.arguments = args
return fragment
}
}
private lateinit var adapter: BaseAdapter<Note, NoteViewHolder>
private lateinit var loadHelper: LoadHelper<Note>
private lateinit var teleprinter: Teleprinter
private lateinit var project: Project
private lateinit var mergeRequest: MergeRequest
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
project = arguments?.getParcelable(KEY_PROJECT)!!
mergeRequest = arguments?.getParcelable(KEY_MERGE_REQUEST)!!
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_merge_request_discussion, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
teleprinter = Teleprinter(baseActivty)
val layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, true)
adapter = BaseAdapter(
onCreateViewHolder = { parent, _ -> NoteViewHolder.inflate(parent) },
onBindViewHolder = { viewHolder, _, item -> viewHolder.bind(item, project) }
)
loadHelper = LoadHelper(
lifecycleOwner = this,
recyclerView = listNotes,
baseAdapter = adapter,
layoutManager = layoutManager,
swipeRefreshLayout = swipeRefreshLayout,
errorOrEmptyTextView = textMessage,
loadInitial = { gitLab.getMergeRequestNotes(project.id, mergeRequest.iid) },
loadMore = { gitLab.loadAnyList(it) }
)
sendMessageView.callback = object : SendMessageView.Callback {
override fun onSendClicked(message: String) {
postNote(message)
}
override fun onAttachmentClicked() {
val intent = AttachActivity.newIntent(baseActivty, project)
val activityOptions = TransitionFactory.createFadeInOptions(baseActivty)
startActivityForResult(intent, REQUEST_ATTACH, activityOptions.toBundle())
}
}
load()
App.bus().register(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_ATTACH -> {
if (resultCode == RESULT_OK) {
val response = data?.getParcelableExtra<FileUploadResponse>(AttachActivity.KEY_FILE_UPLOAD_RESPONSE)!!
fullscreenProgress.visibility = View.GONE
sendMessageView.appendText(response.markdown)
} else {
root.snackbar(R.string.failed_to_upload_file)
}
}
}
}
override fun onDestroyView() {
App.bus().unregister(this)
super.onDestroyView()
}
private fun load() {
loadHelper.load()
}
fun postNote(message: String) {
if (message.isBlank()) {
return
}
fullscreenProgress.visibility = View.VISIBLE
fullscreenProgress.alpha = 0.0f
fullscreenProgress.animate().alpha(1.0f)
// Clear text & collapse keyboard
teleprinter.hideKeyboard()
sendMessageView.clearText()
App.get().gitLab.addMergeRequestNote(project.id, mergeRequest.iid, message)
.mapResponseSuccessResponse()
.with(this)
.subscribe({
if (it.first.code() == 202) {
load()
} else {
fullscreenProgress.visibility = View.GONE
textMessage.isVisible = false
adapter.add(it.second, 0)
listNotes.smoothScrollToPosition(0)
}
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(getString(R.string.connection_error))
})
}
@Suppress("unused")
@Subscribe
fun onMergeRequestChangedEvent(event: MergeRequestChangedEvent) {
if (mergeRequest.id == event.mergeRequest.id) {
mergeRequest = event.mergeRequest
load()
}
}
}
| apache-2.0 |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/stats/SkillSet.kt | 1 | 3627 | /*
* 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.entity.stats
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.JsonValue
import java.util.EnumMap
import kotlin.properties.Delegates
public class SkillSet : Json.Serializable {
public enum class Skills : Comparable<Skills> {
BLUFF,
CRAFT,
DIPLOMACY,
DISABLE_DEVICE,
HEAL,
INTIMIDATE,
LOCKPICKING,
PERCEPTION,
SENSE_MOTIVE,
SPELLCRAFT,
STEALTH,
USE_MAGIC_DEVICE;
public val displayName: String
init {
val words: List<String> = this.toString().splitBy("_")
val sb = StringBuilder()
for ((index, word) in words.withIndex()) {
sb.append(word.substring(0, 1).toUpperCase()).append(word.substring(1).toLowerCase())
if (index < words.size() - 1) {
sb.append(" ")
}
}
this.displayName = sb.toString()
}
companion object {
private val displayNameMap: Map<String, Skills> by Delegates.lazy {
Skills.values().map { skill ->
Pair(skill.displayName, skill)
}.toMap()
}
public fun getByDisplayName(displayName: String): Skills? {
return if (this.displayNameMap.containsKey(displayName)) {
this.displayNameMap[displayName]
} else {
null
}
}
}
}
// Properties
private val skills: MutableMap<Skills, Int> = EnumMap<Skills, Int>(javaClass<Skills>())
// Initialization
init {
for (skill in Skills.values()) {
this.skills[skill] = 0
}
}
// Public Methods
public fun getSkill(skill: Skills): Int {
if (this.skills.containsKey(skill)) {
return this.skills[skill] ?: 0
}
return 0
}
public fun setSkill(skill: Skills, value: Int) {
this.skills[skill] = value
}
// Serializable (Json) Implementation
override fun write(json: Json) {
this.skills.keySet().forEach { skill ->
json.writeValue(skill.toString(), this.skills[skill])
}
}
override fun read(json: Json, jsonData: JsonValue) {
jsonData.forEach { value ->
val skill = Skills.valueOf(value.name())
this.skills[skill] = value.asInt()
}
}
} | mit |
quarkusio/quarkus | integration-tests/mongodb-panache-kotlin/src/main/kotlin/io/quarkus/it/mongodb/panache/reactive/book/ReactiveBookEntityResource.kt | 1 | 4701 | package io.quarkus.it.mongodb.panache.reactive.book
import io.quarkus.panache.common.Parameters.with
import io.quarkus.panache.common.Sort
import io.smallrye.mutiny.Uni
import org.bson.types.ObjectId
import org.jboss.logging.Logger
import org.jboss.resteasy.annotations.SseElementType
import org.reactivestreams.Publisher
import java.net.URI
import java.time.LocalDate.parse
import javax.annotation.PostConstruct
import javax.ws.rs.DELETE
import javax.ws.rs.GET
import javax.ws.rs.NotFoundException
import javax.ws.rs.PATCH
import javax.ws.rs.POST
import javax.ws.rs.PUT
import javax.ws.rs.Path
import javax.ws.rs.PathParam
import javax.ws.rs.Produces
import javax.ws.rs.QueryParam
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
@Path("/reactive/books/entity")
class ReactiveBookEntityResource {
@PostConstruct
fun init() {
val databaseName: String = ReactiveBookEntity.mongoDatabase().name
val collectionName: String = ReactiveBookEntity.mongoCollection().namespace.collectionName
LOGGER.infov("Using BookEntity[database={0}, collection={1}]", databaseName, collectionName)
}
@GET
fun getBooks(@QueryParam("sort") sort: String?): Uni<List<ReactiveBookEntity>> {
return if (sort != null) {
ReactiveBookEntity.listAll(Sort.ascending(sort))
} else ReactiveBookEntity.listAll()
}
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun streamBooks(@QueryParam("sort") sort: String?): Publisher<ReactiveBookEntity> {
return if (sort != null) {
ReactiveBookEntity.streamAll(Sort.ascending(sort))
} else ReactiveBookEntity.streamAll()
}
@POST
fun addBook(book: ReactiveBookEntity): Uni<Response> {
return book.persist<ReactiveBookEntity>().map {
// the ID is populated before sending it to the database
Response.created(URI.create("/books/entity${book.id}")).build()
}
}
@PUT
fun updateBook(book: ReactiveBookEntity): Uni<Response> = book.update<ReactiveBookEntity>().map { Response.accepted().build() }
// PATCH is not correct here but it allows to test persistOrUpdate without a specific subpath
@PATCH
fun upsertBook(book: ReactiveBookEntity): Uni<Response> =
book.persistOrUpdate<ReactiveBookEntity>().map { Response.accepted().build() }
@DELETE
@Path("/{id}")
fun deleteBook(@PathParam("id") id: String?): Uni<Void> {
return ReactiveBookEntity.deleteById(ObjectId(id))
.map { d ->
if (d) {
return@map null
}
throw NotFoundException()
}
}
@GET
@Path("/{id}")
fun getBook(@PathParam("id") id: String?): Uni<ReactiveBookEntity?> = ReactiveBookEntity.findById(ObjectId(id))
@GET
@Path("/search/{author}")
fun getBooksByAuthor(@PathParam("author") author: String): Uni<List<ReactiveBookEntity>> =
ReactiveBookEntity.list("author", author)
@GET
@Path("/search")
fun search(
@QueryParam("author") author: String?,
@QueryParam("title") title: String?,
@QueryParam("dateFrom") dateFrom: String?,
@QueryParam("dateTo") dateTo: String?
): Uni<ReactiveBookEntity?> {
return if (author != null) {
ReactiveBookEntity.find("{'author': ?1,'bookTitle': ?2}", author, title!!).firstResult()
} else ReactiveBookEntity
.find(
"{'creationDate': {\$gte: ?1}, 'creationDate': {\$lte: ?2}}",
parse(dateFrom),
parse(dateTo)
)
.firstResult()
}
@GET
@Path("/search2")
fun search2(
@QueryParam("author") author: String?,
@QueryParam("title") title: String?,
@QueryParam("dateFrom") dateFrom: String?,
@QueryParam("dateTo") dateTo: String?
): Uni<ReactiveBookEntity?> =
if (author != null) {
ReactiveBookEntity.find(
"{'author': :author,'bookTitle': :title}",
with("author", author).and("title", title)
).firstResult()
} else {
ReactiveBookEntity.find(
"{'creationDate': {\$gte: :dateFrom}, 'creationDate': {\$lte: :dateTo}}",
with("dateFrom", parse(dateFrom)).and("dateTo", parse(dateTo))
)
.firstResult()
}
@DELETE
fun deleteAll(): Uni<Void> = ReactiveBookEntity.deleteAll().map { null }
companion object {
private val LOGGER: Logger = Logger.getLogger(ReactiveBookEntityResource::class.java)
}
}
| apache-2.0 |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/main/java/com/garpr/android/features/tournament/TournamentTabsView.kt | 1 | 2626 | package com.garpr.android.features.tournament
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.View.OnClickListener
import androidx.constraintlayout.widget.ConstraintLayout
import com.garpr.android.R
import com.garpr.android.data.models.TournamentMode
import com.garpr.android.extensions.getAttrColor
import com.garpr.android.extensions.layoutInflater
import com.garpr.android.misc.Refreshable
import kotlinx.android.synthetic.main.view_tournament_tabs.view.*
class TournamentTabsView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs), Refreshable {
private val matchesTabClickListener = OnClickListener {
tournamentMode = TournamentMode.MATCHES
onTabClickListener?.onTabClick(this)
}
private val playersTabClickListener = OnClickListener {
tournamentMode = TournamentMode.PLAYERS
onTabClickListener?.onTabClick(this)
}
var onTabClickListener: OnTabClickListener? = null
var tournamentMode: TournamentMode = TournamentMode.MATCHES
set(value) {
field = value
refresh()
}
interface OnTabClickListener {
fun onTabClick(v: TournamentTabsView)
}
init {
@Suppress("LeakingThis")
layoutInflater.inflate(R.layout.view_tournament_tabs, this)
val ta = context.obtainStyledAttributes(attrs, R.styleable.TournamentTabsView)
val indicatorLineColor = ta.getColor(R.styleable.TournamentTabsView_indicatorLineColor,
context.getAttrColor(R.attr.colorAccent))
ta.recycle()
matchesTab.setOnClickListener(matchesTabClickListener)
playersTab.setOnClickListener(playersTabClickListener)
indicatorLine.setBackgroundColor(indicatorLineColor)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
refresh()
}
override fun refresh() {
val layoutParams = indicatorLine.layoutParams as? LayoutParams? ?: return
when (tournamentMode) {
TournamentMode.MATCHES -> {
layoutParams.endToEnd = matchesTab.id
layoutParams.startToStart = matchesTab.id
indicatorLine.visibility = View.VISIBLE
}
TournamentMode.PLAYERS -> {
layoutParams.endToEnd = playersTab.id
layoutParams.startToStart = playersTab.id
indicatorLine.visibility = View.VISIBLE
}
}
indicatorLine.layoutParams = layoutParams
}
}
| unlicense |
JimSeker/ui | Advanced/BottomNavigationViewDemo_kt/app/src/main/java/edu/cs4730/bottomnavigationviewdemo_kt/TwoFragment.kt | 1 | 591 | package edu.cs4730.bottomnavigationviewdemo_kt
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import edu.cs4730.bottomnavigationviewdemo_kt.R
/**
* A simple [Fragment] subclass.
*/
class TwoFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_two, container, false)
}
} | apache-2.0 |
JimSeker/ui | Advanced/GuiDemo_kt/app/src/main/java/edu/cs4730/guidemo_kt/Input_Fragment.kt | 1 | 2262 | package edu.cs4730.guidemo_kt
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import android.widget.EditText
import android.text.TextWatcher
import android.text.Editable
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.fragment.app.Fragment
class Input_Fragment : Fragment(), View.OnClickListener {
var TAG = "Input_fragment"
lateinit var myContext: Context
lateinit var et_single: EditText
lateinit var et_mutli: EditText
lateinit var et_pwd: EditText
lateinit var btn: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "OnCreate")
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.input_fragment, container, false)
et_single = view.findViewById(R.id.et_single)
et_pwd = view.findViewById(R.id.et_pwd)
et_pwd.addTextChangedListener(
object : TextWatcher {
override fun beforeTextChanged(
s: CharSequence,
start: Int,
count: Int,
after: Int
) {
//doing nothing.
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// do nothing here.
}
override fun afterTextChanged(s: Editable) {
// When the text is changed.
Toast.makeText(myContext, et_pwd.getText(), Toast.LENGTH_SHORT).show()
}
}
)
btn = view.findViewById(R.id.button)
btn.setOnClickListener(this)
return view
}
override fun onAttach(context: Context) {
super.onAttach(context)
myContext = context
Log.d(TAG, "onAttach")
}
override fun onClick(v: View) {
Toast.makeText(myContext, et_single!!.text, Toast.LENGTH_LONG).show()
}
} | apache-2.0 |
Vakosta/Chapper | app/src/main/java/org/chapper/chapper/data/database/AppDatabase.kt | 1 | 1521 | package org.chapper.chapper.data.database
import com.raizlabs.android.dbflow.annotation.Database
import com.raizlabs.android.dbflow.annotation.Migration
import com.raizlabs.android.dbflow.sql.SQLiteType
import com.raizlabs.android.dbflow.sql.migration.AlterTableMigration
import org.chapper.chapper.data.model.Chat
import org.chapper.chapper.data.model.Settings
@Database(name = AppDatabase.NAME, version = AppDatabase.VERSION)
class AppDatabase {
companion object {
const val NAME = "Chapper"
const val VERSION = 4
}
@Migration(database = AppDatabase::class, version = 4)
class Migration4Chat : AlterTableMigration<Chat>(Chat::class.java) {
override fun onPreMigrate() {
addColumn(SQLiteType.TEXT, "photoId")
}
}
@Migration(database = AppDatabase::class, version = 4)
class Migration4Settings : AlterTableMigration<Settings>(Settings::class.java) {
override fun onPreMigrate() {
addColumn(SQLiteType.TEXT, "photoId")
}
}
@Migration(database = AppDatabase::class, version = 3)
class Migration3 : AlterTableMigration<Settings>(Settings::class.java) {
override fun onPreMigrate() {
addColumn(SQLiteType.INTEGER, "isSendByEnter")
}
}
@Migration(database = AppDatabase::class, version = 2)
class Migration2 : AlterTableMigration<Chat>(Chat::class.java) {
override fun onPreMigrate() {
addColumn(SQLiteType.TEXT, "lastConnection")
}
}
} | gpl-2.0 |
backpaper0/syobotsum | core/src/syobotsum/actor/Counter.kt | 1 | 746 | package syobotsum.actor
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Label
import com.badlogic.gdx.scenes.scene2d.ui.Skin
class Counter(skin: Skin) : Label("00", skin, "counter") {
var count: Int = 0
set(value) {
field = value
setText(String.format("%02d", value))
}
var callback: Runnable? = null
fun start() {
val decrement = Actions.run(Runnable {
count = count - 1
})
val delay = Actions.delay(1f, decrement)
val repeat = Actions.repeat(count, delay)
val run = callback.let { Actions.run(it) }
addAction(Actions.sequence(repeat, run))
}
}
| apache-2.0 |
gantsign/restrulz-jvm | com.gantsign.restrulz.validation/src/test/kotlin/com/gantsign/restrulz/validation/ByteValidatorTest.kt | 1 | 6343 | /*-
* #%L
* Restrulz
* %%
* Copyright (C) 2017 GantSign Ltd.
* %%
* 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.
* #L%
*/
package com.gantsign.restrulz.validation
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyZeroInteractions
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class ByteValidatorTest {
@Rule
@JvmField
val thrown: ExpectedException = ExpectedException.none()
@Test
fun testNewByteValidatorInvalidArgs() {
thrown.expect(IllegalArgumentException::class.java)
thrown.expectMessage("Parameter 'minimumValue' (41) must be less than or equal to parameter 'maximumValue' (40)")
TestByteValidator(minimumValue = 41, maximumValue = 40)
}
@Test
fun testRequireValidValue() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
assertEquals(expected = 20, actual = testValidator.requireValidValue("test1", 20))
assertEquals(expected = 21, actual = testValidator.requireValidValue("test1", 21))
assertEquals(expected = 40, actual = testValidator.requireValidValue("test1", 40))
}
@Test
fun testRequireValidValueTooLow() {
thrown.expect(InvalidArgumentException::class.java)
thrown.expectMessage("19 is less than the minimum permitted value of 20")
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
testValidator.requireValidValue("test1", 19)
}
@Test
fun testRequireValidValueTooHigh() {
thrown.expect(InvalidArgumentException::class.java)
thrown.expectMessage("41 is greater than the maximum permitted value of 40")
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
testValidator.requireValidValue("test1", 41)
}
@Test
fun testRequireValidValueOrNull() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
assertEquals(expected = 20, actual = testValidator.requireValidValueOrNull("test1", 20))
assertEquals(expected = 21, actual = testValidator.requireValidValueOrNull("test1", 21))
assertEquals(expected = 40, actual = testValidator.requireValidValueOrNull("test1", 40))
assertNull(testValidator.requireValidValueOrNull("test1", null))
}
@Test
fun testRequireValidValueOrNullTooLow() {
thrown.expect(InvalidArgumentException::class.java)
thrown.expectMessage("19 is less than the minimum permitted value of 20")
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
testValidator.requireValidValueOrNull("test1", 19)
}
@Test
fun testRequireValidValueOrNullTooHigh() {
thrown.expect(InvalidArgumentException::class.java)
thrown.expectMessage("41 is greater than the maximum permitted value of 40")
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
testValidator.requireValidValueOrNull("test1", 41)
}
@Test
fun testValidateValue() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
val validationHandler = mock(ValidationHandler::class.java)
assertTrue(testValidator.validateValue(20, validationHandler))
assertTrue(testValidator.validateValue(21, validationHandler))
assertTrue(testValidator.validateValue(40, validationHandler))
verifyZeroInteractions(validationHandler)
}
@Test
fun testValidateValueTooLow() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
val validationHandler = mock(ValidationHandler::class.java)
assertFalse(testValidator.validateValue(19, validationHandler))
verify(validationHandler).handleValidationFailure("19 is less than the minimum permitted value of 20")
}
@Test
fun testValidateValueTooHigh() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
val validationHandler = mock(ValidationHandler::class.java)
assertFalse(testValidator.validateValue(41, validationHandler))
verify(validationHandler).handleValidationFailure("41 is greater than the maximum permitted value of 40")
}
@Test
fun testValidateValueOrNull() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
val validationHandler = mock(ValidationHandler::class.java)
assertTrue(testValidator.validateValueOrNull(20, validationHandler))
assertTrue(testValidator.validateValueOrNull(21, validationHandler))
assertTrue(testValidator.validateValueOrNull(40, validationHandler))
assertTrue(testValidator.validateValueOrNull(null, validationHandler))
verifyZeroInteractions(validationHandler)
}
@Test
fun testValidateValueOrNullTooLow() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
val validationHandler = mock(ValidationHandler::class.java)
assertFalse(testValidator.validateValueOrNull(19, validationHandler))
verify(validationHandler).handleValidationFailure("19 is less than the minimum permitted value of 20")
}
@Test
fun testValidateValueOrNullTooHigh() {
val testValidator = TestByteValidator(minimumValue = 20, maximumValue = 40)
val validationHandler = mock(ValidationHandler::class.java)
assertFalse(testValidator.validateValueOrNull(41, validationHandler))
verify(validationHandler).handleValidationFailure("41 is greater than the maximum permitted value of 40")
}
}
| apache-2.0 |
suncycheng/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/typedef/code/FileCodeMembersProvider.kt | 17 | 1035 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.impl.statements.typedef.code
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass
object FileCodeMembersProvider : GrCodeMembersProvider<GroovyScriptClass> {
override fun getCodeMethods(definition: GroovyScriptClass): Array<GrMethod> = definition.containingFile.methods
}
| apache-2.0 |
msebire/intellij-community | platform/platform-impl/src/com/intellij/internal/inspector/ConfigureCustomSizeAction.kt | 1 | 2171 | // 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.internal.inspector
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.layout.*
import javax.swing.JComponent
import javax.swing.JTextField
/**
* @author Konstantin Bulenkov
*/
class ConfigureCustomSizeAction: DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
ConfigureCustomSizeDialog(e.project).show()
}
companion object {
private fun id() = ConfigureCustomSizeAction::class.java
@JvmStatic
fun widthId() = "${id()}.width"
@JvmStatic
fun heightId() = "${id()}.height"
}
class ConfigureCustomSizeDialog(project: Project?): DialogWrapper(project) {
val width: JTextField
val height: JTextField
init {
title = "Default Size"
width = JTextField(loadWidth(), 20)
height = JTextField(loadHeight(), 20)
init()
}
private fun loadWidth() = PropertiesComponent.getInstance().getValue(widthId(), "640")
private fun loadHeight() = PropertiesComponent.getInstance().getValue(heightId(), "300")
override fun createCenterPanel(): JComponent? {
return panel {
row("Width:") {width()}
row("Height:") {height()}
}
}
override fun doOKAction() {
PropertiesComponent.getInstance().setValue(widthId(), width.text)
PropertiesComponent.getInstance().setValue(heightId(), height.text)
super.doOKAction()
}
override fun doValidate(): ValidationInfo? {
val errorMessage = "Should be integer in range 1..1000"
val w = width.text.toIntOrNull()
val h = height.text.toIntOrNull()
if (w == null || w < 1 || w > 1000) return ValidationInfo(errorMessage, width)
if (h == null || h < 1 || h > 1000) return ValidationInfo(errorMessage, height)
return null
}
}
} | apache-2.0 |
androidthings/endtoend-base | app/src/main/java/com/example/androidthings/endtoend/MainActivity.kt | 1 | 3572 | /*
* Copyright 2018 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.example.androidthings.endtoend
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.example.androidthings.endtoend.auth.FirebaseDeviceAuthenticator
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
private val TAG: String = "MainActivity"
lateinit var gpioManager: GpioManager
lateinit var fcmReceiver: BroadcastReceiver
lateinit var firebaseAuth: FirebaseDeviceAuthenticator
val listener = object : OnLedStateChangedListener {
override fun onStateChanged() {
updateFirestore()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
gpioManager = GpioManager(lifecycle, listener)
gpioManager.initGpio()
firebaseAuth = FirebaseDeviceAuthenticator()
firebaseAuth.initAuth(this)
FirestoreManager.init(this)
}
fun updateFirestore() {
val newStates = arrayOf(gpioManager.leds[0].value,
gpioManager.leds[1].value,
gpioManager.leds[2].value)
FirestoreManager.updateGizmoDocState(newStates)
}
fun initFcmReceiver() {
fcmReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent != null) {
val jsonCommandStr = intent.getStringExtra(FcmContract.COMMAND_KEY)
var cmds = JSONObject(jsonCommandStr)
.getJSONArray("inputs")
.getJSONObject(0)
.getJSONObject("payload")
.getJSONArray("commands")
.getJSONObject(0)
.getJSONArray("execution")
.getJSONObject(0)
.getJSONObject("params")
.getJSONObject("updateToggleSettings")
cmds.keys().forEach { key ->
val newState = cmds.getBoolean(key)
val ledIndex= FcmContract.LEDS.indexOf(key)
gpioManager.setLed(ledIndex, newState)
}
updateFirestore()
}
}
}
LocalBroadcastManager.getInstance(this).registerReceiver(
fcmReceiver,
IntentFilter(FcmContract.FCM_INTENT_ACTION)
)
}
override fun onResume() {
super.onResume()
initFcmReceiver()
}
override fun onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(fcmReceiver)
super.onPause()
}
override fun onStart() {
super.onStart()
firebaseAuth.initAuth(this)
}
}
| apache-2.0 |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/database/resolvers/LibraryMangaGetResolver.kt | 1 | 818 | package eu.kanade.tachiyomi.data.database.resolvers
import android.database.Cursor
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.models.MangaStorIOSQLiteGetResolver
import eu.kanade.tachiyomi.data.database.tables.MangaTable
class LibraryMangaGetResolver : MangaStorIOSQLiteGetResolver() {
companion object {
val INSTANCE = LibraryMangaGetResolver()
}
override fun mapFromCursor(cursor: Cursor): Manga {
val manga = super.mapFromCursor(cursor)
val unreadColumn = cursor.getColumnIndex(MangaTable.COLUMN_UNREAD)
manga.unread = cursor.getInt(unreadColumn)
val categoryColumn = cursor.getColumnIndex(MangaTable.COLUMN_CATEGORY)
manga.category = cursor.getInt(categoryColumn)
return manga
}
}
| apache-2.0 |
icanit/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/pager/PagerReader.kt | 1 | 7882 | package eu.kanade.tachiyomi.ui.reader.viewer.pager
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.database.models.Chapter
import eu.kanade.tachiyomi.data.source.model.Page
import eu.kanade.tachiyomi.ui.reader.viewer.base.BaseReader
import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.LeftToRightReader
import eu.kanade.tachiyomi.ui.reader.viewer.pager.horizontal.RightToLeftReader
import rx.subscriptions.CompositeSubscription
/**
* Implementation of a reader based on a ViewPager.
*/
abstract class PagerReader : BaseReader() {
companion object {
/**
* Zoom automatic alignment.
*/
const val ALIGN_AUTO = 1
/**
* Align to left.
*/
const val ALIGN_LEFT = 2
/**
* Align to right.
*/
const val ALIGN_RIGHT = 3
/**
* Align to right.
*/
const val ALIGN_CENTER = 4
/**
* Left side region of the screen. Used for touch events.
*/
const val LEFT_REGION = 0.33f
/**
* Right side region of the screen. Used for touch events.
*/
const val RIGHT_REGION = 0.66f
}
/**
* Generic interface of a ViewPager.
*/
lateinit var pager: Pager
private set
/**
* Adapter of the pager.
*/
lateinit var adapter: PagerReaderAdapter
private set
/**
* Gesture detector for touch events.
*/
val gestureDetector by lazy { createGestureDetector() }
/**
* Subscriptions for reader settings.
*/
var subscriptions: CompositeSubscription? = null
private set
/**
* Whether transitions are enabled or not.
*/
var transitions: Boolean = false
private set
/**
* Scale type (fit width, fit screen, etc).
*/
var scaleType = 1
private set
/**
* Zoom type (start position).
*/
var zoomType = 1
private set
/**
* Initializes the pager.
*
* @param pager the pager to initialize.
*/
protected fun initializePager(pager: Pager) {
adapter = PagerReaderAdapter(childFragmentManager)
this.pager = pager.apply {
setLayoutParams(ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT))
setOffscreenPageLimit(1)
setId(R.id.view_pager)
setOnChapterBoundariesOutListener(object : OnChapterBoundariesOutListener {
override fun onFirstPageOutEvent() {
readerActivity.requestPreviousChapter()
}
override fun onLastPageOutEvent() {
readerActivity.requestNextChapter()
}
})
setOnPageChangeListener { onPageChanged(it) }
}
pager.adapter = adapter
subscriptions = CompositeSubscription().apply {
val preferences = readerActivity.preferences
add(preferences.imageDecoder()
.asObservable()
.doOnNext { setDecoderClass(it) }
.skip(1)
.distinctUntilChanged()
.subscribe { refreshAdapter() })
add(preferences.zoomStart()
.asObservable()
.doOnNext { setZoomStart(it) }
.skip(1)
.distinctUntilChanged()
.subscribe { refreshAdapter() })
add(preferences.imageScaleType()
.asObservable()
.doOnNext { scaleType = it }
.skip(1)
.distinctUntilChanged()
.subscribe { refreshAdapter() })
add(preferences.enableTransitions()
.asObservable()
.subscribe { transitions = it })
}
setPagesOnAdapter()
}
override fun onDestroyView() {
pager.clearOnPageChangeListeners()
subscriptions?.unsubscribe()
super.onDestroyView()
}
/**
* Creates the gesture detector for the pager.
*
* @return a gesture detector.
*/
protected fun createGestureDetector(): GestureDetector {
return GestureDetector(activity, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapConfirmed(e: MotionEvent): Boolean {
val positionX = e.x
if (positionX < pager.width * LEFT_REGION) {
if (tappingEnabled) onLeftSideTap()
} else if (positionX > pager.width * RIGHT_REGION) {
if (tappingEnabled) onRightSideTap()
} else {
readerActivity.onCenterSingleTap()
}
return true
}
})
}
/**
* Called when a new chapter is set in [BaseReader].
*
* @param chapter the chapter set.
* @param currentPage the initial page to display.
*/
override fun onChapterSet(chapter: Chapter, currentPage: Page) {
this.currentPage = getPageIndex(currentPage) // we might have a new page object
// Make sure the view is already initialized.
if (view != null) {
setPagesOnAdapter()
}
}
/**
* Called when a chapter is appended in [BaseReader].
*
* @param chapter the chapter appended.
*/
override fun onChapterAppended(chapter: Chapter) {
// Make sure the view is already initialized.
if (view != null) {
adapter.pages = pages
}
}
/**
* Sets the pages on the adapter.
*/
protected fun setPagesOnAdapter() {
if (pages.isNotEmpty()) {
adapter.pages = pages
setActivePage(currentPage)
updatePageNumber()
}
}
/**
* Sets the active page.
*
* @param pageNumber the index of the page from [pages].
*/
override fun setActivePage(pageNumber: Int) {
pager.setCurrentItem(pageNumber, false)
}
/**
* Refresh the adapter.
*/
private fun refreshAdapter() {
pager.adapter = adapter
pager.setCurrentItem(currentPage, false)
}
/**
* Called when the left side of the screen was clicked.
*/
protected open fun onLeftSideTap() {
moveToPrevious()
}
/**
* Called when the right side of the screen was clicked.
*/
protected open fun onRightSideTap() {
moveToNext()
}
/**
* Moves to the next page or requests the next chapter if it's the last one.
*/
override fun moveToNext() {
if (pager.currentItem != pager.adapter.count - 1) {
pager.setCurrentItem(pager.currentItem + 1, transitions)
} else {
readerActivity.requestNextChapter()
}
}
/**
* Moves to the previous page or requests the previous chapter if it's the first one.
*/
override fun moveToPrevious() {
if (pager.currentItem != 0) {
pager.setCurrentItem(pager.currentItem - 1, transitions)
} else {
readerActivity.requestPreviousChapter()
}
}
/**
* Sets the zoom start position.
*
* @param zoomStart the value stored in preferences.
*/
private fun setZoomStart(zoomStart: Int) {
if (zoomStart == ALIGN_AUTO) {
if (this is LeftToRightReader)
setZoomStart(ALIGN_LEFT)
else if (this is RightToLeftReader)
setZoomStart(ALIGN_RIGHT)
else
setZoomStart(ALIGN_CENTER)
} else {
zoomType = zoomStart
}
}
}
| apache-2.0 |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/network/GetMsgWorker.kt | 1 | 4341 | package im.fdx.v2ex.network
import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.elvishew.xlog.XLog
import im.fdx.v2ex.R
import im.fdx.v2ex.ui.NotificationActivity
import im.fdx.v2ex.utils.Keys
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import java.util.regex.Pattern
class GetMsgWorker(val context: Context, workerParameters: WorkerParameters) : Worker(context, workerParameters) {
override fun doWork(): Result {
getUnread(context)
return Result.success()
}
private fun getUnread(context: Context) {
vCall(NetManager.URL_FOLLOWING).start(object : Callback {
override fun onFailure(call: Call, e: IOException) {
NetManager.dealError(context, -1)
}
@Throws(IOException::class)
override fun onResponse(call: Call, response: Response) {
val code = response.code
if (code != 200) {
NetManager.dealError(context, code)
return
}
val html = response.body!!.string()
// <a href="/notifications" class="fade">0 条未读提醒</a>
val p = Pattern.compile("(?<=<a href=\"/notifications\".{0,20}>)\\d+")
val matcher = p.matcher(html)
if (matcher.find()) {
val num = Integer.parseInt(matcher.group())
XLog.d("num:$num")
if (num != 0) {
val intent = Intent(Keys.ACTION_GET_NOTIFICATION)
intent.putExtra(Keys.KEY_UNREAD_COUNT, num)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
putNotification(context, num)
}
} else {
XLog.e("not find num of unread message")
}
}
})
}
private fun putNotification(context: Context, number: Int) {
val resultIntent = Intent(context, NotificationActivity::class.java)
resultIntent.putExtra(Keys.KEY_UNREAD_COUNT, number)
val stackBuilder = TaskStackBuilder.create(context)
stackBuilder.addNextIntentWithParentStack(resultIntent)
val resultPendingIntent = stackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE )
val color = ContextCompat.getColor(context, R.color.primary)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel("channel_id", "未读消息", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = context.getSystemService(
Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(context, "channel_id")
mBuilder
// .setSubText("subtext")
.setContentTitle(context.getString(R.string.you_have_notifications, number))
// .setContentText("")
.setTicker(context.getString(R.string.you_have_notifications))
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_notification_icon)
// .setLargeIcon(R.drawable.logo2x)
.setLights(color, 2000, 1000)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setColor(color)
.setContentIntent(resultPendingIntent)
val mNotificationCompat = mBuilder.build()
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
mNotificationManager.notify(Keys.notifyID, mNotificationCompat)
}
} | apache-2.0 |
LordAkkarin/Beacon | ui/src/main/kotlin/tv/dotstart/beacon/ui/component/PreferencePageView.kt | 1 | 3963 | /*
* Copyright 2020 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.component
import javafx.beans.DefaultProperty
import javafx.beans.binding.Bindings
import javafx.beans.property.ObjectProperty
import javafx.beans.property.ReadOnlyObjectProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.fxml.Initializable
import javafx.scene.Node
import javafx.scene.control.ListCell
import javafx.scene.control.ListView
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import tv.dotstart.beacon.ui.delegate.property
import java.net.URL
import java.util.*
/**
* Provides an alternative version of the tab view which displays all available options within a
* standard list view.
*
* This component is primarily aimed at preference related window implementations.
*
* @author [Johannes Donath](mailto:[email protected])
* @date 09/12/2020
*/
@DefaultProperty("pages")
class PreferencePageView : HBox(), Initializable {
private val preferenceListView = ListView<PreferencePage>()
private val contentPane = VBox()
private val _pageProperty: ObjectProperty<PreferencePage> = SimpleObjectProperty()
/**
* Defines a listing of pages present within this component.
*/
val pages: ObservableList<PreferencePage> = FXCollections.observableArrayList()
/**
* Identifies the page which is currently displayed within the preference view.
*/
val pageProperty: ReadOnlyObjectProperty<PreferencePage>
get() = this._pageProperty
/**
* @see pageProperty
*/
val page by property(_pageProperty)
init {
this.styleClass.add("preference-page-view")
this.children.setAll(this.preferenceListView, this.contentPane)
this.preferenceListView.styleClass.add("preference-page-list")
this.preferenceListView.setCellFactory { PageCell() }
Bindings.bindContent(this.preferenceListView.items, this.pages)
this.contentPane.styleClass.add("preference-page-content")
HBox.setHgrow(this.contentPane, Priority.ALWAYS)
this._pageProperty.addListener { _, _, page ->
this.contentPane.children.clear()
page?.let { this.contentPane.children.setAll(it) }
}
val selectionBinding = Bindings.select<PreferencePage>(
this.preferenceListView,
"selectionModel", "selectedItem")
this._pageProperty.bind(selectionBinding)
this.pages.addListener(ListChangeListener { change ->
while (change.next()) {
val currentSelection = this.page
if (currentSelection == null || currentSelection in change.removed) {
this.children
.takeIf(ObservableList<Node>::isNotEmpty)
?.let { this.preferenceListView.selectionModel.select(0) }
}
}
})
}
override fun initialize(location: URL?, resources: ResourceBundle?) {
}
private class PageCell : ListCell<PreferencePage>() {
override fun updateItem(item: PreferencePage?, empty: Boolean) {
super.updateItem(item, empty)
this.textProperty().unbind()
if (!empty && item != null) {
this.textProperty().bind(item.titleProperty)
} else {
this.text = null
}
}
}
}
| apache-2.0 |
loziuu/vehicle-management | ivms/src/main/kotlin/pl/loziuu/ivms/identity/user/domain/User.kt | 1 | 677 | package pl.loziuu.ivms.identity.user.domain
import javax.persistence.*
@Entity
@Table(name = "users")
class User(@Id @GeneratedValue(strategy = GenerationType.IDENTITY) val id: Long = 0,
@Enumerated(EnumType.STRING)
var role: Role = Role.MANAGER,
@Column(unique = true)
val login: String = "",
var password: String = "",
var enabled: Boolean = false) {
fun activate() {
enabled = true;
}
fun deactivate() {
enabled = false
}
fun changePassword(password: String) {
this.password = password;
}
fun changeRole(role: Role) {
this.role = role
}
} | gpl-3.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/parking_lanes/ParkingLanesParser.kt | 2 | 2620 | package de.westnordost.streetcomplete.quests.parking_lanes
import de.westnordost.streetcomplete.quests.parking_lanes.ParkingLanePosition.*
data class LeftAndRightParkingLane(val left: ParkingLane?, val right: ParkingLane?)
fun createParkingLaneSides(tags: Map<String, String>): LeftAndRightParkingLane? {
val expandedTags = expandRelevantSidesTags(tags)
// then get the values for left and right
val left = createParkingLaneForSide(expandedTags, "left")
val right = createParkingLaneForSide(expandedTags, "right")
if (left == null && right == null) return null
return LeftAndRightParkingLane(left, right)
}
private fun createParkingLaneForSide(tags: Map<String, String>, side: String?): ParkingLane? {
val sideVal = if (side != null) ":$side" else ""
val parkingLaneValue = tags["parking:lane$sideVal"]
val parkingLanePositionValue = tags["parking:lane$sideVal:$parkingLaneValue"]
val parkingLanePosition = parkingLanePositionValue?.toParkingLanePosition()
return when (parkingLaneValue) {
"parallel" -> ParallelParkingLane(parkingLanePosition)
"diagonal" -> DiagonalParkingLane(parkingLanePosition)
"perpendicular" -> PerpendicularParkingLane(parkingLanePosition)
"marked" -> MarkedParkingLane
"no_parking" -> NoParking
"no_stopping" -> NoStopping
"fire_lane" -> FireLane
"no" -> NoParkingLane
null -> null
else -> UnknownParkingLane
}
}
private fun String.toParkingLanePosition() = when(this) {
"on_street" -> ON_STREET
"half_on_kerb" -> HALF_ON_KERB
"on_kerb" -> ON_KERB
"shoulder" -> SHOULDER
"painted_area_only" -> PAINTED_AREA_ONLY
"lay_by" -> LAY_BY
else -> UNKNOWN
}
private fun expandRelevantSidesTags(tags: Map<String, String>): Map<String, String> {
val result = tags.toMutableMap()
expandSidesTag("parking:lane", "", result)
expandSidesTag("parking:lane", "parallel", result)
expandSidesTag("parking:lane", "diagonal", result)
expandSidesTag("parking:lane", "perpendicular", result)
return result
}
/** Expand my_tag:both and my_tag into my_tag:left and my_tag:right etc */
private fun expandSidesTag(keyPrefix: String, keyPostfix: String, tags: MutableMap<String, String>) {
val pre = keyPrefix
val post = if (keyPostfix.isEmpty()) "" else ":$keyPostfix"
val value = tags["$pre:both$post"] ?: tags["$pre$post"]
if (value != null) {
if (!tags.containsKey("$pre:left$post")) tags["$pre:left$post"] = value
if (!tags.containsKey("$pre:right$post")) tags["$pre:right$post"] = value
}
} | gpl-3.0 |
wordpress-mobile/WordPress-Stores-Android | plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/persistence/entity/AddonOptionEntity.kt | 2 | 743 | package org.wordpress.android.fluxc.persistence.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.CASCADE
import androidx.room.PrimaryKey
import org.wordpress.android.fluxc.persistence.entity.AddonEntity.LocalPriceType
@Entity(
foreignKeys = [ForeignKey(
entity = AddonEntity::class,
parentColumns = ["addonLocalId"],
childColumns = ["addonLocalId"],
onDelete = CASCADE
)]
)
data class AddonOptionEntity(
@PrimaryKey(autoGenerate = true) val addonOptionLocalId: Long = 0,
val addonLocalId: Long,
val priceType: LocalPriceType,
val label: String?,
val price: String?,
val image: String?
)
| gpl-2.0 |
robfletcher/midcentury-ipsum | src/main/kotlin/com/energizedwork/midcenturyipsum/IpsumGenerator.kt | 1 | 1271 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Robert Fletcher
*
* 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.energizedwork.midcenturyipsum
interface IpsumGenerator {
fun paragraphs(count: Int): Collection<String>
} | mit |
devulex/eventorage | frontend/src/com/devulex/eventorage/react/components/pages/SettingsPageComponent.kt | 1 | 5952 | package com.devulex.eventorage.react.components.pages
import com.devulex.eventorage.locale.Messages
import com.devulex.eventorage.model.*
import com.devulex.eventorage.react.RProps
import com.devulex.eventorage.react.RState
import com.devulex.eventorage.react.ReactComponentSpec
import com.devulex.eventorage.react.dom.ReactDOMBuilder
import com.devulex.eventorage.react.dom.ReactDOMComponent
import com.devulex.eventorage.rpc.getSettings
import com.devulex.eventorage.rpc.updateSetting
import kotlinx.coroutines.experimental.async
import kotlinx.html.*
import kotlinx.html.js.onChangeFunction
import kotlinx.html.js.onClickFunction
import com.devulex.eventorage.common.toggleChecked
class SettingsPageComponent : ReactDOMComponent<SettingsPageComponent.SettingHandlerProps, SettingsPageComponent.SettingsState>() {
companion object : ReactComponentSpec<SettingsPageComponent, SettingsPageComponent.SettingHandlerProps, SettingsPageComponent.SettingsState>
init {
state = SettingsPageComponent.SettingsState()
}
override fun ReactDOMBuilder.render() {
div(classes = "page") {
div(classes = "content") {
div(classes = "settings-field") {
div(classes = "text") {
+(+Messages.YOU_CAN_CHANGE_CLUSTER_SETTINGS)
span(classes = "code") { +"application.conf" }
}
}
div(classes = "settings-field") {
div(classes = "label") { +(+Messages.CLUSTER_NAME) }
div(classes = "value text mono") { +props.staticSettings.elasticsearchClusterName }
}
div(classes = "settings-field") {
div(classes = "label") { +(+Messages.CLUSTER_NODES) }
div(classes = "value text mono") { +props.staticSettings.elasticsearchClusterNodes }
}
div(classes = "settings-field") {
div(classes = "label") { +(+Messages.LANGUAGE) }
div(classes = "value") {
select(classes = "select") {
attributes["value"] = +props.dynamicSettings.language
option {
value = +Language.EN
+"English"
}
option {
value = +Language.RU
+"Russian"
}
onChangeFunction = { e ->
val value = e.target!!.asDynamic().value.toString()
setState {
props.dynamicSettings.language = Language.parse(value)
props.changeLangHandler(Language.parse(value))
}
doUpdateSetting(+SettingProperty.LANGUAGE, value)
}
}
}
}
div(classes = "settings-field") {
div(classes = "label") { +(+Messages.DATE_FORMAT) }
div(classes = "value") {
select(classes = "select mono") {
attributes["value"] = +props.dynamicSettings.dateFormat
option {
value = +DateFormatter.YYYY_MM_DD
+(+DateFormatter.YYYY_MM_DD)
}
option {
value = +DateFormatter.DD_MM_YYYY
+(+DateFormatter.DD_MM_YYYY)
}
onChangeFunction = { e ->
val value = e.target!!.asDynamic().value.toString()
setState {
props.dynamicSettings.dateFormat = DateFormatter.parse(value)
}
doUpdateSetting(+SettingProperty.DATE_FORMAT, value)
}
}
}
}
div(classes = "settings-field") {
div(classes = "checkbox") {
if (props.dynamicSettings.autoCheckUpdates) {
attributes["data-checked"] = ""
}
+(+Messages.AUTOMATICALLY_CHECK_FOR_UPDATES_TO_EVENTORAGE)
onClickFunction = {
it.toggleChecked()
setState {
props.dynamicSettings.autoCheckUpdates = !props.dynamicSettings.autoCheckUpdates
}
doUpdateSetting(+SettingProperty.AUTO_CHECK_UPDATES,
props.dynamicSettings.autoCheckUpdates.toString())
}
span {}
span {}
}
}
}
}
}
class SettingsState : RState
class SettingHandlerProps(var staticSettings: StaticEventorageSettings,
var dynamicSettings: DynamicEventorageSettings) : RProps() {
var changeLangHandler: (Language) -> Unit = {}
}
/**
* Not used
*/
private fun doGetSettings() {
async {
getSettings()
}.catch { err ->
console.error("Failed to get settings: " + err.message)
}
}
private fun doUpdateSetting(name: String, value: String) {
async {
updateSetting(name, value)
}.catch { err ->
console.error("Failed to update setting: " + err.message)
}
}
}
| mit |
jonninja/node.kt | src/main/kotlin/node/express/engines/VelocityEngine.kt | 1 | 867 | package node.express.engines
import node.express.Engine
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
import org.apache.velocity.runtime.RuntimeConstants
import org.apache.velocity.VelocityContext
import java.io.StringWriter
/**
* An express engine that renders using Velocity
*/
class VelocityEngine(): Engine {
val ve = org.apache.velocity.app.VelocityEngine();
init {
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "file");
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "/");
ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, "true");
}
override fun render(path: String, data: Map<String, Any?>): String {
val context = VelocityContext(data);
val template = ve.getTemplate(path)!!;
val sw = StringWriter();
template.merge(context, sw);
return sw.toString();
}
} | mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/registry/type/data/PickupRuleRegistry.kt | 1 | 985 | /*
* 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.registry.type.data
import org.lanternpowered.server.catalog.DefaultCatalogType
import org.lanternpowered.server.registry.internalCatalogTypeRegistry
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.key.minecraftKey
import org.spongepowered.api.data.type.PickupRule
val PickupRuleRegistry = internalCatalogTypeRegistry<PickupRule> {
fun register(id: String) =
register(LanternPickupRule(minecraftKey(id)))
register("disallowed")
register("allowed")
register("creative_only")
}
private class LanternPickupRule(key: NamespacedKey) : DefaultCatalogType(key), PickupRule
| mit |
ratabb/Hishoot2i | common/src/main/java/common/egl/MaxTextureCompat.kt | 1 | 388 | package common.egl
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.JELLY_BEAN_MR1
object MaxTextureCompat : MaxTexture {
private val IMPL: MaxTexture by lazy(this) {
if (SDK_INT >= JELLY_BEAN_MR1) Egl14Impl() else Egl10Impl()
}
override fun get(): Int? = try {
IMPL.get()
} catch (ignore: Exception) {
null
}
}
| apache-2.0 |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/ui/issue/IssueDashboardPagerFragment.kt | 5 | 2699 | /*
* Copyright (c) 2015 PocketHub
*
* 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.pockethub.android.ui.issue
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.github.pockethub.android.R
import com.github.pockethub.android.ui.MainActivity
import com.github.pockethub.android.ui.helpers.PagerHandler
import com.github.pockethub.android.ui.base.BaseFragment
import kotlinx.android.synthetic.main.pager_with_tabs.*
import kotlinx.android.synthetic.main.pager_with_tabs.view.*
/**
* Dashboard activity for issues
*/
class IssueDashboardPagerFragment : BaseFragment() {
private var pagerHandler: PagerHandler<IssueDashboardPagerAdapter>? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.pager_with_tabs, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
view.toolbar.visibility = View.GONE
configurePager()
}
private fun configurePager() {
val adapter = IssueDashboardPagerAdapter(this)
pagerHandler = PagerHandler(this, vp_pages, adapter)
lifecycle.addObserver(pagerHandler!!)
pagerHandler!!.tabs = sliding_tabs_layout
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(pagerHandler!!)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
val intent = Intent(activity, MainActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP or FLAG_ACTIVITY_SINGLE_TOP)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| apache-2.0 |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/lang/commands/LatexNewDefinitionCommand.kt | 1 | 1846 | package nl.hannahsten.texifyidea.lang.commands
import nl.hannahsten.texifyidea.lang.LatexPackage
/**
* @author Hannah Schellekens
*/
enum class LatexNewDefinitionCommand(
override val command: String,
override vararg val arguments: Argument = emptyArray(),
override val dependency: LatexPackage = LatexPackage.DEFAULT,
override val display: String? = null,
override val isMathMode: Boolean = false,
val collapse: Boolean = false
) : LatexCommand {
CATCODE("catcode"),
NEWCOMMAND("newcommand", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)),
NEWCOMMAND_STAR("newcommand*", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)),
NEWIF("newif", "cmd".asRequired()),
PROVIDECOMMAND("providecommand", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)),
PROVIDECOMMAND_STAR("providecommand*", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)),
RENEWCOMMAND("renewcommand", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)),
RENEWCOMMAND_STAR("renewcommand*", "cmd".asRequired(), "args".asOptional(), "default".asOptional(), "def".asRequired(Argument.Type.TEXT)),
NEWENVIRONMENT("newenvironment", "name".asRequired(), "args".asOptional(), "default".asOptional(), "begdef".asRequired(Argument.Type.TEXT), "enddef".asRequired(Argument.Type.TEXT)),
RENEWENVIRONMENT("renewenvironment", "name".asRequired(), "args".asOptional(), "default".asOptional(), "begdef".asRequired(Argument.Type.TEXT), "enddef".asRequired(Argument.Type.TEXT)),
;
override val identifier: String
get() = name
} | mit |
debop/debop4k | debop4k-data/src/main/kotlin/debop4k/data/spring/SpringTransactionalDataSource.kt | 1 | 1555 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.data.spring
import org.springframework.jdbc.datasource.AbstractDataSource
import org.springframework.jdbc.datasource.DataSourceUtils
import java.lang.UnsupportedOperationException
import java.sql.Connection
import javax.sql.DataSource
/**
* Spring framework 의 Transactional annotation 을 이용하여 Transaction 하에서 DB 작업이 가능하도록 해 줍니다.
*
* @author [email protected]
*/
class SpringTransactionalDataSource : AbstractDataSource() {
public var inner: DataSource? = null
override fun getConnection(): Connection {
val conn = DataSourceUtils.getConnection(inner)
if (!DataSourceUtils.isConnectionTransactional(conn, inner)) {
error("Connection is not transactional")
}
return conn
}
override fun getConnection(username: String?, password: String?): Connection {
throw UnsupportedOperationException("Not supported operation")
}
} | apache-2.0 |
ntlv/BasicLauncher2 | app/src/main/java/se/ntlv/basiclauncher/appgrid/AppIconClickHandler.kt | 1 | 2246 | package se.ntlv.basiclauncher.appgrid
import android.app.Activity
import android.content.pm.PackageManager
import android.util.Log
import android.view.View
import android.view.animation.AlphaAnimation
import android.view.animation.Animation
import org.jetbrains.anko.onClick
import org.jetbrains.anko.onLongClick
import rx.Observable
import rx.schedulers.Schedulers
import se.ntlv.basiclauncher.*
import se.ntlv.basiclauncher.database.AppDetail
import se.ntlv.basiclauncher.database.AppDetailRepository
class AppIconClickHandler {
constructor(pm: PackageManager, activity: Activity, repo: AppDetailRepository) {
packageManager = pm
base = activity
mRepo = repo
}
private val packageManager: PackageManager
private val mRepo: AppDetailRepository
private val base: Activity
private val TAG = tag()
private fun onClick(view: View, appDetail: AppDetail): Boolean {
if (appDetail.isPlaceholder()) return false
Log.d(TAG, "Onclick $appDetail")
val anim = AlphaAnimation(1f, 0.2f)
anim.duration = 250
anim.repeatMode = Animation.REVERSE
anim.repeatCount = 1
val animListener = listenForAnimationEvent(anim, targetEvents = AnimationEvent.END)
val starter = Observable.just(appDetail.packageName)
.subscribeOn(Schedulers.computation())
.map { packageManager.getLaunchIntentForPackage(it) }
Observable.zip(animListener, starter, pickSecond())
.observeOn(Schedulers.computation())
.take(1)
.subscribe {
base.startActivityWithClipReveal(it, view)
}
view.startAnimation(anim)
return true
}
private fun onLongClick(origin: View, appDetail: AppDetail): Boolean {
if (appDetail.isPlaceholder()) return false
Log.d(TAG, "OnLongClick $appDetail")
val shadow = View.DragShadowBuilder(origin)
val payload = appDetail.asClipData()
return origin.startDrag(payload, shadow, null, 0)
}
fun bind(origin: View, meta: AppDetail) {
origin.onClick { onClick(origin, meta) }
origin.onLongClick { onLongClick(origin, meta) }
}
}
| mit |
lindar-open/acolyte | src/main/kotlin/lindar/acolyte/util/ListsAcolyte.kt | 1 | 4962 | package lindar.acolyte.util
import java.util.Optional
class ListsAcolyte {
companion object {
@JvmStatic fun <T> listOf(vararg elements: T): List<T> {
return kotlin.collections.listOf(*elements)
}
@JvmStatic fun <T> arrayListOf(vararg elements: T): MutableList<T> {
return kotlin.collections.mutableListOf(*elements)
}
@JvmStatic fun containsIgnoreCase(list: List<String?>?, item: String?): Boolean {
return list.orEmpty().any { str -> str.equals(item, ignoreCase = true) }
}
@JvmStatic fun containsAnyIgnoreCase(list: List<String?>?, vararg items: String?): Boolean {
return list.orEmpty().any { str -> items.any { it.equals(str, ignoreCase = true) } }
}
@JvmStatic fun containsAllIgnoreCase(list: List<String?>?, vararg items: String?): Boolean {
return items.all{str -> list.orEmpty().any{it.equals(str, ignoreCase = true)}}
}
@JvmStatic fun containsAnyIgnoreCase(list: List<String?>?, items: List<String?>?): Boolean {
return items != null && list.orEmpty().any { str -> items.any { it.equals(str, ignoreCase = true) } }
}
@JvmStatic fun containsAllIgnoreCase(list: List<String?>?, items: List<String?>?): Boolean {
return items != null && items.all{str -> list.orEmpty().any{it.equals(str, ignoreCase = true)}}
}
@JvmStatic fun eachContainsIgnoreCase(list: List<String?>?, item: String?): Boolean {
return item != null && list.orEmpty().filterNotNull().any { str -> str.contains(item, ignoreCase = true) }
}
/**
* Checks if list is null or empty
*/
@JvmStatic fun <T> isEmpty(list: List<T>?): Boolean {
return list == null || list.isEmpty()
}
/**
* Checks that list is not null and not empty
*/
@JvmStatic fun <T> isNotEmpty(list: List<T>?): Boolean {
return list != null && !list.isEmpty()
}
/**
* If provided list is null returns a new ArrayList
*/
@JvmStatic fun <T> defaultIfNull(list: MutableList<T>?): MutableList<T> {
return list ?: ArrayList<T>()
}
@JvmStatic fun <T> defaultIfNull(list: MutableList<T>?, defaultVal: MutableList<T>): MutableList<T> {
return list ?: defaultVal
}
@JvmStatic fun <T> defaultIfEmpty(list: MutableList<T>?, defaultVal: MutableList<T>): MutableList<T> {
return if (list == null || list.isEmpty()) defaultVal else list
}
@JvmStatic fun <T> hasOnlyOneItem(list: List<T?>?): Boolean {
return list?.size == 1
}
@JvmStatic fun <T> hasMoreThanOneItem(list: List<T?>?): Boolean {
return list != null && list.size > 1
}
@JvmStatic fun <T> emptyOrHasAtMostOneItem(list: List<T?>?): Boolean {
return list == null || list.size <= 1
}
@JvmStatic fun <T> hasOnlyOneNonNullItem(list: List<T?>?): Boolean {
// we use sequence cause it has lazy evaluation
return list != null && list.asSequence().filter { it != null }.count() == 1
}
@JvmStatic fun <T> hasMoreThanOneNonNullItem(list: List<T?>?): Boolean {
// we use sequence cause it has lazy evaluation
return list != null && list.asSequence().filter { it != null }.count() > 1
}
@JvmStatic fun <T> hasAtLeastOneNonNullItem(list: List<T?>?): Boolean {
// we use sequence cause it has lazy evaluation
return list != null && list.asSequence().filter { it != null }.count() > 0
}
@JvmStatic fun <T> emptyOrHasAtMostOneNonNullItem(list: List<T?>?): Boolean {
// we use sequence cause it has lazy evaluation
return list == null || list.asSequence().filter { it != null }.count() <= 1
}
@JvmStatic fun <T> getFirstItemIfExists(list: List<T?>?): Optional<T> {
return Optional.ofNullable(list?.firstOrNull())
}
@JvmStatic fun <T> getFirstNonNullItemIfExists(list: List<T?>?): Optional<T> {
return Optional.ofNullable(list?.find { it != null })
}
@JvmStatic fun <T> getLastItemIfExists(list: List<T?>?): Optional<T> {
return Optional.ofNullable(list?.lastOrNull())
}
@JvmStatic fun <T> getLastNonNullItemIfExists(list: List<T?>?): Optional<T> {
return Optional.ofNullable(list?.findLast { it != null })
}
@JvmStatic fun <T, U> mapTo(initialList: List<T?>?, mapper: (T?) -> U): List<U> {
return initialList?.filter {it != null}?.map(mapper) ?: ArrayList()
}
@JvmStatic fun <T, U> mapToIncludeNull(initialList: List<T?>?, mapper: (T?) -> U?): List<U?> {
return initialList?.map(mapper) ?: ArrayList()
}
}
} | apache-2.0 |
milos85vasic/Pussycat | Pussycat/src/main/kotlin/net/milosvasic/pussycat/utils/Text.kt | 1 | 150 | package net.milosvasic.pussycat.utils
object Text {
fun isEmpty(text: String?): Boolean {
return text == null || text.isEmpty()
}
} | apache-2.0 |
tomhenne/Jerusalem | src/main/java/de/esymetric/jerusalem/main/Jerusalem.kt | 1 | 14911 | package de.esymetric.jerusalem.main
import de.esymetric.jerusalem.osmDataRepresentation.OSMDataReader
import de.esymetric.jerusalem.osmDataRepresentation.osm2ownMaps.PartitionedOsmNodeID2OwnIDMap
import de.esymetric.jerusalem.ownDataRepresentation.geoData.Position
import de.esymetric.jerusalem.ownDataRepresentation.geoData.importExport.KML
import de.esymetric.jerusalem.rebuilding.Rebuilder
import de.esymetric.jerusalem.routing.Router
import de.esymetric.jerusalem.routing.RoutingType
import de.esymetric.jerusalem.routing.algorithms.TomsAStarStarRouting
import de.esymetric.jerusalem.routing.heuristics.TomsRoutingHeuristics
import de.esymetric.jerusalem.tools.CrossroadsFinder
import de.esymetric.jerusalem.utils.Utils
import org.apache.tools.bzip2.CBZip2InputStream
import java.io.*
import java.util.*
object Jerusalem {
@JvmStatic
fun main(args: Array<String>) {
println("JERUSALEM 1.0 Java Enabled Routing Using Speedy Algorithms for Largely Extended Maps (jerusalem.gps-sport.net) based on OSM (OpenStreetMap.org)")
if (args.isEmpty()) {
printUsage()
return
}
val command = args[0]
val maxExecutionTimeS = 120
val dataDirectoryPath = (System.getProperty("user.dir")
+ File.separatorChar + "jerusalemData")
var tempDirectoryPath = dataDirectoryPath
File(dataDirectoryPath).mkdir()
if ("clean" == command) {
// remove temp files from osm 2 own id map
if (args.size < 2) {
printUsage()
return
}
tempDirectoryPath = (args[1] + File.separatorChar
+ "jerusalemTempData")
File(tempDirectoryPath).mkdirs()
val poniom = PartitionedOsmNodeID2OwnIDMap(
tempDirectoryPath, true
)
poniom.deleteLatLonTempFiles()
poniom.close()
return
}
if ("rebuildIndex" == command) {
if (args.size < 2) {
printUsage()
return
}
tempDirectoryPath = (args[1] + File.separatorChar
+ "jerusalemTempData")
val rebuilder = Rebuilder(
dataDirectoryPath,
tempDirectoryPath, TomsRoutingHeuristics(), true,
false, true
)
rebuilder.makeQuadtreeIndex()
// do NOT close Rebuilder rebuilder.close();
return
}
if ("rebuildTransitions" == command) {
if (args.size < 2) {
printUsage()
return
}
tempDirectoryPath = (args[1] + File.separatorChar
+ "jerusalemTempData")
val rebuilder = Rebuilder(
dataDirectoryPath,
tempDirectoryPath, TomsRoutingHeuristics(), true,
false, false
)
rebuilder.buildTransitions(true)
// do NOT close Rebuilder rebuilder.close();
return
}
if ("rebuild" == command || "rebuildWays" == command) {
val rebuildOnlyWays = "rebuildWays" == command
if (args.size < 3) {
printUsage()
return
}
var filePath: String? = args[1]
if ("-" != filePath) {
println("Rebuilding $filePath")
} else {
println("Rebuilding from stdin")
filePath = null
}
tempDirectoryPath = (args[2] + File.separatorChar
+ "jerusalemTempData")
File(tempDirectoryPath).mkdirs()
val startTime = Date()
println("start date $startTime")
try {
val rebuilder = Rebuilder(
dataDirectoryPath,
tempDirectoryPath, TomsRoutingHeuristics(),
rebuildOnlyWays, rebuildOnlyWays, false
)
if (filePath != null) {
val fis: InputStream = FileInputStream(filePath)
fis.read()
fis.read()
val bzis = CBZip2InputStream(fis)
val osmdr = OSMDataReader(
bzis, rebuilder,
rebuildOnlyWays
)
osmdr.read(startTime)
bzis.close()
fis.close()
} else {
val osmdr = OSMDataReader(
System.`in`,
rebuilder, rebuildOnlyWays
)
osmdr.read(startTime)
}
rebuilder.finishProcessingAndClose()
} catch (e: IOException) {
e.printStackTrace()
}
println("finish date " + Date())
println(
"required time "
+ Utils.formatTimeStopWatch(
Date().time
- startTime.time
)
)
return
}
// routing
if ("route" == command || "routeVerbose" == command || "routeWithTransitions" == command) {
if (args.size < 6) {
printUsage()
return
}
val router = Router(
dataDirectoryPath,
TomsAStarStarRouting(), TomsRoutingHeuristics(),
maxExecutionTimeS
)
Router.debugMode = "routeVerbose" == command
val outputTransitions = "routeWithTransitions" == command
val routingType = args[1]
val lat1 = args[2].toDouble()
val lng1 = args[3].toDouble()
val lat2 = args[4].toDouble()
val lng2 = args[5].toDouble()
val route = router.findRoute(
routingType, lat1, lng1, lat2,
lng2
)
router.close()
if (route != null) {
for (n in route) {
val sb = StringBuilder()
sb.append(n.lat).append(',').append(n.lng)
if (outputTransitions) {
sb.append(',').append(n.numberOfTransitionsIfTransitionsAreLoaded)
}
println(sb.toString())
}
if (args.size > 6) {
val filename = args[6]
val kml = KML()
val trackPts = Vector<Position>()
for (n in route) {
val p = Position()
p.latitude = n.lat
p.longitude = n.lng
trackPts.add(p)
}
kml.trackPositions = trackPts
kml.save(
dataDirectoryPath + File.separatorChar + filename
+ "-" + routingType + ".kml"
)
}
}
return
}
// find crossroads
if ("findCrossroads" == command) {
if (args.size < 2) {
printUsage()
return
}
val routingType = args[1]
val isr = InputStreamReader(System.`in`)
val lnr = LineNumberReader(isr)
val positions: MutableList<Position> = ArrayList()
while (true) {
var line: String? = null
try {
line = lnr.readLine()
} catch (e: IOException) {
e.printStackTrace()
}
if (line == null || "eof" == line) break
val lp = line.split(",").toTypedArray()
if (lp.size < 3) {
continue
}
val p = Position()
p.latitude = lp[0].toDouble()
p.longitude = lp[1].toDouble()
p.altitude = lp[2].toDouble()
positions.add(p)
}
val cf = CrossroadsFinder(dataDirectoryPath)
cf.loadNumberOfCrossroads(positions, RoutingType.valueOf(routingType))
for (p in positions) {
val sb = StringBuilder()
sb.append(p.latitude).append(',').append(p.longitude).append(',').append(p.altitude).append(',')
.append(p.nrOfTransitions.toInt())
println(sb.toString())
}
return
}
// find crossroads test
if ("findCrossroadsTest" == command) {
if (args.size < 2) {
printUsage()
return
}
val routingType = args[1]
val positions: MutableList<Position> = ArrayList()
var pt = Position()
pt.latitude = 48.116915489240476
pt.longitude = 11.48764371871948
pt.altitude = 600.0
positions.add(pt)
pt = Position()
pt.latitude = 48.15
pt.longitude = 11.55
pt.altitude = 660.0
positions.add(pt)
val cf = CrossroadsFinder(dataDirectoryPath)
cf.loadNumberOfCrossroads(positions, RoutingType.valueOf(routingType))
for (p in positions) {
val sb = StringBuilder()
sb.append(p.latitude).append(',').append(p.longitude).append(',').append(p.altitude).append(',')
.append(p.nrOfTransitions.toInt())
println(sb.toString())
}
return
}
// test routing
if ("routingTest" == command) {
val startTime = Date()
println("routing test start date $startTime")
val router = Router(
dataDirectoryPath,
TomsAStarStarRouting(), TomsRoutingHeuristics(),
maxExecutionTimeS
)
Router.debugMode = true
testRoute(
router, 48.116915489240476, 11.48764371871948, 48.219297,
11.372824, "hadern-a8", dataDirectoryPath
)
testRoute(
router, 48.116915489240476, 11.48764371871948,
48.29973956844243, 10.97055673599243, "hadern-kissing",
dataDirectoryPath
)
testRoute(
router, 48.125166, 11.451445, 48.12402, 11.515946, "a96",
dataDirectoryPath
)
testRoute(
router, 48.125166, 11.451445, 48.103516, 11.501441,
"a96_Fuerstenrieder", dataDirectoryPath
)
testRoute(
router, 48.09677, 11.323729, 48.393707, 11.841116,
"autobahn", dataDirectoryPath
)
testRoute(
router, 48.107891, 11.461865, 48.099986, 11.511051,
"durch-waldfriedhof", dataDirectoryPath
)
testRoute(
router, 48.107608, 11.461648, 48.108656, 11.477371,
"grosshadern-fussweg", dataDirectoryPath
)
testRoute(
router, 48.275653, 11.786957, 48.106514, 11.449685,
"muenchen-quer", dataDirectoryPath
)
testRoute(
router, 48.073606, 11.38175, 48.065548, 11.327763,
"gauting-unterbrunn", dataDirectoryPath
)
testRoute(
router, 48.073606, 11.38175, 48.152888, 11.346259,
"gauting-puchheim", dataDirectoryPath
)
testRoute(
router, 48.073606, 11.38175, 48.365138, 11.583881,
"gauting-moosanger", dataDirectoryPath
)
testRoute(
router, 47.986073, 11.326733, 48.230162, 11.717434,
"starnberg-ismaning", dataDirectoryPath
)
router.close()
println("finish date " + Date())
println(
"required time "
+ Utils.formatTimeStopWatch(
Date().time
- startTime.time
)
)
}
}
private fun printUsage() {
println("java -jar Jerusalem.jar route foot|bike|racingBike|mountainBike|car|carShortest <latitude1> <longitude1> <latitude2> <longitude2> [<output-file-base-name>]")
println("java -jar Jerusalem.jar rebuild <source-filepath>|- <temp-filepath>")
println("java -jar Jerusalem.jar rebuildIndex <temp-filepath>")
println("java -jar Jerusalem.jar rebuildTransitions <temp-filepath>")
println("java -jar Jerusalem.jar clean <temp-filepath>")
println("java -jar Jerusalem.jar routingTest")
println("java -jar Jerusalem.jar findCrossroads foot|bike|racingBike|mountainBike|car|carShortest")
println("java -jar Jerusalem.jar findCrossroadsTest foot|bike|racingBike|mountainBike|car|carShortest")
}
private fun testRoute(
router: Router, lat1: Double, lng1: Double, lat2: Double,
lng2: Double, name: String, dataDirectoryPath: String
) {
for (rt in RoutingType.values()) testRoute(
router, rt.name, lat1, lng1, lat2, lng2, name,
dataDirectoryPath
)
}
fun testRoute(
router: Router, routingType: String, lat1: Double,
lng1: Double, lat2: Double, lng2: Double, name: String,
dataDirectoryPath: String
) {
println("---------------------------------------------")
println("Computing Route $name ($routingType)")
println("---------------------------------------------")
val route = router
.findRoute(routingType, lat1, lng1, lat2, lng2)
if (route == null) {
println(
"ERROR: no route found for " + name + " ("
+ routingType + ")"
)
return
}
println()
val kml = KML()
val trackPts = Vector<Position>()
for (n in route) {
val p = Position()
p.latitude = n.lat
p.longitude = n.lng
trackPts.add(p)
}
kml.trackPositions = trackPts
kml.save(
dataDirectoryPath + File.separatorChar + name + "-"
+ routingType + ".kml"
)
}
} | apache-2.0 |
tasks/tasks | app/src/main/java/com/todoroo/astrid/api/SearchFilter.kt | 1 | 3738 | package com.todoroo.astrid.api
import android.os.Parcel
import android.os.Parcelable
import com.todoroo.andlib.sql.Criterion
import com.todoroo.andlib.sql.Join
import com.todoroo.andlib.sql.Query
import com.todoroo.andlib.sql.QueryTemplate
import com.todoroo.astrid.data.Task
import org.tasks.data.*
class SearchFilter : Filter {
private constructor()
constructor(title: String?, query: String) : super(title, getQueryTemplate(query))
override fun supportsHiddenTasks() = false
companion object {
/** Parcelable Creator Object */
@JvmField
val CREATOR: Parcelable.Creator<SearchFilter> = object : Parcelable.Creator<SearchFilter> {
/** {@inheritDoc} */
override fun createFromParcel(source: Parcel): SearchFilter? {
val item = SearchFilter()
item.readFromParcel(source)
return item
}
/** {@inheritDoc} */
override fun newArray(size: Int): Array<SearchFilter?> {
return arrayOfNulls(size)
}
}
private fun getQueryTemplate(query: String): QueryTemplate {
val matcher = "%$query%"
return QueryTemplate()
.where(
Criterion.and(
Task.DELETION_DATE.eq(0),
Criterion.or(
Task.NOTES.like(matcher),
Task.TITLE.like(matcher),
Task.ID.`in`(
Query.select(Tag.TASK)
.from(Tag.TABLE)
.where(Tag.NAME.like(matcher))),
Task.UUID.`in`(
Query.select(UserActivity.TASK)
.from(UserActivity.TABLE)
.where(UserActivity.MESSAGE.like(matcher))),
Task.ID.`in`(
Query.select(Geofence.TASK)
.from(Geofence.TABLE)
.join(Join.inner(Place.TABLE, Place.UID.eq(Geofence.PLACE)))
.where(Criterion.or(Place.NAME.like(matcher),
Place.ADDRESS.like(matcher)))),
Task.ID.`in`(
Query.select(CaldavTask.TASK)
.from(CaldavTask.TABLE)
.join(Join.inner(CaldavCalendar.TABLE, CaldavCalendar.UUID.eq(CaldavTask.CALENDAR)))
.where(CaldavCalendar.NAME.like(matcher))),
Task.ID.`in`(
Query.select(GoogleTask.TASK)
.from(GoogleTask.TABLE)
.join(Join.inner(GoogleTaskList.TABLE, GoogleTaskList.REMOTE_ID.eq(GoogleTask.LIST)))
.where(GoogleTaskList.NAME.like(matcher)))
)))
}
}
} | gpl-3.0 |
natanieljr/droidmate | project/pcComponents/core/src/test/kotlin/org/droidmate/test_suites/ReporterTestSuite.kt | 1 | 1673 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.test_suites
import org.droidmate.test_suite_categories.ExcludedFromFastRegressionTests
import org.junit.experimental.categories.Categories
import org.junit.runner.RunWith
//@RunWith(Categories::class)
//@Categories.ExcludeCategory(ExcludedFromFastRegressionTests::class)
// FIXME dependencies (parent test class should be in commonLib then this test-suit can be put into exploration.report
//@Suite.SuiteClasses(
// extensions_miscKtTest::class,
// extensions_time_seriesKtTest::class,
// functionsKtTest::class,
// ApkSummaryTest::class,
// ExplorationOutput2ReportTest::class
//)
class ReporterTestSuite
| gpl-3.0 |
cloose/luftbild4p3d | src/main/kotlin/org/luftbild4p3d/osm/Way.kt | 1 | 430 | package org.luftbild4p3d.osm
import javax.xml.bind.annotation.XmlAttribute
import javax.xml.bind.annotation.XmlElement
class Way(@XmlAttribute val id: Long = 0) {
@XmlElement(name = "nd")
val nodeReference: MutableCollection<NodeReference> = mutableListOf()
@XmlElement(name = "tag")
val tag: MutableCollection<Tag> = mutableListOf()
fun closed() = nodeReference.first().ref == nodeReference.last().ref
} | gpl-3.0 |
didi/DoraemonKit | Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/DoKitTransformTaskExecutionListener.kt | 2 | 682 | package com.didichuxing.doraemonkit.plugin
import com.android.build.gradle.internal.pipeline.TransformTask
import com.didiglobal.booster.kotlinx.call
import com.didiglobal.booster.kotlinx.get
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.execution.TaskExecutionAdapter
/**
* @author neighbWang
*/
class DoKitTransformTaskExecutionListener(private val project: Project) : TaskExecutionAdapter() {
override fun beforeExecute(task: Task) {
task.takeIf {
it.project == project && it is TransformTask && it.transform.scopes.isNotEmpty()
}?.run {
task["outputStream"]?.call<Unit>("init")
}
}
} | apache-2.0 |
arturbosch/detekt | detekt-test-utils/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/KotlinEnvironmentTestSetup.kt | 1 | 690 | // Remove the suppression when https://github.com/pinterest/ktlint/issues/1125 is fixed
@file:Suppress("SpacingBetweenDeclarationsWithAnnotations")
package io.gitlab.arturbosch.detekt.rules
import io.github.detekt.test.utils.createEnvironment
import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment
import org.spekframework.spek2.dsl.Root
import org.spekframework.spek2.lifecycle.CachingMode
fun Root.setupKotlinEnvironment() {
val wrapper by memoized(CachingMode.SCOPE, { createEnvironment() }, { it.dispose() })
// name is used for delegation
@Suppress("UNUSED_VARIABLE")
val env: KotlinCoreEnvironment by memoized(CachingMode.EACH_GROUP) { wrapper.env }
}
| apache-2.0 |
vitaorganizer/vitaorganizer | src/com/soywiz/util/BitRead.kt | 2 | 1767 | package com.soywiz.util
object BitRead {
fun Int.signExtend(bits: Int): Int = (this shl (32 - bits)) shr (32 - bits)
fun pack16(a: Int, b: Int) = ((a and 0xFF) shl 0) or ((b and 0xFF) shl 8)
fun pack24(a: Int, b: Int, c: Int) = ((a and 0xFF) shl 0) or ((b and 0xFF) shl 8) or ((c and 0xFF) shl 16)
fun pack32(a: Int, b: Int, c: Int, d: Int) = ((a and 0xFF) shl 0) or ((b and 0xFF) shl 8) or ((c and 0xFF) shl 16) or ((d and 0xFF) shl 24)
fun pack64(a: Int, b: Int, c: Int, d: Int, e: Int, f: Int, g: Int, h: Int) = pack32(a, b, c, d).toLong() or pack32(e, f, g, h).toLong().shl(32)
fun S8(bytes: ByteArray, i: Int): Int = bytes[i].toInt()
fun S16_le(bytes: ByteArray, i: Int): Int = pack16(S8(bytes, i + 0), S8(bytes, i + 1)).toShort().toInt()
fun S24_le(bytes: ByteArray, i: Int): Int = pack24(S8(bytes, i + 0), S8(bytes, i + 1), S8(bytes, i + 2)).signExtend(24)
fun S32_le(bytes: ByteArray, i: Int): Int = pack32(S8(bytes, i + 0), S8(bytes, i + 1), S8(bytes, i + 2), S8(bytes, i + 3)).toInt()
fun S64_le(bytes: ByteArray, i: Int): Long = pack64(S8(bytes, i + 0), S8(bytes, i + 1), S8(bytes, i + 2), S8(bytes, i + 3), S8(bytes, i + 4), S8(bytes, i + 5), S8(bytes, i + 6), S8(bytes, i + 7))
fun S16_be(bytes: ByteArray, i: Int): Int = Integer.reverseBytes(S16_le(bytes, i))
fun S32_be(bytes: ByteArray, i: Int): Int = Integer.reverseBytes(S32_le(bytes, i))
fun S64_be(bytes: ByteArray, i: Int): Long = java.lang.Long.reverseBytes(S64_le(bytes, i))
fun U8(bytes: ByteArray, i: Int): Int = bytes[i].toInt() and 0xFF
fun U16_le(bytes: ByteArray, i: Int): Int = S16_le(bytes, i) and 0xFFFF
fun U32_le(bytes: ByteArray, i: Int): Long = S32_le(bytes, i).toLong() and 0xFFFFFFFFL
fun U64_le(bytes: ByteArray, i: Int): Long = S64_le(bytes, i).toLong()
} | gpl-3.0 |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/ApplicationAction.kt | 1 | 5397 | /*
ParaTask Copyright (C) 2017 Nick Robinson>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.gui
import javafx.event.EventHandler
import javafx.scene.control.*
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import javafx.scene.input.KeyEvent
import uk.co.nickthecoder.paratask.ParaTask
import kotlin.reflect.KMutableProperty0
/**
*/
open class ApplicationAction(
val name: String,
keyCode: KeyCode?,
shift: Boolean? = false,
control: Boolean? = false,
alt: Boolean? = false,
meta: Boolean? = false,
shortcut: Boolean? = false,
val tooltip: String? = null,
val label: String? = null
) {
private val defaultKeyCodeCombination: KeyCodeCombination? =
keyCode?.let { createKeyCodeCombination(keyCode, shift, control, alt, meta, shortcut) }
var keyCodeCombination = defaultKeyCodeCombination
open val image: Image? = ParaTask.imageResource("buttons/$name.png")
fun revert() {
keyCodeCombination = defaultKeyCodeCombination
}
fun isChanged(): Boolean = keyCodeCombination != defaultKeyCodeCombination
fun shortcutString(): String = if (keyCodeCombination?.code == null) "" else keyCodeCombination.toString()
fun match(event: KeyEvent): Boolean {
return keyCodeCombination?.match(event) == true
}
fun createTooltip(): Tooltip? {
if (tooltip == null && keyCodeCombination == null) {
return null
}
val result = StringBuilder()
tooltip?.let { result.append(it) }
if (tooltip != null && keyCodeCombination != null) {
result.append(" (")
}
keyCodeCombination?.let { result.append(it.displayText) }
if (tooltip != null && keyCodeCombination != null) {
result.append(")")
}
return Tooltip(result.toString())
}
fun shortcutLabel() = keyCodeCombination?.displayText
fun createMenuItem(shortcuts: ShortcutHelper? = null, action: () -> Unit): MenuItem {
shortcuts?.add(this, action)
val menuItem = MenuItem(label)
menuItem.onAction = EventHandler { action() }
image?.let { menuItem.graphic = ImageView(it) }
menuItem.accelerator = keyCodeCombination
return menuItem
}
fun createCheckMenuItem(shortcuts: ShortcutHelper? = null, property: KMutableProperty0<Boolean>, action: () -> Unit): CheckMenuItem {
val menuItem = CheckMenuItem(label)
menuItem.isSelected = property.getter.call()
val updateAction = {
menuItem.isSelected != menuItem.isSelected
property.setter.call(menuItem.isSelected)
action()
}
shortcuts?.add(this, updateAction)
menuItem.accelerator = keyCodeCombination
menuItem.onAction = EventHandler { updateAction() }
return menuItem
}
fun createButton(shortcuts: ShortcutHelper? = null, action: () -> Unit): Button {
shortcuts?.add(this, action)
val button = Button()
updateButton(button, action)
return button
}
fun createToggleButton(shortcuts: ShortcutHelper? = null, action: () -> Unit): ToggleButton {
val button = ToggleButton()
shortcuts?.add(this, {
button.isSelected = !button.isSelected
action()
})
updateButton(button, action)
return button
}
private fun updateButton(button: ButtonBase, action: () -> Unit) {
if (image == null) {
button.text = label ?: name
} else {
button.graphic = ImageView(image)
}
if (label != null) {
button.text = label
}
button.onAction = EventHandler {
action()
}
button.tooltip = createTooltip()
}
companion object {
fun modifier(down: Boolean?) =
if (down == null) {
KeyCombination.ModifierValue.ANY
} else if (down) {
KeyCombination.ModifierValue.DOWN
} else {
KeyCombination.ModifierValue.UP
}
fun createKeyCodeCombination(
keyCode: KeyCode,
shift: Boolean? = false,
control: Boolean? = false,
alt: Boolean? = false,
meta: Boolean? = false,
shortcut: Boolean? = false): KeyCodeCombination {
return KeyCodeCombination(
keyCode,
modifier(shift), modifier(control), modifier(alt), modifier(meta), modifier(shortcut))
}
}
}
| gpl-3.0 |
nemerosa/ontrack | ontrack-model/src/main/java/net/nemerosa/ontrack/model/support/SettingsRepositoryExtensions.kt | 1 | 2530 | package net.nemerosa.ontrack.model.support
import kotlin.reflect.KProperty0
import kotlin.reflect.KProperty1
/**
* Type safe access to settings.
*/
inline fun <reified T> SettingsRepository.getString(property: KProperty1<T, String?>, defaultValue: String): String =
getString(T::class.java, property.name, defaultValue)
/**
* Type safe access to settings.
*/
inline fun <reified T> SettingsRepository.getInt(property: KProperty1<T, Int?>, defaultValue: Int): Int =
getInt(T::class.java, property.name, defaultValue)
/**
* Type safe access to settings.
*/
inline fun <reified T> SettingsRepository.getLong(property: KProperty1<T, Long?>, defaultValue: Long): Long =
getLong(T::class.java, property.name, defaultValue)
/**
* Type safe access to settings.
*/
inline fun <reified T> SettingsRepository.getBoolean(
property: KProperty1<T, Boolean?>,
defaultValue: Boolean,
): Boolean =
getBoolean(T::class.java, property.name, defaultValue)
/**
* Type safe access to settings.
*/
inline fun <reified T, reified E : Enum<E>> SettingsRepository.getEnum(
property: KProperty1<T, E?>,
defaultValue: E,
): E =
getString(T::class.java, property.name, "")
.takeIf { it.isNotBlank() }
?.let { enumValueOf<E>(it) }
?: defaultValue
/**
* Type safe access to settings.
*/
inline fun <reified T> SettingsRepository.getPassword(
property: KProperty1<T, String?>,
defaultValue: String,
noinline decryptService: (String?) -> String?,
): String = getPassword(T::class.java, property.name, defaultValue, decryptService)
/**
* Type safe setter of settings
*/
inline fun <reified T> SettingsRepository.setString(property: KProperty0<String?>) {
setString(T::class.java, property.name, property.get())
}
/**
* Type safe setter of settings
*/
inline fun <reified T> SettingsRepository.setBoolean(property: KProperty0<Boolean>) {
setBoolean(T::class.java, property.name, property.get())
}
/**
* Type safe setter of settings
*/
inline fun <reified T> SettingsRepository.setInt(property: KProperty0<Int>) {
setInt(T::class.java, property.name, property.get())
}
/**
* Type safe setter of settings
*/
inline fun <reified T> SettingsRepository.setLong(property: KProperty0<Long>) {
setLong(T::class.java, property.name, property.get())
}
/**
* Type safe setter of settings
*/
inline fun <reified T, E : Enum<E>> SettingsRepository.setEnum(property: KProperty0<E>) {
setString(T::class.java, property.name, property.get().toString())
}
| mit |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/chat/ChatDetailPresenter.kt | 1 | 2862 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.chat
import android.util.Log
import com.pickth.commons.mvp.BaseView
import com.pickth.gachi.net.service.GachiService
import com.pickth.gachi.view.chat.adapter.ChatDetailAdapterContract
import com.pickth.gachi.view.chat.adapter.ChatMessage
import okhttp3.ResponseBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.text.SimpleDateFormat
import java.util.*
class ChatDetailPresenter: ChatDetailContract.Presenter {
private lateinit var mView: ChatDetailContract.View
private lateinit var mAdapterView: ChatDetailAdapterContract.View
private lateinit var mAdapterModel: ChatDetailAdapterContract.Model
private lateinit var mParticipantAdapter: ParticipantAdapter
override fun attachView(view: BaseView<*>) {
mView = view as ChatDetailContract.View
}
override fun setChatDetailAdapterView(view: ChatDetailAdapterContract.View) {
mAdapterView = view
}
override fun setChatDetailAdapterModel(model: ChatDetailAdapterContract.Model) {
mAdapterModel = model
}
override fun setParticipantAdapter(adapter: ParticipantAdapter) {
mParticipantAdapter = adapter
}
override fun getItemCount(): Int = mAdapterModel.getItemCount()
override fun sendMessage(msg: String) {
val date = SimpleDateFormat("hh : mm a").format(Date(System.currentTimeMillis())).toString()
mAdapterModel.addItem(ChatMessage(msg, date ,0))
// test input
mAdapterModel.addItem(ChatMessage("test", date ,1))
mView.scrollToPosition(getItemCount())
}
override fun getGachiInfo() {
GachiService().getGachiInfo(mView.getLid())
.enqueue(object: Callback<ResponseBody> {
override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>) {
Log.d("Gachi__ChatPresenter", "getGachiInfo onResponse, code: ${response.code()}")
if(response.code() != 200) return
mView.bindGachiInfo(response.body()?.string()!!)
}
override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
}
})
}
} | apache-2.0 |
inlacou/VolleyControllerLibrary | volleycontroller/src/main/java/com/libraries/inlacou/volleycontroller/Extensions.kt | 1 | 1750 | package com.libraries.inlacou.volleycontroller
import com.android.volley.VolleyError
import java.io.UnsupportedEncodingException
fun VolleyError?.errorMessage(charset: VolleyController.CharSetNames): String {
return errorMessage(charset.toString())
}
fun VolleyError?.errorMessage(charsetName: String): String {
return try {
VolleyController.getErrorMsg(this!!, charsetName)
} catch (e: UnsupportedEncodingException) {
"unknown"
} catch (e: NullPointerException) {
"unknown"
} catch (e: KotlinNullPointerException) {
"unknown"
} catch (e: Exception) {
"unknown"
}
}
val VolleyError?.errorMessage: String
get() {
return try {
VolleyController.getErrorMsg(this!!)
} catch (e: UnsupportedEncodingException) {
"unknown"
} catch (e: NullPointerException) {
"unknown"
} catch (e: KotlinNullPointerException) {
"unknown"
} catch (e: Exception) {
"unknown"
}
}
val VolleyError?.errorMessageISO_8859_1: String
get() {
return try {
VolleyController.getErrorMsg(this!!, VolleyController.CharSetNames.ISO_8859_1.toString())
} catch (e: UnsupportedEncodingException) {
"unknown"
} catch (e: NullPointerException) {
"unknown"
} catch (e: KotlinNullPointerException) {
"unknown"
} catch (e: Exception) {
"unknown"
}
}
val VolleyError?.errorMessageUTF_8: String
get() {
return try {
VolleyController.getErrorMsg(this!!, VolleyController.CharSetNames.UTF_8.toString())
} catch (e: UnsupportedEncodingException) {
"unknown"
} catch (e: NullPointerException) {
"unknown"
} catch (e: KotlinNullPointerException) {
"unknown"
} catch (e: Exception) {
"unknown"
}
}
val VolleyError?.statusCode: Int
get() = this?.networkResponse?.statusCode ?: -1
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.