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
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/InboxViewModel.kt
1
6311
package com.habitrpg.android.habitica.ui.viewmodels import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.paging.DataSource import androidx.paging.PagedList import androidx.paging.PositionalDataSource import androidx.paging.toLiveData import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.extensions.Optional import com.habitrpg.android.habitica.extensions.asOptional import com.habitrpg.android.habitica.extensions.filterOptionalDoOnEmpty import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.members.Member import com.habitrpg.android.habitica.models.social.ChatMessage import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.functions.Consumer import io.reactivex.subjects.BehaviorSubject import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import javax.inject.Inject import kotlin.math.ceil class InboxViewModel(recipientID: String?, recipientUsername: String?) : BaseViewModel() { @Inject lateinit var socialRepository: SocialRepository private val config = PagedList.Config.Builder() .setPageSize(10) .setEnablePlaceholders(false) .build() private val dataSourceFactory = MessagesDataSourceFactory(socialRepository, recipientID) val messages: LiveData<PagedList<ChatMessage>> = dataSourceFactory.toLiveData(config) private val member: MutableLiveData<Member?> by lazy { MutableLiveData<Member?>() } fun getMemberData(): LiveData<Member?> = member private fun loadMemberFromLocal() { disposable.add(memberIDFlowable .filterOptionalDoOnEmpty { member.value = null } .flatMap { socialRepository.getMember(it) } .observeOn(AndroidSchedulers.mainThread()) .subscribe(Consumer { member.value = it }, RxErrorHandler.handleEmptyError())) } protected var memberIDSubject = BehaviorSubject.create<Optional<String>>() val memberIDFlowable = memberIDSubject.toFlowable(BackpressureStrategy.BUFFER) fun setMemberID(groupID: String) { if (groupID == memberIDSubject.value?.value) return memberIDSubject.onNext(groupID.asOptional()) } val memberID: String? get() = memberIDSubject.value?.value override fun inject(component: UserComponent) { component.inject(this) } fun invalidateDataSource() { dataSourceFactory.sourceLiveData.value?.invalidate() } init { if (recipientID?.isNotBlank() == true) { setMemberID(recipientID) loadMemberFromLocal() } else if (recipientUsername?.isNotBlank() == true) { socialRepository.getMemberWithUsername(recipientUsername).subscribe(Consumer { setMemberID(it.id ?: "") member.value = it dataSourceFactory.updateRecipientID(memberIDSubject.value?.value) invalidateDataSource() }, RxErrorHandler.handleEmptyError()) } } } private class MessagesDataSource(val socialRepository: SocialRepository, var recipientID: String?): PositionalDataSource<ChatMessage>() { private var lastFetchWasEnd = false override fun loadRange(params: LoadRangeParams, callback: LoadRangeCallback<ChatMessage>) { if (lastFetchWasEnd) { callback.onResult(emptyList()) return } GlobalScope.launch(Dispatchers.Main.immediate) { if (recipientID?.isNotBlank() != true) { return@launch } val page = ceil(params.startPosition.toFloat() / params.loadSize.toFloat()).toInt() socialRepository.retrieveInboxMessages(recipientID ?: "", page) .subscribe(Consumer { if (it.size != 10) lastFetchWasEnd = true callback.onResult(it) }, RxErrorHandler.handleEmptyError()) } } override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback<ChatMessage>) { lastFetchWasEnd = false GlobalScope.launch(Dispatchers.Main.immediate) { socialRepository.getInboxMessages(recipientID) .map { socialRepository.getUnmanagedCopy(it) } .firstElement() .flatMapPublisher { if (it.isEmpty()) { if (recipientID?.isNotBlank() != true) { return@flatMapPublisher Flowable.just(it) } socialRepository.retrieveInboxMessages(recipientID ?: "", 0) .doOnNext { messages -> if (messages.size != 10) lastFetchWasEnd = true } } else { Flowable.just(it) } } .subscribe(Consumer { callback.onResult(it, 0) }, RxErrorHandler.handleEmptyError()) } } } private class MessagesDataSourceFactory(val socialRepository: SocialRepository, var recipientID: String?) : DataSource.Factory<Int, ChatMessage>() { val sourceLiveData = MutableLiveData<MessagesDataSource>() var latestSource: MessagesDataSource = MessagesDataSource(socialRepository, recipientID) fun updateRecipientID(newID: String?) { recipientID = newID latestSource.recipientID = newID } override fun create(): DataSource<Int, ChatMessage> { latestSource = MessagesDataSource(socialRepository, recipientID) sourceLiveData.postValue(latestSource) return latestSource } } class InboxViewModelFactory(private val recipientID: String?, private val recipientUsername: String?) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { return InboxViewModel(recipientID, recipientUsername) as T } }
gpl-3.0
9f8872997ba8cf5f69f52733f88f67aa
39.987013
131
0.670734
5.535965
false
false
false
false
mdaniel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromUsageFix.kt
1
12454
// 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.intention.HighPriorityAction import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.ide.util.DirectoryChooserUtil import com.intellij.openapi.editor.Editor import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.* import org.jetbrains.annotations.Nls import org.jetbrains.annotations.NonNls import org.jetbrains.kotlin.idea.base.util.module import org.jetbrains.kotlin.descriptors.DescriptorVisibility import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.surroundWith.KotlinSurrounderUtils import org.jetbrains.kotlin.idea.quickfix.IntentionActionPriority import org.jetbrains.kotlin.idea.quickfix.createFromUsage.CreateFromUsageFixBase import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.* import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind.* import org.jetbrains.kotlin.idea.refactoring.SeparateFileWrapper import org.jetbrains.kotlin.idea.refactoring.canRefactor import org.jetbrains.kotlin.idea.refactoring.chooseContainerElementIfNecessary import org.jetbrains.kotlin.idea.refactoring.getOrCreateKotlinFile import org.jetbrains.kotlin.idea.refactoring.ui.CreateKotlinClassDialog import org.jetbrains.kotlin.idea.references.KtSimpleNameReference import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.application.* import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.allChildren import org.jetbrains.kotlin.psi.psiUtil.getQualifiedElementSelector import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.SmartList import java.util.* import com.intellij.codeInsight.daemon.impl.quickfix.ClassKind as IdeaClassKind enum class ClassKind(@NonNls val keyword: String, @Nls val description: String) { PLAIN_CLASS("class", KotlinBundle.message("text.class")), ENUM_CLASS("enum class", KotlinBundle.message("text.enum")), ENUM_ENTRY("", KotlinBundle.message("text.enum.constant")), ANNOTATION_CLASS("annotation class", KotlinBundle.message("text.annotation")), INTERFACE("interface", KotlinBundle.message("text.interface")), OBJECT("object", KotlinBundle.message("text.object")), DEFAULT("", "") // Used as a placeholder and must be replaced with one of the kinds above } fun ClassKind.toIdeaClassKind() = IdeaClassKind { [email protected]() } val ClassKind.actionPriority: IntentionActionPriority get() = if (this == ANNOTATION_CLASS) IntentionActionPriority.LOW else IntentionActionPriority.NORMAL data class ClassInfo( val kind: ClassKind = DEFAULT, val name: String, private val targetParents: List<PsiElement>, val expectedTypeInfo: TypeInfo, val inner: Boolean = false, val open: Boolean = false, val typeArguments: List<TypeInfo> = Collections.emptyList(), val parameterInfos: List<ParameterInfo> = Collections.emptyList(), val primaryConstructorVisibility: DescriptorVisibility? = null ) { val applicableParents by lazy { targetParents.filter { if (kind == OBJECT && it is KtClass && (it.isInner() || it.isLocal)) return@filter false true } } } open class CreateClassFromUsageFix<E : KtElement> protected constructor( element: E, private val classInfo: ClassInfo ) : CreateFromUsageFixBase<E>(element) { override fun getText() = KotlinBundle.message("create.0.1", classInfo.kind.description, classInfo.name) override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean { with(classInfo) { if (kind == DEFAULT) return false if (applicableParents.isEmpty()) return false applicableParents.forEach { if (it is PsiClass) { if (kind == OBJECT || kind == ENUM_ENTRY) return false if (it.isInterface && inner) return false } } } return true } override fun startInWriteAction() = false override fun invoke(project: Project, editor: Editor?, file: KtFile) { if (editor == null) return val applicableParents = SmartList<PsiElement>().also { parents -> classInfo.applicableParents.filterNotTo(parents) { element -> element is KtClassOrObject && element.superTypeListEntries.any { when (it) { is KtDelegatedSuperTypeEntry, is KtSuperTypeEntry -> it.typeAsUserType == this.element is KtSuperTypeCallEntry -> it == this.element else -> false } } } if (classInfo.kind != ENUM_ENTRY && parents.find { it is PsiPackage } == null) { parents += SeparateFileWrapper(PsiManager.getInstance(project)) } } if (isUnitTestMode()) { val targetParent = applicableParents.firstOrNull { element -> if (element is PsiPackage) false else element.allChildren.any { it is PsiComment && it.text == "// TARGET_PARENT:" } } ?: classInfo.applicableParents.last() return doInvoke(targetParent, editor, file) } chooseContainerElementIfNecessary( applicableParents.reversed(), editor, KotlinBundle.message("choose.class.container"), true, ) { doInvoke(it, editor, file) } } private fun createFileByPackage( psiPackage: PsiPackage, editor: Editor, originalFile: KtFile ): KtFile? { val directories = psiPackage.directories.filter { it.canRefactor() } assert(directories.isNotEmpty()) { "Package '${psiPackage.qualifiedName}' must be refactorable" } val currentModule = ModuleUtilCore.findModuleForPsiElement(originalFile) val preferredDirectory = directories.firstOrNull { ModuleUtilCore.findModuleForPsiElement(it) == currentModule } ?: directories.firstOrNull() val targetDirectory = if (directories.size > 1 && !isUnitTestMode()) { DirectoryChooserUtil.chooseDirectory(directories.toTypedArray(), preferredDirectory, originalFile.project, HashMap()) } else { preferredDirectory } ?: return null val fileName = "${classInfo.name}.${KotlinFileType.INSTANCE.defaultExtension}" val targetFile = getOrCreateKotlinFile(fileName, targetDirectory) if (targetFile == null) { val filePath = "${targetDirectory.virtualFile.path}/$fileName" KotlinSurrounderUtils.showErrorHint( targetDirectory.project, editor, KotlinBundle.message("file.0.already.exists.but.does.not.correspond.to.kotlin.file", filePath), KotlinBundle.message("create.file"), null ) } return targetFile } private fun doInvoke(selectedParent: PsiElement, editor: Editor, file: KtFile, startCommand: Boolean = true) { val className = classInfo.name if (selectedParent is SeparateFileWrapper) { if (isUnitTestMode()) { return doInvoke(file, editor, file) } val ideaClassKind = classInfo.kind.toIdeaClassKind() val defaultPackageFqName = file.packageFqName val dialog = object : CreateKotlinClassDialog( file.project, KotlinBundle.message("create.0", ideaClassKind.description.capitalize()), className, defaultPackageFqName.asString(), ideaClassKind, false, file.module ) { override fun reportBaseInSourceSelectionInTest() = true } dialog.show() if (dialog.exitCode != DialogWrapper.OK_EXIT_CODE) return val targetDirectory = dialog.targetDirectory ?: return val fileName = "$className.${KotlinFileType.EXTENSION}" val packageFqName = targetDirectory.getFqNameWithImplicitPrefix() file.project.executeWriteCommand(text) { val targetFile = getOrCreateKotlinFile(fileName, targetDirectory, (packageFqName ?: defaultPackageFqName).asString()) if (targetFile != null) { doInvoke(targetFile, editor, file, false) } } return } val element = element ?: return runWriteAction<Unit> { with(classInfo) { val targetParent = when (selectedParent) { is KtElement, is PsiClass -> selectedParent is PsiPackage -> createFileByPackage(selectedParent, editor, file) else -> throw KotlinExceptionWithAttachments("Unexpected element: ${selectedParent::class.java}") .withPsiAttachment("selectedParent", selectedParent) } ?: return@runWriteAction val constructorInfo = ClassWithPrimaryConstructorInfo( classInfo, // Need for #KT-22137 if (expectedTypeInfo.isUnit) TypeInfo.Empty else expectedTypeInfo, primaryConstructorVisibility = classInfo.primaryConstructorVisibility ) val builder = CallableBuilderConfiguration( Collections.singletonList(constructorInfo), element, file, editor, false, kind == PLAIN_CLASS || kind == INTERFACE ).createBuilder() builder.placement = CallablePlacement.NoReceiver(targetParent) fun buildClass() { builder.build { if (targetParent !is KtFile || targetParent == file) return@build val targetPackageFqName = targetParent.packageFqName if (targetPackageFqName == file.packageFqName) return@build val reference = (element.getQualifiedElementSelector() as? KtSimpleNameExpression)?.mainReference ?: return@build reference.bindToFqName( targetPackageFqName.child(Name.identifier(className)), KtSimpleNameReference.ShorteningMode.FORCED_SHORTENING ) } } if (startCommand) { file.project.executeCommand(text, command = ::buildClass) } else { buildClass() } } } } private class LowPriorityCreateClassFromUsageFix<E : KtElement>( element: E, classInfo: ClassInfo ) : CreateClassFromUsageFix<E>(element, classInfo), LowPriorityAction private class HighPriorityCreateClassFromUsageFix<E : KtElement>( element: E, classInfo: ClassInfo ) : CreateClassFromUsageFix<E>(element, classInfo), HighPriorityAction companion object { fun <E : KtElement> create(element: E, classInfo: ClassInfo): CreateClassFromUsageFix<E> { return when (classInfo.kind.actionPriority) { IntentionActionPriority.NORMAL -> CreateClassFromUsageFix(element, classInfo) IntentionActionPriority.LOW -> LowPriorityCreateClassFromUsageFix(element, classInfo) IntentionActionPriority.HIGH -> HighPriorityCreateClassFromUsageFix(element, classInfo) } } } } private val TypeInfo.isUnit: Boolean get() = ((this as? TypeInfo.DelegatingTypeInfo)?.delegate as? TypeInfo.ByType)?.theType?.isUnit() == true
apache-2.0
18fa491d8bf122132bf0815b59e258f9
43.798561
158
0.64959
5.525288
false
false
false
false
550609334/Twobbble
app/src/main/java/com/twobbble/view/fragment/ExploreFragment.kt
1
9006
package com.twobbble.view.fragment import android.animation.ObjectAnimator import android.app.ActivityOptions import android.content.Intent import android.os.Bundle import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import com.twobbble.R import com.twobbble.application.App import com.twobbble.entity.Shot import com.twobbble.event.OpenDrawerEvent import com.twobbble.presenter.service.ShotsPresenter import com.twobbble.tools.* import com.twobbble.view.activity.DetailsActivity import com.twobbble.view.activity.SearchActivity import com.twobbble.view.activity.UserActivity import com.twobbble.view.adapter.ItemShotAdapter import com.twobbble.view.api.IShotsView import kotlinx.android.synthetic.main.error_layout.* import kotlinx.android.synthetic.main.fragment_explore.* import kotlinx.android.synthetic.main.list.* import kotlinx.android.synthetic.main.search_layout.* import org.greenrobot.eventbus.EventBus /** * Created by liuzipeng on 2017/2/17. */ class ExploreFragment : BaseFragment(), IShotsView { override fun onBackPressed() { hideSearchView() } private val mPresenter: ShotsPresenter by lazy { ShotsPresenter(this) } private var mSort: String? = null private var mSortList: String? = null private var mTimeFrame: String? = null private var mPage: Int = 1 private lateinit var mShots: MutableList<Shot> private var mListAdapter: ItemShotAdapter? = null private var isLoading: Boolean = false private val mSorts = listOf(null, Parameters.COMMENTS, Parameters.RECENT, Parameters.VIEWS) private val mList = listOf(null, Parameters.ANIMATED, Parameters.ATTACHMENTS, Parameters.DEBUTS, Parameters.DEBUTS, Parameters.PLAYOFFS, Parameters.REBOUNDS, Parameters.TEAMS) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { return LayoutInflater.from(activity).inflate(R.layout.fragment_explore, null) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() bindEvent() getShots(false) } private fun initView() { Toolbar.inflateMenu(R.menu.expolre_menu) mRefresh.setColorSchemeResources(R.color.google_red, R.color.google_yellow, R.color.google_green, R.color.google_blue) val layoutManager = LinearLayoutManager(App.instance, LinearLayoutManager.VERTICAL, false) mRecyclerView.layoutManager = layoutManager mRecyclerView.itemAnimator = DefaultItemAnimator() mSortSpinner.setSelection(0, true) mSortListSpinner.setSelection(0, true) } fun getShots(isLoadMore: Boolean = false) { isLoading = true val token = QuickSimpleIO.getString(Constant.KEY_TOKEN) if (token == null || token == "") { mPresenter.getShots(sort = mSort, list = mSortList, timeframe = mTimeFrame, page = mPage, isLoadMore = isLoadMore) } else { mPresenter.getShots(access_token = token, sort = mSort, list = mSortList, timeframe = mTimeFrame, page = mPage, isLoadMore = isLoadMore) } } override fun onStart() { super.onStart() } private fun bindEvent() { mSearchEdit.setOnKeyListener { _, keycode, keyEvent -> if (keyEvent.action == KeyEvent.ACTION_DOWN) {//判断是否为点按下去触发的事件,如果不写,会导致该案件的事件被执行两次 when (keycode) { KeyEvent.KEYCODE_ENTER -> search() } } false } mBackBtn.setOnClickListener { hideSearchView() } mSearchBtn.setOnClickListener { search() } mVoiceBtn.setOnClickListener { startSpeak() } Toolbar.setNavigationOnClickListener { EventBus.getDefault().post(OpenDrawerEvent()) } mRefresh.setOnRefreshListener { mPage = 1 getShots(false) } mErrorLayout.setOnClickListener { hideErrorImg(mErrorLayout) getShots(false) } mRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { val linearManager = recyclerView?.layoutManager as LinearLayoutManager val position = linearManager.findLastVisibleItemPosition() if (mShots.isNotEmpty() && position == mShots.size) { if (!isLoading) { mPage += 1 getShots(true) } } } }) mSortSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) {} override fun onItemSelected(p0: AdapterView<*>?, view: View?, position: Int, p3: Long) { mSort = mSorts[position] mListAdapter = null getShots(false) } } mSortListSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) {} override fun onItemSelected(p0: AdapterView<*>?, view: View?, position: Int, p3: Long) { mListAdapter = null mSortList = mList[position] getShots(false) } } Toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.mNow -> timeFrameUpdate(null) R.id.mWeek -> timeFrameUpdate(Parameters.WEEK) R.id.mMonth -> timeFrameUpdate(Parameters.MONTH) R.id.mYear -> timeFrameUpdate(Parameters.YEAR) R.id.mAllTime -> timeFrameUpdate(Parameters.EVER) R.id.mSearch -> mSearchLayout.showSearchView(Toolbar.width, { isShowSearchBar = true }) } true } } /** * 更新时间线 * @param timeFrame 时间线,默认为null,代表Now,其它的值在Parameters这个单利对象中保存 */ private fun timeFrameUpdate(timeFrame: String?) { mListAdapter = null mTimeFrame = timeFrame getShots(false) } override fun showProgress() { if (mListAdapter == null) mRefresh.isRefreshing = true } override fun hideProgress() { mRefresh.isRefreshing = false } override fun getShotSuccess(shots: MutableList<Shot>?, isLoadMore: Boolean) { isLoading = false if (shots != null && shots.isNotEmpty()) { if (!isLoadMore) { mountList(shots) } else { mListAdapter?.addItems(shots) } } else { if (!isLoadMore) { if (mListAdapter == null) showErrorImg(mErrorLayout) } else { mListAdapter?.loadError { getShots(true) } } } } private fun mountList(shots: MutableList<Shot>) { mShots = shots mListAdapter = ItemShotAdapter(mShots, { EventBus.getDefault().postSticky(mShots[it]) startDetailsActivity() }, { EventBus.getDefault().postSticky(shots[it].user) startActivity(Intent(activity, UserActivity::class.java)) }) mRecyclerView.adapter = mListAdapter } override fun getShotFailed(msg: String, isLoadMore: Boolean) { isLoading = false toast(msg) if (!isLoadMore) { if (mListAdapter == null) showErrorImg(mErrorLayout, msg, R.mipmap.img_network_error_2) } else { mListAdapter?.loadError { getShots(true) } } } private fun search() { if (mSearchEdit.text != null && mSearchEdit.text.toString() != "") { val intent = Intent(activity, SearchActivity::class.java) intent.putExtra(SearchActivity.KEY_KEYWORD, mSearchEdit.text.toString()) startActivity(intent, ActivityOptions. makeSceneTransitionAnimation(activity, mSearchLayout, "searchBar").toBundle()) } } private fun hideSearchView() { mSearchLayout.hideSearchView { isShowSearchBar = false } } }
apache-2.0
6bcc6cb2c3dd751ca87391f9b92c5efd
33.819608
126
0.618383
4.910398
false
false
false
false
siosio/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/introduce/extractionEngine/extractorUtil.kt
1
32301
// 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.refactoring.introduce.extractionEngine import com.intellij.codeHighlighting.HighlightDisplayLevel import com.intellij.openapi.util.Key import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.BaseRefactoringProcessor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.isFunctionType import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.PropertyDescriptor import org.jetbrains.kotlin.descriptors.DescriptorVisibilities import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.inspections.PublicApiImplicitTypeInspection import org.jetbrains.kotlin.idea.inspections.UseExpressionBodyInspection import org.jetbrains.kotlin.idea.intentions.InfixCallToOrdinaryIntention import org.jetbrains.kotlin.idea.intentions.OperatorToFunctionIntention import org.jetbrains.kotlin.idea.intentions.RemoveExplicitTypeArgumentsIntention import org.jetbrains.kotlin.idea.refactoring.introduce.* import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValue.* import org.jetbrains.kotlin.idea.refactoring.introduce.extractionEngine.OutputValueBoxer.AsTuple import org.jetbrains.kotlin.idea.refactoring.removeTemplateEntryBracesIfPossible import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables import org.jetbrains.kotlin.idea.util.getResolutionScope import org.jetbrains.kotlin.idea.util.psi.patternMatching.* import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnificationResult.StronglyMatched import org.jetbrains.kotlin.idea.util.psi.patternMatching.UnificationResult.WeaklyMatched import org.jetbrains.kotlin.idea.util.reformatted import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.KtPsiFactory.CallableBuilder import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.renderer.DescriptorRenderer import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.calls.callUtil.getCalleeExpressionIfAny import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isError import org.jetbrains.kotlin.types.isFlexible import java.util.* private fun buildSignature(config: ExtractionGeneratorConfiguration, renderer: DescriptorRenderer): CallableBuilder { val extractionTarget = config.generatorOptions.target if (!extractionTarget.isAvailable(config.descriptor)) { val message = KotlinBundle.message("error.text.can.t.generate.0.1", extractionTarget.targetName, config.descriptor.extractionData.codeFragmentText ) throw BaseRefactoringProcessor.ConflictsInTestsException(listOf(message)) } val builderTarget = when (extractionTarget) { ExtractionTarget.FUNCTION, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION -> CallableBuilder.Target.FUNCTION else -> CallableBuilder.Target.READ_ONLY_PROPERTY } return CallableBuilder(builderTarget).apply { val visibility = config.descriptor.visibility?.value ?: "" fun TypeParameter.isReified() = originalDeclaration.hasModifier(KtTokens.REIFIED_KEYWORD) val shouldBeInline = config.descriptor.typeParameters.any { it.isReified() } val annotations = if (config.descriptor.annotations.isEmpty()) { "" } else { config.descriptor.annotations.joinToString(separator = "\n", postfix = "\n") { renderer.renderAnnotation(it) } } val extraModifiers = config.descriptor.modifiers.map { it.value } + listOfNotNull(if (shouldBeInline) KtTokens.INLINE_KEYWORD.value else null) val modifiers = if (visibility.isNotEmpty()) listOf(visibility) + extraModifiers else extraModifiers modifier(annotations + modifiers.joinToString(separator = " ")) typeParams( config.descriptor.typeParameters.map { val typeParameter = it.originalDeclaration val bound = typeParameter.extendsBound buildString { if (it.isReified()) { append(KtTokens.REIFIED_KEYWORD.value) append(' ') } append(typeParameter.name) if (bound != null) { append(" : ") append(bound.text) } } } ) fun KotlinType.typeAsString() = renderer.renderType(this) config.descriptor.receiverParameter?.let { val receiverType = it.parameterType val receiverTypeAsString = receiverType.typeAsString() receiver(if (receiverType.isFunctionType) "($receiverTypeAsString)" else receiverTypeAsString) } name(config.generatorOptions.dummyName ?: config.descriptor.name) config.descriptor.parameters.forEach { parameter -> param(parameter.name, parameter.parameterType.typeAsString()) } with(config.descriptor.returnType) { if (KotlinBuiltIns.isUnit(this) || isError || extractionTarget == ExtractionTarget.PROPERTY_WITH_INITIALIZER) { noReturnType() } else { returnType(typeAsString()) } } typeConstraints(config.descriptor.typeParameters.flatMap { it.originalConstraints }.map { it.text!! }) } } fun ExtractionGeneratorConfiguration.getSignaturePreview(renderer: DescriptorRenderer) = buildSignature(this, renderer).asString() fun ExtractionGeneratorConfiguration.getDeclarationPattern( descriptorRenderer: DescriptorRenderer = IdeDescriptorRenderers.SOURCE_CODE ): String { val extractionTarget = generatorOptions.target if (!extractionTarget.isAvailable(descriptor)) { throw BaseRefactoringProcessor.ConflictsInTestsException( listOf( KotlinBundle.message("error.text.can.t.generate.0.1", extractionTarget.targetName, descriptor.extractionData.codeFragmentText ) ) ) } return buildSignature(this, descriptorRenderer).let { builder -> builder.transform { for (i in generateSequence(indexOf('$')) { indexOf('$', it + 2) }) { if (i < 0) break insert(i + 1, '$') } } when (extractionTarget) { ExtractionTarget.FUNCTION, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION, ExtractionTarget.PROPERTY_WITH_GETTER -> builder.blockBody("$0") ExtractionTarget.PROPERTY_WITH_INITIALIZER -> builder.initializer("$0") ExtractionTarget.LAZY_PROPERTY -> builder.lazyBody("$0") } builder.asString() } } fun KotlinType.isSpecial(): Boolean { val classDescriptor = this.constructor.declarationDescriptor as? ClassDescriptor ?: return false return classDescriptor.name.isSpecial || DescriptorUtils.isLocal(classDescriptor) } fun createNameCounterpartMap(from: KtElement, to: KtElement): Map<KtSimpleNameExpression, KtSimpleNameExpression> { return from.collectDescendantsOfType<KtSimpleNameExpression>().zip(to.collectDescendantsOfType<KtSimpleNameExpression>()).toMap() } class DuplicateInfo( val range: KotlinPsiRange, val controlFlow: ControlFlow, val arguments: List<String> ) fun ExtractableCodeDescriptor.findDuplicates(): List<DuplicateInfo> { fun processWeakMatch(match: WeaklyMatched, newControlFlow: ControlFlow): Boolean { val valueCount = controlFlow.outputValues.size val weakMatches = HashMap(match.weakMatches) val currentValuesToNew = HashMap<OutputValue, OutputValue>() fun matchValues(currentValue: OutputValue, newValue: OutputValue): Boolean { if ((currentValue is Jump) != (newValue is Jump)) return false if (currentValue.originalExpressions.zip(newValue.originalExpressions).all { weakMatches[it.first] == it.second }) { currentValuesToNew[currentValue] = newValue weakMatches.keys.removeAll(currentValue.originalExpressions) return true } return false } if (valueCount == 1) { matchValues(controlFlow.outputValues.first(), newControlFlow.outputValues.first()) } else { outer@ for (currentValue in controlFlow.outputValues) for (newValue in newControlFlow.outputValues) { if ((currentValue is ExpressionValue) != (newValue is ExpressionValue)) continue if (matchValues(currentValue, newValue)) continue@outer } } return currentValuesToNew.size == valueCount && weakMatches.isEmpty() } fun getControlFlowIfMatched(match: UnificationResult.Matched): ControlFlow? { val analysisResult = extractionData.copy(originalRange = match.range).performAnalysis() if (analysisResult.status != AnalysisResult.Status.SUCCESS) return null val newControlFlow = analysisResult.descriptor!!.controlFlow if (newControlFlow.outputValues.isEmpty()) return newControlFlow if (controlFlow.outputValues.size != newControlFlow.outputValues.size) return null val matched = when (match) { is StronglyMatched -> true is WeaklyMatched -> processWeakMatch(match, newControlFlow) else -> throw AssertionError("Unexpected unification result: $match") } return if (matched) newControlFlow else null } val unifierParameters = parameters.map { UnifierParameter(it.originalDescriptor, it.parameterType) } val unifier = KotlinPsiUnifier(unifierParameters, true) val scopeElement = getOccurrenceContainer() ?: return Collections.emptyList() val originalTextRange = extractionData.originalRange.getPhysicalTextRange() return extractionData .originalRange .match(scopeElement, unifier) .asSequence() .filter { !(it.range.getPhysicalTextRange().intersects(originalTextRange)) } .mapNotNull { match -> val controlFlow = getControlFlowIfMatched(match) val range = with(match.range) { (elements.singleOrNull() as? KtStringTemplateEntryWithExpression)?.expression?.toRange() ?: this } controlFlow?.let { DuplicateInfo(range, it, unifierParameters.map { param -> match.substitution.getValue(param).text!! }) } } .toList() } private fun ExtractableCodeDescriptor.getOccurrenceContainer(): PsiElement? { return extractionData.duplicateContainer ?: extractionData.targetSibling.parent } private fun makeCall( extractableDescriptor: ExtractableCodeDescriptor, declaration: KtNamedDeclaration, controlFlow: ControlFlow, rangeToReplace: KotlinPsiRange, arguments: List<String> ) { fun insertCall(anchor: PsiElement, wrappedCall: KtExpression): KtExpression? { val firstExpression = rangeToReplace.elements.firstOrNull { it is KtExpression } as? KtExpression if (firstExpression?.isLambdaOutsideParentheses() == true) { val functionLiteralArgument = firstExpression.getStrictParentOfType<KtLambdaArgument>()!! return functionLiteralArgument.moveInsideParenthesesAndReplaceWith(wrappedCall, extractableDescriptor.originalContext) } if (anchor is KtOperationReferenceExpression) { val newNameExpression = when (val operationExpression = anchor.parent as? KtOperationExpression ?: return null) { is KtUnaryExpression -> OperatorToFunctionIntention.convert(operationExpression).second is KtBinaryExpression -> { InfixCallToOrdinaryIntention.convert(operationExpression).getCalleeExpressionIfAny() } else -> null } return newNameExpression?.replaced(wrappedCall) } (anchor as? KtExpression)?.extractableSubstringInfo?.let { return it.replaceWith(wrappedCall) } return anchor.replaced(wrappedCall) } if (rangeToReplace !is KotlinPsiRange.ListRange) return val anchor = rangeToReplace.startElement val anchorParent = anchor.parent!! anchor.nextSibling?.let { from -> val to = rangeToReplace.endElement if (to != anchor) { anchorParent.deleteChildRange(from, to) } } val calleeName = declaration.name?.quoteIfNeeded() val callText = when (declaration) { is KtNamedFunction -> { val argumentsText = arguments.joinToString(separator = ", ", prefix = "(", postfix = ")") val typeArguments = extractableDescriptor.typeParameters.map { it.originalDeclaration.name } val typeArgumentsText = with(typeArguments) { if (isNotEmpty()) joinToString(separator = ", ", prefix = "<", postfix = ">") else "" } "$calleeName$typeArgumentsText$argumentsText" } else -> calleeName } val anchorInBlock = generateSequence(anchor) { it.parent }.firstOrNull { it.parent is KtBlockExpression } val block = (anchorInBlock?.parent as? KtBlockExpression) ?: anchorParent val psiFactory = KtPsiFactory(anchor.project) val newLine = psiFactory.createNewLine() if (controlFlow.outputValueBoxer is AsTuple && controlFlow.outputValues.size > 1 && controlFlow.outputValues .all { it is Initializer } ) { val declarationsToMerge = controlFlow.outputValues.map { (it as Initializer).initializedDeclaration } val isVar = declarationsToMerge.first().isVar if (declarationsToMerge.all { it.isVar == isVar }) { controlFlow.declarationsToCopy.subtract(declarationsToMerge).forEach { block.addBefore(psiFactory.createDeclaration(it.text!!), anchorInBlock) as KtDeclaration block.addBefore(newLine, anchorInBlock) } val entries = declarationsToMerge.map { p -> p.name + (p.typeReference?.let { ": ${it.text}" } ?: "") } anchorInBlock?.replace( psiFactory.createDestructuringDeclaration("${if (isVar) "var" else "val"} (${entries.joinToString()}) = $callText") ) return } } val inlinableCall = controlFlow.outputValues.size <= 1 val unboxingExpressions = if (inlinableCall) { controlFlow.outputValueBoxer.getUnboxingExpressions(callText ?: return) } else { val varNameValidator = NewDeclarationNameValidator(block, anchorInBlock, NewDeclarationNameValidator.Target.VARIABLES) val resultVal = KotlinNameSuggester.suggestNamesByType(extractableDescriptor.returnType, varNameValidator, null).first() block.addBefore(psiFactory.createDeclaration("val $resultVal = $callText"), anchorInBlock) block.addBefore(newLine, anchorInBlock) controlFlow.outputValueBoxer.getUnboxingExpressions(resultVal) } val copiedDeclarations = HashMap<KtDeclaration, KtDeclaration>() for (decl in controlFlow.declarationsToCopy) { val declCopy = psiFactory.createDeclaration<KtDeclaration>(decl.text!!) copiedDeclarations[decl] = block.addBefore(declCopy, anchorInBlock) as KtDeclaration block.addBefore(newLine, anchorInBlock) } if (controlFlow.outputValues.isEmpty()) { anchor.replace(psiFactory.createExpression(callText!!)) return } fun wrapCall(outputValue: OutputValue, callText: String): List<PsiElement> { return when (outputValue) { is ExpressionValue -> { val exprText = if (outputValue.callSiteReturn) { val firstReturn = outputValue.originalExpressions.asSequence().filterIsInstance<KtReturnExpression>().firstOrNull() val label = firstReturn?.getTargetLabel()?.text ?: "" "return$label $callText" } else { callText } Collections.singletonList(psiFactory.createExpression(exprText)) } is ParameterUpdate -> Collections.singletonList( psiFactory.createExpression("${outputValue.parameter.argumentText} = $callText") ) is Jump -> { when { outputValue.elementToInsertAfterCall == null -> Collections.singletonList(psiFactory.createExpression(callText)) outputValue.conditional -> Collections.singletonList( psiFactory.createExpression("if ($callText) ${outputValue.elementToInsertAfterCall.text}") ) else -> listOf( psiFactory.createExpression(callText), newLine, psiFactory.createExpression(outputValue.elementToInsertAfterCall.text!!) ) } } is Initializer -> { val newProperty = copiedDeclarations[outputValue.initializedDeclaration] as KtProperty newProperty.initializer = psiFactory.createExpression(callText) Collections.emptyList() } else -> throw IllegalArgumentException("Unknown output value: $outputValue") } } val defaultValue = controlFlow.defaultOutputValue controlFlow.outputValues .filter { it != defaultValue } .flatMap { wrapCall(it, unboxingExpressions.getValue(it)) } .withIndex() .forEach { val (i, e) = it if (i > 0) { block.addBefore(newLine, anchorInBlock) } block.addBefore(e, anchorInBlock) } defaultValue?.let { if (!inlinableCall) { block.addBefore(newLine, anchorInBlock) } insertCall(anchor, wrapCall(it, unboxingExpressions.getValue(it)).first() as KtExpression)?.removeTemplateEntryBracesIfPossible() } if (anchor.isValid) { anchor.delete() } } private var KtExpression.isJumpElementToReplace: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("IS_JUMP_ELEMENT_TO_REPLACE"), false) private var KtReturnExpression.isReturnForLabelRemoval: Boolean by NotNullablePsiCopyableUserDataProperty(Key.create("IS_RETURN_FOR_LABEL_REMOVAL"), false) fun ExtractionGeneratorConfiguration.generateDeclaration( declarationToReplace: KtNamedDeclaration? = null ): ExtractionResult { val psiFactory = KtPsiFactory(descriptor.extractionData.originalFile) fun getReturnsForLabelRemoval() = descriptor.controlFlow.outputValues .flatMapTo(arrayListOf()) { it.originalExpressions.filterIsInstance<KtReturnExpression>() } fun createDeclaration(): KtNamedDeclaration { descriptor.controlFlow.jumpOutputValue?.elementsToReplace?.forEach { it.isJumpElementToReplace = true } getReturnsForLabelRemoval().forEach { it.isReturnForLabelRemoval = true } return with(descriptor.extractionData) { if (generatorOptions.inTempFile) { createTemporaryDeclaration("${getDeclarationPattern()}\n") } else { psiFactory.createDeclarationByPattern( getDeclarationPattern(), PsiChildRange(originalElements.firstOrNull(), originalElements.lastOrNull()) ) } } } fun getReturnArguments(resultExpression: KtExpression?): List<KtExpression> { return descriptor.controlFlow.outputValues .mapNotNull { when (it) { is ExpressionValue -> resultExpression is Jump -> if (it.conditional) psiFactory.createExpression("false") else null is ParameterUpdate -> psiFactory.createExpression(it.parameter.nameForRef) is Initializer -> psiFactory.createExpression(it.initializedDeclaration.name!!) else -> throw IllegalArgumentException("Unknown output value: $it") } } } fun KtExpression.replaceWithReturn(replacingExpression: KtReturnExpression) { descriptor.controlFlow.defaultOutputValue?.let { val boxedExpression = replaced(replacingExpression).returnedExpression!! descriptor.controlFlow.outputValueBoxer.extractExpressionByValue(boxedExpression, it) } } fun getPublicApiInspectionIfEnabled(): PublicApiImplicitTypeInspection? { val project = descriptor.extractionData.project val inspectionProfileManager = ProjectInspectionProfileManager.getInstance(project) val inspectionProfile = inspectionProfileManager.currentProfile val state = inspectionProfile.getToolsOrNull("PublicApiImplicitType", project)?.defaultState ?: return null if (!state.isEnabled || state.level == HighlightDisplayLevel.DO_NOT_SHOW) return null return state.tool.tool as? PublicApiImplicitTypeInspection } fun useExplicitReturnType(): Boolean { if (descriptor.returnType.isFlexible()) return true val inspection = getPublicApiInspectionIfEnabled() ?: return false val targetClass = (descriptor.extractionData.targetSibling.parent as? KtClassBody)?.parent as? KtClassOrObject if ((targetClass != null && targetClass.isLocal) || descriptor.extractionData.isLocal()) return false val visibility = (descriptor.visibility ?: KtTokens.DEFAULT_VISIBILITY_KEYWORD).toVisibility() return when { visibility.isPublicAPI -> true inspection.reportInternal && visibility == DescriptorVisibilities.INTERNAL -> true inspection.reportPrivate && visibility == DescriptorVisibilities.PRIVATE -> true else -> false } } fun adjustDeclarationBody(declaration: KtNamedDeclaration) { val body = declaration.getGeneratedBody() (body.blockExpressionsOrSingle().singleOrNull() as? KtExpression)?.let { if (it.mustBeParenthesizedInInitializerPosition()) { it.replace(psiFactory.createExpressionByPattern("($0)", it)) } } val jumpValue = descriptor.controlFlow.jumpOutputValue if (jumpValue != null) { val replacingReturn = psiFactory.createExpression(if (jumpValue.conditional) "return true" else "return") body.collectDescendantsOfType<KtExpression> { it.isJumpElementToReplace }.forEach { it.replace(replacingReturn) it.isJumpElementToReplace = false } } body.collectDescendantsOfType<KtReturnExpression> { it.isReturnForLabelRemoval }.forEach { it.getTargetLabel()?.delete() it.isReturnForLabelRemoval = false } /* * Sort by descending position so that internals of value/type arguments in calls and qualified types are replaced * before calls/types themselves */ val currentRefs = body .collectDescendantsOfType<KtSimpleNameExpression> { it.resolveResult != null } .sortedByDescending { it.startOffset } currentRefs.forEach { val resolveResult = it.resolveResult!! val currentRef = if (it.isValid) { it } else { body.findDescendantOfType { expr -> expr.resolveResult == resolveResult } ?: return@forEach } val originalRef = resolveResult.originalRefExpr val newRef = descriptor.replacementMap[originalRef] .fold(currentRef as KtElement) { ref, replacement -> replacement(descriptor, ref) } (newRef as? KtSimpleNameExpression)?.resolveResult = resolveResult } if (generatorOptions.target == ExtractionTarget.PROPERTY_WITH_INITIALIZER) return if (body !is KtBlockExpression) throw AssertionError("Block body expected: ${descriptor.extractionData.codeFragmentText}") val firstExpression = body.statements.firstOrNull() if (firstExpression != null) { for (param in descriptor.parameters) { param.mirrorVarName?.let { varName -> body.addBefore(psiFactory.createProperty(varName, null, true, param.name), firstExpression) body.addBefore(psiFactory.createNewLine(), firstExpression) } } } val defaultValue = descriptor.controlFlow.defaultOutputValue val lastExpression = body.statements.lastOrNull() if (lastExpression is KtReturnExpression) return val defaultExpression = if (!generatorOptions.inTempFile && defaultValue != null && descriptor.controlFlow.outputValueBoxer .boxingRequired && lastExpression!!.isMultiLine() ) { val varNameValidator = NewDeclarationNameValidator(body, lastExpression, NewDeclarationNameValidator.Target.VARIABLES) val resultVal = KotlinNameSuggester.suggestNamesByType(defaultValue.valueType, varNameValidator, null).first() body.addBefore(psiFactory.createDeclaration("val $resultVal = ${lastExpression.text}"), lastExpression) body.addBefore(psiFactory.createNewLine(), lastExpression) psiFactory.createExpression(resultVal) } else lastExpression val returnExpression = descriptor.controlFlow.outputValueBoxer.getReturnExpression(getReturnArguments(defaultExpression), psiFactory) ?: return @Suppress("NON_EXHAUSTIVE_WHEN") when (generatorOptions.target) { ExtractionTarget.LAZY_PROPERTY, ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION -> { // In the case of lazy property absence of default value means that output values are of OutputValue.Initializer type // We just add resulting expressions without return, since returns are prohibited in the body of lazy property if (defaultValue == null) { body.appendElement(returnExpression.returnedExpression!!) } return } } when { defaultValue == null -> body.appendElement(returnExpression) !defaultValue.callSiteReturn -> lastExpression!!.replaceWithReturn(returnExpression) } if (generatorOptions.allowExpressionBody) { val bodyExpression = body.statements.singleOrNull() val bodyOwner = body.parent as KtDeclarationWithBody val useExpressionBodyInspection = UseExpressionBodyInspection() if (bodyExpression != null && useExpressionBodyInspection.isActiveFor(bodyOwner)) { useExpressionBodyInspection.simplify(bodyOwner, !useExplicitReturnType()) } } } fun insertDeclaration(declaration: KtNamedDeclaration, anchor: PsiElement): KtNamedDeclaration { declarationToReplace?.let { return it.replace(declaration) as KtNamedDeclaration } return with(descriptor.extractionData) { val targetContainer = anchor.parent!! // TODO: Get rid of explicit new-lines in favor of formatter rules val emptyLines = psiFactory.createWhiteSpace("\n\n") if (insertBefore) { (targetContainer.addBefore(declaration, anchor) as KtNamedDeclaration).apply { targetContainer.addBefore(emptyLines, anchor) } } else { (targetContainer.addAfter(declaration, anchor) as KtNamedDeclaration).apply { if (!(targetContainer is KtClassBody && (targetContainer.parent as? KtClass)?.isEnum() == true)) { targetContainer.addAfter(emptyLines, anchor) } } } } } val duplicates = if (generatorOptions.inTempFile) Collections.emptyList() else descriptor.duplicates val anchor = with(descriptor.extractionData) { val targetParent = targetSibling.parent val anchorCandidates = duplicates.mapTo(arrayListOf()) { it.range.elements.first().substringContextOrThis } anchorCandidates.add(targetSibling) if (targetSibling is KtEnumEntry) { anchorCandidates.add(targetSibling.siblings().last { it is KtEnumEntry }) } val marginalCandidate = if (insertBefore) { anchorCandidates.minByOrNull { it.startOffset }!! } else { anchorCandidates.maxByOrNull { it.startOffset }!! } // Ascend to the level of targetSibling marginalCandidate.parentsWithSelf.first { it.parent == targetParent } } val shouldInsert = !(generatorOptions.inTempFile || generatorOptions.target == ExtractionTarget.FAKE_LAMBDALIKE_FUNCTION) val declaration = createDeclaration().let { if (shouldInsert) insertDeclaration(it, anchor) else it } adjustDeclarationBody(declaration) if (generatorOptions.inTempFile) return ExtractionResult(this, declaration, Collections.emptyMap()) val replaceInitialOccurrence = { val arguments = descriptor.parameters.map { it.argumentText } makeCall(descriptor, declaration, descriptor.controlFlow, descriptor.extractionData.originalRange, arguments) } if (!generatorOptions.delayInitialOccurrenceReplacement) replaceInitialOccurrence() if (shouldInsert) { ShortenReferences.DEFAULT.process(declaration) } if (generatorOptions.inTempFile) return ExtractionResult(this, declaration, emptyMap()) val duplicateReplacers = HashMap<KotlinPsiRange, () -> Unit>().apply { if (generatorOptions.delayInitialOccurrenceReplacement) { put(descriptor.extractionData.originalRange, replaceInitialOccurrence) } putAll(duplicates.map { it.range to { makeCall(descriptor, declaration, it.controlFlow, it.range, it.arguments) } }) } if (descriptor.typeParameters.isNotEmpty()) { for (ref in ReferencesSearch.search(declaration, LocalSearchScope(descriptor.getOccurrenceContainer()!!))) { val typeArgumentList = (ref.element.parent as? KtCallExpression)?.typeArgumentList ?: continue if (RemoveExplicitTypeArgumentsIntention.isApplicableTo(typeArgumentList, false)) { typeArgumentList.delete() } } } if (declaration is KtProperty) { if (declaration.isExtensionDeclaration() && !declaration.isTopLevel) { val receiverTypeReference = (declaration as? KtCallableDeclaration)?.receiverTypeReference receiverTypeReference?.siblings(withItself = false)?.firstOrNull { it.node.elementType == KtTokens.DOT }?.delete() receiverTypeReference?.delete() } if ((declaration.descriptor as? PropertyDescriptor)?.let { DescriptorUtils.isOverride(it) } == true) { val scope = declaration.getResolutionScope() val newName = KotlinNameSuggester.suggestNameByName(descriptor.name) { it != descriptor.name && scope.getAllAccessibleVariables(Name.identifier(it)).isEmpty() } declaration.setName(newName) } } CodeStyleManager.getInstance(descriptor.extractionData.project).reformat(declaration) return ExtractionResult(this, declaration, duplicateReplacers) }
apache-2.0
999fbbd9e8c1de5bc03efdafbd675201
44.817021
158
0.675211
5.691806
false
false
false
false
actions-on-google/app-actions-dynamic-shortcuts
app/src/main/java/com/example/android/architecture/blueprints/todoapp/data/source/local/TasksDao.kt
1
3101
/* * Copyright (C) 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.data.source.local import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Update import com.example.android.architecture.blueprints.todoapp.data.Task /** * Data Access Object for the tasks table. */ @Dao interface TasksDao { /** * Observes list of tasks. * * @return all tasks. */ @Query("SELECT * FROM Tasks") fun observeTasks(): LiveData<List<Task>> /** * Observes a single task. * * @param taskId the task id. * @return the task with taskId. */ @Query("SELECT * FROM Tasks WHERE entryid = :taskId") fun observeTaskById(taskId: String): LiveData<Task> /** * Select all tasks from the tasks table. * * @return all tasks. */ @Query("SELECT * FROM Tasks") suspend fun getTasks(): List<Task> /** * Select a task by id. * * @param taskId the task id. * @return the task with taskId. */ @Query("SELECT * FROM Tasks WHERE entryid = :taskId") suspend fun getTaskById(taskId: String): Task? /** * Insert a task in the database. If the task already exists, replace it. * * @param task the task to be inserted. */ @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertTask(task: Task) /** * Update a task. * * @param task task to be updated * @return the number of tasks updated. This should always be 1. */ @Update suspend fun updateTask(task: Task): Int /** * Update the complete status of a task * * @param taskId id of the task * @param completed status to be updated */ @Query("UPDATE tasks SET completed = :completed WHERE entryid = :taskId") suspend fun updateCompleted(taskId: String, completed: Boolean) /** * Delete a task by id. * * @return the number of tasks deleted. This should always be 1. */ @Query("DELETE FROM Tasks WHERE entryid = :taskId") suspend fun deleteTaskById(taskId: String): Int /** * Delete all tasks. */ @Query("DELETE FROM Tasks") suspend fun deleteTasks() /** * Delete all completed tasks from the table. * * @return the number of tasks deleted. */ @Query("DELETE FROM Tasks WHERE completed = 1") suspend fun deleteCompletedTasks(): Int }
apache-2.0
773bff8e2eab6c8284bc6febbc061b3d
26.201754
77
0.650758
4.168011
false
false
false
false
siosio/intellij-community
plugins/kotlin/jps/jps-common/src/org/jetbrains/kotlin/platform/compat/compatConversions.kt
1
3001
// 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:Suppress("DEPRECATION_ERROR", "TYPEALIAS_EXPANSION_DEPRECATION_ERROR") package org.jetbrains.kotlin.platform.compat import org.jetbrains.kotlin.config.JvmTarget import org.jetbrains.kotlin.platform.CommonPlatforms import org.jetbrains.kotlin.platform.IdePlatform import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind import org.jetbrains.kotlin.platform.impl.JsIdePlatformKind import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind import org.jetbrains.kotlin.platform.impl.NativeIdePlatformKind import org.jetbrains.kotlin.platform.js.JsPlatform import org.jetbrains.kotlin.platform.js.JsPlatforms import org.jetbrains.kotlin.platform.jvm.JdkPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatform import org.jetbrains.kotlin.platform.jvm.JvmPlatforms import org.jetbrains.kotlin.platform.konan.NativePlatforms import org.jetbrains.kotlin.platform.konan.NativePlatform typealias OldPlatform = org.jetbrains.kotlin.resolve.TargetPlatform typealias NewPlatform = org.jetbrains.kotlin.platform.TargetPlatform fun NewPlatform.toOldPlatform(): OldPlatform = when (val single = singleOrNull()) { null -> CommonPlatforms.CompatCommonPlatform is JvmPlatform -> JvmPlatforms.CompatJvmPlatform is JsPlatform -> JsPlatforms.CompatJsPlatform is NativePlatform -> NativePlatforms.CompatNativePlatform else -> error("Unknown platform $single") } fun OldPlatform.toNewPlatform(): NewPlatform = when (this) { is CommonPlatforms.CompatCommonPlatform -> this is JvmPlatforms.CompatJvmPlatform -> this is JsPlatforms.CompatJsPlatform -> this is NativePlatforms.CompatNativePlatform -> this else -> error( "Can't convert org.jetbrains.kotlin.resolve.TargetPlatform to org.jetbrains.kotlin.platform.TargetPlatform: " + "non-Compat instance passed\n" + "toString: $this\n" + "class: ${this::class}\n" + "hashCode: ${this.hashCode().toString(16)}" ) } fun IdePlatform<*, *>.toNewPlatform(): NewPlatform = when (this) { is CommonIdePlatformKind.Platform -> CommonPlatforms.defaultCommonPlatform is JvmIdePlatformKind.Platform -> JvmPlatforms.jvmPlatformByTargetVersion(this.version) is JsIdePlatformKind.Platform -> JsPlatforms.defaultJsPlatform is NativeIdePlatformKind.Platform -> NativePlatforms.unspecifiedNativePlatform else -> error("Unknown platform $this") } fun NewPlatform.toIdePlatform(): IdePlatform<*, *> = when (val single = singleOrNull()) { null -> CommonIdePlatformKind.Platform is JdkPlatform -> JvmIdePlatformKind.Platform(single.targetVersion) is JvmPlatform -> JvmIdePlatformKind.Platform(JvmTarget.DEFAULT) is JsPlatform -> JsIdePlatformKind.Platform is NativePlatform -> NativeIdePlatformKind.Platform else -> error("Unknown platform $single") }
apache-2.0
03a9e0addecdc743aec90ceea28c3e67
47.403226
158
0.777074
4.725984
false
false
false
false
jwren/intellij-community
plugins/evaluation-plugin/core/src/com/intellij/cce/actions/CodeGolfEmulation.kt
4
4451
package com.intellij.cce.actions import com.intellij.cce.core.* class CodeGolfEmulation(private val settings: Settings = Settings(), private val expectedLine: String) { fun pickBestSuggestion(currentLine: String, lookup: Lookup, session: Session): Lookup { val suggestions = lookup.suggestions.ofSource(settings.source).take(settings.topN).toMutableList() val normalizedExpectedLine = expectedLine.drop(currentLine.length) val line = checkForPerfectLine(normalizedExpectedLine, suggestions, lookup.prefix) val token = checkForFirstToken(normalizedExpectedLine, suggestions, lookup.prefix) val new = when { settings.checkLine && line != null -> { if (line.first.length > expectedLine.length / 2) { session.success = true } suggestions[line.second] = suggestions[line.second].withSuggestionKind(SuggestionKind.LINE) line } settings.checkToken && token != null -> { suggestions[token.second] = suggestions[token.second].withSuggestionKind(SuggestionKind.TOKEN) token } else -> Pair(expectedLine[currentLine.length].toString(), -1) } return Lookup(lookup.prefix, suggestions, lookup.latency, selectedPosition = new.second, isNew = lookup.isNew) } private fun checkForPerfectLine(expectedLine: String, suggestions: List<Suggestion>, prefix: String): Pair<String, Int>? { var res: Pair<String, Int>? = null suggestions.forEachIndexed { index, suggestion -> val normalizedSuggestion = suggestion.text.drop(prefix.length) findResult(normalizedSuggestion, expectedLine, index, res)?.let { res = it } } return res } private fun checkForFirstToken(expectedLine: String, suggestions: List<Suggestion>, prefix: String): Pair<String, Int>? { var res: Pair<String, Int>? = null val expectedToken = firstToken(expectedLine) if (expectedToken.isEmpty()) { return null } suggestions.forEachIndexed { index, suggestion -> val suggestionToken = firstToken(suggestion.text.drop(prefix.length)) findResult(suggestionToken, expectedToken, index, res)?.let { res = it } } return res } private fun findResult(suggestion: String, expected: String, index: Int, res: Pair<String, Int>?): Pair<String, Int>? { if (suggestion.isEmpty() || !expected.startsWith(suggestion)) { return null } val possibleResult = suggestion to index return if (res != null) { possibleResult.takeIf { res.first.length < suggestion.length } } else { possibleResult } } private fun firstToken(line: String): String { var firstToken = "" for (ch in line) { if (ch.isLetter() || ch == '_' || ch.isDigit() && firstToken.isNotBlank()) firstToken += ch else break } return firstToken } /** * @param checkLine Check if expected line starts with suggestion from completion * @param checkToken In case first token in suggestion equals to first token in expected string, we can pick only first token from suggestion. If completion suggest only one token - this option is useless (see checkLine ↑). Suitable for full line or multiple token completions * @param source Take suggestions, with specific source * - STANDARD - standard non-full line completion * - CODOTA - <a href="https://plugins.jetbrains.com/plugin/7638-codota">https://plugins.jetbrains.com/plugin/7638-codota</a> * - TAB_NINE - <a href="https://github.com/codota/tabnine-intellij">https://github.com/codota/tabnine-intellij</a> * - INTELLIJ - <a href="https://jetbrains.team/p/ccrm/code/fl-inference">https://jetbrains.team/p/ccrm/code/fl-inference</a> * @param topN Take only N top suggestions, applying after filtering by source */ data class Settings( val checkLine: Boolean = true, val checkToken: Boolean = true, val source: SuggestionSource? = null, var topN: Int = -1 ) companion object { fun createFromSettings(settings: Settings?, expectedLine: String): CodeGolfEmulation { return CodeGolfEmulation(settings ?: Settings(), expectedLine) } } } private fun List<Suggestion>.ofSource(source: SuggestionSource?): List<Suggestion> { return filter { source == null || it.source == source } } fun Lookup.selectedWithoutPrefix(): String? { if (selectedPosition == -1) { return null } return suggestions[selectedPosition].text.drop(prefix.length) }
apache-2.0
93ef77836f87028b1fa2c05e88485bf1
36.386555
144
0.696336
4.241182
false
false
false
false
vovagrechka/fucking-everything
phizdets/phizdetsc/src/org/jetbrains/kotlin/js/translate/expression/TryTranslator.kt
1
1982
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.js.translate.expression import org.jetbrains.kotlin.js.backend.ast.JsBlock import org.jetbrains.kotlin.js.backend.ast.JsTry import org.jetbrains.kotlin.psi.KtTryExpression import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.js.translate.context.TranslationContext import org.jetbrains.kotlin.js.translate.general.AbstractTranslator import org.jetbrains.kotlin.js.translate.general.Translation.translateAsStatementAndMergeInBlockIfNeeded import org.jetbrains.kotlin.js.translate.utils.JsAstUtils.convertToBlock class TryTranslator( val expression: KtTryExpression, context: TranslationContext ) : AbstractTranslator(context) { fun translate(): JsTry { val tryBlock = translateAsBlock(expression.tryBlock) val catchTranslator = CatchTranslator(expression.catchClauses, context()) val catchBlock = catchTranslator.translate() val finallyExpression = expression.finallyBlock?.finalExpression val finallyBlock = translateAsBlock(finallyExpression) return JsTry(tryBlock, catchBlock, finallyBlock) } private fun translateAsBlock(expression: KtExpression?): JsBlock? { if (expression == null) return null val statement = translateAsStatementAndMergeInBlockIfNeeded(expression, context()) return convertToBlock(statement) } }
apache-2.0
d42d65df0b167cf88fba5011bdba6dae
37.862745
104
0.767407
4.556322
false
false
false
false
vovagrechka/fucking-everything
pieces/pieces-100/src/main/java/pieces100/AlConst.kt
1
5186
package alraune import vgrechka.* object BTFConst { val bodyMarginTopForNavbar_px: Int = AlBTFConst0.bodyMarginTopForNavbar_px val variousTopBodyCrapDomid by myFqname_under() val variousBottomBodyCrapDomid by myFqname_under() val nProgressTop: Int = BTFConst.bodyMarginTopForNavbar_px object verticalFiller { val domid by myFqname_under() val minHeight_pieceOfCalc = "100vh - 28px - 1.5rem - ${bodyMarginTopForNavbar_px}px" } val beginBodyContentDivMarker = "<!--beginBodyContentDiv-->" val endBodyContentDivMarker = "<!--endBodyContentDiv-->" val beginInitialBackResponseMarker = "/*<!--beginInitialBackResponse*/" val endInitialBackResponseMarker = "/*endInitialBackResponse-->*/" val bodyContentDomid by myName() val tinyMceLoadedPromise by myName() val disposeCallbacksAttachedToNode by myName() val begin_pageSha1 = "begin_pageSha1_0cc617ddd0c04d819a59eab4b319b035__" val end_pageSha1 = "__end_pageSha1_7953f2e66dbe4e3982ec2001f7b80c75" val debug_thisWholeContent by myName() val softRefreshNeededNavbarItemDomid by myName() val hardRefreshNeededNavbarItemDomid by myName() val genericDebugFlag: Boolean = alConfig.debug.genericDebugFlag val genericLocalDebugFlag: Boolean = alConfig.debug.genericLocalDebugFlag val begin_ignoreWhenCheckingForStaleness_1 = if (alConfig.debug.genericLocalDebugFlag) (0x1001).toChar().toString() else "begin_ignoreWhenCheckingForStaleness_058d8b945ce848209f46a124b00f763d__" val end_ignoreWhenCheckingForStaleness_1 = if (alConfig.debug.genericLocalDebugFlag) (0x1002).toChar().toString() else "__end_ignoreWhenCheckingForStaleness_cb21d61d98684e5ebdd97f5c6f272e47" val begin_ignoreWhenCheckingForStaleness_2 = if (alConfig.debug.genericLocalDebugFlag) (0x1003).toChar().toString() else "begin_ignoreWhenCheckingForStaleness_34054aa9-46d4-489c-9bdd-a41c517f44ee__" val end_ignoreWhenCheckingForStaleness_2 = if (alConfig.debug.genericLocalDebugFlag) (0x1004).toChar().toString() else "__end_ignoreWhenCheckingForStaleness_346a226b-d871-4b98-abbf-0da4eb574c49" val header_IsStalenessCheck = "Is-Staleness-Check" object CSSClass { val paddingRightScrollbarWidthImportant by myName() } object Wasing { object ElementDataSet { val drawingNodeShit by prefixed() val drawingURLPath by prefixed() private fun prefixed() = named {"wasing${it.capitalize()}"} } object CSSClass { val textContainer by prefixed() val drawingContainer by prefixed() val bodyContextMenu by prefixed() val removeWhenSaving by prefixed() private fun prefixed() = named {"wasing-$it"} } } val whiteBackdropOpacity = "0.25" object Domid { val mainContainer = "x3c7f946c-85bb-417e-8676-7def97abc339" val shitBelowFooter by myName() } object ZIndex { val fixedTopBannerBelowNavbar: Int = 1030 val nProgress: Int = 1031 val navbar: Int = 1040 val pamela: Int = 1050 val midAirCollisionGlobalPageBanner: Int = 100_000 val serviceFuckedUpGlobalPageBanner: Int = 100_000 val workingCrazyWidget: Int = 200_000 val leftScreenDebugMenu: Int = 300_000 val debugHighlight: Int = 1_000_000 } } object AlConst { val pageSize = 10 val pollForUpdatesDelayMs = 5000 val maxSelectLimit = 500 val maxUploadFileSizeBytes = 10 * 1024 * 1024 val alCtlPath: String get() = wtf("Don't call me") // alCtlPath(FEProps.shitDir) val configArgPrefix = "--config=" val commandClassPrefix = "AlCtl_" val pageGetParamName = "page" val queryLoggingEnabled = false val maxXStreamedInstanceXmlLength = 50_000 val genericDetailsLikeMaxLen = 10_000 val minPhoneDigits = 6 val orderFileIdSequence = "order_file_id_seq" val optimisticVersionColumn = "optimisticVersion" val postgresAdvisoryLockIdSequence = "advisory_lock_id_seq" fun mainLogFile(configName: String): String = imf() // FEProps.shitDir + "/alraune-$configName.log" fun cpFirstDir(shitDir: String) = "$shitDir/cp-first" fun alCtlPath(shitDir: String) = "$shitDir/bin/al-ctl" object FTBKeys { val handleUuid = "uuid" val controlNameToValue = "controlNameToValue" val data = "data" } object FTBDataKeys { val impersonate = "impersonate" val debugTagID = "debugTagID" val dundukDebugTagID = "dundukDebugTagID" val codeToEvalWhenTickerOperationFailed = "codeToEvalWhenTickerOperationFailed" val writerSubscriptions = "writerSubscriptions" val preflight = "preflight" val file = "file" } object Cookie { val userSessionUUID = "userSessionUUID" } object domid { } } object KVKey { val requestDBName by myName() val timelineNameToShow by myName() val activeTimelinePointName by myName() val snapshotDBNameCollectionPrefix by named {it + ":"} val imposedTime by myName() }
apache-2.0
c8b5d77a4949bda413dba894fd35b1a5
31.822785
103
0.695719
4.061081
false
true
false
false
StephaneBg/ScoreIt
app/src/main/kotlin/com/sbgapps/scoreit/app/ui/saved/SavedGameActivity.kt
1
3664
/* * Copyright 2020 Stéphane Baiget * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sbgapps.scoreit.app.ui.saved import android.os.Bundle import androidx.recyclerview.widget.ItemTouchHelper import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.sbgapps.scoreit.app.R import com.sbgapps.scoreit.app.databinding.ActivitySavedGamesBinding import com.sbgapps.scoreit.app.databinding.DialogEditNameBinding import com.sbgapps.scoreit.core.ext.onImeActionDone import com.sbgapps.scoreit.core.ui.BaseActivity import com.sbgapps.scoreit.core.widget.DividerItemDecoration import com.sbgapps.scoreit.core.widget.GenericRecyclerViewAdapter import io.uniflow.androidx.flow.onStates import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf class SavedGameActivity : BaseActivity() { private lateinit var binding: ActivitySavedGamesBinding private val viewModel by viewModel<SavedGameViewModel> { parametersOf(getString(R.string.local_date_pattern)) } private val savedGamesAdapter = GenericRecyclerViewAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySavedGamesBinding.inflate(layoutInflater) setContentView(binding.root) setupActionBar(binding.toolbar) binding.recyclerView.apply { adapter = savedGamesAdapter ItemTouchHelper(SavedGameSwipeCallback(::onEdit, ::onDelete)).attachToRecyclerView(this) addItemDecoration(DividerItemDecoration(this@SavedGameActivity)) } onStates(viewModel) { state -> when (state) { is SavedAction.Content -> { val adapters = state.games.map { (name, players, date) -> SavedGameAdapter(name, players, date, ::onGameSelected) } savedGamesAdapter.updateItems(adapters) } is SavedAction.Complete -> finish() } } viewModel.getSavedFiles() } private fun onEdit(position: Int) { displayNameEditionDialog(position) } private fun onDelete(position: Int) { viewModel.deleteGame(position) } private fun onGameSelected(fileName: String) { viewModel.loadGame(fileName) } private fun displayNameEditionDialog(position: Int) { val action = { name: String -> if (name.isNotEmpty()) viewModel.editName(position, name) } val view = DialogEditNameBinding.inflate(layoutInflater) val dialog = MaterialAlertDialogBuilder(this) .setView(view.root) .setPositiveButton(R.string.button_action_ok) { _, _ -> action(view.name.text.toString()) } .setOnDismissListener { viewModel.getSavedFiles() } .create() view.name.apply { requestFocus() onImeActionDone { action(text.toString()) dialog.dismiss() } } dialog.show() } }
apache-2.0
89061ae29eafe26fa1341a5c9c254634
34.911765
115
0.674038
4.788235
false
false
false
false
androidx/androidx
wear/compose/compose-material/src/commonMain/kotlin/androidx/wear/compose/material/dialog/Dialog.kt
3
17613
/* * 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.wear.compose.material.dialog import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.width import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.wear.compose.material.Button import androidx.wear.compose.material.Chip import androidx.wear.compose.material.ToggleChip import androidx.wear.compose.material.contentColorFor import androidx.wear.compose.material.Icon import androidx.wear.compose.material.isRoundDevice import androidx.wear.compose.material.LocalContentColor import androidx.wear.compose.material.LocalTextStyle import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.PositionIndicator import androidx.wear.compose.material.Scaffold import androidx.wear.compose.material.ScalingLazyColumn import androidx.wear.compose.material.ScalingLazyListScope import androidx.wear.compose.material.ScalingLazyListState import androidx.wear.compose.material.rememberScalingLazyListState import kotlinx.coroutines.delay /** * [Alert] lays out the content for an opinionated, alert screen. * This overload offers 5 slots for title, negative button, positive button, optional icon and * optional content. The buttons are shown side-by-side below the icon, text and content. * [Alert] is scrollable by default if the content is taller than the viewport. * * [Alert] can be used as a destination in a navigation graph * e.g. using SwipeDismissableNavHost. However, for a conventional fullscreen dialog, * displayed on top of other content, use [Dialog]. * * Example of an [Alert] with an icon, title, body text and buttons: * @sample androidx.wear.compose.material.samples.AlertWithButtons * * @param title A slot for displaying the title of the dialog, * expected to be one or two lines of text. * @param negativeButton A slot for a [Button] indicating negative sentiment (e.g. No). * Clicking the button must remove the dialog from the composition hierarchy. * @param positiveButton A slot for a [Button] indicating positive sentiment (e.g. Yes). * Clicking the button must remove the dialog from the composition hierarchy. * @param modifier Modifier to be applied to the dialog content. * @param icon Optional slot for an icon to be shown at the top of the dialog. * @param scrollState The scroll state for the dialog so that the scroll position can be displayed * e.g. by the [PositionIndicator] passed to [Scaffold]. * @param backgroundColor [Color] representing the background color for the dialog. * @param contentColor [Color] representing the color for [content]. * @param titleColor [Color] representing the color for [title]. * @param iconColor Icon [Color] that defaults to [contentColor], * unless specifically overridden. * @param verticalArrangement The vertical arrangement of the dialog's children. This allows us * to add spacing between items and specify the arrangement of the items when we have not enough * of them to fill the whole minimum size. * @param contentPadding The padding to apply around the whole of the dialog's contents. * @param content A slot for additional content, expected to be 2-3 lines of text. */ @Composable public fun Alert( title: @Composable ColumnScope.() -> Unit, negativeButton: @Composable () -> Unit, positiveButton: @Composable () -> Unit, modifier: Modifier = Modifier, icon: @Composable (ColumnScope.() -> Unit)? = null, scrollState: ScalingLazyListState = rememberScalingLazyListState(), backgroundColor: Color = MaterialTheme.colors.background, contentColor: Color = contentColorFor(backgroundColor), titleColor: Color = contentColor, iconColor: Color = contentColor, verticalArrangement: Arrangement.Vertical = DialogDefaults.AlertVerticalArrangement, contentPadding: PaddingValues = DialogDefaults.ContentPadding, content: @Composable (ColumnScope.() -> Unit)? = null ) { DialogImpl( modifier = modifier, scrollState = scrollState, verticalArrangement = verticalArrangement, contentPadding = contentPadding, backgroundColor = backgroundColor, ) { if (icon != null) { item { DialogIconHeader(iconColor, content = icon) } } item { DialogTitle(titleColor, padding = DialogDefaults.TitlePadding, title) } if (content != null) { item { DialogBody(contentColor, content) } } // Buttons item { Row( verticalAlignment = Alignment.CenterVertically, ) { negativeButton() Spacer(modifier = Modifier.width(DialogDefaults.ButtonSpacing)) positiveButton() } } } } /** * [Alert] lays out the content for an opinionated, alert screen. * This overload offers 4 slots for title, optional icon, optional message text and * a content slot expected to be one or more vertically stacked [Chip]s or [ToggleChip]s. * [Alert] is scrollable by default if the content is taller than the viewport. * * [Alert] can be used as a destination in a navigation graph * e.g. using SwipeDismissableNavHost. However, for a conventional fullscreen dialog, * displayed on top of other content, use [Dialog]. * * Example of an [Alert] with an icon, title, message text and chips: * @sample androidx.wear.compose.material.samples.AlertWithChips * * @param title A slot for displaying the title of the dialog, * expected to be one or two lines of text. * @param modifier Modifier to be applied to the dialog. * @param icon Optional slot for an icon to be shown at the top of the dialog. * @param message Optional slot for additional message content, expected to be 2-3 lines of text. * @param scrollState The scroll state for the dialog so that the scroll position can be displayed * e.g. by the [PositionIndicator] passed to [Scaffold]. * @param backgroundColor [Color] representing the background color for the dialog. * @param titleColor [Color] representing the color for [title]. * @param messageColor [Color] representing the color for [message]. * @param iconColor [Color] representing the color for [icon]. * @param verticalArrangement The vertical arrangement of the dialog's children. This allows us * to add spacing between items and specify the arrangement of the items when we have not enough * of them to fill the whole minimum size. * @param contentPadding The padding to apply around the whole of the dialog's contents. * @param content A slot for one or more spaced [Chip]s, stacked vertically. */ @Composable public fun Alert( title: @Composable ColumnScope.() -> Unit, modifier: Modifier = Modifier, icon: @Composable (ColumnScope.() -> Unit)? = null, message: @Composable (ColumnScope.() -> Unit)? = null, scrollState: ScalingLazyListState = rememberScalingLazyListState(), backgroundColor: Color = MaterialTheme.colors.background, titleColor: Color = contentColorFor(backgroundColor), messageColor: Color = contentColorFor(backgroundColor), iconColor: Color = contentColorFor(backgroundColor), verticalArrangement: Arrangement.Vertical = DialogDefaults.AlertVerticalArrangement, contentPadding: PaddingValues = DialogDefaults.ContentPadding, content: ScalingLazyListScope.() -> Unit ) { DialogImpl( modifier = modifier, scrollState = scrollState, verticalArrangement = verticalArrangement, contentPadding = contentPadding, backgroundColor = backgroundColor, ) { if (icon != null) { item { DialogIconHeader(iconColor, content = icon) } } item { DialogTitle(titleColor, padding = DialogDefaults.TitlePadding, content = title) } if (message != null) { item { DialogBody(messageColor, message) } } content() } } /** * [Confirmation] lays out the content for an opinionated confirmation screen that * displays a message to the user for [durationMillis]. It has a slot for an icon or image * (which could be animated). * * [Confirmation] can be used as a destination in a navigation graph * e.g. using SwipeDismissableNavHost. However, for a conventional fullscreen dialog, * displayed on top of other content, use [Dialog]. * * Example of a [Confirmation] with animation: * @sample androidx.wear.compose.material.samples.ConfirmationWithAnimation * * @param onTimeout Event invoked when the dialog has been shown for [durationMillis]. * @param modifier Modifier to be applied to the dialog. * @param icon An optional slot for displaying an icon or image. * @param scrollState The scroll state for the dialog so that the scroll position can be displayed * e.g. by the [PositionIndicator] passed to [Scaffold]. * @param durationMillis The number of milliseconds for which the dialog is displayed, * must be positive. Suggested values are [DialogDefaults.ShortDurationMillis], * [DialogDefaults.LongDurationMillis] or [DialogDefaults.IndefiniteDurationMillis]. * @param backgroundColor [Color] representing the background color for this dialog. * @param contentColor [Color] representing the color for [content]. * @param iconColor Icon [Color] that defaults to the [contentColor], * unless specifically overridden. * @param verticalArrangement The vertical arrangement of the dialog's children. This allows us * to add spacing between items and specify the arrangement of the items when we have not enough * of them to fill the whole minimum size. * @param contentPadding The padding to apply around the whole of the dialog's contents. * @param content A slot for the dialog title, expected to be one line of text. */ @Composable public fun Confirmation( onTimeout: () -> Unit, modifier: Modifier = Modifier, icon: @Composable (ColumnScope.() -> Unit)? = null, scrollState: ScalingLazyListState = rememberScalingLazyListState(), durationMillis: Long = DialogDefaults.ShortDurationMillis, backgroundColor: Color = MaterialTheme.colors.background, contentColor: Color = contentColorFor(backgroundColor), iconColor: Color = contentColor, verticalArrangement: Arrangement.Vertical = DialogDefaults.ConfirmationVerticalArrangement, contentPadding: PaddingValues = DialogDefaults.ContentPadding, content: @Composable ColumnScope.() -> Unit ) { require(durationMillis > 0) { "Duration must be a positive integer" } // Always refer to the latest inputs with which ConfirmationDialog was recomposed. val currentOnTimeout by rememberUpdatedState(onTimeout) LaunchedEffect(durationMillis) { delay(durationMillis) currentOnTimeout() } DialogImpl( modifier = modifier, scrollState = scrollState, verticalArrangement = verticalArrangement, contentPadding = contentPadding, backgroundColor = backgroundColor, ) { if (icon != null) { item { DialogIconHeader(iconColor, content = icon) } } item { DialogTitle( titleColor = contentColor, padding = DialogDefaults.TitleBottomPadding, content = content ) } } } /** * Contains the default values used by [Alert] and [Confirmation]. */ public object DialogDefaults { /** * Creates the recommended vertical arrangement for [Alert] dialog content. */ public val AlertVerticalArrangement = Arrangement.spacedBy(4.dp, Alignment.CenterVertically) /** * Creates the recommended vertical arrangement for [Confirmation] dialog content. */ public val ConfirmationVerticalArrangement = Arrangement.spacedBy(space = 8.dp, alignment = Alignment.CenterVertically) /** * The padding to apply around the contents. */ public val ContentPadding = PaddingValues(horizontal = 10.dp) /** * Short duration for showing [Confirmation]. */ public val ShortDurationMillis = 4000L /** * Long duration for showing [Confirmation]. */ public val LongDurationMillis = 10000L /** * Show [Confirmation] indefinitely (supports swipe-to-dismiss). */ public val IndefiniteDurationMillis = Long.MAX_VALUE /** * Spacing between [Button]s. */ internal val ButtonSpacing = 12.dp /** * Spacing below [Icon]. */ internal val IconSpacing = 4.dp /** * Padding around body content. */ internal val BodyPadding @Composable get() = if (isRoundDevice()) PaddingValues(start = 8.dp, end = 8.dp, top = 0.dp, bottom = 12.dp) else PaddingValues(start = 5.dp, end = 5.dp, top = 0.dp, bottom = 12.dp) /** * Padding around title text. */ internal val TitlePadding @Composable get() = if (isRoundDevice()) PaddingValues( start = 14.dp, end = 14.dp, top = 0.dp, bottom = 8.dp ) else PaddingValues(start = 5.dp, end = 5.dp, top = 0.dp, bottom = 8.dp) /** * Bottom padding for title text. */ internal val TitleBottomPadding @Composable get() = PaddingValues(start = 0.dp, end = 0.dp, top = 0.dp, bottom = 16.dp) } /** * Common Wear Material dialog implementation that offers a single content slot, * fills the screen and is scrollable by default if the content is taller than the viewport. */ @Composable private fun DialogImpl( modifier: Modifier = Modifier, scrollState: ScalingLazyListState, verticalArrangement: Arrangement.Vertical, backgroundColor: Color, contentPadding: PaddingValues, content: ScalingLazyListScope.() -> Unit ) { ScalingLazyColumn( state = scrollState, autoCentering = null, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = verticalArrangement, contentPadding = contentPadding, modifier = modifier .fillMaxSize() .background(backgroundColor), content = content ) } /** * [DialogIconHeader] displays an icon at the top of the dialog * followed by the recommended spacing. * * @param iconColor [Color] in which to tint the icon. * @param content Slot for an icon. */ @Composable private fun DialogIconHeader( iconColor: Color, content: @Composable ColumnScope.() -> Unit ) { CompositionLocalProvider(LocalContentColor provides iconColor) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { content() Spacer(Modifier.fillMaxWidth().height(DialogDefaults.IconSpacing)) } } } /** * [DialogTitle] displays the title content in a dialog with the recommended padding. * * @param titleColor [Color] in which the title is displayed. * @param padding The padding around the title content. */ @Composable private fun DialogTitle( titleColor: Color, padding: PaddingValues, content: @Composable ColumnScope.() -> Unit ) { CompositionLocalProvider( LocalContentColor provides titleColor, LocalTextStyle provides MaterialTheme.typography.title3 ) { Column( modifier = Modifier.padding(padding), content = content, ) } } /** * [DialogBody] displays the body content in a dialog with recommended padding. */ @Composable private fun DialogBody( bodyColor: Color, content: @Composable ColumnScope.() -> Unit ) { CompositionLocalProvider( LocalContentColor provides bodyColor, LocalTextStyle provides MaterialTheme.typography.body2 ) { Column( modifier = Modifier.padding(DialogDefaults.BodyPadding), content = content ) } }
apache-2.0
a28edbf02c07f2dc96af0ced982e60c6
37.372549
98
0.703117
4.881652
false
false
false
false
androidx/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/ComposeLineHeight.kt
3
15601
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.text import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.foundation.verticalScroll import androidx.compose.material.Checkbox import androidx.compose.material.RadioButton import androidx.compose.material.Slider import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.text.style.LineHeightStyle.Trim import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp import kotlin.math.round private val HintStyle = TextStyle(fontSize = 14.sp) private fun Float.format(digits: Int = 2) = "%.${digits}f".format(this) private val FontSize = 60.sp @Preview @Composable fun TextLineHeightDemo() { Column( Modifier.verticalScroll(rememberScrollState()) .background(TextMetricColors.Default.background) ) { var lineHeightSp = remember { mutableStateOf(60f) } var lineHeightEm = remember { mutableStateOf(1f) } var lineHeightEnabled = remember { mutableStateOf(false) } val lineHeightStyleEnabled = remember { mutableStateOf(false) } var lineHeightAlignment = remember { mutableStateOf(LineHeightStyle.Default.alignment) } var lineHeightTrim = remember { mutableStateOf(LineHeightStyle.Default.trim) } val includeFontPadding = remember { mutableStateOf(false) } val applyMaxLines = remember { mutableStateOf(false) } val ellipsize = remember { mutableStateOf(false) } val useSizedSpan = remember { mutableStateOf(false) } val singleLine = remember { mutableStateOf(false) } val useTallScript = remember { mutableStateOf(false) } Column(Modifier.padding(16.dp)) { LineHeightConfiguration(lineHeightSp, lineHeightEm, lineHeightEnabled) StringConfiguration(useSizedSpan, singleLine, useTallScript) FontPaddingAndMaxLinesConfiguration(includeFontPadding, applyMaxLines, ellipsize) LineHeightStyleConfiguration( lineHeightStyleEnabled, lineHeightTrim, lineHeightAlignment ) Spacer(Modifier.padding(16.dp)) TextWithLineHeight( lineHeightEnabled.value, lineHeightSp.value, lineHeightEm.value, if (lineHeightStyleEnabled.value) { LineHeightStyle( alignment = lineHeightAlignment.value, trim = lineHeightTrim.value ) } else null, includeFontPadding.value, applyMaxLines.value, ellipsize.value, useSizedSpan.value, singleLine.value, useTallScript.value ) } } } @Composable private fun LineHeightConfiguration( lineHeightSp: MutableState<Float>, lineHeightEm: MutableState<Float>, lineHeightEnabled: MutableState<Boolean> ) { Column { val density = LocalDensity.current val lineHeightInPx = with(density) { lineHeightSp.value.sp.toPx() } Text( "Line height: ${lineHeightSp.value.format()}.sp [$lineHeightInPx px, $density]", style = HintStyle ) Row { Checkbox( checked = lineHeightEnabled.value, onCheckedChange = { lineHeightEnabled.value = it } ) SnappingSlider( value = lineHeightSp.value, onValueChange = { lineHeightSp.value = it lineHeightEm.value = 0f lineHeightEnabled.value = true }, steps = 11, valueRange = 0f..120f ) } val fontSizeInPx = with(density) { FontSize.toPx() } val lineHeightEmInPx = lineHeightEm.value * fontSizeInPx Text( "Line height: ${lineHeightEm.value.format()}.em [$lineHeightEmInPx px]", style = HintStyle ) Row { Checkbox( checked = lineHeightEnabled.value, onCheckedChange = { lineHeightEnabled.value = it } ) SnappingSlider( value = lineHeightEm.value, onValueChange = { lineHeightEm.value = it lineHeightSp.value = 0f lineHeightEnabled.value = true }, steps = 5, valueRange = 0f..3f ) } } } @Composable private fun LineHeightStyleConfiguration( lineHeightStyleEnabled: MutableState<Boolean>, lineHeightTrim: MutableState<Trim>, lineHeightAlignment: MutableState<LineHeightStyle.Alignment> ) { Column(Modifier.horizontalScroll(rememberScrollState())) { Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = lineHeightStyleEnabled.value, onCheckedChange = { lineHeightStyleEnabled.value = it } ) Text("LineHeightStyle", style = HintStyle) } Column(Modifier.padding(horizontal = 16.dp)) { LineHeightTrimOptions(lineHeightTrim, lineHeightStyleEnabled.value) LineHeightAlignmentOptions(lineHeightAlignment, lineHeightStyleEnabled.value) } } } @Composable private fun LineHeightAlignmentOptions( lineHeightAlignment: MutableState<LineHeightStyle.Alignment>, enabled: Boolean ) { val options = listOf( LineHeightStyle.Alignment.Proportional, LineHeightStyle.Alignment.Top, LineHeightStyle.Alignment.Center, LineHeightStyle.Alignment.Bottom ) Row( modifier = Modifier.selectableGroup(), verticalAlignment = Alignment.CenterVertically ) { Text(text = "alignment:", style = HintStyle) options.forEach { option -> Row( Modifier .height(56.dp) .selectable( selected = (option == lineHeightAlignment.value), onClick = { lineHeightAlignment.value = option }, role = Role.RadioButton, enabled = enabled ), verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = (option == lineHeightAlignment.value), onClick = null, enabled = enabled ) Text(text = option.toString().split(".").last(), style = HintStyle) } } } } @Composable private fun LineHeightTrimOptions( lineHeightTrim: MutableState<Trim>, enabled: Boolean ) { val options = listOf( Trim.Both, Trim.None, Trim.FirstLineTop, Trim.LastLineBottom ) Row( modifier = Modifier.selectableGroup(), verticalAlignment = Alignment.CenterVertically ) { Text(text = "trim:", style = HintStyle) options.forEach { option -> Row( Modifier .height(56.dp) .selectable( selected = (option == lineHeightTrim.value), onClick = { lineHeightTrim.value = option }, role = Role.RadioButton, enabled = enabled ), verticalAlignment = Alignment.CenterVertically ) { RadioButton( selected = (option == lineHeightTrim.value), onClick = null, enabled = enabled ) Text(text = option.toString().split(".").last(), style = HintStyle) } } } } @Composable private fun StringConfiguration( useSizeSpan: MutableState<Boolean>, singleLine: MutableState<Boolean>, useTallScript: MutableState<Boolean> ) { Column(Modifier.horizontalScroll(rememberScrollState())) { Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = useSizeSpan.value, onCheckedChange = { useSizeSpan.value = it } ) Text("Size Span", style = HintStyle) Checkbox( checked = singleLine.value, onCheckedChange = { singleLine.value = it } ) Text("Single Line", style = HintStyle) Checkbox( checked = useTallScript.value, onCheckedChange = { useTallScript.value = it } ) Text("Tall script", style = HintStyle) } } } @Composable private fun FontPaddingAndMaxLinesConfiguration( includeFontPadding: MutableState<Boolean>, applyMaxLines: MutableState<Boolean>, ellipsize: MutableState<Boolean>, ) { Column(Modifier.horizontalScroll(rememberScrollState())) { Row(verticalAlignment = Alignment.CenterVertically) { Checkbox( checked = includeFontPadding.value, onCheckedChange = { includeFontPadding.value = it } ) Text("IncludeFontPadding", style = HintStyle) Checkbox( checked = applyMaxLines.value, onCheckedChange = { applyMaxLines.value = it } ) Text("maxLines", style = HintStyle) Checkbox( checked = ellipsize.value, onCheckedChange = { ellipsize.value = it } ) Text("ellipsize", style = HintStyle) } } } @Composable private fun SnappingSlider( value: Float, onValueChange: (Float) -> Unit, modifier: Modifier = Modifier, valueRange: ClosedFloatingPointRange<Float> = 0f..1f, steps: Int = 0, snap: Boolean = true, enabled: Boolean = true ) { var lastValue by remember(value) { mutableStateOf(value) } val increment = valueRange.endInclusive / (steps + 1).toFloat() val snapValue = round(value / increment / 2f) * increment Slider( modifier = modifier, value = lastValue, onValueChangeFinished = { if (snap) { if (lastValue != snapValue) { lastValue = snapValue } } }, onValueChange = onValueChange, valueRange = valueRange, steps = steps, enabled = enabled ) } @Suppress("DEPRECATION") @Composable private fun TextWithLineHeight( lineHeightEnabled: Boolean, lineHeightSp: Float, lineHeightEm: Float, lineHeightStyle: LineHeightStyle?, includeFontPadding: Boolean, applyMaxLines: Boolean, ellipsize: Boolean, useSizeSpan: Boolean, singleLine: Boolean, useTallScript: Boolean ) { val width = with(LocalDensity.current) { (FontSize.toPx() * 5).toDp() } var string = if (singleLine) { if (useTallScript) "ဪไ၇ဤန်" else "Abyfhpq" } else { if (useTallScript) "ဪไ၇ဤနဩဦဤနိမြသကိမ့်ဪไန််" else "ABCDEfgHIjKgpvylzgpvykwi" } if (applyMaxLines) { string = string.repeat(4) } var text = AnnotatedString(string) if (useSizeSpan) { text = if (singleLine) { buildAnnotatedString { append(text) addStyle(style = SpanStyle(fontSize = FontSize * 1.5), start = 1, end = 2) addStyle(style = SpanStyle(fontSize = FontSize * 1.5), start = 3, end = 4) } } else { buildAnnotatedString { append(text) addStyle(style = SpanStyle(fontSize = FontSize * 1.5), start = 1, end = 2) addStyle(style = SpanStyle(fontSize = FontSize * 1.5), start = 10, end = 12) addStyle(style = SpanStyle(fontSize = FontSize * 1.5), start = 18, end = 19) } } } val maxLines = if (applyMaxLines) 3 else Int.MAX_VALUE val style = TextStyle( fontSize = FontSize, color = TextMetricColors.Default.text, lineHeightStyle = lineHeightStyle, lineHeight = if (lineHeightEnabled) { if (lineHeightSp > 0) lineHeightSp.sp else lineHeightEm.em } else { TextUnit.Unspecified }, platformStyle = PlatformTextStyle(includeFontPadding = includeFontPadding) ) val overflow = if (ellipsize) TextOverflow.Ellipsis else TextOverflow.Clip Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) { Column(Modifier.width(width)) { TextWithMetrics( text = text, style = style, maxLines = maxLines, overflow = overflow, softWrap = !singleLine ) } Spacer(Modifier.padding(16.dp)) Column(Modifier.width(width)) { var textFieldValue by remember(text) { mutableStateOf(TextFieldValue(text)) } TextFieldWithMetrics( value = textFieldValue, onValueChange = { textFieldValue = it }, style = style, maxLines = maxLines, softWrap = !singleLine ) } Spacer(Modifier.padding(16.dp)) } }
apache-2.0
97038d3055e25fa3d720a5f3b4f081ef
33.849776
100
0.607412
5.205291
false
false
false
false
pokk/SSFM
app/src/main/kotlin/taiwan/no1/app/ssfm/features/base/BaseActivity.kt
1
4078
package taiwan.no1.app.ssfm.features.base import android.os.Bundle import android.support.annotation.CallSuper import android.support.v4.app.Fragment import android.view.ViewGroup import com.hwangjr.rxbus.RxBus import com.hwangjr.rxbus.annotation.Subscribe import com.hwangjr.rxbus.annotation.Tag import com.trello.rxlifecycle2.components.RxActivity import com.yalantis.guillotine.animation.GuillotineAnimation import com.yalantis.guillotine.interfaces.GuillotineListener import dagger.android.AndroidInjection import dagger.android.AndroidInjector import dagger.android.DispatchingAndroidInjector import dagger.android.HasFragmentInjector import dagger.android.support.HasSupportFragmentInjector import kotlinx.android.synthetic.main.part_toolbar_menu.tb_toolbar import kotlinx.android.synthetic.main.part_toolbar_menu.view.iv_content_hamburger import kotlinx.android.synthetic.main.part_toolbar_view.iv_content_hamburger import taiwan.no1.app.ssfm.R import javax.inject.Inject /** * Base activity for collecting all common methods here. * * @author jieyi * @since 5/9/17 */ abstract class BaseActivity : RxActivity(), HasFragmentInjector, HasSupportFragmentInjector { // Copy from [DaggerAppCompatActivity], becz this cant inherit two classes. /** For providing to support searchFragments. */ @Inject lateinit var supportFragmentInjector: DispatchingAndroidInjector<Fragment> /** For providing to searchFragments. */ @Inject lateinit var fragmentInjector: DispatchingAndroidInjector<android.app.Fragment> val menu by lazy { layoutInflater.inflate(R.layout.page_menu_preference, null) } protected val navigator by lazy { Navigator(this) } /** For keeping the menu is opening or closing. */ private var isMenuClosed = true private val guillotine by lazy { GuillotineAnimation.GuillotineBuilder(menu, menu.iv_content_hamburger, iv_content_hamburger) .setStartDelay(250) .setActionBarViewForAnimation(tb_toolbar) .setClosedOnStart(true) .setGuillotineListener(object : GuillotineListener { override fun onGuillotineClosed() { isMenuClosed = true } override fun onGuillotineOpened() { isMenuClosed = false } }) .build() } // FIXED(jieyi): 9/23/17 Register it in the parent class that it will be not reflected. protected var busEvent = object { @Subscribe(tags = [Tag("testTag")]) fun receive(str: String) { } } private val rootView by lazy { findViewById<ViewGroup>(R.id.root) } //region Activity lifecycle @CallSuper override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) RxBus.get().register(busEvent) } @CallSuper override fun onResume() { super.onResume() // HACK(jieyi): 9/17/17 (jieyi): Navigator shouldn't be active by call a variable. navigator.activity attachMenuView() } @CallSuper override fun onDestroy() { RxBus.get().unregister(busEvent) super.onDestroy() } //endregion /** * Providing the fragment injector([Fragment]) for the searchFragments. * * @return a [supportFragmentInjector] for children of this fragment. */ override fun supportFragmentInjector(): AndroidInjector<Fragment> = supportFragmentInjector /** * Providing the fragment injector([android.app.Fragment]) for the searchFragments. * * @return a [fragmentInjector] for children of this fragment. */ override fun fragmentInjector(): AndroidInjector<android.app.Fragment> = fragmentInjector override fun onBackPressed() { if (!isMenuClosed) { guillotine.close() return } super.onBackPressed() } protected fun attachMenuView() { rootView?.also { it.addView(menu) guillotine } } }
apache-2.0
4c54aed693e542d793fa504152e936b4
34.469565
100
0.693968
4.730858
false
false
false
false
GunoH/intellij-community
platform/testFramework/src/com/intellij/util/io/impl/DirectoryContentSpecImpl.kt
4
11679
// 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.util.io.impl import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.rt.execution.junit.FileComparisonFailure import com.intellij.util.io.* import org.junit.Assert.assertEquals import org.junit.ComparisonFailure import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.zip.Deflater import kotlin.io.path.extension import kotlin.io.path.name sealed class DirectoryContentSpecImpl : DirectoryContentSpec { /** * Path to the original file from which this spec was built. Will be used in 'Comparison Failure' dialog to apply changes to that file. */ abstract val originalFile: Path? abstract override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl } sealed class DirectorySpecBase(override val originalFile: Path?) : DirectoryContentSpecImpl() { protected val children: LinkedHashMap<String, DirectoryContentSpecImpl> = LinkedHashMap() fun addChild(name: String, spec: DirectoryContentSpecImpl) { if (name in children) { val existing = children[name] if (spec is DirectorySpecBase && existing is DirectorySpecBase) { existing.children += spec.children return } throw IllegalArgumentException("'$name' already exists") } children[name] = spec } protected fun generateInDirectory(target: File) { for ((name, child) in children) { child.generate(File(target, name)) } } override fun generateInTempDir(): Path { val target = FileUtil.createTempDirectory("directory-by-spec", null, true) generate(target) return target.toPath() } fun getChildren() : Map<String, DirectoryContentSpecImpl> = Collections.unmodifiableMap(children) override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl { require(other.javaClass == javaClass) other as DirectorySpecBase val result = when (other) { is DirectorySpec -> DirectorySpec() is ZipSpec -> ZipSpec() } result.children.putAll(children) for ((name, child) in other.children) { val oldChild = children[name] result.children[name] = oldChild?.mergeWith(child) ?: child } return result } } class DirectorySpec(originalFile: Path? = null) : DirectorySpecBase(originalFile) { override fun generate(target: File) { if (!FileUtil.createDirectory(target)) { throw IOException("Cannot create directory $target") } generateInDirectory(target) } } class ZipSpec(val level: Int = Deflater.DEFAULT_COMPRESSION) : DirectorySpecBase(null) { override fun generate(target: File) { val contentDir = FileUtil.createTempDirectory("zip-content", null, false) try { generateInDirectory(contentDir) FileUtil.createParentDirs(target) Compressor.Zip(target).withLevel(level).use { it.addDirectory(contentDir) } } finally { FileUtil.delete(contentDir) } } override fun generateInTempDir(): Path { val target = FileUtil.createTempFile("zip-by-spec", ".zip", true) generate(target) return target.toPath() } } class FileSpec(val content: ByteArray?, override val originalFile: Path? = null) : DirectoryContentSpecImpl() { override fun generate(target: File) { FileUtil.writeToFile(target, content ?: ByteArray(0)) } override fun generateInTempDir(): Path { val target = FileUtil.createTempFile("file-by-spec", null, true) generate(target) return target.toPath() } override fun mergeWith(other: DirectoryContentSpec): DirectoryContentSpecImpl { return other as DirectoryContentSpecImpl } } class DirectoryContentBuilderImpl(val result: DirectorySpecBase) : DirectoryContentBuilder() { override fun addChild(name: String, spec: DirectoryContentSpecImpl) { result.addChild(name, spec) } override fun file(name: String) { addChild(name, FileSpec(null)) } override fun file(name: String, text: String) { file(name, text.toByteArray()) } override fun file(name: String, content: ByteArray) { addChild(name, FileSpec(content)) } } private fun DirectorySpecBase.toString(filePathFilter: (String) -> Boolean): String = ArrayList<String>().also { appendToString(this, it, 0, ".", filePathFilter) }.joinToString("\n") private fun appendToString(spec: DirectorySpecBase, result: MutableList<String>, indent: Int, relativePath: String, filePathFilter: (String) -> Boolean) { spec.getChildren().entries .filter { it.value !is FileSpec || filePathFilter("$relativePath/${it.key}") } .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.key }) .forEach { result.add("${" ".repeat(indent)}${it.key}") val child = it.value if (child is DirectorySpec) { appendToString(child, result, indent + 2, "$relativePath/${it.key}", filePathFilter) } } } internal fun assertContentUnderFileMatches(file: Path, spec: DirectoryContentSpecImpl, fileTextMatcher: FileTextMatcher, filePathFilter: (String) -> Boolean, customErrorReporter: ContentMismatchReporter?, expectedDataIsInSpec: Boolean) { if (spec is DirectorySpecBase) { val actualSpec = createSpecByPath(file, file) if (actualSpec is DirectorySpecBase) { val specString = spec.toString(filePathFilter) val dirString = actualSpec.toString(filePathFilter) val (expected, actual) = if (expectedDataIsInSpec) specString to dirString else dirString to specString assertEquals(expected, actual) } } val errorReporter = customErrorReporter ?: ContentMismatchReporter { _, error -> throw error } assertDirectoryContentMatches(file, spec, ".", fileTextMatcher, filePathFilter, errorReporter, expectedDataIsInSpec) } private fun ContentMismatchReporter.assertTrue(relativePath: String, errorMessage: String, condition: Boolean) { if (!condition) { reportError(relativePath, AssertionError(errorMessage)) } } private fun assertDirectoryContentMatches(file: Path, spec: DirectoryContentSpecImpl, relativePath: String, fileTextMatcher: FileTextMatcher, filePathFilter: (String) -> Boolean, errorReporter: ContentMismatchReporter, expectedDataIsInSpec: Boolean) { errorReporter.assertTrue(relativePath, "$file doesn't exist", file.exists()) when (spec) { is DirectorySpec -> { assertDirectoryMatches(file, spec, relativePath, fileTextMatcher, filePathFilter, errorReporter, expectedDataIsInSpec) } is ZipSpec -> { errorReporter.assertTrue(relativePath, "$file is not a file", file.isFile()) val dirForExtracted = FileUtil.createTempDirectory("extracted-${file.name}", null, false).toPath() ZipUtil.extract(file, dirForExtracted, null) assertDirectoryMatches(dirForExtracted, spec, relativePath, fileTextMatcher, filePathFilter, errorReporter, expectedDataIsInSpec) FileUtil.delete(dirForExtracted) } is FileSpec -> { errorReporter.assertTrue(relativePath, "$file is not a file", file.isFile()) if (spec.content != null) { val fileBytes = file.readBytes() if (!Arrays.equals(fileBytes, spec.content)) { val fileString = fileBytes.convertToText() val specString = spec.content.convertToText() val place = if (relativePath != ".") " at $relativePath" else "" if (fileString != null && specString != null) { if (!fileTextMatcher.matches(fileString, specString)) { val specFilePath = spec.originalFile?.toFile()?.absolutePath val (expected, actual) = if (expectedDataIsInSpec) specString to fileString else fileString to specString val (expectedPath, actualPath) = if (expectedDataIsInSpec) specFilePath to null else null to specFilePath errorReporter.reportError(relativePath, FileComparisonFailure("File content mismatch$place:", expected, actual, expectedPath, actualPath)) } } else { errorReporter.reportError(relativePath, AssertionError("Binary file content mismatch$place")) } } } } } } private fun ByteArray.convertToText(): String? { if (isEmpty()) return "" val charset = when (CharsetToolkit(this, Charsets.UTF_8, false).guessFromContent(size)) { CharsetToolkit.GuessedEncoding.SEVEN_BIT -> Charsets.US_ASCII CharsetToolkit.GuessedEncoding.VALID_UTF8 -> Charsets.UTF_8 else -> return null } return String(this, charset) } private fun assertDirectoryMatches(file: Path, spec: DirectorySpecBase, relativePath: String, fileTextMatcher: FileTextMatcher, filePathFilter: (String) -> Boolean, errorReporter: ContentMismatchReporter, expectedDataIsInSpec: Boolean) { errorReporter.assertTrue(relativePath, "$file is not a directory", file.isDirectory()) fun childNameFilter(name: String) = filePathFilter("$relativePath/$name") val childrenNamesInDir = file.directoryStreamIfExists { children -> children.filter { it.isDirectory() || childNameFilter(it.name) } .map { it.name }.sortedWith(String.CASE_INSENSITIVE_ORDER) } ?: emptyList() val children = spec.getChildren() val childrenNamesInSpec = children.entries.filter { it.value is DirectorySpec || childNameFilter(it.key) } .map { it.key }.sortedWith(String.CASE_INSENSITIVE_ORDER) val specString = childrenNamesInSpec.joinToString("\n") val dirString = childrenNamesInDir.joinToString("\n") if (specString != dirString) { val (expected, actual) = if (expectedDataIsInSpec) specString to dirString else dirString to specString errorReporter.reportError(relativePath, ComparisonFailure("Directory content mismatch${if (relativePath != "") " at $relativePath" else ""}:", expected, actual)) } for (child in childrenNamesInDir) { assertDirectoryContentMatches(file.resolve(child), children.getValue(child), "$relativePath/$child", fileTextMatcher, filePathFilter, errorReporter, expectedDataIsInSpec) } } internal fun fillSpecFromDirectory(spec: DirectorySpecBase, dir: Path, originalDir: Path?) { dir.directoryStreamIfExists { children -> children.forEach { spec.addChild(it.fileName.toString(), createSpecByPath(it, originalDir?.resolve(it.fileName))) } } } private fun createSpecByPath(path: Path, originalFile: Path?): DirectoryContentSpecImpl { if (path.isDirectory()) { return DirectorySpec(originalFile).also { fillSpecFromDirectory(it, path, originalFile) } } if (path.extension in setOf("zip", "jar")) { val dirForExtracted = FileUtil.createTempDirectory("extracted-${path.name}", null, false).toPath() ZipUtil.extract(path, dirForExtracted, null) return ZipSpec().also { fillSpecFromDirectory(it, dirForExtracted, null) } } return FileSpec(Files.readAllBytes(path), originalFile) }
apache-2.0
6d3efbb4c0efe327a71584c6c98ef40f
40.710714
152
0.679767
4.952926
false
false
false
false
GunoH/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/CodeReviewTabs.kt
2
2465
// 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 com.intellij.collaboration.ui.codereview import com.intellij.collaboration.messages.CollaborationToolsBundle.message import com.intellij.ui.SimpleTextAttributes.GRAYED_ATTRIBUTES import com.intellij.ui.SimpleTextAttributes.REGULAR_ATTRIBUTES import com.intellij.ui.content.AlertIcon import com.intellij.ui.scale.JBUIScale.scale import com.intellij.ui.tabs.TabInfo import com.intellij.ui.tabs.impl.JBTabsImpl import com.intellij.ui.tabs.impl.TabLabel import icons.CollaborationToolsIcons import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import org.jetbrains.annotations.Nls import java.util.function.Supplier object CodeReviewTabs { fun CoroutineScope.bindTabText(tab: TabInfo, text: Supplier<@Nls String>, countFlow: Flow<Int?>): Job = countFlow .onEach { count -> tab.setText(text) tab.appendCount(count) } .launchIn(this) fun CoroutineScope.bindTabUi( tabs: JBTabsImpl, tab: TabInfo, text: Supplier<@Nls String>, totalFlow: Flow<Int?>, unreadFlow: Flow<Int?> ): Job = combine(totalFlow, unreadFlow, ::Pair) .onEach { (total, unread) -> tab.setText(text) tab.appendUnreadIcon(tabs.getTabLabel(tab), unread) tab.appendCount(total, unread == null || unread <= 0) tab.setUnreadTooltip(unread) } .launchIn(this) } private fun TabInfo.setText(text: Supplier<@Nls String>) { clearText(false).append(text.get(), REGULAR_ATTRIBUTES) } private fun TabInfo.appendCount(count: Int?, smallGap: Boolean = true) { count?.let { append(if (smallGap) " $it" else " $it", GRAYED_ATTRIBUTES) } } private fun TabInfo.appendUnreadIcon(tabLabel: TabLabel, unread: Int?) { if (unread == null || unread <= 0) { stopAlerting() } else { alertIcon = AlertIcon( CollaborationToolsIcons.Review.FileUnread, 0, tabLabel.labelComponent.preferredSize.width + scale(3) ) fireAlert() resetAlertRequest() } } private fun TabInfo.setUnreadTooltip(unread: Int?) { tooltipText = if (unread != null && unread > 0) message("tooltip.code.review.files.not.viewed", unread) else null }
apache-2.0
63cbb8bd1b7089470bb4fb413c877aa5
32.324324
158
0.729817
3.875786
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/CascadeIfInspection.kt
4
2745
// 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.inspections import com.intellij.codeInspection.IntentionWrapper import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.psi.isOneLiner import org.jetbrains.kotlin.idea.intentions.branchedTransformations.getWhenConditionSubjectCandidate import org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions.IfToWhenIntention import org.jetbrains.kotlin.idea.intentions.branchedTransformations.isElseIf import org.jetbrains.kotlin.idea.intentions.branches import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class CascadeIfInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession) = ifExpressionVisitor(fun(expression) { val branches = expression.branches if (branches.size <= 2) return if (expression.isOneLiner()) return if (branches.any { it == null || it.lastBlockStatementOrThis() is KtIfExpression } ) return if (expression.isElseIf()) return if (expression.anyDescendantOfType<KtExpressionWithLabel> { it is KtBreakExpression || it is KtContinueExpression } ) return var current: KtIfExpression? = expression var lastSubjectCandidate: KtExpression? = null while (current != null) { val subjectCandidate = current.condition.getWhenConditionSubjectCandidate(checkConstants = false) ?: return if (lastSubjectCandidate != null && !lastSubjectCandidate.matches(subjectCandidate)) return lastSubjectCandidate = subjectCandidate current = current.`else` as? KtIfExpression } holder.registerProblem( expression.ifKeyword, KotlinBundle.message("cascade.if.should.be.replaced.with.when"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, IntentionWrapper(IfToWhenIntention()) ) }) }
apache-2.0
c994a45191d840a726c7e6eb2aa90a1a
47.157895
158
0.71949
5.501002
false
false
false
false
GunoH/intellij-community
platform/core-api/src/com/intellij/openapi/progress/ProgressSink.kt
3
1459
// 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.progress import com.intellij.openapi.util.NlsContexts.ProgressDetails import com.intellij.openapi.util.NlsContexts.ProgressText import org.jetbrains.annotations.ApiStatus.Experimental import org.jetbrains.annotations.ApiStatus.NonExtendable /** * Represents an entity used to send progress updates to. * The client code is not supposed to read the progress updates, thus there are no getters. * It's up to implementors of this interface to decide what to do with these updates. */ @Experimental @NonExtendable interface ProgressSink { /** * Updates the current progress state. `null` value means "don't change corresponding property". */ fun update( text: @ProgressText String? = null, details: @ProgressDetails String? = null, fraction: Double? = null, ) /** * Updates current progress text. */ fun text(text: @ProgressText String) { update(text = text) } /** * Updates current progress details. */ fun details(details: @ProgressDetails String) { update(details = details) } /** * Updates current progress fraction. * * @param fraction a number between 0.0 and 1.0 reflecting the ratio of work that has already been done (0.0 for nothing, 1.0 for all) */ fun fraction(fraction: Double) { update(fraction = fraction) } }
apache-2.0
0415e151509370a42cbfb2ffbbf5f7c4
28.77551
136
0.721727
4.216763
false
false
false
false
siosio/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/references/KtReference.kt
1
3930
// 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.references import com.intellij.psi.* import com.intellij.psi.impl.source.resolve.ResolveCache import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.PackageViewDescriptor import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.util.application.runWithCancellationCheck import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import java.util.* interface KtDescriptorsBasedReference : KtReference { override val resolver get() = KotlinDescriptorsBasedReferenceResolver fun resolveToDescriptors(bindingContext: BindingContext): Collection<DeclarationDescriptor> { return getTargetDescriptors(bindingContext) } fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> override fun isReferenceTo(element: PsiElement): Boolean { return matchesTarget(element) } } fun KtReference.resolveToDescriptors(bindingContext: BindingContext): Collection<DeclarationDescriptor> { if (this !is KtDescriptorsBasedReference) { error("Reference $this should be KtDescriptorsBasedReference but was ${this::class}") } return resolveToDescriptors(bindingContext) } object KotlinDescriptorsBasedReferenceResolver : ResolveCache.PolyVariantResolver<KtReference> { class KotlinResolveResult(element: PsiElement) : PsiElementResolveResult(element) private fun resolveToPsiElements(ref: KtDescriptorsBasedReference): Collection<PsiElement> { val bindingContext = ref.element.analyze(BodyResolveMode.PARTIAL) return resolveToPsiElements(ref, bindingContext, ref.getTargetDescriptors(bindingContext)) } private fun resolveToPsiElements( ref: KtDescriptorsBasedReference, context: BindingContext, targetDescriptors: Collection<DeclarationDescriptor> ): Collection<PsiElement> { if (targetDescriptors.isNotEmpty()) { return targetDescriptors.flatMap { target -> resolveToPsiElements(ref, target) }.toSet() } val labelTargets = getLabelTargets(ref, context) if (labelTargets != null) { return labelTargets } return Collections.emptySet() } private fun resolveToPsiElements( ref: KtDescriptorsBasedReference, targetDescriptor: DeclarationDescriptor ): Collection<PsiElement> { return if (targetDescriptor is PackageViewDescriptor) { val psiFacade = JavaPsiFacade.getInstance(ref.element.project) val fqName = targetDescriptor.fqName.asString() listOfNotNull(psiFacade.findPackage(fqName)) } else { DescriptorToSourceUtilsIde.getAllDeclarations(ref.element.project, targetDescriptor, ref.element.resolveScope) } } private fun getLabelTargets(ref: KtDescriptorsBasedReference, context: BindingContext): Collection<PsiElement>? { val reference = ref.element as? KtReferenceExpression ?: return null val labelTarget = context[BindingContext.LABEL_TARGET, reference] if (labelTarget != null) { return listOf(labelTarget) } return context[BindingContext.AMBIGUOUS_LABEL_TARGET, reference] } override fun resolve(ref: KtReference, incompleteCode: Boolean): Array<ResolveResult> { return runWithCancellationCheck { val resolveToPsiElements = resolveToPsiElements(ref as KtDescriptorsBasedReference) resolveToPsiElements.map { KotlinResolveResult(it) }.toTypedArray() } } }
apache-2.0
f3a25e61bf168b44f8ee1135cb6dcf67
41.717391
158
0.750636
5.574468
false
false
false
false
K0zka/kerub
src/main/kotlin/com/github/kerubistan/kerub/services/HostService.kt
2
2885
package com.github.kerubistan.kerub.services import com.github.kerubistan.kerub.model.Host import com.github.kerubistan.kerub.model.HostPubKey import com.github.kerubistan.kerub.security.admin import com.wordnik.swagger.annotations.Api import com.wordnik.swagger.annotations.ApiOperation import com.wordnik.swagger.annotations.ApiParam import com.wordnik.swagger.annotations.ApiResponse import com.wordnik.swagger.annotations.ApiResponses import org.apache.shiro.authz.annotation.RequiresAuthentication import org.apache.shiro.authz.annotation.RequiresRoles import java.util.UUID import javax.ws.rs.Consumes import javax.ws.rs.GET import javax.ws.rs.POST import javax.ws.rs.PUT import javax.ws.rs.Path import javax.ws.rs.PathParam import javax.ws.rs.Produces import javax.ws.rs.QueryParam import javax.ws.rs.core.MediaType @Api("s/r/host", description = "Host service") @Path("/host") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) @RequiresAuthentication @RequiresRoles(admin) interface HostService : RestCrud<Host>, RestOperations.List<Host>, RestOperations.SimpleSearch<Host> { @ApiOperation("Add new object") @ApiResponses( ApiResponse(code = 200, message = "OK"), ApiResponse(code = 403, message = "Security error") ) @PUT @Path("/join") fun join(@ApiParam(value = "New host with password", required = true) hostPwd: HostAndPassword): Host @PUT @Path("/join-pubkey") fun joinWithoutPassword(details: HostJoinDetails): Host @ApiOperation("Get the public key of the server", httpMethod = "GET") @GET @Path("/helpers/pubkey") fun getHostPubkey(@QueryParam("address") address: String): HostPubKey @ApiOperation("Find host by address", httpMethod = "GET") @GET @Path("/byaddress/{address}") fun getByAddress(@PathParam("address") address: String): List<Host> @ApiOperation("Get the public key of kerub", httpMethod = "GET", produces = MediaType.TEXT_PLAIN) @GET @Produces(MediaType.TEXT_PLAIN) @Path("/helpers/controller-pubkey") fun getPubkey(): String @POST @ApiOperation( "Ask the controller to remove the host. The host will be deleted once all service migrated to other hosts", httpMethod = "POST", produces = MediaType.APPLICATION_JSON ) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/remove") fun remove(@PathParam("id") id: UUID) @POST @ApiOperation( "Tell the controller that a host crashed. Resources", httpMethod = "POST", produces = MediaType.APPLICATION_JSON ) @Produces(MediaType.APPLICATION_JSON) @Path("/{id}/dead") fun declareDead(@PathParam("id") id: UUID) enum class HostFeatureType { networking, virtualization, storage, hardware } data class HostFeatureSummary( val type: HostFeatureType, val name: String ) @GET @Path("{id}/features") @Produces(MediaType.APPLICATION_JSON) fun getFeatures(@PathParam("id") id: UUID): List<HostFeatureSummary> }
apache-2.0
ed53b53b5a3d75c4f72545ee18e44780
29.368421
110
0.760832
3.531212
false
false
false
false
GunoH/intellij-community
platform/configuration-store-impl/src/FileBasedStorageConfiguration.kt
12
1301
// 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.configurationStore import com.intellij.openapi.components.StateStorageOperation import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile interface FileBasedStorageConfiguration { val isUseVfsForRead: Boolean val isUseVfsForWrite: Boolean fun resolveVirtualFile(path: String, reasonOperation: StateStorageOperation) = doResolveVirtualFile(path, reasonOperation) } internal val defaultFileBasedStorageConfiguration = object : FileBasedStorageConfiguration { override val isUseVfsForRead: Boolean get() = false override val isUseVfsForWrite: Boolean get() = true } internal fun doResolveVirtualFile(path: String, reasonOperation: StateStorageOperation): VirtualFile? { val fs = LocalFileSystem.getInstance() val result = if (reasonOperation == StateStorageOperation.READ) fs.findFileByPath(path) else fs.refreshAndFindFileByPath(path) if (result == null || !result.isValid) { return null } // otherwise virtualFile.contentsToByteArray() will query expensive FileTypeManager.getInstance()).getByFile() result.setCharset(Charsets.UTF_8, null, false) return result }
apache-2.0
0d9d788608eb4922b343a5507457608f
37.294118
140
0.797848
4.965649
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/gttd.kt
2
6028
// 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.codeInsight.navigation.impl import com.intellij.codeInsight.navigation.* import com.intellij.codeInsight.navigation.actions.TypeDeclarationPlaceAwareProvider import com.intellij.codeInsight.navigation.actions.TypeDeclarationProvider import com.intellij.codeInsight.navigation.impl.NavigationActionResult.MultipleTargets import com.intellij.codeInsight.navigation.impl.NavigationActionResult.SingleTarget import com.intellij.model.Symbol import com.intellij.model.psi.PsiSymbolDeclaration import com.intellij.model.psi.PsiSymbolReference import com.intellij.model.psi.PsiSymbolService import com.intellij.model.psi.impl.EvaluatorReference import com.intellij.model.psi.impl.TargetData import com.intellij.model.psi.impl.declaredReferencedData import com.intellij.model.psi.impl.mockEditor import com.intellij.navigation.NavigationTarget import com.intellij.navigation.SymbolNavigationService import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.util.SmartList internal fun gotoTypeDeclaration(file: PsiFile, offset: Int): GTTDActionData? { return processInjectionThenHost(file, offset, ::gotoTypeDeclarationInner) } private fun gotoTypeDeclarationInner(file: PsiFile, offset: Int): GTTDActionData? { val (declaredData, referencedData) = declaredReferencedData(file, offset) ?: return null val targetData = referencedData ?: declaredData ?: return null val editor = mockEditor(file) ?: return null return GTTDActionData(file.project, targetData, editor, offset) } /** * "Go To Type Declaration" action data */ internal class GTTDActionData( private val project: Project, private val targetData: TargetData, private val editor: Editor, private val offset: Int, ) { private fun typeSymbols() = targetData.typeSymbols(editor, offset) @Suppress("DEPRECATION") @Deprecated("Unused in v2 implementation") fun ctrlMouseInfo(): CtrlMouseInfo? { val typeSymbols = typeSymbols().take(2).toList() return when (typeSymbols.size) { 0 -> null 1 -> SingleSymbolCtrlMouseInfo(typeSymbols.single(), targetData.elementAtOffset(), targetData.highlightRanges(), false) else -> MultipleTargetElementsInfo(targetData.highlightRanges()) } } fun ctrlMouseData(): CtrlMouseData? { val typeSymbols = typeSymbols().take(2).toList() return when (typeSymbols.size) { 0 -> null 1 -> symbolCtrlMouseData( project, typeSymbols.single(), targetData.elementAtOffset(), targetData.highlightRanges(), declared = false, ) else -> multipleTargetsCtrlMouseData(targetData.highlightRanges()) } } fun result(): NavigationActionResult? { return result(typeSymbols().navigationTargets(project).toCollection(SmartList())) } } private fun TargetData.typeSymbols(editor: Editor, offset: Int): Sequence<Symbol> { return when (this) { is TargetData.Declared -> typeSymbols(editor, offset) is TargetData.Referenced -> typeSymbols(editor, offset) } } private fun TargetData.Declared.typeSymbols(editor: Editor, offset: Int): Sequence<Symbol> = sequence { val psiSymbolService = PsiSymbolService.getInstance() for (declaration: PsiSymbolDeclaration in declarations) { val target = declaration.symbol val psi = psiSymbolService.extractElementFromSymbol(target) if (psi != null) { for (typeElement in typeElements(editor, offset, psi)) { yield(psiSymbolService.asSymbol(typeElement)) } } else { for (typeProvider in SymbolTypeProvider.EP_NAME.extensions) { yieldAll(typeProvider.getSymbolTypes(target)) } } } } private fun TargetData.Referenced.typeSymbols(editor: Editor, offset: Int): Sequence<Symbol> = sequence { for (reference: PsiSymbolReference in references) { if (reference is EvaluatorReference) { for (targetElement in reference.targetElements) { for (typeElement in typeElements(editor, offset, targetElement)) { yield(PsiSymbolService.getInstance().asSymbol(typeElement)) } } } else { for (typeProvider in SymbolTypeProvider.EP_NAME.extensions) { for (target in reference.resolveReference()) { yieldAll(typeProvider.getSymbolTypes(target)) } } } } } internal fun elementTypeTargets(editor: Editor, offset: Int, targetElements: Collection<PsiElement>): Collection<NavigationTarget> { val result = SmartList<NavigationTarget>() for (targetElement in targetElements) { for (typeElement in typeElements(editor, offset, targetElement)) { result.add(PsiElementNavigationTarget(typeElement)) } } return result } private fun typeElements(editor: Editor, offset: Int, targetElement: PsiElement): Collection<PsiElement> { for (provider in TypeDeclarationProvider.EP_NAME.extensionList) { val result = if (provider is TypeDeclarationPlaceAwareProvider) { provider.getSymbolTypeDeclarations(targetElement, editor, offset) } else { provider.getSymbolTypeDeclarations(targetElement) } return result?.toList() ?: continue } return emptyList() } private fun Sequence<Symbol>.navigationTargets(project: Project): Sequence<NavigationTarget> { return flatMap { typeSymbol -> SymbolNavigationService.getInstance().getNavigationTargets(project, typeSymbol) } } internal fun result(navigationTargets: Collection<NavigationTarget>): NavigationActionResult? { return when (navigationTargets.size) { 0 -> null 1 -> navigationTargets.single().navigationRequest()?.let { request -> SingleTarget(request, null) } else -> MultipleTargets(navigationTargets.map { navigationTarget -> LazyTargetWithPresentation(navigationTarget::navigationRequest, navigationTarget.presentation(), null) }) } }
apache-2.0
72d3ea43d8f8e2ef37e097df6951a3b8
36.209877
132
0.748507
4.644068
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToIndexedFunctionCallIntention.kt
1
5296
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.psi.codeStyle.CodeStyleManager import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.core.CollectingNameValidator import org.jetbrains.kotlin.idea.core.KotlinNameSuggester import org.jetbrains.kotlin.idea.core.NewDeclarationNameValidator import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.getOrCreateParameterList import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ConvertToIndexedFunctionCallIntention : SelfTargetingRangeIntention<KtCallExpression>( KtCallExpression::class.java, KotlinBundle.lazyMessage("convert.to.indexed.function.call") ) { override fun applicabilityRange(element: KtCallExpression): TextRange? { val callee = element.calleeExpression ?: return null val (functionFqName, newFunctionName) = functions[callee.text] ?: return null if (element.singleLambdaArgumentExpression() == null) return null val context = element.analyze(BodyResolveMode.PARTIAL) if (functionFqName != element.getResolvedCall(context)?.resultingDescriptor?.fqNameOrNull()) return null setTextGetter(KotlinBundle.lazyMessage("convert.to.0", "'$newFunctionName'")) return callee.textRange } override fun applyTo(element: KtCallExpression, editor: Editor?) { val functionName = element.calleeExpression?.text ?: return val (_, newFunctionName) = functions[functionName] ?: return val functionLiteral = element.singleLambdaArgumentExpression()?.functionLiteral ?: return val psiFactory = KtPsiFactory(element) val context = element.analyze(BodyResolveMode.PARTIAL) functionLiteral .collectDescendantsOfType<KtReturnExpression> { it.getLabelName() == functionName && it.getTargetFunction(context) == functionLiteral } .forEach { val value = it.returnedExpression val newLabeledReturn = if (value != null) { psiFactory.createExpressionByPattern("return@$newFunctionName $0", value) } else { psiFactory.createExpression("return@$newFunctionName") } it.replace(newLabeledReturn) } val parameterList = functionLiteral.getOrCreateParameterList() val parameters = parameterList.parameters val nameValidator = CollectingNameValidator( filter = NewDeclarationNameValidator(functionLiteral, null, NewDeclarationNameValidator.Target.VARIABLES) ) val indexParameterName = KotlinNameSuggester.suggestNameByName("index", nameValidator) val indexParameter = psiFactory.createParameter(indexParameterName) if (parameters.isEmpty()) { parameterList.addParameter(indexParameter) parameterList.addParameter(psiFactory.createParameter("it")) } else { parameterList.addParameterBefore(indexParameter, parameters.first()) } val callOrQualified = element.getQualifiedExpressionForSelector() ?: element val result = callOrQualified.replace( psiFactory.buildExpression { appendCallOrQualifiedExpression(element, newFunctionName) } ) CodeStyleManager.getInstance(element.project).reformat(result) } companion object { private const val indexed = "Indexed" private val functions = listOf( Pair("filter", "filter$indexed"), Pair("filterTo", "filter${indexed}To"), Pair("fold", "fold$indexed"), Pair("foldRight", "foldRight$indexed"), Pair("forEach", "forEach$indexed"), Pair("map", "map$indexed"), Pair("mapNotNull", "map${indexed}NotNull"), Pair("mapNotNullTo", "map${indexed}NotNullTo"), Pair("mapTo", "map${indexed}To"), Pair("onEach", "onEach$indexed"), Pair("reduce", "reduce$indexed"), Pair("reduceOrNull", "reduce${indexed}OrNull"), Pair("reduceRight", "reduceRight$indexed"), Pair("reduceRightOrNull", "reduceRight${indexed}OrNull"), Pair("runningFold", "runningFold$indexed"), Pair("runningReduce", "runningReduce$indexed"), Pair("scan", "scan$indexed"), Pair("scanReduce", "scanReduce$indexed"), ).associate { (functionName, indexedFunctionName) -> functionName to (FqName("kotlin.collections.$functionName") to indexedFunctionName) } } }
apache-2.0
9527d9a923fa6b5006f9aed2230c56ae
49.438095
158
0.69392
5.476732
false
false
false
false
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/daemon/IgnoreDirectoryMarkerProvider.kt
1
2518
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package mobi.hsz.idea.gitignore.daemon import com.intellij.codeInsight.daemon.LineMarkerInfo import com.intellij.codeInsight.daemon.LineMarkerProvider import com.intellij.openapi.components.service import com.intellij.openapi.editor.markup.GutterIconRenderer import com.intellij.psi.PsiElement import com.intellij.util.PlatformIcons import mobi.hsz.idea.gitignore.IgnoreBundle import mobi.hsz.idea.gitignore.psi.IgnoreEntryDirectory import mobi.hsz.idea.gitignore.psi.IgnoreEntryFile import mobi.hsz.idea.gitignore.services.IgnoreMatcher import mobi.hsz.idea.gitignore.util.Glob import mobi.hsz.idea.gitignore.util.Utils /** * [LineMarkerProvider] that marks entry lines with directory icon if they point to the directory in virtual system. */ class IgnoreDirectoryMarkerProvider : LineMarkerProvider { private val cache = mutableMapOf<String, Boolean>() /** * Returns [LineMarkerInfo] with set [PlatformIcons.FOLDER_ICON] if entry points to the directory. * * @param element current element * @return `null` if entry is not a directory */ @Suppress("ReturnCount") override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? { if (element !is IgnoreEntryFile) { return null } var isDirectory = element is IgnoreEntryDirectory if (!isDirectory) { val key = element.getText() if (cache.containsKey(key)) { isDirectory = cache[key] ?: false } else { val parent = element.getContainingFile().virtualFile.parent ?: return null val project = element.getProject() Utils.getModuleForFile(parent, project) ?: return null val matcher = project.service<IgnoreMatcher>() val file = Glob.findOne(parent, element, matcher) cache[key] = file != null && file.isDirectory.also { isDirectory = it } } } return when { isDirectory -> LineMarkerInfo( element.getFirstChild(), element.getTextRange(), PlatformIcons.FOLDER_ICON, null, null, GutterIconRenderer.Alignment.CENTER, IgnoreBundle.messagePointer("daemon.lineMarker.directory") ) else -> null } } }
mit
0fce1fb31b24d3472ad74f9cd023b2cf
37.738462
140
0.658856
4.956693
false
false
false
false
marverenic/Paper
app/src/main/java/com/marverenic/reader/ui/home/all/AllArticlesViewModel.kt
1
2002
package com.marverenic.reader.ui.home.all import android.content.Context import android.databinding.BaseObservable import android.databinding.Bindable import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import com.marverenic.reader.BR import com.marverenic.reader.R import com.marverenic.reader.model.Stream import com.marverenic.reader.ui.common.article.ArticleAdapter import com.marverenic.reader.ui.common.article.ArticleFetchCallback import com.marverenic.reader.ui.common.article.ArticleReadCallback import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject class AllArticlesViewModel(val context: Context, stream: Stream? = null, var streamTitle: String, val readCallback: ArticleReadCallback, val fetchCallback: ArticleFetchCallback) : BaseObservable() { var stream: Stream? = stream set(value) { field = value adapter.stream = stream adapter.notifyDataSetChanged() } var refreshing: Boolean = (stream == null) set(value) { if (value != field) { refreshSubject.onNext(value) field = value notifyPropertyChanged(BR.refreshing) } } @Bindable get() = field private val refreshSubject = BehaviorSubject.createDefault(refreshing) val adapter: ArticleAdapter by lazy(LazyThreadSafetyMode.NONE) { ArticleAdapter(stream, streamTitle, readCallback, fetchCallback) } val layoutManager = LinearLayoutManager(context) val swipeRefreshColors = intArrayOf( ContextCompat.getColor(context, R.color.colorPrimary), ContextCompat.getColor(context, R.color.colorPrimaryDark), ContextCompat.getColor(context, R.color.colorAccent) ) fun getRefreshObservable(): Observable<Boolean> = refreshSubject }
apache-2.0
28447ba5ff0753db5ce2ec49fc699351
34.140351
74
0.684815
5.017544
false
false
false
false
kirimin/mitsumine
app/src/main/java/me/kirimin/mitsumine/entryinfo/EntryInfoPresenter.kt
1
1626
package me.kirimin.mitsumine.entryinfo import me.kirimin.mitsumine.R import rx.subscriptions.CompositeSubscription import java.net.URLEncoder import javax.inject.Inject class EntryInfoPresenter @Inject constructor(val useCase: EntryInfoUseCase) { private val subscriptions = CompositeSubscription() private lateinit var view: EntryInfoView fun onCreate(view: EntryInfoView, url: String) { this.view = view view.initActionBar() view.showProgressBar() subscriptions.add(useCase.requestEntryInfo(URLEncoder.encode(url, "utf-8")) .filter { !it.isNullObject } .flatMap { useCase.loadStars(entryInfo = it) } .subscribe ({ entryInfo -> view.setEntryInfo(entryInfo) view.hideProgressBar() val commentList = entryInfo.bookmarkList.filter { it.hasComment } val stars = commentList.sortedByDescending { it.stars?.allStarsCount } view.setBookmarkFragments(entryInfo.bookmarkList, commentList, stars, entryInfo.entryId) view.setCommentCount(commentList.count().toString()) if (useCase.isLogin()) { view.setRegisterBookmarkFragment(entryInfo.url) } view.setViewPagerSettings(currentItem = 2, offscreenPageLimit = 3) }, { view.hideProgressBar() view.showError(R.string.network_error) }) ) } fun onDestroy() { subscriptions.unsubscribe() } }
apache-2.0
c5139154d378ac2688c867b1abc688d5
38.682927
108
0.606396
5.14557
false
false
false
false
marktony/ZhiHuDaily
app/src/main/java/com/marktony/zhihudaily/injection/Injection.kt
1
2289
package com.marktony.zhihudaily.injection import android.content.Context import com.marktony.zhihudaily.data.source.local.* import com.marktony.zhihudaily.data.source.remote.* import com.marktony.zhihudaily.data.source.repository.* import com.marktony.zhihudaily.database.AppDatabase import com.marktony.zhihudaily.util.AppExecutors object Injection { private val appExecutors: AppExecutors = AppExecutors() fun provideZhihuDailyNewsRepository(context: Context): ZhihuDailyNewsRepository = ZhihuDailyNewsRepository.getInstance(ZhihuDailyNewsRemoteDataSource.getInstance(appExecutors), ZhihuDailyNewsLocalDataSource.getInstance(appExecutors, AppDatabase.getInstance(context).zhihuDailyNewsDao())) fun provideZhihuDailyContentRepository(context: Context): ZhihuDailyContentRepository = ZhihuDailyContentRepository.getInstance(ZhihuDailyContentRemoteDataSource.getInstance(appExecutors), ZhihuDailyContentLocalDataSource.getInstance(appExecutors, AppDatabase.getInstance(context).zhihuDailyContentDao())) fun provideGuokrHandpickNewsRepository(context: Context): GuokrHandpickNewsRepository = GuokrHandpickNewsRepository.getInstance(GuokrHandpickNewsRemoteDataSource.getInstance(appExecutors), GuokrHandpickNewsLocalDataSource.getInstance(appExecutors, AppDatabase.getInstance(context).guokrHandpickNewsDao())) fun provideGuokrHandpickContentRepository(context: Context): GuokrHandpickContentRepository = GuokrHandpickContentRepository.getInstance(GuokrHandpickContentRemoteDataSource.getInstance(appExecutors), GuokrHandpickContentLocalDataSource.getInstance(appExecutors, AppDatabase.getInstance(context).guokrHandpickContentDao())) fun provideDoubanMomentNewsRepository(context: Context): DoubanMomentNewsRepository = DoubanMomentNewsRepository.getInstance(DoubanMomentNewsRemoteDataSource.getInstance(appExecutors), DoubanMomentNewsLocalDataSource.getInstance(appExecutors, AppDatabase.getInstance(context).doubanMomentNewsDao())) fun provideDoubanMomentContentRepository(context: Context): DoubanMomentContentRepository = DoubanMomentContentRepository.getInstance(DoubanMomentContentRemoteDataSource.getInstance(appExecutors), DoubanMomentContentLocalDataSource.getInstance(appExecutors, AppDatabase.getInstance(context).doubanMomentContentDao())) }
apache-2.0
09b1a4449e892ef32add5101983dc560
87.076923
327
0.877239
6.288462
false
false
false
false
deltadak/plep
src/main/kotlin/nl/deltadak/plep/ui/util/converters/Converters.kt
1
2291
package nl.deltadak.plep.ui.util.converters import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.scene.control.TreeItem import javafx.scene.control.TreeView import nl.deltadak.plep.HomeworkTask /** * This file contains several useful converter methods, specified top level to be easily callable (like static methods). */ /** * Get all the parent tasks when given a list of lists of HomeworkTasks, assuming that the first item of a sublist is the parent task. * * @return A list of HomeworkTasks, which are the parent tasks. */ fun List<List<HomeworkTask>>.getParentTasks(): List<HomeworkTask> = this.map { it[0] } /** * Converts a TreeView to a list of lists of tasks. The first item of each * list is the parent task, the items after that are its subtasks. * * @return List&lt;List&lt;HomeworkTask&gt;&gt; */ fun TreeView<HomeworkTask>.toHomeworkTaskList(): List<List<HomeworkTask>> { // Create a list with the tree items of the parent tasks. val parentItems = this.root.children // Create a list with homework tasks of the parent tasks. val parentTasks = parentItems.toFlatList() // Create the list to eventually return. val tasks = mutableListOf<List<HomeworkTask>>() for (i: Int in 0 until parentItems.size) { // Get the sub tree items of parent task i, and store them in a list. val childItems = parentItems[i].children // Store the subtasks of parent task i in a list. val childTasks = childItems.toFlatList() // Create a list containing one parent and its children. val oneFamily = mutableListOf<HomeworkTask>() // Add the parent to the family. oneFamily.add(parentTasks[i]) // Add its children to the family. oneFamily.addAll(childTasks) // Add the family to the nested list of tasks tasks.add(oneFamily) } return tasks } /** * Converts List of TreeItems of Homeworktasks to List of Homeworktasks. * * @return List of Homeworktasks. */ fun <H> ObservableList<TreeItem<H>>.toFlatList() = this.map {it.value} /** * Convert a List to an ObservableList. * * @return Converted list. */ fun <H> List<H>.toObservableList(): ObservableList<H> = FXCollections.observableList(this)
mit
5355588e9d2c8889208bb003d1fbaf00
29.959459
134
0.705805
4.040564
false
false
false
false
google/intellij-gn-plugin
src/main/java/com/google/idea/gn/psi/builtin/StringJoin.kt
1
1186
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package com.google.idea.gn.psi.builtin import com.google.idea.gn.completion.CompletionIdentifier import com.google.idea.gn.psi.Function import com.google.idea.gn.psi.GnCall import com.google.idea.gn.psi.GnPsiUtil import com.google.idea.gn.psi.GnValue import com.google.idea.gn.psi.scope.Scope class StringJoin : Function { override fun execute(call: GnCall, targetScope: Scope): GnValue? { val exprList = call.exprList.exprList if (exprList.size != 2) { return null } val sep = GnPsiUtil.evaluate(exprList[0], targetScope)?.string ?: return null val list = GnPsiUtil.evaluate(exprList[1], targetScope)?.list?.mapNotNull { it.string } ?: return null return GnValue(list.joinToString(sep)) } override val isBuiltin: Boolean get() = true override val identifierName: String get() = NAME override val identifierType: CompletionIdentifier.IdentifierType get() = CompletionIdentifier.IdentifierType.FUNCTION companion object { const val NAME = "string_join" } }
bsd-3-clause
22a797e116a57c481c02d66fae02165e
32.885714
91
0.733558
3.914191
false
false
false
false
kishmakov/Kitchen
server/src/io/magnaura/server/v1/handles/command.kt
1
806
package io.magnaura.server.v1.handles import io.ktor.application.* import io.ktor.http.* import io.ktor.response.* import io.magnaura.protocol.v1.CommandHandle import io.magnaura.server.Handler import io.magnaura.server.storage.COMMAND_STORAGE private suspend fun commandProcessor(call: ApplicationCall) { val commandId = call.parameters["commandId"] when (val res = COMMAND_STORAGE.get(commandId!!)) { null -> { call.response.status(HttpStatusCode.NotFound) } else -> { call.response.status(HttpStatusCode.OK) val success = CommandHandle.Success(info = res) call.respond(CommandHandle.Response(success = success)) } } } val CommandHandler = Handler( CommandHandle, getProcessor = ::commandProcessor )
gpl-3.0
4df236af715f731a49ed5f6f6ea7b45a
27.821429
67
0.688586
4.176166
false
false
false
false
daemontus/jafra
src/test/kotlin/com/github/daemontus/jafra/RandomIntegrationTest.kt
1
3087
package com.github.daemontus.jafra import org.junit.Test import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue import kotlin.test.assertFalse class RandomTest { @Test(timeout = 10000) fun t1() = test(2, 600, false) @Test(timeout = 10000) fun t2() = test(2, 200, true) @Test(timeout = 20000) fun t3() = test(10, 200, true) @Test(timeout = 10000) fun t4() = test(10, 1000, false) @Test(timeout = 10000) fun t5() = test(2, 10, true) @Test(timeout = 10000) fun t6() = test(2, 10, false) @Test(timeout = 10000) fun t7() = test(10, 20, true) @Test(timeout = 10000) fun t8() = test(10, 20, false) private fun test(agents: Int, messages: Int, sleep: Boolean) { val workerRange = 0..(agents-1) val messageQueues = workerRange.map { LinkedBlockingQueue<Int>() } createSharedMemoryTerminators(agents) .mapIndexed { i, factory -> Worker(i, agents, factory, messageQueues, messages, sleep) } .map { it.writer.start(); it.reader.start(); it } .map { it.writer.join(); it } .map { it.reader.join()} assertFalse(messageQueues.any { it.isNotEmpty() }) } } class Worker( val myId: Int, val processCount: Int, val terminators: Terminator.Factory, val messageQueues: List<BlockingQueue<Int>>, val initialMessages: Int, val sleep: Boolean = true ) { val terminator = terminators.createNew() @Volatile var mainTaskDone = false val reader = Thread() { //receives messages until poison pill comes //message can trigger another message if it's value is high enough var got = messageQueues[myId].take() while (got >= 0) { terminator.messageReceived() if (Math.random() < 0.5 * (got/200.0)) { terminator.messageSent() messageQueues[(Math.random() * processCount).toInt()].add((got/1.5).toInt()) } if (sleep) Thread.sleep((Math.random() * got/2).toLong()) synchronized(messageQueues[myId]) { if (mainTaskDone && terminator.working) terminator.setDone() } got = messageQueues[myId].take() } println("$myId reader out") } val writer = Thread() { //sends max 200 messages, after each message waits a little (simulate main workload) var m = Math.random() * initialMessages while (m > 0) { terminator.messageSent() messageQueues[(Math.random() * processCount).toInt()].add(m.toInt()) m -= 1 if (sleep) Thread.sleep((Math.random() * m).toLong()) } println("$myId is done sending") synchronized(messageQueues[myId]) { if (messageQueues[myId].isEmpty() && terminator.working) { terminator.setDone() } mainTaskDone = true } terminator.waitForTermination() messageQueues[myId].add(-1) } }
mit
875b60f50dc23ad9701292bf224c7aca
28.132075
100
0.579527
4.045872
false
true
false
false
google/summit-ast
src/main/java/com/google/summit/ast/declaration/ClassDeclaration.kt
1
2248
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.summit.ast.declaration import com.google.summit.ast.Identifier import com.google.summit.ast.Node import com.google.summit.ast.SourceLocation import com.google.summit.ast.TypeRef /** * A declaration for a class symbol. * * @param id the unqualified name of the class * @param extendsType an optional type reference to a super class * @param implementsTypes a list of type references to implemented interfaces * @param bodyDeclarations a list of the declarations inside the class body * @param loc the location in the source file */ class ClassDeclaration( id: Identifier, val extendsType: TypeRef?, val implementsTypes: List<TypeRef>, bodyDeclarations: List<Node>, loc: SourceLocation ) : TypeDeclaration(id, loc) { /** The subset of body declarations that declare an inner type (class, enum, or interface). */ val innerTypeDeclarations = bodyDeclarations.filterIsInstance<TypeDeclaration>() /** The field declarations include both static and instance members. */ val fieldDeclarations = bodyDeclarations.filterIsInstance<FieldDeclarationGroup>() /** The property declarations include both static and instance properties. */ val propertyDeclarations = bodyDeclarations.filterIsInstance<PropertyDeclaration>() /** The method declarations include both static and instance methods. */ val methodDeclarations = bodyDeclarations.filterIsInstance<MethodDeclaration>() override fun getChildren(): List<Node> = modifiers + listOfNotNull(id, extendsType) + implementsTypes + innerTypeDeclarations + fieldDeclarations + propertyDeclarations + methodDeclarations }
apache-2.0
9eac98d094b93ce33d962ca61cc79ca4
37.758621
96
0.759342
4.742616
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/graphics/Renderer.kt
1
7555
/* Tickle Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.tickle.graphics import org.joml.Matrix4f import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL11.* import org.lwjgl.system.MemoryUtil import uk.co.nickthecoder.tickle.Game import uk.co.nickthecoder.tickle.util.Rectd /** * Based upon the following tutorial : * https://github.com/SilverTiger/lwjgl3-tutorial/blob/master/src/silvertiger/tutorial/lwjgl/graphic/Renderer.java */ class Renderer(val window: Window) { private val program = ShaderProgram() private var vertexBuffer = VertexBuffer() private val projection = Matrix4f() private var vertices = MemoryUtil.memAllocFloat(4096) private var numVertices: Int = 0 private var drawing: Boolean = false val identityMatrix = Matrix4f() private var currentTexture: Texture? = null private val currentColor = Color(-1f, -1f, -1f, -1f) var currentModelMatrix = identityMatrix private var uniColor: Int = -1 private var uniModel: Int = -1 init { /* Generate Vertex Buffer Object */ vertexBuffer = VertexBuffer() vertexBuffer.bind(Target.ARRAY_BUFFER) /* Create FloatBuffer */ vertices = MemoryUtil.memAllocFloat(4096) /* Upload null data to allocate storage for the VBO */ val size = (vertices.capacity() * java.lang.Float.BYTES).toLong() vertexBuffer.uploadData(Target.ARRAY_BUFFER, size, Usage.DYNAMIC_DRAW) /* Initialize variables */ numVertices = 0 drawing = false /* Load shaders */ val vertexShader = Shader.load(ShaderType.VERTEX_SHADER, Game::class.java.getResourceAsStream("shaders/renderer.vert")) val fragmentShader = Shader.load(ShaderType.FRAGMENT_SHADER, Game::class.java.getResourceAsStream("shaders/renderer.frag")) program.attachShaders(vertexShader, fragmentShader) program.link() program.use() vertexShader.delete() fragmentShader.delete() /* Specify Vertex Pointers */ val posAttrib = program.getAttributeLocation("position") program.enableVertexAttribute(posAttrib) program.pointVertexAttribute(posAttrib, 2, 4 * java.lang.Float.BYTES, 0) /* Specify Texture Pointer */ val texAttrib = program.getAttributeLocation("texcoord") program.enableVertexAttribute(texAttrib) program.pointVertexAttribute(texAttrib, 2, 4 * java.lang.Float.BYTES, 2L * java.lang.Float.BYTES) /* Set model matrix to identity matrix */ val model = Matrix4f() uniModel = program.getUniformLocation("model") program.setUniform(uniModel, model) /* Set color uniform */ uniColor = program.getUniformLocation("color") program.setUniform(uniColor, Color.white()) // centerView(0f, 0f) } fun changeProjection(projection: Matrix4f) { val uniProjection = program.getUniformLocation("projection") program.setUniform(uniProjection, projection) } fun clearColor(color: Color) { GL11.glClearColor(color.red, color.green, color.blue, color.alpha) } fun clear() { glClear(GL_COLOR_BUFFER_BIT or GL_DEPTH_BUFFER_BIT) } fun beginView() { program.use() glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) currentColor.red = -1.12345f // An invalid value, therefore equals tests will fail currentTexture = null } fun endView() { if (drawing) { end() } currentTexture?.unbind() currentTexture = null } fun begin() { if (drawing) { throw IllegalStateException("Renderer is already drawing!") } drawing = true numVertices = 0 } fun end() { if (!drawing) { throw IllegalStateException("Renderer isn't drawing!") } drawing = false flush() } fun flush() { if (numVertices > 0) { vertices.flip() /* Upload the new vertex data */ vertexBuffer.bind(Target.ARRAY_BUFFER) vertexBuffer.uploadSubData(Target.ARRAY_BUFFER, 0, vertices) /* Draw batch */ glDrawArrays(GL_TRIANGLES, 0, numVertices) /* Clear vertex data for next batch */ vertices.clear() numVertices = 0 } } private val WHITE = Color.white() fun drawTexture(texture: Texture, worldRect: Rectd, textureRect: Rectd, color: Color = WHITE) { drawTexture(texture, worldRect.left, worldRect.bottom, worldRect.right, worldRect.top, textureRect, color, identityMatrix) } fun drawTexture(texture: Texture, left: Double, bottom: Double, right: Double, top: Double, textureRect: Rectd, color: Color = WHITE) { drawTexture(texture, left, bottom, right, top, textureRect, color, identityMatrix) } fun drawTexture(texture: Texture, left: Double, bottom: Double, right: Double, top: Double, textureRect: Rectd, color: Color = WHITE, modelMatrix: Matrix4f?) { val mm = modelMatrix ?: identityMatrix if (mm !== currentModelMatrix) { flush() program.setUniform(uniModel, mm) currentModelMatrix = mm } drawTextureRegion( texture, left.toFloat(), bottom.toFloat(), right.toFloat(), top.toFloat(), textureRect.left.toFloat(), textureRect.bottom.toFloat(), textureRect.right.toFloat(), textureRect.top.toFloat(), color) } fun drawTextureRegion( texture: Texture, x1: Float, y1: Float, x2: Float, y2: Float, s1: Float, t1: Float, s2: Float, t2: Float, color: Color = WHITE) { if (currentColor != color) { if (drawing) { end() } currentColor.set(color) program.setUniform(uniColor, color) } if (currentTexture != texture) { if (drawing) { end() } texture.bind() currentTexture = texture } if (vertices.remaining() < 8 * 6) { /* We need more space in the buffer, so flush it */ flush() } if (!drawing) { begin() } // Add the two triangles which make up our rectangle vertices.put(x1).put(y1).put(s1).put(t1) vertices.put(x1).put(y2).put(s1).put(t2) vertices.put(x2).put(y2).put(s2).put(t2) vertices.put(x1).put(y1).put(s1).put(t1) vertices.put(x2).put(y2).put(s2).put(t2) vertices.put(x2).put(y1).put(s2).put(t1) numVertices += 6 // While tinkering, I'm ALWAYS flushing! // flush() } fun delete() { MemoryUtil.memFree(vertices) vertexBuffer.delete() program.delete() } }
gpl-3.0
64f713e73df574c2013e30d4be49e33f
30.348548
163
0.625017
4.319611
false
false
false
false
luxons/seven-wonders
sw-server/src/test/kotlin/org/luxons/sevenwonders/server/repositories/PlayerRepositoryTest.kt
1
2146
package org.luxons.sevenwonders.server.repositories import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertSame import kotlin.test.assertTrue class PlayerRepositoryTest { private lateinit var repository: PlayerRepository @Before fun setUp() { repository = PlayerRepository() } @Test fun contains_falseIfNoUserAdded() { assertFalse(repository.contains("anyUsername")) } @Test fun contains_trueForCreatedPlayer() { repository.createOrUpdate("player1", "Player 1") assertTrue(repository.contains("player1")) } @Test fun createOrUpdate_createsProperly() { val player1 = repository.createOrUpdate("player1", "Player 1") assertEquals("player1", player1.username) assertEquals("Player 1", player1.displayName) } @Test fun createOrUpdate_updatesDisplayName() { val player1 = repository.createOrUpdate("player1", "Player 1") val player1Updated = repository.createOrUpdate("player1", "Much Better Name") assertSame(player1, player1Updated) assertEquals("Much Better Name", player1Updated.displayName) } @Test fun find_failsOnUnknownUsername() { assertFailsWith<PlayerNotFoundException> { repository.find("anyUsername") } } @Test fun find_returnsTheSameObject() { val player1 = repository.createOrUpdate("player1", "Player 1") val player2 = repository.createOrUpdate("player2", "Player 2") assertSame(player1, repository.find("player1")) assertSame(player2, repository.find("player2")) } @Test fun remove_failsOnUnknownUsername() { assertFailsWith<PlayerNotFoundException> { repository.remove("anyUsername") } } @Test fun remove_succeeds() { repository.createOrUpdate("player1", "Player 1") assertTrue(repository.contains("player1")) repository.remove("player1") assertFalse(repository.contains("player1")) } }
mit
49aa313c0cadd1b0b2ddd9197661c124
27.613333
85
0.675676
4.615054
false
true
false
false
ujpv/intellij-rust
src/main/kotlin/org/rust/ide/surroundWith/expression/RustWithParenthesesSurrounder.kt
1
1060
package org.rust.ide.surroundWith.expression import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustExprElement import org.rust.lang.core.psi.RustParenExprElement import org.rust.lang.core.psi.RustPsiFactory class RustWithParenthesesSurrounder : RustExpressionSurrounderBase<RustParenExprElement>() { override fun getTemplateDescription(): String = "(expr)" override fun createTemplate(project: Project): RustParenExprElement = RustPsiFactory(project).createExpression("(a)") as RustParenExprElement override fun getWrappedExpression(expression: RustParenExprElement): RustExprElement = expression.expr override fun isApplicable(expression: RustExprElement): Boolean = true override fun doPostprocessAndGetSelectionRange(editor: Editor, expression: PsiElement): TextRange { val offset = expression.textRange.endOffset return TextRange.from(offset, 0) } }
mit
6a83bf22226821ee508d0f23605630df
39.769231
103
0.79434
4.840183
false
false
false
false
ujpv/intellij-rust
src/test/kotlin/org/rust/ide/inspections/RustInspectionsTestBase.kt
1
1459
package org.rust.ide.inspections import com.intellij.codeInspection.LocalInspectionTool import org.rust.lang.RustTestCaseBase abstract class RustInspectionsTestBase(val useStdLib: Boolean = false) : RustTestCaseBase() { override val dataPath = "" override fun getProjectDescriptor() = if (useStdLib) WithStdlibRustProjectDescriptor else super.getProjectDescriptor() protected inline fun<reified T : LocalInspectionTool> enableInspection() = myFixture.enableInspections(T::class.java) protected inline fun <reified T : LocalInspectionTool> doTest() { enableInspection<T>() myFixture.testHighlighting(true, false, true, fileName) } protected inline fun <reified T : LocalInspectionTool> checkByText(text: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false) { myFixture.configureByText("main.rs", text) enableInspection<T>() myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) } protected inline fun <reified T: LocalInspectionTool> checkFixByText(fixName: String, before: String, after: String, checkWarn: Boolean = true, checkInfo: Boolean = false, checkWeakWarn: Boolean = false) { myFixture.configureByText("main.rs", before) enableInspection<T>() myFixture.checkHighlighting(checkWarn, checkInfo, checkWeakWarn) applyQuickFix(fixName) myFixture.checkResult(after) } }
mit
ea8ab35c6549841495a758af6205c1a9
41.911765
209
0.736806
4.895973
false
true
false
false
lunabox/leetcode
kotlin/problems/src/solution/NumberProblems.kt
1
35791
package solution import java.math.BigInteger import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet import kotlin.math.* class NumberProblems { /** * https://leetcode-cn.com/problems/k-diff-pairs-in-an-array/ * 给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k */ fun findPairs(nums: IntArray, k: Int): Int { if (k < 0) { return 0 } val view = HashSet<Int>() val diff = HashSet<Int>() nums.forEach { if (view.contains(it + k)) { diff.add(it + k) } if (view.contains(it - k)) { diff.add(it) } view.add(it) } return diff.size } /** * https://leetcode-cn.com/problems/diet-plan-performance/ */ fun dietPlanPerformance(calories: IntArray, k: Int, lower: Int, upper: Int): Int { var s = 0 var score = 0 repeat(k) { s += calories[it] } repeat(calories.size - k + 1) { when { s < lower -> score-- s > upper -> score++ } if (it + k < calories.size) { s = s - calories[it] + calories[it + k] } } return score } fun maxCount(m: Int, n: Int, ops: Array<IntArray>): Int { var mm = m var nn = n ops.forEach { mm = min(mm, it[0]) nn = min(nn, it[1]) } return mm * nn } /** * https://leetcode-cn.com/problems/can-place-flowers/ */ fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean { var count = 0 repeat(flowerbed.size) { if (it == 0) { if ((flowerbed.size > 1 && flowerbed[0] == 0 && flowerbed[1] == 0) || (flowerbed.size == 1 && flowerbed[0] == 0)) { count++ flowerbed[it] = 1 } } else if (it == flowerbed.size - 1) { if (flowerbed[it] == 0 && flowerbed[it - 1] == 0) { count++ flowerbed[it] = 1 } } else if (flowerbed[it] == 0 && flowerbed[it - 1] == 0 && flowerbed[it + 1] == 0) { count++ flowerbed[it] = 1 } if (count >= n) { return true } } return count >= n } /** * https://leetcode-cn.com/problems/asteroid-collision/ * 对于数组中的每一个元素,其绝对值表示行星的大小,正负表示行星的移动方向(正表示向右移动,负表示向左移动)。每一颗行星以相同的速度移动。 * 找出碰撞后剩下的所有行星。碰撞规则:两个行星相互碰撞,较小的行星会爆炸。如果两颗行星大小相同,则两颗行星都会爆炸。两颗移动方向相同的行星,永远不会发生碰撞。 */ fun asteroidCollision(asteroids: IntArray): IntArray { val list = asteroids.toMutableList() var i = 0 while (i < list.size - 1) { if (list[i] > 0 && list[i + 1] < 0) { when { list[i] + list[i + 1] > 0 -> { list.removeAt(i + 1) } list[i] + list[i + 1] == 0 -> { list.removeAt(i) list.removeAt(i) i = if (i == 0) 0 else i - 1 } else -> { list.removeAt(i) i = if (i == 0) 0 else i - 1 } } } else { i++ } } return list.toIntArray() } /** * https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/ */ fun findMin(nums: IntArray): Int { return nums.min()!! } /** * https://leetcode-cn.com/problems/search-in-rotated-sorted-array/ */ fun search(nums: IntArray, target: Int): Boolean { return nums.indexOf(target) >= 0 } /** * https://leetcode-cn.com/problems/compare-version-numbers/ */ fun compareVersion(version1: String, version2: String): Int { val v1 = version1.split(".") val v2 = version2.split(".") repeat(max(v1.size, v2.size)) { val subVersion1 = if (it < v1.size) v1[it].toInt() else 0 val subVersion2 = if (it < v2.size) v2[it].toInt() else 0 when { subVersion1 > subVersion2 -> return 1 subVersion1 < subVersion2 -> return -1 else -> return@repeat } } return 0 } /** * https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60/ */ fun numPairsDivisibleBy60(time: IntArray): Int { val count = IntArray(60) var sum = 0 time.map { val value = it % 60 count[value]++ value }.forEach { if (it != 0 && it != 30) { sum += count[60 - it] } } // 上面除了0和30之外,都计算了两次,成对出现,需要去掉一半 sum /= 2 // 0 sum += if (count[0] > 1) count[0] * (count[0] - 1) / 2 else 0 // 30 sum += if (count[30] > 1) count[30] * (count[30] - 1) / 2 else 0 return sum } /** * https://leetcode-cn.com/problems/product-of-array-except-self/ * 给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 */ fun productExceptSelf(nums: IntArray): IntArray { val left = IntArray(nums.size) { 1 } val right = IntArray(nums.size) { 1 } val result = IntArray(nums.size) for (i in 1 until nums.size) { left[i] = left[i - 1] * nums[i - 1] } for (i in nums.size - 2 downTo 0) { right[i] = right[i + 1] * nums[i + 1] } for (i in nums.indices) { result[i] = left[i] * right[i] } return result } /** * https://leetcode-cn.com/problems/array-partition-i/ * 给定长度为 2n 的数组, 你的任务是将这些数分成 n 对, 例如 (a1, b1), (a2, b2), ..., (an, bn) ,使得从1 到 n 的 min(ai, bi) 总和最大 */ fun arrayPairSum(nums: IntArray): Int { var sum = 0 nums.sort() for (i in nums.indices step 2) { sum += nums[i] } return sum } /** * https://leetcode-cn.com/problems/maximum-product-of-three-numbers/ */ fun maximumProduct(nums: IntArray): Int { nums.sort() if (nums[0] < 0 && nums[1] < 0) { val a = nums[0] * nums[1] * nums.last() val b = nums[nums.size - 3] * nums[nums.size - 2] * nums[nums.size - 1] return if (a > b) a else b } return nums[nums.size - 3] * nums[nums.size - 2] * nums[nums.size - 1] } /** * https://leetcode-cn.com/problems/merge-intervals/ * 给出一个区间的集合,请合并所有重叠的区间 */ fun merge(intervals: Array<IntArray>): Array<IntArray> { val result = ArrayList<IntArray>() intervals.sortBy { it[0] } intervals.forEach { if (result.isNotEmpty() && result.last()[1] >= it[0]) { if (result.last()[1] <= it[1]) { result.last()[1] = it[1] } } else { result.add(it) } } val array = Array(result.size) { intArrayOf() } return result.toArray(array) } /** * https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/ */ fun findUnsortedSubarray(nums: IntArray): Int { var left = 0 var right = nums.size - 1 var minValue = -1 var maxValue = -1 for (i in nums.indices) { if (i == 0) { maxValue = nums[i] } else { if (maxValue > nums[i]) { left = i } maxValue = max(maxValue, nums[i]) } } for (i in nums.size - 1 downTo 0) { if (i == nums.lastIndex) { minValue = nums.last() } else { if (minValue < nums[i]) { right = i } minValue = min(minValue, nums[i]) } } return if (left - right + 1 > 0) left - right + 1 else 0 } /** * https://leetcode-cn.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer/ */ fun subtractProductAndSum(n: Int): Int { var num = n var multi = 1 var sum = 0 while (num != 0) { val last = num % 10 multi *= last sum += last num /= 10 } return multi - sum } /** * https://leetcode-cn.com/problems/sum-of-square-numbers/ */ fun judgeSquareSum(c: Int): Boolean { var i = 0 var j = sqrt(c.toDouble()).toInt() while (i <= j) { val r = i * i + j * j when { r == c -> return true r < c -> i++ r > c -> j-- } } return false } /** * https://leetcode-cn.com/problems/non-decreasing-array/ */ fun checkPossibility(nums: IntArray): Boolean { var change = 0 if (nums.size > 1 && nums[0] > nums[1]) { nums[0] = nums[1] change++ } for (i in 1 until nums.lastIndex) { if (nums[i] <= nums[i + 1]) { continue } change++ if (change >= 2) { return false } if (nums[i - 1] > nums[i + 1]) { nums[i + 1] = nums[i] } else { nums[i] = nums[i - 1] } } return true } /** * 你正在和你的朋友玩 猜数字(Bulls and Cows)游戏:你写下一个数字让你的朋友猜。每次他猜测后,你给他一个提示,告诉他有多少位数字和确切位置都猜对了(称为“Bulls”, 公牛),有多少位数字猜对了但是位置不对(称为“Cows”, 奶牛)。你的朋友将会根据提示继续猜,直到猜出秘密数字。 * 请写出一个根据秘密数字和朋友的猜测数返回提示的函数,用 A 表示公牛,用 B 表示奶牛。 * 请注意秘密数字和朋友的猜测数都可能含有重复数字。 */ fun getHint(secret: String, guess: String): String { if (secret.isBlank() || guess.isBlank()) { return "0A0B" } var a = 0 var b = 0 val nums = IntArray(10) val flags = IntArray(secret.length) secret.forEach { nums[it.toInt() - '0'.toInt()]++ } secret.forEachIndexed { index, c -> if (c == guess[index]) { a++ nums[c.toInt() - '0'.toInt()]-- flags[index]++ } } guess.forEachIndexed { index, c -> if (flags[index] == 0 && nums[c.toInt() - '0'.toInt()] > 0) { b++ nums[c.toInt() - '0'.toInt()]-- } } return "${a}A${b}B" } /** * https://leetcode-cn.com/problems/maximum-average-subarray-i/ */ fun findMaxAverage(nums: IntArray, k: Int): Double { var s = nums.filterIndexed { index, _ -> index < k }.sum() var m = s for (i in k until nums.size) { s += nums[i] s -= nums[i - k] m = if (s > m) s else m } return m.toDouble() / k.toDouble() } fun findLengthOfLCIS(nums: IntArray): Int { var cur = Int.MIN_VALUE var curLength = 0 var maxLength = 0 nums.forEach { if (it > cur) { curLength++ } else { curLength = 1 } cur = it if (curLength > maxLength) { maxLength = curLength } } return maxLength } /** * https://leetcode-cn.com/problems/binary-number-with-alternating-bits/ */ fun hasAlternatingBits(n: Int): Boolean { val m = n.xor(n.shr(1)) return m.and(m + 1) == 0 } /** * https://leetcode-cn.com/problems/duplicate-zeros/ */ fun duplicateZeros(arr: IntArray): Unit { var i = 0 while (i < arr.size) { if (arr[i] != 0) { i++ continue } for (j in arr.size - 1 downTo i + 1) { arr[j] = arr[j - 1] } if (i + 1 < arr.size) { arr[i + 1] = 0 } i += 2 } } /** * https://leetcode-cn.com/problems/next-permutation/ */ fun nextPermutation(nums: IntArray): Unit { var n: Int = -1 for (i in nums.lastIndex downTo 1) { if (nums[i - 1] < nums[i]) { n = i - 1 break } } if (n == -1) { nums.sort() } else { var m: Int = nums.lastIndex for (j in n + 1 until nums.size) { if (nums[j] <= nums[n]) { // find just larger than nums[n] m = j - 1 break } } // swap m and n val temp = nums[n] nums[n] = nums[m] nums[m] = temp // reverse nums.slice(IntRange(n + 1, nums.lastIndex)).reversed().forEachIndexed { index, i -> nums[n + index + 1] = i } } } /** * https://leetcode-cn.com/problems/permutations/ */ fun permute(nums: IntArray): List<List<Int>> { val result = ArrayList<List<Int>>() permuteItem(result, nums, 0) return result } private fun permuteItem(result: MutableList<List<Int>>, nums: IntArray, index: Int) { if (index == nums.lastIndex) { result.add(nums.toList()) } else { for (i in index until nums.size) { swap(nums, index, i) permuteItem(result, nums, index + 1) swap(nums, index, i) } } } private fun swap(nums: IntArray, i: Int, j: Int) { if (i != j) { val temp = nums[i] nums[i] = nums[j] nums[j] = temp } } /** * https://leetcode-cn.com/problems/degree-of-an-array/ */ fun findShortestSubArray(nums: IntArray): Int { val left = HashMap<Int, Int>() val right = HashMap<Int, Int>() val countItem = HashMap<Int, Int>() nums.forEachIndexed { index, i -> if (i !in left.keys) { left[i] = index } right[i] = index countItem[i] = countItem.getOrDefault(i, 0) + 1 } var ins = nums.size val degree = countItem.values.max() countItem.filterValues { it == degree }.forEach { if (right[it.key]!! - left[it.key]!! + 1 < ins) { ins = right[it.key]!! - left[it.key]!! + 1 } } return ins } /** * https://leetcode-cn.com/problems/find-pivot-index/ */ fun pivotIndex(nums: IntArray): Int { val arraySum = nums.sum() var leftSum = 0 nums.forEachIndexed { index, i -> if (leftSum == arraySum - i - leftSum) { return index } leftSum += i } return -1 } /** * https://leetcode-cn.com/problems/subsets/ */ fun subsets(nums: IntArray): List<List<Int>> { val result = mutableListOf<List<Int>>() dfsSubSets(nums, IntArray(nums.size), 0, result) return result } private fun dfsSubSets(nums: IntArray, flag: IntArray, index: Int, result: MutableList<List<Int>>) { if (index > nums.lastIndex) { result.add(nums.filterIndexed { m, _ -> flag[m] == 1 }.toList()) return } flag[index] = 0 dfsSubSets(nums, flag, index + 1, result) flag[index] = 1 dfsSubSets(nums, flag, index + 1, result) } /** * https://leetcode-cn.com/problems/self-dividing-numbers/ */ fun selfDividingNumbers(left: Int, right: Int): List<Int> { return (left..right).filter { checkSelfNumber(it) } } private fun checkSelfNumber(n: Int): Boolean { n.toString().map { it.toInt() - '0'.toInt() }.forEach { if (it == 0 || n % it != 0) { return false } } return true } /** * https://leetcode-cn.com/problems/set-mismatch/ */ fun findErrorNums(nums: IntArray): IntArray { val result = IntArray(2) if (nums.isEmpty()) { return result } for (i in nums.indices) { if (nums[abs(nums[i]) - 1] < 0) { result[0] = abs(nums[i]) } else { nums[abs(nums[i]) - 1] *= -1 } } nums.forEachIndexed missing@{ index, i -> if (i > 0) { result[1] = index + 1 return@missing } } return result } /** * https://leetcode-cn.com/problems/rotated-digits/ */ fun rotatedDigits(N: Int): Int { var count = 0 repeat(N) N@{ val n = (it + 1).toString().toCharArray() n.forEachIndexed check@{ index, c -> when (c.toInt() - '0'.toInt()) { 0, 1, 8 -> return@check 2 -> n[index] = '5' 5 -> n[index] = '2' 6 -> n[index] = '9' 9 -> n[index] = '6' else -> return@N } } if (String(n).toInt() != it + 1) { count++ } } return count } /** * https://leetcode-cn.com/problems/find-lucky-integer-in-an-array/ */ fun findLucky(arr: IntArray): Int { val n = arr.sorted().reversed() var current = n[0] var count = 1 for (i in 1..n.lastIndex) { if (n[i] == current) { count++ } else { if (count == current) { return current } current = n[i] count = 1 } } return if (count == current) current else -1 } /** * https://leetcode-cn.com/problems/cells-with-odd-values-in-a-matrix/ */ fun oddCells(n: Int, m: Int, indices: Array<IntArray>): Int { val data = Array(n) { IntArray(m) { 0 } } indices.forEach { loc -> repeat(m) { data[loc[0]][it]++ } repeat(n) { data[it][loc[1]]++ } } var count = 0 for (i in 0 until n) { for (j in 0 until m) { if (data[i][j] % 2 == 1) { count++ } } } return count } /** * https://leetcode-cn.com/problems/string-to-integer-atoi/ */ fun myAtoi(str: String): Int { var s = str.trim() if (s.isEmpty()) { return 0 } if (s[0] != '+' && s[0] != '-' && !s[0].isDigit()) { return 0 } val nav = if (s[0] == '+' || s[0].isDigit()) 1L else -1L s = if (s[0] == '-' || s[0] == '+') s.substring(1) else s if (s.isEmpty() || !s[0].isDigit()) { return 0 } var index = s.lastIndex for (i in s.indices) { if (!s[i].isDigit()) { break } index = i } return try { val r = s.substring(0, index + 1).toBigInteger().multiply(BigInteger.valueOf(nav)) when { r > BigInteger.valueOf(Int.MAX_VALUE.toLong()) -> { Int.MAX_VALUE } r < BigInteger.valueOf(Int.MIN_VALUE.toLong()) -> { Int.MIN_VALUE } else -> { r.toInt() } } } catch (e: Exception) { 0 } } /** * 双周赛 */ fun countLargestGroup(n: Int): Int { val count = IntArray(36) { 0 } for (i in 1..n) { var sum = 0 i.toString().forEach { sum += it - '0' } if (sum > 0) { count[sum - 1]++ } } val m = count.max() var result = 0 count.forEach { if (it == m) { result++ } } return result } /** * https://leetcode-cn.com/problems/number-of-steps-to-reduce-a-number-in-binary-representation-to-one/ */ fun numSteps(s: String): Int { var binNum = BigInteger(s, 2) var count = 0 val one = BigInteger.valueOf(1L) while (binNum > one) { if (binNum.and(one) == one) { binNum++ } else { binNum = binNum.shr(1) } count++ } return count } /** * https://leetcode-cn.com/problems/minimum-subsequence-in-non-increasing-order/ */ fun minSubsequence(nums: IntArray): List<Int> { val numSum = nums.sum() var subSum = 0 val result = mutableListOf<Int>() nums.sorted().reversed().forEach { subSum += it result.add(it) if (subSum > numSum - subSum) { return result.sorted().reversed() } } return result } fun multiply(num1: String, num2: String): String { val result = StringBuffer() val n1 = num1.reversed() val n2 = num2.reversed() val addNum: (StringBuffer, StringBuffer) -> Unit = { result, s -> var addCarry = 0 s.map { it - '0' }.forEachIndexed { index, c -> if (index < result.length) { val m = (result[index] - '0' + c + addCarry) addCarry = m / 10 result.setCharAt(index, ((m % 10) + '0'.toInt()).toChar()) } else { val m = c + addCarry addCarry = m / 10 result.append(m % 10) } } if (addCarry > 0) { result.append(addCarry) } } n1.map { it - '0' }.forEachIndexed { i, n -> val lineBuffer = StringBuffer() var carry = 0 repeat(i) { lineBuffer.append(0) } n2.map { it - '0' }.forEach { m -> val s = n * m + carry carry = s / 10 lineBuffer.append(s % 10) } if (carry > 0) { lineBuffer.append(carry) } addNum(result, lineBuffer) } if (result.count { it == '0' } == result.length) { return "0" } return result.reverse().toString() } fun rotate(matrix: Array<IntArray>): Unit { var temp = 0 val n = matrix.size for (i in 0 until n / 2) { for (j in i until n - i - 1) { temp = matrix[i][j] matrix[i][j] = matrix[n - j - 1][i] matrix[n - j - 1][i] = matrix[n - 1 - i][n - j - 1] matrix[n - 1 - i][n - j - 1] = matrix[j][n - 1 - i] matrix[j][n - 1 - i] = temp } } } /** * https://leetcode-cn.com/problems/search-a-2d-matrix/ */ fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean { matrix.forEach { if (it.isNotEmpty() && target <= it.last()) { val index = it.indexOf(target) if (index >= 0) { return true } } } return false } /** * https://leetcode-cn.com/problems/single-number-ii/ */ fun singleNumber(nums: IntArray): Int { val set = HashSet<Long>() var sum = 0L nums.forEach { set.add(it.toLong()) sum += it } return ((3 * set.sum() - sum) / 2).toInt() } /** * https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/ */ fun majorityElement(nums: IntArray): Int { var vote = 0 var target = 0 nums.forEach { if (vote == 0) { target = it } vote += if (it == target) 1 else -1 } return if (nums.count { it == target } > nums.size / 2) target else 0 } fun processQueries(queries: IntArray, m: Int): IntArray { val ans = IntArray(queries.size) val p = ArrayList<Int>(m) repeat(m) { p.add(it + 1) } queries.forEachIndexed { index, i -> val pos = p.indexOf(i) if (pos >= 0) { ans[index] = pos p.removeAt(pos) p.add(0, i) } } return ans } /** * https://leetcode-cn.com/problems/number-of-ways-to-paint-n-x-3-grid/ */ fun numOfWays(n: Int): Int { var a = 6L var b = 6L repeat(n - 1) { val tempA = 3 * a + 2 * b b = (2 * a + 2 * b) % 1000000007L a = tempA % 1000000007L } return ((a + b) % 1000000007L).toInt() } /** * https://leetcode-cn.com/problems/missing-number-lcci/ */ fun missingNumber(nums: IntArray): Int { return nums.size * (nums.size + 1) / 2 - nums.sum() } /** * https://leetcode-cn.com/problems/er-wei-shu-zu-zhong-de-cha-zhao-lcof/ */ fun findNumberIn2DArray(matrix: Array<IntArray>, target: Int): Boolean { if (matrix.isEmpty() || matrix[0].isEmpty()) { return false } var row = 0 var col = matrix[0].lastIndex while (row < matrix.size && col >= 0) { when { target == matrix[row][col] -> return true target > matrix[row][col] -> row++ else -> col-- } } return false } /** * https://leetcode-cn.com/problems/jump-game/ */ fun canJump(nums: IntArray): Boolean { var step = 0 nums.forEachIndexed { index, i -> step = if (index == 0) { i } else { max(step - 1, i) } if (step == 0 && index < nums.lastIndex) { return false } } return step >= 0 } /** * https://leetcode-cn.com/contest/biweekly-contest-24/problems/minimum-value-to-get-positive-step-by-step-sum/ */ fun minStartValue(nums: IntArray): Int { var m = Int.MAX_VALUE var sum = 0 nums.forEach { sum += it if (sum < m) { m = sum } } return if (m < 0) 1 - m else 1 } /** * https://leetcode-cn.com/contest/biweekly-contest-24/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/ */ fun findMinFibonacciNumbers(k: Int): Int { val fibonacci = mutableListOf<Int>() var a = 1 var b = 1 fibonacci.add(a) fibonacci.add(b) while (fibonacci.last() < k) { val n = a + b fibonacci.add(n) a = b b = n } var count = 0 var sum = k for (i in fibonacci.lastIndex downTo 0) { if (fibonacci[i] <= sum) { sum -= fibonacci[i] count++ if (sum == 0) { return count } } } return count } /** * https://leetcode-cn.com/problems/1-bit-and-2-bit-characters/ */ fun isOneBitCharacter(bits: IntArray): Boolean { var index = 0 while (index < bits.size) { if (index == bits.lastIndex && bits[index] == 0) { return true } when (bits[index]) { 0 -> index++ 1 -> index += 2 } } return false } /** * https://leetcode-cn.com/problems/largest-number-at-least-twice-of-others/ */ fun dominantIndex(nums: IntArray): Int { var maxNum = 0 var maxIndex = 0 nums.forEachIndexed { index, i -> if (i > maxNum) { maxNum = i maxIndex = index } } nums.forEachIndexed { index, i -> if (index != maxIndex && i * 2 > maxNum) { return -1 } } return maxIndex } /** * https://leetcode-cn.com/problems/lucky-numbers-in-a-matrix/ */ fun luckyNumbers(matrix: Array<IntArray>): List<Int> { val ans = mutableListOf<Int>() val minNumberIndex = IntArray(matrix.size) matrix.forEachIndexed { index, ints -> var m = Int.MAX_VALUE ints.forEachIndexed { j, n -> if (n < m) { m = n minNumberIndex[index] = j } } } minNumberIndex.forEachIndexed { index, i -> for (j in matrix.indices) { if (matrix[j][i] > matrix[index][i]) { return@forEachIndexed } } ans.add(matrix[index][i]) } return ans } /** * https://leetcode-cn.com/problems/sort-array-by-parity-ii/ */ fun sortArrayByParityII(A: IntArray): IntArray { var even = 0 var odd = 1 while (odd < A.size || even < A.size) { while (even < A.size && A[even] % 2 == 0) { even += 2 } while (odd < A.size && A[odd] % 2 == 1) { odd += 2 } if (odd < A.size && even < A.size) { val temp = A[odd] A[odd] = A[even] A[even] = temp } } return A } /** * https://leetcode-cn.com/problems/relative-sort-array/ */ fun relativeSortArray(arr1: IntArray, arr2: IntArray): IntArray { val ans = mutableListOf<Int>() val nums = IntArray(1001) { 0 } arr1.forEach { nums[it]++ } arr2.forEach { while (nums[it] != 0) { nums[it]-- ans.add(it) } } for (i in 1..1000) { while (nums[i] != 0) { nums[i]-- ans.add(i) } } return ans.toIntArray() } /** * https://leetcode-cn.com/problems/squares-of-a-sorted-array/ */ fun sortedSquares(A: IntArray): IntArray { val ans = IntArray(A.size) val positive = A.filter { it >= 0 }.map { it * it } var right = 0 val negative = A.filter { it < 0 }.map { it * it } var left = negative.size - 1 for (i in ans.indices) { ans[i] = when { right == positive.size -> negative[left--] left == -1 -> positive[right++] positive[right] >= negative[left] -> negative[left--] else -> positive[right++] } } return ans } /** * https://leetcode-cn.com/problems/sum-of-even-numbers-after-queries/ * 暴力会超时 */ fun sumEvenAfterQueries(A: IntArray, queries: Array<IntArray>): IntArray { val ans = IntArray(queries.size) var base = A.filter { it % 2 == 0 }.sum() queries.forEachIndexed { index, ints -> val before = A[ints[1]] A[ints[1]] += ints[0] val after = A[ints[1]] if (before % 2 == 0) { // 偶数 if (after % 2 == 0) { ans[index] = base - before + after } else { ans[index] = base - before } } else if (after % 2 == 0) { ans[index] = base + after } else { ans[index] = base } base = ans[index] } return ans } /** * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ */ fun searchRange(nums: IntArray, target: Int): IntArray { var left = 0 var right = nums.lastIndex var mid: Int var index = -1 while (left <= right) { mid = (left + right) / 2 if (nums[mid] > target) { right = mid - 1 } else if (nums[mid] < target) { left = mid + 1 } else { index = mid break } } if (index > -1) { left = index while (left >= 0 && nums[left] == target) { left-- } if (left == -1) { left = 0 } else { left++ } right = index while (right < nums.size && nums[right] == target) { right++ } if (right == nums.size) { right = nums.lastIndex } else { right-- } return intArrayOf(left, right) } return intArrayOf(-1, -1) } /** * https://leetcode-cn.com/problems/powerful-integers/ */ fun powerfulIntegers(x: Int, y: Int, bound: Int): List<Int> { val ans = HashSet<Int>() for (i in 0 until 20) { for (j in 0 until 20) { val n = x.toDouble().pow(i) + y.toDouble().pow(j) if (n <= bound) { ans.add(n.toInt()) } } } return ans.toList() } /** * https://leetcode-cn.com/problems/sliding-window-maximum/ */ fun maxSlidingWindow(nums: IntArray, k: Int): IntArray { val queueIndex = LinkedList<Int>() val ans = IntArray(nums.size - k + 1) nums.forEachIndexed { index, i -> while (queueIndex.isNotEmpty() && nums[queueIndex.last] < i) { queueIndex.removeLast() } queueIndex.addLast(index) if (queueIndex.first == index - k) { queueIndex.removeFirst() } if (index >= k - 1) { ans[index - k + 1] = nums[queueIndex.first] } } return ans } }
apache-2.0
4f059deda35464db73470778de8c4ee2
27.521346
155
0.433819
3.802737
false
false
false
false
Quireg/AnotherMovieApp
app/src/main/java/com/anothermovieapp/view/PopularMoviesGridViewFragment.kt
1
2512
/* * Created by Arcturus Mengsk * 2021. */ package com.anothermovieapp.view import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.anothermovieapp.R import com.anothermovieapp.common.Constants import com.anothermovieapp.common.GeneralUtils import com.anothermovieapp.repository.Status import com.anothermovieapp.viewmodel.ViewModelPopularMovies import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class PopularMoviesGridViewFragment : MoviesGridViewFragment() { override var isFetchInProgress = false override var currentPosition: Long = 0 override var totalItems: Long = 0 override var mFragmentTag: String = Constants.POPULAR override var isEmptyData = true @Inject lateinit var viewModel: ViewModelPopularMovies override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mLoadingView?.visibility = View.VISIBLE viewModel.popularMovies.observe(viewLifecycleOwner) { isEmptyData = it.data == null || it.data.isEmpty() it.data?.sortedBy { movie -> movie.popularity } mLoadingView?.visibility = if (it.data == null) View.VISIBLE else View.GONE mListRecyclerViewAdapter?.setData(it.data) isFetchInProgress = it.status == Status.LOADING if (isResumed) { updateProgressBarVisibility() updateAdapterInfoTextView() } if (it.status == Status.ERROR) { GeneralUtils.showToastMessage( requireContext(), getString(R.string.error_fetch_failed) ) } } viewModel.popularMoviesTotalAmount.observe(viewLifecycleOwner) { totalItems = it if (isResumed) { updateAdapterInfoTextView() } } } override fun onResume() { super.onResume() val activity = activity as AppCompatActivity activity.supportActionBar?.title = requireContext().resources.getString(R.string.popular_tab_name) updateAdapterInfoTextView() } override fun fetchNewItems() { if (isFetchInProgress) { return } updateProgressBarVisibility() viewModel.fetchMore() } override fun reload() { currentPosition = 0L viewModel.reload() } }
mit
b2e106cda372c633f1868367a55c9cf2
31.217949
87
0.655653
5.168724
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/simulation/Simulation.kt
1
891
package xyz.jmullin.drifter.simulation import xyz.jmullin.drifter.entity.Entity2D import xyz.jmullin.drifter.entity.EntityContainer2D import xyz.jmullin.drifter.extensions.FloatMath class Simulation<T : Simulated<T>>(val minStepSize: Float, _entities: List<T> = emptyList()) : Entity2D() { var entities = _entities override fun create(container: EntityContainer2D) { depth = Float.MIN_VALUE super.create(container) } override fun update(delta: Float) { var stepped = 0f val stepSize = minStepSize //FloatMath.max(minStepSize, entities.minBy { it.maxStepSize }?.maxStepSize ?: 0f) entities.forEach { it.beforeStep(entities) } while(stepped < delta) { entities.forEach { it.simulate(stepSize, entities.filter { it.interactive }) } stepped += stepSize } super.update(delta) } }
mit
f3c011422c82a088c657d1922a7c2b33
28.733333
117
0.673401
3.977679
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/fun/GiveawayCommand.kt
1
1836
package net.perfectdreams.loritta.morenitta.commands.vanilla.`fun` import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.Permission import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordAbstractCommandBase import java.awt.Color class GiveawayCommand(loritta: LorittaBot) : DiscordAbstractCommandBase(loritta, listOf("giveaway", "sorteio"), net.perfectdreams.loritta.common.commands.CommandCategory.FUN) { companion object { private const val LOCALE_PREFIX = "commands.command" } override fun command() = create { userRequiredPermissions = listOf(Permission.MESSAGE_MANAGE) canUseInPrivateChannel = false localizedDescription("$LOCALE_PREFIX.giveawaymenu.description") executesDiscord { val context = this val embed = EmbedBuilder() .setTitle("\uD83C\uDF89 ${locale["commands.command.giveawaymenu.categoryTitle"]}") .setThumbnail("https://loritta.website/assets/img/loritta_confetti.png") .setDescription("*${locale["commands.command.giveawaymenu.categoryDescription"]}*\n\n") .setColor(Color(200, 20, 217)) val commands = listOf( GiveawaySetupCommand(loritta), GiveawayEndCommand(loritta), GiveawayRerollCommand(loritta) ) for (cmd in commands) { val toBeAdded = run { val usage = cmd.command().usage.build(context.locale) val usageWithinCodeBlocks = if (usage.isNotEmpty()) { "`$usage` " } else { "" } "**${context.serverConfig.commandPrefix}${cmd.labels.firstOrNull()}** $usageWithinCodeBlocks» ${cmd.command().description(loritta.localeManager.getLocaleById(context.serverConfig.localeId))}\n" } embed.appendDescription(toBeAdded) } context.sendMessage(context.getUserMention(true), embed.build()) } } }
agpl-3.0
ab9b844c0b01e0fa12c5f395bea33224
33
198
0.741689
3.895966
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/chat/pub/message/ChatViewModel.kt
1
8952
package me.proxer.app.chat.pub.message import com.gojuno.koptional.rxjava2.filterSome import com.gojuno.koptional.toOptional import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import me.proxer.app.base.PagedViewModel import me.proxer.app.util.ErrorUtils import me.proxer.app.util.data.ResettingMutableLiveData import me.proxer.app.util.extension.buildSingle import me.proxer.app.util.extension.subscribeAndLogErrors import me.proxer.app.util.extension.toParsedMessage import me.proxer.app.util.rx.RxRetryWithDelay import me.proxer.library.enums.ChatMessageAction import org.threeten.bp.Instant import java.util.Collections.emptyList import java.util.LinkedList import java.util.Queue import java.util.concurrent.TimeUnit /** * @author Ruben Gees */ class ChatViewModel(private val chatRoomId: String) : PagedViewModel<ParsedChatMessage>() { override val itemsOnPage = 50 override val dataSingle: Single<List<ParsedChatMessage>> get() = Single.fromCallable { validate() } .flatMap { api.chat.messages(chatRoomId) .messageId(data.value?.lastOrNull()?.id ?: "0") .buildSingle() } .map { it.map { message -> message.toParsedMessage() } } val sendMessageError = ResettingMutableLiveData<ErrorUtils.ErrorAction?>() val draft = ResettingMutableLiveData<String?>() private var pollingDisposable: Disposable? = null private var draftDisposable: Disposable? = null private val sendMessageQueue: Queue<ParsedChatMessage> = LinkedList() private val sentMessageIds = mutableSetOf<String>() private var sendMessageDisposable: Disposable? = null private var currentFirstId = "0" override fun onCleared() { draftDisposable?.dispose() pollingDisposable?.dispose() sendMessageDisposable?.dispose() draftDisposable = null pollingDisposable = null sendMessageDisposable = null super.onCleared() } override fun load() { dataDisposable?.dispose() dataDisposable = dataSingle .doAfterSuccess { newData -> hasReachedEnd = newData.size < itemsOnPage } .map { newData -> mergeNewDataWithExistingData(newData, data.value?.lastOrNull()?.id ?: "0") } .subscribeOn(Schedulers.io()) .doAfterTerminate { isRefreshing = false } .observeOn(AndroidSchedulers.mainThread()) .doOnSubscribe { refreshError.value = null error.value = null isLoading.value = true } .doOnSuccess { if (pollingDisposable == null) startPolling() } .doAfterTerminate { isLoading.value = false } .subscribeAndLogErrors( { currentFirstId = findFirstRemoteId(it) ?: "0" refreshError.value = null error.value = null data.value = it }, { if (data.value?.size ?: 0 > 0) { refreshError.value = ErrorUtils.handle(it) } else { error.value = ErrorUtils.handle(it) } } ) } fun loadDraft() { draftDisposable?.dispose() draftDisposable = Single.fromCallable { storageHelper.getMessageDraft(chatRoomId).toOptional() } .filterSome() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe { draft.value = it } } fun updateDraft(draft: String) { draftDisposable?.dispose() draftDisposable = Single .fromCallable { if (draft.isBlank()) { storageHelper.deleteMessageDraft(chatRoomId) } else { storageHelper.putMessageDraft(chatRoomId, draft) } } .subscribeOn(Schedulers.io()) .subscribe() } fun sendMessage(text: String) { storageHelper.user?.let { user -> val firstId = data.value?.firstOrNull()?.id?.toLong() val nextId = if (firstId == null || firstId >= 0) -1 else firstId - 1 val message = ParsedChatMessage( nextId.toString(), user.id, user.name, user.image, text, ChatMessageAction.NONE, Instant.now() ) data.value = listOf(message).plus(data.value ?: emptyList()) sendMessageQueue.offer(message) if (sendMessageDisposable?.isDisposed != false) { doSendMessages() } } } fun pausePolling() { pollingDisposable?.dispose() } fun resumePolling() { if (data.value != null) { startPolling(true) } } private fun mergeNewDataWithExistingData( newData: List<ParsedChatMessage>, currentId: String ): List<ParsedChatMessage> { val messageIdsToDelete = newData .filter { it.action == ChatMessageAction.REMOVE_MESSAGE } .flatMap { listOf(it.id, it.message) } val previousSentMessageIdAmount = sentMessageIds.size val existingUnsendMessages = data.value?.takeWhile { it.id.toLong() < 0 } ?: emptyList() sentMessageIds.removeAll(newData.map { it.id }) val result = data.value.let { existingData -> when (existingData) { null -> newData else -> when (currentId) { "0" -> newData + existingData .asSequence() .dropWhile { it.id.toLong() < 0 } .filter { oldItem -> newData.none { newItem -> oldItem.id == newItem.id } } .toList() else -> existingData .asSequence() .dropWhile { it.id.toLong() < 0 } .filter { oldItem -> newData.none { newItem -> oldItem.id == newItem.id } } .toList() + newData } } } val mergedResult = existingUnsendMessages.dropLast(previousSentMessageIdAmount - sentMessageIds.size) + result return when (messageIdsToDelete.isNotEmpty()) { true -> mergedResult.filterNot { it.id in messageIdsToDelete } false -> mergedResult } } private fun startPolling(immediate: Boolean = false) { pollingDisposable?.dispose() pollingDisposable = Single.fromCallable { validators.validateLogin() } .flatMap { api.chat.messages(chatRoomId).messageId("0").buildSingle() } .map { it.map { message -> message.toParsedMessage() } } .repeatWhen { it.concatMap { Flowable.timer(3, TimeUnit.SECONDS) } } .retryWhen { it.concatMap { Flowable.timer(3, TimeUnit.SECONDS) } } .map { newData -> mergeNewDataWithExistingData(newData, "0") } .let { if (!immediate) it.delaySubscription(3, TimeUnit.SECONDS) else it } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeAndLogErrors { val firstId = findFirstRemoteId(it) if (firstId != null && firstId != currentFirstId) { currentFirstId = firstId data.value = it } } } private fun doSendMessages() { sendMessageDisposable?.dispose() sendMessageQueue.poll()?.let { item -> sendMessageDisposable = Single.fromCallable { validators.validateLogin() } .flatMap { api.chat.sendMessage(chatRoomId, item.message).buildSingle() } .retryWhen(RxRetryWithDelay(2, 3_000)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeAndLogErrors( { id -> sentMessageIds.add(id) startPolling(true) doSendMessages() }, { data.value = data.value?.dropWhile { message -> message.id.toLong() < 0 } sendMessageQueue.clear() sendMessageError.value = ErrorUtils.handle(it) } ) } } private fun findFirstRemoteId(data: List<ParsedChatMessage>): String? { return data.dropWhile { it.id.toLong() < 0 }.firstOrNull()?.id } }
gpl-3.0
ae243d1dd806fb868718d86e1235a586
35.390244
118
0.562891
5.29078
false
false
false
false
zyyoona7/KExtensions
lib/src/main/java/com/zyyoona7/extensions/network.kt
1
5654
package com.zyyoona7.extensions import android.app.Fragment import android.content.Context import android.net.ConnectivityManager import android.net.NetworkInfo import android.support.annotation.RequiresPermission import android.telephony.TelephonyManager /** * Created by zyyoona7 on 2017/8/26. * 网络相关扩展函数 */ /* ---------- Context ---------- */ /** * 活动网络信息 * 需添加权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> */ val Context.networkInfo: NetworkInfo? @RequiresPermission(value = "android.permission.ACCESS_NETWORK_STATE") get() = connectivityManager?.activeNetworkInfo /** * 网络是否连接 * 需添加权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> * */ val Context.isNetworkConnected: Boolean get() = networkInfo?.isConnected ?: false /** * 判断/设置wifi是否打开 * 需添加权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> */ var Context.isWifiEnable: Boolean get() = wifiManager?.isWifiEnabled ?: false set(value) { @RequiresPermission(value = "android.permission.ACCESS_WIFI_STATE") wifiManager?.isWifiEnabled = value } /** * 是否是WiFi连接 * 需添加权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> */ val Context.isWifiConnected: Boolean get() = networkInfo?.type == ConnectivityManager.TYPE_WIFI /** * 是否是移动数据连接 * 需添加权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> */ val Context.isMobileConnected: Boolean get() = networkInfo?.type == ConnectivityManager.TYPE_MOBILE /** * 获取网络运营商名称 * 中国移动、中国联通、中国电信 */ val Context.networkOperatorName: String? get() = telephonyManager?.networkOperatorName /** * from https://github.com/Blankj/AndroidUtilCode/blob/master/utilcode/src/main/java/com/blankj/utilcode/util/NetworkUtils.java * 获取当前网络类型 * 需添加权限 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> * 16=NETWORK_TYPE_GSM 17=NETWORK_TYPE_TD_SCDMA 18=NETWORK_TYPE_IWLAN */ val Context.networkType: NetworkType get() { var type: NetworkType = NetworkType.NETWORK_NO val isAvailable: Boolean = networkInfo?.isAvailable ?: false if (!isAvailable) return type if (networkInfo!!.type == ConnectivityManager.TYPE_WIFI) { type = NetworkType.NETWORK_WIFI } else if (networkInfo!!.type == ConnectivityManager.TYPE_MOBILE) { when (networkInfo!!.subtype) { 16, TelephonyManager.NETWORK_TYPE_GPRS, TelephonyManager.NETWORK_TYPE_CDMA, TelephonyManager.NETWORK_TYPE_EDGE, TelephonyManager.NETWORK_TYPE_1xRTT, TelephonyManager.NETWORK_TYPE_IDEN -> type = NetworkType.NETWORK_2G 17, TelephonyManager.NETWORK_TYPE_EVDO_A, TelephonyManager.NETWORK_TYPE_UMTS, TelephonyManager.NETWORK_TYPE_EVDO_0, TelephonyManager.NETWORK_TYPE_HSDPA, TelephonyManager.NETWORK_TYPE_HSUPA, TelephonyManager.NETWORK_TYPE_HSPA, TelephonyManager.NETWORK_TYPE_EVDO_B, TelephonyManager.NETWORK_TYPE_EHRPD, TelephonyManager.NETWORK_TYPE_HSPAP -> type = NetworkType.NETWORK_3G 18, TelephonyManager.NETWORK_TYPE_LTE -> type = NetworkType.NETWORK_4G else -> { val subtypeName = networkInfo!!.subtypeName type = if (subtypeName.equals("TD-SCDMA", ignoreCase = true) || subtypeName.equals("WCDMA", ignoreCase = true) || subtypeName.equals("CDMA2000", ignoreCase = true)) { NetworkType.NETWORK_3G } else { NetworkType.NETWORK_UNKNOWN } } } } return type } /* ---------- Fragment ---------- */ val Fragment.networkInfo: NetworkInfo? get() = activity?.networkInfo val Fragment.isNetworkConnected: Boolean get() = activity?.isNetworkConnected ?: false var Fragment.isWifiEnable: Boolean get() = activity?.isWifiEnable ?: false set(value) { activity?.isWifiEnable = value } val Fragment.isWifiConnected: Boolean get() = activity?.isWifiConnected ?: false val Fragment.isMobileConnected: Boolean get() = activity?.isMobileConnected ?: false val Fragment.networkOperatorName: String? get() = activity?.networkOperatorName val Fragment.networkType: NetworkType get() = activity?.networkType ?: NetworkType.NETWORK_NO val android.support.v4.app.Fragment.networkInfo: NetworkInfo? get() = activity?.networkInfo val android.support.v4.app.Fragment.isNetworkConnected: Boolean get() = activity?.isNetworkConnected ?: false var android.support.v4.app.Fragment.isWifiEnable: Boolean get() = activity?.isWifiEnable ?: false set(value) { activity?.isWifiEnable = value } val android.support.v4.app.Fragment.isWifiConnected: Boolean get() = activity?.isWifiConnected ?: false val android.support.v4.app.Fragment.isMobileConnected: Boolean get() = activity?.isMobileConnected ?: false val android.support.v4.app.Fragment.networkOperatorName: String? get() = activity?.networkOperatorName val android.support.v4.app.Fragment.networkType: NetworkType get() = activity?.networkType ?: NetworkType.NETWORK_NO enum class NetworkType { NETWORK_WIFI, NETWORK_4G, NETWORK_3G, NETWORK_2G, NETWORK_UNKNOWN, NETWORK_NO }
apache-2.0
a6d00dec9391c15484b7d709bb978734
31.628743
131
0.681167
4.303318
false
false
false
false
jsargent7089/android
src/androidTest/java/com/nextcloud/client/account/RegisteredUserTest.kt
1
3931
/* * Nextcloud Android client application * * @author Chris Narkiewicz <[email protected]> * Copyright (C) 2020 Chris Narkiewicz * Copyright (C) 2020 Nextcloud GmbH * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.nextcloud.client.account import android.accounts.Account import android.net.Uri import android.os.Parcel import com.owncloud.android.lib.common.OwnCloudAccount import com.owncloud.android.lib.common.OwnCloudBasicCredentials import com.owncloud.android.lib.resources.status.OwnCloudVersion import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNotSame import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import java.net.URI class RegisteredUserTest { private companion object { fun buildTestUser(accountName: String): RegisteredUser { val uri = Uri.parse("https://nextcloud.localhost.localdomain") val credentials = OwnCloudBasicCredentials("user", "pass") val account = Account(accountName, "test-type") val ownCloudAccount = OwnCloudAccount(uri, credentials) val server = Server( uri = URI(uri.toString()), version = OwnCloudVersion.nextcloud_17 ) return RegisteredUser( account = account, ownCloudAccount = ownCloudAccount, server = server ) } } private lateinit var user: RegisteredUser @Before fun setUp() { user = buildTestUser("[email protected]") } @Test fun registeredUserImplementsParcelable() { // GIVEN // registered user instance // WHEN // instance is serialized into Parcel // instance is retrieved from Parcel val parcel = Parcel.obtain() parcel.setDataPosition(0) parcel.writeParcelable(user, 0) parcel.setDataPosition(0) val deserialized = parcel.readParcelable<User>(User::class.java.classLoader) // THEN // retrieved instance in distinct // instances are equal assertNotSame(user, deserialized) assertTrue(deserialized is RegisteredUser) assertEquals(user, deserialized) } @Test fun accountNamesEquality() { // GIVEN // registered user instance with lower-case account name // registered user instance with mixed-case account name val user1 = buildTestUser("account_name") val user2 = buildTestUser("Account_Name") // WHEN // account names are checked for equality val equal = user1.nameEquals(user2) // THEN // account names are equal assertTrue(equal) } @Test fun accountNamesEqualityCheckIsNullSafe() { // GIVEN // registered user instance with lower-case account name // null account val user1 = buildTestUser("account_name") val user2: User? = null // WHEN // account names are checked for equality against null val equal = user1.nameEquals(user2) // THEN // account names are not equal assertFalse(equal) } }
gpl-2.0
3dc83dcae2a563e228a3d8fbb79232c4
32.033613
84
0.65505
4.877171
false
true
false
false
Magneticraft-Team/Magneticraft
src/main/kotlin/com/cout970/magneticraft/misc/inventory/Container.kt
2
1272
package com.cout970.magneticraft.misc.inventory import net.minecraft.entity.player.EntityPlayer import net.minecraft.entity.player.InventoryPlayer import net.minecraft.inventory.Container import net.minecraft.inventory.Slot /** * Created by cout970 on 2017/02/20. */ /** * Gets all slots range is a part of player inventory. */ fun Container.getPlayerSlotRanges(player: EntityPlayer): List<IntRange> { return this.getSlotRanges { it.inventory is InventoryPlayer && it.inventory == player.inventory } } /** * Get all slots range that is not a part of player inventory. */ fun Container.getNonPlayerSlotRanges(): List<IntRange> { return this.getSlotRanges { it.inventory !is InventoryPlayer } } /** * Get all slots filtering with [predicate] */ fun Container.getSlotRanges(predicate: (Slot) -> Boolean): List<IntRange> { val ranges = mutableListOf<IntRange>() val size = inventorySlots.size var start: Int? = null inventorySlots.forEachIndexed { i, slot -> if (predicate(slot)) { if (start == null) start = i } else if (start != null) { ranges += start!!..i start = null } } if (start != null) ranges += start!!..size - 1 return ranges }
gpl-2.0
28c9871551e6d6c52f095336eda78cf9
24.979592
101
0.664308
4.038095
false
false
false
false
yschimke/oksocial
src/main/kotlin/com/baulsupp/okurl/services/travisci/travisci.kt
1
925
package com.baulsupp.okurl.services.travisci import com.baulsupp.okurl.credentials.DefaultToken import com.baulsupp.okurl.kotlin.Rest import com.baulsupp.okurl.kotlin.client import com.baulsupp.okurl.kotlin.queryPages import com.baulsupp.okurl.services.travisci.model.Build import com.baulsupp.okurl.services.travisci.model.BuildList import kotlin.math.min suspend fun queryAllBuilds( slug: String? = null, id: Int? = null, branch: String? = null, limit: Int = 100 ): List<Build> { val repo = slug?.replace("/", "%2F") ?: id.toString() val url = "https://api.travis-ci.org/repo/$repo/builds?limit=${min(100, limit)}" return client.queryPages<BuildList>(url, { Rest(pagination.limit.rangeTo(pagination.count).step(pagination.limit).map { "$url&offset=$it" }) }, DefaultToken, pageLimit = (limit / 100) + 1) .flatMap { it.builds }.filter { branch == null || it.branch?.name == branch }.take(limit) }
apache-2.0
83129703232bd327a68a677af8ae010b
37.541667
101
0.725405
3.375912
false
false
false
false
nisrulz/android-examples
UsingPocketSphinxForVoiceRecognition/app/src/main/java/github/nisrulz/example/usingpocketsphinxforvoicerecognition/SpeechRecognizerManager.kt
1
3324
package github.nisrulz.example.usingpocketsphinxforvoicerecognition import android.content.Intent import android.speech.RecognizerIntent import android.speech.SpeechRecognizer.createSpeechRecognizer import android.widget.Toast import edu.cmu.pocketsphinx.Assets import edu.cmu.pocketsphinx.SpeechRecognizer import edu.cmu.pocketsphinx.SpeechRecognizerSetup import java.io.File class SpeechRecognizerManager( private val assets: Assets, private val hotword: String, //Keyword we are looking for to activate menu private val onResultListener: OnResultListener, ) { private val TAG = SpeechRecognizerManager::class.java.simpleName // Named searches allow to quickly reconfigure the decoder private val KWS_SEARCH = "wakeup" private var speechRecognizerIntent by lazy { createSpeechRecognizer(context) } private lateinit var pocketSphinxRecognizer: SpeechRecognizer private lateinit var googleSpeechRecognizer: android.speech.SpeechRecognizer private suspend fun initPockerSphinx() { //Performs the synchronization of assets in the application and external storage val assetDir = assets.syncAssets() //Creates a new SpeechRecognizer builder with a default configuration val speechRecognizerSetup = SpeechRecognizerSetup.defaultSetup() //Set Dictionary and Acoustic Model files speechRecognizerSetup.setAcousticModel(File(assetDir, "en-us-ptm")) speechRecognizerSetup.setDictionary(File(assetDir, "cmudict-en-us.dict")) // Threshold to tune for keyphrase to balance between false positives and false negatives speechRecognizerSetup.setKeywordThreshold(1e-45f) //Creates a new SpeechRecognizer object based on previous set up. pocketSphinxRecognizer = speechRecognizerSetup.recognizer pocketSphinxRecognizer.addListener(PocketSphinxRecognitionListener()) // Create keyword-activation search. pocketSphinxRecognizer.addKeyphraseSearch(KWS_SEARCH, HOTWORD) if (result != null) { Toast.makeText( context, "Failed to init pocketSphinxRecognizer ", Toast.LENGTH_SHORT ).show() } else { restartSearch() } } private fun initGoogleSpeechRecognizer() { googleSpeechRecognizer ?.setRecognitionListener(GoogleRecognitionListener()) .also { googleSpeechRecognizer = it } Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) .apply { putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM ) putExtra(RecognizerIntent.EXTRA_CONFIDENCE_SCORES, true) }.also { speechRecognizerIntent = it } } fun destroy() { pocketSphinxRecognizer?.apply { cancel() shutdown() } googleSpeechRecognizer?.apply { cancel() destroy() } } private fun restartSearch(searchName: String = KWS_SEARCH) { pocketSphinxRecognizer?.apply { stop() startListening(searchName) } } fun init() { initPockerSphinx() initGoogleSpeechRecognizer() } }
apache-2.0
ac82eae710d9ce0b913ad26a6e3e6811
33.278351
97
0.679603
5.292994
false
false
false
false
anton-okolelov/intellij-rust
src/main/kotlin/org/rust/ide/actions/RsNewProjectAction.kt
1
1455
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.BuildNumber import com.intellij.util.ui.JBUI import org.rust.ide.newProject.RsDirectoryProjectGenerator import org.rust.ide.newProject.RsProjectSettingsStep import javax.swing.JComponent import javax.swing.JPanel // BACKCOMPAT: 2017.3 // Temporary action to create new Rust project in CLion (but works in all IDEs) class RsNewProjectAction : RsProjectSettingsStep(RsDirectoryProjectGenerator(true)) { override fun actionPerformed(e: AnActionEvent) { val panel = createPanel() panel.preferredSize = JBUI.size(600, 300) RsNewProjectDialog(panel).show() } override fun update(e: AnActionEvent) { val build = ApplicationInfo.getInstance().build e.presentation.isEnabledAndVisible = build < BUILD_181 } companion object { private val BUILD_181 = BuildNumber.fromString("181") } } private class RsNewProjectDialog(private val centerPanel: JPanel) : DialogWrapper(true) { init { title = "New Project" init() } override fun createCenterPanel(): JComponent? = centerPanel override fun createSouthPanel(): JComponent? = null }
mit
735c354513cf644eefe3156c63024427
29.957447
89
0.740893
4.46319
false
false
false
false
vafin-mk/codingame
src/main/java/multiplayer/ghostcell/Bot.kt
1
11863
import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap import kotlin.collections.HashSet class Bot(val scanner: Scanner) { private val factoryCount: Int = scanner.nextInt() private val factories = HashMap<Int, Factory>() private val shortPath = HashMap<Edge, Int>()//key = from -> to factories, value - intermediate factory to fastest route private val pathDistance = HashMap<Edge, Int>()//key = from -> to factories, value - distance private val routeConnectors = HashMap<Int, Int>() //id --> how many routes it connects private val factoryValue = HashMap<Int, Double>() //id --> value private val troops = ArrayList<Troop>() private var turn = 0 init { for (id in 0 until factoryCount) { factories.put(id, Factory(id, 0, 0, 0, 0)) routeConnectors.put(id, 0) factoryValue.put(id, 0.0) } val linkCount = scanner.nextInt() val edges = HashMap<Edge, Int>() for (i in 0 until linkCount) { val factory1 = scanner.nextInt() val factory2 = scanner.nextInt() val distance = scanner.nextInt() edges.put(Edge(factory1, factory2), distance) edges.put(Edge(factory2, factory1), distance) } for (id in 0 until factoryCount) { findShortestPath(id, edges) } shortPath .filter { it.key.destination != it.value } .map { it.value } .forEach { routeConnectors.put(it, (routeConnectors[it] ?: 0) + 1) } } //http://www.vogella.com/tutorials/JavaAlgorithmsDijkstra/article.html private fun findShortestPath(source: Int, edges: Map<Edge, Int>) { val settled = HashSet<Int>() val unsettled = HashSet<Int>() val predecessors = HashMap<Int, Int>() //id - id val distance = HashMap<Int, Int>() //id - dist distance.put(source, 0) unsettled.add(source) while(unsettled.isNotEmpty()) { val closestId = distance.filter { unsettled.contains(it.key) }.minBy { it.value }?.key ?: continue settled.add(closestId) unsettled.remove(closestId) val closestDist = distance[closestId] ?: throw IllegalStateException() edges.filter { it.key.source == closestId && !settled.contains(it.key.destination)} .map { it.key.destination } .forEach { destination-> val destinationDist = distance[destination] ?: Int.MAX_VALUE val edgeDist = edges[Edge(closestId, destination)] ?: throw IllegalStateException() if (destinationDist > closestDist + edgeDist) { distance.put(destination, closestDist + edgeDist) predecessors.put(destination, closestId) unsettled.add(destination) } } } for (destination in 0 until factoryCount) { if (destination == source) continue val edge = Edge(source, destination) val shortDist = distance[destination] ?: throw IllegalStateException() val edgeDist = edges[edge] ?: throw IllegalStateException() val path = LinkedList<Int>() var step = destination path.add(step) while (true) { step = predecessors[step] ?: break path.add(step) } path.reverse() if (shortDist + (path.size - 2) <= edgeDist) { shortPath.put(edge, path[1]) pathDistance.put(edge, shortDist + (path.size - 2)) } else { shortPath.put(edge, edge.destination) pathDistance.put(edge, edgeDist) } } } fun begin() { while (true) { readWorld() sendActions() turn++ } } private fun readWorld() { val entityCount = scanner.nextInt() troops.clear() for (i in 0 until entityCount) { val entityId = scanner.nextInt() val entityType = scanner.next() val arg1 = scanner.nextInt() val arg2 = scanner.nextInt() val arg3 = scanner.nextInt() val arg4 = scanner.nextInt() val arg5 = scanner.nextInt() when(entityType) { "FACTORY" -> { val factory = factories[entityId] ?: throw IllegalStateException() with(factory) { owner = arg1 cyborgCount = arg2 production = arg3 disabledTurns = arg4 } } "TROOP" -> { troops.add(Troop(entityId, arg1, arg2, arg3, arg4, arg5)) } "BOMB" -> { } } } factories.values.forEach { factory -> factoryValue.put(factory.id, factory.production + 0.01 * Math.pow(routeConnectors[factory.id]?.toDouble() ?: 0.0, 0.5) + 0.1) } } private fun sendActions() { val actions = think() val string = actions.joinToString(separator = ";") { action -> when(action) { is Move -> "MOVE ${action.source} ${action.destination} ${action.cyborgCount}" is Bomb -> "BOMB ${action.source} ${action.destination}" is Inc -> "INC ${action.factory}" Wait -> "WAIT" is Message -> "MSG ${action.message}" } } println(string) } private fun think() : List<Action> { val result = ArrayList<Action>() result.add(Wait) result.add(Message("Greetings Traveler!")) val allyFactories = factories.values.filter { it.owner == OWNER_ALLY } for (factory in allyFactories) { var unitsToUse = factory.cyborgCount - requiredForDefence(factory) if (unitsToUse <= 0) continue val actions = ArrayList<ActionScore>() for (targetId in 0 until factoryCount) { val targetFactory = factories[targetId] ?: continue when{ targetId == factory.id -> actions.add(ActionScore(Inc(targetId), increaseScore(targetFactory))) targetFactory.owner == OWNER_ALLY -> { actions.add(ActionScore(Move(factory.id, targetFactory.id, defenceReinforcementsRequired(targetFactory)), defenceScore(factory, targetFactory))) } targetFactory.owner == OWNER_NEUTRAL -> { actions.add(ActionScore(Move(factory.id, targetFactory.id, requiredToCaptureNeutral(targetFactory)), neutralAttackScore(factory, targetFactory))) } targetFactory.owner == OWNER_RIVAL -> { actions.add(ActionScore(Move(factory.id, targetFactory.id, 0), rivalAttackScore(factory, targetFactory))) } } } actions.sortByDescending { it.score } // printerr("$actions") for (action in actions.map { it.action }) { when(action) { is Inc -> { unitsToUse -= 10 result.add(action) } is Move -> { val targetFactory = factories[action.destination] ?: throw IllegalStateException() when (targetFactory.owner) { OWNER_ALLY -> { var use = defenceReinforcementsRequired(targetFactory) if (use > unitsToUse) { use = unitsToUse } result.add(Move(action.source, shortPath[Edge(action.source, action.destination)] ?: -1, use)) unitsToUse -= use } OWNER_NEUTRAL -> { var use = requiredToCaptureNeutral(targetFactory) if (use > unitsToUse) { use = unitsToUse } result.add(Move(action.source, shortPath[Edge(action.source, action.destination)] ?: -1, use)) unitsToUse -= use } OWNER_RIVAL -> { result.add(Move(action.source, shortPath[Edge(action.source, action.destination)] ?: -1, unitsToUse)) unitsToUse = 0 } } } } if (unitsToUse <= 0) break } if (turn == 0) { //send bombs var bombsAvailable = 2 val rivalFactory = factories.values.first { it.owner == OWNER_RIVAL } if (rivalFactory.production >= 2) { bombsAvailable-- result.add(Bomb(factory.id, rivalFactory.id)) } val neutrals = factories.values .filter { it.owner == OWNER_NEUTRAL && ((pathDistance[Edge(rivalFactory.id, it.id)] ?: 22) < (pathDistance[Edge(factory.id, it.id)] ?: 22)) } .sortedBy { factoryValue[it.id] }.reversed() for ((id) in neutrals) { bombsAvailable-- result.add(Bomb(factory.id, id)) if (bombsAvailable == 0) break } } } return result } private fun increaseScore(factory: Factory) : Double { return if (factory.production == 3) Double.MIN_VALUE else 1.0 / Math.pow(10.0, 1.6) } private fun defenceScore(source: Factory, destination: Factory) : Double { val value = factoryValue[destination.id] ?: 0.0 val dist = pathDistance[Edge(source.id, destination.id)]?.toDouble() ?: 22.0 return value / (Math.pow(dist, 2.0) * defenceReinforcementsRequired(destination)) } private fun neutralAttackScore(source: Factory, destination: Factory) : Double { val value = factoryValue[destination.id] ?: 0.0 val dist = pathDistance[Edge(source.id, destination.id)]?.toDouble() ?: 22.0 return value / (Math.pow(dist, 2.0) * requiredToCaptureNeutral(destination)) } private fun rivalAttackScore(source: Factory, destination: Factory) : Double { val value = factoryValue[destination.id] ?: 0.0 val dist = pathDistance[Edge(source.id, destination.id)]?.toDouble() ?: 22.0 return value / (Math.pow(dist, 2.0) * 8) } private fun requiredForDefence(factory: Factory, lookAheadTurns: Int = 5) : Int { val incomingTroops = troops.filter { it.destination == factory.id && it.turnsToArrive <= lookAheadTurns } val myUnits = incomingTroops.filter { it.owner == OWNER_ALLY }.map { it.cyborgCount }.sum() + factory.production * lookAheadTurns val enemyUnits = incomingTroops.filter { it.owner == OWNER_RIVAL }.map { it.cyborgCount }.sum() return Math.max(0, enemyUnits - myUnits) } private fun requiredToCaptureNeutral(factory: Factory) : Int { val incomingTroops = troops.filter { it.destination == factory.id } val myUnits = incomingTroops.filter { it.owner == OWNER_ALLY }.map { it.cyborgCount }.sum() val enemyUnits = incomingTroops.filter { it.owner == OWNER_RIVAL }.map { it.cyborgCount }.sum() return Math.max(1, factory.cyborgCount + enemyUnits - myUnits) } private fun defenceReinforcementsRequired(factory: Factory, lookAheadTurns: Int = 5) : Int { val incomingTroops = troops.filter { it.destination == factory.id && it.turnsToArrive <= lookAheadTurns } val myUnits = incomingTroops.filter { it.owner == OWNER_ALLY }.map { it.cyborgCount }.sum() + factory.production * lookAheadTurns + factory.cyborgCount val enemyUnits = incomingTroops.filter { it.owner == OWNER_RIVAL }.map { it.cyborgCount }.sum() return if (myUnits > enemyUnits) 0 else (-1 * (myUnits - enemyUnits)) } } data class Factory(val id: Int, var owner: Int, var cyborgCount: Int, var production: Int, var disabledTurns: Int) data class Troop(val id: Int, var owner: Int, var source: Int, var destination: Int, var cyborgCount: Int, var turnsToArrive: Int) data class Explosive(val id: Int, var owner: Int, var source: Int, var destination: Int, var turnsToArrive: Int) data class Edge(val source: Int, val destination: Int) sealed class Action data class Move(val source: Int, val destination: Int, val cyborgCount: Int) : Action() data class Bomb(val source: Int, val destination: Int) : Action() data class Inc(val factory: Int) : Action() object Wait : Action() data class Message(val message: String) : Action() data class ActionScore(val action: Action, val score: Double) //constants val OWNER_ALLY = 1 val OWNER_NEUTRAL = 0 val OWNER_RIVAL = -1 val UNKNOWN = -1 fun printerr(message: String) = System.err.println(message) fun main(args : Array<String>) = Bot(Scanner(System.`in`)).begin()
mit
a5383e143e4464c0793a65a77f39d240
36.191223
157
0.623788
4.116239
false
false
false
false
macrat/RuuMusic
app/src/main/java/jp/blanktar/ruumusic/service/EffectManager.kt
1
8171
package jp.blanktar.ruumusic.service import kotlin.concurrent.thread import android.content.Context import android.media.MediaPlayer import android.media.audiofx.BassBoost import android.media.audiofx.Equalizer import android.media.audiofx.LoudnessEnhancer import android.media.audiofx.PresetReverb import android.media.audiofx.Virtualizer import android.os.Build import android.os.Handler import android.widget.Toast import jp.blanktar.ruumusic.R import jp.blanktar.ruumusic.util.EqualizerInfo import jp.blanktar.ruumusic.util.Preference class EffectManager(val player: MediaPlayer, val context: Context) { private val preference = Preference(context) private var bassBoost: BassBoost? = null private var presetReverb: PresetReverb? = null private var loudnessEnhancer: LoudnessEnhancer? = null private var equalizer: Equalizer? = null private var virtualizer: Virtualizer? = null init { preference.BassBoostEnabled.setOnChangeListener { updateBassBoost() } preference.BassBoostLevel.setOnChangeListener { updateBassBoost() } preference.ReverbEnabled.setOnChangeListener { updateReverb() } preference.ReverbType.setOnChangeListener { updateReverb() } preference.LoudnessEnabled.setOnChangeListener { updateLoudnessEnhancer() } preference.LoudnessLevel.setOnChangeListener { updateLoudnessEnhancer() } preference.EqualizerEnabled.setOnChangeListener { updateEqualizer() } preference.EqualizerPreset.setOnChangeListener { updateEqualizer() } preference.EqualizerLevel.setOnChangeListener { updateEqualizer() } preference.VirtualizerEnabled.setOnChangeListener { updateVirtualizer() } preference.VirtualizerMode.setOnChangeListener { updateVirtualizer() } preference.VirtualizerStrength.setOnChangeListener { updateVirtualizer() } updateBassBoost() updateReverb() updateLoudnessEnhancer() updateEqualizer() updateVirtualizer() } fun release() { preference.unsetAllListeners() bassBoost?.release() presetReverb?.release() loudnessEnhancer?.release() equalizer?.release() } fun updateBassBoost() { if (preference.BassBoostEnabled.get()) { try { if (bassBoost == null) { bassBoost = BassBoost(0, player.audioSessionId) } bassBoost!!.setStrength(preference.BassBoostLevel.get()) bassBoost!!.enabled = true } catch (e: UnsupportedOperationException) { showToast(context.getString(R.string.audioeffect_cant_enable)) preference.BassBoostEnabled.set(false) } catch (e: RuntimeException) { showToast(context.getString(R.string.audioeffect_failed_enable, context.getString(R.string.bass_boost_switch))) preference.BassBoostEnabled.set(false) } } else { bassBoost?.release() bassBoost = null } } fun updateReverb() { if (preference.ReverbEnabled.get()) { try { if (presetReverb == null) { presetReverb = PresetReverb(0, player.audioSessionId) } presetReverb!!.preset = preference.ReverbType.get() presetReverb!!.enabled = true } catch (e: UnsupportedOperationException) { showToast(context.getString(R.string.audioeffect_cant_enable)) preference.ReverbEnabled.set(false) } catch (e: RuntimeException) { showToast(context.getString(R.string.audioeffect_failed_enable, context.getString(R.string.reverb_switch))) preference.ReverbEnabled.set(false) } } else { presetReverb?.release() presetReverb = null } } fun updateLoudnessEnhancer() { if (Build.VERSION.SDK_INT < 19) { return } if (preference.LoudnessEnabled.get()) { try { if (loudnessEnhancer == null) { loudnessEnhancer = LoudnessEnhancer(player.audioSessionId) } loudnessEnhancer!!.setTargetGain(preference.LoudnessLevel.get()) loudnessEnhancer!!.enabled = true } catch (e: UnsupportedOperationException) { showToast(context.getString(R.string.audioeffect_cant_enable)) preference.LoudnessEnabled.set(false) } catch (e: RuntimeException) { showToast(context.getString(R.string.audioeffect_failed_enable, context.getString(R.string.loudness_switch))) preference.LoudnessEnabled.set(false) } } else { loudnessEnhancer?.release() loudnessEnhancer = null } } fun updateEqualizer() { if (preference.EqualizerEnabled.get()) { try { if (equalizer == null) { equalizer = Equalizer(0, player.audioSessionId) } val preset = preference.EqualizerPreset.get() if (preset < 0) { for (i in 0..(equalizer!!.numberOfBands - 1)) { equalizer!!.setBandLevel(i.toShort(), preference.EqualizerLevel.get(i).toShort()) } } else { equalizer!!.usePreset(preset) for ((i, x) in equalizer!!.properties.bandLevels.withIndex()) { preference.EqualizerLevel.set(i, x.toInt()) } } equalizer!!.enabled = true } catch (e: UnsupportedOperationException) { showToast(context.getString(R.string.audioeffect_cant_enable)) preference.EqualizerEnabled.set(false) } catch (e: RuntimeException) { showToast(context.getString(R.string.audioeffect_failed_enable, context.getString(R.string.equalizer_switch))) preference.EqualizerEnabled.set(false) } } else { equalizer?.release() equalizer = null } } fun getEqualizerInfo(): EqualizerInfo { var eq = equalizer val have_to_release = eq == null if (have_to_release) { eq = Equalizer(0, player.audioSessionId) } val info = EqualizerInfo() info.min = eq!!.bandLevelRange[0] info.max = eq.bandLevelRange[1] info.freqs = IntArray(eq.numberOfBands.toInt()) { i -> eq!!.getCenterFreq(i.toShort()) } info.presets = Array(eq.numberOfPresets.toInt()) { i -> eq!!.getPresetName(i.toShort()) } if (have_to_release) { eq.release() } return info } fun updateVirtualizer() { if (preference.VirtualizerEnabled.get()) { try { if (virtualizer == null) { virtualizer = Virtualizer(0, player.audioSessionId) } if (Build.VERSION.SDK_INT >= 21) { virtualizer!!.forceVirtualizationMode(preference.VirtualizerMode.get()) } virtualizer!!.setStrength(preference.VirtualizerStrength.get()) virtualizer!!.enabled = true } catch (e: UnsupportedOperationException) { showToast(context.getString(R.string.audioeffect_cant_enable)) preference.VirtualizerEnabled.set(false) } catch (e: RuntimeException) { showToast(context.getString(R.string.audioeffect_failed_enable, context.getString(R.string.virtualizer_switch))) preference.VirtualizerEnabled.set(false) } } else { virtualizer?.release() virtualizer = null } } private fun showToast(message: String) { val handler = Handler() thread { handler.post { Toast.makeText(context, message, Toast.LENGTH_LONG).show() } } } }
mit
a6da634f47bc7bff25ac94a2368b478e
35.977376
128
0.598091
5.129316
false
false
false
false
google/horologist
media-ui/src/main/java/com/google/android/horologist/media/ui/components/InfoMediaDisplay.kt
1
1807
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.media.ui.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.Text import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi /** * A simple text only display showing status information. */ @ExperimentalHorologistMediaUiApi @Composable public fun InfoMediaDisplay( modifier: Modifier = Modifier, message: String? = null ) { Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) { Text( text = message.orEmpty(), modifier = Modifier.fillMaxWidth(0.7f), color = MaterialTheme.colors.onBackground, textAlign = TextAlign.Center, overflow = TextOverflow.Ellipsis, maxLines = 2, style = MaterialTheme.typography.body2 ) } }
apache-2.0
1348bd5937367e7834c66cfe91e0ba68
35.14
85
0.743774
4.540201
false
false
false
false
JavaEden/OrchidCore
plugins/OrchidPages/src/main/kotlin/com/eden/orchid/pages/menu/PageIdsMenuType.kt
1
3385
package com.eden.orchid.pages.menu import com.caseyjbrooks.clog.Clog import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.IntDefault import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.options.annotations.StringDefault import com.eden.orchid.api.theme.menus.MenuItem import com.eden.orchid.api.theme.menus.OrchidMenuFactory import org.jsoup.Jsoup import java.util.stream.IntStream import javax.inject.Inject import kotlin.streams.toList @Description("Finds all headers with an ID within the page content and creates menu items for each. All headers " + "between the min and max levels are used, such as h1-h3, or h2-h5. The default is all headers, h1-h6. These " + "header links can either be displayed in a flat list in the order they were found on the page, or as a " + "nested tree, where h2s are grouped under their previous h1, etc.", name = "Page Ids" ) class PageIdsMenuType @Inject constructor( context: OrchidContext ) : OrchidMenuFactory(context, "pageIds", 100) { @Option @IntDefault(1) @Description("The first 'level' of header to match. Defaults to h1.") var maxLevel: Int = 1 @Option @IntDefault(6) @Description("The last 'level' of header to match. Defaults to h6.") var minLevel: Int = 6 @Option @StringDefault("flat") @Description("The structure used to display the items. One of [flat, nested].") lateinit var structure: Structure override fun getMenuItems(): List<MenuItem> { if (maxLevel >= minLevel) { Clog.w("maxLevel must be less than minLevel") return emptyList() } val menuItems = ArrayList<MenuItem.Builder>() val headerLevelMap = HashMap<String, Int>() val doc = Jsoup.parse(page.content) val selector: String = IntStream .rangeClosed(maxLevel, minLevel) .mapToObj { i -> "h$i[id]" } .toList() .joinToString(separator = ",") val ids = doc.select(selector) for (id in ids) { val menuItem = MenuItem.Builder(context) .title(id.text()) .anchor(id.attr("id")) headerLevelMap[id.attr("id")] = Integer.parseInt(id.tag().name.substring(1)) menuItems.add(menuItem) } if (structure == Structure.nested) { val mostRecent = arrayOfNulls<MenuItem.Builder>(7) mostRecent[0] = MenuItem.Builder(context) for (menuItem in menuItems) { val level = headerLevelMap[menuItem.anchor]!! mostRecent[level] = menuItem var offset = 1 var parent = mostRecent[level - offset] while (parent == null && offset < level) { offset++ parent = mostRecent[level - offset] } if (parent != null) { parent.child(menuItem) } mostRecent[level] = menuItem } return mostRecent[0]?.build()?.children ?: ArrayList() } else { return menuItems.map { it.build() } } } enum class Structure { flat, nested } }
mit
27a4279f171fc16d91c914aa24571d04
32.186275
119
0.60384
4.396104
false
false
false
false
wordpress-mobile/WordPress-FluxC-Android
example/src/androidTest/java/org/wordpress/android/fluxc/mocked/MockedStack_WCGatewayTest.kt
2
4093
package org.wordpress.android.fluxc.mocked import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.module.ResponseMockingInterceptor import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.API_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.gateways.GatewayRestClient import org.wordpress.android.fluxc.network.rest.wpcom.wc.gateways.GatewayRestClient.GatewayId.CASH_ON_DELIVERY import javax.inject.Inject class MockedStack_WCGatewayTest : MockedStack_Base() { @Inject internal lateinit var restClient: GatewayRestClient @Inject internal lateinit var interceptor: ResponseMockingInterceptor @Throws(Exception::class) override fun setUp() { super.setUp() mMockedNetworkAppComponent.inject(this) } @Test fun whenFetchGatewaySuccessReturnSuccess() = runBlocking { interceptor.respondWith("wc-pay-fetch-gateway-response-success.json") val result = restClient.fetchGateway( SiteModel().apply { siteId = 123L }, "cod" ) assertTrue(result.result != null) Assert.assertFalse(result.isError) } @Test fun whenFetchGatewayErrorReturnError() = runBlocking { interceptor.respondWithError("wc-pay-fetch-gateway-response-error.json", 500) val result = restClient.fetchGateway( SiteModel().apply { siteId = 123L }, "cod" ) assertTrue(result.isError) assertEquals(API_ERROR, result.error.type) } @Test fun whenValidDataProvidedUpdateGatewayThenSuccessReturned() = runBlocking { interceptor.respondWith("wc-pay-update-gateway-response-success.json") val result = restClient.updatePaymentGateway( SiteModel().apply { siteId = 123L }, CASH_ON_DELIVERY, enabled = true, title = "Pay on Delivery", description = "Pay by cash or card on delivery" ) Assert.assertFalse(result.isError) assertTrue(result.result != null) } @Test fun whenUpdateGatewayFailsDueToUnexpectedServerErrorThenServerErrorReturned() = runBlocking { interceptor.respondWithError("wc-pay-update-gateway-response-error.json", 500) val result = restClient.updatePaymentGateway( SiteModel().apply { siteId = 123L }, CASH_ON_DELIVERY, enabled = false, title = "Pay on Delivery", description = "Pay by cash or card on delivery" ) assertTrue(result.isError) assertEquals(API_ERROR, result.error.type) } @Test fun whenInvalidDataProvidedUpdateGatewayThenInvalidParamReturned() = runBlocking { interceptor.respondWithError("wc-pay-update-gateway-invalid-data-response-error.json", 500) val result = restClient.updatePaymentGateway( SiteModel().apply { siteId = 123L }, enabled = true, title = "THIS IS INVALID TITLE", description = "THIS IS INVALID DESCRIPTION", gatewayId = CASH_ON_DELIVERY ) assertTrue(result.isError) assertEquals(API_ERROR, result.error.type) } @Test fun whenFetchAllGatewaysSucceedsReturnSuccess() = runBlocking { interceptor.respondWith("wc-pay-fetch-all-gateways-response-success.json") val result = restClient.fetchAllGateways( SiteModel().apply { siteId = 123L } ) Assert.assertFalse(result.isError) assertTrue(result.result != null) } @Test fun whenFetchAllGatewaysErrorReturnError() = runBlocking { interceptor.respondWithError("wc-pay-fetch-all-gateways-response-error.json", 500) val result = restClient.fetchAllGateways( SiteModel().apply { siteId = 123L } ) assertTrue(result.isError) assertEquals(API_ERROR, result.error.type) } }
gpl-2.0
a97c4a1f0c76d1e55ebc04b3b745c088
32.54918
110
0.673833
4.522652
false
true
false
false
ntemplon/legends-of-omterra
core/src/com/jupiter/europa/screen/dialog/NewGameDialog.kt
1
6113
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.screen.dialog import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable import com.jupiter.europa.EuropaGame import com.jupiter.europa.scene2d.ui.EuropaButton import com.jupiter.europa.scene2d.ui.ObservableDialog import com.jupiter.europa.screen.MainMenuScreen import com.badlogic.gdx.scenes.scene2d.ui.List as GuiList import com.badlogic.gdx.utils.Array as GdxArray /** * @author Nathan Templon */ public class NewGameDialog : ObservableDialog(NewGameDialog.DIALOG_NAME, NewGameDialog.getDefaultSkin()) { // Enumerations public enum class NewGameExitStates { START_GAME, CANCEL } // Fields private val skinInternal = getDefaultSkin() private var mainTable: Table? = null private var titleLabelInternal: Label? = null private var gameNameField: TextField? = null private var woldLabel: Label? = null private var listWrapper: Table? = null private var newGameWorldList: GuiList<String>? = null private var worldPane: ScrollPane? = null private var buttonTableInternal: Table? = null private var nextButton: EuropaButton? = null private var backButton: EuropaButton? = null public var exitState: NewGameExitStates? = null private set public fun getNewGameName(): String { return this.gameNameField!!.getText() } public fun getNewGameWorldName(): String { return this.newGameWorldList!!.getSelected().toString() } init { this.initComponents() } // Private Methods private fun initComponents() { this.mainTable = Table() this.titleLabelInternal = Label("Save Name: ", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<Label.LabelStyle>())) this.gameNameField = TextField("default", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextField.TextFieldStyle>())) this.gameNameField!!.setMaxLength(16) this.woldLabel = Label("World:", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<Label.LabelStyle>())) this.newGameWorldList = GuiList<String>(skinInternal.get<GuiList.ListStyle>(MainMenuScreen.DEFAULT_KEY, javaClass<GuiList.ListStyle>())) this.newGameWorldList!!.setItems(GdxArray(EuropaGame.game.getWorldNames())) this.worldPane = ScrollPane(this.newGameWorldList, skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<ScrollPane.ScrollPaneStyle>())) this.listWrapper = Table() this.listWrapper!!.add<ScrollPane>(this.worldPane).pad(MainMenuScreen.LIST_WRAPPER_PADDING.toFloat()).expand().fill() this.listWrapper!!.background(skinInternal.get(MainMenuScreen.LIST_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.nextButton = EuropaButton("Accept", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.nextButton!!.addClickListener { e -> this.startNewGame() } this.backButton = EuropaButton("Back", skinInternal.get(MainMenuScreen.DEFAULT_KEY, javaClass<TextButton.TextButtonStyle>())) this.backButton!!.addClickListener { this.cancelNewGame() } this.buttonTableInternal = Table() this.buttonTableInternal!!.add<EuropaButton>(this.backButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX() this.buttonTableInternal!!.add<EuropaButton>(this.nextButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.add<Label>(this.titleLabelInternal).center().left() this.mainTable!!.add<TextField>(this.gameNameField).center().left().padTop(15f).expandX().fillX() this.mainTable!!.row() this.mainTable!!.add<Label>(this.woldLabel).colspan(2).left() this.mainTable!!.row() this.mainTable!!.add<Table>(this.listWrapper).colspan(2).expandY().fill() this.mainTable!!.row() this.mainTable!!.add<Table>(this.buttonTableInternal).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).colspan(2).right().expandX().fillX() this.mainTable!!.row() this.mainTable!!.background(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).center().expandY().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat()) } private fun startNewGame() { this.exitState = NewGameExitStates.START_GAME this.hide() } private fun cancelNewGame() { this.exitState = NewGameExitStates.CANCEL this.hide() } companion object { // Constants private val DIALOG_NAME = "" // Static Methods private fun getDefaultSkin(): Skin { return MainMenuScreen.createMainMenuSkin() } } }
mit
4cb1018110a73a13b6157391952e29fd
40.585034
189
0.719941
4.648669
false
false
false
false
uber/RIBs
android/libraries/rib-android-core/src/main/kotlin/com/uber/rib/core/CoreAppCompatActivity.kt
1
2390
/* * Copyright (C) 2017. Uber Technologies * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.uber.rib.core import android.content.Intent import android.os.Bundle import androidx.annotation.CallSuper import androidx.annotation.IntRange import androidx.appcompat.app.AppCompatActivity /** Core Support v7 AppCompat Activity. */ abstract class CoreAppCompatActivity : AppCompatActivity() { private var activityDelegate: ActivityDelegate? = null @CallSuper override fun onCreate(savedInstanceState: Bundle?) { if (applicationContext is HasActivityDelegate) { activityDelegate = (applicationContext as HasActivityDelegate).activityDelegate() } super.onCreate(savedInstanceState) activityDelegate?.onCreate(savedInstanceState) } @CallSuper override fun onStart() { super.onStart() activityDelegate?.onStart() } @CallSuper override fun onResume() { super.onResume() activityDelegate?.onResume() } @CallSuper override fun onPause() { activityDelegate?.onPause() super.onPause() } @CallSuper override fun onStop() { activityDelegate?.onStop() super.onStop() } @CallSuper override fun onDestroy() { activityDelegate?.onDestroy() activityDelegate = null super.onDestroy() } @CallSuper override fun onRequestPermissionsResult( @IntRange(from = 0, to = 255) requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) activityDelegate?.onRequestPermissionsResult(this, requestCode, permissions, grantResults) } @CallSuper override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) activityDelegate?.onActivityResult(this, requestCode, resultCode, data) } }
apache-2.0
653329ed2fc42f0e01004d7f47ec8b63
27.452381
94
0.739331
4.808853
false
false
false
false
http4k/http4k
http4k-serverless/lambda/src/test/kotlin/org/http4k/serverless/LambdaContextMock.kt
1
872
package org.http4k.serverless import com.amazonaws.services.lambda.runtime.Context class LambdaContextMock(private val functionName: String = "LambdaContextMock") : Context { override fun getFunctionName() = functionName override fun getAwsRequestId() = TODO("LambdaContextMock") override fun getLogStreamName() = TODO("LambdaContextMock") override fun getInvokedFunctionArn() = TODO("LambdaContextMock") override fun getLogGroupName() = TODO("LambdaContextMock") override fun getFunctionVersion() = TODO("LambdaContextMock") override fun getIdentity() = TODO("LambdaContextMock") override fun getClientContext() = TODO("LambdaContextMock") override fun getRemainingTimeInMillis() = TODO("LambdaContextMock") override fun getLogger() = TODO("LambdaContextMock") override fun getMemoryLimitInMB() = TODO("LambdaContextMock") }
apache-2.0
24dde82e6d9f8d74b487f10054bb31cd
50.294118
91
0.764908
5.190476
false
false
false
false
http4k/http4k
src/docs/guide/reference/json/list_gotcha.kt
1
837
package guide.reference.json import org.http4k.core.Body import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.format.Moshi.auto data class MyIntWrapper(val value: Int) fun main() { val aListLens = Body.auto<List<MyIntWrapper>>().toLens() val req = Request(GET, "/").body(""" [ {"value":1}, {"value":2} ] """) val extractedList = aListLens(req) val nativeList = listOf(MyIntWrapper(1), MyIntWrapper(2)) println(nativeList) println(extractedList) println(extractedList == nativeList) //solution: val anArrayLens = Body.auto<Array<MyIntWrapper>>().toLens() println(anArrayLens(req).contentEquals(arrayOf(MyIntWrapper(1), MyIntWrapper(2)))) // produces: // [MyIntWrapper(value=1), MyIntWrapper(value=2)] // [{value=1}, {value=2}] // false // true }
apache-2.0
ff328749ce3749acb1ade6d92667c9a1
24.363636
86
0.681004
3.361446
false
false
false
false
nithia/xkotlin
exercises/sieve/src/example/kotlin/Sieve.kt
1
404
object Sieve { fun primesUpTo(upperBound: Int): List<Int> { val primes = mutableListOf<Int>() var candidates = (2..upperBound).toList() while (candidates.size > 0) { val prime = candidates[0] primes += prime candidates = candidates.filterIndexed { index, value -> index != 0 && value % prime != 0 } } return primes } }
mit
d834f633d3a83b8c82324876074f3a21
30.076923
102
0.54703
4.488889
false
false
false
false
akvo/akvo-flow-mobile
domain/src/main/java/org/akvo/flow/domain/interactor/bootstrap/BootstrapProcessor.kt
1
2856
/* * Copyright (C) 2021 Stichting Akvo (Akvo Foundation) * * This file is part of Akvo Flow. * * Akvo Flow is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Akvo Flow is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>. */ package org.akvo.flow.domain.interactor.bootstrap import kotlinx.coroutines.withContext import org.akvo.flow.domain.exception.WrongDashboardError import org.akvo.flow.domain.executor.CoroutineDispatcher import org.akvo.flow.domain.repository.FormRepository import timber.log.Timber import java.io.File import javax.inject.Inject class BootstrapProcessor @Inject constructor( private val formRepository: FormRepository, private val coroutineDispatcher: CoroutineDispatcher, ) { /** * Checks the bootstrap directory for unprocessed zip files. If they are * found, they're processed one at a time. If an error occurs, all * processing stops (subsequent zips won't be processed if there are * multiple zips in the directory) just in case data in a later zip depends * on the previous one being there. */ suspend fun execute( zipFiles: List<File>, instanceUrl: String, awsBucket: String, ): ProcessingResult { return withContext(coroutineDispatcher.getDispatcher()) { var processingResult: ProcessingResult = ProcessingResult.ProcessingSuccess for (file in zipFiles) { try { formRepository.processZipFile(file, instanceUrl, awsBucket) file.renameTo(File(file.absolutePath + PROCESSED_OK_SUFFIX)) } catch (e: Exception) { Timber.e(e, "Bootstrap error") file.renameTo(File(file.absolutePath + PROCESSED_ERROR_SUFFIX)) processingResult = if (e is WrongDashboardError) { ProcessingResult.ProcessingErrorWrongDashboard } else { ProcessingResult.ProcessingError } break } } processingResult } } companion object { const val CASCADE_RES_SUFFIX = ".sqlite.zip" const val XML_SUFFIX = ".xml" const val PROCESSED_OK_SUFFIX = ".processed" const val PROCESSED_ERROR_SUFFIX = ".error" } }
gpl-3.0
6f9fff5dc88cd90ca183188f954079bf
36.578947
87
0.658613
4.736318
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/androidTest/java/org/wordpress/android/fluxc/module/ResponseMockingInterceptor.kt
2
6145
package org.wordpress.android.fluxc.module import com.google.gson.Gson import com.google.gson.JsonElement import okhttp3.Interceptor import okhttp3.MediaType import okhttp3.Protocol import okhttp3.Request import okhttp3.Response import okhttp3.ResponseBody import okio.Buffer import okio.BufferedSource import okio.buffer import okio.source import org.wordpress.android.fluxc.TestUtils import org.wordpress.android.fluxc.module.ResponseMockingInterceptor.InterceptorMode.ONE_TIME import org.wordpress.android.fluxc.module.ResponseMockingInterceptor.InterceptorMode.STICKY import org.wordpress.android.fluxc.module.ResponseMockingInterceptor.InterceptorMode.STICKY_SUBSTITUTION import java.io.BufferedReader import java.io.ByteArrayInputStream import java.io.IOException import java.io.InputStreamReader import javax.inject.Inject import javax.inject.Singleton @Singleton class ResponseMockingInterceptor @Inject constructor() : Interceptor { companion object { private val SUBSTITUTION_DEFAULT = { string: String -> string } const val NETWORK_DELAY_MS = 500L } /** * ONE_TIME: Use the last response provided for the next request handled, and then clear it. * STICKY: Keep using the last response provided for all requests, until a new response is provided. * STICKY_SUBSTITUTION: Like STICKY, but also run a transformation function on the response. */ enum class InterceptorMode { ONE_TIME, STICKY, STICKY_SUBSTITUTION } private var nextResponseJson: String? = null private var nextResponseCode: Int = 200 private var nextResponseDelay: Long = NETWORK_DELAY_MS private var mode: InterceptorMode = ONE_TIME private var transformStickyResponse = SUBSTITUTION_DEFAULT private val gson by lazy { Gson() } var lastRequest: Request? = null private set var lastRequestUrl: String = "" private set val lastRequestBody: HashMap<String, Any> get() { val buffer = Buffer().apply { lastRequest?.body?.writeTo(this) } return gson.fromJson<HashMap<String, Any>>(buffer.readUtf8(), HashMap::class.java) ?: hashMapOf() } fun respondWith(jsonResponseFileName: String) { nextResponseJson = getStringFromResourceFile(jsonResponseFileName) nextResponseCode = 200 nextResponseDelay = NETWORK_DELAY_MS mode = ONE_TIME transformStickyResponse = SUBSTITUTION_DEFAULT } fun respondWithSticky( jsonResponseFileName: String, responseDelay: Long = NETWORK_DELAY_MS, transformResponse: ((String) -> String)? = null ) { nextResponseJson = getStringFromResourceFile(jsonResponseFileName) nextResponseCode = 200 nextResponseDelay = responseDelay transformResponse?.let { transformStickyResponse = it } mode = if (transformResponse == null) STICKY else STICKY_SUBSTITUTION } @JvmOverloads fun respondWithError(jsonResponseFileName: String, errorCode: Int = 404) { nextResponseJson = getStringFromResourceFile(jsonResponseFileName) nextResponseCode = errorCode nextResponseDelay = NETWORK_DELAY_MS } fun respondWith(jsonResponse: JsonElement) { nextResponseJson = jsonResponse.toString() nextResponseCode = 200 nextResponseDelay = NETWORK_DELAY_MS } @JvmOverloads fun respondWithError(jsonResponse: JsonElement, errorCode: Int = 404, interceptorMode: InterceptorMode = ONE_TIME) { nextResponseJson = jsonResponse.toString() nextResponseCode = errorCode mode = interceptorMode } @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() // Give some time to create a realistic network event TestUtils.waitFor(NETWORK_DELAY_MS) lastRequest = request lastRequestUrl = request.url.toString() nextResponseJson?.let { // Will be a successful response if nextResponseCode is 200, otherwise an error response val response = if (mode == STICKY_SUBSTITUTION) { buildResponse(request, transformStickyResponse(it), nextResponseCode) } else { buildResponse(request, it, nextResponseCode) } if (mode == ONE_TIME) { // Clean up for the next call nextResponseJson = null nextResponseCode = 200 } return response } throw IllegalStateException("Interceptor was not given a response for this request! URL: $lastRequestUrl") } private fun buildResponse(request: Request, responseJson: String, responseCode: Int): Response { return Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .message("") .body(object : ResponseBody() { override fun contentType(): MediaType? { return null } override fun contentLength(): Long { return -1 } override fun source(): BufferedSource { val stream = ByteArrayInputStream(responseJson.toByteArray(charset("UTF-8"))) return stream.source().buffer() } }) .code(responseCode) .build() } private fun getStringFromResourceFile(filename: String): String { try { val inputStream = this.javaClass.classLoader.getResourceAsStream(filename) val bufferedReader = BufferedReader(InputStreamReader(inputStream, "UTF-8")) val buffer = StringBuilder() bufferedReader.forEachLine { buffer.append(it) } bufferedReader.close() return buffer.toString() } catch (e: IOException) { throw IllegalStateException("Could not load response JSON file: $filename") } } }
gpl-2.0
cebc5a7ee17ff328b86976bfc8d3b403
34.726744
120
0.654841
5.418871
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/widget/SelfUpdatingView.kt
1
1659
package com.boardgamegeek.ui.widget import android.content.Context import android.util.AttributeSet import android.view.View import androidx.appcompat.widget.AppCompatTextView abstract class SelfUpdatingView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.textViewStyle ) : AppCompatTextView(context, attrs, defStyleAttr) { private var isVisible: Boolean = false private var isRunning: Boolean = false var timeHintUpdateInterval = 30_000L override fun onDetachedFromWindow() { super.onDetachedFromWindow() isVisible = false updateRunning() } override fun onWindowVisibilityChanged(visibility: Int) { super.onWindowVisibilityChanged(visibility) isVisible = visibility == View.VISIBLE updateRunning() } override fun onVisibilityChanged(changedView: View, visibility: Int) { super.onVisibilityChanged(changedView, visibility) updateRunning() } private fun updateRunning() { val running = isVisible && isShown if (running != isRunning) { if (running) { updateText() postDelayed(mTickRunnable, timeHintUpdateInterval) } else { removeCallbacks(mTickRunnable) } isRunning = running } } private val mTickRunnable = object : Runnable { override fun run() { if (isRunning) { updateText() postDelayed(this, timeHintUpdateInterval) } } } abstract fun updateText() }
gpl-3.0
fc689586cd625f2eb538e7751d14b366
27.62069
74
0.636528
5.439344
false
false
false
false
jeffgbutler/mybatis-qbe
src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/KotlinInsertHelpers.kt
1
3313
/* * Copyright 2016-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mybatis.dynamic.sql.util.kotlin import org.mybatis.dynamic.sql.SqlColumn import org.mybatis.dynamic.sql.insert.BatchInsertDSL import org.mybatis.dynamic.sql.insert.GeneralInsertDSL import org.mybatis.dynamic.sql.insert.GeneralInsertModel import org.mybatis.dynamic.sql.insert.InsertDSL import org.mybatis.dynamic.sql.insert.MultiRowInsertDSL import org.mybatis.dynamic.sql.util.Buildable typealias GeneralInsertCompleter = @MyBatisDslMarker KotlinGeneralInsertBuilder.() -> Unit typealias InsertCompleter<T> = @MyBatisDslMarker InsertDSL<T>.() -> Unit typealias MultiRowInsertCompleter<T> = @MyBatisDslMarker MultiRowInsertDSL<T>.() -> Unit typealias BatchInsertCompleter<T> = @MyBatisDslMarker BatchInsertDSL<T>.() -> Unit typealias InsertSelectCompleter = @MyBatisDslMarker KotlinInsertSelectSubQueryBuilder.() -> Unit @MyBatisDslMarker class KotlinGeneralInsertBuilder(private val dsl: GeneralInsertDSL) : Buildable<GeneralInsertModel> { fun <T> set(column: SqlColumn<T>): GeneralInsertSetClauseFinisher<T> = GeneralInsertSetClauseFinisher(column) override fun build(): GeneralInsertModel = dsl.build() @MyBatisDslMarker inner class GeneralInsertSetClauseFinisher<T>(private val column: SqlColumn<T>) { fun toNull(): KotlinGeneralInsertBuilder = applyToDsl { set(column).toNull() } fun toConstant(constant: String): KotlinGeneralInsertBuilder = applyToDsl { set(column).toConstant(constant) } fun toStringConstant(constant: String): KotlinGeneralInsertBuilder = applyToDsl { set(column).toStringConstant(constant) } fun toValue(value: T): KotlinGeneralInsertBuilder = toValue { value } fun toValue(value: () -> T): KotlinGeneralInsertBuilder = applyToDsl { set(column).toValue(value) } fun toValueOrNull(value: T?): KotlinGeneralInsertBuilder = toValueOrNull { value } fun toValueOrNull(value: () -> T?): KotlinGeneralInsertBuilder = applyToDsl { set(column).toValueOrNull(value) } fun toValueWhenPresent(value: T?): KotlinGeneralInsertBuilder = toValueWhenPresent { value } fun toValueWhenPresent(value: () -> T?): KotlinGeneralInsertBuilder = applyToDsl { set(column).toValueWhenPresent(value) } private fun applyToDsl(block: GeneralInsertDSL.() -> Unit): KotlinGeneralInsertBuilder = [email protected] { dsl.apply(block) } } }
apache-2.0
7ebecf7dd5da3239478e7f4a472a5772
37.523256
113
0.692122
4.886431
false
false
false
false
FHannes/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/codeInspection/style/GrUnnecessaryDefModifierInspection.kt
12
4287
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.codeInspection.style import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel import com.intellij.psi.PsiElement import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiModifierListOwner import org.jetbrains.plugins.groovy.codeInspection.GroovyInspectionBundle import org.jetbrains.plugins.groovy.codeInspection.GroovySuppressableInspectionTool import org.jetbrains.plugins.groovy.codeInspection.bugs.GrRemoveModifierFix import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kDEF import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.kIN import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifier import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.clauses.GrForInClause import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameterList import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import javax.swing.JComponent class GrUnnecessaryDefModifierInspection : GroovySuppressableInspectionTool(), CleanupLocalInspectionTool { companion object { private val FIX = GrRemoveModifierFix(GrModifier.DEF) } @JvmField var reportExplicitTypeOnly: Boolean = true override fun createOptionsPanel(): JComponent? = MultipleCheckboxOptionsPanel(this).apply { addCheckbox(GroovyInspectionBundle.message("unnecessary.def.explicitly.typed.only"), "reportExplicitTypeOnly") } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : PsiElementVisitor() { override fun visitElement(modifier: PsiElement) { if (modifier.node.elementType !== kDEF) return val modifierList = modifier.parent as? GrModifierList ?: return if (!isModifierUnnecessary(modifierList)) return holder.registerProblem( modifier, GroovyInspectionBundle.message("unnecessary.modifier.description", GrModifier.DEF), ProblemHighlightType.LIKE_UNUSED_SYMBOL, FIX ) } } private fun isModifierUnnecessary(modifierList: GrModifierList): Boolean { fun GrModifierList.hasOtherModifiers() = modifiers.any { it.node.elementType != kDEF } if (!reportExplicitTypeOnly && modifierList.hasOtherModifiers()) return true val owner = modifierList.parent as? PsiModifierListOwner ?: return false return when (owner) { is GrParameter -> { val parent = owner.parent if (parent is GrForClause && parent.declaredVariable != owner) return false if (owner.typeElementGroovy != null) return true !reportExplicitTypeOnly && (parent is GrParameterList || parent is GrForInClause && parent.delimiter.node.elementType == kIN) } is GrMethod -> { return if (owner.isConstructor) { true } else if (owner.hasTypeParameters()) { modifierList.hasOtherModifiers() } else { owner.returnTypeElementGroovy != null } } is GrVariable -> owner.typeElementGroovy != null is GrVariableDeclaration -> owner.typeElementGroovy != null else -> false } } }
apache-2.0
70e342c3c52595c944e122b19b4b790c
43.195876
133
0.76767
4.664853
false
false
false
false
benkyokai/tumpaca
app/src/main/kotlin/com/tumpaca/tp/view/TPWebViewClient.kt
1
2283
package com.tumpaca.tp.view import android.content.Intent import android.net.Uri import android.util.Base64 import android.webkit.WebView import android.webkit.WebViewClient import com.tumpaca.tp.model.TPRuntime /** * カスタムWebViewクライアント * Created by yabu on 2016/10/26. */ class TPWebViewClient(val cssFilePath: String) : WebViewClient() { /** * WebView内のリンクをタップしたときは、外部ブラウザを立ち上げる */ override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { if (url != null) { try { view.context.startActivity( Intent(Intent.ACTION_VIEW, Uri.parse(url))) } catch (e: Exception) { return false } return true } else { return false } } /** * ページ読み込み完了時にスタイルシート適用 */ override fun onPageFinished(view: WebView, url: String) { // CSSロード用javascriptを読み込むために一時的にjavascriptを有効にする view.settings.javaScriptEnabled = true view.loadUrl(generateCSS(cssFilePath)) view.settings.javaScriptEnabled = false super.onPageFinished(view, url) } private fun generateCSS(cssFile: String): String { try { val inputStream = TPRuntime.mainApplication.assets.open(cssFile) val buffer = ByteArray(inputStream.available()) inputStream.read(buffer) inputStream.close() val encoded = Base64.encodeToString(buffer, Base64.NO_WRAP) val scripts = "javascript:(function() {" + "var parent = document.getElementsByTagName('head').item(0);" + "var style = document.createElement('style');" + "style.type = 'text/css';" + // Tell the browser to BASE64-decode the string into your script !!! "style.innerHTML = window.atob('$encoded');" + "parent.appendChild(style)" + "})()" return scripts } catch (e: Exception) { e.printStackTrace() return "" } } }
gpl-3.0
e082b5dfb5c19572607d571569524228
31.707692
88
0.576
4.310345
false
false
false
false
misaochan/apps-android-commons
app/src/main/java/fr/free/nrw/commons/explore/depictions/DepictionAdapter.kt
3
1875
package fr.free.nrw.commons.explore.depictions import android.view.View import android.view.ViewGroup import androidx.paging.PagedListAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import fr.free.nrw.commons.R import fr.free.nrw.commons.explore.paging.inflate import fr.free.nrw.commons.upload.structure.depictions.DepictedItem import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.item_depictions.* class DepictionAdapter(val onDepictionClicked: (DepictedItem) -> Unit) : PagedListAdapter<DepictedItem, DepictedItemViewHolder>( object : DiffUtil.ItemCallback<DepictedItem>() { override fun areItemsTheSame(oldItem: DepictedItem, newItem: DepictedItem) = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: DepictedItem, newItem: DepictedItem) = oldItem == newItem } ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DepictedItemViewHolder { return DepictedItemViewHolder(parent.inflate(R.layout.item_depictions)) } override fun onBindViewHolder(holder: DepictedItemViewHolder, position: Int) { holder.bind(getItem(position)!!, onDepictionClicked) } } class DepictedItemViewHolder(override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer { fun bind(item: DepictedItem, onDepictionClicked: (DepictedItem) -> Unit) { containerView.setOnClickListener { onDepictionClicked(item) } depicts_label.text = item.name description.text = item.description if (item.imageUrl?.isNotBlank() == true) { depicts_image.setImageURI(item.imageUrl) } else { depicts_image.setActualImageResource(R.drawable.ic_wikidata_logo_24dp) } } }
apache-2.0
071531ccf52e177362b95f45240c9b69
39.76087
95
0.7344
4.795396
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/video/MediaInfoAdapter.kt
1
4632
/***************************************************************************** * MediaInfoAdapter.java * * Copyright © 2011-2017 VLC authors and VideoLAN * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. */ package org.videolan.vlc.gui.video import android.content.Context import android.content.res.Resources import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import org.videolan.libvlc.interfaces.IMedia import org.videolan.tools.readableSize import org.videolan.vlc.R class MediaInfoAdapter : RecyclerView.Adapter<MediaInfoAdapter.ViewHolder>() { private lateinit var inflater: LayoutInflater private var dataset: List<IMedia.Track>? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { if (!::inflater.isInitialized) inflater = parent.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater return ViewHolder(inflater.inflate(R.layout.info_item, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val track = dataset!![position] val title: String val textBuilder = StringBuilder() val res = holder.itemView.context.resources when (track.type) { IMedia.Track.Type.Audio -> { title = res.getString(R.string.track_audio) appendCommon(textBuilder, res, track) appendAudio(textBuilder, res, track as IMedia.AudioTrack) } IMedia.Track.Type.Video -> { title = res.getString(R.string.track_video) appendCommon(textBuilder, res, track) appendVideo(textBuilder, res, track as IMedia.VideoTrack) } IMedia.Track.Type.Text -> { title = res.getString(R.string.track_text) appendCommon(textBuilder, res, track) } else -> title = res.getString(R.string.track_unknown) } holder.title.text = title holder.text.text = textBuilder.toString() } override fun getItemCount() = dataset?.size ?: 0 fun setTracks(tracks: List<IMedia.Track>) { val size = itemCount dataset = tracks if (size > 0) notifyItemRangeRemoved(0, size - 1) notifyItemRangeInserted(0, tracks.size) } private fun appendCommon(textBuilder: StringBuilder, res: Resources, track: IMedia.Track) { if (track.bitrate != 0) textBuilder.append(res.getString(R.string.track_bitrate_info, track.bitrate.toLong().readableSize())) textBuilder.append(res.getString(R.string.track_codec_info, track.codec)) if (track.language != null && !track.language.equals("und", ignoreCase = true)) textBuilder.append(res.getString(R.string.track_language_info, track.language)) } private fun appendAudio(textBuilder: StringBuilder, res: Resources, track: IMedia.AudioTrack) { textBuilder.append(res.getQuantityString(R.plurals.track_channels_info_quantity, track.channels, track.channels)) textBuilder.append(res.getString(R.string.track_samplerate_info, track.rate)) } private fun appendVideo(textBuilder: StringBuilder, res: Resources, track: IMedia.VideoTrack) { val framerate = track.frameRateNum / track.frameRateDen.toDouble() if (track.width != 0 && track.height != 0) textBuilder.append(res.getString(R.string.track_resolution_info, track.width, track.height)) if (!java.lang.Double.isNaN(framerate)) textBuilder.append(res.getString(R.string.track_framerate_info, framerate)) } inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val title: TextView = itemView.findViewById(R.id.title) val text: TextView = itemView.findViewById(R.id.subtitle) } }
gpl-2.0
22e9b7a035068c609fffba8de29d8e71
43.528846
121
0.678687
4.414681
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/ui/CompletableViewModel.kt
1
1142
package org.tasks.ui import androidx.lifecycle.* import kotlinx.coroutines.launch import timber.log.Timber abstract class CompletableViewModel<T> : ViewModel() { private val data = MutableLiveData<T>() private val error = MutableLiveData<Throwable>() var inProgress = false private set fun observe( lifecycleOwner: LifecycleOwner, dataObserver: suspend (T) -> Unit, errorObserver: (Throwable) -> Unit) { data.observe(lifecycleOwner) { lifecycleOwner.lifecycleScope.launch { dataObserver(it) } } error.observe(lifecycleOwner, errorObserver) } protected suspend fun run(callable: suspend () -> T) { if (!inProgress) { inProgress = true try { data.postValue(callable()) } catch (e: Exception) { Timber.e(e) error.postValue(e) } inProgress = false } } fun removeObserver(owner: LifecycleOwner) { data.removeObservers(owner) error.removeObservers(owner) } }
gpl-3.0
029a8386ae5be6bd319ff410c62476e1
25.581395
58
0.574431
5.030837
false
false
false
false
NextFaze/dev-fun
demo/src/debug/java/com/nextfaze/devfun/demo/KotlinBugScreen.kt
1
9596
@file:SuppressLint("SetTextI18n") package com.nextfaze.devfun.demo import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.os.Handler import android.os.Looper import android.text.SpannableStringBuilder import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.nextfaze.devfun.core.devFun import com.nextfaze.devfun.core.devFunVerbose import com.nextfaze.devfun.demo.inject.BuildTypeFragmentInjector import com.nextfaze.devfun.demo.inject.FragmentInjector import com.nextfaze.devfun.demo.kotlin.color import com.nextfaze.devfun.demo.kotlin.enabled import com.nextfaze.devfun.demo.kotlin.findOrCreate import com.nextfaze.devfun.demo.kotlin.i import com.nextfaze.devfun.demo.kotlin.plusAssign import com.nextfaze.devfun.demo.kotlin.scale import com.nextfaze.devfun.demo.kotlin.startActivity import com.nextfaze.devfun.demo.test.TestCat import com.nextfaze.devfun.error.ErrorHandler import com.nextfaze.devfun.function.DeveloperFunction import kotlinx.android.synthetic.debug.kotlin_bug_fragment.* import java.io.PrintWriter import java.io.StringWriter import java.lang.reflect.Method import java.util.Random import kotlin.reflect.KClass import kotlin.reflect.KMutableProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty0 import kotlin.reflect.KProperty1 import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.jvm.isAccessible import kotlin.reflect.jvm.javaMethod import kotlin.reflect.jvm.kotlinProperty @TestCat class KotlinBugActivity : BaseActivity() { companion object { @DeveloperFunction fun start(context: Context) = context.startActivity<KotlinBugActivity>() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_activity) if (savedInstanceState == null) { supportFragmentManager.beginTransaction().replace(R.id.activity_fragment_view, findOrCreate { KotlinBugFragment() }).commit() } } } /** To simulate normal DevFun behaviour (we want the `property$annotations()` function) */ @Target(AnnotationTarget.PROPERTY) @Retention(AnnotationRetention.BINARY) private annotation class DummyAnnotation class KotlinBugFragment : BaseFragment() { init { devFunVerbose = true // increases likelihood of failure } @DummyAnnotation @Suppress("unused") private val someBoolean: String? by lazy { "sdf" } private val s = PropertyProcessor() private val r = Random() private val handler = Handler(Looper.getMainLooper()) private var testRunning = false private var successCount = 0 override fun inject(injector: FragmentInjector) = (injector as BuildTypeFragmentInjector).inject(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.kotlin_bug_fragment, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) runTestButton.setOnClickListener { runTestButton.text = "Running..." runTestButton.enabled = false textView.text = "" stackTraceTextView.text = "" handler.post { if (!testRunning) { testRunning = true updateSuccessCount() runTest() } } } } /** Doesn't actually work since main thread is being thrashed, but this invocation adds to that thrashing and increases likelihood of failure. */ private fun updateSuccessCount() { handler.postDelayed({ textView.text = "Invocations succeeded before exception: $successCount" if (testRunning) { updateSuccessCount() } }, 10) } private val prop = object : PropertyMethod { override val method = KotlinBugFragment::class.java.getDeclaredMethod("someBoolean\$annotations").apply { isAccessible = true } } private fun runTest() { successCount = 0 test() } private fun stopTest(t: Throwable) { testRunning = false runTestButton.text = "Re-run Test" runTestButton.enabled = true textView.text = "Invocations succeeded before exception: $successCount" stackTraceTextView.text = t.stackTraceAsString devFun.get<ErrorHandler>().onError(t, "Kotlin Reflect Bug", textView.text) } private fun logSuccessCount() { successCount++ logger().d { "successCount=$successCount" } } private fun test() { if (!testRunning) return try { val desc = s.getDescriptor(prop) println("desc=${desc.name}") } catch (t: Throwable) { stopTest(t) return } handler.postDelayed({ test() logSuccessCount() }, r.nextInt(100).toLong()) handler.postAtFrontOfQueue { test() logSuccessCount() } handler.post { test() logSuccessCount() } } } private interface PropertyMethod { val method: Method val clazz: KClass<out Any> get() = method.declaringClass.kotlin } private interface Descriptor { val name: CharSequence } private class PropertyProcessor { fun getDescriptor(propertyMethod: PropertyMethod): Descriptor { return object : Descriptor { val fieldName by lazy { propertyMethod.method.name.substringBefore('$') } val propertyField by lazy { try { propertyMethod.clazz.java.getDeclaredField(fieldName).apply { isAccessible = true } } catch (ignore: NoSuchFieldException) { null // is property without backing field (i.e. has custom getter/setter) } } val property by lazy { val propertyField = propertyField when { propertyField != null -> propertyField.kotlinProperty!! else -> propertyMethod.clazz.declaredMemberProperties.first { it.name == fieldName } }.apply { isAccessible = true } } // Kotlin reflection has weird accessibility issues when invoking get/set/getter/setter .call() // it only seems to work the first time with subsequent calls failing with illegal access exceptions and the like val getter by lazy { property.getter.javaMethod?.apply { isAccessible = true } } val setter by lazy { val property = property if (property is KMutableProperty<*>) property.setter.javaMethod?.apply { isAccessible = true } else null } val propertyDesc by lazy { val lateInit = if (property.isLateinit) "lateinit " else "" val varType = if (property is KMutableProperty<*>) "var" else "val" "$lateInit$varType $fieldName: ${property.simpleName}" } private val receiver by lazy { devFun.instanceOf(propertyMethod.clazz) } private val isUninitialized by lazy { property.isUninitialized } private var value: Any? get() = when { getter != null -> getter!!.invoke(receiver) else -> propertyField?.get(receiver) } set(value) { when { setter != null -> setter!!.invoke(receiver, value) else -> propertyField?.set(receiver, value) } } override val name by lazy { SpannableStringBuilder().apply { this += propertyDesc this += " = " when { property.isLateinit && value == null -> this += i("undefined") isUninitialized -> this += i("uninitialized") property.type == String::class && value != null -> this += """"$value"""" else -> this += "$value" } if (isUninitialized) { this += "\n" this += color(scale(i("\t(tap will initialize)"), 0.85f), 0xFFAAAAAA.toInt()) } } } @Suppress("UNCHECKED_CAST") private val KProperty<*>.isUninitialized: Boolean get() { isAccessible = true return when (this) { is KProperty0<*> -> (getDelegate() as? Lazy<*>)?.isInitialized() == false is KProperty1<*, *> -> ((this as KProperty1<Any?, Any>).getDelegate(receiver) as? Lazy<*>)?.isInitialized() == false else -> false } } } } private val KProperty<*>.simpleName get() = "${type.simpleName}${if (returnType.isMarkedNullable) "?" else ""}" private val KProperty<*>.type get() = returnType.classifier as KClass<*> } private val Throwable.stackTraceAsString get() = StringWriter().apply { printStackTrace(PrintWriter(this)) }.toString()
apache-2.0
43dfd5794fff9108cd78d43600d2c2ee
36.338521
149
0.614318
5.139796
false
true
false
false
apollo-rsps/apollo
game/plugin-testing/src/main/kotlin/org/apollo/game/plugin/testing/junit/api/ActionCapture.kt
1
3091
package org.apollo.game.plugin.testing.junit.api import kotlin.reflect.KClass import kotlin.reflect.full.isSuperclassOf import org.apollo.game.action.Action import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue class ActionCapture(val type: KClass<out Action<*>>) { private var action: Action<*>? = null private val callbacks = mutableListOf<ActionCaptureCallback>() private var lastTicks: Int = 0 fun capture(captured: Action<*>) { assertTrue(type.isSuperclassOf(captured::class)) { "${captured::class.simpleName} is not an instance of ${type.simpleName}" } this.action = captured } private fun callback(delay: ActionCaptureDelay): ActionCaptureCallbackRegistration { val registration = ActionCaptureCallbackRegistration() val callback = ActionCaptureCallback(delay, registration) callbacks.add(callback) return registration } fun runAction(timeout: Int = 50) { action?.let { var pulses = 0 do { it.pulse() pulses++ val tickCallbacks = callbacks.filter { it.delay == ActionCaptureDelay.Ticks(pulses) } tickCallbacks.forEach { it.invoke() } callbacks.removeAll(tickCallbacks) } while (it.isRunning && pulses < timeout) val completionCallbacks = callbacks.filter { it.delay == ActionCaptureDelay.Completed } completionCallbacks.forEach { it.invoke() } callbacks.removeAll(completionCallbacks) } assertEquals(0, callbacks.size, { "untriggered callbacks:\n" + callbacks .map { val delayDescription = when (it.delay) { is ActionCaptureDelay.Ticks -> "${it.delay.count} ticks" is ActionCaptureDelay.Completed -> "action completion" } "$delayDescription (${it.callbackRegistration.description ?: ""})" } .joinToString("\n") .prependIndent(" ") }) } /** * Create a callback registration that triggers after exactly [count] ticks. */ fun exactTicks(count: Int) = callback(ActionCaptureDelay.Ticks(count)) /** * Create a callback registration that triggers after [count] ticks. This method is cumulative, * and will take into account previous calls to [ticks] when creating new callbacks. * * To run a callback after an exact number of ticks use [exactTicks]. */ fun ticks(count: Int): ActionCaptureCallbackRegistration { lastTicks += count return exactTicks(lastTicks) } /** * Create a callback registration that triggers when an [Action] completes. */ fun complete() = callback(ActionCaptureDelay.Completed) /** * Check if this capture has a pending [Action] to run. */ fun isPending(): Boolean { return action?.isRunning ?: false } }
isc
759e3d3b107c921766f77bd20acc8e10
32.247312
101
0.617599
4.961477
false
false
false
false
liceoArzignano/app_bold
app/src/main/kotlin/it/liceoarzignano/bold/firebase/BoldInstanceIdService.kt
1
1274
package it.liceoarzignano.bold.firebase import com.google.firebase.iid.FirebaseInstanceId import com.google.firebase.iid.FirebaseInstanceIdService import com.google.firebase.messaging.FirebaseMessaging import it.liceoarzignano.bold.settings.AppPrefs class BoldInstanceIdService : FirebaseInstanceIdService() { override fun onTokenRefresh() { FirebaseInstanceId.getInstance().token val prefs = AppPrefs(baseContext) val topic: String topic = if (prefs.get(AppPrefs.KEY_IS_TEACHER)) { ADDR6_TOPIC } else { when (prefs.get(AppPrefs.KEY_ADDRESS, "0")) { "1" -> ADDR1_TOPIC "2" -> ADDR2_TOPIC "3" -> ADDR3_TOPIC "4" -> ADDR4_TOPIC "5" -> ADDR5_TOPIC else -> ADDR6_TOPIC } } FirebaseMessaging.getInstance().subscribeToTopic(topic) } companion object { private const val ADDR1_TOPIC = "Scientifico" private const val ADDR2_TOPIC = "ScApplicate" private const val ADDR3_TOPIC = "Linguistico" private const val ADDR4_TOPIC = "ScUmane" private const val ADDR5_TOPIC = "Economico" private const val ADDR6_TOPIC = "Docente" } }
lgpl-3.0
c58a5973af85591999e7c32920f26200
31.666667
63
0.620879
4.26087
false
false
false
false
nemerosa/ontrack
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/subscriptions/SubscriptionsCascContextData.kt
1
953
package net.nemerosa.ontrack.extension.notifications.subscriptions import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.model.annotations.APIDescription data class SubscriptionsCascContextData( @APIDescription("List of events to listen to") val events: List<String>, @APIDescription("Keywords to filter the events") val keywords: String?, @APIDescription("Channel to send notifications to") val channel: String, @APIDescription("Configuration of the channel") @get:JsonProperty("channel-config") val channelConfig: JsonNode, @APIDescription("Is this channel disabled?") val disabled: Boolean? = null, ) { fun normalized() = SubscriptionsCascContextData( events = events.sorted(), keywords = keywords, channel = channel, channelConfig = channelConfig, disabled = disabled ?: false, ) }
mit
97aad4db266eebcecea55df76818ea10
34.333333
66
0.726128
4.887179
false
true
false
false
BjoernPetersen/JMusicBot
src/main/kotlin/net/bjoernpetersen/musicbot/api/config/ConfigUiDsl.kt
1
5868
@file:Suppress("unused", "TooManyFunctions") package net.bjoernpetersen.musicbot.api.config import java.io.File import java.nio.file.Path /** * Configuration object for DSL. * * ### Required * * - [label] * - [describe] * - [action] */ class ActionButtonConfiguration<T> internal constructor() { /** * @see ActionButton.label */ lateinit var label: String /** * @see ActionButton.descriptor */ private lateinit var descriptor: (T) -> String private lateinit var onAction: suspend (Config.Entry<T>) -> Boolean /** * Describe the entry value as a string. * * @see ActionButton.descriptor */ fun describe(descriptor: (T) -> String) { this.descriptor = descriptor } /** * @see ActionButton.action */ fun action(action: suspend (Config.Entry<T>) -> Boolean) { this.onAction = action } internal fun toNode(): ActionButton<T> { val exceptionMessage = when { !::label.isInitialized -> "label not set" !::descriptor.isInitialized -> "descriptor not set" !::onAction.isInitialized -> "action not set" else -> null } if (exceptionMessage != null) throw IllegalStateException(exceptionMessage) return ActionButton( label = label, descriptor = descriptor, action = onAction ) } } /** * Create an [ActionButton]. */ fun <T> actionButton(configure: ActionButtonConfiguration<T>.() -> Unit): ActionButton<T> { val config = ActionButtonConfiguration<T>() config.configure() return config.toNode() } /** * Create and use an [ActionButton]. */ fun <T> SerializedConfiguration<T>.actionButton( configure: ActionButtonConfiguration<T>.() -> Unit ) { val config = ActionButtonConfiguration<T>() config.configure() uiNode = config.toNode() } /** * Create and use an [ActionButton]. */ fun StringConfiguration.actionButton( configure: ActionButtonConfiguration<String>.() -> Unit ) { val config = ActionButtonConfiguration<String>() config.configure() uiNode = config.toNode() } /** * Create a [PathChooser] for opening files. */ fun openFile(): PathChooser { return PathChooser(isDirectory = false, isOpen = true) } /** * Use a [PathChooser] for opening files. */ fun SerializedConfiguration<Path>.openFile() { uiNode = PathChooser(isDirectory = false, isOpen = true) } /** * Create a [PathChooser] for opening directories. */ fun openDirectory(): PathChooser { return PathChooser(isDirectory = true, isOpen = true) } /** * Use a [PathChooser] for opening directories. */ fun SerializedConfiguration<Path>.openDirectory() { uiNode = PathChooser(isDirectory = true, isOpen = true) } /** * Create a [PathChooser] for saving files. */ fun saveFile(): PathChooser { return PathChooser(isDirectory = false, isOpen = false) } /** * Use a [PathChooser] for saving files. */ fun SerializedConfiguration<Path>.saveFile() { uiNode = PathChooser(isDirectory = false, isOpen = false) } /** * Create a [FileChooser] for opening files. */ fun openLegacyFile(): FileChooser { return FileChooser(isDirectory = false, isOpen = true) } /** * Use a [FileChooser] for opening files. */ fun SerializedConfiguration<File>.openLegacyFile() { uiNode = FileChooser(isDirectory = false, isOpen = true) } /** * Create a [FileChooser] for opening directories. */ fun openLegacyDirectory(): FileChooser { return FileChooser(isDirectory = true, isOpen = true) } /** * Use a [FileChooser] for opening directories. */ fun SerializedConfiguration<File>.openLegacyDirectory() { uiNode = FileChooser(isDirectory = true, isOpen = true) } /** * Create a [FileChooser] for saving files. */ fun saveLegacyFile(): FileChooser { return FileChooser(isDirectory = false, isOpen = false) } /** * Use a [FileChooser] for saving files. */ fun SerializedConfiguration<File>.saveLegacyFile() { uiNode = FileChooser(isDirectory = false, isOpen = false) } /** * Configuration object for DSL. * * ### Required * * - [describe] * - [refresh] * * ### Optional * * - [lazy] */ class ChoiceBoxConfiguration<T> internal constructor() { private lateinit var descriptor: (T) -> String private lateinit var onRefresh: suspend () -> List<T>? private var lazy: Boolean = false /** * Set a function to describe a selected element. * * @see ChoiceBox.descriptor */ fun describe(descriptor: (T) -> String) { this.descriptor = descriptor } /** * The function to call when the choice items are updated. * * @see ChoiceBox.refresh */ fun refresh(action: suspend () -> List<T>?) { this.onRefresh = action } /** * Load the choice items lazily. * * @see ChoiceBox.lazy */ fun lazy() { lazy = true } internal fun toNode(): ChoiceBox<T> { val exceptionMessage = when { !::descriptor.isInitialized -> "descriptor not set" !::onRefresh.isInitialized -> "action not set" else -> null } if (exceptionMessage != null) throw IllegalStateException(exceptionMessage) return ChoiceBox( descriptor = descriptor, refresh = onRefresh, lazy = lazy ) } } /** * Create a [ChoiceBox]. */ fun <T> choiceBox(configure: ChoiceBoxConfiguration<T>.() -> Unit): ChoiceBox<T> { val config = ChoiceBoxConfiguration<T>() config.configure() return config.toNode() } /** * Create and use a [ChoiceBox]. */ fun <T> SerializedConfiguration<T>.choiceBox( configure: ChoiceBoxConfiguration<T>.() -> Unit ) { val config = ChoiceBoxConfiguration<T>() config.configure() uiNode = config.toNode() }
mit
e32526586252d57dd867e876b6651186
22.102362
91
0.633606
4.305209
false
true
false
false
FFlorien/AmpachePlayer
app/src/main/java/be/florien/anyflow/player/PlayingQueue.kt
1
4371
package be.florien.anyflow.player import android.content.SharedPreferences import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.map import androidx.paging.PagingData import androidx.paging.cachedIn import be.florien.anyflow.data.DataRepository import be.florien.anyflow.data.local.model.DbSongToPlay import be.florien.anyflow.data.toDbSongToPlay import be.florien.anyflow.data.view.Order import be.florien.anyflow.data.view.Song import be.florien.anyflow.data.view.SongInfo import be.florien.anyflow.extension.applyPutInt import be.florien.anyflow.injection.UserScope import kotlinx.coroutines.* import javax.inject.Inject /** * Event handler for the queue of songs that are playing. */ @UserScope class PlayingQueue @Inject constructor( private val dataRepository: DataRepository, private val sharedPreferences: SharedPreferences, private val orderComposer: OrderComposer ) { companion object { private const val POSITION_NOT_SET = -5 private const val POSITION_PREF = "POSITION_PREF" } var listPositionWithIntent = PositionWithIntent(POSITION_NOT_SET, PlayingQueueIntent.PAUSE) get() { if (field.position == POSITION_NOT_SET) { listPositionWithIntent = PositionWithIntent( sharedPreferences.getInt(POSITION_PREF, 0), PlayingQueueIntent.PAUSE ) } return field } set(value) { if (value.position <= queueSize - 1) { field = value MainScope().launch { val currentSongId = songIdsListUpdater.value?.get(value.position) ?: DbSongToPlay(0L, null) val nextSongId = songIdsListUpdater.value?.getOrNull(value.position + 1) ?: DbSongToPlay(0L, null) (stateUpdater as MutableLiveData).value = PlayingQueueState(currentSongId, nextSongId, field.intent) positionUpdater.value = field.position orderComposer.currentPosition = field.position sharedPreferences.applyPutInt(POSITION_PREF, field.position) val songAtPosition = dataRepository.getSongAtPosition(field.position) if (songAtPosition != [email protected]) { ([email protected] as MutableLiveData).value = songAtPosition orderComposer.currentSong = songAtPosition } } } } var listPosition: Int get() { return listPositionWithIntent.position } set(value) { val previousIntent = listPositionWithIntent.intent listPositionWithIntent = PositionWithIntent(value, previousIntent) } var queueSize: Int = 0 val positionUpdater = MutableLiveData<Int>() val currentSong: LiveData<SongInfo> = MutableLiveData() val songDisplayListUpdater: LiveData<PagingData<Song>> = dataRepository.getSongsInQueueOrder().cachedIn(CoroutineScope(Dispatchers.Default)) private val songIdsListUpdater: LiveData<List<DbSongToPlay>> = dataRepository.getIdsInQueueOrder() val stateUpdater: LiveData<PlayingQueueState> = MutableLiveData() val isOrderedUpdater: LiveData<Boolean> = dataRepository.getOrders() .map { orderList -> orderList.none { it.orderingType == Order.Ordering.RANDOM } } init { songIdsListUpdater.observeForever { queueSize = it.size val indexOf = if (currentSong.value == null) { listPosition } else { it.indexOf(currentSong.value?.toDbSongToPlay()) } listPosition = if (indexOf >= 0) indexOf else 0 } GlobalScope.launch(Dispatchers.IO) { queueSize = dataRepository.getQueueSize() ?: 0 } } class PlayingQueueState( val currentSong: DbSongToPlay, val nextSong: DbSongToPlay?, val intent: PlayingQueueIntent ) enum class PlayingQueueIntent { START, PAUSE, CONTINUE } class PositionWithIntent(val position: Int, val intent: PlayingQueueIntent) }
gpl-3.0
969ac0c836b84b8a513543a85e3263c5
36.367521
97
0.642645
5.234731
false
false
false
false
kotlin-graphics/uno-sdk
core/src/test/kotlin/uno/awe.kt
1
4983
//package uno // //import glm_.and //import org.lwjgl.glfw.Callbacks.glfwFreeCallbacks //import org.lwjgl.glfw.GLFW.* //import org.lwjgl.glfw.GLFWErrorCallback //import org.lwjgl.glfw.GLFWVidMode //import org.lwjgl.opengl.GL //import org.lwjgl.opengl.GL11C.GL_COLOR_BUFFER_BIT //import org.lwjgl.opengl.GL11C.glClear //import org.lwjgl.system.MemoryStack.stackPush //import org.lwjgl.system.MemoryUtil.NULL //import org.lwjgl.util.tinyfd.TinyFileDialogs.* //import java.util.* // //object HelloTinyFD { // // @JvmStatic // fun main(args: Array<String>) { // GLFWErrorCallback.createPrint().set() // if (!glfwInit()) { // throw IllegalStateException("Unable to initialize GLFW") // } // // val window = glfwCreateWindow(300, 300, "Hello tiny file dialogs!", NULL, NULL) // if (window == NULL) { // throw RuntimeException("Failed to create the GLFW window") // } // // glfwSetKeyCallback(window) { windowHnd, key, scancode, action, mods -> // if (action == GLFW_RELEASE) { // return@glfwSetKeyCallback // } // // when (key) { // GLFW_KEY_ESCAPE -> glfwSetWindowShouldClose(windowHnd, true) // GLFW_KEY_B -> tinyfd_beep() // GLFW_KEY_N -> { // println("\nOpening notification popup...") // println(tinyfd_notifyPopup("Please read...", "...this message.", "info")) // } // GLFW_KEY_1 -> { // println("\nOpening message dialog...") // println(if (tinyfd_messageBox("Please read...", "...this message.", "okcancel", "info", true)) "OK" else "Cancel") // } // GLFW_KEY_2 -> { // println("\nOpening input box dialog...") // println(tinyfd_inputBox("Input Value", "How old are you?", "30")) // } // GLFW_KEY_3 -> { // println("\nOpening file open dialog...") // println(tinyfd_openFileDialog("Open File(s)", "", null, null, true)) // } // GLFW_KEY_4 -> stackPush().use({ stack -> // val aFilterPatterns = stack.mallocPointer(2) // // aFilterPatterns.put(stack.UTF8("*.jpg")) // aFilterPatterns.put(stack.UTF8("*.png")) // // aFilterPatterns.flip() // // println("\nOpening file save dialog...") // println(tinyfd_saveFileDialog("Save Image", "", aFilterPatterns, "Image files (*.jpg, *.png)")) // }) // GLFW_KEY_5 -> { // println("\nOpening folder select dialog...") // println(tinyfd_selectFolderDialog("Select Folder", "")) // } // GLFW_KEY_6 -> { // println("\nOpening color chooser dialog...") // stackPush().use { stack -> // val color = stack.malloc(3) // val hex = tinyfd_colorChooser("Choose Color", "#FF00FF", null, color) // println(hex) // if (hex != null) { // println("\tR: " + (color.get(0) and 0xFF)) // println("\tG: " + (color.get(1) and 0xFF)) // println("\tB: " + (color.get(2) and 0xFF)) // } // } // } // } // } // // // Center window // val vidmode = Objects.requireNonNull<GLFWVidMode>(glfwGetVideoMode(glfwGetPrimaryMonitor())) // glfwSetWindowPos( // window, // (vidmode.width() - 300) / 2, // (vidmode.height() - 300) / 2 // ) // // glfwMakeContextCurrent(window) // GL.createCapabilities() // // glfwSwapInterval(1) // // tinyfd_messageBox("tinyfd_query", "", "ok", "info", true) // println("tiny file dialogs " + tinyfd_version + " (" + tinyfd_response() + ")") // println() // println(tinyfd_needs) // println() // println("Press 1 to launch a message dialog.") // println("Press 2 to launch an input box fialog.") // println("Press 3 to launch a file open dialog.") // println("Press 4 to launch a file save dialog.") // println("Press 5 to launch a folder select dialog.") // println("Press 6 to launch a color chooser dialog.") // while (!glfwWindowShouldClose(window)) { // glfwPollEvents() // // glClear(GL_COLOR_BUFFER_BIT) // glfwSwapBuffers(window) // } // // GL.setCapabilities(null) // // glfwFreeCallbacks(window) // glfwDestroyWindow(window) // glfwTerminate() // // Objects.requireNonNull<GLFWErrorCallback>(glfwSetErrorCallback(null)).free() // } // //}
mit
34fe966d0205a7e09ef4a90dc19dc14b
38.872
136
0.501706
4.107997
false
false
false
false
mockk/mockk
modules/mockk/src/jvmMain/kotlin/io/mockk/impl/instantiation/JvmStaticMockFactory.kt
2
2327
package io.mockk.impl.instantiation import io.mockk.InternalPlatformDsl.toStr import io.mockk.MockKException import io.mockk.MockKGateway import io.mockk.MockKGateway.StaticMockFactory import io.mockk.impl.InternalPlatform.hkd import io.mockk.impl.log.Logger import io.mockk.impl.stub.MockType import io.mockk.impl.stub.SpyKStub import io.mockk.impl.stub.StubGatewayAccess import io.mockk.impl.stub.StubRepository import io.mockk.proxy.MockKAgentException import io.mockk.proxy.MockKStaticProxyMaker import kotlin.reflect.KClass class JvmStaticMockFactory( val proxyMaker: MockKStaticProxyMaker, val stubRepository: StubRepository, val gatewayAccess: StubGatewayAccess ) : StaticMockFactory { val refCntMap = RefCounterMap<KClass<*>>() override fun staticMockk(cls: KClass<*>): () -> Unit { if (refCntMap.incrementRefCnt(cls)) { log.debug { "Creating static mockk for ${cls.toStr()}" } val stub = SpyKStub( cls, "static " + cls.simpleName, gatewayAccess, true, MockType.STATIC ) log.trace { "Building static proxy for ${cls.toStr()} hashcode=${hkd(cls)}" } val cancellation = try { proxyMaker.staticProxy(cls.java, JvmMockFactoryHelper.mockHandler(stub)) } catch (ex: MockKAgentException) { throw MockKException("Failed to build static proxy", ex) } stub.hashCodeStr = hkd(cls.java) stub.disposeRoutine = cancellation::cancel stubRepository.add(cls.java, stub) } return { if (refCntMap.decrementRefCnt(cls)) { val stub = stubRepository[cls.java] stub?.let { log.debug { "Disposing static mockk for $cls" } it.dispose() } } } } override fun clear( type: KClass<*>, options: MockKGateway.ClearOptions ) { stubRepository.get(type.java)?.clear(options) } override fun clearAll( options: MockKGateway.ClearOptions ) { stubRepository.allStubs.forEach { it.clear(options) } } companion object { val log = Logger<JvmStaticMockFactory>() } }
apache-2.0
e26b4d2f071c4a98b5f26020e2a6b0ae
28.455696
89
0.617533
4.44084
false
false
false
false
samtstern/quickstart-android
analytics/app/src/main/java/com/google/firebase/quickstart/analytics/kotlin/MainActivity.kt
1
8623
package com.google.firebase.quickstart.analytics.kotlin import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import androidx.preference.PreferenceManager import androidx.viewpager.widget.ViewPager import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import com.google.firebase.quickstart.analytics.R import com.google.firebase.quickstart.analytics.databinding.ActivityMainBinding import java.util.Locale /** * Activity which displays numerous background images that may be viewed. These background images * are shown via {@link ImageFragment}. */ class MainActivity : AppCompatActivity() { companion object { private const val TAG = "MainActivity" private const val KEY_FAVORITE_FOOD = "favorite_food" private val IMAGE_INFOS = arrayOf( ImageInfo(R.drawable.favorite, R.string.pattern1_title, R.string.pattern1_id), ImageInfo(R.drawable.flash, R.string.pattern2_title, R.string.pattern2_id), ImageInfo(R.drawable.face, R.string.pattern3_title, R.string.pattern3_id), ImageInfo(R.drawable.whitebalance, R.string.pattern4_title, R.string.pattern4_id) ) } private lateinit var binding: ActivityMainBinding /** * The [androidx.viewpager.widget.PagerAdapter] that will provide fragments for each image. * This uses a [FragmentPagerAdapter], which keeps every loaded fragment in memory. */ private lateinit var imagePagerAdapter: ImagePagerAdapter /** * The `FirebaseAnalytics` used to record screen views. */ // [START declare_analytics] private lateinit var firebaseAnalytics: FirebaseAnalytics // [END declare_analytics] override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) // [START shared_app_measurement] // Obtain the FirebaseAnalytics instance. firebaseAnalytics = Firebase.analytics // [END shared_app_measurement] // On first app open, ask the user his/her favorite food. Then set this as a user property // on all subsequent opens. val userFavoriteFood = getUserFavoriteFood() if (userFavoriteFood == null) { askFavoriteFood() } else { setUserFavoriteFood(userFavoriteFood) } // Create the adapter that will return a fragment for each image. imagePagerAdapter = ImagePagerAdapter(supportFragmentManager, IMAGE_INFOS) // Set up the ViewPager with the pattern adapter. binding.viewPager.adapter = imagePagerAdapter // Workaround for AppCompat issue not showing ViewPager titles val params = binding.pagerTabStrip.layoutParams as ViewPager.LayoutParams params.isDecor = true // When the visible image changes, send a screen view hit. binding.viewPager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() { override fun onPageSelected(position: Int) { recordImageView() recordScreenView() } }) // Send initial screen screen view hit. recordImageView() } public override fun onResume() { super.onResume() recordScreenView() } /** * Display a dialog prompting the user to pick a favorite food from a list, then record * the answer. */ private fun askFavoriteFood() { val choices = resources.getStringArray(R.array.food_items) val ad = AlertDialog.Builder(this) .setCancelable(false) .setTitle(R.string.food_dialog_title) .setItems(choices) { _, which -> val food = choices[which] setUserFavoriteFood(food) }.create() ad.show() } /** * Get the user's favorite food from shared preferences. * @return favorite food, as a string. */ private fun getUserFavoriteFood(): String? { return PreferenceManager.getDefaultSharedPreferences(this) .getString(KEY_FAVORITE_FOOD, null) } /** * Set the user's favorite food as an app measurement user property and in shared preferences. * @param food the user's favorite food. */ private fun setUserFavoriteFood(food: String) { Log.d(TAG, "setFavoriteFood: $food") PreferenceManager.getDefaultSharedPreferences(this).edit() .putString(KEY_FAVORITE_FOOD, food) .apply() // [START user_property] firebaseAnalytics.setUserProperty("favorite_food", food) // [END user_property] } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { val i = item.itemId if (i == R.id.menu_share) { val name = getCurrentImageTitle() val text = "I'd love you to hear about $name" val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_TEXT, text) sendIntent.type = "text/plain" startActivity(sendIntent) // [START custom_event] firebaseAnalytics.logEvent("share_image") { param("image_name", name) param("full_text", text) } // [END custom_event] } return false } /** * Return the title of the currently displayed image. * * @return title of image */ private fun getCurrentImageTitle(): String { val position = binding.viewPager.currentItem val info = IMAGE_INFOS[position] return getString(info.title) } /** * Return the id of the currently displayed image. * * @return id of image */ private fun getCurrentImageId(): String { val position = binding.viewPager.currentItem val info = IMAGE_INFOS[position] return getString(info.id) } /** * Record a screen view for the visible [ImageFragment] displayed * inside [FragmentPagerAdapter]. */ private fun recordImageView() { val id = getCurrentImageId() val name = getCurrentImageTitle() // [START image_view_event] firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_ITEM) { param(FirebaseAnalytics.Param.ITEM_ID, id) param(FirebaseAnalytics.Param.ITEM_NAME, name) param(FirebaseAnalytics.Param.CONTENT_TYPE, "image") } // [END image_view_event] } /** * This sample has a single Activity, so we need to manually record "screen views" as * we change fragments. */ private fun recordScreenView() { // This string must be <= 36 characters long in order for setCurrentScreen to succeed. val screenName = "${getCurrentImageId()}-${getCurrentImageTitle()}" // [START set_current_screen] firebaseAnalytics.setCurrentScreen(this, screenName, null /* class override */) // [END set_current_screen] } /** * A [FragmentPagerAdapter] that returns a fragment corresponding to * one of the sections/tabs/pages. */ @SuppressLint("WrongConstant") inner class ImagePagerAdapter( fm: FragmentManager, private val infos: Array<ImageInfo> ) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getItem(position: Int): Fragment { val info = infos[position] return ImageFragment.newInstance(info.image) } override fun getCount() = infos.size override fun getPageTitle(position: Int): CharSequence? { if (position < 0 || position >= infos.size) { return null } val l = Locale.getDefault() val info = infos[position] return getString(info.title).toUpperCase(l) } } }
apache-2.0
c4b850e0f2b12b4d4c1ca7a647e0527c
33.630522
99
0.648498
4.891095
false
false
false
false
sksamuel/akka-patterns
rxhive-core/src/main/kotlin/com/sksamuel/rxhive/schemas/FromHiveSchema.kt
1
3891
package com.sksamuel.rxhive.schemas import arrow.core.Option import arrow.core.getOrElse import arrow.core.orElse import com.sksamuel.rxhive.ArrayType import com.sksamuel.rxhive.BooleanType import com.sksamuel.rxhive.CharType import com.sksamuel.rxhive.DateType import com.sksamuel.rxhive.DecimalType import com.sksamuel.rxhive.Float32Type import com.sksamuel.rxhive.Float64Type import com.sksamuel.rxhive.Int16Type import com.sksamuel.rxhive.Int32Type import com.sksamuel.rxhive.Int64Type import com.sksamuel.rxhive.Int8Type import com.sksamuel.rxhive.Precision import com.sksamuel.rxhive.Scale import com.sksamuel.rxhive.StringType import com.sksamuel.rxhive.StructField import com.sksamuel.rxhive.StructType import com.sksamuel.rxhive.Type import com.sksamuel.rxhive.VarcharType import org.apache.hadoop.hive.metastore.api.FieldSchema import org.apache.hadoop.hive.metastore.api.Table object FromHiveSchema { object HiveRegexes { val decimal_r = "decimal\\(\\s*(\\d+?)\\s*,\\s*(\\d+?)\\s*\\)".toRegex() val array_r = "array<(.+?)>".toRegex() val char_r = "char\\(\\s*(\\d+?)\\s*\\)".toRegex() val struct_r = "struct<(.+?)>".toRegex() val struct_field_r = "(.+?):(.+?)(,|$)".toRegex() val varchar_r = "varchar\\(\\s*(\\d+?)\\s*\\)".toRegex() } fun fromHiveTable(table: Table): StructType { // in hive prior to 3.0, columns are null, partitions non-null val fields = table.sd.cols.map { StructField(it.name, fromFieldSchema(it), true) } + table.partitionKeys.map { StructField(it.name, fromFieldSchema(it), false) } return StructType(fields) } fun fromFieldSchema(schema: FieldSchema): Type = fromHiveType( schema.type) fun fromHiveType(type: String): Type { fun decimal(): Option<DecimalType> { val match = FromHiveSchema.HiveRegexes.decimal_r.matchEntire(type) return Option.fromNullable(match).map { val p = Precision(it.groupValues[1].toInt()) val s = Scale(it.groupValues[2].toInt()) DecimalType(p, s) } } fun varchar(): Option<VarcharType> { val match = FromHiveSchema.HiveRegexes.varchar_r.matchEntire(type) return Option.fromNullable(match).map { val size = it.groupValues[1].toInt() VarcharType(size) } } fun char(): Option<CharType> { val match = FromHiveSchema.HiveRegexes.char_r.matchEntire(type) return Option.fromNullable(match).map { val size = it.groupValues[1].toInt() CharType(size) } } fun struct(): Option<StructType> { val match = FromHiveSchema.HiveRegexes.struct_r.matchEntire(type) return Option.fromNullable(match).map { structMatch -> val fields = FromHiveSchema.HiveRegexes.struct_field_r.findAll(structMatch.groupValues[1].trim()).map { fieldMatch -> StructField(fieldMatch.groupValues[1].trim(), fromHiveType(fieldMatch.groupValues[2].trim())) } StructType(fields.toList()) } } fun array(): Option<ArrayType> { val match = FromHiveSchema.HiveRegexes.array_r.matchEntire(type) return Option.fromNullable(match).map { val elementType = fromHiveType(it.groupValues[1].trim()) ArrayType(elementType) } } return when (type) { HiveTypes.string -> StringType HiveTypes.boolean -> BooleanType HiveTypes.double -> Float64Type HiveTypes.float -> Float32Type HiveTypes.bigint -> Int64Type HiveTypes.int -> Int32Type HiveTypes.smallint -> Int16Type HiveTypes.tinyint -> Int8Type HiveTypes.date -> DateType else -> { decimal() .orElse { varchar() } .orElse { array() } .orElse { char() } .orElse { struct() } .getOrElse { throw UnsupportedOperationException("Unknown hive type $type") } } } } }
apache-2.0
986433c645406760e10ce021380d5da1
32.264957
125
0.665639
4.019628
false
false
false
false
chrimaeon/app-rater
library/src/main/java/com/cmgapps/android/apprater/AppRater.kt
1
8555
/* * Copyright (c) 2016. Christian Grach <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cmgapps.android.apprater import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager.NameNotFoundException import android.os.Build import android.text.format.DateUtils import android.util.Log import android.view.MotionEvent import androidx.annotation.VisibleForTesting import androidx.appcompat.app.AlertDialog import com.cmgapps.android.apprater.databinding.DialogContentBinding import com.cmgapps.android.apprater.store.GooglePlayStore import com.cmgapps.android.apprater.store.Store class AppRater private constructor(builder: Builder) { private val debug = builder.debug private val launchesUntilPrompt = builder.launchesUntilPrompt private val daysUntilPrompt = builder.daysUntilPrompt private val daysUntilRemindAgain = builder.daysUntilRemindAgain private val store = builder.store private val preferenceManager = PreferenceManager(builder.context, builder.clock) private val versionCode: Long = try { val context = builder.context val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { @Suppress("DEPRECATION") packageInfo.versionCode.toLong() } else { packageInfo.longVersionCode } } catch (exc: NameNotFoundException) { Log.e(TAG, "PackageName not found: " + builder.context.packageName) 0 } private val clock = builder.clock /** * Call to check if the requirements to open the rating dialog are met * * @return true if requirements are met. */ fun checkForRating(): Boolean { if (debug) { Log.i(TAG, "Rater Content:" + toString()) } val now = clock.millis() return !preferenceManager.declinedToRate && !preferenceManager.appRated && now >= preferenceManager.firstUsedTimestamp + daysUntilPrompt && preferenceManager.useCount > launchesUntilPrompt && now >= preferenceManager.remindLaterTimeStamp + daysUntilRemindAgain } /** * Increments the usage count. */ fun incrementUseCount() { var trackingVersion = preferenceManager.trackingVersion if (trackingVersion == -1L) { trackingVersion = versionCode preferenceManager.trackingVersion = trackingVersion } if (trackingVersion == versionCode) { if (preferenceManager.useCount.toLong() == 0L) { preferenceManager.firstUsedTimestamp = clock.millis() } preferenceManager.incrementUseCount() } else { preferenceManager.resetNewVersion(versionCode) } } /** * Shows a default [AlertDialog]. * * @param activity An [Activity] to show the dialog from. */ @SuppressLint("ClickableViewAccessibility") fun show(activity: Activity) { val pm = activity.packageManager val appName = try { pm.getApplicationInfo(activity.packageName, 0).let { pm.getApplicationLabel(it) } } catch (e: NameNotFoundException) { Log.e(TAG, "Application name can not be found") "App" } val dialogContentBinding = DialogContentBinding.inflate(activity.layoutInflater).apply { header.text = activity.getString(R.string.dialog_cmgrate_message_fmt, appName) } AlertDialog.Builder(activity) .setTitle(R.string.dialog_cmgrate_title) .setView(dialogContentBinding.root) .setPositiveButton(R.string.dialog_cmgrate_ok) { _, _ -> setCurrentVersionRated() val intent = Intent(Intent.ACTION_VIEW, store.getStoreUri(activity)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) activity.startActivity(intent) } .setNeutralButton(R.string.dialog_cmgrate_later) { _, _ -> preferenceManager.remindLaterTimeStamp = clock.millis() } .setNegativeButton(R.string.dialog_cmgrate_no) { _, _ -> preferenceManager.declinedToRate = true } .setOnCancelListener { preferenceManager.remindLaterTimeStamp = clock.millis() }.create().also { dialogContentBinding.ratingBar.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_UP) { setCurrentVersionRated() val intent = Intent(Intent.ACTION_VIEW, store.getStoreUri(activity)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) activity.startActivity(intent) it.dismiss() } true } }.show() } /** * Get the [SharedPreferences] file contents */ override fun toString(): String { return preferenceManager.toString() } /** * Manually set the rated flag for the current version. * * Useful when not using the provided [AlertDialog]; i.e. when using * [Google Play In-App Review API](https://developer.android.com/guide/playcore/in-app-review) * */ fun setCurrentVersionRated() { preferenceManager.appRated = true } /** * Builder for [AppRater] * * default values: * * store = [GooglePlayStore] * * launchesUntilPrompt = 5 * * daysUntilPrompt = 10 * * daysUntilRemindAgain = 5 * * debug = false * */ class Builder { constructor(context: Context) { this.context = context.applicationContext this.clock = SystemClock() } @VisibleForTesting internal constructor(context: Context, clock: Clock) { this.context = context.applicationContext this.clock = clock } internal val context: Context internal val clock: Clock internal var store: Store = GooglePlayStore() private set internal var launchesUntilPrompt = 5 private set internal var daysUntilPrompt = 10 * DateUtils.DAY_IN_MILLIS private set internal var daysUntilRemindAgain = 5 * DateUtils.DAY_IN_MILLIS private set internal var debug = false private set /** * Set the store to open for rating */ fun store(store: Store) = apply { this.store = store } /** * Sets the minimum app launches until the dialog is shown */ fun launchesUntilPrompt(launchesUntilPrompt: Int) = apply { this.launchesUntilPrompt = launchesUntilPrompt } /** * Set the minimal days to pass until the dialog is shown */ fun daysUntilPrompt(daysUntilPrompt: Int) = apply { this.daysUntilPrompt = daysUntilPrompt * DateUtils.DAY_IN_MILLIS } /** * Set the days until the dialog is shown again */ fun daysUntilRemindAgain(daysUntilRemindAgain: Int) = apply { this.daysUntilRemindAgain = daysUntilRemindAgain * DateUtils.DAY_IN_MILLIS } /** * Enables debug mode with Logcat output id the current state */ fun debug(debug: Boolean) = apply { this.debug = debug } /** * creates the App Rater instance */ fun build(): AppRater { return AppRater(this) } } private companion object { private const val TAG = "AppRater" } }
apache-2.0
650e8ae8047bdfda7acb8fc21121fc14
31.405303
98
0.614962
5.089233
false
false
false
false
icapps/niddler-ui
client-lib/src/main/kotlin/com/icapps/niddler/lib/model/BaseUrlHider.kt
1
938
package com.icapps.niddler.lib.model import java.util.concurrent.CopyOnWriteArrayList class BaseUrlHider { private val hiddenBaseUrls = CopyOnWriteArrayList<String>() fun getHiddenBaseUrl(url: String): String? { var longestMatch: String? = null hiddenBaseUrls.forEach { hiddenBase -> if (url.startsWith(hiddenBase)) { if (longestMatch == null || longestMatch!!.length < hiddenBase.length) longestMatch = hiddenBase } } return longestMatch } fun getHiddenBaseUrls(): Collection<String> { return hiddenBaseUrls } fun updateHiddenBaseUrls(newList: Collection<String>) { hiddenBaseUrls.clear() hiddenBaseUrls.addAll(newList) } fun hideBaseUrl(baseUrl: String) { hiddenBaseUrls += baseUrl } fun unhideBaseUrl(baseUrl: String) { hiddenBaseUrls -= baseUrl } }
apache-2.0
32f99b7de8beb850b0e3a1337558ca45
23.710526
86
0.634328
5.016043
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/activity/WebLinkHandlerActivity.kt
1
20136
/* * 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.app.Activity import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.TextUtils import org.mariotaku.chameleon.Chameleon import org.mariotaku.ktextension.toLongOr import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.activity.content.FavoriteConfirmDialogActivity import de.vanita5.twittnuker.activity.content.RetweetQuoteDialogActivity import de.vanita5.twittnuker.app.TwittnukerApplication import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.util.Analyzer import de.vanita5.twittnuker.util.IntentUtils import de.vanita5.twittnuker.util.ThemeUtils import de.vanita5.twittnuker.util.dagger.DependencyHolder import java.util.* class WebLinkHandlerActivity : Activity() { private val userTheme: Chameleon.Theme by lazy { val preferences = DependencyHolder.get(this).preferences return@lazy ThemeUtils.getUserTheme(this, preferences) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val packageManager = packageManager intent.setExtrasClassLoader(TwittnukerApplication::class.java.classLoader) val uri = intent.data if (uri == null || uri.host == null) { finish() return } val (handledIntent, handledSuccessfully) = when (uri.host.toLowerCase(Locale.US)) { "twitter.com", "www.twitter.com", "mobile.twitter.com" -> handleTwitterLink(regulateTwitterUri(uri)) "fanfou.com" -> handleFanfouLink(uri) "twittnuker.org" -> handleTwidereExternalLink(uri) else -> Pair(null, false) } if (handledIntent != null) { handledIntent.putExtras(intent) startActivity(handledIntent) } else { if (!handledSuccessfully) { Analyzer.logException(TwitterLinkException("Unable to handle twitter uri " + uri)) } val fallbackIntent = Intent(Intent.ACTION_VIEW, uri) fallbackIntent.addCategory(Intent.CATEGORY_BROWSABLE) fallbackIntent.`package` = IntentUtils.getDefaultBrowserPackage(this, uri, false) val componentName = fallbackIntent.resolveActivity(packageManager) if (componentName == null) { val targetIntent = Intent(Intent.ACTION_VIEW, uri) targetIntent.addCategory(Intent.CATEGORY_BROWSABLE) startActivity(Intent.createChooser(targetIntent, getString(R.string.action_open_in_browser))) } else if (!TextUtils.equals(packageName, componentName.packageName)) { startActivity(fallbackIntent) } else { // TODO show error } } finish() } override fun onStart() { super.onStart() setVisible(true) } private fun handleTwidereExternalLink(uri: Uri): Pair<Intent?, Boolean> { val pathSegments = uri.pathSegments if (pathSegments.size < 2 || pathSegments[0] != "external") { return Pair(null, false) } val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(pathSegments[1]) if (pathSegments.size >= 3) { for (segment in pathSegments.slice(2..pathSegments.lastIndex)) { builder.appendPath(segment) } } builder.encodedQuery(uri.encodedQuery) builder.encodedFragment(uri.encodedFragment) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } private fun handleFanfouLink(uri: Uri): Pair<Intent?, Boolean> { val pathSegments = uri.pathSegments if (pathSegments.size > 0) { when (pathSegments[0]) { "statuses" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_STATUS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_FANFOU_COM) builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, pathSegments[1]) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } else -> { if (FANFOU_RESERVED_PATHS.contains(pathSegments[0])) return Pair(null, false) if (pathSegments.size == 1) { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_FANFOU_COM) val userKey = UserKey(pathSegments[0], USER_TYPE_FANFOU_COM) builder.appendQueryParameter(QUERY_PARAM_USER_KEY, userKey.toString()) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } return Pair(null, false) } } } return Pair(null, false) } private fun handleTwitterLink(uri: Uri): Pair<Intent?, Boolean> { val pathSegments = uri.pathSegments if (pathSegments.size > 0) { when (pathSegments[0]) { "i" -> { return getIUriIntent(uri, pathSegments) } "intent" -> { return getTwitterIntentUriIntent(uri, pathSegments) } "share" -> { val handledIntent = Intent(this, ComposeActivity::class.java) handledIntent.action = Intent.ACTION_SEND handledIntent.putExtra(Intent.EXTRA_TEXT, uri.getQueryParameter("text")) handledIntent.putExtra(Intent.EXTRA_SUBJECT, uri.getQueryParameter("url")) return Pair(handledIntent, true) } "search" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_SEARCH) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_QUERY, uri.getQueryParameter("q")) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "hashtag" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_SEARCH) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_QUERY, "#${uri.lastPathSegment}") return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "following" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_FRIENDS) builder.appendQueryParameter(QUERY_PARAM_USER_KEY, UserKey.SELF.toString()) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "followers" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_FOLLOWERS) builder.appendQueryParameter(QUERY_PARAM_USER_KEY, UserKey.SELF.toString()) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "favorites" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_FAVORITES) builder.appendQueryParameter(QUERY_PARAM_USER_KEY, UserKey.SELF.toString()) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } else -> { if (pathSegments[0] in TWITTER_RESERVED_PATHS) { return Pair(null, true) } return handleUserSpecificPageIntent(uri, pathSegments, pathSegments[0]) } } } val homeIntent = Intent(this, HomeActivity::class.java) return Pair(homeIntent, true) } private fun handleUserSpecificPageIntent(uri: Uri, pathSegments: List<String>, screenName: String): Pair<Intent?, Boolean> { val segsSize = pathSegments.size if (segsSize == 1) { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } else if (segsSize == 2) { when (pathSegments[1]) { "following" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_FRIENDS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "followers" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_FOLLOWERS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "favorites" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_FAVORITES) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } else -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_LIST) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) builder.appendQueryParameter(QUERY_PARAM_LIST_NAME, pathSegments[1]) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } } } else if (segsSize >= 3) { if ("status" == pathSegments[1] && pathSegments[2].toLongOr(-1L) != -1L) { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_STATUS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, pathSegments[2]) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } else { when (pathSegments[2]) { "members" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_LIST_MEMBERS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) builder.appendQueryParameter(QUERY_PARAM_LIST_NAME, pathSegments[1]) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } "subscribers" -> { val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_USER_LIST_SUBSCRIBERS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_SCREEN_NAME, screenName) builder.appendQueryParameter(QUERY_PARAM_LIST_NAME, pathSegments[1]) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } } } } return Pair(null, false) } private fun getTwitterIntentUriIntent(uri: Uri, pathSegments: List<String>): Pair<Intent?, Boolean> { if (pathSegments.size < 2) return Pair(null, false) when (pathSegments[1]) { "tweet" -> { val handledIntent = Intent(this, ComposeActivity::class.java) handledIntent.action = Intent.ACTION_SEND val text = uri.getQueryParameter("text") val url = uri.getQueryParameter("url") val sb = StringBuilder() if (!text.isNullOrEmpty()) { sb.append(text) } if (!url.isNullOrEmpty()) { if (!sb.isEmpty()) { sb.append(" ") } sb.append(url) } handledIntent.putExtra(Intent.EXTRA_TEXT, sb.toString()) return Pair(handledIntent, true) } "retweet" -> { val tweetId = uri.getQueryParameter("tweet_id") ?: return Pair(null, false) val accountHost = USER_TYPE_TWITTER_COM val intent = Intent(this, RetweetQuoteDialogActivity::class.java) intent.putExtra(EXTRA_STATUS_ID, tweetId) intent.putExtra(EXTRA_ACCOUNT_HOST, accountHost) return Pair(intent, true) } "favorite", "like" -> { val tweetId = uri.getQueryParameter("tweet_id") ?: return Pair(null, false) val accountHost = USER_TYPE_TWITTER_COM val intent = Intent(this, FavoriteConfirmDialogActivity::class.java) intent.putExtra(EXTRA_STATUS_ID, tweetId) intent.putExtra(EXTRA_ACCOUNT_HOST, accountHost) return Pair(intent, true) } "user", "follow" -> { val userKey = uri.getQueryParameter("user_id")?.let { UserKey(it, "twitter.com") } val screenName = uri.getQueryParameter("screen_name") return Pair(IntentUtils.userProfile(accountKey = null, userKey = userKey, screenName = screenName, accountHost = USER_TYPE_TWITTER_COM), true) } } return Pair(null, false) } private fun getIUriIntent(uri: Uri, pathSegments: List<String>): Pair<Intent?, Boolean> { if (pathSegments.size < 2) return Pair(null, false) when (pathSegments[1]) { "moments" -> { val preferences = DependencyHolder.get(this).preferences val (intent, _) = IntentUtils.browse(this, preferences, userTheme, uri, true) return Pair(intent, true) } "web" -> { if (pathSegments.size < 3) return Pair(null, false) when (pathSegments[2]) { "status" -> { if (pathSegments.size < 4) return Pair(null, false) val builder = Uri.Builder() builder.scheme(SCHEME_TWITTNUKER) builder.authority(AUTHORITY_STATUS) builder.appendQueryParameter(QUERY_PARAM_ACCOUNT_HOST, USER_TYPE_TWITTER_COM) builder.appendQueryParameter(QUERY_PARAM_STATUS_ID, pathSegments[3]) return Pair(Intent(Intent.ACTION_VIEW, builder.build()), true) } } } "redirect" -> { val url = uri.getQueryParameter("url")?.let(Uri::parse) ?: return Pair(null, false) val preferences = DependencyHolder.get(this).preferences val (intent, _) = IntentUtils.browse(this, preferences, userTheme, url, false) return Pair(intent, true) } } return Pair(null, false) } private inner class TwitterLinkException(s: String) : Exception(s) companion object { val TWITTER_RESERVED_PATHS = arrayOf("about", "account", "accounts", "activity", "all", "announcements", "anywhere", "api_rules", "api_terms", "apirules", "apps", "auth", "badges", "blog", "business", "buttons", "contacts", "devices", "direct_messages", "download", "downloads", "edit_announcements", "faq", "favorites", "find_sources", "find_users", "followers", "following", "friend_request", "friendrequest", "friends", "goodies", "help", "home", "im_account", "inbox", "invitations", "invite", "jobs", "list", "login", "logo", "logout", "me", "mentions", "messages", "mockview", "newtwitter", "notifications", "nudge", "oauth", "phoenix_search", "positions", "privacy", "public_timeline", "related_tweets", "replies", "retweeted_of_mine", "retweets", "retweets_by_others", "rules", "saved_searches", "search", "sent", "settings", "share", "signup", "signin", "similar_to", "statistics", "terms", "tos", "translate", "trends", "tweetbutton", "twttr", "update_discoverability", "users", "welcome", "who_to_follow", "widgets", "zendesk_auth", "media_signup") val FANFOU_RESERVED_PATHS = arrayOf("home", "privatemsg", "finder", "browse", "search", "settings", "message", "mentions", "favorites", "friends", "followers", "sharer", "photo", "album", "paipai", "q", "userview", "dialogue") private val AUTHORITY_TWITTER_COM = "twitter.com" private fun regulateTwitterUri(data: Uri): Uri { val encodedFragment = data.encodedFragment if (encodedFragment != null && encodedFragment.startsWith("!/")) { return regulateTwitterUri(Uri.parse("https://twitter.com" + encodedFragment.substring(1))) } val builder = data.buildUpon() builder.scheme("https") builder.authority(AUTHORITY_TWITTER_COM) return builder.build() } } }
gpl-3.0
ae5ff17b3e99f3a1aa0c5f899210f529
48.720988
128
0.57057
4.867295
false
false
false
false
Dmedina88/SSB
example/app/src/main/kotlin/com/grayherring/devtalks/base/util/RxSchedulers.kt
1
1254
package com.grayherring.devtalks.base.util import io.reactivex.Flowable import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.util.concurrent.TimeUnit.MILLISECONDS val THROTTLE = 300L val THROTTLE_TEXT = 1000L fun <T> Flowable<T>.applySchedulers(): Flowable<T> = subscribeOn(Schedulers.computation()).observeOn(AndroidSchedulers.mainThread()) fun <T> Flowable<T>.applyThrottle(): Flowable<T> = throttleFirst(THROTTLE, MILLISECONDS) fun <T> Flowable<T>.doAll(): Flowable<T> = applySchedulers().applyThrottle() fun <T> Observable<T>.applySchedulers(): Observable<T> = subscribeOn(Schedulers.computation()).observeOnMainThread() fun <T> Observable<T>.observeOnMainThread(): Observable<T> = observeOn(AndroidSchedulers.mainThread()) fun <T> Observable<T>.mainThread(): Observable<T> = observeOn(AndroidSchedulers.mainThread()).subscribeOn(AndroidSchedulers.mainThread()) fun <T> Observable<T>.applyThrottle(): Observable<T> = throttleFirst(THROTTLE, MILLISECONDS) fun <T> Observable<T>.doAll(): Observable<T> = applySchedulers().applyThrottle() fun <T> Observable<T>.throttleLast(): Observable<T> = throttleLast(THROTTLE_TEXT, MILLISECONDS)
apache-2.0
db071e24d4c2daa473053e89410bd2b8
35.882353
95
0.77512
4.045161
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/integration-tests/foundation-demos/src/main/java/androidx/compose/foundation/demos/text/ComposeMultiParagraph.kt
3
4964
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.demos.text import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.ParagraphStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextIndent import androidx.compose.ui.text.withStyle import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.sp val lorem = loremIpsum(wordCount = 14) @Preview @Composable fun MultiParagraphDemo() { LazyColumn { item { TagLine(tag = "multiple paragraphs basic") TextDemoParagraph() } item { TagLine(tag = "multiple paragraphs TextAlign") TextDemoParagraphTextAlign() } item { TagLine(tag = "multiple paragraphs line height") TextDemoParagraphLineHeight() } item { TagLine(tag = "multiple paragraphs TextIndent") TextDemoParagraphIndent() } item { TagLine(tag = "multiple paragraphs TextDirection") TextDemoParagraphTextDirection() } } } @Preview @Composable fun TextDemoParagraph() { val text1 = "paragraph1 paragraph1 paragraph1 paragraph1 paragraph1" val text2 = "paragraph2 paragraph2 paragraph2 paragraph2 paragraph2" Text( text = buildAnnotatedString { append(text1) withStyle(ParagraphStyle()) { append(text2) } }, style = TextStyle(fontSize = fontSize6) ) } @Preview @Composable fun TextDemoParagraphTextAlign() { val annotatedString = buildAnnotatedString { TextAlign.values().forEach { textAlign -> val str = List(4) { "TextAlign.$textAlign" }.joinToString(" ") withStyle(ParagraphStyle(textAlign = textAlign)) { append(str) } } } Text(text = annotatedString, style = TextStyle(fontSize = fontSize6)) } @Composable fun TextDemoParagraphLineHeight() { val text1 = "LineHeight=30sp: $lorem" val text2 = "LineHeight=40sp: $lorem" val text3 = "LineHeight=50sp: $lorem" Text( text = AnnotatedString( text = text1 + text2 + text3, spanStyles = listOf(), paragraphStyles = listOf( AnnotatedString.Range( ParagraphStyle(lineHeight = 30.sp), 0, text1.length ), AnnotatedString.Range( ParagraphStyle(lineHeight = 40.sp), text1.length, text1.length + text2.length ), AnnotatedString.Range( ParagraphStyle(lineHeight = 50.sp), text1.length + text2.length, text1.length + text2.length + text3.length ) ) ), style = TextStyle(fontSize = fontSize6) ) } @Preview @Composable fun TextDemoParagraphIndent() { val text1 = "TextIndent firstLine TextIndent firstLine TextIndent firstLine" val text2 = "TextIndent restLine TextIndent restLine TextIndent restLine" Text( text = buildAnnotatedString { withStyle(ParagraphStyle(textIndent = TextIndent(firstLine = 20.sp))) { append(text1) } withStyle(ParagraphStyle(textIndent = TextIndent(restLine = 20.sp))) { append(text2) } }, style = TextStyle(fontSize = fontSize6) ) } @Composable fun TextDemoParagraphTextDirection() { val ltrText = "Hello World! Hello World! Hello World! Hello World! Hello World!" val rtlText = "مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم مرحبا بالعالم" Text( text = buildAnnotatedString { withStyle(ParagraphStyle()) { append(ltrText) } withStyle(ParagraphStyle()) { append(rtlText) } }, style = TextStyle(fontSize = fontSize6) ) }
apache-2.0
2df68c21c3e11445b734fc00de33a9dd
30.037975
89
0.619086
4.770428
false
false
false
false
AndroidX/androidx
lifecycle/lifecycle-runtime-ktx/src/main/java/androidx/lifecycle/DispatchQueue.kt
3
3567
/* * 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.lifecycle import android.annotation.SuppressLint import androidx.annotation.AnyThread import androidx.annotation.MainThread import kotlinx.coroutines.Dispatchers import java.util.ArrayDeque import java.util.Queue import kotlin.coroutines.CoroutineContext /** * Helper class for [PausingDispatcher] that tracks runnables which are enqueued to the dispatcher * and also calls back the [PausingDispatcher] when the runnable should run. */ internal class DispatchQueue { // handler thread private var paused: Boolean = true // handler thread private var finished: Boolean = false private var isDraining: Boolean = false private val queue: Queue<Runnable> = ArrayDeque<Runnable>() @MainThread fun pause() { paused = true } @MainThread fun resume() { if (!paused) { return } check(!finished) { "Cannot resume a finished dispatcher" } paused = false drainQueue() } @MainThread fun finish() { finished = true drainQueue() } @MainThread fun drainQueue() { if (isDraining) { // Block re-entrant calls to avoid deep stacks return } try { isDraining = true while (queue.isNotEmpty()) { if (!canRun()) { break } queue.poll()?.run() } } finally { isDraining = false } } @MainThread fun canRun() = finished || !paused @AnyThread @SuppressLint("WrongThread") // false negative, we are checking the thread fun dispatchAndEnqueue(context: CoroutineContext, runnable: Runnable) { with(Dispatchers.Main.immediate) { // This check is here to handle a special but important case. If for example // launchWhenCreated is used while not created it's expected that it will run // synchronously when the lifecycle is created. If we called `dispatch` here // it launches made before the required state is reached would always be deferred // which is not the intended behavior. // // This means that calling `yield()` while paused and then receiving `resume` right // after leads to the runnable being run immediately but that is indeed intended. // This could be solved by implementing `dispatchYield` in the dispatcher but it's // marked as internal API. if (isDispatchNeeded(context) || canRun()) { dispatch(context, Runnable { enqueue(runnable) }) } else { enqueue(runnable) } } } @MainThread private fun enqueue(runnable: Runnable) { check(queue.offer(runnable)) { "cannot enqueue any more runnables" } drainQueue() } }
apache-2.0
3e5d04064ddea20f04ef9dcee945dbe0
30.289474
98
0.622932
4.92
false
false
false
false
peterLaurence/TrekAdvisor
app/src/main/java/com/peterlaurence/trekme/core/statistics/HpFilter.kt
1
1778
package com.peterlaurence.trekme.core.statistics /** * Implementation of Hodrick–Prescott filter. */ fun hpfilter(data: DoubleArray, lambda: Double = 1600.0): DoubleArray { val n = data.size if (n < 3) { return data } val a = DoubleArray(n) val b = DoubleArray(n) val c = DoubleArray(n) a[0] = 1 + lambda b[0] = -2 * lambda c[0] = lambda var K = 1 while (K < n - 2) { a[K] = 6 * lambda + 1 b[K] = -4 * lambda c[K] = lambda K++ } a[1] = 5 * lambda + 1 a[n - 1] = 1 + lambda a[n - 2] = 5 * lambda + 1 b[0] = -2 * lambda b[n - 2] = -2 * lambda b[n - 1] = 0.0 c[n - 2] = 0.0 c[n - 1] = 0.0 return pentas(a, b, c, data, n) } /** * Solves the linear equation system BxX=Y with B being a pentadiagonal matrix. */ private fun pentas(a: DoubleArray, b: DoubleArray, c: DoubleArray, data: DoubleArray, N: Int): DoubleArray { var K: Int = 0 var H1 = 0.0 var H2 = 0.0 var H3 = 0.0 var H4 = 0.0 var H5 = 0.0 var HH1: Double var HH2 = 0.0 var HH3 = 0.0 var HH5 = 0.0 var Z: Double var HB: Double var HC: Double while (K < N) { Z = a[K] - H4 * H1 - HH5 * HH2 HB = b[K] HH1 = H1 H1 = (HB - H4 * H2) / Z b[K] = H1 HC = c[K] HH2 = H2 H2 = HC / Z c[K] = H2 a[K] = (data[K] - HH3 * HH5 - H3 * H4) / Z HH3 = H3 H3 = a[K] H4 = HB - H5 * HH1 HH5 = H5 H5 = HC K++ } H2 = 0.0 H1 = a[N - 1] data[N - 1] = H1 K = N - 2 while (K > -1) { data[K] = a[K] - b[K] * H1 - c[K] * H2 H2 = H1 H1 = data[K] K-- } return data }
gpl-3.0
dbdd0c43ac96a1c22e90fae3c39b35de
18.527473
108
0.442568
2.615611
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/lang/core/stubs/index/RsReexportIndex.kt
3
3916
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.stubs.index import com.intellij.openapi.project.Project import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.stubs.AbstractStubIndex import com.intellij.psi.stubs.IndexSink import com.intellij.psi.stubs.StubIndexKey import com.intellij.util.io.KeyDescriptor import org.rust.lang.core.psi.RsUseItem import org.rust.lang.core.psi.RsUseSpeck import org.rust.lang.core.psi.ext.ancestorStrict import org.rust.lang.core.psi.ext.itemName import org.rust.lang.core.psi.ext.nameInScope import org.rust.lang.core.psi.ext.pathOrQualifier import org.rust.lang.core.stubs.RsFileStub import org.rust.lang.core.stubs.RsUseSpeckStub import org.rust.openapiext.checkCommitIsNotInProgress import org.rust.openapiext.getElements import java.io.DataInput import java.io.DataOutput class RsReexportIndex : AbstractStubIndex<ReexportKey, RsUseSpeck>() { override fun getVersion(): Int = RsFileStub.Type.stubVersion override fun getKey(): StubIndexKey<ReexportKey, RsUseSpeck> = KEY override fun getKeyDescriptor(): KeyDescriptor<ReexportKey> = ReexportKey.KeyDescriptor companion object { val KEY: StubIndexKey<ReexportKey, RsUseSpeck> = StubIndexKey.createIndexKey("org.rust.lang.core.stubs.index.RsReexportIndex") fun index(stub: RsUseSpeckStub, sink: IndexSink) { val useSpeck = stub.psi val isPublic = useSpeck.ancestorStrict<RsUseItem>()?.vis != null if (!isPublic) return val (originalName, producedName) = if (stub.isStarImport) { useSpeck.pathOrQualifier?.referenceName to null } else { useSpeck.itemName(withAlias = false) to useSpeck.nameInScope } originalName?.let { sink.occurrence(KEY, ReexportKey.OriginalNameKey(it)) } producedName?.let { sink.occurrence(KEY, ReexportKey.ProducedNameKey(it)) } } fun findReexportsByProducedName( project: Project, target: String, scope: GlobalSearchScope = GlobalSearchScope.allScope(project) ): Collection<RsUseSpeck> = findReexportsByName(project, ReexportKey.ProducedNameKey(target), scope) fun findReexportsByOriginalName( project: Project, target: String, scope: GlobalSearchScope = GlobalSearchScope.allScope(project) ): Collection<RsUseSpeck> = findReexportsByName(project, ReexportKey.OriginalNameKey(target), scope) private fun findReexportsByName( project: Project, key: ReexportKey, scope: GlobalSearchScope ): Collection<RsUseSpeck> { checkCommitIsNotInProgress(project) return getElements(KEY, key, project, scope) } } } sealed class ReexportKey { abstract val name: String /** * For `use foo as bar` use item, [name] is `foo` */ data class OriginalNameKey(override val name: String) : ReexportKey() /** * For `use foo as bar` use item, [name] is `bar` */ data class ProducedNameKey(override val name: String) : ReexportKey() object KeyDescriptor : com.intellij.util.io.KeyDescriptor<ReexportKey> { override fun save(out: DataOutput, value: ReexportKey) { out.writeBoolean(value is OriginalNameKey) out.writeUTF(value.name) } override fun read(`in`: DataInput): ReexportKey { val isOriginalNameKey = `in`.readBoolean() val name = `in`.readUTF() return if (isOriginalNameKey) OriginalNameKey(name) else ProducedNameKey(name) } override fun getHashCode(value: ReexportKey): Int = value.hashCode() override fun isEqual(lhs: ReexportKey, rhs: ReexportKey): Boolean = lhs == rhs } }
mit
a761e16cfa9dd051630cc9c887b77e32
37.392157
108
0.688202
4.527168
false
false
false
false
Tapchicoma/ultrasonic
ultrasonic/src/main/kotlin/org/moire/ultrasonic/activity/ArtistListModel.kt
1
4019
/* This file is part of Subsonic. Subsonic 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. Subsonic 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 Subsonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2020 (C) Jozsef Varga */ package org.moire.ultrasonic.activity import android.content.Context import android.os.Handler import android.os.Looper import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.moire.ultrasonic.data.ActiveServerProvider import org.moire.ultrasonic.domain.Artist import org.moire.ultrasonic.domain.MusicFolder import org.moire.ultrasonic.service.CommunicationErrorHandler import org.moire.ultrasonic.service.MusicServiceFactory import org.moire.ultrasonic.util.Util /** * Provides ViewModel which contains the list of available Artists */ class ArtistListModel( private val activeServerProvider: ActiveServerProvider, private val context: Context ) : ViewModel() { private val musicFolders: MutableLiveData<List<MusicFolder>> = MutableLiveData() private val artists: MutableLiveData<List<Artist>> = MutableLiveData() /** * Retrieves the available Artists in a LiveData */ fun getArtists(refresh: Boolean, swipe: SwipeRefreshLayout): LiveData<List<Artist>> { backgroundLoadFromServer(refresh, swipe) return artists } /** * Retrieves the available Music Folders in a LiveData */ fun getMusicFolders(): LiveData<List<MusicFolder>> { return musicFolders } /** * Refreshes the cached Artists from the server */ fun refresh(swipe: SwipeRefreshLayout) { backgroundLoadFromServer(true, swipe) } private fun backgroundLoadFromServer(refresh: Boolean, swipe: SwipeRefreshLayout) { viewModelScope.launch { swipe.isRefreshing = true loadFromServer(refresh, swipe) swipe.isRefreshing = false } } private suspend fun loadFromServer(refresh: Boolean, swipe: SwipeRefreshLayout) = withContext(Dispatchers.IO) { val musicService = MusicServiceFactory.getMusicService(context) val isOffline = ActiveServerProvider.isOffline(context) val useId3Tags = Util.getShouldUseId3Tags(context) try { if (!isOffline && !useId3Tags) { musicFolders.postValue( musicService.getMusicFolders(refresh, context, null) ) } val musicFolderId = activeServerProvider.getActiveServer().musicFolderId val result = if (!isOffline && useId3Tags) musicService.getArtists(refresh, context, null) else musicService.getIndexes(musicFolderId, refresh, context, null) val retrievedArtists: MutableList<Artist> = ArrayList(result.shortcuts.size + result.artists.size) retrievedArtists.addAll(result.shortcuts) retrievedArtists.addAll(result.artists) artists.postValue(retrievedArtists) } catch (exception: Exception) { Handler(Looper.getMainLooper()).post { CommunicationErrorHandler.handleError(exception, swipe.context) } } } }
gpl-3.0
743ed44fd7267d9a2164b9b242ed996d
35.87156
89
0.697437
5.068096
false
false
false
false
erickok/borefts2015
android/app/src/main/java/nl/brouwerijdemolen/borefts2013/gui/screens/BeerActivity.kt
1
4568
package nl.brouwerijdemolen.borefts2013.gui.screens import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.MenuItem import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.activity_beer.* import nl.brouwerijdemolen.borefts2013.R import nl.brouwerijdemolen.borefts2013.api.Beer import nl.brouwerijdemolen.borefts2013.ext.* import nl.brouwerijdemolen.borefts2013.gui.* import nl.brouwerijdemolen.borefts2013.gui.components.getMolenString import org.koin.android.ext.android.get import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import java.util.* class BeerActivity : AppCompatActivity() { private val beerViewModel: BeerViewModel by viewModel { parametersOf(arg(KEY_ARGS)) } private lateinit var actionStarOn: MenuItem private lateinit var actionStarOff: MenuItem override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_beer) setupToolbar() beerViewModel.state.observeNonNull(this) { with(it) { beer_name_text.text = getMolenString(beer.fullName) brewer_button.text = beer.brewer?.name brewer_button.setOnClickListener { beerViewModel.openBrewer() } style_button.text = beer.style?.name style_button.setOnClickListener { beerViewModel.openStyle() } abv_text.isVisible = beer.hasAbv abv_text.text = beer.abvText(get()) serving_text.text = beer.servingText(get()).toUpperCase(Locale.getDefault()) abv_view.value = beer.abvIndication color_view.setBackgroundColor(beer.colorIndicationResource(get())) bitterness_view.value = beer.bitternessIndication sweetness_view.value = beer.sweetnessIndication acidity_view.value = beer.acidityIndication tostyle_text.isVisible = !beer.hasFlavourIndication val customTags = beer.tags?.split(',').orEmpty() val tags = if (beer.oakAged) listOf("barrel aged") + customTags else customTags tags_layout.isVisible = tags.isNotEmpty() tags_layout.removeAllViews() tags.forEach { tag -> if (tag.isNotBlank()) { layoutInflater.inflate(R.layout.widget_label, tags_layout, true) (tags_layout.getChildAt(tags_layout.childCount - 1) as TextView).apply { this.text = tag.toUpperCase(Locale.getDefault()) } } } untappd_button.setOnClickListener { if (beer.untappdId.isNullOrEmpty() || beer.untappdId == "-1") { Toast.makeText(this@BeerActivity, R.string.error_notcoupled, Toast.LENGTH_LONG).show() } else { startLink( Uri.parse("untappd://beer/${beer.untappdId}"), Uri.parse("https://untappd.com/qr/beer/${beer.untappdId}")) } } google_button.setOnClickListener { startLink(Uri.parse("http://www.google.com/search?q=" + Uri.encode(beer.brewer?.name + " " + beer.name))) } actionStarOn.isVisible = isStarred actionStarOff.isVisible = !isStarred } } } private fun setupToolbar() { title_toolbar.setNavigationIcon(R.drawable.ic_back) title_toolbar.setNavigationOnClickListener { finish() } title_toolbar.inflateMenu(R.menu.activity_beer) actionStarOn = title_toolbar.menu.findItem(R.id.action_star_on) actionStarOff = title_toolbar.menu.findItem(R.id.action_star_off) title_toolbar.setOnMenuItemClickListener { when (it.itemId) { R.id.action_locate -> beerViewModel.locateBrewer() R.id.action_star_on -> beerViewModel.updateStar(false) R.id.action_star_off -> beerViewModel.updateStar(true) } true } } companion object { operator fun invoke(context: Context, beer: Beer): Intent = Intent(context, BeerActivity::class.java).putExtra(KEY_ARGS, beer) } }
gpl-3.0
762d52b28ba2f8bb51fce646cc476493
44.227723
125
0.61887
4.628166
false
false
false
false
google/playhvz
Android/ghvzApp/app/src/main/java/com/app/playhvz/common/TextInputDialog.kt
1
3273
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.app.playhvz.common import android.app.AlertDialog import android.app.Dialog import android.os.Bundle import android.text.InputType import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.EditText import androidx.fragment.app.DialogFragment import com.app.playhvz.R class TextInputDialog(title: String? = null, hint: String? = null, draftText: String? = null, isMultiline: Boolean = false) : DialogFragment() { companion object { private val TAG = TextInputDialog::class.qualifiedName } private var title: String? = null private var draftText: String? = null private var hintText: String? = null private var supportsMultiline = false private lateinit var customView: View lateinit var editText: EditText var onOk: (() -> Unit)? = null var onCancel: (() -> Unit)? = null init { this.title = title this.hintText = hint this.draftText = draftText this.supportsMultiline = isMultiline } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { customView = requireActivity().layoutInflater.inflate(R.layout.dialog_text_input, null) editText = customView.findViewById(R.id.editText) editText.hint = hintText if (supportsMultiline) { editText.minLines = 3 editText.inputType = InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS } if (draftText != null) { editText.append(draftText) } val builder = AlertDialog.Builder(requireContext()) .setTitle(title) .setView(customView) .setPositiveButton(android.R.string.ok) { _, _ -> onOk?.invoke() } .setNegativeButton(android.R.string.cancel) { _, _ -> onCancel?.invoke() } val dialog = builder.create() dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE) return dialog } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Return already inflated custom view return customView } fun setPositiveButtonCallback(okayCallback: () -> Unit) { onOk = okayCallback } fun setNegativeButtonCallback(negativeCallback: () -> Unit) { onCancel = negativeCallback } fun getNameProposal(): String { return editText.text.toString() } }
apache-2.0
5133f89a6931c4b7298878ad7b54b12c
31.74
153
0.670639
4.62942
false
false
false
false
androidx/androidx
room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/ksp/KspRawType.kt
3
1798
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.compiler.processing.ksp import androidx.room.compiler.codegen.XTypeName import androidx.room.compiler.processing.XRawType import androidx.room.compiler.processing.rawTypeName internal class KspRawType constructor( private val original: KspType ) : XRawType { private val ksType by lazy { original.ksType.starProjection().makeNotNullable() } override val typeName by lazy { xTypeName.java } private val xTypeName: XTypeName by lazy { XTypeName( original.asTypeName().java.rawTypeName(), original.asTypeName().kotlin.rawTypeName(), original.nullability ) } override fun asTypeName() = xTypeName override fun isAssignableFrom(other: XRawType): Boolean { check(other is KspRawType) return ksType.isAssignableFrom(other.ksType) } override fun equals(other: Any?): Boolean { return this === other || xTypeName == (other as? XRawType)?.asTypeName() } override fun hashCode(): Int { return xTypeName.hashCode() } override fun toString(): String { return xTypeName.kotlin.toString() } }
apache-2.0
eb565db32857347a092f76a84151c247
28.966667
80
0.693548
4.622108
false
false
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/ide/intentions/RemovePipelineIntention.kt
1
4020
package org.elm.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.util.DocumentUtil import org.elm.lang.core.psi.ElmPsiElement import org.elm.lang.core.psi.ElmPsiFactory import org.elm.lang.core.psi.ancestors import org.elm.lang.core.psi.elements.* import org.elm.lang.core.psi.startOffset import org.elm.lang.core.withoutExtraParens import org.elm.lang.core.withoutParens import org.elm.openapiext.runWriteCommandAction /** * An intention action that transforms a series of function applications from a pipeline. */ class RemovePipelineIntention : ElmAtCaretIntentionActionBase<RemovePipelineIntention.Context>() { data class Context(val pipeline: Pipeline) override fun getText() = "Remove Pipes" override fun getFamilyName() = text override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? = element .ancestors .filter { isPipelineOperator(it) } .firstOrNull() ?.let { it.parent as? ElmBinOpExpr } ?.asPipeline()?.let { Context(it) } override fun invoke(project: Project, editor: Editor, context: Context) { project.runWriteCommandAction { val pipe = context.pipeline replaceUnwrapped(pipe.pipeline, normalizePipeline(pipe, project, editor)) } } private fun normalizePipeline(originalPipeline: Pipeline, project: Project, editor: Editor): ElmPsiElement { val initial: ElmPsiElement? = null val existingIndent = DocumentUtil.getIndent(editor.document, originalPipeline.pipeline.startOffset).toString() val psiFactory = ElmPsiFactory(project) val isMultiline = isMultiline(originalPipeline) return originalPipeline.segments() .withIndex() .fold(initial, { functionCallSoFar, indexedSegment -> val segment = indexedSegment.value val indentation = existingIndent + " ".repeat(indexedSegment.index) val expressionString = segment.expressionParts.joinToString(" ") { when { isMultiline -> indentation + it.text else -> it.text } } val psi = when { functionCallSoFar != null -> psiFactory.callFunctionWithArgumentAndComments(segment.comments, expressionString, functionCallSoFar, indentation) isMultiline -> psiFactory.createParensWithComments(segment.comments, expressionString, indentation) else -> psiFactory.createParens(expressionString, indentation) } unwrapIfPossible(psi) })!! } private fun isMultiline(pipeline: Pipeline): Boolean = pipeline.segments().any { segment -> segment.comments.isNotEmpty() || segment.expressionParts.any { it.textContains('\n') } } private fun unwrapIfPossible(element: ElmParenthesizedExpr): ElmPsiElement { val wrapped = element.withoutExtraParens return when (val unwrapped = wrapped.withoutParens) { is ElmBinOpExpr, is ElmAnonymousFunctionExpr, is ElmFunctionCallExpr -> wrapped else -> unwrapped } } } private fun replaceUnwrapped(expression: ElmPsiElement, replaceWith: ElmPsiElement) { val unwrapped = when (replaceWith) { is ElmParenthesizedExpr -> replaceWith.withoutParens else -> replaceWith } expression.replace(unwrapped) } fun isPipelineOperator(element: PsiElement): Boolean { return element is ElmOperator && (element.referenceName == "|>" || element.referenceName == "<|") }
mit
e71492150b16e40526122bb10b2050fc
40.020408
142
0.632836
5.296443
false
false
false
false
devromik/black-and-white
sources/src/test/kotlin/net/devromik/bw/ColoringCheck.kt
1
1223
package net.devromik.bw import net.devromik.bw.Color.* import net.devromik.tree.Tree import kotlin.test.* /** * @author Shulnyaev Roman */ fun checkColoring( tree: Tree<String>, treeSize: Int, coloring: Coloring<String>, black: Int, white: Int) { var actualBlack = 0 var actualWhite = 0 var actualGray = 0 val treeIter = tree.levelOrderIterator() while (treeIter.hasNext) { val node = treeIter.next() val nodeColor = coloring.colorOf(node) when (nodeColor) { BLACK, WHITE -> { if (nodeColor == BLACK) ++actualBlack else ++actualWhite val incompatibleColor = if (nodeColor == BLACK) WHITE else BLACK if (!node.isRoot) { assertNotEquals(incompatibleColor, coloring.colorOf(node.parent!!)) } for (child in node) { assertNotEquals(incompatibleColor, coloring.colorOf(child)) } } GRAY -> { ++actualGray } } } assertEquals(black, actualBlack) assertEquals(white, actualWhite) assertEquals(treeSize - (black + white), actualGray) }
mit
756070b82acc5ec8a683282aa491e547
23.979592
87
0.565004
4.415162
false
false
false
false
InfiniteSoul/ProxerAndroid
src/main/kotlin/me/proxer/app/util/rx/CallResponseSingle.kt
2
1741
package me.proxer.app.util.rx import io.reactivex.Single import io.reactivex.SingleObserver import io.reactivex.disposables.Disposable import io.reactivex.exceptions.CompositeException import io.reactivex.exceptions.Exceptions import io.reactivex.plugins.RxJavaPlugins import okhttp3.Call import okhttp3.Response /** * @author Ruben Gees */ class CallResponseSingle(private val originalCall: Call) : Single<Response>() { override fun subscribeActual(observer: SingleObserver<in Response>) { val call = originalCall.clone() val disposable = CallDisposable(call) observer.onSubscribe(disposable) if (disposable.isDisposed) { return } var terminated = false try { call.execute().use { if (!disposable.isDisposed) { terminated = true observer.onSuccess(it) } } } catch (t: Throwable) { Exceptions.throwIfFatal(t) if (terminated) { RxJavaPlugins.onError(t) } else if (!disposable.isDisposed) { try { observer.onError(t) } catch (inner: Throwable) { Exceptions.throwIfFatal(inner) RxJavaPlugins.onError(CompositeException(t, inner)) } } } } private class CallDisposable(private val call: Call) : Disposable { @Volatile private var isDisposed: Boolean = false override fun dispose() { isDisposed = true call.cancel() } override fun isDisposed(): Boolean { return isDisposed } } }
gpl-3.0
44461dc9224cb14c0b50ec3b602fdcbf
24.602941
79
0.572659
5.197015
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/widgets/filepicker/utils/Utility.kt
2
1334
package ru.fantlab.android.ui.widgets.filepicker.utils import android.content.Context import android.content.pm.PackageManager import android.os.Build import ru.fantlab.android.ui.widgets.filepicker.model.FileListItem import java.io.File import java.util.* object Utility { fun checkStorageAccessPermissions(context: Context): Boolean { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val permission = "android.permission.READ_EXTERNAL_STORAGE" val res = context.checkCallingOrSelfPermission(permission) res == PackageManager.PERMISSION_GRANTED } else { true } } fun prepareFileListEntries(internalList: ArrayList<FileListItem>, inter: File, filter: ExtensionFilter?, show_hidden_files: Boolean): ArrayList<FileListItem> { var internalList = internalList try { for (name in Objects.requireNonNull(inter.listFiles(filter))) { if (name.canRead()) { if (name.name.startsWith(".") && !show_hidden_files) continue val item = FileListItem() item.filename = name.name item.isDirectory = name.isDirectory item.location = name.absolutePath item.time = name.lastModified() internalList.add(item) } } internalList.sort() } catch (e: NullPointerException) { e.printStackTrace() internalList = ArrayList() } return internalList } }
gpl-3.0
5afad1120863b2306d897190e2abe1ab
30.046512
90
0.730135
3.715877
false
false
false
false
Tvede-dk/CommonsenseAndroidKotlin
system/src/main/kotlin/com/commonsense/android/kotlin/system/dataFlow/ReferenceCountingMap.kt
1
2284
@file:Suppress("unused", "NOTHING_TO_INLINE", "MemberVisibilityCanBePrivate") package com.commonsense.android.kotlin.system.dataFlow import com.commonsense.android.kotlin.base.* import java.util.concurrent.atomic.* /** * An internal reference counter for some given data. */ data class ReferenceItem<out T>(val item: T, var counter: AtomicInteger) /** * A reference counting based map, so when the counter goes to 0 or below it will be removed. * @property map HashMap<String, ReferenceItem<*>> * @property count Int */ class ReferenceCountingMap { private val map: HashMap<String, ReferenceItem<*>> = hashMapOf() fun <T> addItem(item: T, forKey: String) { if (hasItem(forKey)) { throw RuntimeException("Disallowed to add an element to an already existing index;" + " did you mean increment ?") } map[forKey] = ReferenceItem(item, AtomicInteger(1)) } fun addOrIncrement(item: Any, forKey: String) { if (hasItem(forKey)) { incrementCounter(forKey) } else { addItem(item, forKey) } } fun incrementCounter(forKey: String) = getReference(forKey) { it.counter.incrementAndGet() } fun decrementCounter(forKey: String) = getReference(forKey) { val after = it.counter.decrementAndGet() if (after <= 0) { map.remove(forKey) } } fun hasItem(key: String): Boolean = map.containsKey(key) inline fun <reified T> getItemAs(forKey: String): T? { val item = getItemOr(forKey) if (item is T) { return item } return null } fun getItemOr(forKey: String): Any? { if (hasItem(forKey)) { return map[forKey]?.item } return null } private inline fun getReference(forKey: String, crossinline useWith: FunctionUnit<ReferenceItem<*>>) { if (hasItem(forKey)) { map[forKey]?.let(useWith) } } fun toPrettyString(): String { return "ReferenceCountingMap state:\n\tcount = $count\n\t" + "$map" } /** * The size of this reference counting map. */ val count: Int get() = map.size }
mit
9cad4af039a0effdd433dc5ff95f7e16
25.882353
97
0.595447
4.301318
false
false
false
false
EmmyLua/IntelliJ-EmmyLua
src/main/java/com/tang/intellij/lua/project/StdLibraryProvider.kt
2
3017
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.project import com.intellij.navigation.ItemPresentation import com.intellij.openapi.application.WriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.roots.AdditionalLibraryRootsProvider import com.intellij.openapi.roots.SyntheticLibrary import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.EmptyRunnable import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.stubs.StubIndex import com.tang.intellij.lua.lang.LuaIcons import com.tang.intellij.lua.lang.LuaLanguageLevel import com.tang.intellij.lua.psi.LuaFileUtil import java.io.File import javax.swing.Icon class StdLibraryProvider: AdditionalLibraryRootsProvider() { override fun getAdditionalProjectLibraries(project: Project): Collection<StdLibrary> { val level = LuaSettings.instance.languageLevel val std = LuaFileUtil.getPluginVirtualFile("std/Lua${level.version}") ?: return emptyList() val dir = VfsUtil.findFileByIoFile(File(std), true) ?: return emptyList() dir.children.forEach { it.putUserData(LuaFileUtil.PREDEFINED_KEY, true) } return listOf(StdLibrary(level, dir)) } companion object { fun reload() { WriteAction.run<RuntimeException> { val projects = ProjectManagerEx.getInstanceEx().openProjects for (project in projects) { ProjectRootManagerEx.getInstanceEx(project).makeRootsChange(EmptyRunnable.getInstance(), false, true) } StubIndex.getInstance().forceRebuild(Throwable("Lua language level changed.")) } } } class StdLibrary(private val level: LuaLanguageLevel, private val root: VirtualFile) : SyntheticLibrary(), ItemPresentation { private val roots = listOf(root) override fun hashCode() = root.hashCode() override fun equals(other: Any?): Boolean { return other is StdLibrary && other.root == root } override fun getSourceRoots() = roots override fun getLocationString() = "Lua std library" override fun getIcon(p0: Boolean): Icon = LuaIcons.FILE override fun getPresentableText() = level.toString() } }
apache-2.0
24639d64412b038eb5c22192789e4bb7
37.202532
121
0.714949
4.677519
false
false
false
false
inorichi/tachiyomi-extensions
src/pt/tsukimangas/src/eu/kanade/tachiyomi/extension/pt/tsukimangas/TsukiMangasDto.kt
1
1532
package eu.kanade.tachiyomi.extension.pt.tsukimangas import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class TsukiAuthRequestDto( val username: String, val password: String ) @Serializable data class TsukiAuthResultDto( val token: String? = null ) @Serializable data class TsukiPaginatedDto( val data: List<TsukiMangaDto> = emptyList(), val lastPage: Int, val page: Int, val perPage: Int, val total: Int ) @Serializable data class TsukiMangaDto( val artist: String? = "", val author: String? = "", val genres: List<TsukiGenreDto> = emptyList(), val id: Int, val poster: String? = "", val status: String? = "", val synopsis: String? = "", val title: String, val url: String ) @Serializable data class TsukiGenreDto( val genre: String ) @Serializable data class TsukiChapterDto( val number: String, val title: String? = "", val versions: List<TsukiChapterVersionDto> = emptyList() ) @Serializable data class TsukiChapterVersionDto( @SerialName("created_at") val createdAt: String, val id: Int, val scans: List<TsukiScanlatorDto> = emptyList() ) @Serializable data class TsukiScanlatorDto( val scan: TsukiScanlatorDetailDto ) @Serializable data class TsukiScanlatorDetailDto( val name: String ) @Serializable data class TsukiReaderDto( val pages: List<TsukiPageDto> = emptyList() ) @Serializable data class TsukiPageDto( val server: Int, val url: String )
apache-2.0
4164603e5eb2dcad4b167710a4cf72ad
18.896104
60
0.708225
3.764128
false
false
false
false
inorichi/tachiyomi-extensions
multisrc/overrides/madara/arthurscan/src/ArthurScan.kt
1
1857
package eu.kanade.tachiyomi.extension.pt.arthurscan import eu.kanade.tachiyomi.lib.ratelimit.RateLimitInterceptor import eu.kanade.tachiyomi.multisrc.madara.Madara import okhttp3.OkHttpClient import java.text.SimpleDateFormat import java.util.Locale import java.util.concurrent.TimeUnit class ArthurScan : Madara( "Arthur Scan", "https://arthurscan.xyz", "pt-BR", SimpleDateFormat("MMMMM dd, yyyy", Locale("pt", "BR")) ) { override val client: OkHttpClient = super.client.newBuilder() .addInterceptor(RateLimitInterceptor(1, 1, TimeUnit.SECONDS)) .build() override fun popularMangaSelector() = "div.page-item-detail.manga" override val altName: String = "Nome alternativo: " // [...document.querySelectorAll('div.genres li a')] // .map(x => `Genre("${x.innerText.slice(1, -4).trim()}", "${x.href.replace(/.*-genre\/(.*)\//, '$1')}")`) // .join(',\n') override fun getGenreList(): List<Genre> = listOf( Genre("Ação", "acao"), Genre("Artes Marciais", "artes-marciais"), Genre("Aventura", "aventura"), Genre("Comédia", "comedia"), Genre("Drama", "drama"), Genre("Fantasia", "fantasia"), Genre("Harém", "harem"), Genre("Histórico", "historico"), Genre("Manhua", "manhua"), Genre("Manhwa", "manhwa"), Genre("Mistério", "misterio"), Genre("Reencarnação", "reencarnacao"), Genre("Romance", "romance"), Genre("Sci-fi", "sci-fi"), Genre("Seinen", "seinen"), Genre("Shounen", "shounen"), Genre("Slice of Life", "slice-of-life"), Genre("Sobrenatural", "sobrenatural"), Genre("Vida Escolar", "vida-escolar"), Genre("Web Comic", "web-comic"), Genre("Web Novel", "web-novel"), Genre("Webtoon", "webtoon") ) }
apache-2.0
bcca2d0bd53783c16e7346b45cc9d576
34.557692
114
0.606274
3.65415
false
false
false
false
robfletcher/orca
orca-migration/src/main/kotlin/com/netflix/spinnaker/orca/pipeline/persistence/migration/PipelineMigrationAgent.kt
4
3037
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.pipeline.persistence.migration import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.front50.Front50Service import com.netflix.spinnaker.orca.notifications.AbstractPollingNotificationAgent import com.netflix.spinnaker.orca.notifications.NotificationClusterLock import com.netflix.spinnaker.orca.pipeline.persistence.DualExecutionRepository import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import org.slf4j.LoggerFactory /** * Requires DualExecutionRepository being enabled to run migrations. */ class PipelineMigrationAgent( clusterLock: NotificationClusterLock, private val front50Service: Front50Service, private val dualExecutionRepository: DualExecutionRepository, private val pollingIntervalMs: Long ) : AbstractPollingNotificationAgent(clusterLock) { private val log = LoggerFactory.getLogger(javaClass) override fun tick() { val previouslyMigratedPipelineIds = dualExecutionRepository.primary.retrieveAllExecutionIds(PIPELINE) val executionCriteria = ExecutionRepository.ExecutionCriteria().apply { pageSize = 50 setStatuses(ExecutionStatus.COMPLETED.map { it.name }) } val allPipelineConfigIds = front50Service.allPipelines.map { it["id"] as String } .toMutableList() .let { it + front50Service.allStrategies.map { it["id"] as String } } log.info("Found ${allPipelineConfigIds.size} pipeline configs") allPipelineConfigIds.forEachIndexed { index, pipelineConfigId -> val unmigratedPipelines = dualExecutionRepository.previous .retrievePipelinesForPipelineConfigId(pipelineConfigId, executionCriteria) .filter { !previouslyMigratedPipelineIds.contains(it.id) } .toList() .toBlocking() .single() if (unmigratedPipelines.isNotEmpty()) { log.info("${unmigratedPipelines.size} pipelines to migrate ($pipelineConfigId) [$index/${allPipelineConfigIds.size}]") unmigratedPipelines.forEach { dualExecutionRepository.primary.store(it) } log.info("${unmigratedPipelines.size} pipelines migrated ($pipelineConfigId) [$index/${allPipelineConfigIds.size}]") } } } override fun getPollingInterval() = pollingIntervalMs override fun getNotificationType() = "pipelineMigrator" }
apache-2.0
024f3e436e5e78c36f68b99bec6da3cf
40.040541
126
0.765558
4.665131
false
true
false
false
apollostack/apollo-android
apollo-runtime-common/src/commonTest/kotlin/com/apollographql/apollo3/subscription/AppSyncOperationMessageSerializerTest.kt
1
4966
package com.apollographql.apollo3.subscription import com.apollographql.apollo3.api.ResponseAdapterCache import com.apollographql.apollo3.api.internal.json.BufferedSourceJsonReader import com.apollographql.apollo3.api.internal.json.Utils.readRecursively import com.apollographql.apollo3.testing.MockSubscription import okio.Buffer import kotlin.test.Test import kotlin.test.assertEquals class AppSyncOperationMessageSerializerTest { private val authorization = mapOf( "host" to "example1234567890000.appsync-api.us-east-1.amazonaws.com", "x-api-key" to "da2-12345678901234567890123456" ) private val serializer = AppSyncOperationMessageSerializer(authorization) @Test fun writeClientMessage_init() { val message = OperationClientMessage.Init(mapOf( "param1" to "value1", "param2" to "value2" )) assertEquals( serializer.writeClientMessage(message), ApolloOperationMessageSerializer.writeClientMessage(message) ) } @Test fun writeClientMessage_start() { val message = OperationClientMessage.Start( subscriptionId = "subscription-id", subscription = MockSubscription( variables = mapOf("variable" to "value"), queryDocument = "subscription{commentAdded{id name}", name = "SomeSubscription" ), responseAdapterCache = ResponseAdapterCache.DEFAULT, autoPersistSubscription = false, sendSubscriptionDocument = true ) ApolloOperationMessageSerializer.JSON_KEY_VARIABLES ApolloOperationMessageSerializer.JSON_KEY_OPERATION_NAME ApolloOperationMessageSerializer.JSON_KEY_QUERY assertEquals(parseJson(serializer.writeClientMessage(message)), mapOf( "id" to message.subscriptionId, "type" to "start", "payload" to mapOf( "data" to """{"variables":{"variable":"value"},"operationName":"SomeSubscription","query":"subscription{commentAdded{id name}"}""", "extensions" to mapOf( "authorization" to authorization ) ) )) } @Test fun writeClientMessage_stop() { val message = OperationClientMessage.Stop("subscription-id") assertEquals(serializer.writeClientMessage(message), ApolloOperationMessageSerializer.writeClientMessage(message)) } @Test fun writeClientMessage_terminate() { val message = OperationClientMessage.Terminate() assertEquals(serializer.writeClientMessage(message), ApolloOperationMessageSerializer.writeClientMessage(message)) } @Test fun readServerMessage_connectionAcknowledge() { assertEquals( serializer.readServerMessage("""{"type":"connection_ack","payload":{"connectionTimeoutMs":300000}}"""), OperationServerMessage.ConnectionAcknowledge ) } @Test fun readServerMessage_data() { assertEquals( serializer.readServerMessage("""{"type":"data","id":"some-id","payload":{"key":"value"}}"""), OperationServerMessage.Data( id = "some-id", payload = mapOf("key" to "value") ) ) } @Test fun readServerMessage_keepAlive() { assertEquals(serializer.readServerMessage("""{"type":"ka"}"""), OperationServerMessage.ConnectionKeepAlive) } @Test fun readServerMessage_error() { assertEquals(serializer.readServerMessage("""{"type":"error","id":"some-id","payload":{"key":"value"}}"""), OperationServerMessage.Error( id = "some-id", payload = mapOf("key" to "value") )) } @Test fun readServerMessage_connectionError() { assertEquals(serializer.readServerMessage("""{"type":"connection_error","payload":{"key":"value"}}"""), OperationServerMessage.ConnectionError( payload = mapOf("key" to "value") )) } @Test fun readServerMessage_complete() { assertEquals(serializer.readServerMessage("""{"type":"complete","id":"some-id"}"""), OperationServerMessage.Complete( id = "some-id" )) } @Test fun readServerMessage_unknown() { assertEquals( serializer.readServerMessage("invalid json"), OperationServerMessage.Unsupported("invalid json") ) assertEquals( serializer.readServerMessage("{}"), OperationServerMessage.Unsupported("{}") ) assertEquals( serializer.readServerMessage("""{"type":"unknown"}"""), OperationServerMessage.Unsupported("""{"type":"unknown"}""") ) } private fun OperationMessageSerializer.writeClientMessage(message: OperationClientMessage): String = Buffer() .also { writeClientMessage(message, it) } .readUtf8() private fun OperationMessageSerializer.readServerMessage(json: String): OperationServerMessage = Buffer() .writeUtf8(json) .let { readServerMessage(it) } private fun parseJson(json: String): Any? = Buffer() .writeUtf8(json) .let(::BufferedSourceJsonReader) .readRecursively() }
mit
a8203da64a2b11f72b901cb151ae568f
32.789116
147
0.683649
5.156802
false
true
false
false
da1z/intellij-community
java/java-analysis-impl/src/com/intellij/codeInspection/deprecation/ReplaceMethodCallFix.kt
5
2728
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.codeInspection.deprecation import com.intellij.codeInspection.LocalQuickFixOnPsiElement import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiFormatUtil import com.intellij.psi.util.PsiFormatUtilBase import com.intellij.util.ObjectUtils import org.jetbrains.annotations.Nls internal class ReplaceMethodCallFix(expr: PsiMethodCallExpression, replacementMethod: PsiMethod) : LocalQuickFixOnPsiElement(expr) { private val myReplacementMethodPointer = SmartPointerManager.getInstance(replacementMethod.project).createSmartPsiElementPointer(replacementMethod) private val myReplacementText = PsiFormatUtil.formatMethod(replacementMethod, PsiSubstitutor.EMPTY, PsiFormatUtilBase.SHOW_CONTAINING_CLASS or PsiFormatUtilBase.SHOW_NAME, 0) override fun getText(): String { return "Replace method call with " + myReplacementText } @Nls override fun getFamilyName(): String { return "Replace Method Call" } override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) { val expr = ObjectUtils.tryCast(startElement, PsiMethodCallExpression::class.java) ?: return val replacementMethod = myReplacementMethodPointer.element ?: return val qualifierExpression = expr.methodExpression.qualifierExpression val isReplacementStatic = replacementMethod.hasModifierProperty(PsiModifier.STATIC) val qualifierText = if (qualifierExpression != null && !isReplacementStatic) { qualifierExpression.text + "." } else if (isReplacementStatic) { replacementMethod.containingClass!!.qualifiedName!! + "." } else { "" } val elementFactory = JavaPsiFacade.getElementFactory(project) val newMethodCall = elementFactory.createExpressionFromText(qualifierText + replacementMethod.name + expr.argumentList.text, expr) val replaced = expr.replace(newMethodCall) as PsiMethodCallExpression JavaCodeStyleManager.getInstance(project).shortenClassReferences(replaced.methodExpression) } }
apache-2.0
051c113ad6778853eb5ce01942f72cc5
42.301587
146
0.784457
4.933092
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt
1
8988
package info.nightscout.androidaps.plugins.general.overview.dialogs import android.os.Bundle import android.text.format.DateFormat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import android.view.WindowManager import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.TimeFormat import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.OverviewEditquickwizardDialogBinding import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventQuickWizardChange import info.nightscout.androidaps.utils.DateUtil import info.nightscout.shared.SafeParse import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.extensions.selectedItemPosition import info.nightscout.androidaps.utils.extensions.setEnableForChildren import info.nightscout.androidaps.utils.extensions.setSelection import info.nightscout.androidaps.utils.wizard.QuickWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import java.util.* import javax.inject.Inject class EditQuickWizardDialog : DaggerDialogFragment(), View.OnClickListener { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var quickWizard: QuickWizard @Inject lateinit var dateUtil: DateUtil @Inject lateinit var sp: SP var position = -1 var fromSeconds: Int = 0 var toSeconds: Int = 0 private var _binding: OverviewEditquickwizardDialogBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) isCancelable = true dialog?.setCanceledOnTouchOutside(false) _binding = OverviewEditquickwizardDialogBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { (arguments ?: savedInstanceState)?.let { bundle -> position = bundle.getInt("position", -1) } val entry = if (position == -1) quickWizard.newEmptyItem() else quickWizard[position] if (sp.getBoolean(R.string.key_wear_control, false)) { binding.deviceLabel.visibility = View.VISIBLE binding.device.visibility = View.VISIBLE } else { binding.deviceLabel.visibility = View.GONE binding.device.visibility = View.GONE } binding.okcancel.ok.setOnClickListener { try { entry.storage.put("buttonText", binding.buttonEdit.text.toString()) entry.storage.put("carbs", SafeParse.stringToInt(binding.carbsEdit.text.toString())) entry.storage.put("validFrom", fromSeconds) entry.storage.put("validTo", toSeconds) entry.storage.put("useBG", binding.useBg.selectedItemPosition) entry.storage.put("useCOB", binding.useCob.selectedItemPosition) entry.storage.put("useBolusIOB", binding.useBolusIob.selectedItemPosition) entry.storage.put("device", binding.device.selectedItemPosition) entry.storage.put("useBasalIOB", binding.useBasalIob.selectedItemPosition) entry.storage.put("useTrend", binding.useTrend.selectedItemPosition) entry.storage.put("useSuperBolus", binding.useSuperBolus.selectedItemPosition) entry.storage.put("useTempTarget", binding.useTempTarget.selectedItemPosition) entry.storage.put("usePercentage", binding.usePercentage.selectedItemPosition) val percentage = SafeParse.stringToInt(binding.percentage.text.toString()) entry.storage.put("percentage", percentage) } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) } quickWizard.addOrUpdate(entry) rxBus.send(EventQuickWizardChange()) dismiss() } binding.okcancel.cancel.setOnClickListener { dismiss() } binding.from.setOnClickListener { val clockFormat = if (DateFormat.is24HourFormat(context)) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H val timePicker = MaterialTimePicker.Builder() .setTimeFormat(clockFormat) .setHour(T.secs(fromSeconds.toLong()).hours().toInt()) .setMinute(T.secs((fromSeconds % 3600).toLong()).mins().toInt()) .build() timePicker.addOnPositiveButtonClickListener { fromSeconds = (T.hours(timePicker.hour.toLong()).secs() + T.mins(timePicker.minute.toLong()).secs()).toInt() binding.from.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(fromSeconds)) } timePicker.show(parentFragmentManager, "event_time_time_picker") } fromSeconds = entry.validFrom() binding.from.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(fromSeconds)) binding.to.setOnClickListener { val clockFormat = if (DateFormat.is24HourFormat(context)) TimeFormat.CLOCK_24H else TimeFormat.CLOCK_12H val timePicker = MaterialTimePicker.Builder() .setTimeFormat(clockFormat) .setHour(T.secs(toSeconds.toLong()).hours().toInt()) .setMinute(T.secs((toSeconds % 3600).toLong()).mins().toInt()) .build() timePicker.addOnPositiveButtonClickListener { toSeconds = (T.hours(timePicker.hour.toLong()).secs() + T.mins(timePicker.minute.toLong()).secs()).toInt() binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) } timePicker.show(parentFragmentManager, "event_time_time_picker") } fun usePercentage(custom: Boolean) { if (custom) { binding.percentageLabel.visibility = View.VISIBLE binding.percentage.visibility = View.VISIBLE } else { binding.percentageLabel.visibility = View.GONE binding.percentage.visibility = View.GONE } } binding.usePercentage.setOnCheckedChangeListener { _, checkedId -> usePercentage(checkedId == R.id.use_percentage_custom) } toSeconds = entry.validTo() binding.to.text = dateUtil.timeString(dateUtil.secondsOfTheDayToMilliseconds(toSeconds)) binding.buttonEdit.setText(entry.buttonText()) binding.carbsEdit.setText(entry.carbs().toString()) binding.useBg.setSelection(entry.useBG()) binding.useCob.setSelection(entry.useCOB()) binding.useBolusIob.setSelection(entry.useBolusIOB()) binding.useBasalIob.setSelection(entry.useBasalIOB()) binding.device.setSelection(entry.device()) binding.useTrend.setSelection(entry.useTrend()) binding.useSuperBolus.setSelection(entry.useSuperBolus()) binding.useTempTarget.setSelection(entry.useTempTarget()) binding.usePercentage.setSelection(entry.usePercentage()) usePercentage(entry.usePercentage() == QuickWizardEntry.CUSTOM) binding.percentage.setText(entry.percentage().toString()) binding.useCobYes.setOnClickListener(this) binding.useCobNo.setOnClickListener(this) processCob() } override fun onClick(v: View?) { processCob() } override fun onResume() { super.onResume() dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("position", position) } override fun onDestroyView() { super.onDestroyView() _binding = null } private fun processCob() { if (binding.useCob.selectedItemPosition == QuickWizardEntry.YES) { binding.useBolusIob.setEnableForChildren(false) binding.useBasalIob.setEnableForChildren(false) binding.useBolusIob.setSelection(QuickWizardEntry.YES) binding.useBasalIob.setSelection(QuickWizardEntry.YES) } else { binding.useBolusIob.setEnableForChildren(true) binding.useBasalIob.setEnableForChildren(true) } } }
agpl-3.0
09a5a67d6d75e93f5c7748964a0e2f9b
44.624365
124
0.689475
4.933041
false
false
false
false
auth0/Auth0.Android
auth0/src/main/java/com/auth0/android/provider/WebAuthProvider.kt
1
20119
package com.auth0.android.provider import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import androidx.annotation.VisibleForTesting import com.auth0.android.Auth0 import com.auth0.android.authentication.AuthenticationException import com.auth0.android.authentication.storage.CredentialsManagerException import com.auth0.android.callback.Callback import com.auth0.android.result.Credentials import kotlinx.coroutines.* import java.util.* import kotlin.coroutines.CoroutineContext import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.jvm.Throws /** * OAuth2 Web Authentication Provider. * * * It uses an external browser by sending the [android.content.Intent.ACTION_VIEW] intent. */ public object WebAuthProvider { private val TAG: String? = WebAuthProvider::class.simpleName @JvmStatic @get:VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal var managerInstance: ResumableManager? = null private set // Public methods /** * Initialize the WebAuthProvider instance for logging out the user using an account. Additional settings can be configured * in the LogoutBuilder, like changing the scheme of the return to URL. * * @param account to use for authentication * @return a new Builder instance to customize. */ @JvmStatic public fun logout(account: Auth0): LogoutBuilder { return LogoutBuilder(account) } /** * Initialize the WebAuthProvider instance for authenticating the user using an account. Additional settings can be configured * in the Builder, like setting the connection name or authentication parameters. * * @param account to use for authentication * @return a new Builder instance to customize. */ @JvmStatic public fun login(account: Auth0): Builder { return Builder(account) } /** * Finishes the authentication or log out flow by passing the data received in the activity's onNewIntent() callback. * The final result will be delivered to the callback specified when calling start(). * * * This is no longer required to be called, the authentication is handled internally as long as you've correctly setup the intent-filter. * * @param intent the data received on the onNewIntent() call. When null is passed, the authentication will be considered canceled. * @return true if a result was expected and has a valid format, or false if not. When true is returned a call on the callback is expected. */ @JvmStatic public fun resume(intent: Intent?): Boolean { if (managerInstance == null) { Log.w(TAG, "There is no previous instance of this provider.") return false } val result = AuthorizeResult(intent) val success = managerInstance!!.resume(result) if (success) { resetManagerInstance() } return success } @JvmStatic @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal fun resetManagerInstance() { managerInstance = null } public class LogoutBuilder internal constructor(private val account: Auth0) { private var scheme = "https" private var returnToUrl: String? = null private var ctOptions: CustomTabsOptions = CustomTabsOptions.newBuilder().build() private var federated: Boolean = false /** * When using a Custom Tabs compatible Browser, apply these customization options. * * @param options the Custom Tabs customization options * @return the current builder instance */ public fun withCustomTabsOptions(options: CustomTabsOptions): LogoutBuilder { ctOptions = options return this } /** * Specify a custom Scheme to use on the Return To URL. Default scheme is 'https'. * * @param scheme to use in the Return To URL. * @return the current builder instance */ public fun withScheme(scheme: String): LogoutBuilder { val lowerCase = scheme.toLowerCase(Locale.ROOT) if (scheme != lowerCase) { Log.w( TAG, "Please provide the scheme in lowercase and make sure it's the same configured in the intent filter. Android expects the scheme to be lowercase." ) } this.scheme = scheme return this } /** * Specify a custom Redirect To URL to use to invoke the app on redirection. * Normally, you wouldn't need to call this method manually as the default value is autogenerated for you. * The [LogoutBuilder.withScheme] configuration is ignored when this method is called. It is your responsibility to pass a well-formed URL. * * @param returnToUrl to use to invoke the app on redirection. * @return the current builder instance */ public fun withReturnToUrl(returnToUrl: String): LogoutBuilder { this.returnToUrl = returnToUrl return this } /** * Although not a common practice, you can force the user to log out of their identity provider. * Think of the user experience before you use this parameter. * * This feature is not supported by every identity provider. Read more about the limitations in * the [Log Users Out of Identity Provider](https://auth0.com/docs/logout/log-users-out-of-idps) article. * * @return the current builder instance */ public fun withFederated(): LogoutBuilder { this.federated = true return this } /** * Request the user session to be cleared. When successful, the callback will get invoked. * An error is raised if there are no browser applications installed in the device or if * the user closed the browser before completing the logout. * * @param context to run the log out * @param callback to invoke when log out is successful * @see AuthenticationException.isBrowserAppNotAvailable * @see AuthenticationException.isAuthenticationCanceled */ public fun start(context: Context, callback: Callback<Void?, AuthenticationException>) { resetManagerInstance() if (!ctOptions.hasCompatibleBrowser(context.packageManager)) { val ex = AuthenticationException( "a0.browser_not_available", "No compatible Browser application is installed." ) callback.onFailure(ex) return } if (returnToUrl == null) { returnToUrl = CallbackHelper.getCallbackUri( scheme, context.applicationContext.packageName, account.getDomainUrl() ) } val logoutManager = LogoutManager(account, callback, returnToUrl!!, ctOptions, federated) managerInstance = logoutManager logoutManager.startLogout(context) } @JvmSynthetic @Throws(AuthenticationException::class) public suspend fun await(context: Context) { return await(context, Dispatchers.Main.immediate) } /** * Used internally so that [CoroutineContext] can be injected for testing purpose */ internal suspend fun await( context: Context, coroutineContext: CoroutineContext ) { return withContext(coroutineContext) { suspendCancellableCoroutine { continuation -> start(context, object : Callback<Void?, AuthenticationException> { override fun onSuccess(result: Void?) { continuation.resume(Unit) } override fun onFailure(error: AuthenticationException) { continuation.resumeWithException(error) } }) } } } } public class Builder internal constructor(private val account: Auth0) { private val values: MutableMap<String, String> = mutableMapOf() private val headers: MutableMap<String, String> = mutableMapOf() private var pkce: PKCE? = null private var issuer: String? = null private var scheme: String = "https" private var redirectUri: String? = null private var invitationUrl: String? = null private var ctOptions: CustomTabsOptions = CustomTabsOptions.newBuilder().build() private var leeway: Int? = null /** * Use a custom state in the requests * * @param state to use in the requests * @return the current builder instance */ public fun withState(state: String): Builder { if (state.isNotEmpty()) { values[OAuthManager.KEY_STATE] = state } return this } /** * Specify a custom nonce value to avoid replay attacks. It will be sent in the auth request that will be returned back as a claim in the id_token * * @param nonce to use in the requests * @return the current builder instance */ public fun withNonce(nonce: String): Builder { if (nonce.isNotEmpty()) { values[OAuthManager.KEY_NONCE] = nonce } return this } /** * Set the max age value for the authentication. * * @param maxAge to use in the requests * @return the current builder instance */ public fun withMaxAge(maxAge: Int): Builder { values[OAuthManager.KEY_MAX_AGE] = maxAge.toString() return this } /** * Set the leeway or clock skew to be used for ID Token verification. * Defaults to 60 seconds. * * @param leeway to use for ID token verification, in seconds. * @return the current builder instance */ public fun withIdTokenVerificationLeeway(leeway: Int): Builder { this.leeway = leeway return this } /** * Set the expected issuer to be used for ID Token verification. * Defaults to the value returned by [Auth0.getDomainUrl]. * * @param issuer to use for ID token verification. * @return the current builder instance */ public fun withIdTokenVerificationIssuer(issuer: String): Builder { this.issuer = issuer return this } /** * Use a custom audience in the requests * * @param audience to use in the requests * @return the current builder instance */ public fun withAudience(audience: String): Builder { values[KEY_AUDIENCE] = audience return this } /** * Specify a custom Scheme to use on the Redirect URI. Default scheme is 'https'. * * @param scheme to use in the Redirect URI. * @return the current builder instance */ public fun withScheme(scheme: String): Builder { val lowerCase = scheme.toLowerCase(Locale.ROOT) if (scheme != lowerCase) { Log.w( TAG, "Please provide the scheme in lowercase and make sure it's the same configured in the intent filter. Android expects the scheme to be lowercase." ) } this.scheme = scheme return this } /** * Specify a custom Redirect URI to use to invoke the app on redirection. * Normally, you wouldn't need to call this method manually as the default value is autogenerated for you. * The [Builder.withScheme] configuration is ignored when this method is called. It is your responsibility to pass a well-formed URI. * * @param redirectUri to use to invoke the app on redirection. * @return the current builder instance */ public fun withRedirectUri(redirectUri: String): Builder { this.redirectUri = redirectUri return this } /** * Specify an invitation URL to join an organization. * When called in combination with WebAuthProvider#withOrganization, the invitation URL * will take precedence. * * @param invitationUrl the organization invitation URL * @return the current builder instance * @see withOrganization */ public fun withInvitationUrl(invitationUrl: String): Builder { this.invitationUrl = invitationUrl return this } /** * Specify the ID of an organization to join. * * @param organization the ID of the organization to join * @return the current builder instance * @see withInvitationUrl */ public fun withOrganization(organization: String): Builder { values[OAuthManager.KEY_ORGANIZATION] = organization return this } /** * Give a scope for this request. The default scope used is "openid profile email". * Regardless of the scopes passed, the "openid" scope is always enforced. * * @param scope to request. * @return the current builder instance */ public fun withScope(scope: String): Builder { values[OAuthManager.KEY_SCOPE] = scope return this } /** * Add custom headers for PKCE token request. * * @param headers for token request. * @return the current builder instance */ @Suppress("unused") public fun withHeaders(headers: Map<String, String>): Builder { this.headers.putAll(headers) return this } /** * Give a connection scope for this request. * * @param connectionScope to request. * @return the current builder instance */ public fun withConnectionScope(vararg connectionScope: String): Builder { values[KEY_CONNECTION_SCOPE] = connectionScope.joinToString(separator = ",") { it.trim() } return this } /** * Use extra parameters on the request. * * @param parameters to add * @return the current builder instance */ public fun withParameters(parameters: Map<String, Any?>): Builder { for ((key, value) in parameters) { if (value != null) { values[key] = value.toString() } } return this } /** * Use the given connection. By default no connection is specified, so the login page will be displayed. * * @param connectionName to use * @return the current builder instance */ public fun withConnection(connectionName: String): Builder { values[OAuthManager.KEY_CONNECTION] = connectionName return this } /** * When using a Custom Tabs compatible Browser, apply these customization options. * * @param options the Custom Tabs customization options * @return the current builder instance */ public fun withCustomTabsOptions(options: CustomTabsOptions): Builder { ctOptions = options return this } @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) internal fun withPKCE(pkce: PKCE): Builder { this.pkce = pkce return this } /** * Request user Authentication. The result will be received in the callback. * An error is raised if there are no browser applications installed in the device, or if * device does not support the necessary algorithms to support Proof of Key Exchange (PKCE) * (this is not expected), or if the user closed the browser before completing the authentication. * * @param context context to run the authentication * @param callback to receive the parsed results * @see AuthenticationException.isBrowserAppNotAvailable * @see AuthenticationException.isPKCENotAvailable * @see AuthenticationException.isAuthenticationCanceled */ public fun start( context: Context, callback: Callback<Credentials, AuthenticationException> ) { resetManagerInstance() if (!ctOptions.hasCompatibleBrowser(context.packageManager)) { val ex = AuthenticationException( "a0.browser_not_available", "No compatible Browser application is installed." ) callback.onFailure(ex) return } invitationUrl?.let { val url = Uri.parse(it) val organizationId = url.getQueryParameter(OAuthManager.KEY_ORGANIZATION) val invitationId = url.getQueryParameter(OAuthManager.KEY_INVITATION) if (organizationId.isNullOrBlank() || invitationId.isNullOrBlank()) { val ex = AuthenticationException( "a0.invalid_invitation_url", "The invitation URL provided doesn't contain the 'organization' or 'invitation' values." ) callback.onFailure(ex) return } values[OAuthManager.KEY_ORGANIZATION] = organizationId values[OAuthManager.KEY_INVITATION] = invitationId } val manager = OAuthManager(account, callback, values, ctOptions) manager.setHeaders(headers) manager.setPKCE(pkce) manager.setIdTokenVerificationLeeway(leeway) manager.setIdTokenVerificationIssuer(issuer) managerInstance = manager if (redirectUri == null) { redirectUri = CallbackHelper.getCallbackUri( scheme, context.applicationContext.packageName, account.getDomainUrl() ) } manager.startAuthentication(context, redirectUri!!, 110) } @JvmSynthetic @Throws(AuthenticationException::class) public suspend fun await(context: Context): Credentials { return await(context, Dispatchers.Main.immediate) } /** * Used internally so that [CoroutineContext] can be injected for testing purpose */ internal suspend fun await( context: Context, coroutineContext: CoroutineContext ): Credentials { return withContext(coroutineContext) { suspendCancellableCoroutine { continuation -> start(context, object : Callback<Credentials, AuthenticationException> { override fun onSuccess(result: Credentials) { continuation.resume(result) } override fun onFailure(error: AuthenticationException) { continuation.resumeWithException(error) } }) } } } private companion object { private const val KEY_AUDIENCE = "audience" private const val KEY_CONNECTION_SCOPE = "connection_scope" } } }
mit
ec3094b6a6b0bff8760a3d9b55df8d1e
37.690385
165
0.595706
5.571587
false
false
false
false