repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
brunogabriel/FriendlyDonations-Android
FreeStuffs-Android/app/src/main/java/br/com/freestuffs/shared/extensions/ButterKnife.kt
1
7315
/* * Copyright 2014 Jake Wharton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.freestuffs.shared.extensions import android.app.Activity import android.app.Dialog import android.app.DialogFragment import android.app.Fragment import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty import android.support.v4.app.DialogFragment as SupportDialogFragment import android.support.v4.app.Fragment as SupportFragment fun <V : View> View.bindView(id: Int) : ReadOnlyProperty<View, V> = required(id, viewFinder) fun <V : View> Activity.bindView(id: Int) : ReadOnlyProperty<Activity, V> = required(id, viewFinder) fun <V : View> Dialog.bindView(id: Int) : ReadOnlyProperty<Dialog, V> = required(id, viewFinder) fun <V : View> DialogFragment.bindView(id: Int) : ReadOnlyProperty<DialogFragment, V> = required(id, viewFinder) fun <V : View> SupportDialogFragment.bindView(id: Int) : ReadOnlyProperty<SupportDialogFragment, V> = required(id, viewFinder) fun <V : View> Fragment.bindView(id: Int) : ReadOnlyProperty<Fragment, V> = required(id, viewFinder) fun <V : View> SupportFragment.bindView(id: Int) : ReadOnlyProperty<SupportFragment, V> = required(id, viewFinder) fun <V : View> ViewHolder.bindView(id: Int) : ReadOnlyProperty<ViewHolder, V> = required(id, viewFinder) fun <V : View> View.bindOptionalView(id: Int) : ReadOnlyProperty<View, V?> = optional(id, viewFinder) fun <V : View> Activity.bindOptionalView(id: Int) : ReadOnlyProperty<Activity, V?> = optional(id, viewFinder) fun <V : View> Dialog.bindOptionalView(id: Int) : ReadOnlyProperty<Dialog, V?> = optional(id, viewFinder) fun <V : View> DialogFragment.bindOptionalView(id: Int) : ReadOnlyProperty<DialogFragment, V?> = optional(id, viewFinder) fun <V : View> SupportDialogFragment.bindOptionalView(id: Int) : ReadOnlyProperty<SupportDialogFragment, V?> = optional(id, viewFinder) fun <V : View> Fragment.bindOptionalView(id: Int) : ReadOnlyProperty<Fragment, V?> = optional(id, viewFinder) fun <V : View> SupportFragment.bindOptionalView(id: Int) : ReadOnlyProperty<SupportFragment, V?> = optional(id, viewFinder) fun <V : View> ViewHolder.bindOptionalView(id: Int) : ReadOnlyProperty<ViewHolder, V?> = optional(id, viewFinder) fun <V : View> View.bindViews(vararg ids: Int) : ReadOnlyProperty<View, List<V>> = required(ids, viewFinder) fun <V : View> Activity.bindViews(vararg ids: Int) : ReadOnlyProperty<Activity, List<V>> = required(ids, viewFinder) fun <V : View> Dialog.bindViews(vararg ids: Int) : ReadOnlyProperty<Dialog, List<V>> = required(ids, viewFinder) fun <V : View> DialogFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<DialogFragment, List<V>> = required(ids, viewFinder) fun <V : View> SupportDialogFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<SupportDialogFragment, List<V>> = required(ids, viewFinder) fun <V : View> Fragment.bindViews(vararg ids: Int) : ReadOnlyProperty<Fragment, List<V>> = required(ids, viewFinder) fun <V : View> SupportFragment.bindViews(vararg ids: Int) : ReadOnlyProperty<SupportFragment, List<V>> = required(ids, viewFinder) fun <V : View> ViewHolder.bindViews(vararg ids: Int) : ReadOnlyProperty<ViewHolder, List<V>> = required(ids, viewFinder) fun <V : View> View.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<View, List<V>> = optional(ids, viewFinder) fun <V : View> Activity.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Activity, List<V>> = optional(ids, viewFinder) fun <V : View> Dialog.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Dialog, List<V>> = optional(ids, viewFinder) fun <V : View> DialogFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<DialogFragment, List<V>> = optional(ids, viewFinder) fun <V : View> SupportDialogFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<SupportDialogFragment, List<V>> = optional(ids, viewFinder) fun <V : View> Fragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<Fragment, List<V>> = optional(ids, viewFinder) fun <V : View> SupportFragment.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<SupportFragment, List<V>> = optional(ids, viewFinder) fun <V : View> ViewHolder.bindOptionalViews(vararg ids: Int) : ReadOnlyProperty<ViewHolder, List<V>> = optional(ids, viewFinder) private val View.viewFinder: View.(Int) -> View? get() = { findViewById(it) } private val Activity.viewFinder: Activity.(Int) -> View? get() = { findViewById(it) } private val Dialog.viewFinder: Dialog.(Int) -> View? get() = { findViewById(it) } private val DialogFragment.viewFinder: DialogFragment.(Int) -> View? get() = { dialog?.findViewById(it) ?: view?.findViewById(it) } private val SupportDialogFragment.viewFinder: SupportDialogFragment.(Int) -> View? get() = { dialog?.findViewById(it) ?: view?.findViewById(it) } private val Fragment.viewFinder: Fragment.(Int) -> View? get() = { view.findViewById(it) } private val SupportFragment.viewFinder: SupportFragment.(Int) -> View? get() = { view!!.findViewById(it) } private val ViewHolder.viewFinder: ViewHolder.(Int) -> View? get() = { itemView.findViewById(it) } private fun viewNotFound(id:Int, desc: KProperty<*>): Nothing = throw IllegalStateException("View ID $id for '${desc.name}' not found.") @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, desc -> t.finder(id) as V? ?: viewNotFound(id, desc) } @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(id: Int, finder: T.(Int) -> View?) = Lazy { t: T, desc -> t.finder(id) as V? } @Suppress("UNCHECKED_CAST") private fun <T, V : View> required(ids: IntArray, finder: T.(Int) -> View?) = Lazy { t: T, desc -> ids.map { t.finder(it) as V? ?: viewNotFound(it, desc) } } @Suppress("UNCHECKED_CAST") private fun <T, V : View> optional(ids: IntArray, finder: T.(Int) -> View?) = Lazy { t: T, desc -> ids.map { t.finder(it) as V? }.filterNotNull() } // Like Kotlin's lazy delegate but the initializer gets the target and metadata passed to it private class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> { private object EMPTY private var value: Any? = EMPTY override fun getValue(thisRef: T, property: KProperty<*>): V { if (value == EMPTY) { value = initializer(thisRef, property) } @Suppress("UNCHECKED_CAST") return value as V } }
mit
c6de51e385a72fabeae1320070557db8
41.283237
100
0.699658
3.87037
false
false
false
false
b95505017/android-architecture-components
PagingWithNetworkSample/app/src/main/java/com/android/example/paging/pagingwithnetwork/reddit/repository/inMemory/byItem/ItemKeyedSubredditDataSource.kt
1
6057
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.paging.pagingwithnetwork.reddit.repository.inMemory.byItem import android.arch.lifecycle.MutableLiveData import android.arch.paging.ItemKeyedDataSource import com.android.example.paging.pagingwithnetwork.reddit.api.RedditApi import com.android.example.paging.pagingwithnetwork.reddit.repository.NetworkState import com.android.example.paging.pagingwithnetwork.reddit.vo.RedditPost import retrofit2.Call import retrofit2.Response import java.io.IOException import java.util.concurrent.Executor /** * A data source that uses the "name" field of posts as the key for next/prev pages. * <p> * Note that this is not the correct consumption of the Reddit API but rather shown here as an * alternative implementation which might be more suitable for your backend. * see PageKeyedSubredditDataSource for the other sample. */ class ItemKeyedSubredditDataSource( private val redditApi: RedditApi, private val subredditName: String, private val retryExecutor: Executor) : ItemKeyedDataSource<String, RedditPost>() { // keep a function reference for the retry event private var retry: (() -> Any)? = null /** * There is no sync on the state because paging will always call loadInitial first then wait * for it to return some success value before calling loadAfter and we don't support loadBefore * in this example. * <p> * See BoundaryCallback example for a more complete example on syncing multiple network states. */ val networkState = MutableLiveData<NetworkState>() val initialLoad = MutableLiveData<NetworkState>() fun retryAllFailed() { val prevRetry = retry retry = null prevRetry?.let { retryExecutor.execute { it.invoke() } } } override fun loadBefore(params: LoadParams<String>, callback: LoadCallback<RedditPost>) { // ignored, since we only ever append to our initial load } override fun loadAfter(params: LoadParams<String>, callback: LoadCallback<RedditPost>) { // set network value to loading. networkState.postValue(NetworkState.LOADING) // even though we are using async retrofit API here, we could also use sync // it is just different to show that the callback can be called async. redditApi.getTopAfter(subreddit = subredditName, after = params.key, limit = params.requestedLoadSize).enqueue( object : retrofit2.Callback<RedditApi.ListingResponse> { override fun onFailure(call: Call<RedditApi.ListingResponse>, t: Throwable) { // keep a lambda for future retry retry = { loadAfter(params, callback) } // publish the error networkState.postValue(NetworkState.error(t.message ?: "unknown err")) } override fun onResponse( call: Call<RedditApi.ListingResponse>, response: Response<RedditApi.ListingResponse>) { if (response.isSuccessful) { val items = response.body()?.data?.children?.map { it.data } ?: emptyList() // clear retry since last request succeeded retry = null callback.onResult(items) networkState.postValue(NetworkState.LOADED) } else { retry = { loadAfter(params, callback) } networkState.postValue( NetworkState.error("error code: ${response.code()}")) } } } ) } /** * The name field is a unique identifier for post items. * (no it is not the title of the post :) ) * https://www.reddit.com/dev/api */ override fun getKey(item: RedditPost): String = item.name override fun loadInitial( params: LoadInitialParams<String>, callback: LoadInitialCallback<RedditPost>) { val request = redditApi.getTop( subreddit = subredditName, limit = params.requestedLoadSize ) // update network states. // we also provide an initial load state to the listeners so that the UI can know when the // very first list is loaded. networkState.postValue(NetworkState.LOADING) initialLoad.postValue(NetworkState.LOADING) // triggered by a refresh, we better execute sync try { val response = request.execute() val items = response.body()?.data?.children?.map { it.data } ?: emptyList() retry = null networkState.postValue(NetworkState.LOADED) initialLoad.postValue(NetworkState.LOADED) callback.onResult(items) } catch (ioException: IOException) { retry = { loadInitial(params, callback) } val error = NetworkState.error(ioException.message ?: "unknown error") networkState.postValue(error) initialLoad.postValue(error) } } }
apache-2.0
ac2aaa88869aa2f4436c783f98810f19
41.069444
103
0.613175
5.266957
false
false
false
false
vovagrechka/k2php
k2php/src/org/jetbrains/kotlin/js/translate/utils/utils.kt
1
8255
/* * Copyright 2010-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.kotlin.js.translate.utils import com.intellij.util.SmartList import k2php.* import org.jetbrains.kotlin.backend.common.COROUTINES_INTRINSICS_PACKAGE_FQ_NAME import org.jetbrains.kotlin.backend.common.COROUTINE_SUSPENDED_NAME import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.js.backend.ast.* import org.jetbrains.kotlin.js.backend.ast.metadata.CoroutineMetadata import org.jetbrains.kotlin.js.backend.ast.metadata.coroutineMetadata import org.jetbrains.kotlin.js.translate.context.Namer import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.intrinsic.functions.basic.FunctionIntrinsicWithReceiverComputed import org.jetbrains.kotlin.js.translate.reference.ReferenceTranslator import org.jetbrains.kotlin.js.translate.utils.TranslationUtils.simpleReturnFunction import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.types.KotlinType fun generateDelegateCall( classDescriptor: ClassDescriptor, fromDescriptor: FunctionDescriptor, toDescriptor: FunctionDescriptor, thisObject: JsExpression, context: TranslationContext ) { val overriddenMemberFunctionName = context.getNameForDescriptor(toDescriptor) val overriddenMemberFunctionRef = JsNameRef(overriddenMemberFunctionName, thisObject) val parameters = SmartList<JsParameter>() val args = SmartList<JsExpression>() val functionScope = context.getScopeForDescriptor(fromDescriptor) if (DescriptorUtils.isExtension(fromDescriptor)) { val extensionFunctionReceiverName = functionScope.declareTemporaryName(Namer.getReceiverParameterName()) parameters.add(JsParameter(extensionFunctionReceiverName)) args.add(JsNameRef(extensionFunctionReceiverName)) } for (param in fromDescriptor.valueParameters) { val paramName = param.name.asString() val jsParamName = functionScope.declareTemporaryName(paramName) parameters.add(JsParameter(jsParamName)) args.add(JsNameRef(jsParamName)) } val intrinsic = context.intrinsics().getFunctionIntrinsic(toDescriptor) val invocation = if (intrinsic.exists() && intrinsic is FunctionIntrinsicWithReceiverComputed) { intrinsic.apply(thisObject, args, context) } else { JsInvocation(overriddenMemberFunctionRef, args) } val functionObject = simpleReturnFunction(context.getScopeForDescriptor(fromDescriptor), invocation) functionObject.parameters.addAll(parameters) context.addFunctionToPrototype(classDescriptor, fromDescriptor, functionObject) } fun <T, S> List<T>.splitToRanges(classifier: (T) -> S): List<Pair<List<T>, S>> { if (isEmpty()) return emptyList() var lastIndex = 0 var lastClass: S = classifier(this[0]) val result = mutableListOf<Pair<List<T>, S>>() for ((index, e) in asSequence().withIndex().drop(1)) { val cls = classifier(e) if (cls != lastClass) { result += Pair(subList(lastIndex, index), lastClass) lastClass = cls lastIndex = index } } result += Pair(subList(lastIndex, size), lastClass) return result } fun getReferenceToJsClass(type: KotlinType, context: TranslationContext): JsExpression { val classifierDescriptor = type.constructor.declarationDescriptor val referenceToJsClass: JsExpression = when (classifierDescriptor) { is ClassDescriptor -> { ReferenceTranslator.translateAsTypeReference(classifierDescriptor, context) } is TypeParameterDescriptor -> { assert(classifierDescriptor.isReified) context.usageTracker()?.used(classifierDescriptor) context.getNameForDescriptor(classifierDescriptor).makeRef() } else -> { throw IllegalStateException("Can't get reference for $type") } } return referenceToJsClass } fun TranslationContext.addFunctionToPrototype(classDescriptor: ClassDescriptor, descriptor: FunctionDescriptor, function: JsExpression) { val prototypeRef = JsAstUtils.prototypeOf(getInnerReference(classDescriptor)) // val functionRef = JsNameRef(getNameForDescriptor(descriptor), prototypeRef) classDescriptor.phpClass.statements += function.makeStmt() // addDeclarationStatement(JsAstUtils.assignment(functionRef, function).makeStmt()) } fun TranslationContext.addAccessorsToPrototype( containingClass: ClassDescriptor, propertyDescriptor: PropertyDescriptor, literal: JsObjectLiteral ) { val prototypeRef = JsAstUtils.prototypeOf(getInnerReference(containingClass)) val propertyName = getNameForDescriptor(propertyDescriptor) val defineProperty = JsAstUtils.defineProperty(prototypeRef, propertyName.ident, literal, program()) containingClass.phpClass.constructorFunction.body.statements.add( 0, JsInvocation(JsNameRef("__photlin_defineProperty", scope().declareName("this").makePHPVarRef()), JsStringLiteral(propertyName.ident), literal ).makeStmt()) // containingClass.phpClass.constructorFunction.body.statements.add(0, defineProperty.makeStmt()) // addDeclarationStatement(defineProperty.makeStmt()) } fun FunctionDescriptor.requiresStateMachineTransformation(context: TranslationContext): Boolean = this is AnonymousFunctionDescriptor || context.bindingContext()[BindingContext.CONTAINS_NON_TAIL_SUSPEND_CALLS, this] == true fun JsFunction.fillCoroutineMetadata( context: TranslationContext, descriptor: FunctionDescriptor, hasController: Boolean, isLambda: Boolean ) { if (!descriptor.requiresStateMachineTransformation(context)) return val suspendPropertyDescriptor = context.currentModule.getPackage(COROUTINES_INTRINSICS_PACKAGE_FQ_NAME) .memberScope .getContributedVariables(COROUTINE_SUSPENDED_NAME, NoLookupLocation.FROM_BACKEND).first() val coroutineBaseClassRef = ReferenceTranslator.translateAsTypeReference(TranslationUtils.getCoroutineBaseClass(context), context) fun getCoroutinePropertyName(id: String) = context.getNameForDescriptor(TranslationUtils.getCoroutineProperty(context, id)) coroutineMetadata = CoroutineMetadata( doResumeName = context.getNameForDescriptor(TranslationUtils.getCoroutineDoResumeFunction(context)), resumeName = context.getNameForDescriptor(TranslationUtils.getCoroutineResumeFunction(context)), suspendObjectRef = ReferenceTranslator.translateAsValueReference(suspendPropertyDescriptor, context), baseClassRef = coroutineBaseClassRef, stateName = getCoroutinePropertyName("state"), exceptionStateName = getCoroutinePropertyName("exceptionState"), finallyPathName = getCoroutinePropertyName("finallyPath"), resultName = getCoroutinePropertyName("result"), exceptionName = getCoroutinePropertyName("exception"), facadeName = getCoroutinePropertyName("facade"), hasController = hasController, isLambda = isLambda, hasReceiver = descriptor.dispatchReceiverParameter != null ) }
apache-2.0
e905d2a7e4ed0750cb33ba0fd9bb2c29
43.144385
137
0.754452
4.984903
false
false
false
false
ebraminio/DroidPersianCalendar
PersianCalendar/src/main/java/com/byagowi/persiancalendar/ui/calendar/dialogs/SelectDayDialog.kt
1
1331
package com.byagowi.persiancalendar.ui.calendar.dialogs import android.app.Dialog import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatDialogFragment import com.byagowi.persiancalendar.R import com.byagowi.persiancalendar.ui.MainActivity import com.byagowi.persiancalendar.ui.shared.DayPickerView class SelectDayDialog : AppCompatDialogFragment() { var onSuccess = fun(jdn: Long) {} override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val jdn = arguments?.getLong(BUNDLE_KEY, -1L) ?: -1L val mainActivity = activity as MainActivity val dayPickerView = DayPickerView(mainActivity) dayPickerView.setDayJdnOnView(jdn) return AlertDialog.Builder(mainActivity) .setView(dayPickerView as View) .setCustomTitle(null) .setPositiveButton(R.string.go) { _, _ -> val resultJdn = dayPickerView.dayJdnFromView if (resultJdn != -1L) onSuccess(resultJdn) }.create() } companion object { private const val BUNDLE_KEY = "jdn" fun newInstance(jdn: Long) = SelectDayDialog().apply { arguments = Bundle().apply { putLong(BUNDLE_KEY, jdn) } } } }
gpl-3.0
8fb09b548d9eb57463918f7ce00d0449
31.463415
70
0.673178
4.589655
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/shippinglabels/ShippingLabelRestClient.kt
2
20986
package org.wordpress.android.fluxc.network.rest.wpcom.wc.shippinglabels import android.content.Context import com.android.volley.RequestQueue import com.google.gson.Gson import com.google.gson.JsonElement import com.google.gson.JsonObject import com.google.gson.annotations.SerializedName import com.google.gson.reflect.TypeToken import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.CustomPackage import org.wordpress.android.fluxc.model.shippinglabels.WCPackagesResult.PredefinedOption import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelAddress import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelModel.ShippingLabelPackage import org.wordpress.android.fluxc.model.shippinglabels.WCShippingLabelPackageData import org.wordpress.android.fluxc.model.shippinglabels.WCShippingPackageCustoms import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError import org.wordpress.android.fluxc.network.utils.toMap import java.math.BigDecimal import java.util.Date import java.util.Locale import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton import kotlin.collections.toMap as asMap @Singleton class ShippingLabelRestClient @Inject constructor( dispatcher: Dispatcher, private val jetpackTunnelGsonRequestBuilder: JetpackTunnelGsonRequestBuilder, appContext: Context?, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun fetchShippingLabelsForOrder( orderId: Long, site: SiteModel ): WooPayload<ShippingLabelApiResponse> { val url = WOOCOMMERCE.connect.label.order(orderId).pathV1 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, emptyMap(), ShippingLabelApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun refundShippingLabelForOrder( site: SiteModel, orderId: Long, remoteShippingLabelId: Long ): WooPayload<ShippingLabelApiResponse> { val url = WOOCOMMERCE.connect.label.order(orderId).shippingLabelId(remoteShippingLabelId).refund.pathV1 val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, emptyMap(), ShippingLabelApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun printShippingLabels( site: SiteModel, paperSize: String, shippingLabelIds: List<Long> ): WooPayload<PrintShippingLabelApiResponse> { val url = WOOCOMMERCE.connect.label.print.pathV1 val params = mapOf( "paper_size" to paperSize, "label_id_csv" to shippingLabelIds.joinToString(","), "caption_csv" to "", "json" to "true" ) val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, params, PrintShippingLabelApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun checkShippingLabelCreationEligibility( site: SiteModel, orderId: Long, canCreatePackage: Boolean, canCreatePaymentMethod: Boolean, canCreateCustomsForm: Boolean ): WooPayload<SLCreationEligibilityApiResponse> { val url = WOOCOMMERCE.connect.label.order(orderId).creation_eligibility.pathV1 val params = mapOf( "can_create_package" to canCreatePackage.toString(), "can_create_payment_method" to canCreatePaymentMethod.toString(), "can_create_customs_form" to canCreateCustomsForm.toString() ) val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, params, SLCreationEligibilityApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun verifyAddress( site: SiteModel, address: ShippingLabelAddress, type: ShippingLabelAddress.Type ): WooPayload<VerifyAddressResponse> { val url = WOOCOMMERCE.connect.normalize_address.pathV1 val params = mapOf( "address" to address.toMap(), "type" to type.name.toLowerCase(Locale.ROOT) ) val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, params, VerifyAddressResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun getPackageTypes( site: SiteModel ): WooPayload<GetPackageTypesResponse> { val url = WOOCOMMERCE.connect.packages.pathV1 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, emptyMap(), GetPackageTypesResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun getAccountSettings( site: SiteModel ): WooPayload<AccountSettingsApiResponse> { val url = WOOCOMMERCE.connect.account.settings.pathV1 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, emptyMap(), AccountSettingsApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun updateAccountSettings(site: SiteModel, request: UpdateSettingsApiRequest): WooPayload<Boolean> { val url = WOOCOMMERCE.connect.account.settings.pathV1 val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, request.toMap(), JsonObject::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data!!["success"].asBoolean) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } @Suppress("LongParameterList") suspend fun getShippingRates( site: SiteModel, orderId: Long, origin: ShippingLabelAddress, destination: ShippingLabelAddress, packages: List<ShippingLabelPackage>, customsData: List<WCShippingPackageCustoms>? ): WooPayload<ShippingRatesApiResponse> { val url = WOOCOMMERCE.connect.label.order(orderId).rates.pathV1 val params = mapOf( "origin" to origin.toMap(), "destination" to destination.toMap(), "packages" to packages.map { labelPackage -> val customs = customsData?.first { it.id == labelPackage.id } labelPackage.toMap() + (customs?.toMap() ?: emptyMap()) } ) val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, params, ShippingRatesApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } @Suppress("LongParameterList") suspend fun purchaseShippingLabels( site: SiteModel, orderId: Long, origin: ShippingLabelAddress, destination: ShippingLabelAddress, packagesData: List<WCShippingLabelPackageData>, customsData: List<WCShippingPackageCustoms>?, emailReceipts: Boolean = false ): WooPayload<ShippingLabelStatusApiResponse> { val url = WOOCOMMERCE.connect.label.order(orderId).pathV1 val params = mapOf( "async" to true, "origin" to origin, "destination" to destination, "packages" to packagesData.map { labelPackage -> val customs = customsData?.first { it.id == labelPackage.id } labelPackage.toMap() + (customs?.toMap() ?: emptyMap()) }, "email_receipt" to emailReceipts ) val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, params, ShippingLabelStatusApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } suspend fun fetchShippingLabelsStatus( site: SiteModel, orderId: Long, labelIds: List<Long> ): WooPayload<ShippingLabelStatusApiResponse> { val url = WOOCOMMERCE.connect.label.order(orderId).shippingLabels(labelIds.joinToString(separator = ",")).pathV1 val response = jetpackTunnelGsonRequestBuilder.syncGetRequest( this, site, url, emptyMap(), ShippingLabelStatusApiResponse::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } // Supports both creating custom package(s), or activating existing predefined package(s). // Creating singular or multiple items, as well as mixed items at once are supported. suspend fun createPackages( site: SiteModel, customPackages: List<CustomPackage> = emptyList(), predefinedOptions: List<PredefinedOption> = emptyList() ): WooPayload<Boolean> { // We need at least one of the lists to not be empty to continue with API call. if (customPackages.isEmpty() && predefinedOptions.isEmpty()) { return WooPayload(false) } val url = WOOCOMMERCE.connect.packages.pathV1 // 1. Mapping for custom packages // Here we convert each CustomPackage instance into a Map with proper key names. // This list of Maps will then be used as the "customs" key's value in the API request. val mappedCustomPackages = customPackages.map { mapOf( "name" to it.title, "is_letter" to it.isLetter, "inner_dimensions" to it.dimensions, "box_weight" to it.boxWeight, /* In wp-admin, The two values below are not user-editable but are saved during package creation with hardcoded values. Here we replicate the same behavior. */ "is_user_defined" to true, "max_weight" to 0 ) } // 2. Mapping for predefined options. val predefinedParam = predefinedOptions // First we group all options by carrier, because the list of predefinedOptions can contain // multiple instances with the same carrier name. // For example, "USPS Priority Mail Express Boxes" and "USPS Priority Mail Boxes" are two separate // options having the same carrier: "usps". .groupBy { it.carrier } // Next, build a predefinedParam Map replicating the required JSON request structure. // Example structure: // // "carrier_1": [ "package_1", "package_2", ... ], // "carrier_2": [ "package_3", "package_4", "package_5" ... ], .map { (carrier, options) -> carrier to options .flatMap { it.predefinedPackages } // Put all found package(s) in a list .map { it.id } // Grab all found package id(s) }.asMap() // Convert list of Map to Map val params = mapOf( "custom" to mappedCustomPackages, "predefined" to predefinedParam ) val response = jetpackTunnelGsonRequestBuilder.syncPostRequest( this, site, url, params, JsonObject::class.java ) return when (response) { is JetpackSuccess -> { WooPayload(response.data!!["success"].asBoolean) } is JetpackError -> { WooPayload(response.error.toWooError()) } } } data class PrintShippingLabelApiResponse( val mimeType: String, val b64Content: String, val success: Boolean ) data class ShippingRatesApiResponse( @SerializedName("success") val isSuccess: Boolean, @SerializedName("rates") private val boxesJson: JsonElement ) { companion object { private val gson by lazy { Gson() } } val boxes: Map<String, Map<String, ShippingOption>> get() { val responseType = object : TypeToken<Map<String, Map<String, ShippingOption>>>() {}.type return gson.fromJson(boxesJson, responseType) as? Map<String, Map<String, ShippingOption>> ?: emptyMap() } data class ShippingOption( val rates: List<Rate> ) { data class Rate( val title: String, val insurance: String?, val rate: BigDecimal, @SerializedName("rate_id") val rateId: String, @SerializedName("service_id") val serviceId: String, @SerializedName("carrier_id") val carrierId: String, @SerializedName("shipment_id") val shipmentId: String, @SerializedName("tracking") val hasTracking: Boolean, @SerializedName("retail_rate") val retailRate: BigDecimal, @SerializedName("is_selected") val isSelected: Boolean, @SerializedName("free_pickup") val isPickupFree: Boolean, @SerializedName("delivery_days") val deliveryDays: Int, @SerializedName("delivery_date_guaranteed") val deliveryDateGuaranteed: Boolean, @SerializedName("delivery_date") val deliveryDate: Date? ) } } data class VerifyAddressResponse( @SerializedName("success") val isSuccess: Boolean, @SerializedName("is_trivial_normalization") val isTrivialNormalization: Boolean, @SerializedName("normalized") val suggestedAddress: ShippingLabelAddress?, @SerializedName("field_errors") val error: Error? ) { data class Error( @SerializedName("general") val message: String?, @SerializedName("address") val address: String? ) } data class GetPackageTypesResponse( @SerializedName("success") val isSuccess: Boolean, val storeOptions: StoreOptions, val formSchema: FormSchema, val formData: FormData ) { companion object { private val gson by lazy { Gson() } } data class StoreOptions( @SerializedName("currency_symbol") val currency: String, @SerializedName("dimension_unit") val dimensionUnit: String, @SerializedName("weight_unit") val weightUnit: String, @SerializedName("origin_country") val originCountry: String ) data class FormData( @SerializedName("custom") val customData: List<CustomData>, @SerializedName("predefined") val predefinedJson: JsonElement ) { data class CustomData( val name: String, @SerializedName("inner_dimensions") val innerDimensions: String?, @SerializedName("outer_dimensions") val outerDimensions: String?, @SerializedName("box_weight") val boxWeight: Float?, @SerializedName("max_weight") val maxWeight: Float?, @SerializedName("is_user_defined") val isUserDefined: Boolean?, @SerializedName("is_letter") val isLetter: Boolean ) val predefinedData: Map<String, List<String?>> get() { val responseType = object : TypeToken<Map<String, List<String?>>>() {}.type return gson.fromJson(predefinedJson, responseType) as? Map<String, List<String?>> ?: emptyMap() } } data class FormSchema( @SerializedName("custom") val customSchema: CustomSchema?, @SerializedName("predefined") val predefinedJson: JsonElement? ) { data class CustomSchema( val title: String, val description: String ) data class PackageOption( val title: String, val definitions: List<PackageDefinition> ) { data class PackageDefinition( val id: String, val name: String, val dimensions: Any?, @SerializedName("outer_dimensions") val outerDimensions: String, @SerializedName("inner_dimensions") val innerDimensions: String, @SerializedName("box_weight") val boxWeight: Float?, @SerializedName("max_weight") val maxWeight: Float?, @SerializedName("is_letter") val isLetter: Boolean, @SerializedName("is_flat_rate") val isFlatRate: Boolean?, @SerializedName("can_ship_international") val canShipInternational: Boolean?, @SerializedName("group_id") val groupId: String?, @SerializedName("service_group_ids") val serviceGroupIds: List<String>? ) } val predefinedSchema: Map<String, Map<String, PackageOption>> get() { val responseType = object : TypeToken<Map<String, Map<String, PackageOption>>>() {}.type return gson.fromJson(predefinedJson, responseType) as? Map<String, Map<String, PackageOption>> ?: emptyMap() } } } }
gpl-2.0
2262304fe8e3b0727eaf71cad578020f
37.29562
130
0.584437
5.308879
false
false
false
false
ratabb/Hishoot2i
app/src/main/java/org/illegaller/ratabb/hishoot2i/ui/constants.kt
1
870
@file:Suppress("SpellCheckingInspection") package org.illegaller.ratabb.hishoot2i.ui const val ARG_BACKGROUND_PATH = "arg_background_path" const val ARG_COLOR = "arg_color" const val ARG_CROP_PATH = "arg_crop_path" const val ARG_PIPETTE_COLOR = "arg_pipette_color" const val ARG_SCREEN1_PATH = "arg_screen1_path" const val ARG_SCREEN2_PATH = "arg_screen2_path" const val ARG_SORT = "arg_sort" const val ARG_THEME = "arg_theme" const val KEY_REQ_BACKGROUND = "key_background_request" const val KEY_REQ_CROP = "key_crop_request" const val KEY_REQ_MIX_COLOR = "key_mix_color_request" const val KEY_REQ_PIPETTE = "key_pipette_request" const val KEY_REQ_SCREEN_1 = "key_screen1_request" const val KEY_REQ_SCREEN_2 = "key_screen2_request" const val KEY_REQ_SORT = "key_sort_request" const val KEY_REQ_THEME = "key_theme_request" const val KEY_REQ_SAVE = "key_save_request"
apache-2.0
a3a157ce29e3273a1d09f8a5c3d211a7
38.545455
55
0.749425
2.880795
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/catalog/DefaultCatalogType.kt
1
2044
/* * 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.catalog import org.lanternpowered.api.key.NamespacedKey import org.lanternpowered.api.key.lanternKey import org.lanternpowered.api.key.minecraftKey import org.lanternpowered.api.key.spongeKey import org.spongepowered.api.NamedCatalogType open class DefaultCatalogType(key: NamespacedKey) : AbstractCatalogType() { private val key: NamespacedKey init { check(key.namespace.isNotEmpty()) { "plugin id (key namespace) cannot be empty" } check(key.value.isNotEmpty()) { "id (key value) cannot be empty" } this.key = key } override fun getKey() = this.key companion object { fun minecraft(id: String) = DefaultCatalogType(minecraftKey(id)) fun minecraft(id: String, name: String) = Named(minecraftKey(id), name) fun minecraft(id: String, name: () -> String) = Named(minecraftKey(id), name) fun sponge(id: String) = DefaultCatalogType(spongeKey(id)) fun sponge(id: String, name: String): DefaultCatalogType = Named(spongeKey(id), name) fun sponge(id: String, name: () -> String): DefaultCatalogType = Named(spongeKey(id), name) fun lantern(id: String) = DefaultCatalogType(lanternKey(id)) fun lantern(id: String, name: String): DefaultCatalogType = Named(lanternKey(id), name) fun lantern(id: String, name: () -> String): DefaultCatalogType = Named(lanternKey(id), name) } open class Named(key: NamespacedKey, name: () -> String) : DefaultCatalogType(key), NamedCatalogType { constructor(key: NamespacedKey, name: String): this(key, { name }) private val theName: String by lazy(name) override fun getName() = this.theName } }
mit
a49206d21962728ac813bb9827788b0b
36.851852
106
0.691781
4.063618
false
false
false
false
WindSekirun/RichUtilsKt
RichUtils/src/main/java/pyxis/uzuki/live/richutilskt/utils/RFont.kt
1
1306
@file:JvmName("RichUtils") @file:JvmMultifileClass package pyxis.uzuki.live.richutilskt.utils import android.app.Application import android.content.Context import android.view.View import android.view.ViewGroup /** * Set system font into ViewGroup * * before use this methods, you should initialize SystemFontEngine, using [Application.initializeFontEngine()] method * * @param[layoutRes] layout file * @param[parent] ViewGroup object * @param[isAttachedRoot] isAttachedRoot */ @JvmOverloads fun Context.setTypeface(layoutRes: Int, parent: ViewGroup? = null, isAttachedRoot: Boolean = false): View? = RSystemFontEngine.instance?.setTypeface(this, layoutRes, parent, isAttachedRoot) /** * Set system font into ViewGroup * * before use this methods, you should initialize SystemFontEngine, using [Application.initializeFontEngine()] method * * @param[view] ViewGroup object * @param[parent] ViewGroup object * @param[isAttachedRoot] isAttachedRoot */ @JvmOverloads fun Context.setTypeface(view: ViewGroup, parent: ViewGroup? = null, isAttachedRoot: Boolean = false): View? = RSystemFontEngine.instance?.setTypeface(this, view, parent, isAttachedRoot) /** * Initialize SystemFontEngine */ fun Application.initializeFontEngine() { RSystemFontEngine.initialize(this) }
apache-2.0
50bf5c0651f2723a7d2b1efe286ee5cd
31.675
123
0.76876
4.146032
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkXml.kt
1
3267
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sarangnamu.common import org.slf4j.LoggerFactory import org.w3c.dom.Document import org.xml.sax.InputSource import java.io.File import java.io.FileNotFoundException import java.io.InputStream import java.io.StringReader import javax.xml.parsers.DocumentBuilderFactory import javax.xml.xpath.XPathConstants import javax.xml.xpath.XPathFactory /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 10. 16.. <p/> * * class TestParser : XPathBase() { override fun parsing() { val count = int("count(//xsync)") val number = string("//rgist/text()") if (TextUtils.isEmpty(number)) { val msg = string("//message/text()") val err = string("//error_code/text()") } else { var i=0 while (i++ <count) { // TODO } } } } */ abstract class XPathBase { companion object { private val log = LoggerFactory.getLogger(XPathBase::class.java) } val xpath = XPathFactory.newInstance().newXPath() val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() lateinit var document: Document /** * xml 파일 핸을 연다 */ @Throws(Exception::class) fun loadXml(fp: File) { if (!fp.exists()) { throw FileNotFoundException(fp.absolutePath) } document = builder.parse(fp) parsing() } /** * xml input stream 을 연다 */ @Throws(Exception::class) fun loadXml(ism: InputStream) { document = builder.parse(ism) parsing() } /** * xml string 로드 한다 */ @Throws(Exception::class) fun loadXml(xml: String) { document = builder.parse(InputSource(StringReader(xml))) parsing() } /** string 으로 반환 */ fun string(expr: String) = xpath.evaluate(expr, document, XPathConstants.STRING).toString().trim() /** int 로 반환 */ fun int(expr: String) = string(expr).toInt() /** float 으로 반환 */ fun float(expr: String) = string(expr).toFloat() /** double 로 반환 */ fun double(expr: String) = string(expr).toDouble() /** bool 로 반환 */ fun bool(expr: String) = string(expr).toBoolean() //////////////////////////////////////////////////////////////////////////////////// // // ABSTRACT // //////////////////////////////////////////////////////////////////////////////////// @Throws(Exception::class) abstract fun parsing() }
apache-2.0
9504f82d9ac9488fb24fae5bc0b16cc7
28.154545
102
0.579046
4.186684
false
false
false
false
harningt/atomun-keygen
src/main/java/us/eharning/atomun/keygen/internal/spi/bip0032/BIP0044KeyGeneratorBuilderSpi.kt
1
4607
/* * Copyright 2015, 2017 Thomas Harning Jr. <[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 us.eharning.atomun.keygen.internal.spi.bip0032 import us.eharning.atomun.core.ValidationException import us.eharning.atomun.keygen.* import us.eharning.atomun.keygen.path.BIP0032Path import us.eharning.atomun.keygen.path.BIP0044Path import us.eharning.atomun.keygen.spi.BuilderParameter import us.eharning.atomun.keygen.spi.KeyGeneratorBuilderSpi /** * Service provider for the BIP0044 key generator specification. * * @since 0.0.1 */ internal class BIP0044KeyGeneratorBuilderSpi : KeyGeneratorBuilderSpi(StandardKeyGeneratorAlgorithm.BIP0044) { /** * Construct a key generator. * * @param parameters * builder parameters to drive the process. * * @return DeterministicKeyGenerator instance wrapping build results. * * @since 0.0.1 */ @Throws(ValidationException::class) override fun createGenerator(vararg parameters: BuilderParameter?): DeterministicKeyGenerator { var node: BIP0032Node? = null var path: BIP0044Path? = null for (parameter in parameters) { if (null == parameter) { continue } /* Check counts */ when (parameter) { is SeedParameter -> { require(null == node, { "Only one SeedParameter allowed per builder" }) } is BIP0032Path -> { require(null == path, { "Only one BIP0032Path allowed per builder" }) } else -> throw IllegalArgumentException("Unsupported parameter type: " + parameter) } when (parameter) { is SerializedSeedParameter -> node = BIP0032Generator.strategy.importNode(parameter.serializedSeed) is ByteArraySeedParameter -> node = BIP0032Generator.strategy.generateNodeFromSeed(parameter.getSeed()) is BIP0032Path -> { path = BIP0044Path.fromPath(parameter) require(path.hasChain(), { "Missing final required path element: Chain" }) } else -> throw IllegalArgumentException("Unsupported parameter type: " + parameter) } } if (null == node) { node = BIP0032Generator.strategy.generateNode() } if (null == path) { throw IllegalArgumentException("Missing path") } node = BIP0032Generator.strategy.deriveNode(node, path) return BIP0032Generator(node) } /** * Validate the builder parameters. * * @param parameters * builder parameters to validate. * * @throws RuntimeException * varieties in case of invalid input. * * @since 0.0.1 */ override fun validate(vararg parameters: BuilderParameter?) { var foundSeed = false var foundPath = false for (parameter in parameters) { if (null == parameter) { continue } /* Check counts */ when (parameter) { is SeedParameter -> { require(!foundSeed, { "Only one SeedParameter allowed per builder" }) foundSeed = true } is BIP0032Path -> { require(!foundPath, { "Only one BIP0032Path allowed per builder" }) foundPath = true } else -> throw IllegalArgumentException("Unsupported parameter type: " + parameter) } /* Check types */ when (parameter) { is BIP0032Path -> { BIP0044Path.checkValidPath(parameter) } is ByteArraySeedParameter, is SerializedSeedParameter -> {} else -> throw IllegalArgumentException("Unsupported parameter type: " + parameter) } } } }
apache-2.0
3c5d1808ff3bc42dcad9ec19729f3e26
35.275591
110
0.588669
4.96444
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/BkAnimation.kt
1
2962
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * 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("NOTHING_TO_INLINE", "unused") package net.sarangnamu.common import android.animation.Animator import android.animation.ArgbEvaluator import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.annotation.TargetApi import android.os.Build import android.support.annotation.ColorRes import android.view.View import android.view.Window import android.view.WindowManager /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2017. 11. 22.. <p/> */ inline fun Animator.addEndListener(crossinline f: (Animator?) -> Unit) { addListener(object : Animator.AnimatorListener { override fun onAnimationStart(p0: Animator?) {} override fun onAnimationCancel(p0: Animator?) {} override fun onAnimationRepeat(p0: Animator?) {} override fun onAnimationEnd(animation: Animator?) = f(animation) }) } inline fun View.fadeColor(fcolor: Int, scolor: Int, noinline f: ((Animator?) -> Unit)? = null, duration: Long = 500) { ObjectAnimator.ofObject(this, "backgroundColor", ArgbEvaluator(), fcolor, scolor).apply { this.duration = duration f?.let { this.addEndListener(it) } }.start() } inline fun View.fadeColorRes(@ColorRes fcolor: Int, @ColorRes scolor: Int, noinline f: ((Animator?) -> Unit)? = null, duration: Long = 500) { fadeColor(context.color(fcolor), context.color(scolor), f, duration) } inline fun Window.fadeStatusBar(fcolor:Int, scolor: Int, noinline f: ((Animator?) -> Unit)? = null, duration: Long = 500) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) val from = context.color(fcolor) val to = context.color(scolor) ValueAnimator.ofArgb(from, to).apply { this.duration = duration this.addUpdateListener { statusBarColor = it.animatedValue as Int } f?.let { this.addEndListener(it) } }.start() } } inline fun Window.fadeStatusBarRes(@ColorRes fcolor: Int, @ColorRes scolor: Int, noinline f: ((Animator?) -> Unit)? = null, duration: Long = 500) { fadeStatusBar(context.color(fcolor), context.color(scolor), f, duration) }
apache-2.0
906f1fd74d6f4e6a86f52c5bf16dc914
39.040541
147
0.707968
3.949333
false
false
false
false
cfig/Android_boot_image_editor
bbootimg/src/main/kotlin/utils/Dtbo.kt
1
8318
package utils import avb.AVBInfo import cc.cfig.io.Struct import cfig.Avb import cfig.bootimg.Common import cfig.bootimg.Signer import cfig.bootimg.v3.VendorBoot import cfig.helper.Helper import cfig.helper.Dumpling import cfig.packable.VBMetaParser import cfig.utils.DTC import com.fasterxml.jackson.databind.ObjectMapper import de.vandermeer.asciitable.AsciiTable import org.slf4j.LoggerFactory import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.InputStream class Dtbo( var info: DtboInfo = DtboInfo(), var header: DtboHeader = DtboHeader(), var dtEntries: MutableList<DeviceTreeTableEntry> = mutableListOf() ) { class DtboInfo( var output: String = "", var json: String = "", var imageSize: Int = 0 ) // part I: header data class DtboHeader( var totalSize: Int = 0, var headerSize: Int = 0, var entrySize: Int = 0, var entryCount: Int = 0, var entryOffset: Int = 0, var pageSize: Int = 0, var version: Int = 0 ) { companion object { const val magic = 0xd7b7ab1e private const val FORMAT_STRING = ">I7i" internal const val SIZE = 32 init { check(Struct(FORMAT_STRING).calcSize() == SIZE) } } constructor(iS: InputStream?) : this() { if (iS == null) { return } val info = Struct(FORMAT_STRING).unpack(iS) check(8 == info.size) if ((info[0] as UInt).toLong() != magic) { throw IllegalArgumentException("stream doesn't look like DTBO header") } totalSize = info[1] as Int headerSize = info[2] as Int if (headerSize != DtboHeader.SIZE) { log.warn("headerSize $headerSize != ${DtboHeader.SIZE}") } entrySize = info[3] as Int if (entrySize != DeviceTreeTableEntry.SIZE) { log.warn("entrySize $entrySize != ${DeviceTreeTableEntry.SIZE}") } entryCount = info[4] as Int entryOffset = info[5] as Int pageSize = info[6] as Int version = info[7] as Int } fun encode(): ByteArray { return Struct(FORMAT_STRING).pack( magic, totalSize, headerSize, entrySize, entryCount, entryOffset, pageSize, version ) } } // part II: dt entry table data class DeviceTreeTableEntry( var sequenceNo: Int = 0, var entrySize: Int = 0, var entryOffset: Int = 0, var id: Int = 0, var rev: Int = 0, var flags: Int = 0, var reserved1: Int = 0, var reserved2: Int = 0, var reserved3: Int = 0, ) { companion object { private const val FORMAT_STRING = ">8i" internal const val SIZE = 32 init { check(Struct(FORMAT_STRING).calcSize() == SIZE) } } constructor(iS: InputStream) : this() { val info = Struct(FORMAT_STRING).unpack(iS) check(8 == info.size) entrySize = info[0] as Int entryOffset = info[1] as Int id = info[2] as Int rev = info[3] as Int flags = info[4] as Int reserved1 = info[5] as Int reserved2 = info[6] as Int reserved3 = info[7] as Int } fun encode(): ByteArray { return Struct(FORMAT_STRING).pack( entrySize, entryOffset, id, rev, flags, reserved1, reserved2, reserved3 ) } } companion object { fun parse(fileName: String): Dtbo { val ret = Dtbo() ret.info.output = fileName ret.info.imageSize = File(fileName).length().toInt() ret.info.json = fileName.removeSuffix(".img") + ".json" FileInputStream(fileName).use { fis -> ret.header = DtboHeader(fis) for (i in 0 until ret.header.entryCount) { ret.dtEntries.add(DeviceTreeTableEntry(fis).apply { sequenceNo = i }) } } return ret } private val log = LoggerFactory.getLogger(Dtbo::class.java) private val outDir = Helper.prop("workDir") } fun extractVBMeta(): Dtbo { try { AVBInfo.parseFrom(Dumpling(info.output)).dumpDefault(info.output) } catch (e: Exception) { log.error("extraceVBMeta(): $e") } if (File("vbmeta.img").exists()) { log.warn("Found vbmeta.img, parsing ...") VBMetaParser().unpack("vbmeta.img") } return this } fun unpack(outDir: String): Dtbo { File("${outDir}dt").mkdir() ObjectMapper().writerWithDefaultPrettyPrinter().writeValue(File("${outDir}dtbo.json"), this) dtEntries.forEach { Common.dumpDtb(Helper.Slice(info.output, it.entryOffset, it.entrySize, "${outDir}dt/dt.${it.sequenceNo}")) } return this } fun pack(): Dtbo { FileOutputStream(info.output + ".clear").use { fos -> // Part I this.header.entryCount = this.dtEntries.size this.header.totalSize = (DtboHeader.SIZE + (header.entryCount * DeviceTreeTableEntry.SIZE) + this.dtEntries.sumOf { File("${outDir}dt/dt.${it.sequenceNo}").length() }) .toInt() // Part II - a for (index in 0 until dtEntries.size) { DTC().compile("${outDir}dt/dt.${index}.src", "${outDir}dt/dt.${index}") } // Part II - b var offset = DtboHeader.SIZE + (header.entryCount * DeviceTreeTableEntry.SIZE) this.dtEntries.forEachIndexed { index, deviceTreeTableEntry -> deviceTreeTableEntry.entrySize = File("${outDir}dt/dt.${index}").length().toInt() deviceTreeTableEntry.entryOffset = offset offset += deviceTreeTableEntry.entrySize } // + Part I fos.write(header.encode()) // + Part II this.dtEntries.forEach { fos.write(it.encode()) } // + Part III for (index in 0 until dtEntries.size) { fos.write(File("${outDir}dt/dt.${index}").readBytes()) } } return this } fun printSummary(): Dtbo { val tableHeader = AsciiTable().apply { addRule() addRow("What", "Where") addRule() } val tab = AsciiTable().let { it.addRule() it.addRow("image info", outDir + info.output.removeSuffix(".img") + ".json") it.addRule() it.addRow("device-tree blob (${this.header.entryCount} blobs)", "${outDir}dt/dt.*") it.addRow("\\-- device-tree source ", "${outDir}dt/dt.*.src") it.addRule() it.addRow("AVB info", Avb.getJsonFileName(info.output)) it.addRule() it } val tabVBMeta = AsciiTable().let { if (File("vbmeta.img").exists()) { it.addRule() it.addRow("vbmeta.img", Avb.getJsonFileName("vbmeta.img")) it.addRule() "\n" + it.render() } else { "" } } log.info("\n\t\t\tUnpack Summary of ${info.output}\n{}\n{}{}", tableHeader.render(), tab.render(), tabVBMeta) return this } fun sign(): Dtbo { val avbtool = String.format(Helper.prop("avbtool"), "v1.2") Signer.signAVB(info.output, info.imageSize.toLong(), avbtool) return this } fun updateVbmeta(): Dtbo { Avb.updateVbmeta(info.output) return this } fun printPackSummary(): Dtbo { VendorBoot.printPackSummary(info.output) return this } }
apache-2.0
cba723b4795ba2597daf895009a4f2c8
31.11583
118
0.517913
4.263455
false
false
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/sync/GivenSynchronizingLibraries/WhenSynchronizationIsDisposing.kt
1
5667
package com.lasthopesoftware.bluewater.client.stored.sync.GivenSynchronizingLibraries import android.content.IntentFilter import androidx.test.core.app.ApplicationProvider import com.lasthopesoftware.AndroidContext import com.lasthopesoftware.bluewater.client.browsing.library.access.ILibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.stored.library.items.files.PruneStoredFiles import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobState import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobStatus import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile import com.lasthopesoftware.bluewater.client.stored.library.sync.CheckForSync import com.lasthopesoftware.bluewater.client.stored.library.sync.ControlLibrarySyncs import com.lasthopesoftware.bluewater.client.stored.sync.StoredFileSynchronization import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import com.lasthopesoftware.resources.FakeMessageBus import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import io.reactivex.Observable import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.util.* class WhenSynchronizationIsDisposing : AndroidContext() { companion object { private val random = Random() private val storedFiles = arrayOf( StoredFile().setId(random.nextInt()).setServiceId(1).setLibraryId(4), StoredFile().setId(random.nextInt()).setServiceId(2).setLibraryId(4), StoredFile().setId(random.nextInt()).setServiceId(4).setLibraryId(4), StoredFile().setId(random.nextInt()).setServiceId(5).setLibraryId(4), StoredFile().setId(random.nextInt()).setServiceId(114).setLibraryId(4), StoredFile().setId(random.nextInt()).setServiceId(92).setLibraryId(4), StoredFile().setId(random.nextInt()).setServiceId(random.nextInt()).setLibraryId(10), StoredFile().setId(random.nextInt()).setServiceId(random.nextInt()).setLibraryId(10), StoredFile().setId(random.nextInt()).setServiceId(random.nextInt()).setLibraryId(10), StoredFile().setId(random.nextInt()).setServiceId(random.nextInt()).setLibraryId(10), StoredFile().setId(random.nextInt()).setServiceId(random.nextInt()).setLibraryId(10), StoredFile().setId(random.nextInt()).setServiceId(random.nextInt()).setLibraryId(10) ) private val fakeMessageSender = FakeMessageBus(ApplicationProvider.getApplicationContext()) private val filePruner by lazy { mockk<PruneStoredFiles>() .apply { every { pruneDanglingFiles() } returns Unit.toPromise() } } } override fun before() { val libraryProvider = mockk<ILibraryProvider>() every { libraryProvider.allLibraries } returns Promise( listOf( Library().setId(4), Library().setId(10) ) ) val librarySyncHandler = mockk<ControlLibrarySyncs>() every { librarySyncHandler.observeLibrarySync(any()) } answers { Observable .fromArray(*storedFiles) .filter { f -> f.libraryId == firstArg<LibraryId>().id } .flatMap { f -> Observable.concat( Observable.just( StoredFileJobStatus(mockk(), f, StoredFileJobState.Queued), StoredFileJobStatus(mockk(), f, StoredFileJobState.Downloading), StoredFileJobStatus(mockk(), f, StoredFileJobState.Downloaded) ), Observable.never() ) } } val checkSync = mockk<CheckForSync>() with (checkSync) { every { promiseIsSyncNeeded() } returns Promise(true) } val synchronization = StoredFileSynchronization( libraryProvider, fakeMessageSender, filePruner, checkSync, librarySyncHandler ) val intentFilter = IntentFilter(StoredFileSynchronization.onFileDownloadedEvent) intentFilter.addAction(StoredFileSynchronization.onFileDownloadingEvent) intentFilter.addAction(StoredFileSynchronization.onSyncStartEvent) intentFilter.addAction(StoredFileSynchronization.onSyncStopEvent) intentFilter.addAction(StoredFileSynchronization.onFileQueuedEvent) synchronization.streamFileSynchronization().subscribe().dispose() } @Test fun thenASyncStartedEventOccurs() { assertThat( fakeMessageSender.recordedIntents .single { i -> StoredFileSynchronization.onSyncStartEvent == i.action }).isNotNull } @Test fun thenTheStoredFilesAreBroadcastAsQueued() { assertThat( fakeMessageSender.recordedIntents .filter { i -> StoredFileSynchronization.onFileQueuedEvent == i.action } .map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) }) .containsExactlyElementsOf(storedFiles.map { obj -> obj.id }) } @Test fun thenTheStoredFilesAreBroadcastAsDownloading() { assertThat( fakeMessageSender.recordedIntents .filter { i -> StoredFileSynchronization.onFileDownloadingEvent == i.action } .map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) }) .containsExactlyElementsOf(storedFiles.map { obj -> obj.id }) } @Test fun thenTheStoredFilesAreBroadcastAsDownloaded() { assertThat( fakeMessageSender.recordedIntents .filter { i -> StoredFileSynchronization.onFileDownloadedEvent == i.action } .map { i -> i.getIntExtra(StoredFileSynchronization.storedFileEventKey, -1) }) .containsExactlyElementsOf(storedFiles.map { obj -> obj.id }) } @Test fun thenASyncStoppedEventOccurs() { assertThat( fakeMessageSender.recordedIntents .single { i -> StoredFileSynchronization.onSyncStopEvent == i.action }).isNotNull } }
lgpl-3.0
431e35cdd4814d81c4a0d55dc4df7e0e
39.478571
95
0.779601
4.365948
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/utils/SharedPrefsHelper.kt
1
3059
package com.quickblox.sample.videochat.kotlin.utils import android.content.Context import android.content.SharedPreferences import android.text.TextUtils import com.quickblox.core.helper.StringifyArrayList import com.quickblox.sample.videochat.kotlin.App import com.quickblox.users.model.QBUser private const val SHARED_PREFS_NAME = "qb" private const val QB_USER_ID = "qb_user_id" private const val QB_USER_LOGIN = "qb_user_login" private const val QB_USER_PASSWORD = "qb_user_password" private const val QB_USER_FULL_NAME = "qb_user_full_name" private const val QB_USER_TAGS = "qb_user_tags" object SharedPrefsHelper { private var sharedPreferences: SharedPreferences = App.getInstance().getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE) fun delete(key: String) { if (sharedPreferences.contains(key)) { sharedPreferences.edit().remove(key).apply() } } fun save(key: String, value: Any?) { val editor = sharedPreferences.edit() when { value is Boolean -> editor.putBoolean(key, (value)) value is Int -> editor.putInt(key, (value)) value is Float -> editor.putFloat(key, (value)) value is Long -> editor.putLong(key, (value)) value is String -> editor.putString(key, value) value is Enum<*> -> editor.putString(key, value.toString()) value != null -> throw RuntimeException("Attempting to save non-supported preference") } editor.apply() } fun saveCurrentUser(user: QBUser) { save(QB_USER_ID, user.id) save(QB_USER_LOGIN, user.login) save(QB_USER_PASSWORD, user.password) save(QB_USER_FULL_NAME, user.fullName) save(QB_USER_TAGS, user.tags.itemsAsString) } fun clearAllData() { sharedPreferences.edit().clear().apply() } fun hasCurrentUser(): Boolean { return has(QB_USER_LOGIN) && has(QB_USER_PASSWORD) } @Suppress("UNCHECKED_CAST") operator fun <T> get(key: String): T { return sharedPreferences.all[key] as T } @Suppress("UNCHECKED_CAST") operator fun <T> get(key: String, defValue: T): T { val returnValue = sharedPreferences.all[key] as T return returnValue ?: defValue } private fun has(key: String): Boolean { return sharedPreferences.contains(key) } fun getCurrentUser(): QBUser { val id = get<Int>(QB_USER_ID) val login = get<String>(QB_USER_LOGIN) val password = get<String>(QB_USER_PASSWORD) val fullName = get<String>(QB_USER_FULL_NAME) val tagsInString = get<String>(QB_USER_TAGS) val tags: StringifyArrayList<String> = StringifyArrayList() if (!TextUtils.isEmpty(tagsInString)) { tags.add(*tagsInString.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) } val user = QBUser(login, password) user.id = id user.fullName = fullName user.tags = tags return user } }
bsd-3-clause
11703e584acb529bc9cbc97adc0e08b7
32.626374
102
0.643674
4.009174
false
false
false
false
clangen/musikcube
src/musikdroid/app/src/main/java/io/casey/musikcube/remote/ui/settings/activity/ConnectionsActivity.kt
1
9559
package io.casey.musikcube.remote.ui.settings.activity import android.app.Activity import android.app.Dialog import android.content.Context import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.uacf.taskrunner.Task import com.uacf.taskrunner.Tasks import io.casey.musikcube.remote.R import io.casey.musikcube.remote.ui.settings.model.Connection import io.casey.musikcube.remote.ui.settings.model.ConnectionsDb import io.casey.musikcube.remote.ui.shared.activity.BaseActivity import io.casey.musikcube.remote.ui.shared.extension.* import javax.inject.Inject private const val EXTRA_CONNECTION = "extra_connection" class ConnectionsActivity : BaseActivity() { @Inject lateinit var connectionsDb: ConnectionsDb private lateinit var recycler: RecyclerView private lateinit var emptyText: View private lateinit var adapter: Adapter override fun onCreate(savedInstanceState: Bundle?) { component.inject(this) super.onCreate(savedInstanceState) setResult(Activity.RESULT_CANCELED) setContentView(R.layout.connections_activity) enableUpNavigation() recycler = findViewById(R.id.recycler_view) emptyText = findViewById(R.id.empty_text) adapter = Adapter(itemClickListener, itemLongClickListener) val layoutManager = LinearLayoutManager(this) recycler.layoutManager = layoutManager recycler.addItemDecoration(DividerItemDecoration(this, layoutManager.orientation)) recycler.adapter = adapter } override fun onResume() { super.onResume() runner.run(LoadTask.NAME, LoadTask(connectionsDb)) } @Suppress("UNCHECKED_CAST") override fun onTaskCompleted(taskName: String, taskId: Long, task: Task<*, *>, result: Any) { when (taskName) { LoadTask.NAME, DeleteTask.NAME, RenameTask.NAME -> { adapter.items = (result as List<Connection>) adapter.notifyDataSetChanged() updateViewState() } } } private fun updateViewState() { val count = adapter.itemCount recycler.visibility = if (count == 0) View.GONE else View.VISIBLE emptyText.visibility = if (count == 0) View.VISIBLE else View.GONE } fun rename(connection: Connection, name: String) { runner.run(RenameTask.NAME, RenameTask(connectionsDb, connection, name)) } fun delete(connection: Connection) { runner.run(DeleteTask.NAME, DeleteTask(connectionsDb, connection)) } private val itemClickListener: (View) -> Unit = { view: View -> val connection = view.tag as Connection if (view.id == R.id.button_del) { if (!dialogVisible(ConfirmDeleteDialog.TAG)) { showDialog(ConfirmDeleteDialog.newInstance(connection), ConfirmDeleteDialog.TAG) } } else { val intent = Intent().putExtra(EXTRA_SELECTED_CONNECTION, connection) setResult(RESULT_OK, intent) finish() } } private val itemLongClickListener: (View) -> Boolean = { view: View -> if (!dialogVisible(RenameDialog.TAG)) { showDialog(RenameDialog.newInstance(view.tag as Connection), RenameDialog.TAG) } true } companion object { const val EXTRA_SELECTED_CONNECTION = "extra_selected_connection" fun getStartIntent(context: Context): Intent { return Intent(context, ConnectionsActivity::class.java) } } } private class ViewHolder(itemView: View, clickListener: (View) -> Unit, longClickListener: (View) -> Boolean) : RecyclerView.ViewHolder(itemView) { var name: TextView = itemView.findViewById(R.id.name) var address: TextView = itemView.findViewById(R.id.hostname) var delete: TextView = itemView.findViewById(R.id.button_del) init { itemView.setOnClickListener(clickListener) itemView.setOnLongClickListener(longClickListener) delete.setOnClickListener(clickListener) } fun rebind(connection: Connection) { itemView.tag = connection delete.tag = connection name.text = connection.name address.text = connection.hostname } } private class Adapter(val clickListener: (View) -> Unit, val longClickListener: (View) -> Boolean) : RecyclerView.Adapter<ViewHolder>() { var items = listOf<Connection>() override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.rebind(items[position]) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.connection_row, parent, false) return ViewHolder(view, clickListener, longClickListener) } override fun getItemCount(): Int { return items.size } } private class LoadTask(val db: ConnectionsDb) : Tasks.Blocking<List<Connection>, Exception>() { override fun exec(context: Context?): List<Connection> { return db.connectionsDao().query() } companion object { const val NAME = "LoadTask" } } private class DeleteTask(val db: ConnectionsDb, val connection: Connection) : Tasks.Blocking<List<Connection>, Exception>() { override fun exec(context: Context?): List<Connection> { val dao = db.connectionsDao() dao.delete(connection.name) return dao.query() } companion object { const val NAME = "DeleteTask" } } private class RenameTask(val db: ConnectionsDb, val connection: Connection, val name:String) : Tasks.Blocking<List<Connection>, Exception>() { override fun exec(context: Context?): List<Connection> { val dao = db.connectionsDao() dao.rename(connection.name, name) return dao.query() } companion object { const val NAME = "RenameTask" } } class ConfirmDeleteDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val connection = requireArguments().getParcelableCompat<Connection>(EXTRA_CONNECTION) return when (connection == null) { true -> throw IllegalArgumentException("invalid connection") else -> { AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_confirm_delete_title) .setMessage(getString(R.string.settings_confirm_delete_message, connection.name)) .setNegativeButton(R.string.button_no, null) .setPositiveButton(R.string.button_yes) { _, _ -> (activity as ConnectionsActivity).delete(connection) } .create().apply { setCancelable(false) } } } } companion object { const val TAG = "confirm_delete_dialog" fun newInstance(connection: Connection): ConfirmDeleteDialog { val result = ConfirmDeleteDialog() result.arguments = Bundle().apply { putParcelable(EXTRA_CONNECTION, connection) } return result } } } class RenameDialog : DialogFragment() { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val connection = requireArguments().getParcelableCompat<Connection>(EXTRA_CONNECTION) return when (connection == null) { true -> throw IllegalArgumentException("invalid connection") else -> { val inflater = LayoutInflater.from(context) val view = inflater.inflate(R.layout.dialog_edit, null) val edit = view.findViewById<EditText>(R.id.edit) edit.requestFocus() edit.setText(connection.name) edit.selectAll() AlertDialog.Builder(requireActivity()) .setTitle(R.string.settings_save_as_title) .setNegativeButton(R.string.button_cancel) { _, _ -> hideKeyboard() } .setOnCancelListener { hideKeyboard() } .setPositiveButton(R.string.button_save) { _, _ -> val name = edit.text.toString() (activity as ConnectionsActivity).rename(connection, name) } .create().apply { setView(view) setCancelable(false) } } } } override fun onResume() { super.onResume() showKeyboard() } override fun onPause() { super.onPause() hideKeyboard() } companion object { const val TAG = "rename_dialog" fun newInstance(connection: Connection): RenameDialog { val result = RenameDialog() result.arguments = Bundle().apply { putParcelable(EXTRA_CONNECTION, connection) } return result } } }
bsd-3-clause
b3a51f573ae63551a6a123a8432935a9
33.021352
125
0.634271
4.897029
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/timers/TimerControlSet.kt
1
4125
/* * Copyright (c) 2012 Todoroo Inc * * See the file "LICENSE" for the full license governing this code. */ package com.todoroo.astrid.timers import android.app.Activity import android.os.Bundle import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.compose.ui.platform.ComposeView import androidx.lifecycle.lifecycleScope import com.google.android.material.composethemeadapter.MdcTheme import com.todoroo.astrid.data.Task import com.todoroo.astrid.ui.TimeDurationControlSet import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch import org.tasks.R import org.tasks.compose.collectAsStateLifecycleAware import org.tasks.compose.edit.TimerRow import org.tasks.dialogs.DialogBuilder import org.tasks.themes.Theme import org.tasks.ui.TaskEditControlFragment import javax.inject.Inject /** * Control Set for managing repeats * * @author Tim Su <tim></tim>@todoroo.com> */ @AndroidEntryPoint class TimerControlSet : TaskEditControlFragment() { @Inject lateinit var activity: Activity @Inject lateinit var dialogBuilder: DialogBuilder @Inject lateinit var theme: Theme private lateinit var estimated: TimeDurationControlSet private lateinit var elapsed: TimeDurationControlSet private var dialog: AlertDialog? = null private lateinit var dialogView: View private lateinit var callback: TimerControlSetCallback override fun createView(savedInstanceState: Bundle?) { dialogView = activity.layoutInflater.inflate(R.layout.control_set_timers_dialog, null) estimated = TimeDurationControlSet(activity, dialogView, R.id.estimatedDuration, theme) elapsed = TimeDurationControlSet(activity, dialogView, R.id.elapsedDuration, theme) estimated.setTimeDuration(viewModel.estimatedSeconds.value) elapsed.setTimeDuration(viewModel.elapsedSeconds.value) } override fun onAttach(activity: Activity) { super.onAttach(activity) callback = activity as TimerControlSetCallback } private fun onRowClick() { if (dialog == null) { dialog = buildDialog() } dialog!!.show() } private fun buildDialog(): AlertDialog { return dialogBuilder .newDialog() .setView(dialogView) .setPositiveButton(R.string.ok) { _, _ -> viewModel.estimatedSeconds.value = estimated.timeDurationInSeconds viewModel.elapsedSeconds.value = elapsed.timeDurationInSeconds } .setOnCancelListener {} .create() } private fun timerClicked() { lifecycleScope.launch { if (timerActive()) { val task = callback.stopTimer() viewModel.elapsedSeconds.value = task.elapsedSeconds elapsed.setTimeDuration(task.elapsedSeconds) viewModel.timerStarted.value = 0 } else { val task = callback.startTimer() viewModel.timerStarted.value = task.timerStart } } } override fun bind(parent: ViewGroup?): View = (parent as ComposeView).apply { setContent { MdcTheme { TimerRow( started = viewModel.timerStarted.collectAsStateLifecycleAware().value, estimated = viewModel.estimatedSeconds.collectAsStateLifecycleAware().value, elapsed = viewModel.elapsedSeconds.collectAsStateLifecycleAware().value, timerClicked = this@TimerControlSet::timerClicked, onClick = this@TimerControlSet::onRowClick, ) } } } override fun controlId() = TAG private fun timerActive() = viewModel.timerStarted.value > 0 interface TimerControlSetCallback { suspend fun stopTimer(): Task suspend fun startTimer(): Task } companion object { const val TAG = R.string.TEA_ctrl_timer_pref } }
gpl-3.0
a3168ea1abe5a2231b488a44a1a40839
33.957627
100
0.663515
4.981884
false
false
false
false
dszopa/Spark-Message-Router
src/main/kotlin/io/github/dszopa/message_router/MessageRouter.kt
1
5670
package io.github.dszopa.message_router import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonParseException import io.github.dszopa.message_router.annotation.MessageObject import io.github.dszopa.message_router.annotation.Route import io.github.dszopa.message_router.exception.DuplicateRouteException import io.github.dszopa.message_router.exception.ParameterMismatchException import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner import io.github.lukehutch.fastclasspathscanner.scanner.ScanResult import me.sargunvohra.lib.gsonkotlin.GsonKotlinAdapterFactory import org.eclipse.jetty.websocket.api.Session import org.json.JSONObject import org.slf4j.Logger import org.slf4j.LoggerFactory import java.lang.reflect.Type import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KFunction import kotlin.reflect.full.createInstance import kotlin.reflect.full.declaredFunctions import kotlin.reflect.full.findAnnotation import kotlin.reflect.jvm.javaType import kotlin.reflect.jvm.jvmErasure /** * A router for socket messages * * This class will use reflection to find all functions annotated with * "@Route" and will map the functions to their route values. * * @param packagePath the package to be scanned for routes. * @constructor Creates a new message router with routes found * through reflection. */ class MessageRouter(packagePath: String) { private val logger: Logger = LoggerFactory.getLogger(MessageRouter::class.java) private val routeToMethodCalls: HashMap<String, Triple<Any, KFunction<*>, Type?>> = HashMap() private val kson: Gson = GsonBuilder() .registerTypeAdapterFactory(GsonKotlinAdapterFactory()) .create() init { val scanResult: ScanResult = FastClasspathScanner(packagePath) .enableMethodAnnotationIndexing() .scan() val classesContainingRouteMethods: List<String> = scanResult.getNamesOfClassesWithMethodAnnotation(Route::class.java) for (className: String in classesContainingRouteMethods) { val clazz: KClass<*> = Class.forName(className).kotlin for (function: KFunction<*> in clazz.declaredFunctions) { if (function.annotations.any { it.annotationClass == Route::class}) { if ((function.parameters.size != 3) || (function.parameters[1].type.jvmErasure != Session::class) || ((function.parameters[2].type.jvmErasure != String::class) && (!function.parameters[2].annotations.any { it.annotationClass == MessageObject::class}))) { throw ParameterMismatchException( "Incorrect parameters on method named: ${function.name}. " + "First parameter should be of type Session. Second parameter should be of type String or include the @MessageObject annotation." ) } var param3: Type? = null if (function.parameters[2].annotations.any { it.annotationClass == MessageObject::class}) { param3 = function.parameters[2].type.javaType } val route: Route = function.findAnnotation<Route>()!! // We already confirmed that it has a route annotation val value: String = route.value if (routeToMethodCalls.containsKey(value)) { throw DuplicateRouteException("Cannot create duplicate route: '$value'") } val instance: Any = clazz.createInstance() routeToMethodCalls.put(value, Triple(instance, function, param3)) } } } } /** * Routes incoming socket message to a function and calls that * function with the given parameters. * @param user A session object that indicates the user who sent the socket message. * @param message The socket message, this must be in JSON format * and include a "route" value in order for routing to work. */ fun handle(user: Session, message: String) { val messageJson: JSONObject = JSONObject(message) if (messageJson.has("route") && routeToMethodCalls.containsKey(messageJson.getString("route"))) { val route: String = messageJson.getString("route") val methodTriple: Triple<Any, KFunction<*>, Type?>? = routeToMethodCalls[route] if (methodTriple?.third != null) { try { if (!messageJson.has("data")) { logger.warn("Invalid request to Route: '$route', mapped to method: '${methodTriple.second.name}'. " + "Message did not contain a 'data' field.") return } val messageObject: Any = kson.fromJson(messageJson.get("data").toString(), methodTriple.third) methodTriple.second.call(methodTriple.first, user, messageObject) } catch (exception: JsonParseException) { logger.warn("Invalid request to Route: '$route', mapped to method: '${methodTriple.second.name}'. " + "MessageObject: '${methodTriple.third!!.typeName}' has non-null values that were populated as null.") } } else { methodTriple?.second?.call(methodTriple.first, user, message) } } else { logger.warn("Invalid request, message did not contain a 'route' field"); } } }
mit
cc21e39d4575c6db1aa7ec9d74db236f
47.470085
183
0.640917
4.879518
false
false
false
false
free5ty1e/primestationone-control-android
app/src/main/java/com/chrisprime/primestationonecontrol/model/PrimeStationOne.kt
1
3132
package com.chrisprime.primestationonecontrol.model import android.content.Context import com.chrisprime.primestationonecontrol.utilities.FileUtilities import org.parceler.Parcel import org.parceler.ParcelProperty /** * Created by cpaian on 7/18/15. */ @Parcel(Parcel.Serialization.BEAN) data class PrimeStationOne( @ParcelProperty("ipAddress") var ipAddress: String? = null ?.get { if (PrimeStationOne.Companion.mockIpOverride != null) { return@get PrimeStationOne.Companion.mockIpOverride } else { return@get this } }, @ParcelProperty("piUser") var piUser: String? = null, @ParcelProperty("piPassword") var piPassword: String? = null, @ParcelProperty("version") var version: String? = null, @ParcelProperty("hostname") var hostname: String? = null, @ParcelProperty("mac") var mac: String? = null, @ParcelProperty("splashscreenUriString") var splashscreenUriString: String? = null, @ParcelProperty("retrievedSplashscreen") var isRetrievedSplashscreen: Boolean? = false, @ParcelProperty("megaEmail") var megaEmail: String? = null, @ParcelProperty("megaPassword") var megaPassword: String? = null) { fun updateStoredPrimestation(context: Context) { FileUtilities.storeCurrentPrimeStationToJson(context, this) } override fun toString(): String { return "PrimeStationOne{" + "ipAddress='" + ipAddress + '\'' + ", hostname='" + hostname + '\'' + ", version='" + version + '\'' + ", mac='" + mac + '\'' + ", splashscreenUriString='" + splashscreenUriString + '\'' + ", retrievedSplashscreen=" + isRetrievedSplashscreen + ", megaEmail='" + megaEmail + '\'' + ", megaPassword='" + megaPassword + '\'' + ", piUser='" + piUser + '\'' + ", piPassword='" + piPassword + '\'' + '}' } companion object { val DEFAULT_PI_SSH_PORT = 22 val DEFAULT_PRIMESTATION_VERSION_TEXT_FILE_LOCATION = "/home/pi/primestationone/reference/txt/version.txt" val SPLASHSCREENWITHCONTROLSANDVERSION_PNG_FILE_NAME = "splashscreenwithcontrolsandversion.png" val DEFAULT_PRIMESTATION_SPLASH_SCREEN_FILE_LOCATION = "/home/pi/" + SPLASHSCREENWITHCONTROLSANDVERSION_PNG_FILE_NAME val PRIMESTATION_IMGUR_SPLASHSCREEN_SOURCE_IMAGE_URL = "http://i.imgur.com/UnMdAZX.png" val PRIMESTATION_DATA_STORAGE_PREFIX = "ps1_" val FOUND_PRIMESTATIONS_JSON_FILENAME = PRIMESTATION_DATA_STORAGE_PREFIX + "found_primestations.json" val CURRENT_PRIMESTATION_JSON_FILENAME = PRIMESTATION_DATA_STORAGE_PREFIX + "current_primestation.json" @JvmStatic fun generatePrimeStationOne(): PrimeStationOne { return PrimeStationOne("192.168.1.11", "pi", "primestation1", "Version 1.10 beta", "primestation1pi3") } @JvmField var mockIpOverride: String? = null } }
mit
6d85a9a4a00e9d8699d234d45b058481
46.454545
125
0.62516
4.38042
false
false
false
false
bailuk/AAT
aat-gtk/src/main/kotlin/ch/bailu/aat_gtk/logger/SL4JCache.kt
1
554
package ch.bailu.aat_gtk.logger import org.slf4j.Logger import org.slf4j.LoggerFactory import java.util.HashMap object SL4JCache { private val loggers: MutableMap<String, Logger> = HashMap() operator fun get(c: Class<*>): Logger { return get(c.name) } operator fun get(name: String): Logger { var result = loggers[name] return if (result == null) { result = LoggerFactory.getLogger(name) loggers[name] = result result } else { result } } }
gpl-3.0
b3f63ee8049600128ab5335b11d5a9d9
20.307692
63
0.592058
4.014493
false
false
false
false
olivierg13/EtherTracker
app/src/main/java/com/og/finance/ether/activities/AbstractFragmentActivity.kt
1
8149
/** * Copyright 2013 Olivier Goutay (olivierg13) * * * 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.og.finance.ether.activities import android.app.Fragment import android.app.FragmentManager import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.inputmethod.InputMethodManager import com.crashlytics.android.Crashlytics import com.og.finance.ether.R import com.og.finance.ether.animations.FragmentAnimation import com.og.finance.ether.fragments.AbstractFragment import com.og.finance.ether.fragments.HomeFragment abstract class AbstractFragmentActivity : AppCompatActivity(), FragmentManager.OnBackStackChangedListener { /** * Reference to the currently displaying fragment */ protected var mCurrentFragment: Fragment? = null object FRAGS { val FRAGMENT_KEY = "launch_fragment" val FRAGMENT_NAVIGATION_KEY = "navigation_key" } override fun onResume() { super.onResume() mCurrentFragment = currentFrag //Listen for backstack changes to get the current AbstractFragment displayed fragmentManager.addOnBackStackChangedListener(this) } override fun onBackStackChanged() { mCurrentFragment = visibleFrag } override fun onBackPressed() { try { val fm = fragmentManager if (fm != null) { val entries = fm.backStackEntryCount if (entries <= 1) { finish() } else { fm.popBackStackImmediate() } } } catch (e: RuntimeException) { Crashlytics.logException(e) } } override fun onPause() { super.onPause() mCurrentFragment = visibleFrag //Remove listener of backstack so we don't listen to other activities fragmentManager.removeOnBackStackChangedListener(this) } protected abstract fun initLayout(savedInstanceState: Bundle?) /** * Shows the fragment in the content_frame of the main layout. Shows fragment * by using [android.support.v4.app.FragmentTransaction.replace] * @param frag The fragment to show * * * @param addToBackStack Whether the backstack should hold this new fragment * * * @param animate Whether the transaction should be animated * * * @param transitionAnimation The [com.og.finance.ether.animations.FragmentAnimation] to animate the Fragment transition. Uses [FragmentAnimation.FRAGMENT_TRANSITION_BOTTOM_STAY] by default if null. */ @JvmOverloads fun showFragment(frag: Fragment, addToBackStack: Boolean, animate: Boolean, transitionAnimation: FragmentAnimation? = FragmentAnimation.FRAGMENT_TRANSITION_BOTTOM_STAY) { var animation = transitionAnimation hideKeyboard() val visibleFragment = visibleFrag if (visibleFragment != null && mCurrentFragment != null && (visibleFragment as Any).javaClass == (frag as Any).javaClass) { return } val fm = fragmentManager val transaction = fm.beginTransaction() if (addToBackStack) { transaction.addToBackStack(frag.javaClass.name) } if (animate) { if (animation != null) { transaction.setCustomAnimations(animation.animationEnter, animation.animationExit, animation.animationPopEnter, animation.animationPopExit) } else { animation = FragmentAnimation.FRAGMENT_TRANSITION_BOTTOM_STAY transaction.setCustomAnimations(animation.animationEnter, animation.animationExit, animation.animationPopEnter, animation.animationPopExit) } if (visibleFragment != null) { transaction.hide(visibleFragment) } if (!isFragmentInStack(frag.javaClass)) { transaction.add(R.id.content_frame_container, frag, frag.javaClass.name) } if (!frag.isAdded) { transaction.show(frag) } } else { if (isFragmentInStack(frag.javaClass)) { //Remove it if already in the stack. transaction.remove(frag) } transaction.replace(R.id.content_frame_container, frag, frag.javaClass.name) } mCurrentFragment = frag transaction.commitAllowingStateLoss() } /** * Calls [.showFragment] with * animate set to true * @param frag The fragment to show * * * @param addToBackStack Whether the backstack should hold this new fragment */ fun showFragment(frag: Fragment, addToBackStack: Boolean) { showFragment(frag, addToBackStack, true) } /** * Method searches through the fragments in the [android.support.v4.app.FragmentManager] * for the fragment that is currently visible and returns that fragment * @return The fragment that is currently visible */ //If it has already been set, but is not yet visible val currentFrag: Fragment get() { if (mCurrentFragment != null) { return mCurrentFragment as Fragment } return visibleFrag as Fragment } protected val visibleFrag: Fragment? get() { val fragmentManager = fragmentManager return (0..fragmentManager.backStackEntryCount - 1) .map { fragmentManager.getBackStackEntryAt(it).name } .map { fragmentManager.findFragmentByTag(it) } .firstOrNull { it is AbstractFragment && it.isVisible() } } /** * Allows to check if a fragment is present in the back stack or not * @param fragmentClass The [Class] of the fragment we want to check for * * * @return True if present in the back stack, false otherwise */ fun isFragmentInStack(fragmentClass: Class<*>): Boolean { val fragmentManager = fragmentManager return (0..fragmentManager.backStackEntryCount - 1) .map { fragmentManager.getBackStackEntryAt(it).name } .map { fragmentManager.findFragmentByTag(it) } .any { it != null && it.javaClass == fragmentClass } } /** * Hide the keyboard for the specified activity for the specified view */ fun hideKeyboard() { if (currentFocus != null) { val inputMethodManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0) } } /** * Clear the fragment back stack by calling [FragmentManager.popBackStackImmediate] * @param includeDashboardFragment If you want to clear DashboardFragment or not */ fun clearBackStack(includeDashboardFragment: Boolean) { try { val fm = fragmentManager if (fm != null) { val count = fm.backStackEntryCount for (i in 0..count - 1) { val notSpecialFrag = currentFrag !is HomeFragment if ((notSpecialFrag || includeDashboardFragment) && fm.backStackEntryCount > 1) { if (visibleFrag != null) { fm.popBackStackImmediate() } } } mCurrentFragment = null } } catch (e: Exception) { Crashlytics.logException(e) } } }
apache-2.0
33c1733a734eb85a2ce0cb32cc3346ed
34.898678
202
0.631734
5.190446
false
false
false
false
wiltonlazary/kotlin-native
runtime/src/main/kotlin/kotlin/text/CharCategory.kt
1
4072
/* * Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlin.text /** * Represents the character general category in the Unicode specification. */ public enum class CharCategory(public val value: Int, public val code: String) { /** * General category "Cn" in the Unicode specification. */ UNASSIGNED(0, "Cn"), /** * General category "Lu" in the Unicode specification. */ UPPERCASE_LETTER(1, "Lu"), /** * General category "Ll" in the Unicode specification. */ LOWERCASE_LETTER(2, "Ll"), /** * General category "Lt" in the Unicode specification. */ TITLECASE_LETTER(3, "Lt"), /** * General category "Lm" in the Unicode specification. */ MODIFIER_LETTER(4, "Lm"), /** * General category "Lo" in the Unicode specification. */ OTHER_LETTER(5, "Lo"), /** * General category "Mn" in the Unicode specification. */ NON_SPACING_MARK(6, "Mn"), /** * General category "Me" in the Unicode specification. */ ENCLOSING_MARK(7, "Me"), /** * General category "Mc" in the Unicode specification. */ COMBINING_SPACING_MARK(8, "Mc"), /** * General category "Nd" in the Unicode specification. */ DECIMAL_DIGIT_NUMBER(9, "Nd"), /** * General category "Nl" in the Unicode specification. */ LETTER_NUMBER(10, "Nl"), /** * General category "No" in the Unicode specification. */ OTHER_NUMBER(11, "No"), /** * General category "Zs" in the Unicode specification. */ SPACE_SEPARATOR(12, "Zs"), /** * General category "Zl" in the Unicode specification. */ LINE_SEPARATOR(13, "Zl"), /** * General category "Zp" in the Unicode specification. */ PARAGRAPH_SEPARATOR(14, "Zp"), /** * General category "Cc" in the Unicode specification. */ CONTROL(15, "Cc"), /** * General category "Cf" in the Unicode specification. */ FORMAT(16, "Cf"), /** * General category "Co" in the Unicode specification. */ PRIVATE_USE(18, "Co"), /** * General category "Cs" in the Unicode specification. */ SURROGATE(19, "Cs"), /** * General category "Pd" in the Unicode specification. */ DASH_PUNCTUATION(20, "Pd"), /** * General category "Ps" in the Unicode specification. */ START_PUNCTUATION(21, "Ps"), /** * General category "Pe" in the Unicode specification. */ END_PUNCTUATION(22, "Pe"), /** * General category "Pc" in the Unicode specification. */ CONNECTOR_PUNCTUATION(23, "Pc"), /** * General category "Po" in the Unicode specification. */ OTHER_PUNCTUATION(24, "Po"), /** * General category "Sm" in the Unicode specification. */ MATH_SYMBOL(25, "Sm"), /** * General category "Sc" in the Unicode specification. */ CURRENCY_SYMBOL(26, "Sc"), /** * General category "Sk" in the Unicode specification. */ MODIFIER_SYMBOL(27, "Sk"), /** * General category "So" in the Unicode specification. */ OTHER_SYMBOL(28, "So"), /** * General category "Pi" in the Unicode specification. */ INITIAL_QUOTE_PUNCTUATION(29, "Pi"), /** * General category "Pf" in the Unicode specification. */ FINAL_QUOTE_PUNCTUATION(30, "Pf"); /** * Returns `true` if [char] character belongs to this category. */ public operator fun contains(char: Char): Boolean = char.getType() == this.value public companion object { public fun valueOf(category: Int): CharCategory = when { category >=0 && category <= 16 -> values()[category] category >= 18 && category <= 30 -> values()[category - 1] else -> throw IllegalArgumentException("Category #$category is not defined.") } } }
apache-2.0
a99553364c7e1cb71a7bb918b75cdfa6
22.408046
101
0.574411
4.113131
false
false
false
false
goodwinnk/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/BuiltInWebBrowserUrlProvider.kt
1
3668
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.builtInWebServer import com.intellij.ide.browsers.OpenInBrowserRequest import com.intellij.ide.browsers.WebBrowserService import com.intellij.ide.browsers.WebBrowserUrlProvider import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.impl.http.HttpVirtualFile import com.intellij.psi.PsiFile import com.intellij.util.SmartList import com.intellij.util.Url import com.intellij.util.Urls import org.jetbrains.ide.BuiltInServerManager open class BuiltInWebBrowserUrlProvider : WebBrowserUrlProvider(), DumbAware { override fun canHandleElement(request: OpenInBrowserRequest): Boolean { if (request.virtualFile is HttpVirtualFile) { return true } // we must use base language because we serve file - not part of file, but the whole file // handlebars, for example, contains HTML and HBS psi trees, so, regardless of context, we should not handle such file val viewProvider = request.file.viewProvider return request.isPhysicalFile() && isFileOfMyLanguage(request.file) } protected open fun isFileOfMyLanguage(psiFile: PsiFile): Boolean = WebBrowserService.isHtmlOrXmlFile(psiFile) override fun getUrl(request: OpenInBrowserRequest, file: VirtualFile): Url? { if (file is HttpVirtualFile) { return Urls.newFromVirtualFile(file) } else { return getBuiltInServerUrls(file, request.project, null, request.isAppendAccessToken).firstOrNull() } } } @JvmOverloads fun getBuiltInServerUrls(file: VirtualFile, project: Project, currentAuthority: String?, appendAccessToken: Boolean = true): List<Url> { if (currentAuthority != null && !compareAuthority(currentAuthority)) { return emptyList() } val info = WebServerPathToFileManager.getInstance(project).getPathInfo(file) ?: return emptyList() val effectiveBuiltInServerPort = BuiltInServerOptions.getInstance().effectiveBuiltInServerPort val path = info.path val authority = currentAuthority ?: "localhost:$effectiveBuiltInServerPort" val query = if (appendAccessToken) "?$TOKEN_PARAM_NAME=${acquireToken()}" else "" val urls = SmartList(Urls.newHttpUrl(authority, "/${project.name}/$path", query)) val path2 = info.rootLessPathIfPossible if (path2 != null) { urls.add(Urls.newHttpUrl(authority, '/' + project.name + '/' + path2, query)) } val defaultPort = BuiltInServerManager.getInstance().port if (currentAuthority == null && defaultPort != effectiveBuiltInServerPort) { val defaultAuthority = "localhost:$defaultPort" urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path", query)) if (path2 != null) { urls.add(Urls.newHttpUrl(defaultAuthority, "/${project.name}/$path2", query)) } } return urls } fun compareAuthority(currentAuthority: String?): Boolean { if (currentAuthority.isNullOrEmpty()) { return false } val portIndex = currentAuthority!!.indexOf(':') if (portIndex < 0) { return false } val host = currentAuthority.substring(0, portIndex) if (!isOwnHostName(host)) { return false } val port = StringUtil.parseInt(currentAuthority.substring(portIndex + 1), -1) return port == BuiltInServerOptions.getInstance().effectiveBuiltInServerPort || port == BuiltInServerManager.getInstance().port }
apache-2.0
ce45e84cc303cc270d93e85f3acd767a
38.031915
140
0.732007
4.478632
false
false
false
false
DemonWav/IntelliJBukkitSupport
src/main/kotlin/platform/mixin/debug/MixinPositionManager.kt
1
5305
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.debug import com.demonwav.mcdev.platform.mixin.util.MixinConstants import com.demonwav.mcdev.platform.mixin.util.mixinTargets import com.demonwav.mcdev.util.findContainingClass import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.mapNotNull import com.intellij.debugger.MultiRequestPositionManager import com.intellij.debugger.NoDataException import com.intellij.debugger.SourcePosition import com.intellij.debugger.engine.DebugProcess import com.intellij.debugger.engine.DebuggerUtils import com.intellij.debugger.impl.DebuggerUtilsEx import com.intellij.debugger.requests.ClassPrepareRequestor import com.intellij.ide.highlighter.JavaFileType import com.intellij.openapi.application.runReadAction import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.sun.jdi.AbsentInformationException import com.sun.jdi.Location import com.sun.jdi.ReferenceType import com.sun.jdi.request.ClassPrepareRequest import java.util.stream.Stream import kotlin.streams.toList class MixinPositionManager(private val debugProcess: DebugProcess) : MultiRequestPositionManager { override fun getAcceptedFileTypes(): Set<FileType> = setOf(JavaFileType.INSTANCE) @Throws(NoDataException::class) override fun getSourcePosition(location: Location?): SourcePosition? { location ?: throw NoDataException.INSTANCE val type = location.declaringType() // Check if mixin source map is present (Mixin sets the default stratum to Mixin) if (type.defaultStratum() != MixinConstants.SMAP_STRATUM) { throw NoDataException.INSTANCE } // Return the correct PsiFile based on the source path in the SMAP try { val path = location.sourcePath() // The source path is the package (separated by slashes) and class name with the ".java" file extension val className = path.removeSuffix(".java") .replace('/', '.').replace('\\', '.') val psiFile = findAlternativeSource(className, debugProcess.project) // Lookup class based on its qualified name (TODO: Support for anonymous classes) ?: DebuggerUtils.findClass( className, debugProcess.project, debugProcess.searchScope )?.navigationElement?.containingFile if (psiFile != null) { // File found, return correct source file return SourcePosition.createFromLine(psiFile, location.lineNumber() - 1) } } catch (ignored: AbsentInformationException) { } throw NoDataException.INSTANCE } private fun findAlternativeSource(className: String, project: Project): PsiFile? { val alternativeSource = DebuggerUtilsEx.getAlternativeSourceUrl(className, project) ?: return null val alternativeFile = VirtualFileManager.getInstance().findFileByUrl(alternativeSource) ?: return null return PsiManager.getInstance(project).findFile(alternativeFile) } override fun getAllClasses(classPosition: SourcePosition): List<ReferenceType> { return runReadAction { findMatchingClasses(classPosition) .flatMap { name -> debugProcess.virtualMachineProxy.classesByName(name).stream() } .toList() } } override fun locationsOfLine(type: ReferenceType, position: SourcePosition): List<Location> { // Check if mixin source map is present (Mixin sets the default stratum to Mixin) if (type.defaultStratum() == MixinConstants.SMAP_STRATUM) { try { // Return the line numbers from the correct source file return type.locationsOfLine(MixinConstants.SMAP_STRATUM, position.file.name, position.line + 1) } catch (ignored: AbsentInformationException) { } } throw NoDataException.INSTANCE } override fun createPrepareRequest(requestor: ClassPrepareRequestor, position: SourcePosition): ClassPrepareRequest { throw UnsupportedOperationException( "This class implements MultiRequestPositionManager, " + "corresponding createPrepareRequests version should be used" ) } override fun createPrepareRequests( requestor: ClassPrepareRequestor, position: SourcePosition ): List<ClassPrepareRequest> { return runReadAction { findMatchingClasses(position) .mapNotNull { name -> debugProcess.requestsManager.createClassPrepareRequest(requestor, name) } .toList() } } private fun findMatchingClasses(position: SourcePosition): Stream<String> { val classElement = position.elementAt?.findContainingClass() ?: throw NoDataException.INSTANCE return classElement.mixinTargets .ifEmpty { throw NoDataException.INSTANCE } .stream() .map { it.name } } }
mit
3eec23af25e251907b7db58078cbe59e
39.189394
120
0.698775
5.150485
false
false
false
false
jsilverMDX/GlobalChat2
GlobalChat-Kotlin-Android/app/src/main/java/com/lookrative/globalchat2androidkotlin/GlobalChat.kt
1
1438
package com.lookrative.globalchat2androidkotlin import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.annotation.RequiresApi import kotlinx.android.synthetic.main.activity_global_chat.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @RequiresApi(Build.VERSION_CODES.O) class GlobalChat : AppCompatActivity() { private lateinit var client : GC2Client override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_global_chat) val ip = intent.getStringExtra("serverIp") val name = intent.getStringExtra("serverName") val port = intent.getIntExtra("serverPort", 0) webView.settings.javaScriptEnabled = true; webView.loadUrl("file:///android_asset/chat.html") client = GC2Client(this, ip, port) GlobalScope.launch { client.start() } println("ON ACTIVITY CREATE") } override fun onActivityReenter(resultCode: Int, data: Intent?) { super.onActivityReenter(resultCode, data) println("ON ACTIVITY REENTER") } override fun onBackPressed() { println("ON BACK PRESSED") GlobalScope.launch { client.stop() } super.onBackPressed() } }
gpl-3.0
7ae42f3561a4a1d14e47ee72dd68683a
28
68
0.671071
4.653722
false
false
false
false
lare96/luna
plugins/world/player/skill/firemaking/LightLogAction.kt
1
3854
package world.player.skill.firemaking import api.predef.* import io.luna.game.action.Action import io.luna.game.action.ConditionalAction import io.luna.game.action.InventoryAction import io.luna.game.model.mob.Animation import io.luna.game.model.mob.Player /** * An [InventoryAction] implementation that will light a log on fire. */ class LightLogAction(plr: Player, var delayTicks: Int, val log: Log) : ConditionalAction<Player>(plr, false, 1) { companion object { val TINDERBOX_ID = 590 val FIRE_OBJ_ID = 2732 val ASHES_ID = 592 val LIGHT_ANIMATION = Animation(733) /** * How fast all logs will be lit. Higher value = slower. Must be greater than or equal to {@code 2}. */ val BASE_LIGHT_RATE = 13 /** * Jagex have stated that log type does not have an effect on burn times, so we use a random time between 45s * and 2m. */ val BURN_TIME = 75..200 } /** * The animation delay. */ private var animationDelay: Int = 0 override fun start() = when { occupied(0, 0) -> { mob.sendMessage("You cannot light a fire here.") false } mob.fishing.level < log.level -> { mob.sendMessage("You need a Firemaking level of ${log.level} to light this.") false } !mob.inventory.contains(TINDERBOX_ID) -> { mob.sendMessage("You need a tinderbox to light this.") false } else -> { if (mob.inventory.remove(log.id)) { world.addItem(log.id, 1, mob.position, mob) mob.sendMessage("You light the ${itemName(log.id).toLowerCase()}...") true } else { false } } } override fun condition(): Boolean { if (occupied(0, 0)) { return false } else if (--delayTicks <= 0) { lightFire() return false } doLightAnim() return true } override fun stop() = mob.animation(Animation.CANCEL) override fun ignoreIf(other: Action<*>?) = when (other) { is LightLogAction -> log.id == other.log.id else -> false } /** * Ensure the light animation only plays once every 1.8s, otherwise it stutters. */ private fun doLightAnim() { if (--animationDelay <= 0) { mob.animation(LIGHT_ANIMATION) animationDelay = 3 } } private fun lightFire() { if (world.items.removeFromPosition(mob.position) { it.id == log.id }) { val firePosition = mob.position mob.firemaking.addExperience(log.exp) if (!occupied(-1, 0)) { mob.walking.walk(-1, 0) } else if (!occupied(1, 0)) { mob.walking.walk(1, 0) } else if (!occupied(0, -1)) { mob.walking.walk(0, -1) } else if (!occupied(0, 1)) { mob.walking.walk(0, 1) } val fireObject = world.addObject(FIRE_OBJ_ID, firePosition) world.scheduleOnce(1) { world.scheduleOnce(rand(BURN_TIME)) { world.removeObject(fireObject) world.addItem(ASHES_ID, 1, fireObject.position) } } } } /* TODO This should be handled by collision detection once map loading is added. Right now, only checks for other objects. */ private fun occupied(offsetX: Int, offsetY: Int): Boolean { val offsetPos = mob.position.translate(offsetX, offsetY) return world.objects.findAll(offsetPos).count() > 0L } }
mit
ada2066b2558a6942e6991a55c16abcd
30.080645
117
0.532693
4.184582
false
false
false
false
wikimedia/apps-android-wikipedia
app/src/main/java/org/wikipedia/connectivity/NetworkConnectivityReceiver.kt
1
1711
package org.wikipedia.connectivity import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.ConnectivityManager import androidx.core.net.ConnectivityManagerCompat import org.wikipedia.WikipediaApp import org.wikipedia.analytics.eventplatform.EventPlatformClient import org.wikipedia.events.NetworkConnectEvent import java.util.concurrent.TimeUnit class NetworkConnectivityReceiver : BroadcastReceiver() { private var online = true private var lastCheckedMillis: Long = 0 fun isOnline(): Boolean { if (System.currentTimeMillis() - lastCheckedMillis > ONLINE_CHECK_THRESHOLD_MILLIS) { updateOnlineState() lastCheckedMillis = System.currentTimeMillis() } return online } override fun onReceive(context: Context, intent: Intent) { if (ConnectivityManager.CONNECTIVITY_ACTION == intent.action) { val networkInfo = ConnectivityManagerCompat .getNetworkInfoFromBroadcast(context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager, intent) updateOnlineState() if (networkInfo != null && networkInfo.isConnected) { WikipediaApp.instance.bus.post(NetworkConnectEvent()) } } } private fun updateOnlineState() { val info = (WikipediaApp.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).activeNetworkInfo online = info != null && info.isConnected EventPlatformClient.setEnabled(online) } companion object { private val ONLINE_CHECK_THRESHOLD_MILLIS = TimeUnit.MINUTES.toMillis(1) } }
apache-2.0
f46e46fd81236f6e8dcd376810de6ba7
37.022222
135
0.722385
5.200608
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/ImageCropperActivity.kt
1
6067
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.activity import android.annotation.SuppressLint import android.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.theartofdev.edmodo.cropper.CropImage import com.theartofdev.edmodo.cropper.CropImageOptions import com.theartofdev.edmodo.cropper.CropImageView import kotlinx.android.synthetic.main.activity_crop_image.* import de.vanita5.twittnuker.R /** * Built-in activity for image cropping. * Use [CropImage.activity] to create a builder to start this activity. */ class ImageCropperActivity : BaseActivity(), CropImageView.OnSetImageUriCompleteListener, CropImageView.OnCropImageCompleteListener { /** * Persist URI image to crop URI if specific permissions are required */ private val cropImageUri: Uri get() = intent.getParcelableExtra(CropImage.CROP_IMAGE_EXTRA_SOURCE) /** * the options that were set for the crop image */ private val options: CropImageOptions get() = intent.getParcelableExtra(CropImage.CROP_IMAGE_EXTRA_OPTIONS) /** * Get Android uri to save the cropped image into.<br></br> * Use the given in options or create a temp file. */ private val outputUri: Uri get() = options.outputUri @SuppressLint("NewApi") public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_crop_image) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (savedInstanceState == null) { // no permissions required or already grunted, can start crop image activity cropImageView.setImageUriAsync(cropImageUri) } } override fun onStart() { super.onStart() cropImageView.setOnSetImageUriCompleteListener(this) cropImageView.setOnCropImageCompleteListener(this) } override fun onStop() { super.onStop() cropImageView.setOnSetImageUriCompleteListener(null) cropImageView.setOnCropImageCompleteListener(null) } override fun onBackPressed() { setResultCancel() } override fun onSupportNavigateUp(): Boolean { setResultCancel() return true } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_crop_image, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.perform_crop -> { cropImage() return true } } return super.onOptionsItemSelected(item) } override fun onSetImageUriComplete(view: CropImageView, uri: Uri, error: Exception?) { if (error == null) { if (options.initialCropWindowRectangle != null) { cropImageView.cropRect = options.initialCropWindowRectangle } if (options.initialRotation > -1) { cropImageView.rotatedDegrees = options.initialRotation } } else { setResult(null, error, 1) } } override fun onCropImageComplete(view: CropImageView, result: CropImageView.CropResult) { setResult(result.uri, result.error, result.sampleSize) } //region: Private methods /** * Execute crop image and save the result to output uri. */ private fun cropImage() { if (options.noOutputImage) { setResult(null, null, 1) } else { val outputUri = outputUri cropImageView.saveCroppedImageAsync(outputUri, options.outputCompressFormat, options.outputCompressQuality, options.outputRequestWidth, options.outputRequestHeight, options.outputRequestSizeOptions) } } /** * Rotate the image in the crop image view. */ protected fun rotateImage(degrees: Int) { cropImageView.rotateImage(degrees) } /** * Result with cropped image data or error if failed. */ private fun setResult(uri: Uri?, error: Exception?, sampleSize: Int) { val resultCode = if (error == null) Activity.RESULT_OK else CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE setResult(resultCode, getResultIntent(uri, error, sampleSize)) finish() } /** * Cancel of cropping activity. */ private fun setResultCancel() { setResult(Activity.RESULT_CANCELED) finish() } /** * Get intent instance to be used for the result of this activity. */ private fun getResultIntent(uri: Uri?, error: Exception?, sampleSize: Int): Intent { val result = CropImage.ActivityResult(cropImageView.imageUri, uri, error, cropImageView.cropPoints, cropImageView.cropRect, cropImageView.rotatedDegrees, sampleSize) val intent = Intent() intent.putExtra(CropImage.CROP_IMAGE_EXTRA_RESULT, result) return intent } //endregion }
gpl-3.0
6837bc3edf40cf460a230fffd01d764c
31.972826
133
0.668205
4.663336
false
false
false
false
jk1/youtrack-idea-plugin
src/main/kotlin/com/github/jk1/ytplugin/timeTracker/actions/StopTrackerAction.kt
1
5239
package com.github.jk1.ytplugin.timeTracker.actions import com.github.jk1.ytplugin.ComponentAware import com.github.jk1.ytplugin.logger import com.github.jk1.ytplugin.tasks.NoYouTrackRepositoryException import com.github.jk1.ytplugin.tasks.YouTrackServer import com.github.jk1.ytplugin.timeTracker.TimeTrackerConnector import com.github.jk1.ytplugin.timeTracker.TrackerNotification import com.github.jk1.ytplugin.ui.YouTrackPluginIcons import com.github.jk1.ytplugin.whenActive import com.intellij.ide.util.PropertiesComponent import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.wm.WindowManager import java.util.* import java.util.concurrent.TimeUnit class StopTrackerAction : AnAction( "Stop Work Timer", "Stop tracking and post spent time to the current issue", YouTrackPluginIcons.YOUTRACK_STOP_TIME_TRACKER) { override fun actionPerformed(event: AnActionEvent) { event.whenActive { project -> try { stopTimer(project, ComponentAware.of(project).taskManagerComponent.getActiveYouTrackRepository()) } catch (e: NoYouTrackRepositoryException){ val timer = ComponentAware.of(project).timeTrackerComponent timer.stop() // save time in case of exceptions val time = TimeUnit.MINUTES.toMillis(timer.recordedTime.toLong()) ComponentAware.of(project).spentTimePerTaskStorage.resetSavedTimeForLocalTask(timer.issueId) // not to sum up the same item ComponentAware.of(project).spentTimePerTaskStorage.setSavedTimeForLocalTask(timer.issueId, time) timer.isAutoTrackingTemporaryDisabled = true logger.warn("Time could not be posted as the issue does not belong to current YouTrack instance. " + "Time is saved locally: ${e.message}") logger.debug(e) val trackerNote = TrackerNotification() trackerNote.notify("Could not post time as the issue does not belong to the current YouTrack " + "instance. Time ${timer.recordedTime} is saved locally", NotificationType.WARNING) } } } override fun update(event: AnActionEvent) { val project = event.project if (project != null) { val timer = ComponentAware.of(event.project!!).timeTrackerComponent event.presentation.isEnabled = timer.isRunning event.presentation.isVisible = (timer.isManualTrackingEnabled || timer.isAutoTrackingEnabled) if (timer.isAutoTrackingEnabled){ event.presentation.icon = YouTrackPluginIcons.YOUTRACK_POST_FROM_TIME_TRACKER event.presentation.description = "Post spent time to the current issue and continue tracking" event.presentation.text = "Post Time to Server" } else { event.presentation.icon = YouTrackPluginIcons.YOUTRACK_STOP_TIME_TRACKER event.presentation.description = "Stop tracking and post spent time to the current issue" event.presentation.text = "Stop Work Timer" } } } fun stopTimer(project: Project, repo: YouTrackServer) { val trackerNote = TrackerNotification() val timer = ComponentAware.of(project).timeTrackerComponent try { timer.stop() val bar = WindowManager.getInstance().getStatusBar(project) bar?.removeWidget("Time Tracking Clock") val recordedTime = timer.recordedTime if (recordedTime == "0") trackerNote.notify("Spent time shorter than 1 minute is excluded from time tracking", NotificationType.WARNING) else { try { TimeTrackerConnector(repo, project).postWorkItemToServer(timer.issueId, recordedTime, timer.type, timer.comment, (Date().time).toString(), mapOf()) ComponentAware.of(project).issueWorkItemsStoreComponent[repo].update(repo) } catch (e: Exception) { logger.warn("Time tracking might not be enabled: ${e.message}") logger.debug(e) // save time in case of exceptions val time = TimeUnit.MINUTES.toMillis(timer.recordedTime.toLong()) ComponentAware.of(project).spentTimePerTaskStorage.resetSavedTimeForLocalTask(timer.issueId) // not to sum up the same item ComponentAware.of(project).spentTimePerTaskStorage.setSavedTimeForLocalTask(timer.issueId, time) } val store: PropertiesComponent = PropertiesComponent.getInstance(project) store.saveFields(timer) } } catch (e: IllegalStateException) { logger.warn("Time tracking exception: ${e.message}") logger.debug(e) trackerNote.notify("Could not stop time tracking: timer is not started", NotificationType.WARNING) } } }
apache-2.0
b56dc96279c824a140c7fc5aa6b5419c
46.636364
143
0.662149
4.956481
false
false
false
false
codebutler/odyssey
retrograde-metadata-ovgdb/src/main/java/com/codebutler/retrograde/metadata/ovgdb/db/entity/OvgdbRom.kt
1
1787
/* * Rom.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.metadata.ovgdb.db.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "roms", indices = [Index("romFileName"), Index("romHashCRC")]) data class OvgdbRom( @PrimaryKey @ColumnInfo(name = "romID") val id: Int, @ColumnInfo(name = "systemID") val systemId: Int, @ColumnInfo(name = "regionID") val regionId: Int, @ColumnInfo(name = "romHashCRC") val hashCrc: String, @ColumnInfo(name = "romHashMD5") val hashMd5: String, @ColumnInfo(name = "romHashSHA1") val hashSha1: String, @ColumnInfo(name = "romSize") val size: Int, @ColumnInfo(name = "romFileName") val fileName: String, @ColumnInfo(name = "romExtensionlessFileName") val extensionlessFileName: String, @ColumnInfo(name = "romSerial") val serial: String?, @ColumnInfo(name = "romHeader") val header: String?, @ColumnInfo(name = "romLanguage") val language: String? )
gpl-3.0
035495d413f1c29e0a98011c31c6453e
25.671642
72
0.6939
3.843011
false
false
false
false
robohorse/RoboPOJOGenerator
app/src/main/kotlin/com/robohorse/robopojogenerator/view/GeneratorViewFactory.kt
1
1468
package com.robohorse.robopojogenerator.view import com.intellij.openapi.ui.DialogBuilder import com.robohorse.robopojogenerator.delegates.MessageDelegate import com.robohorse.robopojogenerator.form.GeneratorVew import com.robohorse.robopojogenerator.utils.ClassGenerateHelper import com.robohorse.robopojogenerator.listeners.GenerateActionListener import com.robohorse.robopojogenerator.listeners.GuiFormEventListener internal class GeneratorViewFactory( private val messageDelegate: MessageDelegate, private val classGenerateHelper: ClassGenerateHelper, private val generatorViewBinder: GeneratorViewBinder, private val viewModelMapper: ViewModelMapper ) { fun bindView(builder: DialogBuilder, eventListener: GuiFormEventListener) { val generatorVew = GeneratorVew() val actionListener = GenerateActionListener( generatorVew = generatorVew, eventListener = eventListener, messageDelegate = messageDelegate, classGenerateHelper = classGenerateHelper, viewModelMapper = viewModelMapper ) with(generatorVew) { generatorViewBinder.bindView(this) generateButton.addActionListener(actionListener) builder.setCenterPanel(rootView) } builder.apply { setTitle(PLUGIN_TITLE) removeAllActions() show() } } } private const val PLUGIN_TITLE = "RoboPOJOGenerator"
mit
968c51fc7f24b0421e9820b10ed16419
36.641026
79
0.735695
5.357664
false
false
false
false
VKCOM/vk-android-sdk
api/src/main/java/com/vk/sdk/api/account/dto/AccountUserSettingsInterests.kt
1
2420
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * 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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.account.dto import com.google.gson.annotations.SerializedName /** * @param activities * @param interests * @param music * @param tv * @param movies * @param books * @param games * @param quotes * @param about */ data class AccountUserSettingsInterests( @SerializedName("activities") val activities: AccountUserSettingsInterest? = null, @SerializedName("interests") val interests: AccountUserSettingsInterest? = null, @SerializedName("music") val music: AccountUserSettingsInterest? = null, @SerializedName("tv") val tv: AccountUserSettingsInterest? = null, @SerializedName("movies") val movies: AccountUserSettingsInterest? = null, @SerializedName("books") val books: AccountUserSettingsInterest? = null, @SerializedName("games") val games: AccountUserSettingsInterest? = null, @SerializedName("quotes") val quotes: AccountUserSettingsInterest? = null, @SerializedName("about") val about: AccountUserSettingsInterest? = null )
mit
1a372851dc4647b78033fcd2a3d13147
38.032258
81
0.694215
4.653846
false
false
false
false
pbauerochse/youtrack-worklog-viewer
application/src/main/java/de/pbauerochse/worklogviewer/fx/issuesearch/WebViewSanitizer.kt
1
1548
package de.pbauerochse.worklogviewer.fx.issuesearch /** * Removes unwanted HTML from Issue-Description * so there are no HTML-Links being displayed * in the WebView as they won't be working anyways */ object WebViewSanitizer { private val LINK_EXPRESSION = Regex("<a((\\s*\\w+=\".*?\"\\s*)*)>(.+?)</a>") private val ATTRIBUTE_EXPRESSION = Regex("\\w+=\".*?\"") fun sanitize(description: String): String { return replaceLinks(description) } private fun replaceLinks(description: String): String { return LINK_EXPRESSION.replace(description) { matchResult -> val attributesAndValues = ATTRIBUTE_EXPRESSION.findAll(matchResult.groupValues[1]).map { it.groupValues[0].trim() }.toList() val attributes = readAttributeMap(attributesAndValues) val linkText = matchResult.groupValues[3] val additionalClasses = attributes["class"]?.let { " $it" } ?: "" val titleAttribute = attributes["title"]?.let { " title=\"$it\"" } ?: "" val classValue = "link$additionalClasses" return@replace "<span class=\"$classValue\"$titleAttribute>$linkText</span>" } } private fun readAttributeMap(attributes: List<String>): Map<String, String> { return attributes.filter { it.isNotBlank() }.associate { attribute -> val key = attribute.substringBefore("=") val value = attribute.substringAfter("=").trim().removeSurrounding("\"") return@associate Pair(key, value) } } }
mit
5e22e08d54ff396b1cdde68d8e20f807
36.780488
136
0.634367
4.662651
false
false
false
false
ligee/kotlin-jupyter
jupyter-lib/shared-compiler/src/main/kotlin/org/jetbrains/kotlinx/jupyter/exceptions/ReplCompilerException.kt
1
2531
package org.jetbrains.kotlinx.jupyter.exceptions import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlin.script.experimental.api.ResultWithDiagnostics import kotlin.script.experimental.api.ScriptDiagnostic class ReplCompilerException( val failedCode: String, val errorResult: ResultWithDiagnostics.Failure? = null, message: String? = null ) : ReplException( message ?: errorResult?.getErrors() ?: "", errorResult?.reports?.map { it.exception }?.firstOrNull() ) { val firstError = errorResult?.reports?.firstOrNull { it.severity == ScriptDiagnostic.Severity.ERROR || it.severity == ScriptDiagnostic.Severity.FATAL } override fun getAdditionalInfoJson(): JsonObject? { return firstError?.location?.let { val errorMessage = firstError.message JsonObject( mapOf( "lineStart" to JsonPrimitive(it.start.line), "colStart" to JsonPrimitive(it.start.col), "lineEnd" to JsonPrimitive(it.end?.line ?: -1), "colEnd" to JsonPrimitive(it.end?.col ?: -1), "message" to JsonPrimitive(errorMessage), "path" to JsonPrimitive(firstError.sourcePath.orEmpty()) ) ) } } override fun render() = message } fun <T> ResultWithDiagnostics<T>.getErrors(): String { val filteredReports = reports.filter { it.code != ScriptDiagnostic.incompleteCode } return filteredReports.joinToString("\n") { report -> report.location?.let { loc -> report.sourcePath?.let { sourcePath -> compilerDiagnosticToString( sourcePath, loc.start.line, loc.start.col, loc.end?.line ?: -1, loc.end?.col ?: -1, ) }?.let { "$it " } }.orEmpty() + report.message } } fun compilerDiagnosticToString( path: String, line: Int, column: Int, lineEnd: Int, columnEnd: Int, ): String { val start = if (line == -1 && column == -1) "" else "$line:$column" val end = if (lineEnd == -1 && columnEnd == -1) "" else if (lineEnd == line) " - $columnEnd" else " - $lineEnd:$columnEnd" val loc = if (start.isEmpty() && end.isEmpty()) "" else " ($start$end)" return path + loc }
apache-2.0
4f5331912aa3cfff31d5df85e1e0cd9f
31.037975
104
0.568155
4.593466
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/repl.kt
1
24903
package org.jetbrains.kotlinx.jupyter import jupyter.kotlin.CompilerArgs import jupyter.kotlin.DependsOn import jupyter.kotlin.KotlinContext import jupyter.kotlin.Repository import jupyter.kotlin.providers.UserHandlesProvider import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.config.KotlinCompilerVersion import org.jetbrains.kotlinx.jupyter.api.Code import org.jetbrains.kotlinx.jupyter.api.ExecutionCallback import org.jetbrains.kotlinx.jupyter.api.KotlinKernelHost import org.jetbrains.kotlinx.jupyter.api.KotlinKernelVersion import org.jetbrains.kotlinx.jupyter.api.Renderable import org.jetbrains.kotlinx.jupyter.api.SessionOptions import org.jetbrains.kotlinx.jupyter.codegen.ClassAnnotationsProcessor import org.jetbrains.kotlinx.jupyter.codegen.ClassAnnotationsProcessorImpl import org.jetbrains.kotlinx.jupyter.codegen.FieldsProcessor import org.jetbrains.kotlinx.jupyter.codegen.FieldsProcessorImpl import org.jetbrains.kotlinx.jupyter.codegen.FileAnnotationsProcessor import org.jetbrains.kotlinx.jupyter.codegen.FileAnnotationsProcessorImpl import org.jetbrains.kotlinx.jupyter.codegen.RenderersProcessorImpl import org.jetbrains.kotlinx.jupyter.codegen.ResultsRenderersProcessor import org.jetbrains.kotlinx.jupyter.codegen.ThrowableRenderersProcessor import org.jetbrains.kotlinx.jupyter.codegen.ThrowableRenderersProcessorImpl import org.jetbrains.kotlinx.jupyter.common.looksLikeReplCommand import org.jetbrains.kotlinx.jupyter.compiler.CompilerArgsConfigurator import org.jetbrains.kotlinx.jupyter.compiler.DefaultCompilerArgsConfigurator import org.jetbrains.kotlinx.jupyter.compiler.ScriptImportsCollector import org.jetbrains.kotlinx.jupyter.compiler.util.Classpath import org.jetbrains.kotlinx.jupyter.compiler.util.EvaluatedSnippetMetadata import org.jetbrains.kotlinx.jupyter.compiler.util.SerializedCompiledScriptsData import org.jetbrains.kotlinx.jupyter.config.catchAll import org.jetbrains.kotlinx.jupyter.config.getCompilationConfiguration import org.jetbrains.kotlinx.jupyter.dependencies.JupyterScriptDependenciesResolver import org.jetbrains.kotlinx.jupyter.dependencies.JupyterScriptDependenciesResolverImpl import org.jetbrains.kotlinx.jupyter.dependencies.ScriptDependencyAnnotationHandlerImpl import org.jetbrains.kotlinx.jupyter.exceptions.LibraryProblemPart import org.jetbrains.kotlinx.jupyter.exceptions.rethrowAsLibraryException import org.jetbrains.kotlinx.jupyter.execution.InterruptionCallbacksProcessor import org.jetbrains.kotlinx.jupyter.libraries.KERNEL_LIBRARIES import org.jetbrains.kotlinx.jupyter.libraries.LibrariesProcessor import org.jetbrains.kotlinx.jupyter.libraries.LibrariesProcessorImpl import org.jetbrains.kotlinx.jupyter.libraries.LibrariesScanner import org.jetbrains.kotlinx.jupyter.libraries.LibraryResolver import org.jetbrains.kotlinx.jupyter.libraries.LibraryResourcesProcessorImpl import org.jetbrains.kotlinx.jupyter.libraries.ResolutionInfoProvider import org.jetbrains.kotlinx.jupyter.libraries.getDefaultResolutionInfoSwitcher import org.jetbrains.kotlinx.jupyter.magics.CompletionMagicsProcessor import org.jetbrains.kotlinx.jupyter.magics.CompoundCodePreprocessor import org.jetbrains.kotlinx.jupyter.magics.ErrorsMagicsProcessor import org.jetbrains.kotlinx.jupyter.magics.FullMagicsHandler import org.jetbrains.kotlinx.jupyter.magics.MagicsProcessor import org.jetbrains.kotlinx.jupyter.messaging.DisplayHandler import org.jetbrains.kotlinx.jupyter.repl.CellExecutor import org.jetbrains.kotlinx.jupyter.repl.CompletionResult import org.jetbrains.kotlinx.jupyter.repl.ContextUpdater import org.jetbrains.kotlinx.jupyter.repl.EvalResult import org.jetbrains.kotlinx.jupyter.repl.EvalResultEx import org.jetbrains.kotlinx.jupyter.repl.InternalEvaluator import org.jetbrains.kotlinx.jupyter.repl.InternalVariablesMarkersProcessor import org.jetbrains.kotlinx.jupyter.repl.KotlinCompleter import org.jetbrains.kotlinx.jupyter.repl.ListErrorsResult import org.jetbrains.kotlinx.jupyter.repl.impl.BaseKernelHost import org.jetbrains.kotlinx.jupyter.repl.impl.CellExecutorImpl import org.jetbrains.kotlinx.jupyter.repl.impl.InternalEvaluatorImpl import org.jetbrains.kotlinx.jupyter.repl.impl.InternalVariablesMarkersProcessorImpl import org.jetbrains.kotlinx.jupyter.repl.impl.InterruptionCallbacksProcessorImpl import org.jetbrains.kotlinx.jupyter.repl.impl.JupyterCompilerWithCompletion import org.jetbrains.kotlinx.jupyter.repl.impl.ScriptImportsCollectorImpl import org.jetbrains.kotlinx.jupyter.repl.impl.SharedReplContext import java.io.File import java.net.URLClassLoader import java.util.concurrent.atomic.AtomicReference import kotlin.script.experimental.api.ResultWithDiagnostics import kotlin.script.experimental.api.ScriptCompilationConfiguration import kotlin.script.experimental.api.ScriptConfigurationRefinementContext import kotlin.script.experimental.api.ScriptEvaluationConfiguration import kotlin.script.experimental.api.asSuccess import kotlin.script.experimental.api.constructorArgs import kotlin.script.experimental.api.dependencies import kotlin.script.experimental.api.fileExtension import kotlin.script.experimental.api.implicitReceivers import kotlin.script.experimental.api.refineConfiguration import kotlin.script.experimental.api.with import kotlin.script.experimental.dependencies.RepositoryCoordinates import kotlin.script.experimental.jvm.BasicJvmReplEvaluator import kotlin.script.experimental.jvm.JvmDependency import kotlin.script.experimental.jvm.baseClassLoader import kotlin.script.experimental.jvm.jvm data class CheckResult(val isComplete: Boolean = true) class EvalRequestData( val code: Code, val displayHandler: DisplayHandler? = null, val jupyterId: Int = -1, val storeHistory: Boolean = true, @Suppress("UNUSED") val isSilent: Boolean = false, ) enum class ExecutedCodeLogging { OFF, ALL, GENERATED } interface ReplRuntimeProperties { val version: KotlinKernelVersion? val librariesFormatVersion: Int val currentBranch: String val currentSha: String val jvmTargetForSnippets: String } interface ReplOptions { val currentBranch: String val librariesDir: File var trackClasspath: Boolean var executedCodeLogging: ExecutedCodeLogging var writeCompiledClasses: Boolean var outputConfig: OutputConfig } interface ReplForJupyter { fun eval(code: Code): EvalResult = eval(EvalRequestData(code)) fun eval(evalData: EvalRequestData): EvalResult fun <T> eval(execution: ExecutionCallback<T>): T fun evalEx(evalData: EvalRequestData): EvalResultEx fun evalOnShutdown(): List<EvalResult> fun checkComplete(code: Code): CheckResult suspend fun complete(code: Code, cursor: Int, callback: (CompletionResult) -> Unit) suspend fun listErrors(code: Code, callback: (ListErrorsResult) -> Unit) val homeDir: File? val currentClasspath: Collection<String> val currentClassLoader: ClassLoader val mavenRepositories: List<RepositoryCoordinates> val libraryResolver: LibraryResolver? val runtimeProperties: ReplRuntimeProperties val resolutionInfoProvider: ResolutionInfoProvider val throwableRenderersProcessor: ThrowableRenderersProcessor var outputConfig: OutputConfig val notebook: NotebookImpl val fileExtension: String val isEmbedded: Boolean get() = false } fun <T> ReplForJupyter.execute(callback: ExecutionCallback<T>): T { return eval(callback) } class ReplForJupyterImpl( override val resolutionInfoProvider: ResolutionInfoProvider, private val scriptClasspath: List<File> = emptyList(), override val homeDir: File? = null, override val mavenRepositories: List<RepositoryCoordinates> = listOf(), override val libraryResolver: LibraryResolver? = null, override val runtimeProperties: ReplRuntimeProperties = defaultRuntimeProperties, private val scriptReceivers: List<Any> = emptyList(), override val isEmbedded: Boolean = false, ) : ReplForJupyter, ReplOptions, BaseKernelHost, UserHandlesProvider { constructor( config: KernelConfig, runtimeProperties: ReplRuntimeProperties, scriptReceivers: List<Any> = emptyList() ) : this( config.resolutionInfoProvider, config.scriptClasspath, config.homeDir, config.mavenRepositories, config.libraryResolver, runtimeProperties, scriptReceivers, config.embedded ) override val currentBranch: String get() = runtimeProperties.currentBranch override val librariesDir: File = KERNEL_LIBRARIES.homeLibrariesDir(homeDir) private val libraryInfoSwitcher = getDefaultResolutionInfoSwitcher( resolutionInfoProvider, librariesDir, currentBranch ) private var outputConfigImpl = OutputConfig() private var currentKernelHost: KotlinKernelHost? = null override val notebook = NotebookImpl(runtimeProperties) val librariesScanner = LibrariesScanner(notebook) private val resourcesProcessor = LibraryResourcesProcessorImpl() override val sessionOptions: SessionOptions = object : SessionOptions { override var resolveSources: Boolean get() = resolver.resolveSources set(value) { resolver.resolveSources = value } } override var outputConfig get() = outputConfigImpl set(value) { // reuse output config instance, because it is already passed to CapturingOutputStream and stream parameters should be updated immediately outputConfigImpl.update(value) } override var trackClasspath: Boolean = false private var _executedCodeLogging: ExecutedCodeLogging = ExecutedCodeLogging.OFF override var executedCodeLogging: ExecutedCodeLogging get() = _executedCodeLogging set(value) { _executedCodeLogging = value internalEvaluator.logExecution = value != ExecutedCodeLogging.OFF } override var writeCompiledClasses: Boolean get() = internalEvaluator.writeCompiledClasses set(value) { internalEvaluator.writeCompiledClasses = value } private val internalVariablesMarkersProcessor: InternalVariablesMarkersProcessor = InternalVariablesMarkersProcessorImpl() private val resolver: JupyterScriptDependenciesResolver = JupyterScriptDependenciesResolverImpl(mavenRepositories) private val beforeCellExecution = mutableListOf<ExecutionCallback<*>>() private val shutdownCodes = mutableListOf<ExecutionCallback<*>>() private val ctx = KotlinContext() private val compilerArgsConfigurator: CompilerArgsConfigurator = DefaultCompilerArgsConfigurator( runtimeProperties.jvmTargetForSnippets ) private val librariesProcessor: LibrariesProcessor = LibrariesProcessorImpl(libraryResolver, runtimeProperties.version) private val magics = MagicsProcessor( FullMagicsHandler( this, librariesProcessor, libraryInfoSwitcher, ) ) private val completionMagics = CompletionMagicsProcessor(homeDir) private val errorsMagics = ErrorsMagicsProcessor() private val codePreprocessor = CompoundCodePreprocessor(magics) private val importsCollector: ScriptImportsCollector = ScriptImportsCollectorImpl() // Used for various purposes, i.e. completion and listing errors private val compilerConfiguration: ScriptCompilationConfiguration = getCompilationConfiguration( scriptClasspath, scriptReceivers, compilerArgsConfigurator, importsCollector = importsCollector ).with { refineConfiguration { onAnnotations(DependsOn::class, Repository::class, CompilerArgs::class, handler = ::onAnnotationsHandler) } } override val fileExtension: String get() = compilerConfiguration[ScriptCompilationConfiguration.fileExtension]!! private val ScriptCompilationConfiguration.classpath get() = this[ScriptCompilationConfiguration.dependencies] ?.filterIsInstance<JvmDependency>() ?.flatMap { it.classpath } .orEmpty() override val currentClasspath = compilerConfiguration.classpath.map { it.canonicalPath }.toMutableSet() private val currentSources = mutableSetOf<String>() private class FilteringClassLoader(parent: ClassLoader, val includeFilter: (String) -> Boolean) : ClassLoader(parent) { override fun loadClass(name: String?, resolve: Boolean): Class<*> { val c = if (name != null && includeFilter(name)) { parent.loadClass(name) } else parent.parent.loadClass(name) if (resolve) { resolveClass(c) } return c } } private val evaluatorConfiguration = ScriptEvaluationConfiguration { implicitReceivers.invoke(v = scriptReceivers) if (!isEmbedded) { jvm { val filteringClassLoader = FilteringClassLoader(ClassLoader.getSystemClassLoader()) { fqn -> listOf( "jupyter.kotlin.", "org.jetbrains.kotlinx.jupyter.api", "kotlin." ).any { fqn.startsWith(it) } || (fqn.startsWith("org.jetbrains.kotlin.") && !fqn.startsWith("org.jetbrains.kotlinx.jupyter.")) } val scriptClassloader = URLClassLoader(scriptClasspath.map { it.toURI().toURL() }.toTypedArray(), filteringClassLoader) baseClassLoader(scriptClassloader) } } constructorArgs(this@ReplForJupyterImpl) } private val jupyterCompiler by lazy { JupyterCompilerWithCompletion.create(compilerConfiguration, evaluatorConfiguration) } private val evaluator: BasicJvmReplEvaluator by lazy { BasicJvmReplEvaluator() } private val completer = KotlinCompleter() private val contextUpdater = ContextUpdater(ctx, evaluator) private val internalEvaluator: InternalEvaluator = InternalEvaluatorImpl( jupyterCompiler, evaluator, contextUpdater, executedCodeLogging != ExecutedCodeLogging.OFF, internalVariablesMarkersProcessor, ) private val renderersProcessor: ResultsRenderersProcessor = RenderersProcessorImpl(contextUpdater).apply { registerDefaultRenderers() } override val currentClassLoader: ClassLoader get() = internalEvaluator.lastClassLoader override val throwableRenderersProcessor: ThrowableRenderersProcessor = ThrowableRenderersProcessorImpl() private val fieldsProcessor: FieldsProcessor = FieldsProcessorImpl(contextUpdater) private val classAnnotationsProcessor: ClassAnnotationsProcessor = ClassAnnotationsProcessorImpl() private val fileAnnotationsProcessor: FileAnnotationsProcessor = FileAnnotationsProcessorImpl(ScriptDependencyAnnotationHandlerImpl(resolver), compilerArgsConfigurator, jupyterCompiler, this) private val interruptionCallbacksProcessor: InterruptionCallbacksProcessor = InterruptionCallbacksProcessorImpl(this) override fun checkComplete(code: String) = jupyterCompiler.checkComplete(code) internal val sharedContext = SharedReplContext( classAnnotationsProcessor, fileAnnotationsProcessor, fieldsProcessor, renderersProcessor, throwableRenderersProcessor, codePreprocessor, resourcesProcessor, librariesProcessor, librariesScanner, notebook, beforeCellExecution, shutdownCodes, internalEvaluator, this, internalVariablesMarkersProcessor, interruptionCallbacksProcessor, ).also { notebook.sharedReplContext = it } private var evalContextEnabled = false private fun <T> withEvalContext(action: () -> T): T { return synchronized(this) { evalContextEnabled = true try { action() } finally { evalContextEnabled = false } } } private val executor: CellExecutor = CellExecutorImpl(sharedContext) private fun onAnnotationsHandler(context: ScriptConfigurationRefinementContext): ResultWithDiagnostics<ScriptCompilationConfiguration> { return if (evalContextEnabled) fileAnnotationsProcessor.process(context, currentKernelHost!!) else context.compilationConfiguration.asSuccess() } @TestOnly @Suppress("unused") private fun printVariables(isHtmlFormat: Boolean = false) = log.debug( if (isHtmlFormat) notebook.variablesReportAsHTML() else notebook.variablesReport() ) @TestOnly @Suppress("unused") private fun printUsagesInfo(cellId: Int, usedVariables: Set<String>?) { log.debug(buildString { if (usedVariables == null || usedVariables.isEmpty()) { append("No usages for cell $cellId") return@buildString } append("Usages for cell $cellId:\n") usedVariables.forEach { append(it + "\n") } }) } override fun evalEx(evalData: EvalRequestData): EvalResultEx { return withEvalContext { rethrowAsLibraryException(LibraryProblemPart.BEFORE_CELL_CALLBACKS) { beforeCellExecution.forEach { executor.execute(it) } } var cell: CodeCellImpl? = null val compiledData: SerializedCompiledScriptsData val newImports: List<String> val result = try { log.debug("Current cell id: ${evalData.jupyterId}") executor.execute(evalData.code, evalData.displayHandler, currentCellId = evalData.jupyterId - 1) { internalId, codeToExecute -> if (evalData.storeHistory) { cell = notebook.addCell(internalId, codeToExecute, EvalData(evalData)) } } } finally { compiledData = internalEvaluator.popAddedCompiledScripts() newImports = importsCollector.popAddedImports() } cell?.resultVal = result.result.value val rendered = result.result.let { log.catchAll { renderersProcessor.renderResult(executor, it) } }?.let { log.catchAll { if (it is Renderable) it.render(notebook) else it } } val newClasspath = log.catchAll { updateClasspath() } ?: emptyList() val newSources = log.catchAll { updateSources() } ?: emptyList() val variablesStateUpdate = notebook.variablesState.mapValues { "" } EvalResultEx( result.result.value, rendered, result.scriptInstance, result.result.name, EvaluatedSnippetMetadata(newClasspath, newSources, compiledData, newImports, variablesStateUpdate), ) } } override fun eval(evalData: EvalRequestData): EvalResult { return evalEx(evalData).run { EvalResult(renderedValue, metadata) } } override fun <T> eval(execution: ExecutionCallback<T>): T { return synchronized(this) { executor.execute(execution) } } override fun evalOnShutdown(): List<EvalResult> { return shutdownCodes.map { val res = log.catchAll { rethrowAsLibraryException(LibraryProblemPart.SHUTDOWN) { executor.execute(it) } } EvalResult(res) } } /** * Updates current classpath with newly resolved libraries paths * Also, prints information about resolved libraries to stdout if [trackClasspath] is true * * @return Newly resolved classpath */ private fun updateClasspath(): Classpath { val resolvedClasspath = resolver.popAddedClasspath().map { it.canonicalPath } if (resolvedClasspath.isEmpty()) return emptyList() val (oldClasspath, newClasspath) = resolvedClasspath.partition { it in currentClasspath } currentClasspath.addAll(newClasspath) if (trackClasspath) { val sb = StringBuilder() if (newClasspath.isNotEmpty()) { sb.appendLine("${newClasspath.count()} new paths were added to classpath:") newClasspath.sortedBy { it }.forEach { sb.appendLine(it) } } if (oldClasspath.isNotEmpty()) { sb.appendLine("${oldClasspath.count()} resolved paths were already in classpath:") oldClasspath.sortedBy { it }.forEach { sb.appendLine(it) } } sb.appendLine("Current classpath size: ${currentClasspath.count()}") println(sb.toString()) } return newClasspath } private fun updateSources(): Classpath { val resolvedClasspath = resolver.popAddedSources().map { it.canonicalPath } val newClasspath = resolvedClasspath.filter { it !in currentSources } currentSources.addAll(newClasspath) return newClasspath } private val completionQueue = LockQueue<CompletionResult, CompletionArgs>() override suspend fun complete(code: String, cursor: Int, callback: (CompletionResult) -> Unit) = doWithLock( CompletionArgs(code, cursor, callback), completionQueue, CompletionResult.Empty(code, cursor), ::doComplete ) private fun doComplete(args: CompletionArgs): CompletionResult { if (looksLikeReplCommand(args.code)) return doCommandCompletion(args.code, args.cursor) val preprocessed = completionMagics.process(args.code, args.cursor) if (preprocessed.cursorInsideMagic) { return KotlinCompleter.getResult(args.code, args.cursor, preprocessed.completions) } return completer.complete( jupyterCompiler.completer, compilerConfiguration, args.code, preprocessed.code, jupyterCompiler.nextCounter(), args.cursor ) } private val listErrorsQueue = LockQueue<ListErrorsResult, ListErrorsArgs>() override suspend fun listErrors(code: String, callback: (ListErrorsResult) -> Unit) = doWithLock(ListErrorsArgs(code, callback), listErrorsQueue, ListErrorsResult(code), ::doListErrors) private fun doListErrors(args: ListErrorsArgs): ListErrorsResult { if (looksLikeReplCommand(args.code)) return reportCommandErrors(args.code) val preprocessingResult = errorsMagics.process(args.code) val errorsList = preprocessingResult.diagnostics + jupyterCompiler.listErrors(preprocessingResult.code) return ListErrorsResult(args.code, errorsList) } private fun <T, Args : LockQueueArgs<T>> doWithLock( args: Args, queue: LockQueue<T, Args>, default: T, action: (Args) -> T ) { queue.add(args) val result = synchronized(this) { val lastArgs = queue.get() if (lastArgs !== args) { default } else { action(args) } } args.callback(result) } private interface LockQueueArgs<T> { val callback: (T) -> Unit } private data class CompletionArgs( val code: String, val cursor: Int, override val callback: (CompletionResult) -> Unit ) : LockQueueArgs<CompletionResult> private data class ListErrorsArgs(val code: String, override val callback: (ListErrorsResult) -> Unit) : LockQueueArgs<ListErrorsResult> @JvmInline private value class LockQueue<T, Args : LockQueueArgs<T>>( private val args: AtomicReference<Args?> = AtomicReference() ) { fun add(args: Args) { this.args.set(args) } fun get(): Args { return args.get()!! } } init { log.info("Starting kotlin REPL engine. Compiler version: ${KotlinCompilerVersion.VERSION}") log.info("Kernel version: ${runtimeProperties.version}") log.info("Classpath used in script: $scriptClasspath") } override fun <T> withHost(currentHost: KotlinKernelHost, callback: () -> T): T { try { currentKernelHost = currentHost return callback() } finally { currentKernelHost = null } } override val host: KotlinKernelHost? get() = currentKernelHost }
apache-2.0
7d636e62daf1358b1a4f83c6133c4a75
37.549536
195
0.708027
5.070861
false
true
false
false
fredyw/leetcode
src/main/kotlin/leetcode/Problem1541.kt
1
1026
package leetcode import java.util.* /** * https://leetcode.com/problems/minimum-insertions-to-balance-a-parentheses-string/ */ class Problem1541 { fun minInsertions(s: String): Int { var answer = 0 val stack = Stack<Char>() var i = 0 while (i < s.length) { if (s[i] == '(') { stack.add(s[i]) i++ } else if (s[i] == ')' && (i + 1 == s.length || s[i + 1] != ')')) { if (stack.isEmpty()) { answer += 2 } else { stack.pop() answer++ } i++ } else if (s[i] == ')' && s[i + 1] == ')') { if (stack.isEmpty()) { answer++ } else { stack.pop() } i += 2 } } while (!stack.isEmpty()) { answer += 2 stack.pop() } return answer } }
mit
14a43de7bdc7173c663d0adf25bd0a86
24.02439
84
0.339181
4.187755
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepic/droid/ui/activities/SplashActivity.kt
1
6025
package org.stepic.droid.ui.activities import android.annotation.TargetApi import android.content.Intent import android.content.pm.ShortcutInfo import android.content.pm.ShortcutManager import android.content.res.Resources import android.graphics.drawable.Icon import android.os.Bundle import androidx.annotation.DrawableRes import androidx.annotation.StringRes import com.google.firebase.remoteconfig.FirebaseRemoteConfig import io.branch.referral.Branch import org.stepic.droid.R import org.stepic.droid.analytic.AmplitudeAnalytic import org.stepic.droid.analytic.Analytic import org.stepic.droid.analytic.BranchParams import org.stepic.droid.analytic.experiments.OnboardingSplitTestVersion2 import org.stepic.droid.base.App import org.stepic.droid.configuration.RemoteConfig import org.stepic.droid.core.presenters.SplashPresenter import org.stepic.droid.core.presenters.contracts.SplashView import org.stepic.droid.util.AppConstants import org.stepic.droid.util.defaultLocale import org.stepik.android.view.routing.deeplink.BranchRoute import java.util.Arrays import javax.inject.Inject class SplashActivity : BackToExitActivityBase(), SplashView { companion object { private const val RUSSIAN_LANGUAGE_CODE = "ru" } @Inject internal lateinit var splashPresenter: SplashPresenter @Inject internal lateinit var analytics: Analytic @Inject internal lateinit var firebaseRemoteConfig: FirebaseRemoteConfig @Inject internal lateinit var onboardingSplitTestVersion2: OnboardingSplitTestVersion2 private val locale = Resources.getSystem().configuration.defaultLocale override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) App.componentManager().splashComponent().inject(this) splashPresenter.attachView(this) // if (!isTaskRoot) { // finish() // return // } defineShortcuts() } private fun defineShortcuts() { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.N_MR1) { return } val shortcutManager = getSystemService(ShortcutManager::class.java) ?: return val catalogIntent = screenManager.getCatalogIntent(applicationContext) catalogIntent.action = AppConstants.OPEN_SHORTCUT_CATALOG val catalogShortcut = createShortcutInfo(AppConstants.CATALOG_SHORTCUT_ID, R.string.catalog_title, catalogIntent, R.drawable.ic_shortcut_find_courses) val profileIntent = screenManager.getMyProfileIntent(applicationContext) profileIntent.action = AppConstants.OPEN_SHORTCUT_PROFILE val profileShortcut = createShortcutInfo(AppConstants.PROFILE_SHORTCUT_ID, R.string.profile_title, profileIntent, R.drawable.ic_shortcut_profile) shortcutManager.dynamicShortcuts = Arrays.asList(catalogShortcut, profileShortcut) } @TargetApi(25) private fun createShortcutInfo(id: String, @StringRes titleRes: Int, catalogIntent: Intent, @DrawableRes iconRes: Int): ShortcutInfo { val title = getString(titleRes) return ShortcutInfo.Builder(this, id) .setShortLabel(title) .setLongLabel(title) .setIcon(Icon.createWithResource(this, iconRes)) .setIntent(catalogIntent) .build() } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) this.intent = intent } override fun onStart() { super.onStart() val uri = intent?.data if (uri == null) { splashPresenter.onSplashCreated() } else { Branch .sessionBuilder(this) .withCallback { referringParams, error -> if (error == null && referringParams != null && referringParams.has(BranchParams.FIELD_CAMPAIGN)) { analytics.reportAmplitudeEvent(AmplitudeAnalytic.Branch.LINK_OPENED, mapOf( AmplitudeAnalytic.Branch.PARAM_CAMPAIGN to referringParams[BranchParams.FIELD_CAMPAIGN], AmplitudeAnalytic.Branch.IS_FIRST_SESSION to referringParams.optBoolean(BranchParams.IS_FIRST_SESSION, false) )) } splashPresenter.onSplashCreated(referringParams) } .withData(uri) .init() } } override fun onDestroy() { super.onDestroy() splashPresenter.detachView(this) if (isFinishing) { App.componentManager().releaseSplashComponent() } } override fun onShowLaunch() { screenManager.showLaunchFromSplash(this) finish() } override fun onShowHome() { screenManager.showMainFeedFromSplash(this) finish() } override fun onShowCatalog() { screenManager.showMainFeed(this, MainFeedActivity.CATALOG_INDEX) } override fun onShowOnboarding() { if (locale.language == RUSSIAN_LANGUAGE_CODE && firebaseRemoteConfig.getString(RemoteConfig.PERSONALIZED_ONBOARDING_COURSE_LISTS).isNotEmpty()) { when (onboardingSplitTestVersion2.currentGroup) { OnboardingSplitTestVersion2.Group.Control -> screenManager.showOnboarding(this) OnboardingSplitTestVersion2.Group.Personalized -> screenManager.showLaunchScreen(this) OnboardingSplitTestVersion2.Group.None -> screenManager.showLaunchFromSplash(this) OnboardingSplitTestVersion2.Group.ControlPersonalized -> screenManager.showOnboarding(this) } } else { sharedPreferenceHelper.setPersonalizedOnboardingWasShown() screenManager.showOnboarding(this) } finish() } override fun onDeepLinkRoute(route: BranchRoute) { screenManager.openDeepLink(this, route) finish() } }
apache-2.0
5039e53d0fbf586b66e5822a27400096
35.737805
158
0.681992
5.033417
false
true
false
false
jrenner/libgdx-kotlin-extensions
src/org/jrenner/libgdx/kotlin/Vector.kt
1
1141
package org.jrenner.libgdx.kotlin import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.math.Vector3 import com.badlogic.gdx.math.Quaternion // Vector2 fun Vector2.plus(v : Vector2) : Vector2 { return this.add(v)!! } fun Vector2.minus(v : Vector2) : Vector2 { return this.sub(v)!! } fun Vector2.times(v : Vector2) : Vector2 { return this.scl(v)!! } fun Vector2.times(f : Float) : Vector2 { return this.scl(f)!! } fun Vector2.div(v : Vector2) : Vector2 { this.x /= v.x this.y /= v.y return this } fun Vector2.div(f : Float) : Vector2 { this.x /= f this.y /= f return this } // Vector3 fun Vector3.plus(v : Vector3) : Vector3 { return this.add(v)!! } fun Vector3.minus(v : Vector3) : Vector3 { return this.sub(v)!! } fun Vector3.times(v : Vector3) : Vector3 { return this.scl(v)!! } fun Vector3.times(f : Float) : Vector3 { return this.scl(f)!! } fun Vector3.div(v : Vector3) : Vector3 { this.x /= v.x this.y /= v.y this.z /= v.z return this } fun Vector3.div(f : Float) : Vector3 { this.x /= f this.y /= f this.z /= f return this }
apache-2.0
14b1b740cc0162fbca416df46a45d0a4
16.029851
42
0.611744
2.647332
false
false
false
false
StepicOrg/stepic-android
model/src/main/java/org/stepik/android/model/util/ParcelableExtensions.kt
1
1869
package org.stepik.android.model.util import android.os.Parcel import android.os.Parcelable import ru.nobird.android.core.model.putNullable import java.util.Date private fun getParcelableWriter(flags: Int): Parcel.(Parcelable) -> Unit = { writeParcelable(it, flags) } private fun <T: Parcelable> getParcelableReader(classLoader: ClassLoader): Parcel.() -> T? = { readParcelable(classLoader) } fun <K : Parcelable, V : Parcelable> Parcel.writeMapCustom(map: Map<K, V>, flags: Int) = writeMap(map, getParcelableWriter(flags), getParcelableWriter(flags)) fun <V : Parcelable> Parcel.writeMapCustomString(map: Map<String, V>, flags: Int) = writeMap(map, Parcel::writeString, getParcelableWriter(flags)) inline fun <K, V> Parcel.writeMap(map: Map<K, V>, writeKey: Parcel.(K) -> Unit, writeVal: Parcel.(V) -> Unit) { writeInt(map.size) for ((key, value) in map.entries) { writeKey(key) writeVal(value) } } inline fun <K, V> Parcel.readMap(readKey: Parcel.() -> K?, readVal: Parcel.() -> V?): Map<K, V> { val size = readInt() val map = HashMap<K, V>(size) for (i in 0 until size) { val key = readKey() val value = readVal() key?.let { map.putNullable(it, value) } } return map } fun <K : Parcelable, V : Parcelable> Parcel.readMapCustom(classLoaderKey: ClassLoader, classLoaderValue: ClassLoader): Map<K, V> = readMap(getParcelableReader(classLoaderKey), getParcelableReader(classLoaderValue)) fun <V : Parcelable> Parcel.readMapCustomString(classLoaderValue: ClassLoader): Map<String, V> = readMap(Parcel::readString, getParcelableReader(classLoaderValue)) internal const val NO_VALUE = -1L fun Parcel.writeDate(value: Date?) = writeLong(value?.time ?: NO_VALUE) fun Parcel.readDate(): Date? = readLong().takeIf { it != NO_VALUE }?.let(::Date)
apache-2.0
60d2755fe31139582838eb6f859d9303
37.163265
130
0.686998
3.615087
false
false
false
false
walleth/walleth
app/src/main/java/org/walleth/overview/OnboardingController.kt
1
1703
package org.walleth.overview import android.app.Activity import kotlinx.android.synthetic.main.activity_overview.* import org.ligi.tracedroid.sending.sendTraceDroidStackTracesIfExist import org.walleth.R import org.walleth.data.config.Settings import uk.co.deanwild.materialshowcaseview.IShowcaseListener import uk.co.deanwild.materialshowcaseview.MaterialShowcaseView class OnboardingController(val activity: Activity, private val viewModel: TransactionListViewModel, val settings: Settings) { private val showcaseView by lazy { MaterialShowcaseView.Builder(activity) .setTarget(activity.receive_button) .setListener(object : IShowcaseListener { override fun onShowcaseDismissed(showcaseView: MaterialShowcaseView?) { dismiss() } override fun onShowcaseDisplayed(showcaseView: MaterialShowcaseView?) = Unit }) .setDismissText(android.R.string.ok) .setTargetTouchable(true) .setContentText(R.string.onboard_showcase_message) .build() } fun install() { if (!settings.onboardingDone) { viewModel.isOnboardingVisible.value = true showcaseView.show(activity) settings.onboardingDone = true } else { sendTraceDroidStackTracesIfExist("[email protected]", activity) } } fun dismiss() { if (viewModel.isOnboardingVisible.value == true) { viewModel.isOnboardingVisible.value = false showcaseView.hide() } } }
gpl-3.0
da305b90545e5c03abb1dd4927e205f7
33.08
96
0.632413
4.994135
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt
1
9664
package info.nightscout.androidaps.utils import android.Manifest import android.annotation.SuppressLint import android.bluetooth.BluetoothAdapter import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.os.PowerManager import android.provider.Settings import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentActivity import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.DaggerAppCompatActivityWithResult import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidPermission @Inject constructor( val rh: ResourceHelper, val rxBus: RxBus, val injector: HasAndroidInjector ) { private var permissionBatteryOptimizationFailed = false @SuppressLint("BatteryLife") fun askForPermission(activity: FragmentActivity, permissions: Array<String>) { var test = false var testBattery = false for (s in permissions) { test = test || ContextCompat.checkSelfPermission(activity, s) != PackageManager.PERMISSION_GRANTED if (s == Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) { val powerManager = activity.getSystemService(Context.POWER_SERVICE) as PowerManager val packageName = activity.packageName testBattery = testBattery || !powerManager.isIgnoringBatteryOptimizations(packageName) } } if (test) { if (activity is DaggerAppCompatActivityWithResult) try { activity.requestMultiplePermissions.launch(permissions) } catch (ignored: IllegalStateException) { ToastUtils.errorToast(activity, rh.gs(R.string.error_asking_for_permissions)) } } if (testBattery) { try { if (activity is DaggerAppCompatActivityWithResult) try { activity.callForBatteryOptimization.launch(null) } catch (ignored: IllegalStateException) { ToastUtils.errorToast(activity, rh.gs(R.string.error_asking_for_permissions)) } } catch (e: ActivityNotFoundException) { permissionBatteryOptimizationFailed = true OKDialog.show(activity, rh.gs(R.string.permission), rh.gs(R.string.alert_dialog_permission_battery_optimization_failed)) { activity.recreate() } } } } fun askForPermission(activity: FragmentActivity, permission: String) = askForPermission(activity, arrayOf(permission)) fun permissionNotGranted(context: Context, permission: String): Boolean { var selfCheck = ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED if (permission == Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) { if (!permissionBatteryOptimizationFailed) { val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager val packageName = context.packageName selfCheck = selfCheck && powerManager.isIgnoringBatteryOptimizations(packageName) } } return !selfCheck } @Synchronized fun notifyForSMSPermissions(activity: FragmentActivity, smsCommunicatorPlugin: SmsCommunicatorPlugin) { if (smsCommunicatorPlugin.isEnabled()) { if (permissionNotGranted(activity, Manifest.permission.RECEIVE_SMS)) { val notification = NotificationWithAction(injector, Notification.PERMISSION_SMS, rh.gs(R.string.smscommunicator_missingsmspermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.RECEIVE_SMS, Manifest.permission.SEND_SMS, Manifest.permission.RECEIVE_MMS)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_SMS)) // Following is a bug in Android 8 // if (permissionNotGranted(activity, Manifest.permission.READ_PHONE_STATE)) { // val notification = NotificationWithAction(injector, Notification.PERMISSION_PHONE_STATE, rh.gs(R.string.smscommunicator_missingphonestatepermission), Notification.URGENT) // notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.READ_PHONE_STATE)) } // rxBus.send(EventNewNotification(notification)) // } else rxBus.send(EventDismissNotification(Notification.PERMISSION_PHONE_STATE)) } } @SuppressLint("MissingPermission") @Synchronized fun notifyForBtConnectPermission(activity: FragmentActivity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { // Manifest.permission.BLUETOOTH_CONNECT if (permissionNotGranted(activity, Manifest.permission.BLUETOOTH_CONNECT) || permissionNotGranted(activity, Manifest.permission.BLUETOOTH_SCAN)) { val notification = NotificationWithAction(injector, Notification.PERMISSION_BT, rh.gs(R.string.needconnectpermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT)) } rxBus.send(EventNewNotification(notification)) } else { activity.startActivity(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)) rxBus.send(EventDismissNotification(Notification.PERMISSION_BT)) } } } @Synchronized fun notifyForBatteryOptimizationPermission(activity: FragmentActivity) { if (permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)) { val notification = NotificationWithAction(injector, Notification.PERMISSION_BATTERY, rh.gs(R.string.needwhitelisting, rh.gs(R.string.app_name)), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_BATTERY)) } @Synchronized fun notifyForStoragePermission(activity: FragmentActivity) { if (permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { val notification = NotificationWithAction(injector, Notification.PERMISSION_STORAGE, rh.gs(R.string.needstoragepermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_STORAGE)) } @Synchronized fun notifyForLocationPermissions(activity: FragmentActivity) { if (permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION)) { val notification = NotificationWithAction(injector, Notification.PERMISSION_LOCATION, rh.gs(R.string.needlocationpermission), Notification.URGENT) notification.action(R.string.request) { askForPermission(activity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)) } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_LOCATION)) } @Synchronized fun notifyForSystemWindowPermissions(activity: FragmentActivity) { // Check if Android Q or higher if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { if (!Settings.canDrawOverlays(activity)) { val notification = NotificationWithAction(injector, Notification.PERMISSION_SYSTEM_WINDOW, rh.gs(R.string.needsystemwindowpermission), Notification.URGENT) notification.action(R.string.request) { // Check if Android Q or higher if (Build.VERSION.SDK_INT > Build.VERSION_CODES.P) { // Show alert dialog to the user saying a separate permission is needed // Launch the settings activity if the user prefers val intent = Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + activity.packageName) ) activity.startActivity(intent) } } rxBus.send(EventNewNotification(notification)) } else rxBus.send(EventDismissNotification(Notification.PERMISSION_SYSTEM_WINDOW)) } } }
agpl-3.0
8efba2c1d18134b38181ba25d5303af5
56.874251
189
0.708092
5.113228
false
false
false
false
maiconhellmann/pomodoro
app/src/main/kotlin/br/com/maiconhellmann/pomodoro/ui/history/HistoryAdapter.kt
1
2946
package br.com.maiconhellmann.pomodoro.ui.history import android.support.v7.widget.RecyclerView import android.text.format.DateUtils import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import br.com.maiconhellmann.pomodoro.R import br.com.maiconhellmann.pomodoro.data.model.Pomodoro import br.com.maiconhellmann.pomodoro.util.extension.gone import br.com.maiconhellmann.pomodoro.util.extension.leftPadding import br.com.maiconhellmann.pomodoro.util.extension.visible import kotlinx.android.synthetic.main.fragment_pomodoro.* import kotlinx.android.synthetic.main.item_history_pomodoro.view.* import rx.Observable import rx.subjects.PublishSubject import javax.inject.Inject class HistoryAdapter @Inject constructor() : RecyclerView.Adapter<HistoryAdapter.PomodoroViewHolder>() { private val clickSubject = PublishSubject.create<Pomodoro>() val clickEvent: Observable<Pomodoro> = clickSubject var dataList: List<Pomodoro> = emptyList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PomodoroViewHolder { val itemView = LayoutInflater.from(parent.context) .inflate(R.layout.item_history_pomodoro, parent, false) return PomodoroViewHolder(itemView) } override fun onBindViewHolder(holder: PomodoroViewHolder, position: Int) { val data = dataList[position] val now = System.currentTimeMillis() val header = DateUtils.getRelativeTimeSpanString(data.startDateTime.time, now, DateUtils.DAY_IN_MILLIS) if(position > 0){ val dataPrevius = dataList[position-1] val previousHeader = DateUtils.getRelativeTimeSpanString(dataPrevius.startDateTime.time, now, DateUtils.DAY_IN_MILLIS) if(previousHeader != header){ holder.itemView.tvHeader.visible() }else{ holder.itemView.tvHeader.gone() } }else{ holder.itemView.tvHeader.visible() } holder.itemView.tvHeader.text = header val relativeTimeStarted = DateUtils.getRelativeTimeSpanString(data.startDateTime.time).toString() holder.itemView.tvElapsedTime.text = relativeTimeStarted holder.itemView.tvStatus.text = data.status.name val elapsedTime = (data.endDateTime.time - data.startDateTime.time)/1000 val sec = elapsedTime % 60 val min = elapsedTime / 60 % 60 holder.itemView.tvTime.text = holder.itemView.context.getString( R.string.min_sec, min.toString().leftPadding(2, "0"), sec.toString().leftPadding(2, "0")) } override fun getItemCount(): Int = dataList.size inner class PomodoroViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { init { itemView.setOnClickListener{ clickSubject.onNext(dataList[layoutPosition]) } } } }
apache-2.0
9167adba289763708ac9e018113f04be
34.926829
130
0.703666
4.546296
false
false
false
false
Heiner1/AndroidAPS
omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/driver/pod/response/SetUniqueIdResponse.kt
1
3857
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.PodStatus import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.ResponseType.ActivationResponseType import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.byValue import java.nio.ByteBuffer class SetUniqueIdResponse( encoded: ByteArray ) : ActivationResponseBase(ActivationResponseType.SET_UNIQUE_ID_RESPONSE, encoded) { val messageType: Byte = encoded[0] val messageLength: Short = (encoded[1].toInt() and 0xff).toShort() val pulseVolumeInTenThousandthMicroLiter: Short = ByteBuffer.wrap(byteArrayOf(encoded[2], encoded[3])).short val pumpRate: Short = (encoded[4].toInt() and 0xff).toShort() val primePumpRate: Short = (encoded[5].toInt() and 0xff).toShort() val numberOfEngagingClutchDrivePulses: Short = (encoded[6].toInt() and 0xff).toShort() val numberOfPrimePulses: Short = (encoded[7].toInt() and 0xff).toShort() val podExpirationTimeInHours: Short = (encoded[8].toInt() and 0xff).toShort() val firmwareVersionMajor: Short = (encoded[9].toInt() and 0xff).toShort() val firmwareVersionMinor: Short = (encoded[10].toInt() and 0xff).toShort() val firmwareVersionInterim: Short = (encoded[11].toInt() and 0xff).toShort() val bleVersionMajor: Short = (encoded[12].toInt() and 0xff).toShort() val bleVersionMinor: Short = (encoded[13].toInt() and 0xff).toShort() val bleVersionInterim: Short = (encoded[14].toInt() and 0xff).toShort() val productId: Short = (encoded[15].toInt() and 0xff).toShort() val podStatus: PodStatus = byValue(encoded[16], PodStatus.UNKNOWN) val lotNumber: Long = ByteBuffer.wrap( byteArrayOf( 0, 0, 0, 0, encoded[17], encoded[18], encoded[19], encoded[20] ) ).long val podSequenceNumber: Long = ByteBuffer.wrap( byteArrayOf( 0, 0, 0, 0, encoded[21], encoded[22], encoded[23], encoded[24] ) ).long val uniqueIdReceivedInCommand: Long = ByteBuffer.wrap( byteArrayOf( 0, 0, 0, 0, encoded[25], encoded[26], encoded[27], encoded[28] ) ).long override fun toString(): String { return "SetUniqueIdResponse{" + "messageType=" + messageType + ", messageLength=" + messageLength + ", pulseVolume=" + pulseVolumeInTenThousandthMicroLiter + ", pumpRate=" + pumpRate + ", primePumpRate=" + primePumpRate + ", numberOfEngagingClutchDrivePulses=" + numberOfEngagingClutchDrivePulses + ", numberOfPrimePulses=" + numberOfPrimePulses + ", podExpirationTimeInHours=" + podExpirationTimeInHours + ", softwareVersionMajor=" + firmwareVersionMajor + ", softwareVersionMinor=" + firmwareVersionMinor + ", softwareVersionInterim=" + firmwareVersionInterim + ", bleVersionMajor=" + bleVersionMajor + ", bleVersionMinor=" + bleVersionMinor + ", bleVersionInterim=" + bleVersionInterim + ", productId=" + productId + ", podStatus=" + podStatus + ", lotNumber=" + lotNumber + ", podSequenceNumber=" + podSequenceNumber + ", uniqueIdReceivedInCommand=" + uniqueIdReceivedInCommand + ", activationResponseType=" + activationResponseType + ", responseType=" + responseType + ", encoded=" + encoded.contentToString() + '}' } }
agpl-3.0
b2fbfba53740ae3beca034ec33978190
41.384615
115
0.618875
4.368063
false
false
false
false
Heiner1/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSBasalSetTemporaryBasal.kt
1
1970
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRSPacketAPSBasalSetTemporaryBasal( injector: HasAndroidInjector, private var percent: Int ) : DanaRSPacket(injector) { var temporaryBasalRatio = 0 var temporaryBasalDuration = 0 var error = 0 init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BASAL__APS_SET_TEMPORARY_BASAL aapsLogger.debug(LTag.PUMPCOMM, "New message: percent: $percent") if (percent < 0) percent = 0 if (percent > 500) percent = 500 temporaryBasalRatio = percent if (percent < 100) { temporaryBasalDuration = PARAM30MIN aapsLogger.debug(LTag.PUMPCOMM, "APS Temp basal start percent: $percent duration 30 min") } else { temporaryBasalDuration = PARAM15MIN aapsLogger.debug(LTag.PUMPCOMM, "APS Temp basal start percent: $percent duration 15 min") } } override fun getRequestParams(): ByteArray { val request = ByteArray(3) request[0] = (temporaryBasalRatio and 0xff).toByte() request[1] = (temporaryBasalRatio ushr 8 and 0xff).toByte() request[2] = (temporaryBasalDuration and 0xff).toByte() return request } override fun handleMessage(data: ByteArray) { val result = byteArrayToInt(getBytes(data, DATA_START, 1)) if (result != 0) { failed = true aapsLogger.debug(LTag.PUMPCOMM, "Set APS temp basal start result: $result FAILED!!!") } else { failed = false aapsLogger.debug(LTag.PUMPCOMM, "Set APS temp basal start result: $result") } } override val friendlyName: String = "BASAL__APS_SET_TEMPORARY_BASAL" companion object { const val PARAM30MIN = 160 const val PARAM15MIN = 150 } }
agpl-3.0
ef9570c76a521ac7559da888f9fa1d09
32.982759
101
0.655838
4.592075
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/core/descriptorUtils.kt
1
6938
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.core import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.* import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.languageVersionSettings import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.lexer.KtModifierKeywordToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.OverridingUtil import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension import org.jetbrains.kotlin.resolve.findOriginalTopMostOverriddenDescriptors import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.resolve.scopes.utils.getImplicitReceiversHierarchy import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor import java.util.* fun DeclarationDescriptorWithVisibility.isVisible(from: DeclarationDescriptor, languageVersionSettings: LanguageVersionSettings): Boolean { return isVisible(from, null, languageVersionSettings = languageVersionSettings) } fun DeclarationDescriptorWithVisibility.isVisible( context: PsiElement, receiverExpression: KtExpression?, bindingContext: BindingContext, resolutionFacade: ResolutionFacade ): Boolean { val resolutionScope = context.getResolutionScope(bindingContext, resolutionFacade) val from = resolutionScope.ownerDescriptor return isVisible(from, receiverExpression, bindingContext, resolutionScope, resolutionFacade.languageVersionSettings) } private fun DeclarationDescriptorWithVisibility.isVisible( from: DeclarationDescriptor, receiverExpression: KtExpression?, bindingContext: BindingContext? = null, resolutionScope: LexicalScope? = null, languageVersionSettings: LanguageVersionSettings ): Boolean { if (DescriptorVisibilityUtils.isVisibleWithAnyReceiver(this, from, languageVersionSettings)) return true if (bindingContext == null || resolutionScope == null) return false // for extension it makes no sense to check explicit receiver because we need dispatch receiver which is implicit in this case if (receiverExpression != null && !isExtension) { val receiverType = bindingContext.getType(receiverExpression) ?: return false val explicitReceiver = ExpressionReceiver.create(receiverExpression, receiverType, bindingContext) return DescriptorVisibilityUtils.isVisible(explicitReceiver, this, from, languageVersionSettings) } else { return resolutionScope.getImplicitReceiversHierarchy().any { DescriptorVisibilityUtils.isVisible(it.value, this, from, languageVersionSettings) } } } private fun compareDescriptorsText(project: Project, d1: DeclarationDescriptor, d2: DeclarationDescriptor): Boolean { if (d1 == d2) return true if (d1.name != d2.name) return false val renderedD1 = IdeDescriptorRenderers.SOURCE_CODE.render(d1) val renderedD2 = IdeDescriptorRenderers.SOURCE_CODE.render(d2) if (renderedD1 == renderedD2) return true val declarations1 = DescriptorToSourceUtilsIde.getAllDeclarations(project, d1) val declarations2 = DescriptorToSourceUtilsIde.getAllDeclarations(project, d2) if (declarations1 == declarations2 && declarations1.isNotEmpty()) return true return false } fun compareDescriptors(project: Project, currentDescriptor: DeclarationDescriptor?, originalDescriptor: DeclarationDescriptor?): Boolean { if (currentDescriptor == originalDescriptor) return true if (currentDescriptor == null || originalDescriptor == null) return false if (currentDescriptor.name != originalDescriptor.name) return false if (originalDescriptor is SyntheticJavaPropertyDescriptor && currentDescriptor is SyntheticJavaPropertyDescriptor) { return compareDescriptors(project, currentDescriptor.getMethod, originalDescriptor.getMethod) } if (compareDescriptorsText(project, currentDescriptor, originalDescriptor)) return true if (originalDescriptor is CallableDescriptor && currentDescriptor is CallableDescriptor) { val overriddenOriginalDescriptor = originalDescriptor.findOriginalTopMostOverriddenDescriptors() val overriddenCurrentDescriptor = currentDescriptor.findOriginalTopMostOverriddenDescriptors() if (overriddenOriginalDescriptor.size != overriddenCurrentDescriptor.size) return false return overriddenCurrentDescriptor.zip(overriddenOriginalDescriptor).all { compareDescriptorsText(project, it.first, it.second) } } return false } fun DescriptorVisibility.toKeywordToken(): KtModifierKeywordToken = when (val normalized = normalize()) { DescriptorVisibilities.PUBLIC -> KtTokens.PUBLIC_KEYWORD DescriptorVisibilities.PROTECTED -> KtTokens.PROTECTED_KEYWORD DescriptorVisibilities.INTERNAL -> KtTokens.INTERNAL_KEYWORD else -> { if (DescriptorVisibilities.isPrivate(normalized)) { KtTokens.PRIVATE_KEYWORD } else { error("Unexpected visibility '$normalized'") } } } fun <D : CallableMemberDescriptor> D.getDirectlyOverriddenDeclarations(): Collection<D> { val result = LinkedHashSet<D>() for (overriddenDescriptor in overriddenDescriptors) { @Suppress("UNCHECKED_CAST") when (overriddenDescriptor.kind) { DECLARATION -> result.add(overriddenDescriptor as D) FAKE_OVERRIDE, DELEGATION -> result.addAll((overriddenDescriptor as D).getDirectlyOverriddenDeclarations()) SYNTHESIZED -> { //do nothing } else -> throw AssertionError("Unexpected callable kind ${overriddenDescriptor.kind}: $overriddenDescriptor") } } return OverridingUtil.filterOutOverridden(result) } fun <D : CallableMemberDescriptor> D.getDeepestSuperDeclarations(withThis: Boolean = true): Collection<D> { val overriddenDeclarations = DescriptorUtils.getAllOverriddenDeclarations(this) if (overriddenDeclarations.isEmpty() && withThis) { return setOf(this) } return overriddenDeclarations.filterNot(DescriptorUtils::isOverride) } fun <T : DeclarationDescriptor> T.unwrapIfFakeOverride(): T { return if (this is CallableMemberDescriptor) DescriptorUtils.unwrapFakeOverride(this) else this }
apache-2.0
e546f1600ffdcfe8e4dbd874e42e3859
46.197279
139
0.782646
5.528287
false
false
false
false
PolymerLabs/arcs
java/arcs/core/storage/StorageKey.kt
1
1510
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.storage /** Locator for a specific piece of data within the storage layer. */ abstract class StorageKey(val protocol: StorageKeyProtocol) { abstract fun toKeyString(): String /** * Creates a new [StorageKey] of the same type, replacing the component with the given one. * Callers must ensure that the component is unique (or sufficiently random) if they want the * returned storage key to be unique. Other, non-component, properties of the [StorageKey] will be * preserved (if any exist for the relevant [StorageKey] subclass). */ abstract fun newKeyWithComponent(component: String): StorageKey override fun toString(): String { return "${protocol.protocol}${toKeyString()}" } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other::class != this::class) return false return toString() == other.toString() } override fun hashCode() = toString().hashCode() } /** * This describes the metadata related to a [StorageKey] type. The [companion] object of a * [StorageKey] implementation should implement this interface. */ interface StorageKeySpec<T : StorageKey> : StorageKeyParser<T>
bsd-3-clause
15d4517079d6770ba7c94279288d9872
33.318182
100
0.718543
4.33908
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/activitylog/list/filter/ActivityLogTypeFilterViewHolder.kt
1
2151
package org.wordpress.android.ui.activitylog.list.filter import android.view.LayoutInflater import android.view.ViewGroup import android.widget.CheckBox import android.widget.TextView import androidx.annotation.LayoutRes import androidx.recyclerview.widget.RecyclerView import org.wordpress.android.R import org.wordpress.android.ui.activitylog.list.filter.ActivityLogTypeFilterViewModel.ListItemUiState import org.wordpress.android.ui.activitylog.list.filter.ActivityLogTypeFilterViewModel.ListItemUiState.ActivityType import org.wordpress.android.ui.activitylog.list.filter.ActivityLogTypeFilterViewModel.ListItemUiState.SectionHeader import org.wordpress.android.ui.utils.UiHelpers sealed class ActivityLogTypeFilterViewHolder(internal val parent: ViewGroup, @LayoutRes layout: Int) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(layout, parent, false)) { abstract fun onBind(uiState: ListItemUiState) class ActivityTypeViewHolder( parent: ViewGroup, private val uiHelpers: UiHelpers ) : ActivityLogTypeFilterViewHolder(parent, R.layout.activity_log_type_filter_item) { private val container = itemView.findViewById<ViewGroup>(R.id.container) private val activityType = itemView.findViewById<TextView>(R.id.activity_type) private val checkbox = itemView.findViewById<CheckBox>(R.id.checkbox) override fun onBind(uiState: ListItemUiState) { uiState as ActivityType uiHelpers.setTextOrHide(activityType, uiState.title) checkbox.isChecked = uiState.checked container.setOnClickListener { uiState.onClick.invoke() } } } class HeaderViewHolder( parent: ViewGroup, private val uiHelpers: UiHelpers ) : ActivityLogTypeFilterViewHolder(parent, R.layout.activity_log_type_filter_header) { private val headerTitle = itemView.findViewById<TextView>(R.id.header_title) override fun onBind(uiState: ListItemUiState) { uiState as SectionHeader uiHelpers.setTextOrHide(headerTitle, uiState.title) } } }
gpl-2.0
bad09e1de9603281e9a02ca0d96c957b
44.765957
116
0.752673
4.866516
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/reader/viewmodels/ReaderPostListViewModel.kt
1
10731
package org.wordpress.android.ui.reader.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineDispatcher import org.wordpress.android.R import org.wordpress.android.datasets.ReaderPostTable import org.wordpress.android.models.ReaderPost import org.wordpress.android.models.ReaderTag import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.modules.UI_THREAD import org.wordpress.android.ui.pages.SnackbarMessageHolder import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents import org.wordpress.android.ui.reader.discover.ReaderNavigationEvents.ShowSitePickerForResult import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.BLOCK_SITE import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.BOOKMARK import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.FOLLOW import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.LIKE import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.REBLOG import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.REPORT_POST import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.SITE_NOTIFICATIONS import org.wordpress.android.ui.reader.discover.ReaderPostCardActionType.TOGGLE_SEEN_STATUS import org.wordpress.android.ui.reader.discover.ReaderPostCardActionsHandler import org.wordpress.android.ui.reader.reblog.ReblogUseCase import org.wordpress.android.ui.reader.subfilter.SubfilterListItem import org.wordpress.android.ui.reader.tracker.ReaderTracker import org.wordpress.android.ui.reader.tracker.ReaderTrackerType import org.wordpress.android.ui.reader.usecases.BookmarkPostState.PreLoadPostContent import org.wordpress.android.ui.reader.usecases.ReaderSeenStatusToggleUseCase import org.wordpress.android.ui.reader.usecases.ReaderSiteFollowUseCase.FollowSiteState.FollowStatusChanged import org.wordpress.android.ui.utils.UiString.UiStringRes import org.wordpress.android.util.AppLog import org.wordpress.android.util.AppLog.T import org.wordpress.android.viewmodel.Event import org.wordpress.android.viewmodel.ScopedViewModel import javax.inject.Inject import javax.inject.Named class ReaderPostListViewModel @Inject constructor( private val readerPostCardActionsHandler: ReaderPostCardActionsHandler, private val reblogUseCase: ReblogUseCase, private val readerTracker: ReaderTracker, private val seenStatusToggleUseCase: ReaderSeenStatusToggleUseCase, @Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) : ScopedViewModel(mainDispatcher) { private var isStarted = false private var readerViewModel: ReaderViewModel? = null /** * Post which is about to be reblogged after the user selects a target site. */ private var pendingReblogPost: ReaderPost? = null private val _navigationEvents = MediatorLiveData<Event<ReaderNavigationEvents>>() val navigationEvents: LiveData<Event<ReaderNavigationEvents>> = _navigationEvents private val _snackbarEvents = MediatorLiveData<Event<SnackbarMessageHolder>>() val snackbarEvents: LiveData<Event<SnackbarMessageHolder>> = _snackbarEvents private val _preloadPostEvents = MediatorLiveData<Event<PreLoadPostContent>>() val preloadPostEvents = _preloadPostEvents private val _refreshPosts = MediatorLiveData<Event<Unit>>() val refreshPosts: LiveData<Event<Unit>> = _refreshPosts private val _updateFollowStatus = MediatorLiveData<FollowStatusChanged>() val updateFollowStatus: LiveData<FollowStatusChanged> = _updateFollowStatus fun start(readerViewModel: ReaderViewModel?) { this.readerViewModel = readerViewModel if (isStarted) { return } isStarted = true init() } private fun init() { readerPostCardActionsHandler.initScope(viewModelScope) _navigationEvents.addSource(readerPostCardActionsHandler.navigationEvents) { event -> val target = event.peekContent() if (target is ShowSitePickerForResult) { pendingReblogPost = target.post } _navigationEvents.value = event } _snackbarEvents.addSource(readerPostCardActionsHandler.snackbarEvents) { event -> _snackbarEvents.value = event } _preloadPostEvents.addSource(readerPostCardActionsHandler.preloadPostEvents) { event -> _preloadPostEvents.value = event } _refreshPosts.addSource(readerPostCardActionsHandler.refreshPosts) { event -> _refreshPosts.value = event } _updateFollowStatus.addSource(readerPostCardActionsHandler.followStatusUpdated) { data -> _updateFollowStatus.value = data } } /** * Handles reblog button action * * @param post post to reblog */ fun onReblogButtonClicked( post: ReaderPost, bookmarksList: Boolean, source: String ) { launch { readerPostCardActionsHandler.onAction( post, REBLOG, bookmarksList, source = source ) } } fun onBlockSiteButtonClicked( post: ReaderPost, bookmarksList: Boolean, source: String ) { launch { readerPostCardActionsHandler.onAction( post, BLOCK_SITE, bookmarksList, source = source ) } } fun onBookmarkButtonClicked( blogId: Long, postId: Long, isBookmarkList: Boolean, source: String ) { launch(bgDispatcher) { ReaderPostTable.getBlogPost(blogId, postId, true)?.let { readerPostCardActionsHandler.onAction( it, BOOKMARK, isBookmarkList, source = source ) } } } fun onFollowSiteClicked( post: ReaderPost, bookmarksList: Boolean, source: String ) { launch(bgDispatcher) { readerPostCardActionsHandler.onAction( post, FOLLOW, bookmarksList, source = source ) } } fun onSiteNotificationMenuClicked( blogId: Long, postId: Long, isBookmarkList: Boolean, source: String ) { launch(bgDispatcher) { ReaderPostTable.getBlogPost(blogId, postId, true)?.let { readerPostCardActionsHandler.onAction( it, SITE_NOTIFICATIONS, isBookmarkList, source = source ) } } } fun onLikeButtonClicked( post: ReaderPost, bookmarksList: Boolean, source: String ) { launch(bgDispatcher) { readerPostCardActionsHandler.onAction( post, LIKE, bookmarksList, source = source ) } } fun onReportPostButtonClicked( post: ReaderPost, bookmarksList: Boolean, source: String ) { launch(bgDispatcher) { readerPostCardActionsHandler.onAction( post, REPORT_POST, bookmarksList, source = source ) } } fun onToggleSeenStatusClicked( post: ReaderPost, bookmarksList: Boolean, source: String ) { launch(bgDispatcher) { readerPostCardActionsHandler.onAction( post, TOGGLE_SEEN_STATUS, bookmarksList, source = source ) } } fun onExternalPostOpened(post: ReaderPost) { launch(bgDispatcher) { seenStatusToggleUseCase.markPostAsSeenIfNecessary(post) } } /** * Handles site selection * * @param site selected site to reblog to */ fun onReblogSiteSelected(siteLocalId: Int) { launch { val state = reblogUseCase.onReblogSiteSelected(siteLocalId, pendingReblogPost) val navigationTarget = reblogUseCase.convertReblogStateToNavigationEvent(state) if (navigationTarget != null) { _navigationEvents.postValue(Event(navigationTarget)) } else { _snackbarEvents.postValue(Event(SnackbarMessageHolder(UiStringRes(R.string.reader_reblog_error)))) } pendingReblogPost = null } } fun onEmptyStateButtonTapped(tag: ReaderTag) { readerViewModel?.selectedTabChange(tag) } // TODO this is related to tracking time spent in reader - // we should move it to the parent but also keep it here for !isTopLevel :( fun onFragmentResume( isTopLevelFragment: Boolean, isSearch: Boolean, isFilterable: Boolean, subfilterListItem: SubfilterListItem? ) { AppLog.d( T.READER, "TRACK READER ReaderPostListFragment > START Count [mIsTopLevel = $isTopLevelFragment]" ) if (!isTopLevelFragment && !isSearch) { // top level is tracked in ReaderFragment, search is tracked in ReaderSearchActivity readerTracker.start(ReaderTrackerType.FILTERED_LIST) } // TODO check if the subfilter is set to a value and uncomment this code if (isFilterable && subfilterListItem?.isTrackedItem == true) { AppLog.d(T.READER, "TRACK READER ReaderPostListFragment > START Count SUBFILTERED_LIST") readerTracker.start(ReaderTrackerType.SUBFILTERED_LIST) } } fun onFragmentPause(isTopLevelFragment: Boolean, isSearch: Boolean, isFilterable: Boolean) { AppLog.d( T.READER, "TRACK READER ReaderPostListFragment > STOP Count [mIsTopLevel = $isTopLevelFragment]" ) if (!isTopLevelFragment && !isSearch) { // top level is tracked in ReaderFragment, search is tracked in ReaderSearchActivity readerTracker.stop(ReaderTrackerType.FILTERED_LIST) } if (isFilterable) { readerTracker.stop(ReaderTrackerType.SUBFILTERED_LIST) } } }
gpl-2.0
102a070d1dcc992b4afe5dbdb3863906
33.954397
114
0.650172
5.278406
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/impl/mixin/RustFnItemImplMixin.kt
1
1210
package org.rust.lang.core.psi.impl.mixin import com.intellij.lang.ASTNode import com.intellij.openapi.util.Iconable import com.intellij.psi.stubs.IStubElementType import org.rust.lang.core.psi.RustDeclaringElement import org.rust.lang.core.psi.RustFnItem import org.rust.ide.icons.RustIcons import org.rust.ide.icons.addTestMark import org.rust.ide.icons.addVisibilityIcon import org.rust.lang.core.psi.impl.RustItemImpl import org.rust.lang.core.stubs.RustItemStub import javax.swing.Icon public abstract class RustFnItemImplMixin : RustItemImpl , RustFnItem { constructor(node: ASTNode) : super(node) constructor(stub: RustItemStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override val declarations: Collection<RustDeclaringElement> get() = fnParams?.paramList.orEmpty().filterNotNull() override fun getIcon(flags: Int): Icon? { val icon = if (isTest) RustIcons.FUNCTION.addTestMark() else RustIcons.FUNCTION if ((flags and Iconable.ICON_FLAG_VISIBILITY) == 0) return icon; return icon.addVisibilityIcon(isPublic) } val isTest: Boolean get() = hasAttribute("test") }
mit
98f62e2260e62b4d42ab3fbb0e265cee
30.842105
93
0.72562
3.980263
false
true
false
false
hsson/card-balance-app
app/src/main/java/se/creotec/chscardbalance2/controller/SettingsActivity.kt
1
9540
// Copyright (c) 2017 Alexander Håkansson // // This software is released under the MIT License. // https://opensource.org/licenses/MIT package se.creotec.chscardbalance2.controller import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.SwitchCompat import android.text.InputFilter import android.text.InputType import android.view.View import android.widget.NumberPicker import android.widget.TextView import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import se.creotec.chscardbalance2.Constants import se.creotec.chscardbalance2.GlobalState import se.creotec.chscardbalance2.R import se.creotec.chscardbalance2.service.BalanceService import se.creotec.chscardbalance2.service.MenuService import se.creotec.chscardbalance2.util.CardNumberMask import se.creotec.chscardbalance2.util.NotificationsHelper import se.creotec.chscardbalance2.util.Util class SettingsActivity : AppCompatActivity() { var cardNumberContainer: View? = null var cardNumberText: TextView? = null var menuLangContainer: View? = null var menuLangText: TextView? = null var toggleLowBalanceContainer: View? = null var toggleLowBalanceNotifications: SwitchCompat? = null var lowBalanceLimitContainer: View? = null var lowBalanceLimitText: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) val global = application as GlobalState var formattedNumber = Util.formatCardNumber(global.model.cardData.cardNumber) cardNumberContainer = findViewById(R.id.settings_card_number) cardNumberContainer?.setOnClickListener { val dialog = MaterialDialog.Builder(this) .title(R.string.prefs_card_number) .inputType(InputType.TYPE_CLASS_NUMBER) .input(getString(R.string.card_number_hint), formattedNumber) { dialog, input -> if (input.toString().replace(" ", "").length == Constants.CARD_NUMBER_LENGTH) { dialog.getActionButton(DialogAction.POSITIVE).isEnabled = true formattedNumber = input.toString() } else { dialog.getActionButton(DialogAction.POSITIVE).isEnabled = false } } .onPositive { _, _ -> setCardNumber(formattedNumber.replace(" ", ""), true) } .alwaysCallInputCallback() .negativeText(R.string.action_cancel) .positiveText(R.string.action_save) .build() dialog.inputEditText?.let { val filters = Array<InputFilter>(1) { _ -> InputFilter.LengthFilter(Constants.CARD_NUMBER_LENGTH + 3) } it.filters = filters it.addTextChangedListener(CardNumberMask()) } dialog.show() } cardNumberText = findViewById<TextView>(R.id.settings_card_number_text) menuLangContainer = findViewById(R.id.settings_menu_lang) menuLangContainer?.setOnClickListener { MaterialDialog.Builder(this) .title(R.string.prefs_menu_lang) .items(R.array.prefs_menu_lang_list) .itemsCallbackSingleChoice(getDefaultLangIndex(global.model.preferredMenuLanguage)) { _, _, which, _ -> when (which) { 0 -> setMenuLang(Constants.ENDPOINT_MENU_LANG_EN, true) 1 -> setMenuLang(Constants.ENDPOINT_MENU_LANG_SV, true) } true } .negativeText(R.string.action_cancel) .show() } menuLangText = findViewById<TextView>(R.id.settings_menu_lang_text) lowBalanceLimitContainer = findViewById(R.id.settings_low_balance_limit) toggleLowBalanceContainer = findViewById(R.id.settings_enable_low_balance_parent) toggleLowBalanceNotifications = findViewById<SwitchCompat>(R.id.settings_enable_low_balance_switch) lowBalanceLimitText = findViewById<TextView>(R.id.settings_low_balance_limit_text) val lowBalanceLimitString = getString(R.string.currency_suffix, global.model.notifications.lowBalanceNotificationLimit.toString()) lowBalanceLimitText?.text = lowBalanceLimitString toggleLowBalanceNotifications?.let { it.isChecked = global.model.notifications.isLowBalanceNotificationsEnabled notificationsEnabledToggled(it.isChecked) it.setOnCheckedChangeListener { _, checked -> notificationsEnabledToggled(checked, savePreference = true) } } toggleLowBalanceContainer?.setOnClickListener { toggleLowBalanceNotifications?.toggle() } lowBalanceLimitContainer?.setOnClickListener { val dialog = MaterialDialog.Builder(this) .title(R.string.prefs_notifications_low_balance_label) .customView(R.layout.dialog_number_picker, false) .negativeText(R.string.action_cancel) .positiveText(R.string.action_save) .onPositive { dialog, action-> if (action == DialogAction.POSITIVE) { val numberPicker = dialog.customView?.findViewById(R.id.dialog_notify_number_picker) as NumberPicker setLowBalanceLimit(numberPicker.value, savePreference = true) } } .build() val numberPicker = dialog.customView?.findViewById(R.id.dialog_notify_number_picker) as NumberPicker numberPicker.minValue = Constants.PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_MIN numberPicker.maxValue = Constants.PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_MAX numberPicker.wrapSelectorWheel = false numberPicker.value = global.model.notifications.lowBalanceNotificationLimit dialog.show() } setCardNumber(global.model.cardData.cardNumber) setMenuLang(global.model.preferredMenuLanguage) } private fun setLowBalanceLimit(limit: Int, savePreference: Boolean = false) { val limitToSet: Int if (limit < Constants.PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_MIN || limit > Constants.PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_MAX) { limitToSet = Constants.PREFS_NOTIFICATION_LOW_BALANCE_LIMIT_DEFAULT } else { limitToSet = limit } val lowBalanceLimitString = getString(R.string.currency_suffix, limitToSet.toString()) lowBalanceLimitText?.text = lowBalanceLimitString if (savePreference) { val global = application as GlobalState global.model.notifications.lowBalanceNotificationLimit = limitToSet global.saveNotificationData() } } private fun notificationsEnabledToggled(enabled: Boolean, savePreference: Boolean = false) { lowBalanceLimitContainer?.let { it.isClickable = enabled it.isFocusable = enabled if (enabled) { it.alpha = 1f } else { it.alpha = 0.2f } } if (savePreference) { if (!enabled) { NotificationsHelper.cancelAll(this) } val global = application as GlobalState global.model.notifications.isLowBalanceNotificationsEnabled = enabled global.saveNotificationData() } } private fun setCardNumber(cardNumber: String?, savePreference: Boolean = false) { if (cardNumber == null) { return } val number = Util.formatCardNumber(cardNumber) cardNumberText?.text = number if (savePreference) { val global = application as GlobalState if (number != global.model.cardData.cardNumber) { global.model.cardData.cardNumber = cardNumber global.saveCardData() global.model.userInfo = "" global.saveUserInfoData() } } } private fun setMenuLang(lang: String?, savePreference: Boolean = false) { if (lang == null) { return } when (lang) { Constants.ENDPOINT_MENU_LANG_EN -> menuLangText?.text = getString(R.string.prefs_menu_lang_en) Constants.ENDPOINT_MENU_LANG_SV -> menuLangText?.text = getString(R.string.prefs_menu_lang_sv) else -> return } if (savePreference) { val global = application as GlobalState global.model.preferredMenuLanguage = lang global.saveMenuData() val updateMenuIntent = Intent(this, MenuService::class.java) updateMenuIntent.action = Constants.ACTION_UPDATE_MENU startService(updateMenuIntent) } } private fun getDefaultLangIndex(lang: String?): Int { if (lang == null) { return -1 } when (lang) { Constants.ENDPOINT_MENU_LANG_EN -> return 0 Constants.ENDPOINT_MENU_LANG_SV -> return 1 else -> return 0 } } }
mit
bdc0b43606437ebcd4544d3d1aab80d7
41.584821
138
0.625432
4.952752
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/createClassUtils.kt
1
8149
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass import com.intellij.codeInsight.daemon.quickFix.CreateClassOrPackageFix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.quickfix.DelegatingIntentionAction import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.containsStarProjections import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.guessTypes import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.noSubstitutions import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.parents import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.bindingContextUtil.getAbbreviatedTypeOrType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.resolve.scopes.receivers.Qualifier import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue import org.jetbrains.kotlin.types.* import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.descriptors.ClassKind as ClassDescriptorKind internal fun String.checkClassName(): Boolean = isNotEmpty() && Character.isUpperCase(first()) private fun String.checkPackageName(): Boolean = isNotEmpty() && Character.isLowerCase(first()) internal fun getTargetParentsByQualifier( element: KtElement, isQualified: Boolean, qualifierDescriptor: DeclarationDescriptor? ): List<PsiElement> { val file = element.containingKtFile val project = file.project val targetParents: List<PsiElement> = when { !isQualified -> element.parents.filterIsInstance<KtClassOrObject>().toList() + file qualifierDescriptor is ClassDescriptor -> listOfNotNull(DescriptorToSourceUtilsIde.getAnyDeclaration(project, qualifierDescriptor)) qualifierDescriptor is PackageViewDescriptor -> if (qualifierDescriptor.fqName != file.packageFqName) { listOfNotNull(JavaPsiFacade.getInstance(project).findPackage(qualifierDescriptor.fqName.asString())) } else listOf(file) else -> emptyList() } return targetParents.filter { it.canRefactor() } } internal fun getTargetParentsByCall(call: Call, context: BindingContext): List<PsiElement> { val callElement = call.callElement return when (val receiver = call.explicitReceiver) { null -> getTargetParentsByQualifier(callElement, false, null) is Qualifier -> getTargetParentsByQualifier( callElement, true, context[BindingContext.REFERENCE_TARGET, receiver.referenceExpression] ) is ReceiverValue -> getTargetParentsByQualifier(callElement, true, receiver.type.constructor.declarationDescriptor) else -> throw AssertionError("Unexpected receiver: $receiver") } } internal fun isInnerClassExpected(call: Call) = call.explicitReceiver is ReceiverValue internal fun KtExpression.guessTypeForClass(context: BindingContext, moduleDescriptor: ModuleDescriptor) = guessTypes(context, moduleDescriptor, coerceUnusedToUnit = false).singleOrNull() internal fun KotlinType.toClassTypeInfo(): TypeInfo { return TypeInfo.ByType(this, Variance.OUT_VARIANCE).noSubstitutions() } internal fun getClassKindFilter(expectedType: KotlinType, containingDeclaration: PsiElement): (ClassKind) -> Boolean { if (expectedType.isAnyOrNullableAny()) { return { _ -> true } } val descriptor = expectedType.constructor.declarationDescriptor ?: return { _ -> false } val canHaveSubtypes = !(expectedType.constructor.isFinal || expectedType.containsStarProjections()) || expectedType.isUnit() val isEnum = DescriptorUtils.isEnumClass(descriptor) if (!(canHaveSubtypes || isEnum) || descriptor is TypeParameterDescriptor ) return { _ -> false } return { classKind -> when (classKind) { ClassKind.ENUM_ENTRY -> isEnum && containingDeclaration == DescriptorToSourceUtils.descriptorToDeclaration(descriptor) ClassKind.INTERFACE -> containingDeclaration !is PsiClass || (descriptor as? ClassDescriptor)?.kind == ClassDescriptorKind.INTERFACE else -> canHaveSubtypes } } } internal fun KtSimpleNameExpression.getCreatePackageFixIfApplicable(targetParent: PsiElement): IntentionAction? { val name = getReferencedName() if (!name.checkPackageName()) return null val basePackage: PsiPackage = when (targetParent) { is KtFile -> JavaPsiFacade.getInstance(targetParent.project).findPackage(targetParent.packageFqName.asString()) is PsiPackage -> targetParent else -> null } ?: return null val baseName = basePackage.qualifiedName val fullName = if (baseName.isNotEmpty()) "$baseName.$name" else name val javaFix = CreateClassOrPackageFix.createFix(fullName, resolveScope, this, basePackage, null, null, null) ?: return null return object : DelegatingIntentionAction(javaFix) { override fun getFamilyName(): String = KotlinBundle.message("fix.create.from.usage.family") override fun getText(): String = KotlinBundle.message("create.package.0", fullName) } } data class UnsubstitutedTypeConstraintInfo( val typeParameter: TypeParameterDescriptor, private val originalSubstitution: Map<TypeConstructor, TypeProjection>, val upperBound: KotlinType ) { fun performSubstitution(vararg substitution: Pair<TypeConstructor, TypeProjection>): TypeConstraintInfo? { val currentSubstitution = LinkedHashMap<TypeConstructor, TypeProjection>().apply { this.putAll(originalSubstitution) this.putAll(substitution) } val substitutedUpperBound = TypeSubstitutor.create(currentSubstitution).substitute(upperBound, Variance.INVARIANT) ?: return null return TypeConstraintInfo(typeParameter, substitutedUpperBound) } } data class TypeConstraintInfo( val typeParameter: TypeParameterDescriptor, val upperBound: KotlinType ) fun getUnsubstitutedTypeConstraintInfo(element: KtTypeElement): UnsubstitutedTypeConstraintInfo? { val context = element.analyze(BodyResolveMode.PARTIAL) val containingTypeArg = (element.parent as? KtTypeReference)?.parent as? KtTypeProjection ?: return null val argumentList = containingTypeArg.parent as? KtTypeArgumentList ?: return null val containingTypeRef = (argumentList.parent as? KtTypeElement)?.parent as? KtTypeReference ?: return null val containingType = containingTypeRef.getAbbreviatedTypeOrType(context) ?: return null val baseType = containingType.constructor.declarationDescriptor?.defaultType ?: return null val typeParameter = containingType.constructor.parameters.getOrNull(argumentList.arguments.indexOf(containingTypeArg)) val upperBound = typeParameter?.upperBounds?.singleOrNull() ?: return null val substitution = getTypeSubstitution(baseType, containingType) ?: return null return UnsubstitutedTypeConstraintInfo(typeParameter, substitution, upperBound) } fun getTypeConstraintInfo(element: KtTypeElement) = getUnsubstitutedTypeConstraintInfo(element)?.performSubstitution()
apache-2.0
282c2a776de3b386a74b48b6d0f834a0
48.090361
158
0.770033
5.326144
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/lightClasses/IdeLightClassInheritanceHelper.kt
4
2553
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.caches.lightClasses import com.intellij.psi.CommonClassNames import com.intellij.psi.PsiClass import org.jetbrains.kotlin.asJava.ImpreciseResolveResult import org.jetbrains.kotlin.asJava.ImpreciseResolveResult.* import org.jetbrains.kotlin.asJava.classes.KtLightClass import org.jetbrains.kotlin.asJava.classes.LightClassInheritanceHelper import org.jetbrains.kotlin.asJava.classes.defaultJavaAncestorQualifiedName import org.jetbrains.kotlin.idea.base.util.isInDumbMode import org.jetbrains.kotlin.idea.search.PsiBasedClassResolver import org.jetbrains.kotlin.psi.KtSimpleNameExpression import org.jetbrains.kotlin.psi.KtSuperTypeCallEntry import org.jetbrains.kotlin.psi.KtSuperTypeListEntry class IdeLightClassInheritanceHelper : LightClassInheritanceHelper { override fun isInheritor( lightClass: KtLightClass, baseClass: PsiClass, checkDeep: Boolean ): ImpreciseResolveResult { if (baseClass.project.isInDumbMode) return NO_MATCH if (lightClass.manager.areElementsEquivalent(baseClass, lightClass)) return NO_MATCH val classOrObject = lightClass.kotlinOrigin ?: return UNSURE if (checkDeep && baseClass.qualifiedName == CommonClassNames.JAVA_LANG_OBJECT) { return MATCH } val entries = classOrObject.superTypeListEntries val hasSuperClass = entries.any { it is KtSuperTypeCallEntry } if (baseClass.qualifiedName == classOrObject.defaultJavaAncestorQualifiedName() && (!hasSuperClass || checkDeep)) { return MATCH } val amongEntries = isAmongEntries(baseClass, entries) return when { !checkDeep -> amongEntries amongEntries == MATCH -> MATCH else -> UNSURE } } private fun isAmongEntries(baseClass: PsiClass, entries: List<KtSuperTypeListEntry>): ImpreciseResolveResult { val psiBasedResolver = PsiBasedClassResolver.getInstance(baseClass) entries@ for (entry in entries) { val reference: KtSimpleNameExpression = entry.typeAsUserType?.referenceExpression ?: continue@entries when (psiBasedResolver.canBeTargetReference(reference)) { MATCH -> return MATCH NO_MATCH -> continue@entries UNSURE -> return UNSURE } } return NO_MATCH } }
apache-2.0
42eab7e502de40bbd9024aa5f7b07f7e
43.017241
158
0.725421
4.986328
false
false
false
false
hermantai/samples
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-13/app-code/app/src/main/java/dev/mfazio/abl/teams/SingleTeamFragment.kt
3
1363
package dev.mfazio.abl.teams import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.activityViewModels import androidx.navigation.findNavController import androidx.navigation.fragment.navArgs import dev.mfazio.abl.NavGraphDirections import dev.mfazio.abl.databinding.FragmentSingleTeamBinding class SingleTeamFragment : Fragment() { private val args: SingleTeamFragmentArgs by navArgs() private val singleTeamViewModel by activityViewModels<SingleTeamViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { val binding = FragmentSingleTeamBinding .inflate(inflater, container, false) .apply { vm = singleTeamViewModel.apply { setTeam(args.teamId) } viewRosterButtonClickListener = View.OnClickListener { view -> val action = NavGraphDirections.actionGoToTeamRoster( args.teamId ) view.findNavController().navigate(action) } lifecycleOwner = viewLifecycleOwner } return binding.root } }
apache-2.0
55a5909cf7d7f602f98c108b352e10f2
30.72093
80
0.666911
5.495968
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/internal/inspector/ConfigureCustomSizeAction.kt
7
1585
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.inspector import com.intellij.ide.util.propComponentProperty import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.components.dialog import com.intellij.ui.dsl.builder.bindIntText import com.intellij.ui.dsl.builder.columns import com.intellij.ui.dsl.builder.panel import java.awt.GraphicsEnvironment /** * @author Konstantin Bulenkov */ internal class ConfigureCustomSizeAction : DumbAwareAction() { override fun getActionUpdateThread() = ActionUpdateThread.BGT override fun actionPerformed(e: AnActionEvent) { val centerPanel = panel { row("Width:") { intTextField(1..maxWidth()) .bindIntText(CustomSizeModel::width) .columns(20) .focused() } row("Height:") { intTextField(1..maxHeight()) .bindIntText(CustomSizeModel::height) .columns(20) } } dialog("Default Size", centerPanel, project = e.project).show() } private fun maxWidth(): Int = maxWindowBounds().width private fun maxHeight(): Int = maxWindowBounds().height private fun maxWindowBounds() = GraphicsEnvironment.getLocalGraphicsEnvironment().maximumWindowBounds object CustomSizeModel { var width by propComponentProperty(defaultValue = 640) var height by propComponentProperty(defaultValue = 300) } }
apache-2.0
0761aa5d0e813949e7dc05bb323b6768
32.041667
120
0.738801
4.675516
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/post-processing/src/org/jetbrains/kotlin/idea/j2k/post/processing/inference/common/ConstraintBuilder.kt
2
5106
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.j2k.post.processing.inference.common import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtTypeElement import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.utils.addToStdlib.safeAs @Suppress("unused") class ConstraintBuilder( private val inferenceContext: InferenceContext, private val boundTypeCalculator: BoundTypeCalculator, private val constraintBoundProvider: ConstraintBoundProvider ) : BoundTypeCalculator by boundTypeCalculator, ConstraintBoundProvider by constraintBoundProvider { private val constraints = mutableListOf<Constraint>() fun TypeVariable.isSubtypeOf(supertype: BoundType, priority: ConstraintPriority) { asBoundType().isSubtypeOf(supertype, priority) } fun TypeVariable.isSubtypeOf(supertype: TypeVariable, priority: ConstraintPriority) { asBoundType().isSubtypeOf(supertype.asBoundType(), priority) } fun KtExpression.isSubtypeOf(supertype: KtExpression, priority: ConstraintPriority) { boundType().isSubtypeOf(supertype.boundType(), priority) } fun KtExpression.isSubtypeOf(supertype: TypeVariable, priority: ConstraintPriority) { boundType().isSubtypeOf(supertype.asBoundType(), priority) } fun KtExpression.isSubtypeOf(supertype: BoundType, priority: ConstraintPriority) { boundType().isSubtypeOf(supertype, priority) } fun KtExpression.isTheSameTypeAs(other: State, priority: ConstraintPriority) { boundType().label.safeAs<TypeVariableLabel>()?.typeVariable?.let { typeVariable -> constraints += EqualsConstraint( typeVariable.constraintBound(), other.constraintBound() ?: return@let, priority ) } } fun TypeVariable.isTheSameTypeAs(other: BoundType, priority: ConstraintPriority) { asBoundType().isTheSameTypeAs(other, priority) } fun TypeVariable.isTheSameTypeAs( other: TypeVariable, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { asBoundType().isTheSameTypeAs(other.asBoundType(), priority, ignoreTypeVariables) } fun KtTypeElement.isTheSameTypeAs( other: KtTypeElement, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { inferenceContext.typeElementToTypeVariable[this] ?.asBoundType() ?.isTheSameTypeAs( inferenceContext.typeElementToTypeVariable[other]?.asBoundType() ?: return, priority, ignoreTypeVariables ) } fun TypeVariable.isTheSameTypeAs( other: KtTypeElement, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { asBoundType().isTheSameTypeAs( inferenceContext.typeElementToTypeVariable[other]?.asBoundType() ?: return, priority, ignoreTypeVariables ) } fun BoundType.isTheSameTypeAs( other: KtTypeElement, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { isTheSameTypeAs( inferenceContext.typeElementToTypeVariable[other]?.asBoundType() ?: return, priority, ignoreTypeVariables ) } private fun BoundType.isTheSameTypeAs( other: BoundType, priority: ConstraintPriority, ignoreTypeVariables: Set<TypeVariable> = emptySet() ) { (typeParameters zip other.typeParameters).forEach { (left, right) -> left.boundType.isTheSameTypeAs(right.boundType, priority, ignoreTypeVariables) } if (typeVariable !in ignoreTypeVariables && other.typeVariable !in ignoreTypeVariables) { constraints += EqualsConstraint( constraintBound() ?: return, other.constraintBound() ?: return, priority ) } } fun BoundType.isSubtypeOf(supertype: BoundType, priority: ConstraintPriority) { (typeParameters zip supertype.typeParameters).forEach { (left, right) -> when (left.variance) { Variance.OUT_VARIANCE -> left.boundType.isSubtypeOf(right.boundType, priority) Variance.IN_VARIANCE -> right.boundType.isSubtypeOf(left.boundType, priority) Variance.INVARIANT -> right.boundType.isTheSameTypeAs(left.boundType, priority) } } constraints += SubtypeConstraint( constraintBound() ?: return, supertype.constraintBound() ?: return, priority ) } fun KtExpression.boundType() = with(boundTypeCalculator) { [email protected](inferenceContext) } val collectedConstraints: List<Constraint> get() = constraints }
apache-2.0
267595c5a423dc8b44f6f7c1ffecbc96
36.007246
158
0.671955
5.685969
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/testEntities/testSrc/com/intellij/workspaceModel/storage/entities/test/api/primitiveEntities.kt
1
5927
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import com.intellij.workspaceModel.storage.MutableEntityStorage interface BooleanEntity : WorkspaceEntity { val data: Boolean //region generated code @GeneratedCodeApiVersion(1) interface Builder : BooleanEntity, WorkspaceEntity.Builder<BooleanEntity>, ObjBuilder<BooleanEntity> { override var entitySource: EntitySource override var data: Boolean } companion object : Type<BooleanEntity, Builder>() { operator fun invoke(data: Boolean, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): BooleanEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: BooleanEntity, modification: BooleanEntity.Builder.() -> Unit) = modifyEntity( BooleanEntity.Builder::class.java, entity, modification) //endregion interface IntEntity : WorkspaceEntity { val data: Int //region generated code @GeneratedCodeApiVersion(1) interface Builder : IntEntity, WorkspaceEntity.Builder<IntEntity>, ObjBuilder<IntEntity> { override var entitySource: EntitySource override var data: Int } companion object : Type<IntEntity, Builder>() { operator fun invoke(data: Int, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): IntEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: IntEntity, modification: IntEntity.Builder.() -> Unit) = modifyEntity( IntEntity.Builder::class.java, entity, modification) //endregion interface StringEntity : WorkspaceEntity { val data: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : StringEntity, WorkspaceEntity.Builder<StringEntity>, ObjBuilder<StringEntity> { override var entitySource: EntitySource override var data: String } companion object : Type<StringEntity, Builder>() { operator fun invoke(data: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): StringEntity { val builder = builder() builder.data = data builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: StringEntity, modification: StringEntity.Builder.() -> Unit) = modifyEntity( StringEntity.Builder::class.java, entity, modification) //endregion interface ListEntity : WorkspaceEntity { val data: List<String> //region generated code @GeneratedCodeApiVersion(1) interface Builder : ListEntity, WorkspaceEntity.Builder<ListEntity>, ObjBuilder<ListEntity> { override var entitySource: EntitySource override var data: MutableList<String> } companion object : Type<ListEntity, Builder>() { operator fun invoke(data: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ListEntity { val builder = builder() builder.data = data.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ListEntity, modification: ListEntity.Builder.() -> Unit) = modifyEntity( ListEntity.Builder::class.java, entity, modification) //endregion interface OptionalIntEntity : WorkspaceEntity { val data: Int? //region generated code @GeneratedCodeApiVersion(1) interface Builder : OptionalIntEntity, WorkspaceEntity.Builder<OptionalIntEntity>, ObjBuilder<OptionalIntEntity> { override var entitySource: EntitySource override var data: Int? } companion object : Type<OptionalIntEntity, Builder>() { operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OptionalIntEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OptionalIntEntity, modification: OptionalIntEntity.Builder.() -> Unit) = modifyEntity( OptionalIntEntity.Builder::class.java, entity, modification) //endregion interface OptionalStringEntity : WorkspaceEntity { val data: String? //region generated code @GeneratedCodeApiVersion(1) interface Builder : OptionalStringEntity, WorkspaceEntity.Builder<OptionalStringEntity>, ObjBuilder<OptionalStringEntity> { override var entitySource: EntitySource override var data: String? } companion object : Type<OptionalStringEntity, Builder>() { operator fun invoke(entitySource: EntitySource, init: (Builder.() -> Unit)? = null): OptionalStringEntity { val builder = builder() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: OptionalStringEntity, modification: OptionalStringEntity.Builder.() -> Unit) = modifyEntity( OptionalStringEntity.Builder::class.java, entity, modification) //endregion // Not supported at the moment /* interface OptionalListIntEntity : WorkspaceEntity { val data: List<Int>? } */
apache-2.0
51c0cd9aadd88f8bdf826e3d18c7c052
30.526596
138
0.744221
4.862182
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/client/ClientSession.kt
2
2634
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.client import com.intellij.codeWithMe.ClientId import com.intellij.openapi.application.Application import com.intellij.openapi.components.ComponentManager import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectEx import com.intellij.util.messages.MessageBus import org.jetbrains.annotations.ApiStatus /** * An object associated with each participant working inside an IDE. * There's always a session of a local owner of the IDE that lives as long as [Application]/[Project] itself, * in case of Code With Me there also can be other client sessions corresponding to the joined guests, * in case of Gateway there also can be the client working with the IDE remotely. * * Manage services registered with <applicationService client="..."/> and <projectService client="..."/>. * * One can create per-client services when it's needed to * 1) alter the behavior between the local, controller, and guests * 2) to have the data kept on a per-client basis * * Getting a service with [Application.getService]/[Project.getService] will search through per-client services of the current [ClientId], * there's also [Application.getServices]/[Project.getServices] for getting all services, that should be enough for simple cases. * If you need more control over client sessions or per-client services, take a look at the API of [ClientSessionsManager]. * * Avoid exposing [ClientSession] and its inheritors in the public API. * Use sessions and per-client services internally in your code instead of relaying on [ClientId] implicitly stored in the context of execution. */ @ApiStatus.Experimental @ApiStatus.Internal interface ClientSession : ComponentManager { val clientId: ClientId val type: ClientType @Deprecated("sessions don't have their own message bus", level = DeprecationLevel.ERROR) override fun getMessageBus(): MessageBus { error("Not supported") } val isLocal: Boolean get() = type.isLocal val isController: Boolean get() = type.isController val isGuest: Boolean get() = type.isGuest val isOwner: Boolean get() = type.isOwner val isRemote: Boolean get() = type.isRemote } /** * Application level [ClientSession] */ @ApiStatus.Experimental @ApiStatus.Internal interface ClientAppSession : ClientSession /** * Project level [ClientSession] */ @ApiStatus.Experimental @ApiStatus.Internal interface ClientProjectSession : ClientSession { val project: ProjectEx val appSession: ClientAppSession }
apache-2.0
60f67301b39f4fd081fb8268fd4e415a
39.523077
144
0.774487
4.479592
false
false
false
false
yongce/AndroidLib
baseLib/src/androidTest/java/me/ycdev/android/lib/common/utils/SystemSwitchUtils.kt
1
760
package me.ycdev.android.lib.common.utils import android.annotation.SuppressLint import android.content.Context import android.net.wifi.WifiManager @SuppressLint("MissingPermission") object SystemSwitchUtils { fun isWifiEnabled(cxt: Context): Boolean { val wifiMgr = cxt.applicationContext.getSystemService( Context.WIFI_SERVICE ) as WifiManager val wifiState = wifiMgr.wifiState return wifiState == WifiManager.WIFI_STATE_ENABLED || wifiState == WifiManager.WIFI_STATE_ENABLING } fun setWifiEnabled(cxt: Context, enable: Boolean) { val wifiMgr = cxt.applicationContext.getSystemService( Context.WIFI_SERVICE ) as WifiManager wifiMgr.isWifiEnabled = enable } }
apache-2.0
f52725a3b0a1ff7418ba5f6143a8842e
32.043478
106
0.713158
4.497041
false
false
false
false
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/manager/ListenerManager.kt
1
1647
package me.ycdev.android.lib.common.manager @Suppress("unused") open class ListenerManager<IListener : Any>(override val weakReference: Boolean) : ObjectManager<IListener>(weakReference) { /** * Only invoked when invoke [addListener] */ protected open fun onFirstListenerAdd() { // nothing to do } /** * Only invoked when invoke [removeListener] */ protected open fun onLastListenerRemoved() { // nothing to do } /** * Override this method to notify the listener when registered. */ protected open fun onListenerAdded(listener: IListener) { // nothing to do } final override fun onFirstObjectAdd() { onFirstListenerAdd() } final override fun onLastObjectRemoved() { onLastListenerRemoved() } final override fun onObjectAdded(obj: IListener) { onListenerAdded(obj) } /** * Get the listeners count right now. * But the returned value may be NOT accurate if [weakReference] is true. * Some of the listeners may be already collected by GC. */ val listenersCount: Int by ::objectsCount fun addListener(listener: IListener) = super.addObject(listener) fun addListener(listener: IListener, tag: String) = super.addObject(listener, tag) fun removeListener(listener: IListener) = super.removeObject(listener) fun notifyListeners(action: NotifyAction<IListener>) = super.notifyObjects(action) fun notifyListeners(action: (IListener) -> Unit) = super.notifyObjects(action) companion object { private const val TAG = "ListenerManager" } }
apache-2.0
65b58283158ff578fe110c70d914a87b
26.45
86
0.67031
4.600559
false
false
false
false
JetBrains-Research/viktor
src/main/kotlin/org/jetbrains/bio/viktor/Sorting.kt
1
3310
package org.jetbrains.bio.viktor import java.util.* /** * Sorts the elements in this 1-D array in in descending order. * * The operation is done **in place**. * * @param reverse if `true` the elements are sorted in `ascending` order. * Defaults to `false`. */ fun F64Array.sort(reverse: Boolean = false) = reorder(argSort(reverse)) /** * Returns a permutation of indices which makes the 1-D array sorted. * * @param reverse see [sort] for details. */ fun F64Array.argSort(reverse: Boolean = false): IntArray { check(this is F64FlatArray) { "expected a 1-D array" } val comparator = Comparator(IndexedDoubleValue::compareTo) val indexedValues = Array(length) { IndexedDoubleValue(it, unsafeGet(it)) } indexedValues.sortWith(if (reverse) comparator.reversed() else comparator) return IntArray(length) { indexedValues[it].index } } /** A version of [IndexedValue] specialized to [Double]. */ private data class IndexedDoubleValue(val index: Int, val value: Double) : Comparable<IndexedDoubleValue> { override fun compareTo(other: IndexedDoubleValue): Int { val res = value.compareTo(other.value) return if (res != 0) { res } else { index.compareTo(other.index) } } } internal inline fun <T> reorderInternal( a: F64Array, indices: IntArray, axis: Int, get: (Int) -> T, set: (Int, T) -> Unit ) { require(indices.size == a.shape[axis]) val copy = indices.clone() for (pos in 0 until a.shape[axis]) { val value = get(pos) var j = pos while (true) { val k = copy[j] copy[j] = j if (k == pos) { set(j, value) break } else { set(j, get(k)) j = k } } } } /** * Partitions the array. * * Rearranges the elements in this array in such a way that * the [p]-th element moves to its position in the sorted copy * of the array. All elements smaller than the [p]-th element * are moved before this element, and all elements greater or * equals to this element are moved behind it. * * The operation is done **in place**. * * @param p the index of the element to partition by. * @since 0.2.3 */ fun F64Array.partition(p: Int) { check(this is F64FlatArray) { "expected a 1-D array" } require(p in 0 until length) { "p must be in [0, $length)" } partition(p, 0, length - 1) } /** * Helper [partition] extension. * * Invariants: p = partition(values, left, right, p) * for all i < p: * values[i] < values[p] * for all i >= p: * values[i] >= values[p] * * @param p the index of the element to partition by. * @param left start index (inclusive). * @param right end index (inclusive). */ internal fun F64FlatArray.partition(p: Int, left: Int, right: Int): Int { val pivot = this[p] swap(p, right) // move to end. var ptr = left for (i in left until right) { if (this[i] < pivot) { swap(i, ptr) ptr++ } } swap(right, ptr) return ptr } @Suppress("nothing_to_inline") internal inline fun F64FlatArray.swap(i: Int, j: Int) { val tmp = unsafeGet(i) unsafeSet(i, unsafeGet(j)) unsafeSet(j, tmp) }
mit
dfcd63f0a59b4c130f2609097846ad06
26.131148
79
0.602719
3.487882
false
false
false
false
pureal-code/pureal-os
traits/src/net/pureal/traits/graphics/Fill.kt
1
2317
package net.pureal.traits.graphics import net.pureal.traits.* import java.util.SortedMap trait Fill { fun colorAt(location: Vector2): Color fun transform(transform: Transform2): TransformedFill = object : TransformedFill { override val original = this@Fill override val transform = transform } } object Fills { fun solid(color: Color) = object : SolidFill { override val color = color } val invisible = object : InvisibleFill {} fun linearGradient(stops: SortedMap<out Number, Color>) = object : LinearGradient { override val stops = stops } fun radialGradient(stops: SortedMap<out Number, Color>) = object : RadialGradient { override val stops = stops } } trait TransformedFill : Fill { val original: Fill val transform: Transform2 override fun colorAt(location: Vector2) = original.colorAt(transform.inverse()(location)) } trait InvisibleFill : SolidFill { override val color: Color get() = Colors.transparent } trait SolidFill : Fill { val color: Color override fun colorAt(location: Vector2) = color } trait Gradient : Fill { val stops: SortedMap<out Number, Color> protected fun colorAt(location: Number): Color { val l = location.toDouble() val entries = stops.entrySet() val equalStops = entries filter { it.key.toDouble() == l } if (!equalStops.empty) return equalStops.single().value val nextBiggerStop = (entries filter { it.key.toDouble() > l }).firstOrNull() val nextSmallerStop = (entries filter { it.key.toDouble() < l }).lastOrNull() if (nextBiggerStop == null && nextSmallerStop == null) return Colors.transparent if (nextBiggerStop == null) return nextSmallerStop!!.value if (nextSmallerStop == null) return nextBiggerStop.value val portion = (l - nextSmallerStop.key.toDouble()) / (nextBiggerStop.key.toDouble() - nextSmallerStop.key.toDouble()) return nextSmallerStop.value * (1 - portion) + nextBiggerStop.value * portion } } trait LinearGradient : Gradient { override fun colorAt(location: Vector2) = super<Gradient>.colorAt(location.x.toDouble()) } trait RadialGradient : Gradient { override fun colorAt(location: Vector2) = super<Gradient>.colorAt(location.length) }
bsd-3-clause
2dbeb68f3b2e492b481b71387df33f43
31.194444
125
0.686232
4.100885
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreateBinaryOperationActionFactory.kt
6
2686
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.project.builtIns import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.lexer.KtToken import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtBinaryExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.expressions.OperatorConventions import java.util.* object CreateBinaryOperationActionFactory : CreateCallableMemberFromUsageFactory<KtBinaryExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtBinaryExpression? { return diagnostic.psiElement.parent as? KtBinaryExpression } override fun createCallableInfo(element: KtBinaryExpression, diagnostic: Diagnostic): CallableInfo? { val token = element.operationToken as KtToken val operationName = when (token) { KtTokens.IDENTIFIER -> element.operationReference.getReferencedName() else -> OperatorConventions.getNameForOperationSymbol(token, false, true)?.asString() } ?: return null val inOperation = token in OperatorConventions.IN_OPERATIONS val comparisonOperation = token in OperatorConventions.COMPARISON_OPERATIONS val leftExpr = element.left ?: return null val rightExpr = element.right ?: return null val receiverExpr = if (inOperation) rightExpr else leftExpr val argumentExpr = if (inOperation) leftExpr else rightExpr val builtIns = element.builtIns val receiverType = TypeInfo(receiverExpr, Variance.IN_VARIANCE) val returnType = when { inOperation -> TypeInfo.ByType(builtIns.booleanType, Variance.INVARIANT).noSubstitutions() comparisonOperation -> TypeInfo.ByType(builtIns.intType, Variance.INVARIANT).noSubstitutions() else -> TypeInfo(element, Variance.OUT_VARIANCE) } val parameters = Collections.singletonList(ParameterInfo(TypeInfo(argumentExpr, Variance.IN_VARIANCE))) val isOperator = token != KtTokens.IDENTIFIER return FunctionInfo( operationName, receiverType, returnType, parameterInfos = parameters, modifierList = KtPsiFactory(element).createModifierList(if (isOperator) KtTokens.OPERATOR_KEYWORD else KtTokens.INFIX_KEYWORD) ) } }
apache-2.0
e6b20939f0a48b70b4222f331ee5406b
49.679245
158
0.743485
5.235867
false
false
false
false
martijn-heil/wac-core
src/main/kotlin/tk/martijn_heil/wac_core/craft/vessel/motor/Battleship.kt
1
2138
/* * wac-core * Copyright (C) 2016 Martijn Heil * * 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 tk.martijn_heil.wac_core.craft.vessel.motor import org.bukkit.Location import org.bukkit.entity.Entity import org.bukkit.plugin.Plugin import tk.martijn_heil.wac_core.craft.Rotation import tk.martijn_heil.wac_core.craft.vessel.MotorShip import tk.martijn_heil.wac_core.craft.vessel.Ship class Battleship(plugin: Plugin, detectionPoint: Location) : Ship { private val updateInterval = 40L private var motorShip: MotorShip init { motorShip = MotorShip(plugin, detectionPoint, updateInterval) plugin.server.scheduler.scheduleSyncRepeatingTask(plugin, { update() }, 0, updateInterval) } private fun update() { motorShip.update() } override fun rotate(rotation: Rotation) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override var heading: Int get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. set(value) {} override var location: Location get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. set(value) {} override val onBoardEntities: Collection<Entity> get() = TODO("not implemented") //To change initializer of created properties use File | Settings | File Templates. }
gpl-3.0
71e6488d247ff19cbe9fdbe25ceacd57
38.611111
123
0.705332
4.208661
false
false
false
false
dahlstrom-g/intellij-community
jvm/jvm-analysis-impl/src/com/intellij/codeInspection/IllegalDependencyOnInternalPackageInspection.kt
8
2187
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.codeInspection import com.intellij.analysis.JvmAnalysisBundle import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.packageDependencies.DependenciesBuilder import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassOwner import com.intellij.psi.PsiFile import com.intellij.psi.impl.light.LightJavaModule import com.intellij.psi.util.PsiUtil import com.intellij.util.SmartList class IllegalDependencyOnInternalPackageInspection : AbstractBaseUastLocalInspectionTool() { override fun checkFile(file: PsiFile, manager: InspectionManager, isOnTheFly: Boolean): Array<ProblemDescriptor>? { if (!PsiUtil.isLanguageLevel9OrHigher(file) || JavaModuleGraphUtil.findDescriptorByElement(file) != null) { return null } val problems: MutableList<ProblemDescriptor> = SmartList() DependenciesBuilder.analyzeFileDependencies(file) { place, dependency -> if (dependency is PsiClass) { val dependencyFile = dependency.containingFile if (dependencyFile is PsiClassOwner && dependencyFile.isPhysical && dependencyFile.virtualFile != null) { val javaModule = JavaModuleGraphUtil.findDescriptorByElement(dependencyFile) if (javaModule == null || javaModule is LightJavaModule) { return@analyzeFileDependencies } val moduleName = javaModule.name if (moduleName.startsWith("java.")) { return@analyzeFileDependencies } val packageName = dependencyFile.packageName if (!JavaModuleGraphUtil.exports(javaModule, packageName, null)) { problems.add(manager.createProblemDescriptor(place, JvmAnalysisBundle.message("inspection.message.illegal.dependency.module.doesn.t.export", moduleName, packageName), null as LocalQuickFix?, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly)) } } } } return if (problems.isEmpty()) null else problems.toTypedArray() } }
apache-2.0
5c035b9d3538994f368c7af11a1a91bd
47.622222
255
0.727023
5.145882
false
false
false
false
theapache64/Mock-API
src/com/theah64/mock_api/lab2/Main.kt
1
4554
package com.theah64.mock_api.lab2 import com.theah64.webengine.utils.Request import java.lang.StringBuilder import java.util.regex.Pattern const val TABLE_DATA = "<table class=\"table table-bordered \">\n" + " <thead>\n" + " <tr>\n" + " <th>Returned Key</th>\n" + " <th>Description</th>\n" + " <th>Example</th>\n" + " </tr>\n" + " </thead>\n" + " <tbody>\n" + " <tr>\n" + " <td>error</td>\n" + " <td>The returned status for the API call, can be either 'true' or 'false'</td>\n" + " <td>true</td>\n" + " </tr>\n" + " <tr>\n" + " <td>message</td>\n" + " <td>Either the error message or the successful message</td>\n" + " <td>OK</td>\n" + " </tr>\n" + " <tr>\n" + " <td>data</td>\n" + " <td>If 'error' is returned as 'false' the API query results will be inside 'data'</td>\n" + " <td>data</td>\n" + " </tr>\n" + " </tbody>\n" + "</table>" fun main() { val markDown = MarkDownUtils.toMarkDownTable(TABLE_DATA) println(markDown) } class MarkDownUtils { companion object { const val TABLE_HEAD_REGEX = "<thead>.+(<tr>.+<\\/tr>).+<\\/thead>" const val TABLE_BODY_REGEX = "<tbody>.+(<tr>.+<\\/tr>).+<\\/tbody>" fun toMarkDownTable(_tableData: String): String { var tableData = _tableData tableData = tableData.replace("\n", "") tableData = tableData.replace(Regex("\\s+"), " ") // getting headers val headers = getHeadings(tableData) // Getting rows val rows = getRows(tableData) if (headers != null) { val sBuilder = StringBuilder("|") val lineBuilder = StringBuilder("|") // Adding headers for (header in headers) { sBuilder.append(header).append("|") lineBuilder.append(get('-', header.length - 1)).append("|") } sBuilder.append("\n").append(lineBuilder).append("\n") rows?.let { tableRows -> for (row in tableRows) { sBuilder.append("|") for (value in row) { sBuilder.append(value).append("|") } sBuilder.append("\n") } } return sBuilder.toString() } else { throw Request.RequestException("Invalid table data, couldn't get table header data") } } private fun get(char: Char, length: Int): Any { val sb = StringBuilder() for (i in 0..length) { sb.append(char) } return sb.toString() } fun getRows(tableData: String): List<List<String>>? { var headings = mutableListOf<List<String>>() val pattern = Pattern.compile(TABLE_BODY_REGEX) val matcher = pattern.matcher(tableData) if (matcher.find()) { var tBody = matcher.group(0) tBody = tBody.replace(Regex("(<\\s*tbody>|</\\s*tbody>)"), "") tBody.split("<tr>") .filter { row -> row.trim().isNotEmpty() } .map { row -> val tds = row.split("<td>") .filter { td -> td.trim().isNotEmpty() } .map { td -> td.replace(Regex("(</td>|</tr>)"), "").trim() } headings.add(tds) } } return headings } private fun getHeadings(tableData: String): List<String>? { var headings: List<String>? = null val pattern = Pattern.compile(TABLE_HEAD_REGEX) val matcher = pattern.matcher(tableData) if (matcher.find()) { var trHead = matcher.group(1) trHead = trHead.replace(Regex("(<\\s*tr\\s*>|<\\s*th\\s*>|</\\s*tr\\s*>)"), "") headings = trHead.split("</th>") .map { value -> value.trim() } .filter { value -> value.isNotEmpty() } } return headings } } }
apache-2.0
3a925d8788b89b8bcdcb396f954d8e0f
32.240876
108
0.435441
4.14
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/data/database/form/FormRepository.kt
1
880
package org.secfirst.umbrella.data.database.form import javax.inject.Inject class FormRepository @Inject constructor(private val formDao: FormDao) : FormRepo { override suspend fun loadForm(formTitle: String) = formDao.getForm(formTitle) override suspend fun removeActiveForm(activeForm: ActiveForm) = formDao.delete(activeForm) override suspend fun loadScreenBy(sh1ID: String): List<Screen> = formDao.getScreenBy(sh1ID) override suspend fun persistActiveForm(activeForm: ActiveForm) = formDao.saveActiveForm(activeForm) override suspend fun persistFormData(answer: Answer) = formDao.insertAnswer(answer) override suspend fun loadModelForms() = formDao.getAllFormModel() override suspend fun loadAnswerBy(formId: Long) = formDao.getAnswerBy(formId) override suspend fun loadActiveForms(): List<ActiveForm> = formDao.getAllActiveForms() }
gpl-3.0
462f7daf863acd21ceb84c18a81ab73f
37.304348
103
0.7875
3.9819
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/secretsmanager/src/main/kotlin/com/kotlin/secrets/DeleteSecret.kt
1
1683
// snippet-sourcedescription:[DeleteSecret.kt demonstrates how to delete a secret.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[AWS Secrets Manager] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.secrets // snippet-start:[secretsmanager.kotlin.delete_secret.import] import aws.sdk.kotlin.services.secretsmanager.SecretsManagerClient import aws.sdk.kotlin.services.secretsmanager.model.DeleteSecretRequest import kotlin.system.exitProcess // snippet-end:[secretsmanager.kotlin.delete_secret.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <secretName> Where: secretName - The name of the secret (for example, tutorials/MyFirstSecret). """ if (args.size != 1) { println(usage) exitProcess(0) } val secretName = args[0] deleteSpecificSecret(secretName) } // snippet-start:[secretsmanager.kotlin.delete_secret.main] suspend fun deleteSpecificSecret(secretName: String) { val request = DeleteSecretRequest { secretId = secretName } SecretsManagerClient { region = "us-east-1" }.use { secretsClient -> secretsClient.deleteSecret(request) println("$secretName is deleted.") } } // snippet-end:[secretsmanager.kotlin.delete_secret.main]
apache-2.0
57393f6475072b46d604a4781f4126c5
28.053571
84
0.701129
3.932243
false
false
false
false
sachil/Essence
app/src/main/java/xyz/sachil/essence/model/net/bean/WeeklyPopularData.kt
1
479
package xyz.sachil.essence.model.net.bean import androidx.room.* import xyz.sachil.essence.model.cache.converter.ListConverter @Entity( tableName = "weekly_popular_table", indices = [Index(value = ["category", "type"])], ) @TypeConverters(ListConverter::class) class WeeklyPopularData : TypeData() { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "row_id") var rowId: Int = 0 @ColumnInfo(name = "popular_type") var popularType: String = "" }
apache-2.0
2ca5bdeaacbff477e5567ca25ff7125a
24.210526
61
0.695198
3.601504
false
false
false
false
elpassion/mainframer-intellij-plugin
src/main/kotlin/com/elpassion/mainframerplugin/task/TaskExecutor.kt
1
2733
package com.elpassion.mainframerplugin.task import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionEnvironmentBuilder import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFileManager import io.reactivex.Single import io.reactivex.SingleEmitter import io.reactivex.functions.Consumer class TaskExecutor(private val project: Project, private val commandLineProvider: (Project, TaskData, DataContext) -> GeneralCommandLine) { fun executeSync(task: MainframerTask, executionId: Long, context: DataContext): Boolean { return Single.fromCallable { createExecutionEnv(task, executionId, context) } .subscribeOn(UINonModalScheduler) .doAfterSuccess { saveAllDocuments() } .flatMap(executeAsync) .observeOn(UINonModalScheduler) .map { it.exitCode == 0 } .doAfterSuccess(syncFiles) .onErrorReturnItem(false) .blockingGet() } private fun createExecutionEnv(task: MainframerTask, executionId: Long, context: DataContext): ExecutionEnvironment { return ExecutionEnvironmentBuilder(project, DefaultRunExecutor.getRunExecutorInstance()) .runProfile(MainframerRunProfile(task, { taskData: TaskData -> commandLineProvider(project, taskData, context) })) .build() .apply { this.executionId = executionId } } private val executeAsync: (ExecutionEnvironment) -> Single<ProcessEvent> = { env -> Single.create { emitter -> env.runner.execute(env) { it.processHandler?.addProcessListener(EmitOnTerminatedProcessAdapter(emitter)) } } } private class EmitOnTerminatedProcessAdapter(private val emitter: SingleEmitter<ProcessEvent>) : ProcessAdapter() { override fun processTerminated(event: ProcessEvent) { emitter.onSuccess(event) } } private val syncFiles = Consumer<Boolean> { ApplicationManager.getApplication().runWriteAction { VirtualFileManager.getInstance().syncRefresh() } } } private fun saveAllDocuments() = FileDocumentManager.getInstance().saveAllDocuments()
apache-2.0
7b5efb486ddcae771a1bdc83033829a2
41.71875
130
0.709477
5.444223
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/ui/layout/layoutImpl.kt
1
1348
// 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.ui.layout import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.layout.migLayout.* import java.awt.Container import javax.swing.ButtonGroup import javax.swing.JComponent import javax.swing.JLabel @PublishedApi @JvmOverloads internal fun createLayoutBuilder(isUseMagic: Boolean = true): LayoutBuilder { return LayoutBuilder(MigLayoutBuilder(createIntelliJSpacingConfiguration(), isUseMagic = isUseMagic)) } interface LayoutBuilderImpl { fun newRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, isSeparated: Boolean = false): Row fun newTitledRow(title: String): Row // backward compatibility @Deprecated(level = DeprecationLevel.HIDDEN, message = "deprecated") fun newRow(label: JLabel? = null, buttonGroup: ButtonGroup? = null, separated: Boolean = false, indented: Boolean = false) = newRow(label, buttonGroup, separated) fun build(container: Container, layoutConstraints: Array<out LCFlags>) fun noteRow(text: String, linkHandler: ((url: String) -> Unit)? = null) fun commentRow(text: String) val preferredFocusedComponent: JComponent? val validateCallbacks: List<() -> ValidationInfo?> val applyCallbacks: List<() -> Unit> }
apache-2.0
c0405d0ab9c0b6b12f57688b03cd7d19
37.542857
164
0.771513
4.265823
false
false
false
false
google/intellij-community
platform/platform-impl/src/com/intellij/ui/popup/list/PopupInlineActionsSupportImpl.kt
2
4760
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.popup.list import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.ui.ExperimentalUI import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.popup.ActionPopupStep import com.intellij.ui.popup.PopupFactoryImpl.ActionItem import com.intellij.ui.popup.PopupFactoryImpl.InlineActionItem import com.intellij.ui.popup.list.ListPopupImpl.ListWithInlineButtons import com.intellij.ui.scale.JBUIScale import com.intellij.util.ui.JBInsets import com.intellij.util.ui.JBUI import java.awt.Point import java.awt.event.InputEvent import javax.swing.* private const val INLINE_BUTTON_WIDTH = 16 class PopupInlineActionsSupportImpl(private val myListPopup: ListPopupImpl) : PopupInlineActionsSupport { private val myStep = myListPopup.listStep as ActionPopupStep override fun hasExtraButtons(element: Any): Boolean = calcExtraButtonsCount(element) > 0 override fun calcExtraButtonsCount(element: Any): Int { if (!ExperimentalUI.isNewUI() || element !is ActionItem) return 0 var res = 0 res += myStep.getInlineActions(element).size if (res != 0 && myStep.hasSubstep(element)) res++ return res } override fun calcButtonIndex(element: Any?, point: Point): Int? { if (element == null) return null val list = myListPopup.list val index = list.selectedIndex val bounds = list.getCellBounds(index, index) ?: return null JBInsets.removeFrom(bounds, PopupListElementRenderer.getListCellPadding()) val buttonsCount: Int = calcExtraButtonsCount(element) if (buttonsCount <= 0) return null val distanceToRight = bounds.x + bounds.width - point.x val buttonsToRight = distanceToRight / buttonWidth() if (buttonsToRight >= buttonsCount) return null return buttonsCount - buttonsToRight - 1 } override fun runInlineAction(element: Any, index: Int, event: InputEvent?) : Boolean { val pair = getExtraButtonsActions(element, event)[index] pair.first.run() return pair.second } private fun getExtraButtonsActions(element: Any, event: InputEvent?): List<Pair<Runnable, Boolean>> { if (!ExperimentalUI.isNewUI() || element !is ActionItem) return emptyList() val res: MutableList<Pair<Runnable, Boolean>> = mutableListOf() res.addAll(myStep.getInlineActions(element).map { item: InlineActionItem -> Pair(createInlineActionRunnable(item.action, event), true) }) if (!res.isEmpty() && myStep.hasSubstep(element)) res.add(Pair(createNextStepRunnable(element), false)) return res } override fun getExtraButtons(list: JList<*>, value: Any, isSelected: Boolean): List<JComponent> { if (value !is ActionItem) return emptyList() val inlineActions = myStep.getInlineActions(value) if (inlineActions.isEmpty()) return emptyList() val res: MutableList<JComponent> = java.util.ArrayList() val activeIndex = getActiveButtonIndex(list) for (i in 0 until inlineActions.size) res.add(createActionButton(inlineActions[i], i == activeIndex, isSelected)) res.add(createSubmenuButton(value, res.size == activeIndex)) return res } private fun getActiveButtonIndex(list: JList<*>): Int? = (list as? ListWithInlineButtons)?.selectedButtonIndex private fun createSubmenuButton(value: ActionItem, active: Boolean): JComponent { val icon = if (myStep.isFinal(value)) AllIcons.Actions.More else AllIcons.Icons.Ide.MenuArrow return createExtraButton(icon, active) } private fun createActionButton(action: InlineActionItem, active: Boolean, isSelected: Boolean): JComponent = createExtraButton(action.getIcon(isSelected), active) private fun createExtraButton(icon: Icon, active: Boolean): JComponent { val label = JLabel(icon) val leftRightInsets = JBUI.CurrentTheme.List.buttonLeftRightInsets() label.border = JBUI.Borders.empty(0, leftRightInsets) val panel = Wrapper(label) val size = panel.preferredSize size.width = buttonWidth(leftRightInsets) panel.preferredSize = size panel.minimumSize = size panel.isOpaque = active panel.background = JBUI.CurrentTheme.List.buttonHoverBackground() return panel } private fun buttonWidth(leftRightInsets: Int = JBUI.CurrentTheme.List.buttonLeftRightInsets()) : Int = JBUIScale.scale(INLINE_BUTTON_WIDTH + leftRightInsets * 2) private fun createNextStepRunnable(element: ActionItem) = Runnable { myListPopup.showNextStepPopup(myStep.onChosen(element, false), element) } private fun createInlineActionRunnable(action: AnAction, inputEvent: InputEvent?) = Runnable { myStep.performAction(action, inputEvent) } }
apache-2.0
50c254ba66cf4970bc6564628d41904a
40.4
163
0.757143
4.227353
false
false
false
false
RuneSuite/client
updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/SecureRandomFuture.kt
1
1720
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Type.BOOLEAN_TYPE import org.objectweb.asm.Type.VOID_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Field2 import org.runestar.client.updater.mapper.Method2 import java.security.SecureRandom import java.util.concurrent.ExecutorService import java.util.concurrent.Future class SecureRandomFuture : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == Any::class.type } .and { it.instanceMethods.any { it.returnType == SecureRandom::class.type } } @MethodParameters() class get : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == SecureRandom::class.type } } @MethodParameters() class shutdown : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == VOID_TYPE } } @MethodParameters() class isDone : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } class future : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == Future::class.type } } class executor : IdentityMapper.InstanceField() { override val predicate = predicateOf<Field2> { it.type == ExecutorService::class.type } } }
mit
2b9c870c68f210defce76b3b18da9393
38.113636
99
0.747093
4.332494
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/ui/compose/utils/WindowInsets.kt
1
1436
package com.nononsenseapps.feeder.ui.compose.utils import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.add import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp fun WindowInsets.addMargin( all: Dp = 0.dp, ) = addMargin(vertical = all, horizontal = all) fun WindowInsets.addMargin( vertical: Dp = 0.dp, horizontal: Dp = 0.dp, ) = addMargin( left = horizontal, right = horizontal, top = vertical, bottom = vertical, ) @Composable fun WindowInsets.addMarginLayout( start: Dp = 0.dp, end: Dp = 0.dp, top: Dp = 0.dp, bottom: Dp = 0.dp, ): WindowInsets { val layoutDirection = LocalLayoutDirection.current return addMargin( left = when (layoutDirection) { LayoutDirection.Ltr -> start LayoutDirection.Rtl -> end }, right = when (layoutDirection) { LayoutDirection.Ltr -> end LayoutDirection.Rtl -> start }, top = top, bottom = bottom, ) } fun WindowInsets.addMargin( left: Dp = 0.dp, right: Dp = 0.dp, top: Dp = 0.dp, bottom: Dp = 0.dp, ) = add( WindowInsets( left = left, right = right, top = top, bottom = bottom, ) )
gpl-3.0
e76b88e949a483a5e7d4f0c99165fe71
23.338983
56
0.638579
3.860215
false
false
false
false
deadpixelsociety/roto-ld34
core/src/com/thedeadpixelsociety/ld34/LD34Game.kt
1
2216
package com.thedeadpixelsociety.ld34 import com.badlogic.gdx.ApplicationAdapter import com.badlogic.gdx.Gdx import com.badlogic.gdx.assets.AssetManager import com.badlogic.gdx.audio.Music import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator import com.badlogic.gdx.graphics.glutils.ShapeRenderer import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer import com.badlogic.gdx.utils.Timer import com.thedeadpixelsociety.ld34.screens.GameScreenService import com.thedeadpixelsociety.ld34.screens.LevelScreen class LD34Game() : ApplicationAdapter() { val screenService = GameScreenService() override fun create() { createFonts() loadSounds() GameServices.put(AssetManager()) GameServices.put(ShapeRenderer()) GameServices.put(SpriteBatch()) GameServices.put(Box2DDebugRenderer()) GameServices.put(screenService) Timer.schedule(object : Timer.Task() { override fun run() { screenService.push(LevelScreen("-1")) } }, 1f) } private fun loadSounds() { Sounds.coin = Gdx.audio.newSound(Gdx.files.internal("sounds/coin.wav")) Sounds.bounce = Gdx.audio.newSound(Gdx.files.internal("sounds/bounce.wav")) Sounds.dead = Gdx.audio.newSound(Gdx.files.internal("sounds/dead.wav")) } private fun createFonts() { val gen = FreeTypeFontGenerator(Gdx.files.internal("fonts/PrintClearly.otf")) Fonts.font32 = gen.generateFont(FreeTypeFontGenerator.FreeTypeFontParameter().apply { size = 32 color = Color.WHITE }) gen.dispose() } override fun resize(width: Int, height: Int) { screenService.resize(width, height) } override fun render() { screenService.render(Gdx.graphics.deltaTime) } override fun pause() { screenService.pause() } override fun resume() { screenService.resume() } override fun dispose() { screenService.dispose() GameServices.dispose() Fonts.font32.dispose() Sounds.dispose() } }
mit
0d356fb052497403f2e8088a2740f620
28.959459
93
0.678249
4.165414
false
false
false
false
allotria/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/hints/settings/language/CasesPanel.kt
3
3209
// 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.codeInsight.hints.settings.language import com.intellij.codeInsight.hints.ChangeListener import com.intellij.codeInsight.hints.ImmediateConfigurable import com.intellij.openapi.util.NlsContexts import com.intellij.ui.ContextHelpLabel import com.intellij.util.ui.JBUI import java.awt.Component import java.awt.Dimension import javax.swing.Box import javax.swing.BoxLayout import javax.swing.JCheckBox import javax.swing.JPanel internal class CasesPanel( cases: List<ImmediateConfigurable.Case>, @NlsContexts.Checkbox mainCheckBoxName: String, private val loadMainCheckBoxValue: () -> Boolean, private val onUserChangedMainCheckBox: (Boolean) -> Unit, listener: ChangeListener, private val disabledExternally: () -> Boolean ) : JPanel() { private val caseListPanel = CaseListPanel(cases, listener) private val mainCheckBox = JCheckBox(mainCheckBoxName) init { layout = BoxLayout(this, BoxLayout.Y_AXIS) add(mainCheckBox) if (cases.isNotEmpty()) { add(caseListPanel) } mainCheckBox.addActionListener { val selected = mainCheckBox.isSelected caseListPanel.setEnabledCheckboxes(selected) onUserChangedMainCheckBox(selected) } updateFromSettings() revalidate() } fun updateFromSettings() { val mainCheckBoxSelected = loadMainCheckBoxValue() val disabledExternally = disabledExternally() mainCheckBox.isEnabled = !disabledExternally mainCheckBox.isSelected = mainCheckBoxSelected caseListPanel.setEnabledCheckboxes(mainCheckBoxSelected && !disabledExternally) caseListPanel.updateCheckBoxes() } } private class CaseListPanel(val cases: List<ImmediateConfigurable.Case>, listener: ChangeListener) : JPanel() { val checkBoxes = mutableListOf<JCheckBox>() init { layout = BoxLayout(this, BoxLayout.Y_AXIS) border = JBUI.Borders.empty(0, 20, 0, 0) add(Box.createRigidArea(JBUI.size(0, 5))) for (case in cases) { val checkBox = JCheckBox(case.name, case.value) checkBox.alignmentX = Component.LEFT_ALIGNMENT checkBoxes.add(checkBox) checkBox.addActionListener { case.value = checkBox.isSelected listener.settingsChanged() } val description = case.extendedDescription if (description != null) { val checkBoxPanel = JPanel() checkBoxPanel.layout = BoxLayout(checkBoxPanel, BoxLayout.X_AXIS) checkBoxPanel.alignmentX = Component.LEFT_ALIGNMENT checkBoxPanel.add(checkBox) checkBoxPanel.add(Box.createRigidArea(JBUI.size(5, 0))) checkBoxPanel.add(ContextHelpLabel.create(description)) add(checkBoxPanel) } else { add(checkBox) } add(Box.createRigidArea(Dimension(0, 3))) } add(Box.createRigidArea(JBUI.size(0, 5))) } fun setEnabledCheckboxes(value: Boolean) { for (checkBox in checkBoxes) { checkBox.isEnabled = value } } fun updateCheckBoxes() { for ((index, checkBox) in checkBoxes.withIndex()) { checkBox.isSelected = cases[index].value } } }
apache-2.0
5ca19ec4c2bb8321f1a52666d5b88079
32.789474
140
0.727018
4.330634
false
false
false
false
allotria/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/GlobalActionRecorder.kt
5
2733
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.recorder import com.intellij.application.subscribe import com.intellij.ide.IdeEventQueue import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.ex.AnActionListener import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.Disposer import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorPanel import java.awt.event.KeyEvent import java.awt.event.MouseEvent object GlobalActionRecorder { private val LOG = logger<GlobalActionRecorder>() private var disposable: Disposable? = null var isActive: Boolean = false private set private val globalActionListener = object : AnActionListener { override fun beforeActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { if (event.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions EventDispatcher.processActionEvent(action, event) LOG.info("IDEA is going to perform action ${action.templatePresentation.text}") } override fun beforeEditorTyping(c: Char, dataContext: DataContext) { LOG.info("IDEA typing detected: ${c}") } override fun afterActionPerformed(action: AnAction, dataContext: DataContext, event: AnActionEvent) { if (event.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions LOG.info("IDEA action performed ${action.templatePresentation.text}") } } private val globalAwtProcessor = IdeEventQueue.EventDispatcher { awtEvent -> try { when (awtEvent) { is MouseEvent -> EventDispatcher.processMouseEvent(awtEvent) is KeyEvent -> EventDispatcher.processKeyBoardEvent(awtEvent) } } catch (e: Exception) { LOG.warn(e) } false } fun activate() { if (isActive) return LOG.info("Global action recorder is active") disposable = Disposer.newDisposable() AnActionListener.TOPIC.subscribe(disposable!!, globalActionListener) IdeEventQueue.getInstance().addDispatcher(globalAwtProcessor, disposable) //todo: add disposal dependency on component isActive = true } fun deactivate() { if (isActive) { LOG.info("Global action recorder is non active") disposable?.let { this.disposable = null Disposer.dispose(it) } } isActive = false ContextChecker.clearContext() } }
apache-2.0
f93257d30977d5f18d62e2d9376211f0
34.973684
140
0.745335
4.640068
false
false
false
false
allotria/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/FusStatesRecorder.kt
2
2787
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.actions import com.intellij.internal.statistic.StatisticsDevKitUtil import com.intellij.internal.statistic.eventLog.EventLogNotificationService import com.intellij.internal.statistic.eventLog.LogEvent import com.intellij.internal.statistic.eventLog.fus.FeatureUsageLogger import com.intellij.internal.statistic.eventLog.fus.FeatureUsageStateEventTracker import com.intellij.internal.statistic.service.fus.collectors.FUStateUsagesLogger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.project.Project import java.util.concurrent.CompletableFuture import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicBoolean internal object FusStatesRecorder { private val log = logger<FusStatesRecorder>() private val statesLogger = FUStateUsagesLogger() private val state = ConcurrentLinkedQueue<LogEvent>() private var isRecordingInProgress = AtomicBoolean(false) private val lock = Any() fun recordStateAndWait(project: Project, indicator: ProgressIndicator): List<LogEvent>? { synchronized(lock) { state.clear() isRecordingInProgress.getAndSet(true) val subscriber: (LogEvent) -> Unit = { this.recordEvent(it) } val recorderId = StatisticsDevKitUtil.DEFAULT_RECORDER EventLogNotificationService.subscribe(subscriber, recorderId) try { val logApplicationStatesFuture = statesLogger.logApplicationStates() val logProjectStatesFuture = statesLogger.logProjectStates(project, indicator) val settingsFuture = CompletableFuture.allOf( *FeatureUsageStateEventTracker.EP_NAME.extensions.map { it.reportNow() }.toTypedArray()) CompletableFuture.allOf(logApplicationStatesFuture, logProjectStatesFuture, settingsFuture) .thenCompose { FeatureUsageLogger.flush() } .get(10, TimeUnit.SECONDS) } catch (e: Exception) { log.warn("Failed recording state collectors to log", e) return null } finally { EventLogNotificationService.unsubscribe(subscriber, recorderId) isRecordingInProgress.getAndSet(false) } return state.toList() } } private fun recordEvent(logEvent: LogEvent) { if (logEvent.event.state) { state.add(logEvent) } } fun getCurrentState(): List<LogEvent> { return state.toList() } fun isRecordingInProgress(): Boolean = isRecordingInProgress.get() fun isComparisonAvailable(): Boolean = !isRecordingInProgress.get() && state.isNotEmpty() }
apache-2.0
09d6ad49d4f81c81bb60eb403e9d33da
40.61194
140
0.763904
4.830156
false
false
false
false
Raizlabs/DBFlow
lib/src/main/kotlin/com/dbflow5/runtime/DirectModelNotifier.kt
1
5415
package com.dbflow5.runtime import com.dbflow5.adapter.ModelAdapter import com.dbflow5.config.DatabaseConfig import com.dbflow5.structure.ChangeAction /** * Description: Directly notifies about model changes. Users should use [.get] to use the shared * instance in [DatabaseConfig.Builder] */ class DirectModelNotifier /** * Private constructor. Use shared [.get] to ensure singular instance. */ private constructor() : ModelNotifier { private val modelChangedListenerMap = linkedMapOf<Class<*>, MutableSet<OnModelStateChangedListener<*>>>() private val tableChangedListenerMap = linkedMapOf<Class<*>, MutableSet<OnTableChangedListener>>() interface OnModelStateChangedListener<in T> { fun onModelChanged(model: T, action: ChangeAction) } interface ModelChangedListener<in T> : OnModelStateChangedListener<T>, OnTableChangedListener init { if (instanceCount > 0) { throw IllegalStateException("Cannot instantiate more than one DirectNotifier. Use DirectNotifier.get()") } instanceCount++ } @Suppress("UNCHECKED_CAST") override fun <T : Any> notifyModelChanged(model: T, adapter: ModelAdapter<T>, action: ChangeAction) { modelChangedListenerMap[adapter.table] ?.forEach { listener -> (listener as OnModelStateChangedListener<T>).onModelChanged(model, action) } tableChangedListenerMap[adapter.table] ?.forEach { listener -> listener.onTableChanged(adapter.table, action) } } override fun <T : Any> notifyTableChanged(table: Class<T>, action: ChangeAction) { tableChangedListenerMap[table]?.forEach { listener -> listener.onTableChanged(table, action) } } override fun newRegister(): TableNotifierRegister = DirectTableNotifierRegister(this) fun <T : Any> registerForModelChanges(table: Class<T>, listener: ModelChangedListener<T>) { registerForModelStateChanges(table, listener) registerForTableChanges(table, listener) } fun <T : Any> registerForModelStateChanges(table: Class<T>, listener: OnModelStateChangedListener<T>) { var listeners = modelChangedListenerMap[table] if (listeners == null) { listeners = linkedSetOf() modelChangedListenerMap.put(table, listeners) } listeners.add(listener) } fun <T> registerForTableChanges(table: Class<T>, listener: OnTableChangedListener) { var listeners = tableChangedListenerMap[table] if (listeners == null) { listeners = linkedSetOf() tableChangedListenerMap.put(table, listeners) } listeners.add(listener) } fun <T : Any> unregisterForModelChanges(table: Class<T>, listener: ModelChangedListener<T>) { unregisterForModelStateChanges(table, listener) unregisterForTableChanges(table, listener) } fun <T : Any> unregisterForModelStateChanges(table: Class<T>, listener: OnModelStateChangedListener<T>) { val listeners = modelChangedListenerMap[table] listeners?.remove(listener) } fun <T> unregisterForTableChanges(table: Class<T>, listener: OnTableChangedListener) { val listeners = tableChangedListenerMap[table] listeners?.remove(listener) } /** * Clears all listeners. */ fun clearListeners() = tableChangedListenerMap.clear() private class DirectTableNotifierRegister(private val directModelNotifier: DirectModelNotifier) : TableNotifierRegister { private val registeredTables = arrayListOf<Class<*>>() private var modelChangedListener: OnTableChangedListener? = null private val internalChangeListener = object : OnTableChangedListener { override fun onTableChanged(table: Class<*>?, action: ChangeAction) { modelChangedListener?.onTableChanged(table, action) } } override fun <T> register(tClass: Class<T>) { registeredTables.add(tClass) directModelNotifier.registerForTableChanges(tClass, internalChangeListener) } override fun <T> unregister(tClass: Class<T>) { registeredTables.remove(tClass) directModelNotifier.unregisterForTableChanges(tClass, internalChangeListener) } override fun unregisterAll() { registeredTables.forEach { table -> directModelNotifier.unregisterForTableChanges(table, internalChangeListener) } this.modelChangedListener = null } override fun setListener(listener: OnTableChangedListener?) { this.modelChangedListener = listener } override val isSubscribed: Boolean get() = !registeredTables.isEmpty() } companion object { internal var instanceCount = 0 private val notifier: DirectModelNotifier by lazy { DirectModelNotifier() } @JvmStatic fun get(): DirectModelNotifier = notifier operator fun invoke() = get() } }
mit
a0db9cd23a84c431d0da27327e0b3449
34.625
116
0.637673
5.252182
false
false
false
false
beergame/PintIonary
app/src/main/java/tk/beergame/pintionary/app/DrawActivity.kt
1
9944
package tk.beergame.pintionary.app import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.MotionEvent import android.view.SurfaceHolder import android.view.SurfaceView import android.widget.Button import android.widget.Toast import java.util.HashMap import io.realm.ErrorCode import io.realm.ObjectServerError import io.realm.Realm import io.realm.SyncConfiguration import io.realm.SyncCredentials import io.realm.SyncUser import tk.beergame.pintionary.app.models.Drawing import tk.beergame.pintionary.app.models.DrawingPoint /** * Class DrawActivity. */ class DrawActivity : AppCompatActivity(), SurfaceHolder.Callback { private var realm: Realm? = null private var surfaceView: SurfaceView? = null private var ratio = -1.0 private var marginLeft: Double = 0.toDouble() private var marginTop: Double = 0.toDouble() private var drawThread: DrawThread? = null private var color = "Charcoal" private var currentPath: Drawing? = null private val nameToColorMap = HashMap<String, Int>() private var ID = "" private var PASSWORD = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent ID = intent.getStringExtra("id") PASSWORD = intent.getStringExtra("password") setContentView(R.layout.activity_main) createUserIfNeededAndLogin() surfaceView = findViewById(R.id.surface_view) as SurfaceView surfaceView!!.holder.addCallback(this@DrawActivity) val btnClean = findViewById(R.id.btn_clean) as Button btnClean.setOnClickListener { wipeCanvas() Toast.makeText(this@DrawActivity, "Draw cleaned", Toast.LENGTH_SHORT).show() } } private fun createUserIfNeededAndLogin() { val syncCredentials = SyncCredentials.usernamePassword(ID, PASSWORD, false) SyncUser.loginAsync(syncCredentials, AUTH_URL, object : SyncUser.Callback<SyncUser> { override fun onSuccess(user: SyncUser) { val syncConfiguration = SyncConfiguration.Builder(user, REALM_URL).build() Realm.setDefaultConfiguration(syncConfiguration) realm = Realm.getDefaultInstance() } override fun onError(error: ObjectServerError) { if (error.errorCode == ErrorCode.INVALID_CREDENTIALS) { SyncUser.loginAsync(SyncCredentials.usernamePassword(ID, PASSWORD, true), AUTH_URL, this) } else { val errorMsg = "$error.errorCode, $error.errorMessage" Toast.makeText(applicationContext, errorMsg, Toast.LENGTH_LONG).show() } } }) } private fun wipeCanvas() { if (realm != null) { realm!!.executeTransactionAsync { r -> r.deleteAll() } } } override fun onDestroy() { super.onDestroy() if (realm != null) { realm!!.close() realm = null } } override fun onTouchEvent(event: MotionEvent): Boolean { if (realm == null) { return false } val viewLocation = IntArray(2) surfaceView!!.getLocationInWindow(viewLocation) val action = event.action if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { val x = event.rawX val y = event.rawY val pointX = (x.toDouble() - marginLeft - viewLocation[0].toDouble()) * ratio val pointY = (y.toDouble() - marginTop - viewLocation[1].toDouble()) * ratio when (action) { MotionEvent.ACTION_DOWN -> { realm!!.beginTransaction() currentPath = realm!!.createObject(Drawing::class.java) currentPath!!.color = color val point = realm!!.createObject<DrawingPoint>(DrawingPoint::class.java) point.x = pointX point.y = pointY currentPath!!.drawingPoints.add(point) realm!!.commitTransaction() } MotionEvent.ACTION_MOVE -> { realm!!.beginTransaction() val point = realm!!.createObject<DrawingPoint>(DrawingPoint::class.java) point.x = pointX point.y = pointY currentPath!!.drawingPoints.add(point) realm!!.commitTransaction() } MotionEvent.ACTION_UP -> { realm!!.beginTransaction() currentPath!!.completed = true val point = realm!!.createObject<DrawingPoint>(DrawingPoint::class.java) point.x = pointX point.y = pointY currentPath!!.drawingPoints.add(point) realm!!.commitTransaction() currentPath = null } else -> { realm!!.beginTransaction() currentPath!!.completed = true realm!!.commitTransaction() currentPath = null } } return true } return false } override fun surfaceCreated(surfaceHolder: SurfaceHolder) { if (drawThread == null) { drawThread = DrawThread() drawThread!!.start() } } override fun surfaceChanged(surfaceHolder: SurfaceHolder, format: Int, width: Int, height: Int) { val isPortrait = width < height ratio = if (isPortrait) { EDGE_WIDTH.toDouble() / height } else { EDGE_WIDTH.toDouble() / width } if (isPortrait) { marginLeft = (width - height) / 2.0 marginTop = 0.0 } else { marginLeft = 0.0 marginTop = (height - width) / 2.0 } } override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) { if (drawThread != null) { drawThread!!.shutdown() drawThread = null } ratio = -1.0 } internal inner class DrawThread : Thread() { private var bgRealm: Realm? = null fun shutdown() { synchronized(this) { if (bgRealm != null) { bgRealm!!.stopWaitForChange() } } interrupt() } override fun run() { while (ratio < 0 && !isInterrupted) { } if (isInterrupted) { return } var canvas: Canvas? = null try { val holder = surfaceView!!.holder canvas = holder.lockCanvas() canvas!!.drawColor(Color.WHITE) } finally { if (canvas != null) { surfaceView!!.holder.unlockCanvasAndPost(canvas) } } while (realm == null && !isInterrupted) { } if (isInterrupted) { return } bgRealm = Realm.getDefaultInstance() val results = bgRealm!!.where<Drawing>(Drawing::class.java).findAll() while (!isInterrupted) { try { val holder = surfaceView!!.holder canvas = holder.lockCanvas() synchronized(holder) { canvas!!.drawColor(Color.WHITE) val paint = Paint() for (drawing in results) { val points = drawing.drawingPoints val color = nameToColorMap[drawing.color] if (color != null) { paint.color = color } else { paint.color = -0xe3d7c1 } paint.style = Paint.Style.STROKE paint.strokeWidth = (4 / ratio).toFloat() val iterator = points.iterator() val firstPoint = iterator.next() val path = Path() val firstX = (firstPoint.x / ratio + marginLeft).toFloat() val firstY = (firstPoint.y / ratio + marginTop).toFloat() path.moveTo(firstX, firstY) while (iterator.hasNext()) { val point = iterator.next() val x = (point.x / ratio + marginLeft).toFloat() val y = (point.y / ratio + marginTop).toFloat() path.lineTo(x, y) } canvas!!.drawPath(path, paint) } } } finally { if (canvas != null) { surfaceView!!.holder.unlockCanvasAndPost(canvas) } } bgRealm!!.waitForChange() } synchronized(this) { bgRealm!!.close() } } } /** * Realm object server identification. */ companion object { private val REALM_URL = "realm://" + BuildConfig.OBJECT_SERVER_IP + ":9080/~/Draw" private val AUTH_URL = "http://" + BuildConfig.OBJECT_SERVER_IP + ":9080/auth" private val EDGE_WIDTH = 683 } }
mit
f1711d6e25a935990e29ffafc2821b69
34.137809
109
0.515788
5.289362
false
false
false
false
AndroidX/androidx
window/window-core/src/main/java/androidx/window/core/layout/WindowHeightSizeClass.kt
3
3280
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window.core.layout import androidx.window.core.layout.WindowHeightSizeClass.Companion.COMPACT import androidx.window.core.layout.WindowHeightSizeClass.Companion.EXPANDED import androidx.window.core.layout.WindowHeightSizeClass.Companion.MEDIUM /** * A class to represent the height size buckets for a viewport. The possible values are [COMPACT], * [MEDIUM], and [EXPANDED]. [WindowHeightSizeClass] should not be used as a proxy for the device * type. It is possible to have resizeable windows in different device types. * The viewport might change from a [COMPACT] all the way to an [EXPANDED] size class. */ class WindowHeightSizeClass private constructor( private val rawValue: Int ) { override fun toString(): String { val name = when (this) { COMPACT -> "COMPACT" MEDIUM -> "MEDIUM" EXPANDED -> "EXPANDED" else -> "UNKNOWN" } return "WindowHeightSizeClass: $name" } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as WindowHeightSizeClass if (rawValue != other.rawValue) return false return true } override fun hashCode(): Int { return rawValue } companion object { /** * A bucket to represent a compact height, typical for a phone that is in landscape. */ @JvmField val COMPACT: WindowHeightSizeClass = WindowHeightSizeClass(0) /** * A bucket to represent a medium height, typical for a phone in portrait or a tablet. */ @JvmField val MEDIUM: WindowHeightSizeClass = WindowHeightSizeClass(1) /** * A bucket to represent an expanded height window, typical for a large tablet or a * desktop form-factor. */ @JvmField val EXPANDED: WindowHeightSizeClass = WindowHeightSizeClass(2) /** * Returns a recommended [WindowHeightSizeClass] for the height of a window given the * height in DP. * @param dpHeight the height of the window in DP * @return A recommended size class for the height * @throws IllegalArgumentException if the height is negative */ @JvmStatic internal fun compute(dpHeight: Float): WindowHeightSizeClass { require(dpHeight > 0) { "Height must be positive, received $dpHeight" } return when { dpHeight < 480 -> COMPACT dpHeight < 900 -> MEDIUM else -> EXPANDED } } } }
apache-2.0
8d40d6f03efabbb561bf4d4adb67698c
33.536842
98
0.650915
4.8737
false
false
false
false
smmribeiro/intellij-community
platform/platform-tests/testSrc/com/intellij/openapi/progress/impl/CoroutineSuspenderTest.kt
9
2069
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.progress.impl import com.intellij.openapi.progress.* import com.intellij.testFramework.LightPlatformTestCase import com.intellij.util.ConcurrencyUtil import kotlinx.coroutines.* import kotlinx.coroutines.sync.Semaphore class CoroutineSuspenderTest : LightPlatformTestCase() { fun `test cancel paused coroutines`(): Unit = runBlocking { val count = 10 val started = Semaphore(count, count) val suspender = coroutineSuspender(false) val job = launch(Dispatchers.Default + suspender) { repeat(count) { launch { started.release() checkCanceled() fail("must not be called") } } } started.timeoutAcquire() // all coroutines are started letBackgroundThreadsSuspend() job.cancel() job.timeoutJoin() } fun `test resume paused coroutines`(): Unit = runBlocking { val count = 10 val started = Semaphore(count, count) val paused = Semaphore(count, count) val suspender = coroutineSuspender() val result = async(Dispatchers.Default + suspender) { (1..count).map { async { // coroutine context (including CoroutineSuspender) is inherited checkCanceled() // won't suspend started.release() paused.acquire() checkCanceled() // should suspend here it } }.awaitAll().sum() } started.timeoutAcquire() // all coroutines are started suspender.pause() // pause suspender before next checkCanceled repeat(count) { paused.release() // let coroutines pause in next checkCanceled } letBackgroundThreadsSuspend() val children = result.children.toList() assertSize(count, children) assertFalse(children.any { it.isCompleted }) suspender.resume() assertEquals(55, result.timeoutAwait()) } private suspend fun letBackgroundThreadsSuspend(): Unit = delay(ConcurrencyUtil.DEFAULT_TIMEOUT_MS) }
apache-2.0
7de36c1960305e9edd2cb3cf4bd4e695
32.918033
120
0.684872
4.767281
false
true
false
false
smmribeiro/intellij-community
plugins/kotlin/j2k/services/src/org/jetbrains/kotlin/nj2k/inference/common/SuperFunctionsProvider.kt
6
2533
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.nj2k.inference.common import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.nj2k.* import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import org.jetbrains.kotlin.utils.addToStdlib.safeAs abstract class SuperFunctionsProvider { abstract fun provideSuperFunctionDescriptors(function: KtFunction): List<FunctionDescriptor>? lateinit var inferenceContext: InferenceContext } class ResolveSuperFunctionsProvider(private val resolutionFacade: ResolutionFacade) : SuperFunctionsProvider() { override fun provideSuperFunctionDescriptors(function: KtFunction): List<FunctionDescriptor>? = function.resolveToDescriptorIfAny(resolutionFacade) ?.safeAs<FunctionDescriptor>() ?.original ?.overriddenDescriptors ?.toList() } class ByInfoSuperFunctionsProvider( private val resolutionFacade: ResolutionFacade, private val converterContext: NewJ2kConverterContext ) : SuperFunctionsProvider() { private val labelToFunction by lazy(LazyThreadSafetyMode.NONE) { val functions = mutableMapOf<JKElementInfoLabel, KtNamedFunction>() for (element in inferenceContext.elements) { element.forEachDescendantOfType<KtNamedFunction> { function -> val label = function.nameIdentifier?.getLabel() ?: return@forEachDescendantOfType functions += label to function } } functions } override fun provideSuperFunctionDescriptors(function: KtFunction): List<FunctionDescriptor>? = function.nameIdentifier?.elementInfo(converterContext)?.firstIsInstanceOrNull<FunctionInfo>() ?.superFunctions ?.mapNotNull { superFunction -> when (superFunction) { is ExternalSuperFunctionInfo -> superFunction.descriptor is InternalSuperFunctionInfo -> labelToFunction[superFunction.label]?.resolveToDescriptorIfAny(resolutionFacade) } } }
apache-2.0
00025ad4c52176e421b4cb0fba15bbbe
45.072727
158
0.737465
5.692135
false
false
false
false
android/compose-samples
Jetchat/app/src/main/java/com/example/compose/jetchat/components/JetchatScaffold.kt
1
1759
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.compose.jetchat.components import androidx.compose.material3.DrawerState import androidx.compose.material3.DrawerValue.Closed import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ModalDrawerSheet import androidx.compose.material3.ModalNavigationDrawer import androidx.compose.material3.rememberDrawerState import androidx.compose.runtime.Composable import com.example.compose.jetchat.theme.JetchatTheme @OptIn(ExperimentalMaterial3Api::class) @Composable fun JetchatDrawer( drawerState: DrawerState = rememberDrawerState(initialValue = Closed), onProfileClicked: (String) -> Unit, onChatClicked: (String) -> Unit, content: @Composable () -> Unit ) { JetchatTheme { ModalNavigationDrawer( drawerState = drawerState, drawerContent = { ModalDrawerSheet { JetchatDrawerContent( onProfileClicked = onProfileClicked, onChatClicked = onChatClicked ) } }, content = content ) } }
apache-2.0
4357b9317ba67cdaad5a03eca762ba46
34.18
75
0.702672
4.678191
false
false
false
false
eugenkiss/kotlinfx
kotlinfx-core/src/main/kotlin/kotlinfx/kalium/Test.kt
2
4296
// The purpose of this file is to be able to test new implementation ideas without // needing to generate all the bindings package kotlinfx.kalium.test import javafx.beans.value.ObservableValue import javafx.beans.value.WritableValue import javafx.beans.property.Property import javafx.scene.Node import javafx.scene.control.ComboBoxBase import javafx.scene.control.TextInputControl import javafx.scene.control.ProgressBar import javafx.scene.control.ProgressIndicator import javafx.scene.control.Slider import java.util.Observable import javafx.scene.control.Label import javafx.scene.shape.Rectangle import javafx.scene.paint.Paint import javafx.scene.shape.Shape private var enclosing: Pair<Any, String>? = null private val calcMap: MutableMap<Pair<Any, String>, () -> Unit> = hashMapOf() // To not set redundant listeners private var isConstruction = false private val listenerMap: MutableMap<Pair<Any, String>, MutableSet<Any>> = hashMapOf() public class V<T>(private var value: T) { val callbacks: MutableList<() -> Unit> = arrayListOf() fun invoke(): T { if (enclosing != null && (isConstruction || !listenerMap.containsKey(enclosing) || !listenerMap.get(enclosing)!!.contains(this))) { val e = enclosing!! listenerMap.getOrPut(e) { hashSetOf() } .add(this) callbacks.add { calcMap.get(e)!!() } } return value } fun u(newValue: T) { value = newValue for (callback in callbacks) { callback() } } } public class K<T>(private val calc: () -> T) { init { val e = Pair(this, "K") calcMap.put(e, {}) isConstruction = true; enclosing = e; calc(); enclosing = null; isConstruction = false } val callbacks: MutableList<() -> Unit> = arrayListOf() fun invoke(): T { if (enclosing != null && (isConstruction || !listenerMap.containsKey(enclosing) || !listenerMap.get(enclosing)!!.contains(this))) { val e = enclosing!! listenerMap.getOrPut(e) { hashSetOf() } .add(this) callbacks.add { calcMap.get(e)!!() } } return calc() } } private fun template<T>(name: String, f: (() -> T)?, thiz: Any, property: ObservableValue<T>): T { if (f == null) { if (enclosing != null && (isConstruction || !listenerMap.containsKey(enclosing) || !listenerMap.get(enclosing)!!.contains(thiz))) { val e = enclosing!! listenerMap.getOrPut(e) { hashSetOf() } .add(thiz) property.addListener { v: Any?, o: Any?, n: Any? -> calcMap.get(e)!!() } } } else { if (property is WritableValue<*>) { [suppress("UNCHECKED_CAST", "NAME_SHADOWING")] val property = property as WritableValue<T> val e = Pair(thiz, name) val g = { enclosing = e; property.setValue(f()); enclosing = null } calcMap.put(e, g) isConstruction = true; g(); isConstruction = false } } return property.getValue()!! } public fun Node.disable(f: (() -> Boolean)? = null): Boolean = template<Boolean>("disable", f, this, disableProperty()!!) public fun Node.hover(f: (() -> Boolean)? = null): Boolean = template<Boolean>("hover", f, this, hoverProperty()!!) public fun Node.style(f: (() -> String)? = null): String = template<String>("style", f, this, styleProperty()!!) public fun ComboBoxBase<String>.value(f: (() -> String)? = null): String = template<String>("value", f, this, valueProperty()!!) public fun TextInputControl.text(f: (() -> String)? = null): String = template<String>("text", f, this, textProperty()!!) public fun Label.text(f: (() -> String)? = null): String = template<String>("text", f, this, textProperty()!!) [suppress("UNCHECKED_CAST")] public fun ProgressIndicator.progress(f: (() -> Double)? = null): Double = template<Double>("progress", f, this, progressProperty()!! as ObservableValue<Double>) [suppress("UNCHECKED_CAST")] public fun Slider.value(f: (() -> Double)? = null): Double = template<Double>("slider", f, this, valueProperty()!! as ObservableValue<Double>) public fun Shape.fill(f: (() -> Paint)? = null): Paint = template<Paint>("fill", f, this, fillProperty()!!)
mit
922417e3c1eda6fb39b00a9798822e55
34.8
114
0.630354
3.966759
false
false
false
false
kickstarter/android-oss
app/src/test/java/com/kickstarter/viewmodels/EditorialViewHolderViewModelTest.kt
1
3176
package com.kickstarter.viewmodels import com.kickstarter.KSRobolectricTestCase import com.kickstarter.R import com.kickstarter.libs.Environment import com.kickstarter.ui.data.Editorial import org.junit.Test import rx.observers.TestSubscriber class EditorialViewHolderViewModelTest : KSRobolectricTestCase() { private lateinit var vm: EditorialViewHolderViewModel.ViewModel private val backgroundColor = TestSubscriber<Int>() private val ctaDescription = TestSubscriber<Int>() private val ctaTitle = TestSubscriber<Int>() private val editorial = TestSubscriber<Editorial>() private val graphic = TestSubscriber<Int>() private fun setUpEnvironment(environment: Environment) { this.vm = EditorialViewHolderViewModel.ViewModel(environment) this.vm.outputs.backgroundColor().subscribe(this.backgroundColor) this.vm.outputs.ctaDescription().subscribe(this.ctaDescription) this.vm.outputs.ctaTitle().subscribe(this.ctaTitle) this.vm.outputs.editorial().subscribe(this.editorial) this.vm.outputs.graphic().subscribe(this.graphic) } @Test fun testBackgroundColor() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.GO_REWARDLESS) this.backgroundColor.assertValue(R.color.kds_trust_700) } @Test fun testCtaDescription() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.GO_REWARDLESS) this.ctaDescription.assertValue(R.string.Find_projects_that_speak_to_you) } @Test fun testCtaTitle() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.GO_REWARDLESS) this.ctaTitle.assertValue(R.string.Back_it_because_you_believe_in_it) } @Test fun testEditorial() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.GO_REWARDLESS) this.vm.inputs.editorialClicked() this.editorial.assertValue(Editorial.GO_REWARDLESS) } @Test fun testGraphic() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.GO_REWARDLESS) this.graphic.assertValue(R.drawable.go_rewardless_header) } @Test fun testLightsOnTitle() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.LIGHTS_ON) this.ctaTitle.assertValue(R.string.Introducing_Lights_On) } @Test fun testLightsOnDescription() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.LIGHTS_ON) this.ctaDescription.assertValue(R.string.Support_creative_spaces_and_businesses_affected_by) } @Test fun testLightsOnGrafic() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.LIGHTS_ON) this.graphic.assertValue(R.drawable.lights_on) } @Test fun testLightsOnEditorialClicked() { setUpEnvironment(environment()) this.vm.inputs.configureWith(Editorial.LIGHTS_ON) this.vm.inputs.editorialClicked() this.editorial.assertValue(Editorial.LIGHTS_ON) } }
apache-2.0
a91db3f67f1f1c9664ccd5353eeef681
26.859649
100
0.707494
4.392808
false
true
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/stable/StableRecyclerFragment.kt
1
7973
package com.habitrpg.android.habitica.ui.fragments.inventory.stable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.extensions.getTranslatedType import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.inventory.Animal import com.habitrpg.android.habitica.models.user.OwnedMount import com.habitrpg.android.habitica.models.user.OwnedObject import com.habitrpg.android.habitica.models.user.OwnedPet import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.adapter.inventory.StableRecyclerAdapter import com.habitrpg.android.habitica.ui.fragments.BaseFragment import com.habitrpg.android.habitica.ui.helpers.* import io.reactivex.Maybe import io.reactivex.functions.BiFunction import io.reactivex.functions.Consumer import io.realm.RealmResults import java.util.* import javax.inject.Inject class StableRecyclerFragment : BaseFragment() { @Inject lateinit var inventoryRepository: InventoryRepository private val recyclerView: RecyclerViewEmptySupport? by bindView(R.id.recyclerView) private val emptyView: TextView? by bindView(R.id.emptyView) var adapter: StableRecyclerAdapter? = null var itemType: String? = null var itemTypeText: String? = null var user: User? = null internal var layoutManager: androidx.recyclerview.widget.GridLayoutManager? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) if (savedInstanceState != null) { this.itemType = savedInstanceState.getString(ITEM_TYPE_KEY, "") } return container?.inflate(R.layout.fragment_recyclerview) } override fun onDestroy() { inventoryRepository.close() super.onDestroy() } override fun injectFragment(component: UserComponent) { component.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) resetViews() recyclerView?.setEmptyView(emptyView) emptyView?.text = getString(R.string.empty_items, itemTypeText) layoutManager = androidx.recyclerview.widget.GridLayoutManager(activity, 2) layoutManager?.spanSizeLookup = object : androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { return if (adapter?.getItemViewType(position) == 0 || adapter?.getItemViewType(position) == 1) { layoutManager?.spanCount ?: 1 } else { 1 } } } recyclerView?.layoutManager = layoutManager activity?.let { recyclerView?.addItemDecoration(MarginDecoration(it, setOf(HEADER_VIEW_TYPE))) } adapter = recyclerView?.adapter as? StableRecyclerAdapter if (adapter == null) { adapter = StableRecyclerAdapter() adapter?.activity = this.activity as? MainActivity adapter?.itemType = this.itemType adapter?.context = context recyclerView?.adapter = adapter recyclerView?.itemAnimator = SafeDefaultItemAnimator() } this.loadItems() view.post { setGridSpanCount(view.width) } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(ITEM_TYPE_KEY, this.itemType) } private fun setGridSpanCount(width: Int) { var spanCount = 0 if (context != null && context?.resources != null) { val itemWidth: Float = context?.resources?.getDimension(R.dimen.pet_width) ?: 0.toFloat() spanCount = (width / itemWidth).toInt() } if (spanCount == 0) { spanCount = 1 } layoutManager?.spanCount = spanCount } private fun loadItems() { val observable: Maybe<out RealmResults<out Animal>> = if ("pets" == itemType) { inventoryRepository.getPets().firstElement() } else { inventoryRepository.getMounts().firstElement() } val ownedObservable: Maybe<out Map<String, OwnedObject>> = if ("pets" == itemType) { inventoryRepository.getOwnedPets().firstElement() } else { inventoryRepository.getOwnedMounts().firstElement() }.map { val animalMap = mutableMapOf<String, OwnedObject>() it.forEach { animal -> val castedAnimal = animal as? OwnedObject ?: return@forEach animalMap[castedAnimal.key ?: ""] = castedAnimal } animalMap } compositeSubscription.add(observable.zipWith(ownedObservable, BiFunction<RealmResults<out Animal>, Map<String, OwnedObject>, ArrayList<Any>> { unsortedAnimals, ownedAnimals -> mapAnimals(unsortedAnimals, ownedAnimals) }).subscribe(Consumer { items -> adapter?.setItemList(items) }, RxErrorHandler.handleEmptyError())) } private fun mapAnimals(unsortedAnimals: RealmResults<out Animal>, ownedAnimals: Map<String, OwnedObject>): ArrayList<Any> { val items = ArrayList<Any>() var lastAnimal: Animal = unsortedAnimals[0] ?: return items var lastSectionTitle = "" for (animal in unsortedAnimals) { val identifier = if (animal.animal.isNotEmpty() && animal.type != "special") animal.animal else animal.key val lastIdentifier = if (lastAnimal.animal.isNotEmpty()) lastAnimal.animal else lastAnimal.key if (identifier != lastIdentifier || animal === unsortedAnimals[unsortedAnimals.size - 1]) { if (!((lastAnimal.type == "premium" || lastAnimal.type == "special") && lastAnimal.numberOwned == 0)) { items.add(lastAnimal) } lastAnimal = animal } if (animal.type != lastSectionTitle) { if (items.size > 0 && items[items.size - 1].javaClass == String::class.java) { items.removeAt(items.size - 1) } items.add(animal.getTranslatedType(context)) lastSectionTitle = animal.type } when (itemType) { "pets" -> { val ownedPet = ownedAnimals[animal?.key] as? OwnedPet if (ownedPet?.trained ?: 0 > 0) { lastAnimal.numberOwned += 1 } } "mounts" -> { val ownedMount = ownedAnimals[animal?.key] as? OwnedMount if (ownedMount?.owned == true) { lastAnimal.numberOwned = lastAnimal.numberOwned + 1 } } } } if (!((lastAnimal.type == "premium" || lastAnimal.type == "special") && lastAnimal.numberOwned == 0)) { items.add(lastAnimal) } items.add(0, "header") return items } companion object { private const val ITEM_TYPE_KEY = "CLASS_TYPE_KEY" private const val HEADER_VIEW_TYPE = 0 private const val SECTION_VIEW_TYPE = 1 } }
gpl-3.0
34f6b205d28a797f2cafeea006648765
39.526042
183
0.625235
5.011314
false
false
false
false
rei-m/HBFav_material
app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/dialog/EditUserIdDialogFragmentViewModel.kt
1
2851
/* * Copyright (c) 2017. Rei Matsushita * * 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 me.rei_m.hbfavmaterial.viewmodel.widget.dialog import android.arch.lifecycle.ViewModel import android.arch.lifecycle.ViewModelProvider import android.databinding.ObservableField import android.view.View import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject import me.rei_m.hbfavmaterial.model.UserModel class EditUserIdDialogFragmentViewModel(private val userModel: UserModel, private val userIdErrorMessage: String, userId: String) : ViewModel() { val userId: ObservableField<String> = ObservableField(userId) val idErrorMessage: ObservableField<String> = ObservableField("") val isLoading = userModel.isLoading val isRaisedError = userModel.isRaisedError private var dismissDialogEventSubject = PublishSubject.create<Unit>() val dismissDialogEvent: io.reactivex.Observable<Unit> = dismissDialogEventSubject private val disposable: CompositeDisposable = CompositeDisposable() init { disposable.addAll(userModel.user.subscribe { if (this.userId.get() == "") { this.userId.set(it.id) } else { idErrorMessage.set("") dismissDialogEventSubject.onNext(Unit) } }, userModel.unauthorised.subscribe { idErrorMessage.set(userIdErrorMessage) }) } @Suppress("UNUSED_PARAMETER") fun onClickSetUp(view: View) { userModel.setUpUserId(userId.get()) } @Suppress("UNUSED_PARAMETER") fun onClickCancel(view: View) { dismissDialogEventSubject.onNext(Unit) } class Factory(private val userModel: UserModel, private val userIdErrorMessage: String, var userId: String = "") : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(EditUserIdDialogFragmentViewModel::class.java)) { return EditUserIdDialogFragmentViewModel(userModel, userIdErrorMessage, userId) as T } throw IllegalArgumentException("Unknown class name") } } }
apache-2.0
24373d2f03714e5e543b38aa5d48168c
37.527027
112
0.685374
4.907057
false
false
false
false
pengwei1024/sampleShare
HenCoderSample/class2/src/main/java/com/apkfuns/class2/CustomView.kt
1
4486
package com.apkfuns.class2 import android.content.Context import android.graphics.* import android.util.AttributeSet import android.view.View import android.graphics.LightingColorFilter import android.graphics.ColorFilter import android.graphics.CornerPathEffect import android.graphics.PathEffect import android.graphics.DiscretePathEffect import android.graphics.BlurMaskFilter /** * Created by pengwei on 2017/12/8. * LinearGradient、RadialGradient、SweepGradient、BitmapShader、ComposeShader */ class CustomView : View { constructor(context: Context?) : super(context) constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun onDraw(canvas: Canvas) { super.onDraw(canvas) val paint = Paint(Paint.ANTI_ALIAS_FLAG) // 绘制渐变的圆形 // var shader = LinearGradient(100f, 100f, 500f, 500f, Color.parseColor("#E91E63"), // Color.parseColor("#2196F3"), Shader.TileMode.CLAMP) // paint.shader = shader // canvas.drawCircle(300f, 300f, 200f, paint) // paint.textSize = 72f // canvas.drawText("Hello World", 20f, 60f, paint) // BitmapShader 和 配合实现圆形头像 // var bitmap:Bitmap = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) // bitmap = Bitmap.createScaledBitmap(bitmap, 600, 600, true) // val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) // paint.shader = shader // canvas.drawCircle(300f, 300f, 200f, paint) // 混合着色器 // var bitmap1 = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher) // val shader1 = BitmapShader(bitmap1, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT) // var bitmap2 = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher_round) // val shader2 = BitmapShader(bitmap2, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT) // val shader = ComposeShader(shader1, shader2, PorterDuff.Mode.SRC_OVER) // paint.shader = shader // // ComposeShader() 在硬件加速下是不支持两个相同类型的 Shader 的,所以这里也需要关闭硬件加速才能看到效果 // setLayerType(View.LAYER_TYPE_SOFTWARE, null) // canvas.drawRect(0f, 0f, 500f, 500f, paint) // ColorFilter // var option = BitmapFactory.Options() // option.inSampleSize = 2 // var bitmap = BitmapFactory.decodeResource(resources, R.mipmap.pic1, option) // val lightingColorFilter = LightingColorFilter(0x00ffff, 0x003000) // paint.colorFilter = lightingColorFilter // // LightingColorFilter PorterDuffColorFilter 和 ColorMatrixColorFilter // canvas.drawBitmap(bitmap, 0f, 0f, paint) // setStrokeCap // paint.strokeCap = Paint.Cap.ROUND // 设置线头的形状。线头形状有三种:BUTT 平头、ROUND 圆头、SQUARE 方头。默认为 BUTT // paint.strokeJoin = Paint.Join.ROUND // 拐角的形状 // paint.strokeWidth = 30f // canvas.drawLine(50f, 50f, 300f, 300f, paint) // 绘制虚线轮廓 // paint.style = Paint.Style.STROKE // var pathEffect = DashPathEffect(floatArrayOf(10f, 5f), 10f) // paint.pathEffect = pathEffect // canvas.drawCircle(300f, 300f, 200f, paint) // // var path = Path() // path.lineTo(100f, 100f) // path.lineTo(200f, 0f) // var pathEffect2 = CornerPathEffect(20f) // val pathEffect3 = DiscretePathEffect(20f, 5f) // paint.pathEffect = pathEffect3 // canvas.drawPath(path, paint) // 文字添加阴影 // paint.textSize = 70f // paint.setShadowLayer(10f, 0f, 0f, Color.RED) // canvas.drawText("Hello World", 80f, 300f, paint) // 设置模糊效果 // 需要关闭硬件加速 setLayerType(View.LAYER_TYPE_SOFTWARE, null) paint.maskFilter = BlurMaskFilter(50f, BlurMaskFilter.Blur.NORMAL) val options = BitmapFactory.Options() options.inSampleSize = 2 val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.pic2, options) canvas.drawBitmap(bitmap, 100f, 100f, paint) } }
apache-2.0
3afd98626d04b4adf2b9f5fcd4ef27dd
37.554545
144
0.676179
3.652024
false
false
false
false
Zoltu/StubKafkaBroker
src/main/kotlin/com/zoltu/extensions/NioExtensions.kt
1
2723
package com.zoltu.extensions import java.nio.ByteBuffer import java.nio.channels.AsynchronousServerSocketChannel import java.nio.channels.AsynchronousSocketChannel import java.nio.channels.CompletionHandler import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit fun AsynchronousServerSocketChannel.listen(): CompletableFuture<AsynchronousSocketChannel> { val completionHandler = object : CompletionHandler<AsynchronousSocketChannel, CompletableFuture<AsynchronousSocketChannel>> { override fun completed(socketChannel: AsynchronousSocketChannel, attachment: CompletableFuture<AsynchronousSocketChannel>) { attachment.complete(socketChannel) } override fun failed(throwable: Throwable, attachment: CompletableFuture<AsynchronousSocketChannel>) { attachment.completeExceptionally(throwable) } } val completableFuture = CompletableFuture<AsynchronousSocketChannel>() this.accept<CompletableFuture<AsynchronousSocketChannel>>(completableFuture, completionHandler) return completableFuture } fun AsynchronousSocketChannel.readInt(): CompletableFuture<Int> { return this.readBytes(4).thenApply { it.int } } fun AsynchronousSocketChannel.readBytes(length: Int): CompletableFuture<ByteBuffer> { data class Attachment(val future: CompletableFuture<ByteBuffer>, val byteBuffer: ByteBuffer) val completionHandler = object : CompletionHandler<Int, Attachment> { override fun completed(result: Int, attachment: Attachment) { if (result == -1) { attachment.future.completeExceptionally(Exception("Reached the end of the TCP stream.")) return } attachment.byteBuffer.flip() attachment.future.complete(attachment.byteBuffer) } override fun failed(throwable: Throwable, attachment: Attachment) { attachment.future.completeExceptionally(throwable) } } val completableFuture = CompletableFuture<ByteBuffer>() val byteBuffer = ByteBuffer.allocate(length); val attachment = Attachment(completableFuture, byteBuffer) this.read<Attachment>(byteBuffer, attachment, completionHandler) return completableFuture } fun AsynchronousSocketChannel.writeBytes(byteBuffers: Array<ByteBuffer>): CompletableFuture<Nothing> { val completionHandler = object : CompletionHandler<Long, CompletableFuture<Nothing>> { override fun completed(result: Long, attachment: CompletableFuture<Nothing>) { attachment.complete(null) } override fun failed(throwable: Throwable, attachment: CompletableFuture<Nothing>) { attachment.completeExceptionally(throwable) } } val completableFuture = CompletableFuture<Nothing>() this.write(byteBuffers, 0, byteBuffers.size, 0, TimeUnit.MILLISECONDS, completableFuture, completionHandler) return completableFuture }
cc0-1.0
09c6086e1d5afd357c4aa75c4da71851
38.463768
126
0.813074
4.906306
false
false
false
false
ngthtung2805/dalatlaptop
app/src/main/java/com/tungnui/abccomputer/models/Order.kt
1
3583
package com.tungnui.abccomputer.models import android.os.Parcel import android.os.Parcelable import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class Order ( @SerializedName("id") @Expose var id: Int? = null, @SerializedName("parent_id") @Expose var parentId: Int? = null, @SerializedName("number") @Expose var number: String? = null, @SerializedName("order_key") @Expose var orderKey: String? = null, @SerializedName("created_via") @Expose var createdVia: String? = null, @SerializedName("version") @Expose var version: String? = null, @SerializedName("status") @Expose var status: String? = null, @SerializedName("currency") @Expose var currency: String? = null, @SerializedName("date_created") @Expose var dateCreated: String? = null, @SerializedName("date_created_gmt") @Expose var dateCreatedGmt: String? = null, @SerializedName("date_modified") @Expose var dateModified: String? = null, @SerializedName("date_modified_gmt") @Expose var dateModifiedGmt: String? = null, @SerializedName("discount_total") @Expose var discountTotal: String? = null, @SerializedName("discount_tax") @Expose var discountTax: String? = null, @SerializedName("shipping_total") @Expose var shippingTotal: String? = null, @SerializedName("shipping_tax") @Expose var shippingTax: String? = null, @SerializedName("cart_tax") @Expose var cartTax: String? = null, @SerializedName("total") @Expose var total: String? = null, @SerializedName("total_tax") @Expose var totalTax: String? = null, @SerializedName("prices_include_tax") @Expose var pricesIncludeTax: Boolean? = null, @SerializedName("customer_id") @Expose var customerId: Int? = null, @SerializedName("customer_ip_address") @Expose var customerIpAddress: String? = null, @SerializedName("customer_user_agent") @Expose var customerUserAgent: String? = null, @SerializedName("customer_note") @Expose var customerNote: String? = null, @SerializedName("billing") @Expose var billing: Billing? = null, @SerializedName("shipping") @Expose var shipping: Shipping? = null, @SerializedName("payment_method") @Expose var paymentMethod: String? = null, @SerializedName("payment_method_title") @Expose var paymentMethodTitle: String? = null, @SerializedName("transaction_id") @Expose var transactionId: String? = null, @SerializedName("date_paid") @Expose var datePaid: Any? = null, @SerializedName("date_paid_gmt") @Expose var datePaidGmt: Any? = null, @SerializedName("date_completed") @Expose var dateCompleted: Any? = null, @SerializedName("date_completed_gmt") @Expose var dateCompletedGmt: Any? = null, @SerializedName("cart_hash") @Expose var cartHash: String? = null, @SerializedName("line_items") @Expose var lineItems: List<LineItem>? = null, @SerializedName("tax_lines") @Expose var taxLines: List<Any>? = null, @SerializedName("shipping_lines") @Expose var shippingLines: List<ShippingLine>? = null, /* @SerializedName("fee_lines") @Expose var feeLines: List<Any>? = null, @SerializedName("coupon_lines") @Expose var couponLines: List<Any>? = null,*/ @SerializedName("refunds") @Expose var refunds: List<Any>? = null )
mit
5bedc733415eaf13c71038391c8ca69a
26.351145
50
0.65113
4.003352
false
false
false
false
androidx/androidx
benchmark/benchmark-common/src/main/java/androidx/benchmark/Errors.kt
3
13316
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.benchmark import android.content.Intent import android.content.IntentFilter import android.content.pm.ApplicationInfo import android.os.BatteryManager import android.os.Build import android.util.Log import androidx.test.platform.app.InstrumentationRegistry import java.io.File /** * Lazy-initialized test-suite global state for errors around measurement inaccuracy. */ internal object Errors { /** * Same as trimMargins, but add newlines on either side. */ @Suppress("MemberVisibilityCanBePrivate") internal fun String.trimMarginWrapNewlines(): String { return "\n" + trimMargin() + " \n" } @Suppress("MemberVisibilityCanBePrivate") internal fun Set<String>.toDisplayString(): String { return toList().sorted().joinToString(" ") } private const val TAG = "Benchmark" val PREFIX: String private val UNSUPPRESSED_WARNING_MESSAGE: String? private var warningString: String? = null /** * Battery percentage required to avoid low battery warning. * * This number is supposed to be a conservative cutoff for when low-battery-triggered power * savings modes (such as disabling cores) may be enabled. It's possible that * [BatteryManager.EXTRA_BATTERY_LOW] is a better source of truth for this, but we want to be * conservative in case the device loses power slowly while benchmarks run. */ private const val MINIMUM_BATTERY_PERCENT = 25 fun acquireWarningStringForLogging(): String? { val ret = warningString warningString = null return ret } val isEmulator = Build.FINGERPRINT.startsWith("generic") || Build.FINGERPRINT.startsWith("unknown") || Build.MODEL.contains("google_sdk") || Build.MODEL.contains("Emulator") || Build.MODEL.contains("Android SDK built for x86") || Build.MANUFACTURER.contains("Genymotion") || Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic") || "google_sdk" == Build.PRODUCT private val isDeviceRooted = arrayOf( "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su" ).any { File(it).exists() } /** * Note: initialization may not occur before entering BenchmarkState code, since we assert * state (like activity presence) that only happens during benchmark run. For this reason, be * _very_ careful about where this object is accessed. */ init { val context = InstrumentationRegistry.getInstrumentation().targetContext val appInfo = context.applicationInfo var warningPrefix = "" var warningString = "" if (Arguments.profiler?.requiresDebuggable != true && (appInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0) ) { warningPrefix += "DEBUGGABLE_" warningString += """ |WARNING: Debuggable Benchmark | Benchmark is running with debuggable=true, which drastically reduces | runtime performance in order to support debugging features. Run | benchmarks with debuggable=false. Debuggable affects execution speed | in ways that mean benchmark improvements might not carry over to a | real user's experience (or even regress release performance). """.trimMarginWrapNewlines() } if (isEmulator) { warningPrefix += "EMULATOR_" warningString += """ |WARNING: Running on Emulator | Benchmark is running on an emulator, which is not representative of | real user devices. Use a physical device to benchmark. Emulator | benchmark improvements might not carry over to a real user's | experience (or even regress real device performance). """.trimMarginWrapNewlines() } if (Build.FINGERPRINT.contains(":eng/")) { warningPrefix += "ENG-BUILD_" warningString += """ |WARNING: Running on Eng Build | Benchmark is running on device flashed with a '-eng' build. Eng builds | of the platform drastically reduce performance to enable testing | changes quickly. For this reason they should not be used for | benchmarking. Use a '-user' or '-userdebug' system image. """.trimMarginWrapNewlines() } val arguments = InstrumentationRegistry.getArguments() if (arguments.getString("coverage") == "true") { warningPrefix += "CODE-COVERAGE_" warningString += """ |WARNING: Code coverage enabled | Benchmark is running with code coverage enabled, which typically alters the dex | in a way that can affect performance. Ensure that code coverage is disabled by | setting testCoverageEnabled to false in the buildType your benchmarks run in. """.trimMarginWrapNewlines() } if (isDeviceRooted && !CpuInfo.locked) { warningPrefix += "UNLOCKED_" warningString += """ |WARNING: Unlocked CPU clocks | Benchmark appears to be running on a rooted device with unlocked CPU | clocks. Unlocked CPU clocks can lead to inconsistent results due to | dynamic frequency scaling, and thermal throttling. On a rooted device, | lock your device clocks to a stable frequency with `./gradlew lockClocks` """.trimMarginWrapNewlines() } if (!CpuInfo.locked && IsolationActivity.isSustainedPerformanceModeSupported() && !IsolationActivity.sustainedPerformanceModeInUse ) { warningPrefix += "UNSUSTAINED-ACTIVITY-MISSING_" warningString += """ |WARNING: Cannot use SustainedPerformanceMode without IsolationActivity | Benchmark running on device that supports Window.setSustainedPerformanceMode, | but not launching IsolationActivity via the AndroidBenchmarkRunner. This | Activity is required to limit CPU clock max frequency, to prevent thermal | throttling. To fix this, add the following to your benchmark module-level | build.gradle: | android.defaultConfig.testInstrumentationRunner | = "androidx.benchmark.junit4.AndroidBenchmarkRunner" """.trimMarginWrapNewlines() } else if (IsolationActivity.singleton.get() == null) { warningPrefix += "ACTIVITY-MISSING_" warningString += """ |WARNING: Not using IsolationActivity via AndroidBenchmarkRunner | AndroidBenchmarkRunner should be used to isolate benchmarks from interference | from other visible apps. To fix this, add the following to your module-level | build.gradle: | android.defaultConfig.testInstrumentationRunner | = "androidx.benchmark.junit4.AndroidBenchmarkRunner" """.trimMarginWrapNewlines() } if (Arguments.profiler == StackSamplingSimpleperf) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { warningPrefix += "SIMPLEPERF_" warningString += """ |ERROR: Cannot use Simpleperf on this device's API level (${Build.VERSION.SDK_INT}) | Simpleperf prior to API 28 (P) requires AOT compilation, and isn't | currently supported by the benchmark library. """.trimMarginWrapNewlines() } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P && !isDeviceRooted) { warningPrefix += "SIMPLEPERF_" warningString += """ |ERROR: Cannot use Simpleperf on this device's API level (${Build.VERSION.SDK_INT}) | without root. Simpleperf on API 28 (P) can only be used on a rooted device, | or when the APK is debuggable. Debuggable performance measurements should | be avoided, due to measurement inaccuracy. """.trimMarginWrapNewlines() } else if ( Build.VERSION.SDK_INT >= 29 && !context.isProfileableByShell() ) { warningPrefix += "SIMPLEPERF_" warningString += """ |ERROR: Apk must be profileable to use simpleperf. | ensure you put <profileable android:shell="true"/> within the | <application ...> tag of your benchmark module """.trimMarginWrapNewlines() } } val filter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) val batteryPercent = context.registerReceiver(null, filter)?.run { val level = getIntExtra(BatteryManager.EXTRA_LEVEL, 100) val scale = getIntExtra(BatteryManager.EXTRA_SCALE, 100) level * 100 / scale } ?: 100 if (batteryPercent < MINIMUM_BATTERY_PERCENT) { warningPrefix += "LOW-BATTERY_" warningString += """ |WARNING: Device has low battery ($batteryPercent%) | When battery is low, devices will often reduce performance (e.g. disabling big | cores) to save remaining battery. This occurs even when they are plugged in. | Wait for your battery to charge to at least $MINIMUM_BATTERY_PERCENT%. | Currently at $batteryPercent%. """.trimMarginWrapNewlines() } Arguments.profiler?.run { val profilerName = javaClass.simpleName warningPrefix += "PROFILED_" warningString += """ |WARNING: Using profiler=$profilerName, results will be affected. """.trimMarginWrapNewlines() } PREFIX = warningPrefix if (warningString.isNotEmpty()) { this.warningString = warningString warningString.split("\n").map { Log.w(TAG, it) } } val warningSet = PREFIX .split('_') .filter { it.isNotEmpty() } .toSet() val alwaysSuppressed = setOf("PROFILED") val neverSuppressed = setOf("SIMPLEPERF") val suppressedWarnings = Arguments.suppressedErrors + alwaysSuppressed - neverSuppressed val unsuppressedWarningSet = warningSet - suppressedWarnings UNSUPPRESSED_WARNING_MESSAGE = if (unsuppressedWarningSet.isNotEmpty()) { """ |ERRORS (not suppressed): ${unsuppressedWarningSet.toDisplayString()} |(Suppressed errors: ${Arguments.suppressedErrors.toDisplayString()}) |$warningString |While you can suppress these errors (turning them into warnings) |PLEASE NOTE THAT EACH SUPPRESSED ERROR COMPROMISES ACCURACY | |// Sample suppression, in a benchmark module's build.gradle: |android { | defaultConfig { | // Enable measuring on an emulator, or devices with low battery | testInstrumentationRunnerArguments["androidx.benchmark.suppressErrors"] = "EMULATOR,LOW-BATTERY" | } |} """.trimMargin() } else { null } } /** * We don't throw immediately when the error is detected, since this will result in an error * deeply buried in a stack of intializer errors. Instead, they're deferred until this method * call. */ fun throwIfError() { // Note - we ignore configuration errors in dry run mode, since we don't care about // measurement accuracy, and we want to support e.g. running on emulators, -eng builds, and // unlocked devices in presubmit. if (!Arguments.dryRunMode && UNSUPPRESSED_WARNING_MESSAGE != null) { throw AssertionError(UNSUPPRESSED_WARNING_MESSAGE) } if (Arguments.error != null) { throw AssertionError(Arguments.error) } } }
apache-2.0
04752ed6adc54866561c291b104cbcbd
45.236111
121
0.602959
5.084383
false
false
false
false
ncoe/rosetta
Pells_equation/Kotlin/src/Pell.kt
1
1659
import java.math.BigInteger import kotlin.math.sqrt class BIRef(var value: BigInteger) { operator fun minus(b: BIRef): BIRef { return BIRef(value - b.value) } operator fun times(b: BIRef): BIRef { return BIRef(value * b.value) } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as BIRef if (value != other.value) return false return true } override fun hashCode(): Int { return value.hashCode() } override fun toString(): String { return value.toString() } } fun f(a: BIRef, b: BIRef, c: Int) { val t = a.value a.value = b.value b.value = b.value * BigInteger.valueOf(c.toLong()) + t } fun solvePell(n: Int, a: BIRef, b: BIRef) { val x = sqrt(n.toDouble()).toInt() var y = x var z = 1 var r = x shl 1 val e1 = BIRef(BigInteger.ONE) val e2 = BIRef(BigInteger.ZERO) val f1 = BIRef(BigInteger.ZERO) val f2 = BIRef(BigInteger.ONE) while (true) { y = r * z - y z = (n - y * y) / z r = (x + y) / z f(e1, e2, r) f(f1, f2, r) a.value = f2.value b.value = e2.value f(b, a, x) if (a * a - BIRef(n.toBigInteger()) * b * b == BIRef(BigInteger.ONE)) { return } } } fun main() { val x = BIRef(BigInteger.ZERO) val y = BIRef(BigInteger.ZERO) intArrayOf(61, 109, 181, 277).forEach { solvePell(it, x, y) println("x^2 - %3d * y^2 = 1 for x = %,27d and y = %,25d".format(it, x.value, y.value)) } }
mit
d54a52668dc4683db95f3d40fd54da63
22.7
95
0.536468
2.983813
false
false
false
false
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/wizards/archetype/CatalogUiUtil.kt
1
2933
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.idea.maven.wizards.archetype import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.ui.layout.* import com.intellij.util.io.exists import com.intellij.util.text.nullize import org.jetbrains.idea.maven.indices.arhetype.MavenCatalog import org.jetbrains.idea.maven.indices.arhetype.MavenCatalogManager import org.jetbrains.idea.maven.wizards.MavenWizardBundle import java.net.URL import kotlin.io.path.Path import kotlin.io.path.name internal fun createCatalog(name: String, location: String): MavenCatalog? { if (MavenCatalogManager.isLocal(location)) { val path = getPathOrNull(location) ?: return null return MavenCatalog.Local(name, path) } else { val url = getUrlOrNull(location) ?: return null return MavenCatalog.Remote(name, url) } } internal fun getPathOrError(location: String) = runCatching { Path(FileUtil.expandUserHome(location)) } internal fun getUrlOrError(location: String) = runCatching { URL(location) } internal fun getPathOrNull(location: String) = getPathOrError(location).getOrNull() internal fun getUrlOrNull(location: String) = getUrlOrError(location).getOrNull() internal fun suggestCatalogNameByLocation(location: String): String { if (MavenCatalogManager.isLocal(location)) { return getPathOrNull(location)?.name?.nullize() ?: location } else { return getUrlOrNull(location)?.host?.nullize() ?: location } } internal fun ValidationInfoBuilder.validateCatalogLocation(location: String): ValidationInfo? { if (location.isEmpty()) { return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.empty")) } if (MavenCatalogManager.isLocal(location)) { return validateLocalLocation(location) } else { return validateRemoteLocation(location) } } private fun ValidationInfoBuilder.validateLocalLocation(location: String): ValidationInfo? { val pathOrError = getPathOrError(location) val exception = pathOrError.exceptionOrNull() if (exception != null) { val message = exception.message return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.invalid", message)) } val path = pathOrError.getOrThrow() if (!path.exists()) { return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.not.exists")) } return null } private fun ValidationInfoBuilder.validateRemoteLocation(location: String): ValidationInfo? { val exception = getUrlOrError(location).exceptionOrNull() if (exception != null) { val message = exception.message return error(MavenWizardBundle.message("maven.new.project.wizard.archetype.catalog.dialog.location.error.invalid", message)) } return null }
apache-2.0
12f4ac1999e7f3d4132654631a1eb8cd
37.605263
128
0.775656
4.142655
false
false
false
false
smmribeiro/intellij-community
plugins/yaml/src/org/jetbrains/yaml/formatter/YamlInjectedBlockFactory.kt
2
9437
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. @file:JvmName("YamlInjectedBlockFactory") package org.jetbrains.yaml.formatter import com.intellij.formatting.* import com.intellij.injected.editor.DocumentWindow import com.intellij.lang.ASTNode import com.intellij.lang.Language import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiLanguageInjectionHost import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.common.DefaultInjectedLanguageBlockBuilder import com.intellij.psi.templateLanguages.OuterLanguageElement import com.intellij.util.SmartList import com.intellij.util.castSafelyTo import com.intellij.util.text.TextRangeUtil import com.intellij.util.text.escLBr import org.jetbrains.yaml.YAMLFileType import org.jetbrains.yaml.YAMLLanguage internal fun substituteInjectedBlocks(settings: CodeStyleSettings, rawSubBlocks: List<Block>, injectionHost: ASTNode, wrap: Wrap?, alignment: Alignment?): List<Block> { val injectedBlocks = SmartList<Block>().apply { val outerBLocks = rawSubBlocks.filter { (it as? ASTBlock)?.node is OuterLanguageElement } val fixedIndent = IndentImpl(Indent.Type.SPACES, false, settings.getIndentSize(YAMLFileType.YML), false, false) YamlInjectedLanguageBlockBuilder(settings, outerBLocks).addInjectedBlocks(this, injectionHost, wrap, alignment, fixedIndent) } if (injectedBlocks.isEmpty()) return rawSubBlocks injectedBlocks.addAll(0, rawSubBlocks.filter(injectedBlocks.first().textRange.startOffset.let { start -> { it.textRange.endOffset <= start } })) injectedBlocks.addAll(rawSubBlocks.filter(injectedBlocks.last().textRange.endOffset.let { end -> { it.textRange.startOffset >= end } })) return injectedBlocks } private class YamlInjectedLanguageBlockBuilder(settings: CodeStyleSettings, val outerBlocks: List<Block>) : DefaultInjectedLanguageBlockBuilder(settings) { override fun supportsMultipleFragments(): Boolean = true lateinit var injectionHost: ASTNode lateinit var injectedFile: PsiFile lateinit var injectionLanguage: Language override fun addInjectedBlocks(result: MutableList<in Block>, injectionHost: ASTNode, wrap: Wrap?, alignment: Alignment?, indent: Indent?): Boolean { this.injectionHost = injectionHost return super.addInjectedBlocks(result, injectionHost, wrap, alignment, indent) } override fun addInjectedLanguageBlocks(result: MutableList<in Block>, injectedFile: PsiFile, indent: Indent?, offset: Int, injectedEditableRange: TextRange?, shreds: List<PsiLanguageInjectionHost.Shred>) { this.injectedFile = injectedFile return super.addInjectedLanguageBlocks(result, injectedFile, indent, offset, injectedEditableRange, shreds) } override fun createBlockBeforeInjection(node: ASTNode, wrap: Wrap?, alignment: Alignment?, indent: Indent?, range: TextRange): Block? = super.createBlockBeforeInjection(node, wrap, alignment, indent, removeIndentFromRange(range)) private fun removeIndentFromRange(range: TextRange): TextRange = trimBlank(range, range.shiftLeft(injectionHost.startOffset).substring(injectionHost.text)) private fun injectedToHost(textRange: TextRange): TextRange = InjectedLanguageManager.getInstance(injectedFile.project).injectedToHost(injectedFile, textRange) private fun hostToInjected(textRange: TextRange): TextRange? { val documentWindow = PsiDocumentManager.getInstance(injectedFile.project).getCachedDocument(injectedFile) as? DocumentWindow ?: return null return TextRange(documentWindow.hostToInjected(textRange.startOffset), documentWindow.hostToInjected(textRange.endOffset)) } override fun createInjectedBlock(node: ASTNode, originalBlock: Block, indent: Indent?, offset: Int, range: TextRange, language: Language): Block { this.injectionLanguage = language val trimmedRange = trimBlank(range, range.substring(node.text)) return YamlInjectedLanguageBlockWrapper(originalBlock, injectedToHost(trimmedRange), trimmedRange, outerBlocks, indent, YAMLLanguage.INSTANCE) } private fun trimBlank(range: TextRange, substring: String): TextRange { val preWS = substring.takeWhile { it.isWhitespace() }.count() val postWS = substring.takeLastWhile { it.isWhitespace() }.count() return if (preWS < range.length) range.run { TextRange(startOffset + preWS, endOffset - postWS) } else range } private inner class YamlInjectedLanguageBlockWrapper(val original: Block, val rangeInHost: TextRange, val myRange: TextRange, outerBlocks: Collection<Block>, private val indent: Indent?, private val language: Language?) : BlockEx { override fun toString(): String = "YamlInjectedLanguageBlockWrapper($original, $myRange," + " rangeInRoot = $textRange '${textRange.substring(injectionHost.psi.containingFile.text).escLBr()}')" override fun getTextRange(): TextRange { val subBlocks = subBlocks if (subBlocks.isEmpty()) return rangeInHost return TextRange.create( subBlocks.first().textRange.startOffset.coerceAtMost(rangeInHost.startOffset), subBlocks.last().textRange.endOffset.coerceAtLeast(rangeInHost.endOffset)) } private val myBlocks by lazy(LazyThreadSafetyMode.NONE) { SmartList<Block>().also { result -> val outerBlocksQueue = ArrayDeque(outerBlocks) for (block in original.subBlocks) { myRange.intersection(block.textRange)?.let { blockRange -> val blockRangeInHost = injectedToHost(blockRange) fun createInnerWrapper(blockRangeInHost: TextRange, blockRange: TextRange, outerNodes: Collection<Block>) = YamlInjectedLanguageBlockWrapper(block, blockRangeInHost, blockRange, outerNodes, replaceAbsoluteIndent(block), block.castSafelyTo<BlockEx>()?.language ?: injectionLanguage) result.addAll(outerBlocksQueue.popWhile { it.textRange.endOffset <= blockRangeInHost.startOffset }) if (block.subBlocks.isNotEmpty()) { result.add(createInnerWrapper( blockRangeInHost, blockRange, outerBlocksQueue.popWhile { blockRangeInHost.contains(it.textRange) })) } else { val outer = outerBlocksQueue.popWhile { blockRangeInHost.contains(it.textRange) } val remainingInjectedRanges = TextRangeUtil.excludeRanges(blockRangeInHost, outer.map { it.textRange }) val splitInjectedLeaves = remainingInjectedRanges.map { part -> createInnerWrapper(part, hostToInjected(part) ?: blockRange, emptyList()) } result.addAll((splitInjectedLeaves + outer).sortedBy { it.textRange.startOffset }) } } } result.addAll(outerBlocksQueue) } } private fun replaceAbsoluteIndent(block: Block): Indent? = block.indent.castSafelyTo<IndentImpl>()?.takeIf { it.isAbsolute } ?.run { IndentImpl(type, false, spaces, isRelativeToDirectParent, isEnforceIndentToChildren) } ?:block.indent override fun getSubBlocks(): List<Block> = myBlocks override fun getWrap(): Wrap? = original.wrap override fun getIndent(): Indent? = indent override fun getAlignment(): Alignment? = original.alignment override fun getSpacing(child1: Block?, child2: Block): Spacing? = original.getSpacing(child1?.unwrap(), child2.unwrap()) override fun getChildAttributes(newChildIndex: Int): ChildAttributes = original.getChildAttributes(newChildIndex) override fun isIncomplete(): Boolean = original.isIncomplete override fun isLeaf(): Boolean = original.isLeaf override fun getLanguage(): Language? = language } private fun Block.unwrap() = this.castSafelyTo<YamlInjectedLanguageBlockWrapper>()?.original ?: this private fun <T> ArrayDeque<T>.popWhile(pred: (T) -> Boolean): List<T> { if (this.isEmpty()) return emptyList() val result = SmartList<T>() while (this.isNotEmpty() && pred(this.first())) result.add(this.removeFirst()) return result; } }
apache-2.0
72994f3f5aadc91805c5d1b7f468b5fd
50.57377
158
0.65826
5.392571
false
false
false
false
smmribeiro/intellij-community
platform/built-in-server/src/org/jetbrains/ide/InstallPluginService.kt
1
6160
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.ide import com.google.gson.reflect.TypeToken import com.intellij.ide.plugins.marketplace.MarketplaceRequests import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.ApplicationNamesInfo import com.intellij.openapi.application.ex.ApplicationInfoEx import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.installAndEnable import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.AppIcon import com.intellij.util.PlatformUtils import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresReadLockAbsence import com.intellij.util.io.getHostName import com.intellij.util.io.origin import com.intellij.util.net.NetUtils import com.intellij.util.text.nullize import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.FullHttpRequest import io.netty.handler.codec.http.HttpRequest import io.netty.handler.codec.http.QueryStringDecoder import java.io.OutputStream import java.net.URI import java.net.URISyntaxException @Suppress("HardCodedStringLiteral") internal class InstallPluginService : RestService() { override fun getServiceName() = "installPlugin" override fun isOriginAllowed(request: HttpRequest) = OriginCheckResult.ASK_CONFIRMATION var isAvailable = true private val trustedHosts = System.getProperty("idea.api.install.hosts.trusted", "").split(",") private val trustedPredefinedHosts = setOf( "marketplace.jetbrains.com", "plugins.jetbrains.com", "package-search.services.jetbrains.com", "package-search.jetbrains.com" ) override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? { val pluginId = getStringParameter("pluginId", urlDecoder) val passedPluginIds = getStringParameter("pluginIds", urlDecoder) val action = getStringParameter("action", urlDecoder) if (pluginId.isNullOrBlank() && passedPluginIds.isNullOrBlank()) { return productInfo(request, context) } val pluginIds = if (pluginId.isNullOrBlank()) { gson.fromJson(passedPluginIds, object : TypeToken<List<String?>?>() {}.type) } else { listOf(pluginId) } return when (action) { "checkCompatibility" -> checkCompatibility(request, context, pluginIds) "install" -> installPlugin(request, context, pluginIds) else -> productInfo(request, context) } } @RequiresBackgroundThread @RequiresReadLockAbsence private fun checkCompatibility( request: FullHttpRequest, context: ChannelHandlerContext, pluginIds: List<String>, ): Nothing? { val marketplaceRequests = MarketplaceRequests.getInstance() val compatibleUpdatesInfo = pluginIds .mapNotNull { PluginId.findId(it) } .map { id -> id.idString to (marketplaceRequests.getLastCompatiblePluginUpdate(id) != null) } .let { info -> if (info.size != 1) info else listOf("compatible" to info[0].second) } //check if there is an update for this IDE with this ID. val out = BufferExposingByteArrayOutputStream() val writer = createJsonWriter(out) writer.beginObject() compatibleUpdatesInfo.forEach { val (pluginId, value) = it writer.name(pluginId).value(value) } writer.endObject() writer.close() send(out, request, context) return null } private fun installPlugin(request: FullHttpRequest, context: ChannelHandlerContext, pluginIds: List<String>): Nothing? { val plugins = pluginIds.mapNotNull { PluginId.findId(it) } if (isAvailable) { isAvailable = false val effectiveProject = getLastFocusedOrOpenedProject() ?: ProjectManager.getInstance().defaultProject ApplicationManager.getApplication().invokeLater(Runnable { AppIcon.getInstance().requestAttention(effectiveProject, true) installAndEnable(effectiveProject, plugins.toSet()) { } isAvailable = true }, effectiveProject.disposed) } sendOk(request, context) return null } private fun productInfo(request: FullHttpRequest, context: ChannelHandlerContext): Nothing? { val out = BufferExposingByteArrayOutputStream() writeIDEInfo(out) send(out, request, context) return null } private fun writeIDEInfo(out: OutputStream) { val writer = createJsonWriter(out) writer.beginObject() var appName = ApplicationInfoEx.getInstanceEx().fullApplicationName val build = ApplicationInfo.getInstance().build if (!PlatformUtils.isIdeaUltimate()) { val productName = ApplicationNamesInfo.getInstance().productName appName = appName.replace("$productName ($productName)", productName) appName = StringUtil.trimStart(appName, "JetBrains ") } writer.name("name").value(appName) writer.name("buildNumber").value(build.asString()) writer.endObject() writer.close() } override fun isHostTrusted(request: FullHttpRequest, urlDecoder: QueryStringDecoder): Boolean { val origin = request.origin val originHost = try { if (origin == null) null else URI(origin).host.nullize() } catch (ignored: URISyntaxException) { return false } val hostName = getHostName(request) if (hostName != null && !NetUtils.isLocalhost(hostName)) { LOG.error("Expected 'request.hostName' to be localhost. hostName='$hostName', origin='$origin'") } return (originHost != null && ( trustedPredefinedHosts.contains(originHost) || trustedHosts.contains(originHost) || NetUtils.isLocalhost(originHost))) || super.isHostTrusted(request, urlDecoder) } }
apache-2.0
409af0e61d776f4bdc340565f37d7f51
35.886228
158
0.733766
4.720307
false
false
false
false
vector-im/vector-android
vector/src/main/java/im/vector/view/PasswordStrengthBar.kt
2
3798
/* * Copyright 2019 New Vector 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. */ package im.vector.view import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.LinearLayout import androidx.annotation.IntRange import butterknife.BindColor import butterknife.BindView import butterknife.ButterKnife import im.vector.R /** * A password strength bar custom widget * Strength is an Integer * -> 0 No strength * -> 1 Weak * -> 2 Fair * -> 3 Good * -> 4 Strong */ class PasswordStrengthBar @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) { @BindView(R.id.password_strength_bar_1) lateinit var bar1: View @BindView(R.id.password_strength_bar_2) lateinit var bar2: View @BindView(R.id.password_strength_bar_3) lateinit var bar3: View @BindView(R.id.password_strength_bar_4) lateinit var bar4: View @BindColor(R.color.password_strength_bar_undefined) @JvmField var colorBackground: Int = 0 @BindColor(R.color.password_strength_bar_weak) @JvmField var colorWeak: Int = 0 @BindColor(R.color.password_strength_bar_low) @JvmField var colorLow: Int = 0 @BindColor(R.color.password_strength_bar_ok) @JvmField var colorOk: Int = 0 @BindColor(R.color.password_strength_bar_strong) @JvmField var colorStrong: Int = 0 @IntRange(from = 0, to = 4) var strength = 0 set(newValue) { field = newValue.coerceIn(0, 4) when (newValue) { 0 -> { bar1.setBackgroundColor(colorBackground) bar2.setBackgroundColor(colorBackground) bar3.setBackgroundColor(colorBackground) bar4.setBackgroundColor(colorBackground) } 1 -> { bar1.setBackgroundColor(colorWeak) bar2.setBackgroundColor(colorBackground) bar3.setBackgroundColor(colorBackground) bar4.setBackgroundColor(colorBackground) } 2 -> { bar1.setBackgroundColor(colorLow) bar2.setBackgroundColor(colorLow) bar3.setBackgroundColor(colorBackground) bar4.setBackgroundColor(colorBackground) } 3 -> { bar1.setBackgroundColor(colorOk) bar2.setBackgroundColor(colorOk) bar3.setBackgroundColor(colorOk) bar4.setBackgroundColor(colorBackground) } 4 -> { bar1.setBackgroundColor(colorStrong) bar2.setBackgroundColor(colorStrong) bar3.setBackgroundColor(colorStrong) bar4.setBackgroundColor(colorStrong) } } } init { LayoutInflater.from(context) .inflate(R.layout.view_password_strength_bar, this, true) orientation = HORIZONTAL ButterKnife.bind(this) strength = 0 } }
apache-2.0
de77e80dfb43ab11841e793081dd9f81
30.92437
75
0.617167
4.570397
false
false
false
false
microg/android_packages_apps_UnifiedNlp
ui/src/main/kotlin/org/microg/nlp/ui/BackendListFragment.kt
1
7893
/* * SPDX-FileCopyrightText: 2020, microG Project Team * SPDX-License-Identifier: Apache-2.0 */ package org.microg.nlp.ui import android.content.Context import android.content.Intent import android.content.pm.PackageManager.GET_META_DATA import android.os.Build import android.os.Bundle import android.provider.Settings import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.NavController import androidx.navigation.fragment.findNavController import androidx.navigation.navOptions import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.launch import org.microg.nlp.api.Constants.ACTION_GEOCODER_BACKEND import org.microg.nlp.api.Constants.ACTION_LOCATION_BACKEND import org.microg.nlp.client.UnifiedLocationClient import org.microg.nlp.ui.databinding.BackendListBinding import org.microg.nlp.ui.databinding.BackendListEntryBinding import org.microg.nlp.ui.model.BackendInfo import org.microg.nlp.ui.model.BackendListEntryCallback import org.microg.nlp.ui.model.BackendType class BackendListFragment : Fragment(R.layout.backend_list), BackendListEntryCallback { val locationAdapter: BackendSettingsLineAdapter = BackendSettingsLineAdapter(this) val geocoderAdapter: BackendSettingsLineAdapter = BackendSettingsLineAdapter(this) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = BackendListBinding.inflate(inflater, container, false) binding.fragment = this return binding.root } override fun onResume() { super.onResume() UnifiedLocationClient[requireContext()].ref() lifecycleScope.launchWhenStarted { updateAdapters() } } override fun onPause() { super.onPause() UnifiedLocationClient[requireContext()].unref() } override fun onOpenDetails(entry: BackendInfo?) { if (entry == null) return findNavController().navigate(requireContext(), R.id.openBackendDetails, bundleOf( "type" to entry.type.name, "package" to entry.serviceInfo.packageName, "name" to entry.serviceInfo.name )) } override fun onEnabledChange(entry: BackendInfo?, newValue: Boolean) { val activity = requireActivity() as AppCompatActivity activity.lifecycleScope.launch { entry?.updateEnabled(this@BackendListFragment, newValue) } } private suspend fun updateAdapters() { val activity = requireActivity() as AppCompatActivity locationAdapter.setEntries(createBackendInfoList(activity, Intent(ACTION_LOCATION_BACKEND), UnifiedLocationClient[activity].getLocationBackends(), BackendType.LOCATION)) geocoderAdapter.setEntries(createBackendInfoList(activity, Intent(ACTION_GEOCODER_BACKEND), UnifiedLocationClient[activity].getGeocoderBackends(), BackendType.GEOCODER)) } private fun createBackendInfoList(activity: AppCompatActivity, intent: Intent, enabledBackends: Array<String>, type: BackendType): Array<BackendInfo?> { val backends = activity.packageManager.queryIntentServices(intent, GET_META_DATA).map { val info = BackendInfo(it.serviceInfo, type, firstSignatureDigest(activity, it.serviceInfo.packageName)) if (enabledBackends.contains(info.signedComponent) || enabledBackends.contains(info.unsignedComponent)) { info.enabled.set(true) } info.fillDetails(activity) activity.lifecycleScope.launch { info.loadIntents(activity) } info }.sortedBy { it.name.get() } if (backends.isEmpty()) return arrayOf(null) return backends.toTypedArray() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { handleActivityResult(requestCode, resultCode, data) } } class BackendSettingsLineViewHolder(val binding: BackendListEntryBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(fragment: BackendListFragment, entry: BackendInfo?) { binding.callbacks = fragment binding.entry = entry binding.executePendingBindings() } } class BackendSettingsLineAdapter(val fragment: BackendListFragment) : RecyclerView.Adapter<BackendSettingsLineViewHolder>() { private val entries: MutableList<BackendInfo?> = arrayListOf() fun addOrUpdateEntry(entry: BackendInfo?) { if (entry == null) { if (entries.contains(null)) return entries.add(entry) notifyItemInserted(entries.size - 1) } else { val oldIndex = entries.indexOfFirst { it?.unsignedComponent == entry.unsignedComponent } if (oldIndex != -1) { if (entries[oldIndex] == entry) return entries.removeAt(oldIndex) } val targetIndex = when (val i = entries.indexOfFirst { it == null || it.name.get().toString() > entry.name.get().toString() }) { -1 -> entries.size else -> i } entries.add(targetIndex, entry) when (oldIndex) { targetIndex -> notifyItemChanged(targetIndex) -1 -> notifyItemInserted(targetIndex) else -> notifyItemMoved(oldIndex, targetIndex) } } } fun removeEntry(entry: BackendInfo?) { val index = entries.indexOfFirst { it == entry || it?.unsignedComponent == entry?.unsignedComponent } entries.removeAt(index) notifyItemRemoved(index) } fun setEntries(entries: Array<BackendInfo?>) { val oldEntries = this.entries.toTypedArray() for (oldEntry in oldEntries) { if (!entries.any { it == oldEntry || it?.unsignedComponent == oldEntry?.unsignedComponent }) { removeEntry(oldEntry) } } entries.forEach { addOrUpdateEntry(it) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BackendSettingsLineViewHolder { return BackendSettingsLineViewHolder(BackendListEntryBinding.inflate(LayoutInflater.from(parent.context), parent, false)) } override fun onBindViewHolder(holder: BackendSettingsLineViewHolder, position: Int) { holder.bind(fragment, entries[position]) } override fun getItemCount(): Int { return entries.size } } fun NavController.navigate(context: Context, @IdRes resId: Int, args: Bundle? = null) { navigate(resId, args, if (context.systemAnimationsEnabled) navOptions { anim { enter = androidx.navigation.ui.R.anim.nav_default_enter_anim exit = androidx.navigation.ui.R.anim.nav_default_exit_anim popEnter = androidx.navigation.ui.R.anim.nav_default_pop_enter_anim popExit = androidx.navigation.ui.R.anim.nav_default_pop_exit_anim } } else null) } val Context.systemAnimationsEnabled: Boolean get() { val duration: Float val transition: Float if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { duration = Settings.Global.getFloat(contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f) transition = Settings.Global.getFloat(contentResolver, Settings.Global.TRANSITION_ANIMATION_SCALE, 1f) } else { duration = Settings.System.getFloat(contentResolver, Settings.System.ANIMATOR_DURATION_SCALE, 1f) transition = Settings.System.getFloat(contentResolver, Settings.System.TRANSITION_ANIMATION_SCALE, 1f) } return duration != 0f && transition != 0f }
apache-2.0
2bc9edf04405360c1328e2fbfc17533c
41.208556
177
0.69568
4.656637
false
false
false
false
breadwallet/breadwallet-android
ui/ui-staking/src/main/java/Staking.kt
1
6857
/** * BreadWallet * * Created by Drew Carlson <[email protected]> on 10/30/20. * Copyright (c) 2020 breadwallet LLC * * 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.breadwallet.ui.uistaking import com.breadwallet.crypto.TransferFeeBasis import com.breadwallet.ui.ViewEffect import java.math.BigDecimal object Staking { sealed class M { sealed class TransactionError { object FeeEstimateFailed : TransactionError() object TransferFailed : TransactionError() object Unknown : TransactionError() } abstract val currencyId: String abstract val currencyCode: String abstract val address: String abstract val balance: BigDecimal abstract val isAuthenticating: Boolean abstract val isFingerprintEnabled: Boolean data class Loading( override val currencyCode: String = "", override val currencyId: String = "", override val address: String = "", override val balance: BigDecimal = BigDecimal.ZERO, override val isAuthenticating: Boolean = false, override val isFingerprintEnabled: Boolean = false, ) : M() data class SetValidator( override val currencyId: String, override val currencyCode: String, override val address: String, override val balance: BigDecimal = BigDecimal.ZERO, override val isAuthenticating: Boolean = false, override val isFingerprintEnabled: Boolean, val originalAddress: String, val isAddressValid: Boolean, val isAddressChanged: Boolean, val canSubmitTransfer: Boolean, val transactionError: TransactionError?, val feeEstimate: TransferFeeBasis?, val isCancellable: Boolean, val confirmWhenReady: Boolean = false ) : M() { companion object { fun createDefault( balance: BigDecimal, currencyId: String, currencyCode: String, originalAddress: String? = null, isFingerprintEnabled: Boolean ) = SetValidator( balance = balance, currencyId = currencyId, currencyCode = currencyCode, address = "", isAddressValid = true, isAddressChanged = false, canSubmitTransfer = false, transactionError = null, isCancellable = originalAddress != null, originalAddress = originalAddress ?: "", feeEstimate = null, isFingerprintEnabled = isFingerprintEnabled ) } } data class ViewValidator( override val currencyId: String, override val currencyCode: String, override val address: String, override val balance: BigDecimal, override val isAuthenticating: Boolean = false, override val isFingerprintEnabled: Boolean = false, val state: State, val feeEstimate: TransferFeeBasis? = null ) : M() { enum class State { PENDING_STAKE, PENDING_UNSTAKE, STAKED } } } sealed class E { sealed class AccountUpdated : E() { abstract val currencyCode: String abstract val balance: BigDecimal data class Unstaked( override val currencyCode: String, override val balance: BigDecimal ) : AccountUpdated() data class Staked( override val currencyCode: String, val address: String, val state: M.ViewValidator.State, override val balance: BigDecimal ) : AccountUpdated() } data class OnAddressChanged(val address: String) : E() data class OnAddressValidated( val isValid: Boolean, val fromClipboard: Boolean = false, ) : E() data class OnTransferFailed(val transactionError: M.TransactionError) : E() data class OnFeeUpdated( val address: String?, val feeEstimate: TransferFeeBasis, val balance: BigDecimal ) : E() data class OnAuthenticationSettingsUpdated(val isFingerprintEnabled: Boolean) : E() object OnStakeClicked : E() object OnUnstakeClicked : E() object OnChangeClicked : E() object OnCancelClicked : E() object OnPasteClicked : E() object OnCloseClicked : E() object OnHelpClicked : E() object OnConfirmClicked : E() object OnTransactionConfirmClicked : E() object OnTransactionCancelClicked : E() object OnAuthSuccess : E() object OnAuthCancelled : E() } sealed class F { object LoadAccount : F() object LoadAuthenticationSettings : F() data class PasteFromClipboard( val currentDelegateAddress: String ) : F() object Help : F(), ViewEffect object Close : F(), ViewEffect data class Unstake(val feeEstimate: TransferFeeBasis) : F() data class EstimateFee(val address: String?) : F() data class Stake(val address: String, val feeEstimate: TransferFeeBasis) : F() data class ValidateAddress(val address: String) : F() data class ConfirmTransaction( val currencyCode: String, val address: String?, val balance: BigDecimal, val fee: BigDecimal ) : F(), ViewEffect } }
mit
14a1b9f944b84d93b6cabe9b3e0d2cbe
36.469945
91
0.605658
5.336187
false
false
false
false
seventhroot/elysium
bukkit/rpk-stats-bukkit/src/main/kotlin/com/rpkit/stats/bukkit/command/stats/StatsCommand.kt
1
3175
/* * Copyright 2016 Ross Binden * * 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.rpkit.stats.bukkit.command.stats import com.rpkit.characters.bukkit.character.RPKCharacterProvider import com.rpkit.players.bukkit.profile.RPKMinecraftProfileProvider import com.rpkit.stats.bukkit.RPKStatsBukkit import com.rpkit.stats.bukkit.stat.RPKStatProvider import com.rpkit.stats.bukkit.stat.RPKStatVariableProvider import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player /** * Stats command. * Shows all stat values for the player's active character. */ class StatsCommand(private val plugin: RPKStatsBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender.hasPermission("rpkit.stats.command.stats")) { if (sender is Player) { val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) val characterProvider = plugin.core.serviceManager.getServiceProvider(RPKCharacterProvider::class) val minecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (minecraftProfile != null) { val character = characterProvider.getActiveCharacter(minecraftProfile) if (character != null) { val statsProvider = plugin.core.serviceManager.getServiceProvider(RPKStatProvider::class) val statVariableProvider = plugin.core.serviceManager.getServiceProvider(RPKStatVariableProvider::class) sender.sendMessage(plugin.messages["stats-list-title"]) statsProvider.stats.forEach { stat -> sender.sendMessage(plugin.messages["stats-list-item", mapOf( Pair("stat", stat.name), Pair("value", stat.get(character, statVariableProvider.statVariables).toString()) )]) } } else { sender.sendMessage(plugin.messages["no-character"]) } } else { sender.sendMessage(plugin.messages["no-minecraft-profile"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } } else { sender.sendMessage(plugin.messages["no-permission-stats"]) } return true } }
apache-2.0
7e4f81ee164e905ce7ccf6af158393d2
45.705882
128
0.651969
5.13754
false
false
false
false
like5188/Common
sample/src/main/java/com/like/common/sample/TwoLineChartActivity.kt
1
4438
package com.like.common.sample import android.databinding.DataBindingUtil import android.view.View import com.like.common.base.context.BaseActivity import com.like.common.base.viewmodel.BaseViewModel import com.like.common.sample.databinding.ActivityTwoLineChartBinding import com.like.common.view.chart.horizontalScrollTwoLineChartView.core.OnClickListener import com.like.common.view.chart.horizontalScrollTwoLineChartView.entity.TwoLineData import com.like.logger.Logger class TwoLineChartActivity : BaseActivity() { private val mBinding: ActivityTwoLineChartBinding by lazy { DataBindingUtil.setContentView<ActivityTwoLineChartBinding>(this, R.layout.activity_two_line_chart) } override fun getViewModel(): BaseViewModel? { mBinding.root // 测试有月份值默认值的情况 mBinding.viewTwoLineChart.twoLineChartView.setData(getSimulatedData1(), 5, listener = object : OnClickListener { override fun onClick(position: Int) { Logger.e("触摸点位置:$position") } }) mBinding.viewTwoLineChart.llHuanbi.visibility = View.VISIBLE mBinding.viewTwoLineChart.llTongbi.visibility = View.VISIBLE mBinding.viewTwoLineChart.tvUnit.text = "单位:日" return null } fun changeData1(view: View) { mBinding.viewTwoLineChart.twoLineChartView.setData(getSimulatedData1()) mBinding.viewTwoLineChart.llHuanbi.visibility = View.VISIBLE mBinding.viewTwoLineChart.llTongbi.visibility = View.VISIBLE mBinding.viewTwoLineChart.tvUnit.text = "单位:日" } fun changeData2(view: View) { mBinding.viewTwoLineChart.twoLineChartView.setData(getSimulatedData2()) mBinding.viewTwoLineChart.llHuanbi.visibility = View.VISIBLE mBinding.viewTwoLineChart.llTongbi.visibility = View.GONE mBinding.viewTwoLineChart.tvUnit.text = "单位:月" } fun changeData3(view: View) { mBinding.viewTwoLineChart.twoLineChartView.setData(getSimulatedData3()) mBinding.viewTwoLineChart.llHuanbi.visibility = View.GONE mBinding.viewTwoLineChart.llTongbi.visibility = View.VISIBLE mBinding.viewTwoLineChart.tvUnit.text = "单位:时" } fun clearData(view: View) { mBinding.viewTwoLineChart.twoLineChartView.setData(emptyList()) } fun getSimulatedData1(): List<TwoLineData> { return listOf( TwoLineData(1, 0f, 0f, showData2 = "--"), TwoLineData(2, 50f, -20f), TwoLineData(3, 100f, 10f), TwoLineData(4, 0f, 50f, "--"), TwoLineData(5, 0f, 0f, "--"), TwoLineData(6, 0f, 0f, "--", "--") ) // return listOf( // TwoLineData(1, ratio2 = 0f), // TwoLineData(2, ratio2 = 20f), // TwoLineData(3, ratio2 = 10f), // TwoLineData(4, ratio2 = 50f), // TwoLineData(5, ratio2 = 20f), // TwoLineData(6, ratio2 = 10f) // ) // return listOf( // TwoLineData(1, ratio2 = 0f), // TwoLineData(2, ratio2 = 0f), // TwoLineData(3, ratio2 = 0f), // TwoLineData(4, ratio2 = 0f), // TwoLineData(5, ratio2 = 0f), // TwoLineData(6, ratio2 = 0f) // ) // return listOf( // TwoLineData(1, 0f), // TwoLineData(2, 0f), // TwoLineData(3, 0f), // TwoLineData(4, 0f), // TwoLineData(5, 0f), // TwoLineData(6, 0f) // ) // return listOf( // TwoLineData(1, -10f), // TwoLineData(2, 20f), // TwoLineData(3, -30f), // TwoLineData(4, 15f), // TwoLineData(5, 50f), // TwoLineData(6, -20f) // ) } fun getSimulatedData2(): List<TwoLineData> { return listOf( TwoLineData(1, ratio2 = 20f), TwoLineData(2, ratio2 = -10f), TwoLineData(3, ratio2 = 0f, showData2 = "--"), TwoLineData(4, ratio2 = -20f) ) } fun getSimulatedData3(): List<TwoLineData> { return listOf( TwoLineData(1, -50f), TwoLineData(2, -100f), TwoLineData(3, 0f, showData1 = "--") ) } }
apache-2.0
a7a9302f50ce997654a281bbc6537eb4
36.681034
120
0.588101
3.786828
false
false
false
false
kangsLee/sh8email-kotlin
app/src/main/kotlin/org/triplepy/sh8email/sh8/activities/SplashActivity.kt
1
782
package org.triplepy.sh8email.sh8.activities import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import org.triplepy.sh8email.sh8.activities.login.LoginActivity import org.triplepy.sh8email.sh8.ext.startActivity /** * The sh8email-android Project. * ============================== * org.triplepy.sh8email.sh8.activities * ============================== * Created by igangsan on 2016. 9. 1.. */ class SplashActivity() : AppCompatActivity(){ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Todo: load something Handler().postDelayed({ startActivity(LoginActivity::class.java) supportFinishAfterTransition() }, 1000) } }
apache-2.0
a1f8670d3e70dfe76fab7e28cfb97926
26.964286
63
0.662404
4.25
false
false
false
false