repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
jwren/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/TypeMappingConversion.kt
6
5917
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.nj2k.conversions import com.intellij.psi.PsiClass import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMap import org.jetbrains.kotlin.j2k.ast.Nullability import org.jetbrains.kotlin.j2k.toKotlinMutableTypesMap import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.symbols.JKClassSymbol import org.jetbrains.kotlin.nj2k.symbols.JKUniverseClassSymbol import org.jetbrains.kotlin.nj2k.tree.* import org.jetbrains.kotlin.nj2k.types.* import org.jetbrains.kotlin.psi.KtClass class TypeMappingConversion( context: NewJ2kConverterContext, inline val filter: (typeElement: JKTypeElement) -> Boolean = { true } ) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { when (element) { is JKTypeElement -> { if (filter(element)) { element.type = element.type.mapType(element) } } is JKNewExpression -> { val newClassSymbol = element.classSymbol.mapClassSymbol() return recurse( JKNewExpression( newClassSymbol, element::arguments.detached(), element::typeArgumentList.detached().fixTypeArguments(newClassSymbol), element::classBody.detached(), element.isAnonymousClass ).withPsiAndFormattingFrom(element) ) } } return recurse(element) } private fun JKTypeArgumentList.fixTypeArguments(classSymbol: JKClassSymbol): JKTypeArgumentList { if (typeArguments.isNotEmpty()) { return JKTypeArgumentList( typeArguments.map { typeArgument -> JKTypeElement(typeArgument.type.mapType(null), typeArgument::annotationList.detached()) } ) } return when (val typeParametersCount = classSymbol.expectedTypeParametersCount()) { 0 -> this else -> JKTypeArgumentList(List(typeParametersCount) { JKTypeElement(typeFactory.types.nullableAny) }) } } private fun JKType.fixRawType(typeElement: JKTypeElement?) = when (typeElement?.parent) { is JKClassLiteralExpression -> this is JKIsExpression -> addTypeParametersToRawProjectionType(JKStarProjectionTypeImpl) .updateNullability(Nullability.NotNull) is JKInheritanceInfo -> addTypeParametersToRawProjectionType(typeFactory.types.nullableAny) else -> addTypeParametersToRawProjectionType(JKStarProjectionTypeImpl) } private fun JKType.mapType(typeElement: JKTypeElement?): JKType = when (this) { is JKJavaPrimitiveType -> mapPrimitiveType() is JKClassType -> mapClassType() is JKJavaVoidType -> typeFactory.types.unit is JKJavaArrayType -> JKClassType( symbolProvider.provideClassSymbol(type.arrayFqName()), if (type is JKJavaPrimitiveType) emptyList() else listOf(type.mapType(typeElement)), nullability ) is JKVarianceTypeParameterType -> JKVarianceTypeParameterType( variance, boundType.mapType(null) ) is JKCapturedType -> { JKCapturedType( wildcardType.mapType(null) as JKWildCardType, nullability ) } else -> this }.fixRawType(typeElement) private fun JKClassSymbol.mapClassSymbol(): JKClassSymbol { if (this is JKUniverseClassSymbol) return this val newFqName = kotlinCollectionClassName() ?: kotlinStandardType() ?: fqName return symbolProvider.provideClassSymbol(newFqName) } private fun JKClassType.mapClassType(): JKClassType = JKClassType( classReference.mapClassSymbol(), parameters.map { it.mapType(null) }, nullability ) private fun JKClassSymbol.kotlinCollectionClassName(): String? = toKotlinMutableTypesMap[fqName] private fun JKClassSymbol.kotlinStandardType(): String? { if (isKtFunction(fqName)) return fqName return JavaToKotlinClassMap.mapJavaToKotlin(FqName(fqName))?.asString() } private fun JKJavaPrimitiveType.mapPrimitiveType(): JKClassType = typeFactory.fromPrimitiveType(this) private inline fun <reified T : JKType> T.addTypeParametersToRawProjectionType(typeParameter: JKType): T = if (this is JKClassType && parameters.isEmpty()) { val parametersCount = classReference.expectedTypeParametersCount() val typeParameters = List(parametersCount) { typeParameter } JKClassType( classReference, typeParameters, nullability ) as T } else this private fun JKClassSymbol.expectedTypeParametersCount(): Int = when (val resolvedClass = target) { is PsiClass -> resolvedClass.typeParameters.size is KtClass -> resolvedClass.typeParameters.size is JKClass -> resolvedClass.typeParameterList.typeParameters.size else -> 0 } companion object { private val ktFunctionRegex = "kotlin\\.jvm\\.functions\\.Function\\d+".toRegex() private fun isKtFunction(fqName: String) = ktFunctionRegex.matches(fqName) } }
apache-2.0
91dd2777731748a3fee73e585e0ba60e
39.258503
120
0.625993
5.733527
false
false
false
false
android/compose-samples
Jetsurvey/app/src/main/java/com/example/compose/jetsurvey/survey/SurveyRepository.kt
1
4290
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.compose.jetsurvey.survey import android.os.Build import com.example.compose.jetsurvey.R import com.example.compose.jetsurvey.survey.PossibleAnswer.Action import com.example.compose.jetsurvey.survey.SurveyActionType.PICK_DATE import com.example.compose.jetsurvey.survey.SurveyActionType.TAKE_PHOTO // Static data of questions private val jetpackQuestions = mutableListOf( Question( id = 1, questionText = R.string.in_my_free_time, answer = PossibleAnswer.MultipleChoice( options = listOf( AnswerOption(R.string.read), AnswerOption(R.string.work_out), AnswerOption(R.string.draw), AnswerOption(R.string.play_games), AnswerOption(R.string.dance), AnswerOption(R.string.watch_movies) ) ), description = R.string.select_all ), Question( id = 2, questionText = R.string.pick_superhero, answer = PossibleAnswer.SingleChoice( options = listOf( AnswerOption(R.string.spark, R.drawable.spark), AnswerOption(R.string.lenz, R.drawable.lenz), AnswerOption(R.string.bugchaos, R.drawable.bug_of_chaos), AnswerOption(R.string.frag, R.drawable.frag) ) ), description = R.string.select_one ), Question( id = 7, questionText = R.string.favourite_movie, answer = PossibleAnswer.SingleChoice( listOf( AnswerOption(R.string.star_trek), AnswerOption(R.string.social_network), AnswerOption(R.string.back_to_future), AnswerOption(R.string.outbreak) ) ), description = R.string.select_one ), Question( id = 3, questionText = R.string.takeaway, answer = Action(label = R.string.pick_date, actionType = PICK_DATE), description = R.string.select_date ), Question( id = 4, questionText = R.string.selfies, answer = PossibleAnswer.Slider( range = 1f..10f, steps = 3, startText = R.string.strongly_dislike, endText = R.string.strongly_like, neutralText = R.string.neutral ) ), ).apply { // TODO: FIX! After taking the selfie, the picture doesn't appear in API 22 and lower. if (Build.VERSION.SDK_INT >= 23) { add( Question( id = 975, questionText = R.string.selfie_skills, answer = Action(label = R.string.add_photo, actionType = TAKE_PHOTO), permissionsRequired = when (Build.VERSION.SDK_INT) { in 23..28 -> listOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) else -> emptyList() }, permissionsRationaleText = R.string.selfie_permissions ) ) } }.toList() private val jetpackSurvey = Survey( title = R.string.which_jetpack_library, questions = jetpackQuestions ) object JetpackSurveyRepository : SurveyRepository { override fun getSurvey() = jetpackSurvey @Suppress("UNUSED_PARAMETER") override fun getSurveyResult(answers: List<Answer<*>>): SurveyResult { return SurveyResult( library = "Compose", result = R.string.survey_result, description = R.string.survey_result_description ) } } interface SurveyRepository { fun getSurvey(): Survey fun getSurveyResult(answers: List<Answer<*>>): SurveyResult }
apache-2.0
20604f788e02f013f85d0081bf340c5f
32.779528
91
0.61049
4.346505
false
false
false
false
smmribeiro/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/annotator/GrAnnotatorImpl.kt
4
2921
// 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 org.jetbrains.plugins.groovy.annotator import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.roots.FileIndexFacade import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import org.jetbrains.plugins.groovy.GroovyBundle import org.jetbrains.plugins.groovy.codeInspection.type.GroovyStaticTypeCheckVisitor import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod import org.jetbrains.plugins.groovy.lang.psi.util.isCompileStatic import org.jetbrains.plugins.groovy.lang.psi.util.isFake class GrAnnotatorImpl : Annotator { override fun annotate(element: PsiElement, holder: AnnotationHolder) { val file = holder.currentAnnotationSession.file if (FileIndexFacade.getInstance(file.project).isInLibrarySource(file.virtualFile)) { return } if (element is GroovyPsiElement) { element.accept(GroovyAnnotator(holder)) if (isCompileStatic(element)) { element.accept(GroovyStaticTypeCheckVisitor(holder)) } } else if (element is PsiComment) { val text = element.getText() if (text.startsWith("/*") && !text.endsWith("*/")) { val range = element.getTextRange() holder.newAnnotation(HighlightSeverity.ERROR, GroovyBundle.message("doc.end.expected")).range( TextRange.create(range.endOffset - 1, range.endOffset)).create() } } else { val parent = element.parent if (parent is GrMethod && element == parent.nameIdentifierGroovy) { val illegalCharacters = illegalJvmNameSymbols.findAll(parent.name).mapTo(HashSet()) { it.value } if (illegalCharacters.isNotEmpty() && !parent.isFake()) { val chars = illegalCharacters.joinToString { "'$it'" } holder.newAnnotation(HighlightSeverity.WARNING, GroovyBundle.message("illegal.method.name", chars)).create() } if (parent.returnTypeElementGroovy == null) { GroovyAnnotator.checkMethodReturnType(parent, element, holder) } } else if (parent is GrField) { if (element == parent.nameIdentifierGroovy) { val getters = parent.getters for (getter in getters) { GroovyAnnotator.checkMethodReturnType(getter, parent.nameIdentifierGroovy, holder) } val setter = parent.setter if (setter != null) { GroovyAnnotator.checkMethodReturnType(setter, parent.nameIdentifierGroovy, holder) } } } } } }
apache-2.0
83701e7afeb25b35b598fe36ec6444df
42.597015
140
0.716878
4.473201
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/LambdaResultInflowBehaviour.kt
5
991
// 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.slicer import com.intellij.slicer.SliceUsage import com.intellij.util.Processor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.psi.KtElement object LambdaResultInflowBehaviour : KotlinSliceAnalysisMode.Behaviour { override fun processUsages( element: KtElement, parent: KotlinSliceUsage, uniqueProcessor: Processor<in SliceUsage> ) { InflowSlicer(element, uniqueProcessor, parent).processChildren(parent.forcedExpressionMode) } override val slicePresentationPrefix: String get() = KotlinBundle.message("slicer.text.tracking.enclosing.lambda") override val testPresentationPrefix: String get() = "[LAMBDA IN] " override fun equals(other: Any?) = other === this override fun hashCode() = 0 }
apache-2.0
5052cd77459e61f8a5c12040fc04ab00
35.740741
158
0.74672
4.587963
false
false
false
false
smmribeiro/intellij-community
python/src/com/jetbrains/python/sdk/poetry/PyPoetryPackageManagementService.kt
9
2434
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.sdk.poetry import com.intellij.execution.ExecutionException import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.webcore.packaging.RepoPackage import com.jetbrains.python.packaging.PyPIPackageUtil import com.jetbrains.python.packaging.PyPackageManagerUI import com.jetbrains.python.packaging.PyRequirementParser import com.jetbrains.python.packaging.ui.PyPackageManagementService /** * @author vlan */ /** * This source code is edited by @koxudaxi Koudai Aono <[email protected]> */ class PyPoetryPackageManagementService(project: Project, sdk: Sdk) : PyPackageManagementService(project, sdk) { override fun getAllRepositories(): List<String>? = null override fun canInstallToUser() = false override fun getAllPackages(): List<RepoPackage> { PyPIPackageUtil.INSTANCE.loadAdditionalPackages(sdk.poetrySources, false) return allPackagesCached } override fun reloadAllPackages(): List<RepoPackage> { PyPIPackageUtil.INSTANCE.loadAdditionalPackages(sdk.poetrySources, true) return allPackagesCached } override fun getAllPackagesCached(): List<RepoPackage> = PyPIPackageUtil.INSTANCE.getAdditionalPackages(sdk.poetrySources) override fun installPackage(repoPackage: RepoPackage, version: String?, forceUpgrade: Boolean, extraOptions: String?, listener: Listener, installToUser: Boolean) { val ui = PyPackageManagerUI(project, sdk, object : PyPackageManagerUI.Listener { override fun started() { listener.operationStarted(repoPackage.name) } override fun finished(exceptions: List<ExecutionException?>?) { listener.operationFinished(repoPackage.name, toErrorDescription(exceptions, sdk)) } }) val requirement = when { version != null -> PyRequirementParser.fromLine("${repoPackage.name}==$version") else -> PyRequirementParser.fromLine(repoPackage.name) } ?: return val extraArgs = extraOptions?.split(" +".toRegex()) ?: emptyList() ui.install(listOf(requirement), extraArgs) } }
apache-2.0
09686ba10cb33f812e276e3e7066fbd1
38.274194
140
0.701726
4.70793
false
false
false
false
kenail2002/logAnalyzer
h2database/src/main/java/p/k/tools/datasource/LogRecord.kt
1
868
package p.k.tools.datasource import java.sql.Timestamp import java.util.* class LogRecord() { var id: Long = 0 var logLevel: String? = null var logTime: Timestamp? = null var threadName: String? = null var msg: String? = null init { this.id = System.currentTimeMillis() * 1000 + Random().nextInt() % 100 } constructor(logTime:Timestamp,logLevel:String,threadName:String,msg:String) : this() { this.logTime=logTime this.logLevel=logLevel this.threadName=threadName this.msg=msg } override fun toString(): String { val sb = StringBuilder() sb.append("id=").append(this.id) sb.append(",logTime=").append(this.logTime) sb.append(",logLevel=").append(this.logLevel) sb.append(",msg=").append(this.msg) return sb.toString() } }
apache-2.0
ed3674980778e0f7fa11b37804fae56d
22.486486
88
0.614055
3.892377
false
false
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/Module/Search/SearchPetalActivity.kt
1
7224
package stan.androiddemo.project.petal.Module.Search import android.app.Activity import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.* import android.view.inputmethod.EditorInfo import android.widget.ArrayAdapter import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import com.jakewharton.rxbinding.widget.RxTextView import kotlinx.android.synthetic.main.activity_search_petal.* import licola.demo.com.huabandemo.Module.Search.SearcHHintAdapter import rx.android.schedulers.AndroidSchedulers import rx.functions.Func1 import rx.schedulers.Schedulers import stan.androiddemo.R import stan.androiddemo.UI.FlowLayout import stan.androiddemo.project.petal.API.SearchAPI import stan.androiddemo.project.petal.Base.BasePetalActivity import stan.androiddemo.project.petal.Config.Config import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient import stan.androiddemo.project.petal.Module.Type.PetalTypeActivity import stan.androiddemo.tool.CompatUtils import stan.androiddemo.tool.Logger import stan.androiddemo.tool.SPUtils import stan.androiddemo.tool.Utils import java.util.concurrent.TimeUnit class SearchPetalActivity : BasePetalActivity() { lateinit var mAdapter:ArrayAdapter<String> val arrListHttpHint = ArrayList<String>() var itemWidth = 0 companion object { fun launch(activity:Activity){ val intent = Intent(activity,SearchPetalActivity::class.java) activity.startActivity(intent) } } override fun getTag(): String { return this.toString() } override fun getLayoutId(): Int { return R.layout.activity_search_petal } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(toolbar) toolbar.setNavigationOnClickListener { onBackPressed() } image_btn_clear_history.setImageDrawable(CompatUtils.getTintListDrawable(mContext,R.drawable.ic_close_black_24dp,R.color.tint_list_grey)) initFlowReference(flow_search_reference_petal) mAdapter = SearcHHintAdapter(mContext,android.R.layout.simple_spinner_dropdown_item,arrListHttpHint) auto_txt_search_petal.setAdapter(mAdapter) initHintHttp() auto_txt_search_petal.setOnItemClickListener { _, _, i, _ -> Logger.d(arrListHttpHint[i]) SearchPetalResultActivity.launch(this,arrListHttpHint[i]) } RxTextView.editorActions(auto_txt_search_petal, Func1 { it == EditorInfo.IME_ACTION_SEARCH }).throttleFirst(500,TimeUnit.MILLISECONDS) .subscribe { initActionSearch() } initClearHistory() } override fun onResume() { super.onResume() initFLoaHistory(flow_search_history_petal) } fun initFLoaHistory(flowHistory:FlowLayout){ flowHistory.removeAllViews() val txtList = SPUtils.get(mContext,Config.HISTORYTEXT,HashSet<String>()) as HashSet<String> if (!txtList.isEmpty()){ for (txt in txtList){ addHistoryChildText(flowHistory,txt) } } else{ addChildNoHistoryTip(flowHistory,resources.getString(R.string.hint_not_history)) } } fun addHistoryChildText(flowHistory: FlowLayout,str: String){ val txt = LayoutInflater.from(mContext).inflate(R.layout.petal_txt_history_view_item,flowHistory,false) as TextView txt.text = str flowHistory.addView(txt) txt.setOnClickListener { SearchPetalResultActivity.launch(this,str) } } fun addChildNoHistoryTip(flowHistory: FlowLayout,str: String){ val txtTip = TextView(mContext) val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) layoutParams.gravity = Gravity.CENTER layoutParams.setMargins(10, 10, 10, 10) txtTip.text = str txtTip.layoutParams = layoutParams txtTip.gravity = Gravity.CENTER_HORIZONTAL flowHistory.addView(txtTip) } fun initFlowReference(flowHistory: FlowLayout){ val txtList = resources.getStringArray(R.array.title_array_all) val typeList = resources.getStringArray(R.array.type_array_all) itemWidth = Utils.getScreenWidth(mContext) / 3 - 2 for (i in 0 until txtList.size){ addReferenceButton(flowHistory,txtList[i],typeList[i],R.drawable.ic_loyalty_black_24dp) } } fun addReferenceButton(flowHistory: FlowLayout,str: String,type:String,resId:Int){ val btn = Button(mContext) val layoutParams = LinearLayout.LayoutParams(itemWidth,ViewGroup.LayoutParams.WRAP_CONTENT) layoutParams.gravity = Gravity.CENTER layoutParams.setMargins(1,1,1,1) btn.setCompoundDrawablesRelativeWithIntrinsicBounds(null, CompatUtils.getTintListDrawable(mContext,resId,R.color.tint_list_pink) ,null,null) btn.text = str btn.setBackgroundColor(Color.WHITE) btn.tag = type btn.layoutParams = layoutParams btn.gravity = Gravity.CENTER btn.setOnClickListener { PetalTypeActivity.launch(this,str,type) } flowHistory.addView(btn) } fun initHintHttp(){ RxTextView.textChanges(auto_txt_search_petal).observeOn(Schedulers.io()) .filter { it.length > 0 } .debounce(300,TimeUnit.MILLISECONDS) .switchMap { RetrofitClient.createService(SearchAPI::class.java).httpsSearHintBean(mAuthorization,it.toString()) } .map { it.result } .filter { it != null && it.size > 0 } .observeOn(AndroidSchedulers.mainThread()) .subscribe({it-> run { arrListHttpHint.clear() arrListHttpHint.addAll(it!!) mAdapter.notifyDataSetChanged() } },{ err-> run { err.printStackTrace() } }) } fun initActionSearch(){ if (auto_txt_search_petal.text.length > 0){ SearchPetalResultActivity.launch(this,auto_txt_search_petal.text.toString()) } } fun initClearHistory(){ image_btn_clear_history.setOnClickListener { flow_search_history_petal.removeAllViews() SPUtils.remove(mContext,Config.HISTORYTEXT) addChildNoHistoryTip(flow_search_history_petal,resources.getString(R.string.hint_not_history)) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.petal_search_menu,menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item!!.itemId){ R.id.action_search->{ initActionSearch() } } return super.onOptionsItemSelected(item) } }
mit
77c53b67dbbbc250d0d22dab93a375d4
36.625
145
0.66196
4.486957
false
false
false
false
TachiWeb/TachiWeb-Server
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/library/LibraryControllerImpl.kt
1
3554
package xyz.nulldev.ts.api.v2.java.impl.library import com.f2prateek.rx.preferences.Preference import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.preference.getOrDefault import uy.kohesive.injekt.injectLazy import xyz.nulldev.ts.api.v2.java.model.FilterStatus import xyz.nulldev.ts.api.v2.java.model.SortDirection import xyz.nulldev.ts.api.v2.java.model.library.* import eu.kanade.tachiyomi.ui.library.LibrarySort as LibrarySortConsts class LibraryControllerImpl : LibraryController { private val prefs by injectLazy<PreferencesHelper>() private val libraryConstMappings = mapOf( LibrarySortConsts.ALPHA to LibrarySortType.ALPHA, LibrarySortConsts.LAST_READ to LibrarySortType.LAST_READ, LibrarySortConsts.LAST_UPDATED to LibrarySortType.LAST_UPDATED, LibrarySortConsts.UNREAD to LibrarySortType.UNREAD, LibrarySortConsts.TOTAL to LibrarySortType.TOTAL, LibrarySortConsts.SOURCE to LibrarySortType.SOURCE ) override var flags: LibraryFlags get() = LibraryFlags( filters = listOf( loadFilter(FilterType.DOWNLOADED), loadFilter(FilterType.UNREAD), loadFilter(FilterType.COMPLETED) ), sort = LibrarySort( libraryConstMappings[prefs.librarySortingMode().getOrDefault()] ?: error("Unknown sort type"), if(prefs.librarySortingAscending().getOrDefault()) { SortDirection.ASCENDING } else { SortDirection.DESCENDING } ), display = if(prefs.libraryAsList().getOrDefault()) { DisplayType.LIST } else { DisplayType.GRID }, showDownloadBadges = prefs.downloadBadge().getOrDefault() ) set(value) { value.filters.forEach { filterTypeToPref(it.type).set(when(it.status) { FilterStatus.ANY -> false FilterStatus.INCLUDE -> true FilterStatus.EXCLUDE -> throw IllegalArgumentException("FilterStatus.EXCLUDE is not supported in this field!") }) } prefs.librarySortingMode().set(libraryConstMappings.entries.find { it.value == value.sort.type}?.key ?: error("Unknown sorting mode!")) prefs.librarySortingAscending().set(when(value.sort.direction) { SortDirection.DESCENDING -> false SortDirection.ASCENDING -> true }) prefs.libraryAsList().set(when(value.display) { DisplayType.GRID -> false DisplayType.LIST -> true }) prefs.downloadBadge().set(value.showDownloadBadges) } private fun filterTypeToPref(filterType: FilterType): Preference<Boolean> { return when(filterType) { FilterType.DOWNLOADED -> prefs.filterDownloaded() FilterType.UNREAD -> prefs.filterUnread() FilterType.COMPLETED -> prefs.filterCompleted() } } private fun loadFilter(type: FilterType): LibraryFilter { return LibraryFilter(type, if(filterTypeToPref(type).getOrDefault()) { FilterStatus.INCLUDE } else { FilterStatus.ANY}) } }
apache-2.0
714441d8cd2e93760489440c15d5331b
42.341463
130
0.597355
5.272997
false
false
false
false
koma-im/koma
src/main/kotlin/koma/gui/view/window/roomfinder/publicroomlist/listview.kt
1
8222
package koma.gui.view.window.roomfinder.publicroomlist import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.collections.transformation.FilteredList import javafx.geometry.Orientation import javafx.geometry.Pos import javafx.scene.control.Button import javafx.scene.control.ListView import javafx.scene.control.ScrollBar import javafx.scene.input.MouseEvent import javafx.scene.layout.Priority import javafx.util.Callback import koma.gui.view.window.roomfinder.publicroomlist.listcell.DiscoveredRoomFragment import koma.gui.view.window.roomfinder.publicroomlist.listcell.joinById import koma.koma_app.AppStore import koma.matrix.DiscoveredRoom import koma.matrix.RoomListing import koma.matrix.room.naming.RoomId import koma.util.getOrThrow import koma.util.onFailure import koma.util.onSuccess import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.MainScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.* import kotlinx.coroutines.javafx.JavaFx import kotlinx.coroutines.launch import link.continuum.desktop.gui.* import link.continuum.desktop.util.Account import mu.KotlinLogging import org.controlsfx.control.Notifications import org.controlsfx.control.textfield.CustomTextField import org.controlsfx.control.textfield.TextFields import java.util.function.Predicate private val logger = KotlinLogging.logger {} fun canBeValidRoomAlias(input: String): Boolean { val ss = input.split(':') if (ss.size != 2) return false return ss[0].startsWith('#') && ss[1].isNotEmpty() } fun canBeValidRoomId(input: String): Boolean { val ss = input.split(':') if (ss.size != 2) return false return ss[0].startsWith('!') && ss[1].isNotEmpty() } class PublicRoomsView(private val account: Account, private val appData: AppStore ) { private val scope = MainScope() val ui = VBox(5.0) private val _input = MutableStateFlow("") val input: StateFlow<String> get() = _input private val roomListView: RoomListView init { val field = TextFields.createClearableTextField() as CustomTextField field.textProperty().addListener { _, _, newValue -> _input.value = newValue } roomListView = RoomListView(input, account, appData) VBox.setVgrow(ui, Priority.ALWAYS) field.promptText = "#example:matrix.org" val joinByAliasButton = Button("Join by Room Alias").apply { showIf(false) setOnAction { joinRoomByAlias(input.value) } } val joinByIdButton = Button("Join by Room ID").apply { showIf(false) setOnAction { val inputid = input.value scope.joinById(RoomId(inputid), inputid, this, account, appData) } } input.onEach { val inputStartAlias = it.startsWith('#') joinByAliasButton.showIf(inputStartAlias) val inputIsAlias = canBeValidRoomAlias(it) joinByAliasButton.isDisable = !inputIsAlias joinByIdButton.showIf(it.startsWith('!')) joinByIdButton.isDisable = !canBeValidRoomId(it) }.launchIn(scope) ui.apply { hbox(5.0) { alignment = Pos.CENTER_LEFT label("Filter:") add(field) add(joinByAliasButton) add(joinByIdButton) } add(roomListView.root) } } private fun joinRoomByAlias(alias: String) { val api = account.server scope.launch { val rs = api.resolveRoomAlias(alias) rs.onSuccess { joinById(it.room_id, alias, [email protected] , account, appData) } rs.onFailure { launch(Dispatchers.JavaFx) { Notifications.create() .owner([email protected]) .title("Failed to resolve room alias $alias") .position(Pos.CENTER) .text(it.message) .showWarning() } } } } } class RoomListView( input: StateFlow<String>, private val account: Account, appData: AppStore ) { private val scope = MainScope() private val roomlist: ObservableList<DiscoveredRoom> = FXCollections.observableArrayList<DiscoveredRoom>() private val matchRooms = FilteredList(roomlist) val root = ListView(matchRooms) private var scrollBar: ScrollBar? = null private val needLoadMore = Channel<Unit>(Channel.CONFLATED) // rooms already joined by user or loaded in room finder private val existing = hashSetOf<RoomId>() init { val myRooms = appData.keyValueStore.roomsOf(account.userId) existing.addAll(myRooms.joinedRoomList) with(root) { VBox.setVgrow(this, Priority.ALWAYS) cellFactory = Callback{ DiscoveredRoomFragment(account, appData) } } root.skinProperty().addListener { _ -> scrollBar = findScrollBar() scrollBar?.let { it.visibleProperty().addListener { _, _, viewFilled -> if (!viewFilled) needLoadMore.offer(Unit) // listView not fully filled } it.valueProperty().divide(it.maxProperty()).addListener { _, _, scrollPerc -> if (scrollPerc.toFloat() > 0.78) needLoadMore.offer(Unit) } } } needLoadMore.offer(Unit) input.onEach { logger.trace { "input: $it." } updateFilter(it.trim()) }.debounce(200).distinctUntilChanged().flatMapLatest { logger.trace { "fetch: $it." } account.publicRoomFlow(it.takeIf { it.isNotBlank() }, limit = 20).takeWhile { kResult -> kResult.isSuccess }.map { it.getOrThrow() } }.buffer(0) // slow down requests unless needed .zip(needLoadMore.consumeAsFlow(), ::first) .onEach { addNewRooms(it.chunk) loadMoreIfNotFilled() }.launchIn(scope) } //workaround some problem with zip private suspend fun<T> first(r: RoomListing, i: T): RoomListing { logger.trace { "loaded ${r.chunk.size} rooms"} return r } private fun loadMoreIfNotFilled() { val sb = scrollBar ?: run { logger.warn { "scrollBar is null"} needLoadMore.offer(Unit) return } if (!sb.isVisible) { logger.debug { "scrollBar isVisible is false"} needLoadMore.offer(Unit) return } if (sb.value / sb.max.coerceAtLeast(0.01) > 0.85) { logger.debug { "scrollBar is at ${sb.value} of ${sb.max}"} needLoadMore.offer(Unit) return } } private fun updateFilter(term: String) { // all rooms unfiltered if (term.isBlank()) { matchRooms.predicate = null return } if (term.startsWith('#') || term.startsWith('!')) { return } val words = term.split(' ') matchRooms.predicate = Predicate { r: DiscoveredRoom -> r.containsTerms(words) } } /** * deduplicate */ private fun addNewRooms(rooms: List<DiscoveredRoom>) { val new = rooms.filter { existing.add(it.room_id) } logger.debug { "adding ${new.size} of ${rooms.size}" } roomlist.addAll(new) } private fun findScrollBar(): ScrollBar? { val nodes = root.lookupAll("VirtualScrollBar") for (node in nodes) { if (node is ScrollBar) { if (node.orientation == Orientation.VERTICAL) { logger.debug { "found scrollbar $node"} return node } } } System.err.println("failed to find scrollbar of listview") return null } }
gpl-3.0
7e33617c1d636683a8972afad76c0c89
33.84322
110
0.595962
4.535025
false
false
false
false
thuytrinh/KotlinPlayground
src/test/kotlin/turbine/HotFlowWithTurbineTest.kt
1
1541
package turbine import app.cash.turbine.test import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.test.runBlockingTest import org.assertj.core.api.Assertions.assertThat import org.junit.Test class HotFlowWithTurbineTest { @Test fun `should receive 1, 2, 3 and should not complete`() = runBlockingTest { // Given val hotFlow = channelFlow { send(1) send(2) send(3) awaitClose() } // When hotFlow.test { // Then assertThat(expectItem()).isEqualTo(1) assertThat(expectItem()).isEqualTo(2) assertThat(expectItem()).isEqualTo(3) } } @Test fun `should receive 1, 2 and 3 (alternative version)`() = runBlockingTest { // Given val hotFlow = MutableStateFlow(1) // When hotFlow.test { // Then assertThat(expectItem()).isEqualTo(1) // When hotFlow.value = 2 // Then assertThat(expectItem()).isEqualTo(2) } } @Test fun `should throw exception`() = runBlockingTest { // Given val hotFlow = channelFlow<Int> { error("Oops!") awaitClose() } // When hotFlow.test { // Then expectError() } } @Test fun `should not throw exception`() = runBlockingTest { // Given val hotFlow = channelFlow { send(0) awaitClose() } // When hotFlow.test { // Then assertThat(expectItem()).isEqualTo(0) } } }
mit
ea2cd3a96971695e78d0192d33bf6de4
18.75641
77
0.619079
4.098404
false
true
false
false
seventhroot/elysium
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/command/ItemMetaCommand.kt
1
3874
package com.rpkit.essentials.bukkit.command import com.rpkit.essentials.bukkit.RPKEssentialsBukkit import org.bukkit.ChatColor import org.bukkit.Material import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class ItemMetaCommand(private val plugin: RPKEssentialsBukkit) : CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (sender.hasPermission("rpkit.essentials.command.itemmeta")) { if (sender is Player) { val itemInMainHand = sender.inventory.itemInMainHand if (itemInMainHand.type != Material.AIR) { if (args.size >= 2) { val meta = itemInMainHand.itemMeta ?: plugin.server.itemFactory.getItemMeta(itemInMainHand.type) if (meta == null) { sender.sendMessage(plugin.messages["item=meta-failed-to-create"]) return true } if (args[0].equals("setname", ignoreCase = true)) { val name = ChatColor.translateAlternateColorCodes('&', args.drop(1).joinToString(" ")) meta.setDisplayName(name) sender.sendMessage(plugin.messages["item-meta-set-name-valid", mapOf( Pair("name", name) )]) } else if (args[0].equals("addlore", ignoreCase = true)) { val lore = meta.lore ?: mutableListOf<String>() val loreItem = ChatColor.translateAlternateColorCodes('&', args.drop(1).joinToString(" ")) lore.add(loreItem) sender.sendMessage(plugin.messages["item-meta-add-lore-valid", mapOf( Pair("lore", loreItem) )]) meta.lore = lore } else if (args[0].equals("removelore", ignoreCase = true)) { if (meta.hasLore()) { val lore = meta.lore ?: mutableListOf<String>() val loreItem = ChatColor.translateAlternateColorCodes('&', args.drop(1).joinToString(" ")) if (lore.contains(loreItem)) { lore.remove(loreItem) sender.sendMessage(plugin.messages["item-meta-remove-lore-valid", mapOf( Pair("lore", loreItem) )]) } else { sender.sendMessage(plugin.messages["item-meta-remove-lore-invalid-lore-item"]) } meta.lore = lore } else { sender.sendMessage(plugin.messages["item-meta-remove-lore-invalid-lore"]) } } else { sender.sendMessage(plugin.messages["item-meta-usage"]) } itemInMainHand.itemMeta = meta } else { sender.sendMessage(plugin.messages["item-meta-usage"]) } } else { sender.sendMessage(plugin.messages["item-meta-invalid-item"]) } } else { sender.sendMessage(plugin.messages["not-from-console"]) } } else { sender.sendMessage(plugin.messages["no-permission-item-meta"]) } return true } }
apache-2.0
ca8a3f933138bb2aedb142664e1fce33
52.068493
122
0.48064
5.630814
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/search/gene/SeededGene.kt
1
7979
package org.evomaster.core.search.gene import org.evomaster.core.output.OutputFormat import org.evomaster.core.problem.util.ParamUtil import org.evomaster.core.search.gene.collection.EnumGene import org.evomaster.core.search.gene.interfaces.ComparableGene import org.evomaster.core.search.gene.root.CompositeFixedGene import org.evomaster.core.search.gene.utils.GeneUtils import org.evomaster.core.search.impact.impactinfocollection.value.SeededGeneImpact import org.evomaster.core.search.service.AdaptiveParameterControl import org.evomaster.core.search.service.Randomness import org.evomaster.core.search.service.mutator.MutationWeightControl import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy /** * represent gene which contains seeded values customized by user with the driver */ class SeededGene<T>( name: String, /** * the gene and its value could be randomized and handled during the search */ val gene: T, /** * a set of candidates specified by user, the search could manipulate which one is applied */ val seeded: EnumGene<T>, //FIXME but T genes are not immutable... need a ChoiceGene /** * representing if the [seeded] is applied to represent this * otherwise apply [gene] */ var employSeeded: Boolean = false ) : CompositeFixedGene(name, listOf(gene, seeded)) where T : ComparableGene, T: Gene{ /** * we might prevent search to manipulate the [employSeeded] */ var isEmploySeededMutable = true private set /** * forbid changing [employSeeded] during the search */ fun forbidEmploySeededMutable(){ isEmploySeededMutable = false } override fun isLocallyValid() : Boolean{ return getViewOfChildren().all { it.isLocallyValid() } } override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) { if(!gene.initialized) gene.randomize(randomness, tryToForceNewValue) if (isEmploySeededMutable){ if (tryToForceNewValue) { employSeeded = !employSeeded return } else if (randomness.nextBoolean()){ employSeeded = randomness.nextBoolean() } } if (!employSeeded) gene.randomize(randomness, tryToForceNewValue) else seeded.randomize(randomness, tryToForceNewValue) } override fun copyContent(): SeededGene<T> { val copy = SeededGene(name, gene.copy() as T, seeded.copy() as EnumGene<T>, employSeeded) copy.isEmploySeededMutable = this.isEmploySeededMutable return copy } /** * @return a gene representing [this] */ fun getPhenotype() : T{ return if (!employSeeded) gene else seeded.values[seeded.index] } override fun getValueAsPrintableString( previousGenes: List<Gene>, mode: GeneUtils.EscapeMode?, targetFormat: OutputFormat?, extraCheck: Boolean ): String { return if (employSeeded) seeded.getValueAsPrintableString(mode = mode, targetFormat = targetFormat) else gene.getValueAsPrintableString(mode = mode, targetFormat = targetFormat) } override fun copyValueFrom(other: Gene) { if (other !is SeededGene<*>) throw IllegalArgumentException("Invalid gene ${other::class.java}") this.employSeeded = other.employSeeded this.isEmploySeededMutable = other.isEmploySeededMutable if (employSeeded) this.seeded.copyValueFrom(other.seeded) else this.gene.copyValueFrom(other.gene as Gene) } override fun containsSameValueAs(other: Gene): Boolean { if (other !is SeededGene<*>) throw IllegalArgumentException("Invalid gene ${other::class.java}") return this.employSeeded == other.employSeeded && (if (employSeeded) this.seeded.containsSameValueAs(other.seeded) else this.gene.containsSameValueAs(other.gene as Gene)) } override fun possiblySame(gene : Gene) : Boolean = super.possiblySame(gene) && this.gene.possiblySame((gene as SeededGene<*>).gene as Gene) override fun bindValueBasedOn(gene: Gene): Boolean { // only allow bind value for gene if (gene is SeededGene<*> && isEmploySeededMutable){ employSeeded = gene.employSeeded if (!employSeeded) return ParamUtil.getValueGene(this.gene).bindValueBasedOn(ParamUtil.getValueGene(gene.gene as Gene)) else return seeded.bindValueBasedOn(gene.seeded) } if (gene !is SeededGene<*> && !employSeeded){ return ParamUtil.getValueGene(this.gene).bindValueBasedOn(ParamUtil.getValueGene(gene)) } return false } override fun adaptiveSelectSubsetToMutate(randomness: Randomness, internalGenes: List<Gene>, mwc: MutationWeightControl, additionalGeneMutationInfo: AdditionalGeneMutationInfo): List<Pair<Gene, AdditionalGeneMutationInfo?>> { if (additionalGeneMutationInfo.impact != null && additionalGeneMutationInfo.impact is SeededGeneImpact){ if (internalGenes.size != 1) throw IllegalStateException("mismatched input: the internalGenes should only contain one candidate") return if (internalGenes.contains(gene)) listOf(gene to additionalGeneMutationInfo.copyFoInnerGene(additionalGeneMutationInfo.impact.geneImpact, gene = gene)) else if (internalGenes.contains(seeded)) listOf(seeded to additionalGeneMutationInfo.copyFoInnerGene(additionalGeneMutationInfo.impact.seededGeneImpact, gene = seeded)) else throw IllegalStateException("mismatched input: the internalGenes should contain either gene or seeded") } throw IllegalArgumentException("impact is null or not SeedGeneImpact") } override fun mutablePhenotypeChildren(): List<Gene> { return listOf((if (employSeeded) seeded else gene)) } override fun customShouldApplyShallowMutation( randomness: Randomness, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { var changeEmploySeed = false if (isEmploySeededMutable){ if (!enableAdaptiveGeneMutation || additionalGeneMutationInfo?.impact == null){ changeEmploySeed = randomness.nextBoolean() }else{ if (additionalGeneMutationInfo.impact is SeededGeneImpact){ changeEmploySeed = additionalGeneMutationInfo.impact.employSeedImpact.determinateSelect( minManipulatedTimes = 5, times = 1.5, preferTrue = true, targets = additionalGeneMutationInfo.targets, selector = additionalGeneMutationInfo.archiveGeneSelector ) }else throw IllegalArgumentException("impact is null or not SeededGeneImpact ${additionalGeneMutationInfo.impact}") } } return changeEmploySeed } override fun shallowMutate( randomness: Randomness, apc: AdaptiveParameterControl, mwc: MutationWeightControl, selectionStrategy: SubsetGeneMutationSelectionStrategy, enableAdaptiveGeneMutation: Boolean, additionalGeneMutationInfo: AdditionalGeneMutationInfo? ): Boolean { if (isEmploySeededMutable) employSeeded = !employSeeded return true } override fun isMutable(): Boolean { return isEmploySeededMutable || gene.isMutable() || seeded.isMutable() } }
lgpl-3.0
30dccfbdf1e745e5540f1119b3e87abb
38.310345
229
0.674771
5.015085
false
false
false
false
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/output/oracles/ImplementedOracle.kt
1
5724
package org.evomaster.core.output.oracles import io.swagger.v3.oas.models.PathItem import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.Lines import org.evomaster.core.output.OutputFormat import org.evomaster.core.output.ObjectGenerator import org.evomaster.core.output.TestCase import org.evomaster.core.problem.rest.RestCallAction import org.evomaster.core.problem.httpws.service.HttpWsCallResult import org.evomaster.core.problem.rest.RestActionBuilderV3 import org.evomaster.core.problem.rest.RestIndividual import org.evomaster.core.search.EvaluatedAction import org.evomaster.core.search.EvaluatedIndividual import org.slf4j.Logger import org.slf4j.LoggerFactory import java.net.URI import java.net.URISyntaxException abstract class ImplementedOracle { private val log: Logger = LoggerFactory.getLogger(ImplementedOracle::class.java) /** * [variableDeclaration] handles, for each [ImplementedOracle] the process of generating variables that * activate and deactivate the checking of that particular oracle, along with a short * comment explaining its purpose. */ abstract fun variableDeclaration(lines: Lines, format: OutputFormat) /** * [addExpectations] handles the process of generating the code for failing expectations, as evaluated * by the particular oracle implementation. */ abstract fun addExpectations(call: RestCallAction, lines: Lines, res: HttpWsCallResult, name: String, format: OutputFormat) /** * The [setObjectGenerator] method is used to add the [ObjectGenerator] to individual oracles. At the time * of writing, both implemented oracles require information from this object (schemas and supported codes). */ abstract fun setObjectGenerator(gen: ObjectGenerator) /** * The [generatesExpectation] method is used to determine if, for a given [EvaluatedAction], the * [ImplementedOracle] generates an expectation. */ abstract fun generatesExpectation(call: RestCallAction, res: HttpWsCallResult): Boolean /** * The [generatesExpectation] method is used to determine if, for a given [EvaluatedIndividual], * the [ImplementedOracle] generates an expectation. */ abstract fun generatesExpectation(individual: EvaluatedIndividual<*>): Boolean /** * The [selectForClustering] method determines if a particular action is selected for clustering, * according to the current [ImplementedOracle]. Normally, selection is based on whether or not * an [ImplementedOracle] generates an expectation for the given [EvaluatedAction]. However, additional * conditions may be imposed (for example, ensuring that the [EvaluatedAction] is of a particular type, * and that is has a call and a result of types [RestCallAction] and [RestCallResult], respectively). * * Additional conditions may be required by future [ImplementedOracle] objects. */ abstract fun selectForClustering(action: EvaluatedAction): Boolean /** * [getName] returns the name of the oracle. This is used for identification, both in the generated * code and in determining oracle status. */ abstract fun getName(): String /** * The [adjustName] method returns a String with a name adjustment, or null if the [ImplementedOracle] * does not adjust the [TestCase] name. The name adjustment is appended to the existing name. */ open fun adjustName(): String?{ return null } /** * Some OpenAPI paths are called inconsistently (e.g. with or without "/api" appended as a prefix). * * This is a workaround (ScoutAPI only sees paths without the prefix, others with the prefix). * Longer term, this could also be a place to handle any additional peculiarities with SUT specific * OpenAPI standards. * * The same applies where the prefix is "v2" (e.g. language tools). */ fun retrievePath(objectGenerator: ObjectGenerator, call: RestCallAction): PathItem? { val swagger = objectGenerator.getSwagger() val basePath = RestActionBuilderV3.getBasePathFromURL(swagger) // This is likely where the problem is. /* If the basepath is empty - it shows up as "/" leading to "//" in the final path. if the basepath is not empty, ignoring it also causes problems. */ val adjustedBasePath = if (basePath.endsWith("/")) { basePath.dropLast(1) } else{ basePath } val possibleItems = objectGenerator.getSwagger().paths.filter{ e -> call.path.toString().contentEquals(adjustedBasePath + e.key) //call.path.toString().contentEquals(basePath+e.key) } val result = when (possibleItems.size){ 0 -> null 1 -> possibleItems.entries.first().value else -> { // This should not happen unless multiples paths match the call. But it's technically not impossible. Then pick the longest key (to avoid matching root "/", see ProxyPrint). // I'd prefer not to throw exceptions that would disrupt the rest of the writing process. //log.warn("There seem to be multiple paths matching a call: ${call.verb}${call.path}. Only one will be returned.") val possibleItemString = possibleItems.entries.joinToString { it.key } LoggingUtil.Companion.uniqueWarn(log, "There seem to be multiple paths matching a call: ${call.verb}\n${possibleItemString}. Only one will be returned.") possibleItems.entries.maxByOrNull{ it.key.length }?.value } } return result } }
lgpl-3.0
ae24a21f26bfd1889afa9b46f42812ba
44.07874
189
0.70318
4.714992
false
false
false
false
xwiki-contrib/android-authenticator
app/src/main/java/org/xwiki/android/sync/activities/AccountListAdapter.kt
1
1827
package org.xwiki.android.sync.activities import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import org.xwiki.android.sync.R import org.xwiki.android.sync.contactdb.UserAccount import org.xwiki.android.sync.utils.AccountClickListener class AccountListAdapter( private val mContext: Context, private var availableAccounts: List<UserAccount>, private val listener: AccountClickListener ) : RecyclerView.Adapter<AccountListAdapter.AccountListViewHolder>() { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ) = AccountListViewHolder(LayoutInflater.from(mContext), listener) override fun getItemCount(): Int = availableAccounts.size override fun onBindViewHolder(holder: AccountListViewHolder, position: Int) { holder.account = availableAccounts[position] } class AccountListViewHolder( layoutInflater: LayoutInflater, listener: AccountClickListener ) : RecyclerView.ViewHolder( layoutInflater.inflate(R.layout.account_list_layout, null) ) { private val tvAccountName: TextView = itemView.findViewById(R.id.tvAccountName) private val tvAccountServerAddress: TextView = itemView.findViewById(R.id.tvAccountServerAddress) var account: UserAccount? = null set(value) { field = value tvAccountName.text = account ?.accountName ?: "" tvAccountServerAddress.text = account ?.serverAddress ?: "" } init { itemView.findViewById<View>(R.id.llAccountItem).setOnClickListener { account ?.also { listener(it) } } } } }
lgpl-2.1
ef4a4f2cdcbb8a6198854ab2b21effb4
33.471698
105
0.706623
4.978202
false
false
false
false
daemontus/Distributed-CTL-Model-Checker
src/main/kotlin/com/github/sybila/checker/map/RangeStateMap.kt
3
620
package com.github.sybila.checker.map import com.github.sybila.checker.StateMap class RangeStateMap<out Params : Any>( private val range: IntRange, private val value: Params, private val default: Params ) : StateMap<Params> { override fun states(): Iterator<Int> = range.iterator() override fun entries(): Iterator<Pair<Int, Params>> = range.asSequence().map { it to value }.iterator() override fun get(state: Int): Params = if (state in range) value else default override fun contains(state: Int): Boolean = state in range override val sizeHint: Int = range.count() }
gpl-3.0
fcd482f540752a5300e3b92f43fb74ff
28.571429
107
0.693548
4.133333
false
false
false
false
AlmasB/FXGL
fxgl-core/src/main/kotlin/com/almasb/fxgl/time/Timer.kt
1
4426
/* * FXGL - JavaFX Game Library. The MIT License (MIT). * Copyright (c) AlmasB ([email protected]). * See LICENSE for details. */ package com.almasb.fxgl.time import javafx.beans.property.ReadOnlyBooleanProperty import javafx.util.Duration import java.util.concurrent.CopyOnWriteArrayList /** * Timer that supports running actions at an interval and with a delay. * Runs on the same thread that updates the timer. * * @author Almas Baimagambetov ([email protected]) */ class Timer { private val timerActions = CopyOnWriteArrayList<TimerAction>() /** * @return time in seconds accumulated by this timer */ var now = 0.0 private set /** * Call this to drive (advance) the timer. * * @param tpf time per frame by which to advance this timer */ fun update(tpf: Double) { now += tpf timerActions.forEach { it.update(tpf) if (it.isExpired) timerActions.remove(it) } } /** * The Runnable [action] will be scheduled to start at given [interval]. * The action will start for the first time after given interval. * The action will be scheduled unlimited number of times unless user cancels it * via the returned action object. * * @return timer action */ fun runAtInterval(action: Runnable, interval: Duration): TimerAction { return runAtInterval(action, interval, Int.MAX_VALUE) } /** * The Runnable [action] will be scheduled to start at given [interval]. * The action will start for the first time after given interval. * The action will be scheduled [limit] number of times unless user cancels it * via the returned action object. * * @return timer action */ fun runAtInterval(action: Runnable, interval: Duration, limit: Int): TimerAction { val act = TimerAction(interval, action, limit) timerActions.add(act) return act } /** * The Runnable [action] will be scheduled to start at given [interval]. * The Runnable action will be scheduled IFF * [whileCondition] is initially true. * The action will start for the first time after given interval. * The action will be removed from schedule when [whileCondition] becomes "false". * Note: you must retain the reference to the [whileCondition] property to avoid it being * garbage collected, otherwise the [action] may never stop. * * @return timer action */ fun runAtIntervalWhile(action: Runnable, interval: Duration, whileCondition: ReadOnlyBooleanProperty): TimerAction { if (!whileCondition.get()) { return TimerAction(interval, action, 0) } val act = TimerAction(interval, action) timerActions.add(act) whileCondition.addListener { _, _, isTrue -> if (!isTrue) act.expire() } return act } /** * The Runnable [action] will be scheduled to run once after given [delay]. * The action can be cancelled before it starts via the returned action object. * * @return timer action */ fun runOnceAfter(action: Runnable, delay: Duration): TimerAction { return runAtInterval(action, delay, 1) } /** * The Runnable [action] will be scheduled to run once after given [delay]. * The action can be cancelled before it starts via the returned action object. * * @return timer action */ fun runOnceAfter(action: () -> Unit, delay: Duration): TimerAction { return runOnceAfter(Runnable(action), delay) } /** * Remove all scheduled actions. */ fun clear() { timerActions.clear() } /** * Constructs a local timer that is driven by this timer. */ fun newLocalTimer(): LocalTimer = object : LocalTimer { private var time = 0.0 /** * Captures current time. */ override fun capture() { time = now } /** * Returns true if difference between captured time * and now is greater or equal to given duration. * * @param duration time duration to check * @return true if elapsed, false otherwise */ override fun elapsed(duration: Duration) = now - time >= duration.toSeconds() } }
mit
a20f6d1397d1285c32b89475cc0ad3c4
28.912162
120
0.623588
4.567595
false
false
false
false
newbieandroid/AppBase
app/src/main/java/com/fuyoul/sanwenseller/structure/presenter/EditBabyP.kt
1
5795
package com.fuyoul.sanwenseller.structure.presenter import android.app.Activity import android.content.Context import android.util.Log import com.alibaba.fastjson.JSON import com.fuyoul.sanwenseller.base.BaseP import com.fuyoul.sanwenseller.bean.reqhttp.ReqEditBaby import com.fuyoul.sanwenseller.bean.reqhttp.ReqReleaseBaby import com.fuyoul.sanwenseller.bean.reshttp.ResHttpBabyItem import com.fuyoul.sanwenseller.bean.reshttp.ResHttpResult import com.fuyoul.sanwenseller.bean.reshttp.ResQiNiuBean import com.fuyoul.sanwenseller.configs.Code import com.fuyoul.sanwenseller.helper.HttpDialogHelper import com.fuyoul.sanwenseller.helper.MsgDialogHelper import com.fuyoul.sanwenseller.helper.QiNiuHelper import com.fuyoul.sanwenseller.listener.HttpReqListener import com.fuyoul.sanwenseller.listener.QiNiuUpLoadListener import com.fuyoul.sanwenseller.structure.model.EditBabyM import com.fuyoul.sanwenseller.structure.view.EditBabyV import com.fuyoul.sanwenseller.utils.NormalFunUtils /** * @author: chen * @CreatDate: 2017\10\27 0027 * @Desc: */ class EditBabyP(editBabyV: EditBabyV) : BaseP<EditBabyM, EditBabyV>(editBabyV) { override fun getModelImpl(): EditBabyM = EditBabyM() fun editBaby(activity: Activity, item: ResHttpBabyItem, addImgs: List<String>, deleteImgs: List<String>) { val data = ReqEditBaby() data.detail = item.introduce data.goodsClassifyId = item.goodsClassifyId data.name = item.goodsName data.goodsId = item.goodsId data.price = item.price data.imgs = ReqEditBaby.ImgsBean() //如果是本地图片 if (addImgs.isNotEmpty() && !addImgs[0].startsWith("http")) { data.imgs.add = addImgs data.imgs.delete = deleteImgs HttpDialogHelper.showDialog(activity, true, false) QiNiuHelper.multQiNiuUpLoad(activity, addImgs, object : QiNiuUpLoadListener { override fun complete(path: List<ResQiNiuBean>) { val result = ArrayList<String>() result.add(path[0].key!!) data.imgs.add = result edit(activity, data) } override fun error(error: String) { NormalFunUtils.showToast(activity, "更改图片失败,请重试") HttpDialogHelper.dismisss() } }) } else { edit(activity, data) } } private fun edit(activity: Activity, data: ReqEditBaby) { getModelImpl().editBaby(data, object : HttpReqListener(activity) { override fun reqOk(result: ResHttpResult) { MsgDialogHelper.showStateDialog(activity, "编辑成功", true, object : MsgDialogHelper.DialogOndismissListener { override fun onDismiss(context: Context) { activity.setResult(Activity.RESULT_OK) activity.finish() } }) } override fun withoutData(code: Int, msg: String) { if (code == Code.HTTP_SUCCESS) { MsgDialogHelper.showStateDialog(activity, "编辑成功", true, object : MsgDialogHelper.DialogOndismissListener { override fun onDismiss(context: Context) { activity.setResult(Activity.RESULT_OK) activity.finish() } }) } else { NormalFunUtils.showToast(activity, msg) } } override fun error(errorInfo: String) { NormalFunUtils.showToast(activity, errorInfo) } }) } fun releaseBaby(activity: Activity, data: ReqReleaseBaby) { HttpDialogHelper.showDialog(activity, true, false) val localPath = ArrayList<String>() localPath.add(data.imgs) QiNiuHelper.multQiNiuUpLoad(activity, localPath, object : QiNiuUpLoadListener { override fun complete(path: List<ResQiNiuBean>) { data.imgs = path[0].key doReleaseBaby(activity, data) } override fun error(error: String) { HttpDialogHelper.dismisss() NormalFunUtils.showToast(activity, "图片上传失败,请重试") } }) } private fun doReleaseBaby(activity: Activity, data: ReqReleaseBaby) { Log.e("csl", "发布宝贝实体:${JSON.toJSONString(data)}") getModelImpl().releaseBaby(data, object : HttpReqListener(activity) { override fun reqOk(result: ResHttpResult) { MsgDialogHelper.showStateDialog(activity, "发布成功", true, object : MsgDialogHelper.DialogOndismissListener { override fun onDismiss(context: Context) { activity.setResult(Activity.RESULT_OK) activity.finish() } }) } override fun withoutData(code: Int, msg: String) { if (code == Code.HTTP_SUCCESS) { MsgDialogHelper.showStateDialog(activity, "发布成功", true, object : MsgDialogHelper.DialogOndismissListener { override fun onDismiss(context: Context) { activity.setResult(Activity.RESULT_OK) activity.finish() } }) } NormalFunUtils.showToast(activity, msg) } override fun error(errorInfo: String) { NormalFunUtils.showToast(activity, errorInfo) } }) } }
apache-2.0
d0d6cf5180d252a1b7289b08e16a1472
30.666667
126
0.593788
4.741265
false
false
false
false
shchurov/gitter-kotlin-client
app/src/main/kotlin/com/github/shchurov/gitterclient/data/subscribers/ErrorMessageGenerator.kt
1
1228
package com.github.shchurov.gitterclient.data.subscribers import com.github.shchurov.gitterclient.R import com.github.shchurov.gitterclient.data.network.model.ErrorResponse import com.github.shchurov.gitterclient.utils.getString import com.google.gson.Gson import retrofit.HttpException import java.net.SocketTimeoutException import java.net.UnknownHostException @Suppress("UNCHECKED_CAST") object ErrorMessageGenerator { private val gson = Gson() fun generateErrorMessage(exception: Throwable): String { return when (exception) { is HttpException -> generateApiError(exception) is UnknownHostException, is SocketTimeoutException -> getConnectionError() else -> getUnexpectedError() } } private fun generateApiError(exception: HttpException) = try { val errorResponse = gson.fromJson(exception.response().errorBody().string(), ErrorResponse::class.java) getString(R.string.gitter_error, errorResponse.description) } catch (e: Exception) { getUnexpectedError() } private fun getConnectionError() = getString(R.string.check_your_connection) private fun getUnexpectedError() = getString(R.string.unexpected_error) }
apache-2.0
a8539bbc6d420d950caf612ab4f873c6
34.114286
111
0.745114
4.834646
false
false
false
false
nickthecoder/tickle
tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/physics/TickleLineJoint.kt
1
3208
/* 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.physics import org.jbox2d.dynamics.joints.LineJoint import org.jbox2d.dynamics.joints.LineJointDef import org.joml.Vector2d import uk.co.nickthecoder.tickle.Actor import uk.co.nickthecoder.tickle.util.Angle /** * Join two actors together, as if there were an extendable rod between them. * By default, this rod can grow infinitely long, but can be limited * using [limitTranslation]. * * NOTE. It is up to you to destroy the joint (for example, if actorA or actorB dies before the scene is over). * * @param pointA The position of the pin, relative to [actorA]. * This is (0,0), if you want them welded at the "middle" of actorA. * Note, you do NOT have to account for the actor's rotation (if it is rotated), * but you DO have to take account of its scale (if it has been scaled). * * @param pointB The position of the pin, relative to [actorB]. * This is (0,0), if you want them welded at the "middle" of actorB. * Note, you do NOT have to account for the actor's rotation (if it is rotated), * but you DO have to take account of its scale (if it has been scaled). */ class TickleLineJoint(actorA: Actor, actorB: Actor, pointA: Vector2d, pointB: Vector2d) : TickleJoint<LineJoint, LineJointDef>(actorA, actorB, pointA, pointB) { var referenceAngle: Angle = Angle.radians(0.0) set(v) { field = v replace() } override fun createDef(): LineJointDef { val jointDef = LineJointDef() jointDef.bodyA = actorA.body!!.jBox2DBody jointDef.bodyB = actorB.body!!.jBox2DBody tickleWorld.pixelsToWorld(jointDef.localAnchorA, pointA) tickleWorld.pixelsToWorld(jointDef.localAnchorB, pointB) return jointDef } /** * Prevents the extendable rod from becoming too short, or too long. * The opposite is [freeTranslation]. */ fun limitTranslation(lower: Double, upper: Double) { jBox2dJoint?.setLimits(tickleWorld.pixelsToWorld(lower), tickleWorld.pixelsToWorld(upper)) } /** * The opposite of [limitTranslation] */ fun freeTranslation() { jBox2dJoint?.EnableLimit(false) } fun getLimits(): Pair<Double, Double>? { jBox2dJoint?.let { if (it.isLimitEnabled) { return Pair(tickleWorld.worldToPixels(it.lowerLimit), tickleWorld.worldToPixels(it.upperLimit)) } else { return null } } return null } }
gpl-3.0
8b23ffc9692948e554a5fdec490d9318
35.044944
111
0.68485
3.787485
false
false
false
false
tronalddump-io/tronald-app
src/main/kotlin/io/tronalddump/app/random/RandomController.kt
1
3004
package io.tronalddump.app.random import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.Content import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import io.swagger.v3.oas.annotations.responses.ApiResponses import io.tronalddump.app.Url import io.tronalddump.app.meme.MemeGenerator import io.tronalddump.app.quote.QuoteModel import io.tronalddump.app.quote.QuoteModelAssembler import io.tronalddump.app.quote.QuoteRepository import io.tronalddump.app.quote_source.QuoteSourceModel import io.tronalddump.app.search.PageModel import org.springframework.hateoas.MediaTypes import org.springframework.http.HttpHeaders import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody @RequestMapping(value = [Url.RANDOM]) @RestController class RandomController( private val assembler: QuoteModelAssembler, private val memeGenerator: MemeGenerator, private val repository: QuoteRepository ) { @ApiResponses(value = [ ApiResponse(responseCode = "200", content = [ Content(schema = Schema(implementation = ResponseEntity::class)) ]) ]) @Operation(summary = "Retrieve a random quote meme", tags = ["quote"]) @ResponseBody @RequestMapping( headers = [ "${HttpHeaders.ACCEPT}=${MediaType.IMAGE_JPEG_VALUE}" ], method = [RequestMethod.GET], value = ["/meme"] ) fun meme(@RequestHeader(HttpHeaders.ACCEPT) acceptHeader: String): ResponseEntity<StreamingResponseBody> { var quote = repository.randomQuote().get() val headers = HttpHeaders() headers.contentType = MediaType.IMAGE_JPEG headers.set("X-Quote-Id", quote.quoteId) val stream = StreamingResponseBody { memeGenerator.generate(it, quote) } return ResponseEntity( stream, headers, HttpStatus.OK ) } @ApiResponses(value = [ ApiResponse(responseCode = "200", content = [ Content(schema = Schema(implementation = QuoteModel::class)) ]) ]) @Operation(summary = "Retrieve a random quote", tags = ["quote"]) @ResponseBody @RequestMapping( headers = [ "${HttpHeaders.ACCEPT}=${MediaType.APPLICATION_JSON_VALUE}", "${HttpHeaders.ACCEPT}=${MediaTypes.HAL_JSON_VALUE}" ], method = [RequestMethod.GET], produces = [MediaType.APPLICATION_JSON_VALUE], value = ["/quote"] ) fun random(@RequestHeader(HttpHeaders.ACCEPT) acceptHeader: String): QuoteModel { return assembler.toModel( repository.randomQuote().get() ) } }
gpl-3.0
5104bd63df0a1a2d96267b06b502d883
34.761905
110
0.674434
4.593272
false
false
false
false
HughG/partial-order
partial-order-app/src/main/kotlin/org/tameter/partialorder/source/kpouchdb/RedmineSourceSpecDoc.kt
1
711
package org.tameter.partialorder.source.kpouchdb import org.tameter.partialorder.source.RedmineSourceSpec external interface RedmineSourceSpecDoc : SourceSpecDoc, RedmineSourceSpec val REDMINE_SOURCE_SPEC_DOC_TYPE = "${SOURCE_SPEC_DOC_TYPE}_redmine" fun RedmineSourceSpecDoc( description: String, url: String, projectId: String? = null, apiKey: String? = null ): RedmineSourceSpecDoc { return SourceSpecDoc<RedmineSourceSpecDoc>( "${url}:projectId=${projectId}", REDMINE_SOURCE_SPEC_DOC_TYPE, description ).apply { asDynamic().url = url asDynamic().projectId = projectId asDynamic().apiKey = apiKey } }
mit
0f9efd1a335bca455e81b29ba9f36bfd
28.625
74
0.673699
4.062857
false
false
false
false
nlefler/Glucloser
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/models/parcelable/PlaceParcelable.kt
1
1377
package com.nlefler.glucloser.a.models.parcelable import android.os.Parcel import android.os.Parcelable import java.util.* /** * Created by Nathan Lefler on 12/24/14. */ public class PlaceParcelable() : Parcelable { var primaryId: String = UUID.randomUUID().toString() var name: String = "" var foursquareId: String = "" var latitude: Float = 0f var longitude: Float = 0f var visitCount: Int = 0 /** Parcelable */ protected constructor(parcel: Parcel): this() { name = parcel.readString() foursquareId = parcel.readString() latitude = parcel.readFloat() longitude = parcel.readFloat() } override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeString(name) dest.writeString(foursquareId) dest.writeFloat(latitude) dest.writeFloat(longitude) } companion object { @JvmField val CREATOR: Parcelable.Creator<PlaceParcelable> = object : Parcelable.Creator<PlaceParcelable> { override fun createFromParcel(parcel: Parcel): PlaceParcelable { return PlaceParcelable(parcel) } override fun newArray(size: Int): Array<PlaceParcelable> { return Array(size, {i -> PlaceParcelable() }) } } } }
gpl-2.0
1ba13cb20202155677cd3f006ac37f95
27.6875
115
0.630356
4.485342
false
false
false
false
robinverduijn/gradle
.teamcity/Gradle_Check/configurations/Gradleception.kt
1
1902
package configurations import common.buildToolGradleParameters import common.customGradle import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId import jetbrains.buildServer.configs.kotlin.v2018_2.BuildSteps import jetbrains.buildServer.configs.kotlin.v2018_2.buildSteps.GradleBuildStep import model.CIBuildModel import model.Stage class Gradleception(model: CIBuildModel, stage: Stage) : BaseGradleBuildType(model, stage = stage, init = { uuid = "${model.projectPrefix}Gradleception" id = AbsoluteId(uuid) name = "Gradleception - Java8 Linux" description = "Builds Gradle with the version of Gradle which is currently under development (twice)" params { param("env.JAVA_HOME", buildJavaHome) } features { publishBuildStatusToGithub(model) } val buildScanTagForType = buildScanTag("Gradleception") val defaultParameters = (buildToolGradleParameters() + listOf(buildScanTagForType)).joinToString(separator = " ") applyDefaults(model, this, ":install", notQuick = true, extraParameters = "-Pgradle_installPath=dogfood-first $buildScanTagForType", extraSteps = { localGradle { name = "BUILD_WITH_BUILT_GRADLE" tasks = "clean :install" gradleHome = "%teamcity.build.checkoutDir%/dogfood-first" gradleParams = "-Pgradle_installPath=dogfood-second -PignoreIncomingBuildReceipt=true $defaultParameters" } localGradle { name = "QUICKCHECK_WITH_GRADLE_BUILT_BY_GRADLE" tasks = "clean sanityCheck test" gradleHome = "%teamcity.build.checkoutDir%/dogfood-second" gradleParams = defaultParameters } }) }) fun BuildSteps.localGradle(init: GradleBuildStep.() -> Unit): GradleBuildStep = customGradle(init) { param("ui.gradleRunner.gradle.wrapper.useWrapper", "false") buildFile = "" }
apache-2.0
7321e27dd459850f0f9032865c89acfe
38.625
151
0.706099
4.382488
false
true
false
false
anthologist/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/activities/ViewPagerActivity.kt
1
31331
package com.simplemobiletools.gallery.activities import android.animation.Animator import android.animation.ValueAnimator import android.annotation.TargetApi import android.app.Activity import android.content.Intent import android.content.pm.ActivityInfo import android.content.res.Configuration import android.database.Cursor import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Color import android.graphics.Matrix import android.graphics.drawable.ColorDrawable import android.media.ExifInterface import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Handler import android.provider.MediaStore import android.support.v4.view.ViewPager import android.util.DisplayMetrics import android.view.Menu import android.view.MenuItem import android.view.View import android.view.WindowManager import android.view.animation.DecelerateInterpolator import com.bumptech.glide.Glide import com.simplemobiletools.commons.dialogs.PropertiesDialog import com.simplemobiletools.commons.dialogs.RenameItemDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.* import com.simplemobiletools.commons.models.FileDirItem import com.simplemobiletools.gallery.R import com.simplemobiletools.gallery.adapters.MyPagerAdapter import com.simplemobiletools.gallery.asynctasks.GetMediaAsynctask import com.simplemobiletools.gallery.dialogs.DeleteWithRememberDialog import com.simplemobiletools.gallery.dialogs.SaveAsDialog import com.simplemobiletools.gallery.dialogs.SlideshowDialog import com.simplemobiletools.gallery.extensions.* import com.simplemobiletools.gallery.fragments.PhotoFragment import com.simplemobiletools.gallery.fragments.VideoFragment import com.simplemobiletools.gallery.fragments.ViewPagerFragment import com.simplemobiletools.gallery.helpers.* import com.simplemobiletools.gallery.models.Medium import kotlinx.android.synthetic.main.activity_medium.* import java.io.* import java.util.* class ViewPagerActivity : SimpleActivity(), ViewPager.OnPageChangeListener, ViewPagerFragment.FragmentListener { private var mPath = "" private var mDirectory = "" private var mIsFullScreen = false private var mPos = -1 private var mShowAll = false private var mIsSlideshowActive = false private var mSkipConfirmationDialog = false private var mRotationDegrees = 0 private var mPrevHashcode = 0 private var mSlideshowHandler = Handler() private var mSlideshowInterval = SLIDESHOW_DEFAULT_INTERVAL private var mSlideshowMoveBackwards = false private var mSlideshowMedia = mutableListOf<Medium>() private var mAreSlideShowMediaVisible = false private var mIsOrientationLocked = false private var mStoredReplaceZoomableImages = false private var mMediaFiles = ArrayList<Medium>() companion object { var screenWidth = 0 var screenHeight = 0 var wasDecodedByGlide = false } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_medium) setTranslucentNavigation() mMediaFiles = MediaActivity.mMedia.clone() as ArrayList<Medium> handlePermission(PERMISSION_WRITE_STORAGE) { if (it) { initViewPager() } else { toast(R.string.no_storage_permissions) finish() } } storeStateVariables() } override fun onResume() { super.onResume() if (!hasPermission(PERMISSION_WRITE_STORAGE)) { finish() return } if (mStoredReplaceZoomableImages != config.replaceZoomableImages) { mPrevHashcode = 0 refreshViewPager() } supportActionBar?.setBackgroundDrawable(resources.getDrawable(R.drawable.actionbar_gradient_background)) if (config.maxBrightness) { val attributes = window.attributes attributes.screenBrightness = 1f window.attributes = attributes } setupRotation() invalidateOptionsMenu() if (config.blackBackground) { updateStatusbarColor(Color.BLACK) } } override fun onPause() { super.onPause() stopSlideshow() storeStateVariables() } override fun onDestroy() { super.onDestroy() if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) { config.temporarilyShowHidden = false } if (config.isThirdPartyIntent) { config.isThirdPartyIntent = false if (intent.extras == null || !intent.getBooleanExtra(IS_FROM_GALLERY, false)) { mMediaFiles.clear() } } } private fun initViewPager() { measureScreen() val uri = intent.data if (uri != null) { var cursor: Cursor? = null try { val proj = arrayOf(MediaStore.Images.Media.DATA) cursor = contentResolver.query(uri, proj, null, null, null) if (cursor?.moveToFirst() == true) { mPath = cursor.getStringValue(MediaStore.Images.Media.DATA) } } finally { cursor?.close() } } else { try { mPath = intent.getStringExtra(PATH) mShowAll = config.showAll } catch (e: Exception) { showErrorToast(e) finish() return } } if (intent.extras?.containsKey(REAL_FILE_PATH) == true) { mPath = intent.extras.getString(REAL_FILE_PATH) } if (mPath.isEmpty()) { toast(R.string.unknown_error_occurred) finish() return } if (!getDoesFilePathExist(mPath)) { Thread { scanPath(mPath) }.start() finish() return } if (intent.extras?.containsKey(IS_VIEW_INTENT) == true) { if (isShowHiddenFlagNeeded()) { if (!config.isPasswordProtectionOn) { config.temporarilyShowHidden = true } } config.isThirdPartyIntent = true } showSystemUI() mDirectory = mPath.getParentPath() if (mDirectory.startsWith(OTG_PATH.trimEnd('/'))) { mDirectory += "/" } supportActionBar?.title = mPath.getFilenameFromPath() view_pager.onGlobalLayout { if (!isActivityDestroyed()) { if (mMediaFiles.isNotEmpty()) { gotMedia(mMediaFiles) } } } refreshViewPager() if (config.blackBackground) { view_pager.background = ColorDrawable(Color.BLACK) } if (config.hideSystemUI) { view_pager.onGlobalLayout { Handler().postDelayed({ fragmentClicked() }, 500) } } window.decorView.setOnSystemUiVisibilityChangeListener { visibility -> mIsFullScreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0 view_pager.adapter?.let { (it as MyPagerAdapter).toggleFullscreen(mIsFullScreen) checkSystemUI() } } } private fun setupRotation() { if (mIsOrientationLocked) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED } } else if (config.screenRotation == ROTATE_BY_DEVICE_ROTATION) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR } else if (config.screenRotation == ROTATE_BY_SYSTEM_SETTING) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_viewpager, menu) val currentMedium = getCurrentMedium() ?: return true menu.apply { findItem(R.id.menu_share_1).isVisible = !config.replaceShare findItem(R.id.menu_share_2).isVisible = config.replaceShare findItem(R.id.menu_rotate).isVisible = currentMedium.isImage() findItem(R.id.menu_save_as).isVisible = mRotationDegrees != 0 findItem(R.id.menu_hide).isVisible = !currentMedium.name.startsWith('.') findItem(R.id.menu_unhide).isVisible = currentMedium.name.startsWith('.') findItem(R.id.menu_lock_orientation).isVisible = mRotationDegrees == 0 findItem(R.id.menu_lock_orientation).title = getString(if (mIsOrientationLocked) R.string.unlock_orientation else R.string.lock_orientation) findItem(R.id.menu_rotate).setShowAsAction( if (mRotationDegrees != 0) { MenuItem.SHOW_AS_ACTION_ALWAYS } else { MenuItem.SHOW_AS_ACTION_IF_ROOM }) } return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (getCurrentMedium() == null) return true when (item.itemId) { R.id.menu_set_as -> setAs(getCurrentPath()) R.id.menu_slideshow -> initSlideshow() R.id.menu_copy_to -> copyMoveTo(true) R.id.menu_move_to -> copyMoveTo(false) R.id.menu_open_with -> openPath(getCurrentPath(), true) R.id.menu_hide -> toggleFileVisibility(true) R.id.menu_unhide -> toggleFileVisibility(false) R.id.menu_share_1 -> shareMedium(getCurrentMedium()!!) R.id.menu_share_2 -> shareMedium(getCurrentMedium()!!) R.id.menu_delete -> checkDeleteConfirmation() R.id.menu_rename -> renameFile() R.id.menu_edit -> openEditor(getCurrentPath()) R.id.menu_properties -> showProperties() R.id.menu_show_on_map -> showOnMap() R.id.menu_rotate_right -> rotateImage(90) R.id.menu_rotate_left -> rotateImage(270) R.id.menu_rotate_one_eighty -> rotateImage(180) R.id.menu_lock_orientation -> toggleLockOrientation() R.id.menu_save_as -> saveImageAs() R.id.menu_settings -> launchSettings() else -> return super.onOptionsItemSelected(item) } return true } private fun storeStateVariables() { config.apply { mStoredReplaceZoomableImages = replaceZoomableImages } } private fun updatePagerItems(media: MutableList<Medium>) { val pagerAdapter = MyPagerAdapter(this, supportFragmentManager, media) if (!isActivityDestroyed()) { view_pager.apply { adapter = pagerAdapter currentItem = mPos removeOnPageChangeListener(this@ViewPagerActivity) addOnPageChangeListener(this@ViewPagerActivity) } } } private fun initSlideshow() { SlideshowDialog(this) { startSlideshow() } } private fun startSlideshow() { if (getMediaForSlideshow()) { view_pager.onGlobalLayout { if (!isActivityDestroyed()) { hideSystemUI() mSlideshowInterval = config.slideshowInterval mSlideshowMoveBackwards = config.slideshowMoveBackwards mIsSlideshowActive = true window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) scheduleSwipe() } } } } private fun animatePagerTransition(forward: Boolean) { val oldPosition = view_pager.currentItem val animator = ValueAnimator.ofInt(0, view_pager.width) animator.addListener(object : Animator.AnimatorListener { override fun onAnimationRepeat(animation: Animator?) { } override fun onAnimationEnd(animation: Animator?) { if (view_pager.isFakeDragging) { try { view_pager.endFakeDrag() } catch (ignored: Exception) { stopSlideshow() } if (view_pager.currentItem == oldPosition) { slideshowEnded(forward) } } } override fun onAnimationCancel(animation: Animator?) { view_pager.endFakeDrag() } override fun onAnimationStart(animation: Animator?) { } }) animator.interpolator = DecelerateInterpolator() animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { var oldDragPosition = 0 override fun onAnimationUpdate(animation: ValueAnimator) { if (view_pager?.isFakeDragging == true) { val dragPosition = animation.animatedValue as Int val dragOffset = dragPosition - oldDragPosition oldDragPosition = dragPosition try { view_pager.fakeDragBy(dragOffset * (if (forward) 1f else -1f)) } catch (e: Exception) { stopSlideshow() } } } }) animator.duration = SLIDESHOW_SCROLL_DURATION view_pager.beginFakeDrag() animator.start() } private fun slideshowEnded(forward: Boolean) { if (config.loopSlideshow) { if (forward) { view_pager.setCurrentItem(0, false) } else { view_pager.setCurrentItem(view_pager.adapter!!.count - 1, false) } } else { stopSlideshow() toast(R.string.slideshow_ended) } } private fun stopSlideshow() { if (mIsSlideshowActive) { mIsSlideshowActive = false showSystemUI() mSlideshowHandler.removeCallbacksAndMessages(null) window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) } } private fun scheduleSwipe() { mSlideshowHandler.removeCallbacksAndMessages(null) if (mIsSlideshowActive) { if (getCurrentMedium()!!.isImage() || getCurrentMedium()!!.isGif()) { mSlideshowHandler.postDelayed({ if (mIsSlideshowActive && !isActivityDestroyed()) { swipeToNextMedium() } }, mSlideshowInterval * 1000L) } else { (getCurrentFragment() as? VideoFragment)!!.playVideo() } } } private fun swipeToNextMedium() { animatePagerTransition(!mSlideshowMoveBackwards) } private fun getMediaForSlideshow(): Boolean { mSlideshowMedia = mMediaFiles.toMutableList() if (!config.slideshowIncludePhotos) { mSlideshowMedia = mSlideshowMedia.filter { !it.isImage() } as MutableList } if (!config.slideshowIncludeVideos) { mSlideshowMedia = mSlideshowMedia.filter { it.isImage() || it.isGif() } as MutableList } if (!config.slideshowIncludeGIFs) { mSlideshowMedia = mSlideshowMedia.filter { !it.isGif() } as MutableList } if (config.slideshowRandomOrder) { mSlideshowMedia.shuffle() mPos = 0 } else { mPath = getCurrentPath() mPos = getPositionInList(mSlideshowMedia) } return if (mSlideshowMedia.isEmpty()) { toast(R.string.no_media_for_slideshow) false } else { updatePagerItems(mSlideshowMedia) mAreSlideShowMediaVisible = true true } } private fun copyMoveTo(isCopyOperation: Boolean) { val currPath = getCurrentPath() val fileDirItems = arrayListOf(FileDirItem(currPath, currPath.getFilenameFromPath())) tryCopyMoveFilesTo(fileDirItems, isCopyOperation) { config.tempFolderPath = "" if (!isCopyOperation) { refreshViewPager() } } } private fun toggleFileVisibility(hide: Boolean) { toggleFileVisibility(getCurrentPath(), hide) { val newFileName = it.getFilenameFromPath() supportActionBar?.title = newFileName getCurrentMedium()!!.apply { name = newFileName path = it getCurrentMedia()[mPos] = this } invalidateOptionsMenu() } } private fun rotateImage(degrees: Int) { mRotationDegrees = (mRotationDegrees + degrees) % 360 getCurrentFragment()?.let { (it as? PhotoFragment)?.rotateImageViewBy(mRotationDegrees) } supportInvalidateOptionsMenu() } private fun toggleLockOrientation() { mIsOrientationLocked = !mIsOrientationLocked if (mIsOrientationLocked) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LOCKED } } else { setupRotation() } invalidateOptionsMenu() } private fun saveImageAs() { val currPath = getCurrentPath() SaveAsDialog(this, currPath, false) { handleSAFDialog(it) { Thread { saveImageToFile(currPath, it) }.start() } } } private fun saveImageToFile(oldPath: String, newPath: String) { toast(R.string.saving) if (oldPath == newPath && oldPath.isJpg()) { if (tryRotateByExif(oldPath)) { return } } val newFile = File(newPath) val tmpFile = File(filesDir, ".tmp_${newPath.getFilenameFromPath()}") try { getFileOutputStream(tmpFile.toFileDirItem(applicationContext)) { if (it == null) { toast(R.string.unknown_error_occurred) return@getFileOutputStream } val oldLastModified = getCurrentFile().lastModified() if (oldPath.isJpg()) { copyFile(getCurrentFile(), tmpFile) saveExifRotation(ExifInterface(tmpFile.absolutePath), mRotationDegrees) } else { val bitmap = BitmapFactory.decodeFile(oldPath) saveFile(tmpFile, bitmap, it as FileOutputStream) } if (tmpFile.length() > 0 && getDoesFilePathExist(newPath)) { tryDeleteFileDirItem(FileDirItem(newPath, newPath.getFilenameFromPath())) } copyFile(tmpFile, newFile) scanPath(newPath) toast(R.string.file_saved) if (config.keepLastModified) { newFile.setLastModified(oldLastModified) updateLastModified(newPath, oldLastModified) } it.flush() it.close() mRotationDegrees = 0 invalidateOptionsMenu() // we cannot refresh a specific image in Glide Cache, so just clear it all val glide = Glide.get(applicationContext) glide.clearDiskCache() runOnUiThread { glide.clearMemory() } } } catch (e: OutOfMemoryError) { toast(R.string.out_of_memory_error) } catch (e: Exception) { showErrorToast(e) } finally { tryDeleteFileDirItem(FileDirItem(tmpFile.absolutePath, tmpFile.absolutePath.getFilenameFromPath())) } } @TargetApi(Build.VERSION_CODES.N) private fun tryRotateByExif(path: String): Boolean { return try { if (saveImageRotation(path, mRotationDegrees)) { mRotationDegrees = 0 invalidateOptionsMenu() toast(R.string.file_saved) true } else { false } } catch (e: Exception) { showErrorToast(e) false } } private fun copyFile(source: File, destination: File) { var inputStream: InputStream? = null var out: OutputStream? = null try { val fileDocument = if (isPathOnSD(destination.absolutePath)) getDocumentFile(destination.parent) else null out = getFileOutputStreamSync(destination.absolutePath, source.getMimeType(), fileDocument) inputStream = FileInputStream(source) inputStream.copyTo(out!!) } finally { inputStream?.close() out?.close() } } private fun saveFile(file: File, bitmap: Bitmap, out: FileOutputStream) { val matrix = Matrix() matrix.postRotate(mRotationDegrees.toFloat()) val bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true) bmp.compress(file.absolutePath.getCompressionFormat(), 90, out) } private fun isShowHiddenFlagNeeded(): Boolean { val file = File(mPath) if (file.isHidden) { return true } var parent = file.parentFile ?: return false while (true) { if (parent.isHidden || parent.list()?.any { it.startsWith(NOMEDIA) } == true) { return true } if (parent.absolutePath == "/") { break } parent = parent.parentFile ?: return false } return false } private fun getCurrentFragment() = (view_pager.adapter as MyPagerAdapter).getCurrentFragment(view_pager.currentItem) private fun showProperties() { if (getCurrentMedium() != null) { PropertiesDialog(this, getCurrentPath(), false) } } private fun showOnMap() { val exif: ExifInterface try { exif = ExifInterface(getCurrentPath()) } catch (e: Exception) { showErrorToast(e) return } val lat = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) val lat_ref = exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF) val lon = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) val lon_ref = exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF) if (lat == null || lat_ref == null || lon == null || lon_ref == null) { toast(R.string.unknown_location) } else { val geoLat = if (lat_ref == "N") { convertToDegree(lat) } else { 0 - convertToDegree(lat) } val geoLon = if (lon_ref == "E") { convertToDegree(lon) } else { 0 - convertToDegree(lon) } val uriBegin = "geo:$geoLat,$geoLon" val query = "$geoLat, $geoLon" val encodedQuery = Uri.encode(query) val uriString = "$uriBegin?q=$encodedQuery&z=16" val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString)) val packageManager = packageManager if (intent.resolveActivity(packageManager) != null) { startActivity(intent) } else { toast(R.string.no_app_found) } } } private fun convertToDegree(stringDMS: String): Float { val dms = stringDMS.split(",".toRegex(), 3).toTypedArray() val stringD = dms[0].split("/".toRegex(), 2).toTypedArray() val d0 = stringD[0].toDouble() val d1 = stringD[1].toDouble() val floatD = d0 / d1 val stringM = dms[1].split("/".toRegex(), 2).toTypedArray() val m0 = stringM[0].toDouble() val m1 = stringM[1].toDouble() val floatM = m0 / m1 val stringS = dms[2].split("/".toRegex(), 2).toTypedArray() val s0 = stringS[0].toDouble() val s1 = stringS[1].toDouble() val floatS = s0 / s1 return (floatD + floatM / 60 + floatS / 3600).toFloat() } override fun onActivityResult(requestCode: Int, resultCode: Int, resultData: Intent?) { if (requestCode == REQUEST_EDIT_IMAGE) { if (resultCode == Activity.RESULT_OK && resultData != null) { mPos = -1 mPrevHashcode = 0 refreshViewPager() } } else if (requestCode == REQUEST_SET_AS) { if (resultCode == Activity.RESULT_OK) { toast(R.string.wallpaper_set_successfully) } } super.onActivityResult(requestCode, resultCode, resultData) } private fun checkDeleteConfirmation() { if (mSkipConfirmationDialog || config.skipDeleteConfirmation) { deleteConfirmed() } else { askConfirmDelete() } } private fun askConfirmDelete() { DeleteWithRememberDialog(this, getString(R.string.proceed_with_deletion)) { mSkipConfirmationDialog = it deleteConfirmed() } } private fun deleteConfirmed() { val path = getCurrentMedia()[mPos].path tryDeleteFileDirItem(FileDirItem(path, path.getFilenameFromPath())) { refreshViewPager() } } private fun isDirEmpty(media: ArrayList<Medium>): Boolean { return if (media.isEmpty()) { deleteDirectoryIfEmpty() finish() true } else { false } } private fun renameFile() { RenameItemDialog(this, getCurrentPath()) { getCurrentMedia()[mPos].path = it updateActionbarTitle() } } override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) measureScreen() } private fun measureScreen() { val metrics = DisplayMetrics() if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { windowManager.defaultDisplay.getRealMetrics(metrics) screenWidth = metrics.widthPixels screenHeight = metrics.heightPixels } else { windowManager.defaultDisplay.getMetrics(metrics) screenWidth = metrics.widthPixels screenHeight = metrics.heightPixels } } private fun refreshViewPager() { GetMediaAsynctask(applicationContext, mDirectory, false, false, mShowAll) { gotMedia(it) }.execute() } private fun gotMedia(media: ArrayList<Medium>) { if (isDirEmpty(media) || media.hashCode() == mPrevHashcode) { return } mPrevHashcode = media.hashCode() mMediaFiles = media mPos = if (mPos == -1) { getPositionInList(media) } else { Math.min(mPos, mMediaFiles.size - 1) } updateActionbarTitle() updatePagerItems(mMediaFiles.toMutableList()) invalidateOptionsMenu() checkOrientation() } private fun getPositionInList(items: MutableList<Medium>): Int { mPos = 0 for ((i, medium) in items.withIndex()) { if (medium.path == mPath) { return i } } return mPos } private fun deleteDirectoryIfEmpty() { val fileDirItem = FileDirItem(mDirectory, mDirectory.getFilenameFromPath(), getIsPathDirectory(mDirectory)) if (config.deleteEmptyFolders && !fileDirItem.isDownloadsFolder() && fileDirItem.isDirectory && fileDirItem.getProperFileCount(applicationContext, true) == 0) { tryDeleteFileDirItem(fileDirItem, true) } scanPath(mDirectory) } private fun checkOrientation() { if (!mIsOrientationLocked && config.screenRotation == ROTATE_BY_ASPECT_RATIO) { var flipSides = false try { val pathToLoad = getCurrentPath() val exif = android.media.ExifInterface(pathToLoad) val orientation = exif.getAttributeInt(android.media.ExifInterface.TAG_ORIENTATION, -1) flipSides = orientation == ExifInterface.ORIENTATION_ROTATE_90 || orientation == ExifInterface.ORIENTATION_ROTATE_270 } catch (e: Exception) { } val res = getCurrentPath().getResolution() ?: return val width = if (flipSides) res.y else res.x val height = if (flipSides) res.x else res.y if (width > height) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } else if (width < height) { requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } } } override fun fragmentClicked() { mIsFullScreen = !mIsFullScreen checkSystemUI() } override fun videoEnded(): Boolean { if (mIsSlideshowActive) { swipeToNextMedium() } return mIsSlideshowActive } override fun goToPrevItem() { view_pager.setCurrentItem(view_pager.currentItem - 1, false) checkOrientation() } override fun goToNextItem() { view_pager.setCurrentItem(view_pager.currentItem + 1, false) checkOrientation() } private fun checkSystemUI() { if (mIsFullScreen) { hideSystemUI() } else { stopSlideshow() showSystemUI() } } private fun updateActionbarTitle() { runOnUiThread { if (mPos < getCurrentMedia().size) { supportActionBar?.title = getCurrentMedia()[mPos].path.getFilenameFromPath() } } } private fun getCurrentMedium(): Medium? { return if (getCurrentMedia().isEmpty() || mPos == -1) { null } else { getCurrentMedia()[Math.min(mPos, getCurrentMedia().size - 1)] } } private fun getCurrentMedia() = if (mAreSlideShowMediaVisible) mSlideshowMedia else mMediaFiles private fun getCurrentPath() = getCurrentMedium()!!.path private fun getCurrentFile() = File(getCurrentPath()) override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { if (view_pager.offscreenPageLimit == 1) { view_pager.offscreenPageLimit = 2 } if (mPos != position) { mPos = position updateActionbarTitle() mRotationDegrees = 0 supportInvalidateOptionsMenu() scheduleSwipe() } } override fun onPageScrollStateChanged(state: Int) { if (state == ViewPager.SCROLL_STATE_IDLE && getCurrentMedium() != null) { checkOrientation() } } }
apache-2.0
9ff6c091f5d975d412dfa2ac49d03fc5
32.944745
168
0.583288
5.016974
false
false
false
false
SUPERCILEX/Robot-Scouter
library/shared-scouting/src/main/java/com/supercilex/robotscouter/shared/scouting/viewholder/StopwatchViewHolder.kt
1
15826
package com.supercilex.robotscouter.shared.scouting.viewholder import android.os.Build import android.view.ContextMenu import android.view.Gravity import android.view.LayoutInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.CallSuper import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.transition.AutoTransition import androidx.transition.TransitionManager import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat import com.github.rubensousa.gravitysnaphelper.GravitySnapHelper import com.google.android.material.snackbar.BaseTransientBottomBar import com.google.android.material.snackbar.Snackbar import com.google.firebase.firestore.DocumentReference import com.supercilex.robotscouter.common.second import com.supercilex.robotscouter.core.data.model.add import com.supercilex.robotscouter.core.data.model.remove import com.supercilex.robotscouter.core.model.Metric import com.supercilex.robotscouter.core.ui.RecyclerPoolHolder import com.supercilex.robotscouter.core.ui.longSnackbar import com.supercilex.robotscouter.core.ui.notifyItemsNoChangeAnimation import com.supercilex.robotscouter.core.ui.setOnLongClickListenerCompat import com.supercilex.robotscouter.core.unsafeLazy import com.supercilex.robotscouter.shared.scouting.MetricListFragment import com.supercilex.robotscouter.shared.scouting.MetricViewHolderBase import com.supercilex.robotscouter.shared.scouting.R import kotlinx.android.synthetic.main.scout_base_stopwatch.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.Job import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout import java.lang.ref.WeakReference import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit import com.supercilex.robotscouter.core.ui.R as RC open class StopwatchViewHolder( itemView: View, fragment: MetricListFragment ) : MetricViewHolderBase<Metric.Stopwatch, List<Long>>(itemView), View.OnClickListener, View.OnLongClickListener { private var timer: Timer? = null private var undoAddSnackbar: Snackbar? = null private val onToOffIcon by unsafeLazy { checkNotNull(AnimatedVectorDrawableCompat.create( itemView.context, R.drawable.ic_timer_on_to_off_24dp)) } private val offToOnIcon by unsafeLazy { checkNotNull(AnimatedVectorDrawableCompat.create( itemView.context, R.drawable.ic_timer_off_to_on_24dp)) } private val startStopwatchTitle by unsafeLazy { itemView.resources.getString(R.string.metric_stopwatch_start_title) } private val cyclesAdapter = Adapter() init { stopwatch.setOnClickListener(this) stopwatch.setOnLongClickListenerCompat(this) cycles.layoutManager = LinearLayoutManager( itemView.context, RecyclerView.HORIZONTAL, false ).apply { initialPrefetchItemCount = 6 } cycles.adapter = cyclesAdapter GravitySnapHelper(Gravity.START).attachToRecyclerView(cycles) cycles.setRecycledViewPool( (fragment.requireParentFragment() as RecyclerPoolHolder).recyclerPool) } override fun bind() { super.bind() cycles.setHasFixedSize(false) cyclesAdapter.notifyDataSetChanged() val timer = TIMERS[metric.ref] if (timer == null) { setStartTitle() updateStyle(false, false) } else { timer.holder = this updateStyle(true, false) timer.updateButtonTime() } this.timer = timer } override fun onClick(v: View) { val currentTimer = timer if (currentTimer == null) { undoAddSnackbar?.dismiss() timer = Timer(this) } else { val lap = currentTimer.stop() metric.add(metric.value.size, lap) metric.value.size.let { notifyCycleAdded(it, it) } itemView.longSnackbar(R.string.scout_stopwatch_lap_added_message, RC.string.undo) { val hadAverage = metric.value.size >= LIST_SIZE_WITH_AVERAGE metric.remove(lap) notifyCycleRemoved(metric.value.size, metric.value.size, hadAverage) timer = Timer(this, currentTimer.startTimeMillis) } } } override fun onLongClick(v: View): Boolean { val currentTimer = timer ?: return false currentTimer.stop() undoAddSnackbar = itemView.longSnackbar(RC.string.cancelled, RC.string.undo) { timer = Timer(this, currentTimer.startTimeMillis) }.addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() { override fun onDismissed(transientBottomBar: Snackbar, event: Int) { undoAddSnackbar = null } }) return true } private fun notifyCycleAdded(position: Int, size: Int) { // Force RV to request layout when adding first item cycles.setHasFixedSize(size >= LIST_SIZE_WITH_AVERAGE) if (size == LIST_SIZE_WITH_AVERAGE) { updateFirstCycleName() cyclesAdapter.notifyItemInserted(0) // Add the average card cyclesAdapter.notifyItemInserted(position) } else { // Account for the average card being there or not. Since we are adding a new lap, // there are only two possible states: 1 item or n + 2 items. cyclesAdapter.notifyItemInserted(if (size == 1) 0 else position) // Ensure the average card is updated if it's there cyclesAdapter.notifyItemChanged(0) updateCycleNames(position, size) if (size >= LIST_SIZE_WITH_AVERAGE) { cycles.post { cycles.smoothScrollToPosition(position) } } } } private fun notifyCycleRemoved(position: Int, size: Int, hadAverage: Boolean) { // Force RV to request layout when removing last item cycles.setHasFixedSize(size > 0) cyclesAdapter.notifyItemRemoved(if (hadAverage) position + 1 else position) if (hadAverage && size == 1) { cyclesAdapter.notifyItemRemoved(0) // Remove the average card updateFirstCycleName() } else if (size >= LIST_SIZE_WITH_AVERAGE) { cyclesAdapter.notifyItemChanged(0) // Ensure the average card is updated updateCycleNames(position, size) } } private fun updateFirstCycleName() = cycles.notifyItemsNoChangeAnimation { notifyItemChanged(0) } private fun updateCycleNames(position: Int, size: Int) { if (size >= LIST_SIZE_WITH_AVERAGE) { cycles.notifyItemsNoChangeAnimation { notifyItemRangeChanged(position + 1, size - position) } } } private fun setStartTitle() { stopwatch.text = startStopwatchTitle } private fun setStopTitle(formattedTime: String) { stopwatch.text = itemView.resources .getString(R.string.metric_stopwatch_stop_title, formattedTime) } private fun updateStyle(isRunning: Boolean, animate: Boolean = true) { // There's a bug pre-L where changing the view state doesn't update the vector drawable. // Because of that, calling View#setActivated(isRunning) doesn't update the background // color and we end up with unreadable text. if (Build.VERSION.SDK_INT < 21) return stopwatch.isActivated = isRunning if (animate) { val drawable = if (isRunning) onToOffIcon else offToOnIcon stopwatch.setCompoundDrawablesRelativeWithIntrinsicBounds(drawable, null, null, null) drawable.start() } else { stopwatch.setCompoundDrawablesRelativeWithIntrinsicBounds(if (isRunning) { R.drawable.ic_timer_off_24dp } else { R.drawable.ic_timer_on_24dp }, 0, 0, 0) } } private class Timer( holder: StopwatchViewHolder, val startTimeMillis: Long = System.currentTimeMillis() ) { private val updater: Job /** * The ID of the metric who originally started the request. We need to validate it since * ViewHolders may be recycled across different instances. */ private val metric = holder.metric private var _holder: WeakReference<StopwatchViewHolder> = WeakReference(holder) var holder: StopwatchViewHolder? get() = _holder.get()?.takeIf { it.metric.ref == metric.ref } set(holder) { _holder = WeakReference(checkNotNull(holder)) } /** @return the time since this class was instantiated in milliseconds */ private val elapsedTimeMillis: Long get() = System.currentTimeMillis() - startTimeMillis init { TIMERS[holder.metric.ref] = this updater = GlobalScope.launch(Dispatchers.Main) { try { withTimeout(TimeUnit.MINUTES.toMillis(GAME_TIME_MINS)) { while (isActive) { updateButtonTime() delay(1000) } } } catch (e: TimeoutCancellationException) { stop() } } updateStyle() updateButtonTime() } fun updateButtonTime() { holder?.setStopTitle(getFormattedTime(elapsedTimeMillis)) } /** @return the time since this class was instantiated and then cancelled */ fun stop(): Long { holder?.timer = null TIMERS.remove(metric.ref) updater.cancel() updateStyle() holder?.setStartTitle() return elapsedTimeMillis } private fun updateStyle() { val holder = holder ?: return TransitionManager.beginDelayedTransition(holder.itemView as ViewGroup, transition) holder.updateStyle(updater.isActive) } private companion object { const val GAME_TIME_MINS = 3L val transition = AutoTransition().apply { excludeTarget(RecyclerView::class.java, true) } } } private inner class Adapter : RecyclerView.Adapter<DataHolder>() { val hasAverageItems get() = metric.value.size > 1 override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): DataHolder = LayoutInflater.from(parent.context).inflate( R.layout.scout_stopwatch_cycle_item, parent, false ).apply { layoutParams = layoutParams.apply { width = ViewGroup.LayoutParams.WRAP_CONTENT } }.let { if (viewType == DATA_ITEM) CycleHolder(it) else AverageHolder(it) } override fun onBindViewHolder(holder: DataHolder, position: Int) { val cycles = metric.value when { holder is AverageHolder -> holder.bind(cycles) hasAverageItems -> { val realIndex = position - 1 holder.bind(this@StopwatchViewHolder, cycles[realIndex]) } else -> holder.bind(this@StopwatchViewHolder, cycles[position]) } } override fun getItemCount(): Int { val size = metric.value.size return if (hasAverageItems) size + 1 else size } override fun getItemViewType(position: Int): Int = if (hasAverageItems && position == 0) AVERAGE_ITEM else DATA_ITEM } private abstract class DataHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener { protected val title: TextView = itemView.findViewById(R.id.title) protected val value: TextView = itemView.findViewById(R.id.value) /** * The outclass's instance. Used indirectly since this ViewHolder may be recycled across * different instances. */ private lateinit var holder: StopwatchViewHolder private val hasAverage get() = holder.cyclesAdapter.hasAverageItems protected val realPosition get() = if (hasAverage) adapterPosition - 1 else adapterPosition @CallSuper open fun bind(holder: StopwatchViewHolder, nanoTime: Long) { this.holder = holder } override fun onCreateContextMenu( menu: ContextMenu, v: View, menuInfo: ContextMenu.ContextMenuInfo? ) { menu.add(R.string.delete).setOnMenuItemClickListener(this) } override fun onMenuItemClick(item: MenuItem): Boolean { val metric = holder.metric val hadAverage = hasAverage val position = realPosition val rawPosition = adapterPosition val newCycles = metric.value.toMutableList() if (position >= newCycles.size) return false val deletedCycle = newCycles.removeAt(position) metric.remove(deletedCycle) holder.notifyCycleRemoved(position, metric.value.size, hadAverage) itemView.longSnackbar(R.string.deleted, R.string.undo) { val latestMetric = holder.metric latestMetric.add(position, deletedCycle) holder.notifyCycleAdded(rawPosition, latestMetric.value.size) } return true } } private class CycleHolder(itemView: View) : DataHolder(itemView) { init { itemView.setOnCreateContextMenuListener(this) } override fun bind(holder: StopwatchViewHolder, nanoTime: Long) { super.bind(holder, nanoTime) title.text = itemView.context.getString( R.string.metric_stopwatch_cycle_title, realPosition + 1) value.text = getFormattedTime(nanoTime) } } private class AverageHolder(itemView: View) : DataHolder(itemView) { init { title.setText(R.string.metric_stopwatch_cycle_average_title) } fun bind(cycles: List<Long>) { value.text = getFormattedTime(cycles.sum() / cycles.size) } } private companion object { val TIMERS = ConcurrentHashMap<DocumentReference, Timer>() const val LIST_SIZE_WITH_AVERAGE = 2 // Don't conflict with metric types since the pool is shared const val DATA_ITEM = 1000 const val AVERAGE_ITEM = 1001 private const val COLON = ":" private const val LEADING_ZERO = "0" fun getFormattedTime(nanos: Long): String { val minutes = TimeUnit.MILLISECONDS.toMinutes(nanos) return (minutes.toString() + COLON + (TimeUnit.MILLISECONDS.toSeconds(nanos) - minutes * 60)).let { val split = it.split(COLON.toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() if (split.second().length > 1) { it } else { split.first() + COLON + LEADING_ZERO + split.second() } } } } }
gpl-3.0
5bb7293dea7e671a642df792b955dbd6
35.549654
97
0.629597
5.016165
false
false
false
false
NordicSemiconductor/Android-nRF-Toolbox
profile_gls/src/main/java/no/nordicsemi/android/gls/main/view/GLSContentView.kt
1
6988
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.gls.main.view import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Settings import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import no.nordicsemi.android.gls.R import no.nordicsemi.android.gls.data.GLSData import no.nordicsemi.android.gls.data.GLSRecord import no.nordicsemi.android.gls.data.RequestStatus import no.nordicsemi.android.gls.data.WorkingMode import no.nordicsemi.android.gls.main.viewmodel.GLSViewModel import no.nordicsemi.android.theme.ScreenSection import no.nordicsemi.android.ui.view.BatteryLevelView import no.nordicsemi.android.ui.view.SectionTitle @Composable internal fun GLSContentView(state: GLSData, onEvent: (GLSScreenViewEvent) -> Unit) { Column( modifier = Modifier .fillMaxSize() .padding(horizontal = 16.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Spacer(modifier = Modifier.height(16.dp)) SettingsView(state, onEvent) Spacer(modifier = Modifier.height(16.dp)) RecordsView(state) Spacer(modifier = Modifier.height(16.dp)) state.batteryLevel?.let { BatteryLevelView(it) Spacer(modifier = Modifier.height(16.dp)) } Button( onClick = { onEvent(DisconnectEvent) } ) { Text(text = stringResource(id = R.string.disconnect)) } Spacer(modifier = Modifier.height(16.dp)) } } @Composable private fun SettingsView(state: GLSData, onEvent: (GLSScreenViewEvent) -> Unit) { ScreenSection { SectionTitle(icon = Icons.Default.Settings, title = "Request items") Spacer(modifier = Modifier.height(16.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly ) { if (state.requestStatus == RequestStatus.PENDING) { CircularProgressIndicator() } else { WorkingMode.values().forEach { Button(onClick = { onEvent(OnWorkingModeSelected(it)) }) { Text(it.toDisplayString()) } } } } } } @Composable private fun RecordsView(state: GLSData) { ScreenSection { if (state.records.isEmpty()) { RecordsViewWithoutData() } else { RecordsViewWithData(state) } } } @Composable private fun RecordsViewWithData(state: GLSData) { Column(modifier = Modifier.fillMaxWidth()) { SectionTitle(resId = R.drawable.ic_records, title = "Records") Spacer(modifier = Modifier.height(16.dp)) state.records.forEachIndexed { i, it -> RecordItem(it) if (i < state.records.size - 1) { Spacer(modifier = Modifier.size(8.dp)) } } } } @Composable private fun RecordItem(record: GLSRecord) { val viewModel: GLSViewModel = hiltViewModel() Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clip(RoundedCornerShape(10.dp)) .clickable { viewModel.onEvent(OnGLSRecordClick(record)) } .padding(8.dp) ) { Column( modifier = Modifier .fillMaxWidth() .weight(1f) ) { record.time?.let { Text( text = stringResource(R.string.gls_timestamp, it), style = MaterialTheme.typography.titleMedium ) } Spacer(modifier = Modifier.size(4.dp)) Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.Bottom, modifier = Modifier.fillMaxWidth() ) { Text( text = record.type.toDisplayString(), style = MaterialTheme.typography.bodySmall ) Text( text = glucoseConcentrationDisplayValue( record.glucoseConcentration, record.unit ), style = MaterialTheme.typography.labelLarge, ) } } } } @Composable private fun RecordsViewWithoutData() { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally ) { SectionTitle(icon = Icons.Default.Search, title = "No items") Spacer(modifier = Modifier.height(16.dp)) Text( text = stringResource(id = R.string.gls_no_records_info), style = MaterialTheme.typography.bodyMedium ) } }
bsd-3-clause
ecbe764c517acf45338e72d890f0fdd3
32.27619
89
0.652833
4.705724
false
false
false
false
daemontus/glucose
app/src/main/java/com/github/daemontus/glucose/demo/presentation/ShowDetailPresenter.kt
2
3384
package com.github.daemontus.glucose.demo.presentation import android.os.Bundle import android.support.design.widget.TabLayout import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.view.View import android.view.ViewGroup import android.widget.TextView import com.github.daemontus.glucose.demo.R import com.github.daemontus.glucose.demo.data.Series import com.github.daemontus.glucose.demo.data.Show import com.github.daemontus.glucose.demo.domain.ShowRepository import com.glucose.app.Presenter import com.glucose.app.PresenterDelegate import com.glucose.app.PresenterGroup import com.glucose.app.PresenterHost import com.glucose.app.presenter.* import rx.android.schedulers.AndroidSchedulers class ShowDetailPresenter(context: PresenterHost, parent: ViewGroup?) : PresenterGroup(context, R.layout.presenter_show_detail, parent) { val showId: Long by NativeState(-1, longBundler) val repo = ShowRepository() val showTitle = findView<TextView>(R.id.show_title) val pager = findView<ViewPager>(R.id.show_list_pager) val tabs = findView<TabLayout>(R.id.show_list_tabs) init { tabs.setupWithViewPager(pager, true) } override fun onAttach(arguments: Bundle) { super.onAttach(arguments) repo.getShowById(showId).observeOn(AndroidSchedulers.mainThread()) .subscribe { show -> if (show == null) { //Normally, you would display some kind of error, right? ;) host.activity.onBackPressed() } else { showTitle.text = show.name loadSeries(show) } }.until(Lifecycle.Event.DETACH) } override fun onDetach() { pager.adapter = null showTitle.text = "" super.onDetach() } private fun loadSeries(show: Show) { repo.getSeriesByShow(show) .observeOn(AndroidSchedulers.mainThread()) .subscribe { series -> pager.adapter = null val adapter = SeriesAdapter(series, this) pager.adapter = adapter } } class SeriesAdapter( private val series: List<Series>, private val presenter: PresenterGroup ) : PagerAdapter() { private val presenters = arrayOfNulls<Presenter?>(series.size) override fun instantiateItem(container: ViewGroup, position: Int): Any { val child = presenter.attach(container, SeriesPresenter::class.java, (SeriesPresenter::seriesId.name with series[position].seriesId) and (Presenter::canReattachAfterStateChange.name with false) ) presenters[position]?.let { presenter.detach(it) } presenters[position] = child return child.view } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any?) { presenters[position]?.let { presenter.detach(it) } presenters[position] = null container.removeView(`object` as View) } override fun getPageTitle(position: Int): CharSequence = series[position].name override fun isViewFromObject(view: View?, `object`: Any?): Boolean = `object` == view override fun getCount(): Int = series.size } }
mit
ca21a34f20401836fb85bfeceb6feb9c
34.631579
137
0.651005
4.5
false
false
false
false
CaelumF/Cbot
src/com/gmail/caelum119/Cbot2/IRCCbot.kt
1
2823
package com.gmail.caelum119.Cbot2 import com.gmail.caelum119.Cbot2.message_structure.IRCContext import com.gmail.caelum119.Cbot2.message_structure.Identity import com.gmail.caelum119.Cbot2.message_structure.Message import com.gmail.caelum119.Cbot2.modules.Welcomer import org.jibble.pircbot.IrcException import org.jibble.pircbot.PircBot import java.util.* /** * First created 9/26/2016 in Cbot * For IRC bots. * each bot would be connected to several channels and servers */ open class IRCCBot(val serverName: String = "irc.freenode.org", val channelName: String = "##CoderdojoBots", val loginName: String = "Unnamed", val loiginPassword: String = "") : PircBot(), Runnable, CBot { override val onMessageOutCallbacks: ArrayList<(String) -> Unit> = ArrayList() override val onMessageCallbacks = ArrayList<(message: Message) -> Unit>() override val onJoinCallbacks = ArrayList<(channel: String, sender: String, login: String, hostname: String) -> Unit>() /** Server, channel **/ val connectedServers = HashMap<Pair<String, String>, IRCContext>() val botName = "Cbot" init { this.name = "xxxadeefg" } override fun run() { Welcomer Identity connect(serverName) joinChannel(channelName) } override fun sendMessage(message: String) { sendMessage(channelName, message) } override fun onMessage(channel: String?, sender: String?, login: String?, hostname: String?, message: String?) { super.onMessage(channel, sender, login, hostname, message) val context = connectedServers[Pair(server, channel)] if (context != null) { onMessageCallbacks.forEach { it.invoke(Message.createMessage(sender ?: "Null", message ?: "", context)) } } else { /**This must have been connected to a channel not using [connectToChannel] **/ } } override fun onJoin(channel: String, sender: String, login: String, hostname: String) { super.onJoin(channel, sender, login, hostname) onJoinCallbacks.forEach { it.invoke(channel, sender, login, hostname) } } fun connectToChannel(server: String, channel: String, serverPort: Int = 6667, password: String?) { try { if (password == null) connect(server, port) if (password != null) connect(server, port, password) } catch (e: IrcException) { throw e } val newContext = IRCContext(server, channel, this) connectedServers.put(Pair(server, channel), newContext) } /** * TODO: Fix this hack */ companion object globalIRCBot : IRCCBot() { /** * So that future implementations will */ } }
mit
32752e010ceecdc34439460fa00fc68f
33.864198
122
0.638328
4.163717
false
false
false
false
jpmoreto/play-with-robots
android/app/src/main/java/jpm/android/positionandmapping/ahrs/FusionAhrs.kt
1
6624
package jpm.android.positionandmapping.ahrs /* based on: https://github.com/xioTechnologies/Fusion/blob/master/Fusion/FusionAhrs.c http://x-io.co.uk/open-source-imu-and-ahrs-algorithms/ https://hal-univ-tlse3.archives-ouvertes.fr/hal-00488376/document */ class FusionAhrs(val gain: Float, minMagneticField: Float,maxMagneticField: Float) { fun update(gyroscope: FloatArray, accelerometer: FloatArray, magnetometer: FloatArray, samplePeriod: Float) { // Calculate feedback error var halfFeedbackError = vector3Zero // scaled by 0.5 to avoid repeated multiplications by 2 // Abandon feedback calculation if accelerometer measurement invalid if ( accelerometer[vX] != 0.0f || accelerometer[vY] != 0.0f || accelerometer[vZ] != 0.0f) { // Calculate direction of gravity assumed by quaternion val halfGravity = floatArrayOf( quaternion[qX] * quaternion[qZ] - quaternion[qW] * quaternion[qY], quaternion[qW] * quaternion[qX] + quaternion[qY] * quaternion[qZ], quaternion[qW] * quaternion[qW] - 0.5f + quaternion[qZ] * quaternion[qZ]) // equal to 3rd column of rotation matrix representation scaled by 0.5 // Calculate accelerometer feedback error halfFeedbackError = vector3CrossProduct(vectorNormalise(accelerometer), halfGravity) // Abandon magnetometer feedback calculation if magnetometer measurement invalid val magnetometerNorm = magnetometer.fold(0.0f) { acc, e -> acc + e * e } if (magnetometerNorm in minMagneticFieldSquared..maxMagneticFieldSquared) { // Compute direction of 'magnetic west' assumed by quaternion val halfEast = floatArrayOf( quaternion[qX] * quaternion[qY] + quaternion[qW] * quaternion[qZ], quaternion[qW] * quaternion[qW] - 0.5f + quaternion[qY] * quaternion[qY], quaternion[qY] * quaternion[qZ] - quaternion[qW] * quaternion[qX]) // equal to 2nd column of rotation matrix representation scaled by 0.5 // Calculate magnetometer feedback error halfFeedbackError = vectorAdd(halfFeedbackError, vector3CrossProduct(vectorNormalise(vector3CrossProduct(accelerometer, magnetometer)), halfEast)) } } // Ramp down gain until initialisation complete if (gain == 0f) { rampedGain = 0f // skip initialisation if gain is zero } val feedbackGain = if (rampedGain > gain) { rampedGain -= (INITIAL_GAIN - gain) * samplePeriod / Companion.INITIALISATION_PERIOD rampedGain } else { gain } // Convert gyroscope to radians per second scaled by 0.5 var halfGyroscope = vectorMult(gyroscope, 0.5f * degreesToRadians(1f)) // Apply feedback to gyroscope halfGyroscope = vectorAdd(halfGyroscope, vectorMult(halfFeedbackError, feedbackGain)) // Integrate rate of change of quaternion quaternion = vectorAdd(quaternion, quaternionMultVector3(quaternion, vectorMult(halfGyroscope, samplePeriod))) // Normalise quaternion quaternion = vectorNormalise(quaternion) // Calculate linear acceleration val gravity = floatArrayOf( 2.0f * (quaternion[qX] * quaternion[qZ] - quaternion[qW] * quaternion[qY]), 2.0f * (quaternion[qW] * quaternion[qX] + quaternion[qY] * quaternion[qZ]), 2.0f * (quaternion[qW] * quaternion[qW] - 0.5f + quaternion[qZ] * quaternion[qZ])) // equal to 3rd column of rotation matrix representation linearAcceleration = vectorSub(accelerometer, gravity) } fun calculateEarthAcceleration(): FloatArray { val qwqw = quaternion[qW] * quaternion[qW] // calculate common terms to avoid repeated operations val qwqx = quaternion[qW] * quaternion[qX] val qwqy = quaternion[qW] * quaternion[qY] val qwqz = quaternion[qW] * quaternion[qZ] val qxqy = quaternion[qX] * quaternion[qY] val qxqz = quaternion[qX] * quaternion[qZ] val qyqz = quaternion[qY] * quaternion[qZ] // transpose of a rotation matrix representation of the quaternion multiplied with the linear acceleration return floatArrayOf( 2.0f * ((qwqw - 0.5f + quaternion[qX] * quaternion[qX]) * linearAcceleration[vX] + (qxqy - qwqz) * linearAcceleration[vY] + (qxqz + qwqy) * linearAcceleration[vZ]), 2.0f * ((qxqy + qwqz) * linearAcceleration[vX] + (qwqw - 0.5f + quaternion[qY] * quaternion[qY]) * linearAcceleration[vY] + (qyqz - qwqx) * linearAcceleration[vZ]), 2.0f * ((qxqz - qwqy) * linearAcceleration[vX] + (qyqz + qwqx) * linearAcceleration[vY] + (qwqw - 0.5f + quaternion[qZ] * quaternion[qZ]) * linearAcceleration[vZ]) ) } fun isInitialising(): Boolean = rampedGain > gain fun reinitialise() { quaternion = quaternionIdentity linearAcceleration = vector3Zero rampedGain = INITIAL_GAIN } fun getQuaternion(): FloatArray = quaternion fun getLinearAcceleration(): FloatArray = linearAcceleration // http://www.novatel.com/solutions/attitude/ // http://www.skylinesoft.com/SkylineGlobe/TerraExplorer/v6.5.0/APIReferenceGuide/Yaw_Pitch_and_Roll_Angles.htm // http://planning.cs.uiuc.edu/node102.html // // fun getRoll(): Double { return Math.atan2( quaternion[0] * quaternion[1].toDouble() + quaternion[2] * quaternion[3].toDouble(), 0.5 - quaternion[1] * quaternion[1].toDouble() - quaternion[2] * quaternion[2].toDouble()) } fun getPitch(): Double { return Math.asin(-2.0 * (quaternion[1] * quaternion[3].toDouble() - quaternion[0] * quaternion[2].toDouble())) } fun getYaw(): Double { return Math.atan2( quaternion[1] * quaternion[2].toDouble() + quaternion[0] * quaternion[3].toDouble(), 0.5 - quaternion[2] * quaternion[2].toDouble() - quaternion[3] * quaternion[3].toDouble()) } private val minMagneticFieldSquared = minMagneticField * minMagneticField private val maxMagneticFieldSquared = maxMagneticField * maxMagneticField private var quaternion = quaternionIdentity private var linearAcceleration = vector3Zero private var rampedGain = INITIAL_GAIN companion object { private val INITIALISATION_PERIOD = 3.0f private val INITIAL_GAIN = 10.0f } }
mit
dd13d86cf964229d4dd35f19788c0187
46.661871
174
0.64689
4.026748
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/physics/PhysicsWorld.kt
1
2855
package com.binarymonks.jj.core.physics import com.badlogic.gdx.physics.box2d.Joint import com.badlogic.gdx.physics.box2d.JointDef import com.badlogic.gdx.physics.box2d.World import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.api.PhysicsAPI import com.binarymonks.jj.core.async.Bond import com.binarymonks.jj.core.async.OneTimeTask import com.binarymonks.jj.core.pools.Poolable import com.binarymonks.jj.core.pools.new import com.binarymonks.jj.core.pools.recycle open class PhysicsWorld( val b2dworld: World = World(JJ.B.config.b2d.gravity, true) ) : PhysicsAPI { var velocityIterations = 20 var positionIterations = 20 var stepping = false var stepReleased = false override var collisionGroups = CollisionGroups() override var materials = Materials() var isUpdating = false internal set init { b2dworld.setContactListener(JJContactListener()) } fun update() { isUpdating = true val frameDelta = JJ.clock.deltaFloat if (frameDelta > 0) { b2dworld.step(frameDelta, velocityIterations, positionIterations) } isUpdating = false } /** * Lets you create joints during the physics step */ fun createJoint(jointDef: JointDef): Bond<Joint> { @Suppress("UNCHECKED_CAST") val bond = new(Bond::class) as Bond<Joint> val delayedJoint = new(DelayedCreateJoint::class).set(jointDef, bond) if (isUpdating) { JJ.tasks.addPostPhysicsTask(delayedJoint) } else { JJ.tasks.addPrePhysicsTask(delayedJoint) } return bond } /** * Lets you destroy a joint during the physics step */ fun destroyJoint(joint: Joint) { if (isUpdating) { JJ.tasks.addPostPhysicsTask(new(DelayedDestroyJoint::class).set(joint)) } else { JJ.B.physicsWorld.b2dworld.destroyJoint(joint) } } } internal class DelayedCreateJoint : OneTimeTask(), Poolable { var jointDef: JointDef? = null var bond: Bond<Joint>? = null fun set(jointDef: JointDef, bond: Bond<Joint>): DelayedCreateJoint { this.jointDef = jointDef this.bond = bond return this } override fun doOnce() { val joint = JJ.B.physicsWorld.b2dworld.createJoint(jointDef) bond!!.succeed(joint) recycle(this) } override fun reset() { jointDef = null bond = null } } internal class DelayedDestroyJoint : OneTimeTask(), Poolable { var joint: Joint? = null fun set(joint: Joint): DelayedDestroyJoint { this.joint = joint return this } override fun doOnce() { JJ.B.physicsWorld.b2dworld.destroyJoint(joint) recycle(this) } override fun reset() { joint = null } }
apache-2.0
ab9b2248b76b844a315f08369f500228
24.720721
83
0.647285
3.873813
false
false
false
false
carlphilipp/stock-tracker-android
src/fr/cph/stock/android/activity/MainActivity.kt
1
5736
/** * Copyright 2017 Carl-Philipp Harmant * * * 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 fr.cph.stock.android.activity import android.app.ActionBar import android.app.ActionBar.LayoutParams import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.ListView import android.widget.RelativeLayout import android.widget.TextView import fr.cph.stock.android.Constants import fr.cph.stock.android.R import fr.cph.stock.android.StockTrackerApp import fr.cph.stock.android.adapter.MainListAdapter import fr.cph.stock.android.domain.Portfolio import fr.cph.stock.android.domain.UrlType import fr.cph.stock.android.listener.ErrorMainOnClickListener import fr.cph.stock.android.task.MainTask import org.json.JSONObject class MainActivity : Activity(), StockTrackerActivity { private lateinit var menuItem: MenuItem private lateinit var ada: MainListAdapter private lateinit var portfolio: Portfolio private lateinit var errorView: TextView private lateinit var listView: ListView override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) setContentView(R.layout.main) portfolio = if (bundle != null) bundle.getParcelable(Constants.PORTFOLIO) else intent.getParcelableExtra(Constants.PORTFOLIO) ada = MainListAdapter(this, portfolio) listView = findViewById(R.id.mainList) listView.adapter = ada listView.setOnItemClickListener { _, _, position, _ -> when (position) { 0 -> { val intent = Intent(baseContext, AccountActivity::class.java) intent.putExtra(Constants.PORTFOLIO, portfolio) startActivityForResult(intent, MainActivity.ACCOUNT_REQUEST) overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } 1 -> { val intent = Intent(baseContext, EquityActivity::class.java) intent.putExtra(Constants.PORTFOLIO, portfolio) startActivityForResult(intent, MainActivity.EQUITY_REQUEST) overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } 2 -> { val intent = Intent(baseContext, OverallActivity::class.java) intent.putExtra(Constants.PORTFOLIO, portfolio) startActivityForResult(intent, MainActivity.OVERALL_REQUEST) overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) } } } actionBar.displayOptions = ActionBar.DISPLAY_SHOW_HOME or ActionBar.DISPLAY_SHOW_TITLE or ActionBar.DISPLAY_SHOW_CUSTOM errorView = findViewById(R.id.errorMessage) errorView.setOnClickListener(ErrorMainOnClickListener(listView, errorView)) } override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) { overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) when (resultCode) { 100 -> finish() Activity.RESULT_OK -> { portfolio = intent!!.getParcelableExtra(Constants.PORTFOLIO) ada.update(portfolio) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_logout -> consume { MainTask(this, UrlType.LOGOUT, emptyMap()).execute() } R.id.refresh -> consume { menuItem = item menuItem.setActionView(R.layout.progressbar) menuItem.expandActionView() MainTask(this, UrlType.RELOAD, emptyMap()).execute() } else -> super.onOptionsItemSelected(item) } override fun update(portfolio: Portfolio) { this.portfolio = portfolio menuItem.collapseActionView() menuItem.actionView = null ada.update(this.portfolio) val app = application as StockTrackerApp app.toast() } override fun displayError(json: JSONObject) { val sessionError = (application as StockTrackerApp).isSessionError(json) if (sessionError) { (application as StockTrackerApp).loadErrorActivity(this, json) } else { val params = RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) params.addRule(RelativeLayout.BELOW, errorView.id) listView.layoutParams = params errorView.text = json.optString("error") menuItem.collapseActionView() menuItem.actionView = null } } override fun logOut() { (application as StockTrackerApp).logOut(this) } companion object { val ACCOUNT_REQUEST = 1 val EQUITY_REQUEST = 2 val OVERALL_REQUEST = 3 val CHART_REQUEST = 4 } }
apache-2.0
bcc5475abb7203e46ed02cefc23c3fa9
36.736842
127
0.66196
4.674817
false
false
false
false
tipsy/javalin
javalin/src/main/java/io/javalin/jetty/JettyUtil.kt
1
3850
package io.javalin.jetty import io.javalin.core.LoomUtil import io.javalin.core.LoomUtil.loomAvailable import io.javalin.core.LoomUtil.useLoomThreadPool import io.javalin.core.util.JavalinLogger import org.eclipse.jetty.server.LowResourceMonitor import org.eclipse.jetty.server.Server import org.eclipse.jetty.server.handler.StatisticsHandler import org.eclipse.jetty.util.thread.QueuedThreadPool import org.eclipse.jetty.util.thread.ThreadPool import java.io.IOException import java.util.concurrent.TimeoutException private var defaultLogger: org.eclipse.jetty.util.log.Logger? = null object JettyUtil { @JvmStatic fun getOrDefault(server: Server?) = server ?: Server(defaultThreadPool()).apply { addBean(LowResourceMonitor(this)) insertHandler(StatisticsHandler()) setAttribute("is-default-server", true) } private fun defaultThreadPool() = if (useLoomThreadPool && loomAvailable) { JavalinLogger.info("Loom is available, using Virtual ThreadPool... Neat!") LoomThreadPool() } else { QueuedThreadPool(250, 8, 60_000).apply { name = "JettyServerThreadPool" } } @JvmField var logDuringStartup = false @JvmStatic fun disableJettyLogger() { if (logDuringStartup) return defaultLogger = defaultLogger ?: org.eclipse.jetty.util.log.Log.getLog() org.eclipse.jetty.util.log.Log.setLog(NoopLogger()) } fun reEnableJettyLogger() { if (logDuringStartup) return org.eclipse.jetty.util.log.Log.setLog(defaultLogger) } var logIfNotStarted = true @JvmStatic fun maybeLogIfServerNotStarted(jettyServer: JettyServer) = Thread { Thread.sleep(5000) if (logIfNotStarted && !jettyServer.started) { JavalinLogger.info("It looks like you created a Javalin instance, but you never started it.") JavalinLogger.info("Try: Javalin app = Javalin.create().start();") JavalinLogger.info("For more help, visit https://javalin.io/documentation#server-setup") JavalinLogger.info("To disable this message, do `JettyUtil.logIfNotStarted = false`") } }.start() // jetty throws if client aborts during response writing. testing name avoids hard dependency on jetty. fun isClientAbortException(t: Throwable) = t::class.java.name == "org.eclipse.jetty.io.EofException" // Jetty may timeout connections to avoid having broken connections that remain open forever // This is rare, but intended (see issues #163 and #1277) fun isJettyTimeoutException(t: Throwable) = t is IOException && t.cause is TimeoutException class NoopLogger : org.eclipse.jetty.util.log.Logger { override fun getName() = "noop" override fun getLogger(name: String) = this override fun setDebugEnabled(enabled: Boolean) {} override fun isDebugEnabled() = false override fun ignore(ignored: Throwable) {} override fun warn(msg: String, vararg args: Any) {} override fun warn(thrown: Throwable) {} override fun warn(msg: String, thrown: Throwable) {} override fun info(msg: String, vararg args: Any) {} override fun info(thrown: Throwable) {} override fun info(msg: String, thrown: Throwable) {} override fun debug(msg: String, vararg args: Any) {} override fun debug(s: String, l: Long) {} override fun debug(thrown: Throwable) {} override fun debug(msg: String, thrown: Throwable) {} } } class LoomThreadPool : ThreadPool { private val executorService = LoomUtil.getExecutorService() override fun execute(command: Runnable) { executorService.submit(command) } override fun join() {} override fun getThreads() = 1 override fun getIdleThreads() = 1 override fun isLowOnThreads() = false }
apache-2.0
c9a209bd3a6a23c423556e33046f6935
37.5
107
0.697143
4.25885
false
false
false
false
fan123199/V2ex-simple
app/src/main/java/im/fdx/v2ex/utils/EndlessOnScrollListener.kt
1
1686
package im.fdx.v2ex.utils import androidx.recyclerview.widget.RecyclerView import com.elvishew.xlog.XLog import im.fdx.v2ex.utils.extensions.logd abstract class EndlessOnScrollListener(val rvReply: RecyclerView) : RecyclerView.OnScrollListener() { private val mLinearLayoutManager = rvReply.layoutManager as androidx.recyclerview.widget.LinearLayoutManager private val visibleThreshold = 2 private var pageToLoad = 1 var loading = false var totalPage = 0 private var pageAfterLoaded = pageToLoad override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { XLog.d("onScrolled + $dy") if (dy < 0) { return } val visibleItemCount = recyclerView.childCount val totalItemCount = mLinearLayoutManager.itemCount val firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition() val lastVisibleItem = mLinearLayoutManager.findLastCompletelyVisibleItemPosition() synchronized(this) { logd("$totalItemCount , $lastVisibleItem , $pageToLoad") if (lastVisibleItem == totalItemCount - 1) { rvReply.stopScroll() if (pageAfterLoaded == totalPage) { onCompleted() } } if (pageToLoad < totalPage && !loading && totalItemCount - visibleItemCount <= firstVisibleItem + visibleThreshold) { // End has been reached, Do something pageToLoad++ onLoadMore(pageToLoad) loading = true } } } fun restart() { pageToLoad = 1 } fun isRestart() :Boolean { return pageToLoad == 1 } fun success() { pageAfterLoaded = pageToLoad } abstract fun onLoadMore(currentPage: Int) abstract fun onCompleted() }
apache-2.0
a2cb2e45de7c8be28ef103ab22f4ab74
25.359375
123
0.701661
4.830946
false
false
false
false
sealedtx/coursework-db-kotlin
app/src/main/java/coursework/kiulian/com/freerealestate/Utils.kt
1
1996
@file:JvmName("Utils") package coursework.kiulian.com.freerealestate import android.Manifest import android.app.Activity import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.provider.MediaStore import android.support.v4.app.ActivityCompat import android.widget.Toast import coursework.kiulian.com.freerealestate.view.dialogs.ImagePickDialog import java.io.IOException import java.text.SimpleDateFormat import java.util.* import kotlin.collections.ArrayList /** * Created by User on 30.03.2017. */ fun Activity.requestPermission(requestCode: Int, permissions: Array<String>): Boolean { val permToRequest = ArrayList<String>() for (perm in permissions) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) permToRequest.add(perm) if (permToRequest.isNotEmpty()) { ActivityCompat.requestPermissions(this, permToRequest.toTypedArray(), requestCode) return false } return true } fun Context.getBitmapFromIntent(requestCode: Int, data: Intent): Bitmap? { var bitmap: Bitmap? = null if (requestCode == ImagePickDialog.TAKE_PHOTO) { try { bitmap = data.extras.get("data") as Bitmap } catch (e: IOException) { e.printStackTrace() Toast.makeText(this, "Something went wrong. Try again", Toast.LENGTH_SHORT).show() } } else if (requestCode == ImagePickDialog.PICK_IMAGE) { try { val uri = data.data bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri) } catch (e: IOException) { e.printStackTrace() Toast.makeText(this, "Something went wrong. Try again", Toast.LENGTH_SHORT).show() } } return bitmap } fun Date.createdAt(): String { val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") return format.format(this) }
bsd-2-clause
4ad23f4eaefd0a4084384e97966499d1
30.68254
118
0.702405
4.33913
false
false
false
false
songzhw/Hello-kotlin
Advanced_hm/src/main/kotlin/ca/six/kjdemo/io/ScannerDemo.kt
1
470
package ca.six.kjdemo.io import java.util.* fun main() { val str = "Hello world, this is word;apple;"; val scanner = Scanner(str); println("01: ${scanner.findWithinHorizon("w.*d", 5)}") //=> null println("02: ${scanner.findWithinHorizon("w.*d", 15)}") //=> world println("03: ${scanner.findWithinHorizon("w.*d", 25)}") //=> word println("04: ${scanner.nextLine()}") //=> ;apple; (这一点不太明白, 为什么nextLine()是最后一部分) }
apache-2.0
0d6024a7d62813c08ad284f4f1b9358b
35.583333
85
0.611872
3.062937
false
false
false
false
kantega/niagara
niagara-data/src/main/kotlin/org/kantega/niagara/data/Product.kt
1
2184
package org.kantega.niagara.data interface Product1<A>{ fun component1():A fun hList() = hList(component1()) } interface Product2<A,B>{ fun component1():A fun component2():B fun hList() = hList(component1(),component2()) } interface Product3<A,B,C>{ fun component1():A fun component2():B fun component3():C fun hList() = hList(component1(),component2(),component3()) } interface Product4<A,B,C,D>{ fun component1():A fun component2():B fun component3():C fun component4():D fun hList() = hList(component1(),component2(),component3(),component4()) } interface Product5<A,B,C,D,E>{ fun component1():A fun component2():B fun component3():C fun component4():D fun component5():E fun hList() = hList(component1(),component2(),component3(),component4(),component5()) } interface Product6<A,B,C,D,E,F>{ fun component1():A fun component2():B fun component3():C fun component4():D fun component5():E fun component6():F fun hList() = hList(component1(),component2(),component3(),component4(),component5(),component6()) } interface Product7<A,B,C,D,E,F,G>{ fun component1():A fun component2():B fun component3():C fun component4():D fun component5():E fun component6():F fun component7():G fun hList() = hList(component1(),component2(),component3(),component4(),component5(),component6(),component7()) } interface Product8<A,B,C,D,E,F,G,H>{ fun component1():A fun component2():B fun component3():C fun component4():D fun component5():E fun component6():F fun component7():G fun component8():H fun hList() = hList(component1(),component2(),component3(),component4(),component5(),component6(),component7(),component8()) } interface Product9<A,B,C,D,E,F,G,H,I>{ fun component1():A fun component2():B fun component3():C fun component4():D fun component5():E fun component6():F fun component7():G fun component8():H fun component9():I fun hList() = hList(component1(),component2(),component3(),component4(),component5(),component6(),component7(),component8(),component9()) }
apache-2.0
43ecfe972d904c75689ebd5a0e786efd
25.325301
141
0.651557
3.329268
false
false
false
false
android/android-studio-poet
aspoet/src/test/kotlin/com/google/androidstudiopoet/models/AndroidModuleBlueprintTest.kt
1
7680
package com.google.androidstudiopoet.models import com.google.androidstudiopoet.input.* import com.google.androidstudiopoet.testutils.* import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.whenever import org.junit.Test class AndroidModuleBlueprintTest { private val resourcesConfig0: ResourcesConfig = mock() @Test fun `blueprint create proper activity names`() { val blueprint = getAndroidModuleBlueprint(numOfActivities = 2) blueprint.activityNames.assertEquals(listOf("Activity0", "Activity1")) } @Test fun `blueprint creates activity blueprint with java class when java code exists`() { whenever(resourcesConfig0.layoutCount).thenReturn(1) val androidModuleBlueprint = getAndroidModuleBlueprint() assertThat(androidModuleBlueprint.activityBlueprints).isEqualTo(listOf(ActivityBlueprint( "Activity0", false, false, androidModuleBlueprint.resourcesBlueprint!!.layoutBlueprints[0], androidModuleBlueprint.packagePath, androidModuleBlueprint.packageName, androidModuleBlueprint.packagesBlueprint.javaPackageBlueprints[0].classBlueprints[0], listOf(), false))) } @Test fun `blueprint creates activity blueprint with koltin class when java code doesn't exist`() { whenever(resourcesConfig0.layoutCount).thenReturn(1) val androidModuleBlueprint = getAndroidModuleBlueprint( javaConfig = CodeConfig().apply { packages = 0 classesPerPackage = 0 methodsPerClass = 0 } ) assertOn(androidModuleBlueprint) { activityBlueprints[0].classToReferFromActivity.assertEquals( androidModuleBlueprint.packagesBlueprint.kotlinPackageBlueprints[0].classBlueprints[0]) } } @Test fun `enableDataBinding is false when data binding config is null`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = null) androidModuleBlueprint.enableDataBinding.assertFalse() } @Test fun `enableDataBinding is false when data binding config has zero listener count`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = DataBindingConfig(listenerCount = 0)) androidModuleBlueprint.enableDataBinding.assertFalse() } @Test fun `enableDataBinding is true when data binding config has positive listener count`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = DataBindingConfig(listenerCount = 2)) androidModuleBlueprint.enableDataBinding.assertTrue() } @Test fun `enableDataBinding is false when data binding config has negative listener count`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = DataBindingConfig(listenerCount = -1)) androidModuleBlueprint.enableDataBinding.assertFalse() } @Test fun `enableKapt is true when data binding config specifies to be true`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = DataBindingConfig(listenerCount = 1, kapt = true)) androidModuleBlueprint.enableDataBinding.assertTrue() androidModuleBlueprint.enableKapt.assertTrue() } @Test fun `enableKapt is false when data binding config does not specify`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = DataBindingConfig(listenerCount = 1)) androidModuleBlueprint.enableDataBinding.assertTrue() androidModuleBlueprint.enableKapt.assertFalse() } @Test fun `enableKapt is false when data binding config is null`() { val androidModuleBlueprint = getAndroidModuleBlueprint(dataBindingConfig = null) androidModuleBlueprint.enableDataBinding.assertFalse() androidModuleBlueprint.enableKapt.assertFalse() } @Test fun `enableCompose is false when compose config is null`() { val androidModuleBlueprint = getAndroidModuleBlueprint(composeConfig = null) androidModuleBlueprint.enableCompose.assertFalse() } @Test fun `enableCompose is false when compose config has zero action count`() { val androidModuleBlueprint = getAndroidModuleBlueprint(composeConfig = ComposeConfig(actionCount = 0)) androidModuleBlueprint.enableCompose.assertFalse() } @Test fun `enableCompose is true when compose config has positive action count`() { val androidModuleBlueprint = getAndroidModuleBlueprint(composeConfig = ComposeConfig(actionCount = 2)) androidModuleBlueprint.enableCompose.assertTrue() } @Test fun `enableCompose is false when compose config has negative action count`() { val androidModuleBlueprint = getAndroidModuleBlueprint(composeConfig = ComposeConfig(actionCount = -1)) androidModuleBlueprint.enableCompose.assertFalse() } @Test fun `empty resource config generates null resources blueprint`() { val androidModuleBlueprint = getAndroidModuleBlueprint(resourcesConfig = ResourcesConfig(0, 0, 0)) androidModuleBlueprint.resourcesBlueprint.assertNull() } @Test(expected = IllegalArgumentException::class) fun `cannot have both compose config and data binding config`() { getAndroidModuleBlueprint( composeConfig = ComposeConfig(), dataBindingConfig = DataBindingConfig() ) } @Test(expected = IllegalArgumentException::class) fun `cannot have both compose config and view binding`() { getAndroidModuleBlueprint( composeConfig = ComposeConfig(), viewBinding = true ) } @Test(expected = IllegalArgumentException::class) fun `cannot have both data binding and view binding`() { getAndroidModuleBlueprint( dataBindingConfig = DataBindingConfig(), viewBinding = true ) } private fun getAndroidModuleBlueprint( name: String = "androidAppModule1", numOfActivities: Int = 1, resourcesConfig: ResourcesConfig = resourcesConfig0, projectRoot: String = "root", hasLaunchActivity: Boolean = true, useKotlin: Boolean = false, dependencies: Set<Dependency> = setOf(), productFlavorConfigs: List<FlavorConfig>? = null, buildTypeConfigs: List<BuildTypeConfig>? = null, javaConfig: CodeConfig? = defaultCodeConfig(), kotlinConfig: CodeConfig? = defaultCodeConfig(), extraLines: List<String>? = null, generateTests: Boolean = true, dataBindingConfig: DataBindingConfig? = null, composeConfig: ComposeConfig? = null, viewBinding: Boolean = false, androidBuildConfig: AndroidBuildConfig = AndroidBuildConfig(), pluginConfigs: List<PluginConfig>? = null, generateBazelFiles: Boolean? = false ) = AndroidModuleBlueprint(name, numOfActivities, resourcesConfig, projectRoot, hasLaunchActivity, useKotlin, dependencies, productFlavorConfigs, buildTypeConfigs, javaConfig, kotlinConfig, extraLines, generateTests, dataBindingConfig, composeConfig, viewBinding, androidBuildConfig, pluginConfigs, generateBazelFiles) private fun defaultCodeConfig() = CodeConfig().apply { packages = 1 classesPerPackage = 1 methodsPerClass = 1 } }
apache-2.0
77c058d56508ad874df93352792bd857
38.592784
140
0.693359
5.416079
false
true
false
false
didi/DoraemonKit
Android/dokit-no-op/src/main/java/com/didichuxing/doraemonkit/kit/core/AbsDokitView.kt
1
5140
package com.didichuxing.doraemonkit.kit.core import android.app.Activity import android.content.Context import android.content.res.Resources import android.os.Bundle import android.view.* import android.widget.FrameLayout import androidx.annotation.IdRes import androidx.annotation.StringRes /** * ================================================ * 作 者:jint(金台) * 版 本:1.0 * 创建日期:2019-09-20-16:22 * 描 述:dokit 页面浮标抽象类 一般的悬浮窗都需要继承该抽象接口 * 修订历史: * ================================================ */ abstract class AbsDokitView : DokitView, TouchProxy.OnTouchEventListener, DokitViewManager.DokitViewAttachedListener { val TAG = "" /** * 页面启动模式 */ var mode: DoKitViewLaunchMode = DoKitViewLaunchMode.SINGLE_INSTANCE val isNormalMode = false @JvmField protected var mWindowManager = null /** * 创建FrameLayout#LayoutParams 内置悬浮窗调用 */ var normalLayoutParams: FrameLayout.LayoutParams? = null /** * 创建FrameLayout#LayoutParams 系统悬浮窗调用 */ var systemLayoutParams: WindowManager.LayoutParams? = null /** * 当前dokitViewName 用来当做map的key 和dokitViewIntent的tag一致 */ var tag = "" var bundle: Bundle? = null /** * weakActivity attach activity */ val activity: Activity? get() = null fun setActivity(activity: Activity) { } val doKitView: View? get() = null /** * 只控件在布局边界发生大小变化被裁剪的原因: * https://juejin.cn/post/6844903624452079623 * */ val parentView: DokitFrameLayout? get() = null override fun onDestroy() { } /** * 默认实现为true * * @return */ override fun canDrag(): Boolean { return true } /** * 搭配shouldDealBackKey使用 自定义处理完以后需要返回true * 默认模式的onBackPressed 拦截在NormalDokitViewManager#getDokitRootContentView中被处理 * 系统模式下的onBackPressed 在当前类的performCreate 初始话DoKitView时被处理 * 返回false 表示交由系统处理 * 返回 true 表示当前的返回事件已由自己处理 并拦截了改返回事件 */ override fun onBackPressed(): Boolean { return false } /** * 默认不自己处理返回按键 * * @return */ override fun shouldDealBackKey(): Boolean { return false } override fun onEnterBackground() { } override fun onEnterForeground() { } override fun onMove(x: Int, y: Int, dx: Int, dy: Int) { } /** * 手指弹起时保存当前浮标位置 * * @param x * @param y */ override fun onUp(x: Int, y: Int) { } /** * 手指按下时的操作 * * @param x * @param y */ override fun onDown(x: Int, y: Int) { } /** * home键被点击 只有系统悬浮窗控件才会被调用 */ open fun onHomeKeyPress() {} /** * 菜单键被点击 只有系统悬浮窗控件才会被调用 */ open fun onRecentAppKeyPress() {} /** * 不能在改方法中进行dokitview的添加和删除 因为处于遍历过程在 * 只有系统模式下才会调用 * * @param dokitView */ override fun onDokitViewAdd(dokitView: AbsDokitView?) {} override fun onResume() { } override fun onPause() {} /** * 系统悬浮窗需要调用 * * @return */ val context: Context? get() = null val resources: Resources? get() = null fun getString(@StringRes resId: Int): String? { return null } val isShow: Boolean get() = false protected fun <T : View> findViewById(@IdRes id: Int): T? { return null } /** * 将当前dokitView于activity解绑 */ fun detach() { } /** * 操作DecorView的直接子布局 * 测试专用 */ fun dealDecorRootView(decorRootView: FrameLayout?) { } /** * 更新view的位置 * * @param isActivityBackResume 是否是从其他页面返回时更新的位置 */ open fun updateViewLayout(tag: String, isActivityBackResume: Boolean) { } /** * 是否限制布局边界 * * @return */ open fun restrictBorderline(): Boolean { return true } fun post(run: Runnable) { } fun postDelayed(run: Runnable, delayMillis: Long) { } /** * 获取屏幕短边的长度 不包含statusBar * * @return */ val screenShortSideLength: Int get() = -1 //ScreenUtils.getAppScreenHeight(); 不包含statusBar /** * 获取屏幕长边的长度 不包含statusBar * * @return */ val screenLongSideLength: Int get() = -1 /** * 强制刷新当前dokitview */ open fun immInvalidate() { } }
apache-2.0
3cc144be817a8d6d36d8ad8254e171df
15.634981
79
0.564929
3.651085
false
false
false
false
tasks/tasks
app/src/androidTest/java/com/todoroo/astrid/subtasks/SubtasksTestCase.kt
1
1700
package com.todoroo.astrid.subtasks import androidx.test.InstrumentationRegistry import com.todoroo.astrid.api.Filter import com.todoroo.astrid.core.BuiltInFilterExposer import com.todoroo.astrid.dao.TaskDao import com.todoroo.astrid.data.Task import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.tasks.data.TaskListMetadataDao import org.tasks.injection.InjectingTestCase import org.tasks.preferences.Preferences import javax.inject.Inject abstract class SubtasksTestCase : InjectingTestCase() { lateinit var updater: SubtasksFilterUpdater lateinit var filter: Filter @Inject lateinit var taskListMetadataDao: TaskListMetadataDao @Inject lateinit var taskDao: TaskDao @Inject lateinit var preferences: Preferences override fun setUp() { super.setUp() filter = BuiltInFilterExposer.getMyTasksFilter(InstrumentationRegistry.getTargetContext().resources) preferences.clear(SubtasksFilterUpdater.ACTIVE_TASKS_ORDER) updater = SubtasksFilterUpdater(taskListMetadataDao, taskDao) } fun expectParentAndPosition(task: Task, parent: Task?, positionInParent: Int) { val parentId = parent?.uuid ?: "-1" val n = updater.findNodeForTask(task.uuid) assertNotNull("No node found for task " + task.title, n) assertEquals("Parent mismatch", parentId, n!!.parent!!.uuid) assertEquals("Position mismatch", positionInParent, n.parent!!.children.indexOf(n)) } companion object { /* Starting State: * * A * B * C * D * E * F */ val DEFAULT_SERIALIZED_TREE = "[-1, [1, 2, [3, 4]], 5, 6]".replace("\\s".toRegex(), "") } }
gpl-3.0
6c5faab3c47970153a3ec786e64af94e
33.714286
108
0.717647
4.239401
false
true
false
false
AoEiuV020/PaNovel
IronDB/src/main/java/cc/aoeiuv020/irondb/Iron.kt
1
784
package cc.aoeiuv020.irondb import cc.aoeiuv020.irondb.impl.DatabaseImpl import cc.aoeiuv020.irondb.impl.GsonSerializer import cc.aoeiuv020.irondb.impl.ReplaceFileSeparator import java.io.File /** * Created by AoEiuV020 on 2018.05.27-14:42:39. */ object Iron { fun db( base: File, // 默认使用gson进行序列化, dataSerializer: DataSerializer = GsonSerializer(), // 默认简单替换文件分隔符, keySerializer: KeySerializer = ReplaceFileSeparator(), subSerializer: KeySerializer = keySerializer ): Database = DatabaseImpl( base = base, subSerializer = subSerializer, keySerializer = keySerializer, dataSerializer = dataSerializer ) }
gpl-3.0
4def8e07cf96a30380b46703c74cadd8
28.64
66
0.652703
4.043716
false
false
false
false
didi/DoraemonKit
Android/dokit-plugin/src/main/kotlin/com/didichuxing/doraemonkit/plugin/transform/DoKitBaseTransform.kt
2
3310
package com.didichuxing.doraemonkit.plugin.transform import com.android.build.api.transform.QualifiedContent import com.android.build.api.transform.Transform import com.android.build.api.transform.TransformInvocation import com.android.build.gradle.BaseExtension import com.android.build.gradle.internal.pipeline.TransformManager import com.didichuxing.doraemonkit.plugin.DoKitTransformInvocation import com.didichuxing.doraemonkit.plugin.println import com.didiglobal.booster.annotations.Priority import com.didiglobal.booster.gradle.* import com.didiglobal.booster.transform.AbstractKlassPool import com.didiglobal.booster.transform.Transformer import org.gradle.api.Project /** * Represents the transform base * DoKitCommTransform 作用于 CommTransformer、BigImgTransformer、UrlConnectionTransformer、GlobalSlowMethodTransformer * @author johnsonlee */ open class DoKitBaseTransform protected constructor(val project: Project) : Transform() { /*transformers * Preload transformers as List to fix NoSuchElementException caused by ServiceLoader in parallel mode * booster 的默认出炉逻辑 DoKit已重写自处理 */ open val transformers = listOf<Transformer>() internal val verifyEnabled = project.getProperty(OPT_TRANSFORM_VERIFY, false) private val android: BaseExtension = project.getAndroid() private lateinit var androidKlassPool: AbstractKlassPool init { project.afterEvaluate { androidKlassPool = object : AbstractKlassPool(android.bootClasspath) {} } } val bootKlassPool: AbstractKlassPool get() = androidKlassPool override fun getName() = this.javaClass.simpleName override fun isIncremental() = !verifyEnabled override fun isCacheable() = !verifyEnabled override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> = TransformManager.CONTENT_CLASS override fun getScopes(): MutableSet<in QualifiedContent.Scope> = when { transformers.isEmpty() -> mutableSetOf() project.plugins.hasPlugin("com.android.library") -> SCOPE_PROJECT project.plugins.hasPlugin("com.android.application") -> SCOPE_FULL_PROJECT project.plugins.hasPlugin("com.android.dynamic-feature") -> SCOPE_FULL_WITH_FEATURES else -> TODO("Not an Android project") } override fun getReferencedScopes(): MutableSet<in QualifiedContent.Scope> = when { transformers.isEmpty() -> when { project.plugins.hasPlugin("com.android.library") -> SCOPE_PROJECT project.plugins.hasPlugin("com.android.application") -> SCOPE_FULL_PROJECT project.plugins.hasPlugin("com.android.dynamic-feature") -> SCOPE_FULL_WITH_FEATURES else -> TODO("Not an Android project") } else -> super.getReferencedScopes() } final override fun transform(invocation: TransformInvocation) { DoKitTransformInvocation(invocation, this).apply { if (isIncremental) { doIncrementalTransform() } else { outputProvider?.deleteAll() doFullTransform() } } } } /** * The option for transform outputs verifying, default is false */ private const val OPT_TRANSFORM_VERIFY = "dokit.transform.verify"
apache-2.0
ca6e9fe2aa550a0dbe77c4c29a9459bf
35.764045
112
0.725244
4.762737
false
false
false
false
jereksel/LibreSubstratum
app/src/main/kotlin/com/jereksel/libresubstratum/adapters/PrioritiesDetailAdapter.kt
1
5608
/* * Copyright (C) 2017 Andrzej Ressel ([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 <https://www.gnu.org/licenses/>. */ package com.jereksel.libresubstratum.adapters import android.graphics.Color import android.support.v7.util.DiffUtil import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import android.text.Html import android.view.LayoutInflater import android.view.MotionEvent import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.RelativeLayout import android.widget.TextView import com.jereksel.libresubstratum.R import com.jereksel.libresubstratum.activities.prioritiesdetail.PrioritiesDetailContract.Presenter import com.jereksel.libresubstratum.data.InstalledOverlay import com.jereksel.libresubstratum.extensions.getLogger import com.jereksel.libresubstratum.utils.SimpleDiffCallback import kotterknife.bindView import org.jetbrains.anko.sdk25.coroutines.onLongClick import java.util.* import kotlin.collections.ArrayList class PrioritiesDetailAdapter( overlays: List<InstalledOverlay>, val presenter: Presenter ): RecyclerView.Adapter<PrioritiesDetailAdapter.ViewHolder>() { val log = getLogger() val overlays = ArrayList(overlays) lateinit var itemTouchListener: ItemTouchHelper override fun onBindViewHolder(holder: ViewHolder, position: Int) { val overlay = overlays[position] val isEnabled = presenter.isEnabled(overlay.overlayId) val color = if(isEnabled) Color.GREEN else Color.RED holder.targetName.setTextColor(color) holder.targetIcon.setImageDrawable(overlay.targetDrawable) holder.themeIcon.setImageDrawable(overlay.sourceThemeDrawable) holder.targetName.text = "${overlay.targetName} - ${overlay.sourceThemeName}" val listener = View.OnTouchListener { _, event -> if (event.actionMasked == MotionEvent.ACTION_DOWN) { itemTouchListener.startDrag(holder) } false } holder.card.setOnClickListener { @Suppress("NAME_SHADOWING") val position = holder.adapterPosition val oldOverlays = overlays.toMutableList() val o = overlays.removeAt(position) overlays.add(0, o) presenter.updateOverlays(overlays) val newOverlays = overlays.toMutableList() DiffUtil.calculateDiff(SimpleDiffCallback(oldOverlays, newOverlays)).dispatchUpdatesTo(this) } holder.card.onLongClick(returnValue = true) { presenter.toggleOverlay(overlay.overlayId) notifyItemChanged(holder.adapterPosition) } holder.reorder.setOnTouchListener(listener) holder.themeIcon.setOnLongClickListener { presenter.openAppInSplit(overlay.targetId) true } holder.targetIcon.setOnLongClickListener { presenter.openAppInSplit(overlay.targetId) true } listOf( Triple(overlay.type1a, holder.type1a, R.string.theme_type1a_list), Triple(overlay.type1b, holder.type1b, R.string.theme_type1b_list), Triple(overlay.type1c, holder.type1c, R.string.theme_type1c_list), Triple(overlay.type2, holder.type2, R.string.theme_type2_list), Triple(overlay.type3, holder.type3, R.string.theme_type3_list) ).forEach { (name, view, stringId) -> if (!name.isNullOrEmpty()) { val text = view.context.getString(stringId) view.text = Html.fromHtml("<b>$text:</b> ${name?.replace("_", " ")}") view.visibility = View.VISIBLE } else { view.visibility = View.GONE } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = LayoutInflater.from(parent.context).inflate(R.layout.item_priorities_detail, parent, false) return ViewHolder(v) } fun onItemMove(fromPosition: Int, toPosition: Int) { Collections.swap(overlays, fromPosition, toPosition) presenter.updateOverlays(overlays) notifyItemMoved(fromPosition, toPosition) } override fun getItemCount() = overlays.size class ViewHolder(var view: View) : RecyclerView.ViewHolder(view) { val card: RelativeLayout by bindView(R.id.card) val targetIcon: ImageView by bindView(R.id.target_icon) val themeIcon: ImageView by bindView(R.id.theme_icon) val targetName: TextView by bindView(R.id.target_name) val reorder: ImageView by bindView(R.id.reorder) val type1a: TextView by bindView(R.id.theme_type1a) val type1b: TextView by bindView(R.id.theme_type1b) val type1c: TextView by bindView(R.id.theme_type1c) val type2: TextView by bindView(R.id.theme_type2) val type3: TextView by bindView(R.id.theme_type3) } }
mit
806d4a93254abcff1efded5713a0dcd7
36.644295
107
0.693652
4.461416
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/RowOptionsRunner.kt
1
6189
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.options import javafx.collections.ObservableList import javafx.event.ActionEvent import javafx.scene.control.ContextMenu import javafx.scene.control.Menu import javafx.scene.control.MenuItem import javafx.scene.control.SeparatorMenuItem import uk.co.nickthecoder.paratask.Tool import uk.co.nickthecoder.paratask.table.WrappedRow class RowOptionsRunner<in R : Any>(tool: Tool) : OptionsRunner(tool) { fun buildContextMenu(contextMenu: ContextMenu, rows: List<R>) { val firstRow = if (rows.isEmpty()) null else rows[0] contextMenu.items.clear() val optionsName = tool.optionsName val topLevelOptions = OptionsManager.getTopLevelOptions(optionsName) var addedSubMenus = false var count = 0 topLevelOptions.listFileOptions().filter { it.acceptRow(firstRow) }.forEach { fileOptions -> val items: ObservableList<MenuItem> val optionsList: List<Option> = fileOptions.listOptions().filter { it.isRow }.sorted() if (optionsList.isNotEmpty()) { if (count > 0 && count + optionsList.size > 15) { val subMenu = Menu(fileOptions.name) items = subMenu.items if (!addedSubMenus) { contextMenu.items.add(SeparatorMenuItem()) } contextMenu.items.add(subMenu) addedSubMenus = true } else { items = contextMenu.items if (items.isNotEmpty()) { items.add(SeparatorMenuItem()) } } for (option in optionsList) { val menuItem = createMenuItem(option) menuItem.addEventHandler(ActionEvent.ACTION) { runRows(option, rows) } items.add(menuItem) count++ } } } if (contextMenu.items.count() > 0) { val menu = Menu("Non-Row Options") val temp = ContextMenu() createNonRowOptionsMenu(temp) menu.items.addAll(temp.items) contextMenu.items.add(0, menu) contextMenu.items.add(1, SeparatorMenuItem()) } else { createNonRowOptionsMenu(contextMenu) } } fun runBatch(batch: Map<Option, List<WrappedRow<R>>>, newTab: Boolean, prompt: Boolean) { val batchRefresher = BatchRefresher() refresher = batchRefresher for ((option, list) in batch) { if (option.isMultiple) { doMultiple(option, list.map { it.row }, newTab = newTab, prompt = prompt) } else { list.map { it.row }.forEach { if (option.isRow) { doRow(option, it, newTab = newTab, prompt = prompt) } else { doNonRow(option, newTab = newTab, prompt = prompt) } } } } batchRefresher.complete() } fun runDefault(row: R, prompt: Boolean = false, newTab: Boolean = false) { refresher = Refresher() val option = OptionsManager.findOptionForRow(".", tool.optionsName, row) ?: return doRow(option, row, prompt = prompt, newTab = newTab) } fun runRows(option: Option, rows: List<R>, prompt: Boolean = false, newTab: Boolean = false) { val batchRefresher = BatchRefresher() refresher = batchRefresher doRows(option, rows, prompt = prompt, newTab = newTab) batchRefresher.complete() } private fun doRows(option: Option, rows: List<R>, prompt: Boolean = false, newTab: Boolean = false) { try { if (option.isMultiple) { doMultiple(option, rows, prompt = prompt, newTab = newTab) } else { for (row in rows) { doRow(option, row, prompt = prompt, newTab = newTab) } } } catch(e: Exception) { handleException(e) } } private fun doRow(option: Option, row: R, prompt: Boolean = false, newTab: Boolean = false) { try { val result = option.run(tool, row = row) process(result, newTab = newTab || option.newTab, prompt = prompt || option.prompt, refresh = option.refresh) } catch(e: Exception) { handleException(e) } } private fun doMultiple(option: Option, rows: List<R>, newTab: Boolean, prompt: Boolean) { try { val result = option.runMultiple(tool, rows) process(result, newTab = newTab || option.newTab, prompt = prompt || option.prompt, refresh = option.refresh) } catch(e: Exception) { handleException(e) } } inner class BatchRefresher : Refresher() { var count = 0 var batchComplete = false override fun add() { count++ } override fun onFinished() { count-- if (count == 0 && batchComplete) { tool.toolPane?.parametersPane?.run() } } fun complete() { batchComplete = true if (count == 0) { tool.toolPane?.parametersPane?.run() } } } }
gpl-3.0
66a369b265cc0b922063d1b823574e88
31.746032
105
0.560187
4.702888
false
false
false
false
SrirangaDigital/shankara-android
app/src/main/java/co/ideaportal/srirangadigital/shankaraandroid/search/bindings/RecentSearchAdapter.kt
1
1653
package co.ideaportal.srirangadigital.shankaraandroid.search.bindings import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import co.ideaportal.srirangadigital.shankaraandroid.R import co.ideaportal.srirangadigital.shankaraandroid.search.rowdata.RecentSearchObject import co.ideaportal.srirangadigital.shankaraandroid.util.AdapterClickListener class RecentSearchAdapter(private val context : Context, private val items: List<RecentSearchObject>, private val adapterClickListener: AdapterClickListener) : RecyclerView.Adapter<RecentViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecentViewHolder = RecentViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_recent_search, parent, false)) override fun onBindViewHolder(holder: RecentViewHolder, position: Int) { val item = getItemAtPos(position) holder.tvRecentSearchText.text = item.recent_search_text //set search results val resultCount = item.recent_search_results.toInt() if(resultCount>1) holder.tvResult.text = context.getString(R.string.recent_search_results,item.recent_search_results) if(resultCount==1) holder.tvResult.text = context.getString(R.string.recent_search_result,item.recent_search_results) holder.rlRecentSearch.setOnClickListener { adapterClickListener.onClick(position) } } override fun getItemCount(): Int = items.size private fun getItemAtPos(pos: Int): RecentSearchObject = items[pos] }
gpl-2.0
04da086642edd11fc3eb676e36c7267f
38.380952
202
0.76709
4.656338
false
false
false
false
nextcloud/android
app/src/main/java/com/owncloud/android/utils/FilesUploadHelper.kt
1
3651
/* * * Nextcloud Android client application * * @author Tobias Kaminsky * Copyright (C) 2022 Tobias Kaminsky * Copyright (C) 2022 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.owncloud.android.utils import com.nextcloud.client.account.User import com.nextcloud.client.jobs.BackgroundJobManager import com.owncloud.android.MainApp import com.owncloud.android.datamodel.OCFile import com.owncloud.android.datamodel.UploadsStorageManager import com.owncloud.android.db.OCUpload import com.owncloud.android.files.services.NameCollisionPolicy import com.owncloud.android.lib.common.utils.Log_OC import javax.inject.Inject class FilesUploadHelper { @Inject lateinit var backgroundJobManager: BackgroundJobManager @Inject lateinit var uploadsStorageManager: UploadsStorageManager init { MainApp.getAppComponent().inject(this) } @Suppress("LongParameterList") fun uploadNewFiles( user: User, localPaths: Array<String>, remotePaths: Array<String>, createRemoteFolder: Boolean, createdBy: Int, requiresWifi: Boolean, requiresCharging: Boolean, nameCollisionPolicy: NameCollisionPolicy, localBehavior: Int ) { val uploads = localPaths.mapIndexed { index, localPath -> OCUpload(localPath, remotePaths[index], user.accountName).apply { this.nameCollisionPolicy = nameCollisionPolicy isUseWifiOnly = requiresWifi isWhileChargingOnly = requiresCharging uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS this.createdBy = createdBy isCreateRemoteFolder = createRemoteFolder localAction = localBehavior } } uploadsStorageManager.storeUploads(uploads) backgroundJobManager.startFilesUploadJob(user) } fun uploadUpdatedFile( user: User, existingFiles: Array<OCFile>, behaviour: Int, nameCollisionPolicy: NameCollisionPolicy ) { Log_OC.d(this, "upload updated file") val uploads = existingFiles.map { file -> OCUpload(file, user).apply { fileSize = file.fileLength this.nameCollisionPolicy = nameCollisionPolicy isCreateRemoteFolder = true this.localAction = behaviour isUseWifiOnly = false isWhileChargingOnly = false uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS } } uploadsStorageManager.storeUploads(uploads) backgroundJobManager.startFilesUploadJob(user) } fun retryUpload(upload: OCUpload, user: User) { Log_OC.d(this, "retry upload") upload.uploadStatus = UploadsStorageManager.UploadStatus.UPLOAD_IN_PROGRESS uploadsStorageManager.updateUpload(upload) backgroundJobManager.startFilesUploadJob(user) } }
gpl-2.0
af0612445228124e7b567b01af83e5b0
34.105769
84
0.6894
4.913863
false
false
false
false
ohmae/mmupnp
mmupnp/src/main/java/net/mm2d/upnp/internal/server/ServerConst.kt
1
790
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.server internal object ServerConst { /** * IPv4 Address for SSDP */ const val SSDP_ADDRESS_V4 = "239.255.255.250" /** * IPv6 Address for SSDP */ const val SSDP_ADDRESS_V6 = "FF02::C" /** * Port number for SSDP. */ const val SSDP_PORT = 1900 /** * IPv4 Address for Multicast Eventing */ const val EVENT_ADDRESS_V4 = "239.255.255.246" /** * IPv6 Address for Multicast Eventing */ const val EVENT_ADDRESS_V6 = "FF02::130" /** * Port number for Multicast Eventing */ const val EVENT_PORT = 7900 }
mit
9e25b000d3bea7ef99a83906bae5acd6
18.55
51
0.592072
3.356223
false
false
false
false
synyx/calenope
modules/core/src/main/kotlin/de/synyx/calenope/core/std/model/MemoryEvent.kt
1
1093
package de.synyx.calenope.core.std.model import de.synyx.calenope.core.api.model.Attendee import de.synyx.calenope.core.api.model.Event import org.joda.time.Instant /** * @author clausen - [email protected] */ data class MemoryEvent( private val id : String, private val title : String, private val description : String? = "", private val location : String? = "", private val start : Instant, private val end : Instant?, private val creator : Attendee, private val attendees : Collection<Attendee>? = emptyList () ) : Event { override fun id () : String = id override fun title () : String = title override fun description () : String = description ?: "" override fun location () : String = location ?: "" override fun start () : Instant = start override fun end () : Instant? = end override fun creator () : Attendee = creator override fun attendees () : Collection<Attendee> = attendees ?: emptyList () }
apache-2.0
cce7ddc890c41e10a6b75d19903aa848
29.361111
82
0.597438
4.354582
false
false
false
false
apixandru/intellij-community
platform/projectModel-impl/src/com/intellij/configurationStore/SchemeManagerIprProvider.kt
2
3382
/* * 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.configurationStore import com.intellij.openapi.components.RoamingType import com.intellij.openapi.util.io.FileUtil import com.intellij.util.ArrayUtil import com.intellij.util.PathUtilRt import com.intellij.util.containers.ContainerUtil import com.intellij.util.loadElement import com.intellij.util.text.UniqueNameGenerator import com.intellij.util.toByteArray import org.jdom.Element import java.io.InputStream import java.util.* class SchemeManagerIprProvider(private val subStateTagName: String) : StreamProvider { private val nameToData = ContainerUtil.newConcurrentMap<String, ByteArray>() override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean { nameToData.get(PathUtilRt.getFileName(fileSpec))?.let(ByteArray::inputStream).let { consumer(it) } return true } override fun delete(fileSpec: String, roamingType: RoamingType): Boolean { nameToData.remove(PathUtilRt.getFileName(fileSpec)) return true } override fun processChildren(path: String, roamingType: RoamingType, filter: (String) -> Boolean, processor: (String, InputStream, Boolean) -> Boolean): Boolean { for ((name, data) in nameToData) { if (filter(name) && !data.inputStream().use { processor(name, it, false) }) { break } } return true } override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) { LOG.assertTrue(content.isNotEmpty()) nameToData.put(PathUtilRt.getFileName(fileSpec), ArrayUtil.realloc(content, size)) } fun load(state: Element?, nameGetter: ((Element) -> String)? = null) { nameToData.clear() if (state == null) { return } val nameGenerator = UniqueNameGenerator() for (child in state.getChildren(subStateTagName)) { var name = nameGetter?.invoke(child) ?: child.getAttributeValue("name") if (name == null) { for (optionElement in child.getChildren("option")) { if (optionElement.getAttributeValue("name") == "myName") { name = optionElement.getAttributeValue("value") } } } if (name.isNullOrEmpty()) { continue } nameToData.put(nameGenerator.generateUniqueName("${FileUtil.sanitizeFileName(name, false)}.xml"), child.toByteArray()) } } fun writeState(state: Element, comparator: Comparator<String>? = null) { val names = nameToData.keys.toTypedArray() if (comparator == null) { names.sort() } else { names.sortWith(comparator) } for (name in names) { nameToData.get(name)?.let { state.addContent(loadElement(it.inputStream())) } } } }
apache-2.0
233d88e74df97218e118e048484c76c1
33.520408
124
0.685393
4.432503
false
false
false
false
martin-nordberg/KatyDOM
Katydid-VDOM-JS/src/main/kotlin/i/katydid/vdom/elements/forms/KatydidInputTelephone.kt
1
2797
// // (C) Copyright 2017-2019 Martin E. Nordberg III // Apache 2.0 License // package i.katydid.vdom.elements.forms import i.katydid.vdom.builders.KatydidPhrasingContentBuilderImpl import i.katydid.vdom.elements.KatydidHtmlElementImpl import o.katydid.vdom.builders.KatydidAttributesContentBuilder import o.katydid.vdom.types.EDirection //--------------------------------------------------------------------------------------------------------------------- /** * Virtual node for an input type="tel" element. */ internal class KatydidInputTelephone<Msg>( phrasingContent: KatydidPhrasingContentBuilderImpl<Msg>, selector: String?, key: Any?, accesskey: Char?, autocomplete: String?, autofocus: Boolean?, contenteditable: Boolean?, dir: EDirection?, disabled: Boolean?, draggable: Boolean?, form: String?, hidden: Boolean?, lang: String?, list: String?, maxlength: Int?, minlength: Int?, name: String?, pattern: String?, placeholder: String?, readonly: Boolean?, required: Boolean?, size: Int?, spellcheck: Boolean?, style: String?, tabindex: Int?, title: String?, translate: Boolean?, value: String?, defineAttributes: KatydidAttributesContentBuilder<Msg>.() -> Unit ) : KatydidHtmlElementImpl<Msg>(selector, key ?: name, accesskey, contenteditable, dir, draggable, hidden, lang, spellcheck, style, tabindex, title, translate) { init { phrasingContent.contentRestrictions.confirmInteractiveContentAllowed() require(maxlength == null || maxlength >= 0) { "Attribute maxlength must be non-negative." } require(minlength == null || minlength >= 0) { "Attribute minlength must be non-negative." } require(size == null || size >= 0) { "Attribute size must be non-negative." } setAttribute("autocomplete", autocomplete) setBooleanAttribute("autofocus", autofocus) setBooleanAttribute("disabled", disabled) setAttribute("form", form) setAttribute("list", list) setNumberAttribute("maxlength", maxlength) setNumberAttribute("minlength", minlength) setAttribute("name", name) setAttribute("pattern", pattern) setAttribute("placeholder", placeholder) setBooleanAttribute("readonly", readonly) setBooleanAttribute("required", required) setNumberAttribute("size", size) setAttribute("value", value) setAttribute("type", "tel") phrasingContent.attributesContent(this).defineAttributes() this.freeze() } //// override val nodeName = "INPUT" } //---------------------------------------------------------------------------------------------------------------------
apache-2.0
991ee3d0e1c38c7a5a1c83cf57e3f016
31.523256
119
0.610297
5.189239
false
false
false
false
ivan-osipov/Clabo
src/main/kotlin/com/github/ivan_osipov/clabo/utils/typealiases.kt
1
313
package com.github.ivan_osipov.clabo.utils typealias ChatId = String typealias CallbackData = String typealias MessageId = String typealias FileId = String /** * It is url or file id */ typealias FilePointer = String typealias CallbackQueryId = String typealias MsgCode = String typealias Text = String
apache-2.0
d7181103f64c74ba35d8a8ac694fc063
14.65
42
0.769968
3.9125
false
false
false
false
edvin/tornadofx
src/test/kotlin/tornadofx/testapps/DrawerTest.kt
1
3742
package tornadofx.testapps import javafx.beans.property.SimpleStringProperty import javafx.scene.paint.Color import tornadofx.* class DrawerTestApp : App(DrawerWorkspace::class) { override fun onBeforeShow(view: UIComponent) { workspace.root.setPrefSize(600.0, 400.0) workspace.dock<JustAView>() } } class JustAView : View("Just A View") { override val root = vbox { label("I'm just a view - I do nothing") button("Load another View").action { workspace.dock<TestDrawerContributor>() } } } class AnotherView : View("Another") { override val root = stackpane { label(title) } } class YetAnotherView : View("Yet Another") { override val root = stackpane { label(title) } } class TestDrawerContributor : View("Test View with dynamic drawer item") { override val root = stackpane { vbox { label("I add something to the drawer when I'm docked") button("Load another View").action { workspace.dock<AnotherView>() } button("Load yet another View").action { workspace.dock<YetAnotherView>() } } } override fun onDock() { workspace.leftDrawer.item("Temp Drawer") { stackpane { label("I'm only guest starring!") } } } } class DrawerWorkspace : Workspace("Drawer Workspace", Workspace.NavigationMode.Stack) { init { menubar { menu("Options") { checkmenuitem("Toggle Navigation Mode").action { navigationMode = if (navigationMode == NavigationMode.Stack) NavigationMode.Tabs else NavigationMode.Stack } } } with(bottomDrawer) { item("Console") { style { backgroundColor += Color.BLACK } label("""Connected to the target VM, address: '127.0.0.1:64653', transport: 'socket' Disconnected from the target VM, address: '127.0.0.1:64653', transport: 'socket' Process finished with exit code 0 """) { style { backgroundColor += Color.BLACK textFill = Color.LIGHTGREY fontFamily = "Consolas" } } } item("Events") { } } with(leftDrawer) { item<TableViewDirtyTest>() item("Form item") { form { fieldset("Customer Details") { field("Name") { textfield() } field("Password") { textfield() } } } } item("SqueezeBox Item", showHeader = false) { squeezebox(multiselect = false, fillHeight = true) { fold("Customer Editor") { form { fieldset("Customer Details") { field("Name") { textfield() } field("Password") { textfield() } } } } fold("Some other editor") { stackpane { label("Nothing here") } } fold("A Table") { tableview(observableListOf("One", "Two", "Three")) { column<String, String>("Value") { SimpleStringProperty(it.value) } } } } } } } }
apache-2.0
2e8cfce4184dce95a95be0968e86d9c9
29.680328
126
0.466328
5.182825
false
false
false
false
Ribesg/anko
preview/xml-converter/src/org/jetbrains/kotlin/android/xmlconverter/AttributeOptimizer.kt
2
1656
/* * Copyright 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.android.xmlconverter import org.jetbrains.kotlin.android.attrs.NoAttr internal val attributeOptimizations = listOf( ::optimizeInclude, ::optimizeHelperConstructors ) internal fun optimizeInclude(name: String, attrs: List<KeyValuePair>): Pair<String, List<KeyValuePair>>? { val layout = attrs.firstOrNull { it.key == "layout" }?.value return if (name == "include" && layout != null) { val rendered = renderReference(NoAttr, "layout", layout) "$name<View>(${rendered?.value ?: layout})" to attrs.filter { it.key != "layout" } } else null } internal fun optimizeHelperConstructors(name: String, attrs: List<KeyValuePair>): Pair<String, List<KeyValuePair>>? { val helpers = listOf( attrs.firstOrNull { it.key == "text" }, attrs.firstOrNull { it.key == "textResource" } ).filterNotNull() return if (helpers.isNotEmpty()) { val helper = helpers.first() "$name(${helper.value})" to attrs.filter { it.key != helper.key } } else null }
apache-2.0
de545978da92211abaf05edae5358c17
37.534884
117
0.688406
4.109181
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/preferences/RangePreference.kt
1
1037
package com.sapuseven.untis.preferences import android.content.Context import android.util.AttributeSet import androidx.preference.EditTextPreference import com.sapuseven.untis.R class RangePreference(context: Context, attrs: AttributeSet?) : EditTextPreference(context, attrs) { companion object { fun convertToPair(text: String?): Pair<Int, Int>? = text?.split("-")?.map { it.toIntOrNull() ?: 0 }?.toPair() } override fun getSummary(): CharSequence = convertToPair(parseInput(text))?.let { context.getString(R.string.preference_timetable_range_desc, it.first, it.second) } ?: "" private fun parseInput(value: String?): String? = value?.let { Regex("[^\\d]*(\\d+)[^\\d]*(\\d+)[^\\d]*").replace(it, "$1-$2") } override fun setText(text: String?) = super.setText(parseInput(text)) override fun shouldDisableDependents(): Boolean = super.shouldDisableDependents() || (convertToPair(text)?.first ?: 1) <= 1 } private fun <E> List<E>.toPair(): Pair<E, E>? = if (this.size != 2) null else this.zipWithNext().first()
gpl-3.0
8e06e49215fe359b778e11efee497d41
37.407407
129
0.703954
3.575862
false
false
false
false
thanksmister/androidthings-mqtt-alarm-panel
app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/network/ImageApi.kt
1
2313
/* * <!-- * ~ Copyright (c) 2017. ThanksMister 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.thanksmister.iot.mqtt.alarmpanel.network import com.facebook.stetho.okhttp3.StethoInterceptor import com.google.gson.GsonBuilder import com.thanksmister.iot.mqtt.alarmpanel.network.adapters.DataTypeAdapterFactory import com.thanksmister.iot.mqtt.alarmpanel.network.model.ImageResponse import java.util.concurrent.TimeUnit import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class ImageApi { private val service: ImageRequest init { val base_url = "https://api.imgur.com/" val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY val httpClient = OkHttpClient.Builder() .addInterceptor(logging) .connectTimeout(10000, TimeUnit.SECONDS) .readTimeout(10000, TimeUnit.SECONDS) .addNetworkInterceptor(StethoInterceptor()) .build() val gson = GsonBuilder() .registerTypeAdapterFactory(DataTypeAdapterFactory()) .create() val retrofit = Retrofit.Builder() .client(httpClient) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(base_url) .build() service = retrofit.create(ImageRequest::class.java) } fun getImagesByTag(clientId: String, tag: String): Call<ImageResponse> { val service = service val auth = "Client-ID " + clientId return service.getImagesByTag(auth, tag) } }
apache-2.0
09759a967fdf898ecad20a18e2afa74a
32.057143
87
0.673584
4.439539
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/lazy/layout/LazyLayoutItemProvider.kt
3
8070
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lazy.layout import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.State /** * Provides all the needed info about the items which could be later composed and displayed as * children or [LazyLayout]. */ @Stable @ExperimentalFoundationApi interface LazyLayoutItemProvider { /** * The total number of items in the lazy layout (visible or not). */ val itemCount: Int /** * The item for the given [index]. */ @Composable fun Item(index: Int) /** * Returns the content type for the item on this index. It is used to improve the item * compositions reusing efficiency. Note that null is a valid type and items of such * type will be considered compatible. */ fun getContentType(index: Int): Any? = null /** * Returns the key for the item on this index. * * @see getDefaultLazyLayoutKey which you can use if the user didn't provide a key. */ fun getKey(index: Int): Any = getDefaultLazyLayoutKey(index) /** * Contains the mapping between the key and the index. It could contain not all the items of * the list as an optimization or be empty if user didn't provide a custom key-index mapping. */ val keyToIndexMap: Map<Any, Int> get() = emptyMap() } /** * This creates an object meeting following requirements: * 1) Objects created for the same index are equals and never equals for different indexes. * 2) This class is saveable via a default SaveableStateRegistry on the platform. * 3) This objects can't be equals to any object which could be provided by a user as a custom key. */ @ExperimentalFoundationApi @Suppress("MissingNullability") expect fun getDefaultLazyLayoutKey(index: Int): Any /** * Common content holder to back interval-based `item` DSL of lazy layouts. */ @ExperimentalFoundationApi interface LazyLayoutIntervalContent { /** * Returns item key based on a local index for the current interval. */ val key: ((index: Int) -> Any)? get() = null /** * Returns item type based on a local index for the current interval. */ val type: ((index: Int) -> Any?) get() = { null } } /** * Default implementation of [LazyLayoutItemProvider] shared by lazy layout implementations. * * @param intervals [IntervalList] of [LazyLayoutIntervalContent] defined by lazy list DSL * @param nearestItemsRange range of indices considered near current viewport * @param itemContent composable content based on index inside provided interval */ @ExperimentalFoundationApi fun <T : LazyLayoutIntervalContent> LazyLayoutItemProvider( intervals: IntervalList<T>, nearestItemsRange: IntRange, itemContent: @Composable (interval: T, index: Int) -> Unit, ): LazyLayoutItemProvider = DefaultLazyLayoutItemsProvider(itemContent, intervals, nearestItemsRange) @ExperimentalFoundationApi private class DefaultLazyLayoutItemsProvider<IntervalContent : LazyLayoutIntervalContent>( val itemContentProvider: @Composable IntervalContent.(index: Int) -> Unit, val intervals: IntervalList<IntervalContent>, nearestItemsRange: IntRange ) : LazyLayoutItemProvider { override val itemCount get() = intervals.size override val keyToIndexMap: Map<Any, Int> = generateKeyToIndexMap(nearestItemsRange, intervals) @Composable override fun Item(index: Int) { withLocalIntervalIndex(index) { localIndex, content -> content.itemContentProvider(localIndex) } } override fun getKey(index: Int): Any = withLocalIntervalIndex(index) { localIndex, content -> content.key?.invoke(localIndex) ?: getDefaultLazyLayoutKey(index) } override fun getContentType(index: Int): Any? = withLocalIntervalIndex(index) { localIndex, content -> content.type.invoke(localIndex) } private inline fun <T> withLocalIntervalIndex( index: Int, block: (localIndex: Int, content: IntervalContent) -> T ): T { val interval = intervals[index] val localIntervalIndex = index - interval.startIndex return block(localIntervalIndex, interval.value) } /** * Traverses the interval [list] in order to create a mapping from the key to the index for all * the indexes in the passed [range]. * The returned map will not contain the values for intervals with no key mapping provided. */ @ExperimentalFoundationApi private fun generateKeyToIndexMap( range: IntRange, list: IntervalList<LazyLayoutIntervalContent> ): Map<Any, Int> { val first = range.first check(first >= 0) val last = minOf(range.last, list.size - 1) return if (last < first) { emptyMap() } else { hashMapOf<Any, Int>().also { map -> list.forEach( fromIndex = first, toIndex = last, ) { if (it.value.key != null) { val keyFactory = requireNotNull(it.value.key) val start = maxOf(first, it.startIndex) val end = minOf(last, it.startIndex + it.size - 1) for (i in start..end) { map[keyFactory(i - it.startIndex)] = i } } } } } } } /** * Delegating version of [LazyLayoutItemProvider], abstracting internal [State] access. * This way, passing [LazyLayoutItemProvider] will not trigger recomposition unless * its methods are called within composable functions. * * @param delegate [State] to delegate [LazyLayoutItemProvider] functionality to. */ @ExperimentalFoundationApi fun DelegatingLazyLayoutItemProvider( delegate: State<LazyLayoutItemProvider> ): LazyLayoutItemProvider = DefaultDelegatingLazyLayoutItemProvider(delegate) @ExperimentalFoundationApi private class DefaultDelegatingLazyLayoutItemProvider( private val delegate: State<LazyLayoutItemProvider> ) : LazyLayoutItemProvider { override val itemCount: Int get() = delegate.value.itemCount @Composable override fun Item(index: Int) { delegate.value.Item(index) } override val keyToIndexMap: Map<Any, Int> get() = delegate.value.keyToIndexMap override fun getKey(index: Int): Any = delegate.value.getKey(index) override fun getContentType(index: Int): Any? = delegate.value.getContentType(index) } /** * Finds a position of the item with the given key in the lists. This logic allows us to * detect when there were items added or removed before our current first item. */ @ExperimentalFoundationApi internal fun LazyLayoutItemProvider.findIndexByKey( key: Any?, lastKnownIndex: Int, ): Int { if (key == null) { // there were no real item during the previous measure return lastKnownIndex } if (lastKnownIndex < itemCount && key == getKey(lastKnownIndex) ) { // this item is still at the same index return lastKnownIndex } val newIndex = keyToIndexMap[key] if (newIndex != null) { return newIndex } // fallback to the previous index if we don't know the new index of the item return lastKnownIndex }
apache-2.0
ccd51032a78c6681114f49062b0a3f81
33.788793
99
0.680545
4.66474
false
false
false
false
deeplearning4j/deeplearning4j
nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/ConstantOfShape.kt
1
3209
/* * ****************************************************************************** * * * * * * This program and the accompanying materials are made available under the * * terms of the Apache License, Version 2.0 which is available at * * https://www.apache.org/licenses/LICENSE-2.0. * * * * See the NOTICE file distributed with this work for additional * * information regarding copyright ownership. * * 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. * * * * SPDX-License-Identifier: Apache-2.0 * ***************************************************************************** */ package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations import org.nd4j.autodiff.samediff.SDVariable import org.nd4j.autodiff.samediff.SameDiff import org.nd4j.autodiff.samediff.internal.SameDiffOp import org.nd4j.linalg.api.buffer.DataType import org.nd4j.linalg.api.ndarray.INDArray import org.nd4j.samediff.frameworkimport.ImportGraph import org.nd4j.samediff.frameworkimport.hooks.PreImportHook import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry import org.nd4j.shade.protobuf.GeneratedMessageV3 import org.nd4j.shade.protobuf.ProtocolMessageEnum /** * A port of constant_of_shape.py from onnx tensorflow for samediff: * https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/constant_of_shape.py * * @author Adam Gibson */ @PreHookRule(nodeNames = [],opNames = ["ConstantOfShape"],frameworkName = "onnx") class ConstantOfShape : PreImportHook { override fun doImport( sd: SameDiff, attributes: Map<String, Any>, outputNames: List<String>, op: SameDiffOp, mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>, importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>, dynamicVariables: Map<String, GeneratedMessageV3> ): Map<String, List<SDVariable>> { val outputVarName = outputNames[0] var outputVar: SDVariable? = null var inputShape = sd.getVariable(op.inputsToOp[0]) if(!attributes.containsKey("value")) { //zeros float 32 as according to onnx spec outputVar = sd.create(outputVarName,inputShape, DataType.FLOAT,"c",true) } else { val firstVal = attributes["value"] as INDArray outputVar = sd.create(inputShape,firstVal.dataType(),"c",false) val firstValue = firstVal.getDouble(0) outputVar = sd.assign(outputVar,sd.constant(firstValue)).castTo(outputVarName,firstVal.dataType()) } return mapOf(outputVar.name() to listOf(outputVar)) } }
apache-2.0
f912e97c17ffca795007d38f19fe0688
44.211268
184
0.700218
4.21682
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/wordSelection/RsGroupSelectionHandler.kt
3
2546
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.wordSelection import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.LineTokenizer import com.intellij.psi.PsiComment import com.intellij.psi.PsiElement import com.intellij.psi.PsiWhiteSpace import org.rust.lang.core.psi.RsElementTypes import org.rust.lang.core.psi.RsMembers import org.rust.lang.core.psi.RsStmt import org.rust.lang.core.psi.ext.endOffset import org.rust.lang.core.psi.ext.startOffset import java.util.* class RsGroupSelectionHandler : ExtendWordSelectionHandlerBase() { override fun canSelect(e: PsiElement): Boolean = e is RsStmt || RsFieldLikeSelectionHandler.isFieldLikeDecl(e) || e.parent is RsMembers || e is PsiComment override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange> { // see com.intellij.codeInsight.editorActions.wordSelection.StatementGroupSelectioner for the reference implementation val result = ArrayList<TextRange>() var startElement = e var endElement = e while (startElement.prevSibling != null) { val sibling = startElement.prevSibling if (sibling.node.elementType == RsElementTypes.LBRACE) break if (sibling is PsiWhiteSpace) { val strings = LineTokenizer.tokenize(sibling.text.toCharArray(), false) if (strings.size > 2) { break } } startElement = sibling } while (startElement is PsiWhiteSpace) startElement = startElement.nextSibling while (endElement.nextSibling != null) { val sibling = endElement.nextSibling if (sibling.node.elementType == RsElementTypes.RBRACE) break if (sibling is PsiWhiteSpace) { val strings = LineTokenizer.tokenize(sibling.text.toCharArray(), false) if (strings.size > 2) { break } } endElement = sibling } while (endElement is PsiWhiteSpace) endElement = endElement.prevSibling result.addAll( expandToWholeLine( editorText, TextRange(startElement.startOffset, endElement.endOffset) ) ) return result } }
mit
5c5548dcfba60d423e93ef1934e535d5
32.946667
126
0.666929
4.858779
false
false
false
false
jorjoluiso/QuijoteLui
src/main/kotlin/com/quijotelui/service/ReporteRetencionServiceImpl.kt
1
1516
package com.quijotelui.service import com.quijotelui.electronico.util.Fechas import com.quijotelui.model.ReporteRetencion import com.quijotelui.repository.IReporteRetencionDao import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class ReporteRetencionServiceImpl : IReporteRetencionService { @Autowired lateinit var reporteRetencionDao: IReporteRetencionDao override fun findByFechas(fechaInicio: String, fechaFin: String): MutableList<ReporteRetencion> { val fechas = Fechas() val fechaInDateTypeInicio = fechas.toDate(fechaInicio) val fechaInDateTypeFin = fechas.toDate(fechaFin) return reporteRetencionDao.findByFechas(fechaInDateTypeInicio, fechaInDateTypeFin) } override fun findByFechasEstado(fechaInicio: String, fechaFin: String, estado: String): MutableList<ReporteRetencion> { val fechas = Fechas() val fechaInDateTypeInicio = fechas.toDate(fechaInicio) val fechaInDateTypeFin = fechas.toDate(fechaFin) if (estado.equals("Autorizados")) { return reporteRetencionDao.findByFechasAutorizado(fechaInDateTypeInicio, fechaInDateTypeFin) } else if (estado.equals("NoAutorizados")) { return reporteRetencionDao.findByFechasNoAutorizado(fechaInDateTypeInicio, fechaInDateTypeFin) } else { return reporteRetencionDao.findByFechas(fechaInDateTypeInicio, fechaInDateTypeFin) } } }
gpl-3.0
25a9c9cb07eda8f2c422ee0ce3c04d35
36.925
123
0.755937
4.858974
false
false
false
false
androidx/androidx
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/NavigationRail.kt
3
25565
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3 import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.indication import androidx.compose.foundation.interaction.Interaction import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.foundation.selection.selectable import androidx.compose.foundation.selection.selectableGroup import androidx.compose.material.ripple.rememberRipple import androidx.compose.material3.tokens.NavigationRailTokens import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Stable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.layout.Placeable import androidx.compose.ui.layout.layoutId import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.constrainWidth import androidx.compose.ui.unit.dp import kotlin.math.roundToInt /** * <a href="https://m3.material.io/components/navigation-rail/overview" class="external" target="_blank">Material Design bottom navigation rail</a>. * * Navigation rails provide access to primary destinations in apps when using tablet and desktop * screens. * * ![Navigation rail image](https://developer.android.com/images/reference/androidx/compose/material3/navigation-rail.png) * * The navigation rail should be used to display three to seven app destinations and, optionally, a * [FloatingActionButton] or a logo header. Each destination is typically represented by an icon and * an optional text label. * * [NavigationRail] should contain multiple [NavigationRailItem]s, each representing a singular * destination. * * A simple example looks like: * @sample androidx.compose.material3.samples.NavigationRailSample * * See [NavigationRailItem] for configuration specific to each item, and not the overall * NavigationRail component. * * @param modifier the [Modifier] to be applied to this navigation rail * @param containerColor the color used for the background of this navigation rail. Use * [Color.Transparent] to have no color. * @param contentColor the preferred color for content inside this navigation rail. Defaults to * either the matching content color for [containerColor], or to the current [LocalContentColor] if * [containerColor] is not a color from the theme. * @param header optional header that may hold a [FloatingActionButton] or a logo * @param windowInsets a window insets of the navigation rail. * @param content the content of this navigation rail, typically 3-7 [NavigationRailItem]s */ @Composable fun NavigationRail( modifier: Modifier = Modifier, containerColor: Color = NavigationRailDefaults.ContainerColor, contentColor: Color = contentColorFor(containerColor), header: @Composable (ColumnScope.() -> Unit)? = null, windowInsets: WindowInsets = NavigationRailDefaults.windowInsets, content: @Composable ColumnScope.() -> Unit ) { Surface( color = containerColor, contentColor = contentColor, modifier = modifier, ) { Column( Modifier .fillMaxHeight() .windowInsetsPadding(windowInsets) .widthIn(min = NavigationRailTokens.ContainerWidth) .padding(vertical = NavigationRailVerticalPadding) .selectableGroup(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(NavigationRailVerticalPadding) ) { if (header != null) { header() Spacer(Modifier.height(NavigationRailHeaderPadding)) } content() } } } /** * Material Design navigation rail item. * * A [NavigationRailItem] represents a destination within a [NavigationRail]. * * Navigation rails provide access to primary destinations in apps when using tablet and desktop * screens. * * The text label is always shown (if it exists) when selected. Showing text labels if not selected * is controlled by [alwaysShowLabel]. * * @param selected whether this item is selected * @param onClick called when this item is clicked * @param icon icon for this item, typically an [Icon] * @param modifier the [Modifier] to be applied to this item * @param enabled controls the enabled state of this item. When `false`, this component will not * respond to user input, and it will appear visually disabled and disabled to accessibility * services. * @param label optional text label for this item * @param alwaysShowLabel whether to always show the label for this item. If false, the label will * only be shown when this item is selected. * @param colors [NavigationRailItemColors] that will be used to resolve the colors used for this * item in different states. See [NavigationRailItemDefaults.colors]. * @param interactionSource the [MutableInteractionSource] representing the stream of [Interaction]s * for this item. You can create and pass in your own `remember`ed instance to observe * [Interaction]s and customize the appearance / behavior of this item in different states. */ @Composable fun NavigationRailItem( selected: Boolean, onClick: () -> Unit, icon: @Composable () -> Unit, modifier: Modifier = Modifier, enabled: Boolean = true, label: @Composable (() -> Unit)? = null, alwaysShowLabel: Boolean = true, colors: NavigationRailItemColors = NavigationRailItemDefaults.colors(), interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, ) { val styledIcon = @Composable { val iconColor by colors.iconColor(selected = selected) // If there's a label, don't have a11y services repeat the icon description. val clearSemantics = label != null && (alwaysShowLabel || selected) Box(modifier = if (clearSemantics) Modifier.clearAndSetSemantics {} else Modifier) { CompositionLocalProvider(LocalContentColor provides iconColor, content = icon) } } val styledLabel: @Composable (() -> Unit)? = label?.let { @Composable { val style = MaterialTheme.typography.fromToken(NavigationRailTokens.LabelTextFont) val textColor by colors.textColor(selected = selected) CompositionLocalProvider(LocalContentColor provides textColor) { ProvideTextStyle(style, content = label) } } } Box( modifier .selectable( selected = selected, onClick = onClick, enabled = enabled, role = Role.Tab, interactionSource = interactionSource, indication = null, ) .height(height = NavigationRailItemHeight) .widthIn(min = NavigationRailItemWidth), contentAlignment = Alignment.Center ) { val animationProgress: Float by animateFloatAsState( targetValue = if (selected) 1f else 0f, animationSpec = tween(ItemAnimationDurationMillis) ) // The entire item is selectable, but only the indicator pill shows the ripple. To achieve // this, we re-map the coordinates of the item's InteractionSource into the coordinates of // the indicator. val deltaOffset: Offset with(LocalDensity.current) { val itemWidth = NavigationRailItemWidth.roundToPx() val indicatorWidth = NavigationRailTokens.ActiveIndicatorWidth.roundToPx() deltaOffset = Offset((itemWidth - indicatorWidth).toFloat() / 2, 0f) } val offsetInteractionSource = remember(interactionSource, deltaOffset) { MappedInteractionSource(interactionSource, deltaOffset) } val indicatorShape = if (label != null) { NavigationRailTokens.ActiveIndicatorShape.toShape() } else { NavigationRailTokens.NoLabelActiveIndicatorShape.toShape() } // The indicator has a width-expansion animation which interferes with the timing of the // ripple, which is why they are separate composables val indicatorRipple = @Composable { Box( Modifier .layoutId(IndicatorRippleLayoutIdTag) .clip(indicatorShape) .indication(offsetInteractionSource, rememberRipple()) ) } val indicator = @Composable { Box( Modifier .layoutId(IndicatorLayoutIdTag) .background( color = colors.indicatorColor.copy(alpha = animationProgress), shape = indicatorShape ) ) } NavigationRailItemBaselineLayout( indicatorRipple = indicatorRipple, indicator = indicator, icon = styledIcon, label = styledLabel, alwaysShowLabel = alwaysShowLabel, animationProgress = animationProgress, ) } } /** Defaults used in [NavigationRail] */ object NavigationRailDefaults { /** Default container color of a navigation rail. */ val ContainerColor: Color @Composable get() = NavigationRailTokens.ContainerColor.toColor() /** * Default window insets for navigation rail. */ val windowInsets: WindowInsets @Composable get() = WindowInsets.systemBarsForVisualComponents .only(WindowInsetsSides.Vertical + WindowInsetsSides.Start) } /** Defaults used in [NavigationRailItem]. */ object NavigationRailItemDefaults { /** * Creates a [NavigationRailItemColors] with the provided colors according to the Material * specification. * * @param selectedIconColor the color to use for the icon when the item is selected. * @param selectedTextColor the color to use for the text label when the item is selected. * @param indicatorColor the color to use for the indicator when the item is selected. * @param unselectedIconColor the color to use for the icon when the item is unselected. * @param unselectedTextColor the color to use for the text label when the item is unselected. * @return the resulting [NavigationRailItemColors] used for [NavigationRailItem] */ @Composable fun colors( selectedIconColor: Color = NavigationRailTokens.ActiveIconColor.toColor(), selectedTextColor: Color = NavigationRailTokens.ActiveLabelTextColor.toColor(), indicatorColor: Color = NavigationRailTokens.ActiveIndicatorColor.toColor(), unselectedIconColor: Color = NavigationRailTokens.InactiveIconColor.toColor(), unselectedTextColor: Color = NavigationRailTokens.InactiveLabelTextColor.toColor(), ): NavigationRailItemColors = NavigationRailItemColors( selectedIconColor = selectedIconColor, selectedTextColor = selectedTextColor, selectedIndicatorColor = indicatorColor, unselectedIconColor = unselectedIconColor, unselectedTextColor = unselectedTextColor, ) } /** Represents the colors of the various elements of a navigation item. */ @Stable class NavigationRailItemColors internal constructor( private val selectedIconColor: Color, private val selectedTextColor: Color, private val selectedIndicatorColor: Color, private val unselectedIconColor: Color, private val unselectedTextColor: Color, ) { /** * Represents the icon color for this item, depending on whether it is [selected]. * * @param selected whether the item is selected */ @Composable internal fun iconColor(selected: Boolean): State<Color> { return animateColorAsState( targetValue = if (selected) selectedIconColor else unselectedIconColor, animationSpec = tween(ItemAnimationDurationMillis) ) } /** * Represents the text color for this item, depending on whether it is [selected]. * * @param selected whether the item is selected */ @Composable internal fun textColor(selected: Boolean): State<Color> { return animateColorAsState( targetValue = if (selected) selectedTextColor else unselectedTextColor, animationSpec = tween(ItemAnimationDurationMillis) ) } /** Represents the color of the indicator used for selected items. */ internal val indicatorColor: Color @Composable get() = selectedIndicatorColor override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || other !is NavigationRailItemColors) return false if (selectedIconColor != other.selectedIconColor) return false if (unselectedIconColor != other.unselectedIconColor) return false if (selectedTextColor != other.selectedTextColor) return false if (unselectedTextColor != other.unselectedTextColor) return false if (selectedIndicatorColor != other.selectedIndicatorColor) return false return true } override fun hashCode(): Int { var result = selectedIconColor.hashCode() result = 31 * result + unselectedIconColor.hashCode() result = 31 * result + selectedTextColor.hashCode() result = 31 * result + unselectedTextColor.hashCode() result = 31 * result + selectedIndicatorColor.hashCode() return result } } /** * Base layout for a [NavigationRailItem]. * * @param indicatorRipple indicator ripple for this item when it is selected * @param indicator indicator for this item when it is selected * @param icon icon for this item * @param label text label for this item * @param alwaysShowLabel whether to always show the label for this item. If false, the label will * only be shown when this item is selected. * @param animationProgress progress of the animation, where 0 represents the unselected state of * this item and 1 represents the selected state. This value controls other values such as indicator * size, icon and label positions, etc. */ @Composable private fun NavigationRailItemBaselineLayout( indicatorRipple: @Composable () -> Unit, indicator: @Composable () -> Unit, icon: @Composable () -> Unit, label: @Composable (() -> Unit)?, alwaysShowLabel: Boolean, animationProgress: Float, ) { Layout({ indicatorRipple() if (animationProgress > 0) { indicator() } Box(Modifier.layoutId(IconLayoutIdTag)) { icon() } if (label != null) { Box( Modifier .layoutId(LabelLayoutIdTag) .alpha(if (alwaysShowLabel) 1f else animationProgress) ) { label() } } }) { measurables, constraints -> val iconPlaceable = measurables.first { it.layoutId == IconLayoutIdTag }.measure(constraints) val totalIndicatorWidth = iconPlaceable.width + (IndicatorHorizontalPadding * 2).roundToPx() val animatedIndicatorWidth = (totalIndicatorWidth * animationProgress).roundToInt() val indicatorVerticalPadding = if (label == null) { IndicatorVerticalPaddingNoLabel } else { IndicatorVerticalPaddingWithLabel } val indicatorHeight = iconPlaceable.height + (indicatorVerticalPadding * 2).roundToPx() val indicatorRipplePlaceable = measurables .first { it.layoutId == IndicatorRippleLayoutIdTag } .measure( Constraints.fixed( width = totalIndicatorWidth, height = indicatorHeight ) ) val indicatorPlaceable = measurables .firstOrNull { it.layoutId == IndicatorLayoutIdTag } ?.measure( Constraints.fixed( width = animatedIndicatorWidth, height = indicatorHeight ) ) val labelPlaceable = label?.let { measurables .first { it.layoutId == LabelLayoutIdTag } .measure( // Measure with loose constraints for height as we don't want the label to // take up more space than it needs constraints.copy(minHeight = 0) ) } if (label == null) { placeIcon(iconPlaceable, indicatorRipplePlaceable, indicatorPlaceable, constraints) } else { placeLabelAndIcon( labelPlaceable!!, iconPlaceable, indicatorRipplePlaceable, indicatorPlaceable, constraints, alwaysShowLabel, animationProgress, ) } } } /** * Places the provided [Placeable]s in the center of the provided [constraints]. */ private fun MeasureScope.placeIcon( iconPlaceable: Placeable, indicatorRipplePlaceable: Placeable, indicatorPlaceable: Placeable?, constraints: Constraints, ): MeasureResult { val width = constraints.constrainWidth( maxOf( iconPlaceable.width, indicatorRipplePlaceable.width, indicatorPlaceable?.width ?: 0 ) ) val height = constraints.maxHeight val iconX = (width - iconPlaceable.width) / 2 val iconY = (height - iconPlaceable.height) / 2 val rippleX = (width - indicatorRipplePlaceable.width) / 2 val rippleY = (height - indicatorRipplePlaceable.height) / 2 return layout(width, height) { indicatorPlaceable?.let { val indicatorX = (width - it.width) / 2 val indicatorY = (height - it.height) / 2 it.placeRelative(indicatorX, indicatorY) } iconPlaceable.placeRelative(iconX, iconY) indicatorRipplePlaceable.placeRelative(rippleX, rippleY) } } /** * Places the provided [Placeable]s in the correct position, depending on [alwaysShowLabel] and * [animationProgress]. * * When [alwaysShowLabel] is true, the positions do not move. The [iconPlaceable] will be placed * near the top of the item and the [labelPlaceable] will be placed near the bottom, according to * the spec. * * When [animationProgress] is 1 (representing the selected state), the positions will be the same * as above. * * Otherwise, when [animationProgress] is 0, [iconPlaceable] will be placed in the center, like in * [placeIcon], and [labelPlaceable] will not be shown. * * When [animationProgress] is animating between these values, [iconPlaceable] and [labelPlaceable] * will be placed at a corresponding interpolated position. * * [indicatorRipplePlaceable] and [indicatorPlaceable] will always be placed in such a way that to * share the same center as [iconPlaceable]. * * @param labelPlaceable text label placeable inside this item * @param iconPlaceable icon placeable inside this item * @param indicatorRipplePlaceable indicator ripple placeable inside this item * @param indicatorPlaceable indicator placeable inside this item, if it exists * @param constraints constraints of the item * @param alwaysShowLabel whether to always show the label for this item. If true, icon and label * positions will not change. If false, positions transition between 'centered icon with no label' * and 'top aligned icon with label'. * @param animationProgress progress of the animation, where 0 represents the unselected state of * this item and 1 represents the selected state. Values between 0 and 1 interpolate positions of * the icon and label. */ private fun MeasureScope.placeLabelAndIcon( labelPlaceable: Placeable, iconPlaceable: Placeable, indicatorRipplePlaceable: Placeable, indicatorPlaceable: Placeable?, constraints: Constraints, alwaysShowLabel: Boolean, animationProgress: Float, ): MeasureResult { val height = constraints.maxHeight // Label should be `ItemVerticalPadding` from the bottom val labelY = height - labelPlaceable.height - NavigationRailItemVerticalPadding.roundToPx() // Icon (when selected) should be `ItemVerticalPadding` from the top val selectedIconY = NavigationRailItemVerticalPadding.roundToPx() val unselectedIconY = if (alwaysShowLabel) selectedIconY else (height - iconPlaceable.height) / 2 // How far the icon needs to move between unselected and selected states val iconDistance = unselectedIconY - selectedIconY // The interpolated fraction of iconDistance that all placeables need to move based on // animationProgress, since the icon is higher in the selected state. val offset = (iconDistance * (1 - animationProgress)).roundToInt() val width = constraints.constrainWidth( maxOf( iconPlaceable.width, labelPlaceable.width, indicatorPlaceable?.width ?: 0 ) ) val labelX = (width - labelPlaceable.width) / 2 val iconX = (width - iconPlaceable.width) / 2 val rippleX = (width - indicatorRipplePlaceable.width) / 2 val rippleY = selectedIconY - IndicatorVerticalPaddingWithLabel.roundToPx() return layout(width, height) { indicatorPlaceable?.let { val indicatorX = (width - it.width) / 2 val indicatorY = selectedIconY - IndicatorVerticalPaddingWithLabel.roundToPx() it.placeRelative(indicatorX, indicatorY + offset) } if (alwaysShowLabel || animationProgress != 0f) { labelPlaceable.placeRelative(labelX, labelY + offset) } iconPlaceable.placeRelative(iconX, selectedIconY + offset) indicatorRipplePlaceable.placeRelative(rippleX, rippleY + offset) } } private const val IndicatorRippleLayoutIdTag: String = "indicatorRipple" private const val IndicatorLayoutIdTag: String = "indicator" private const val IconLayoutIdTag: String = "icon" private const val LabelLayoutIdTag: String = "label" /** * Vertical padding between the contents of the [NavigationRail] and its top/bottom, and internally * between items. */ internal val NavigationRailVerticalPadding: Dp = 4.dp /** * Padding at the bottom of the [NavigationRail]'s header. This padding will only be added when the * header is not null. */ private val NavigationRailHeaderPadding: Dp = 8.dp private const val ItemAnimationDurationMillis: Int = 150 /*@VisibleForTesting*/ /** Width of an individual [NavigationRailItem]. */ internal val NavigationRailItemWidth: Dp = NavigationRailTokens.ContainerWidth /*@VisibleForTesting*/ /** Height of an individual [NavigationRailItem]. */ internal val NavigationRailItemHeight: Dp = NavigationRailTokens.NoLabelActiveIndicatorHeight /*@VisibleForTesting*/ /** Vertical padding between the contents of a [NavigationRailItem] and its top/bottom. */ internal val NavigationRailItemVerticalPadding: Dp = 4.dp private val IndicatorHorizontalPadding: Dp = (NavigationRailTokens.ActiveIndicatorWidth - NavigationRailTokens.IconSize) / 2 private val IndicatorVerticalPaddingWithLabel: Dp = (NavigationRailTokens.ActiveIndicatorHeight - NavigationRailTokens.IconSize) / 2 private val IndicatorVerticalPaddingNoLabel: Dp = (NavigationRailTokens.NoLabelActiveIndicatorHeight - NavigationRailTokens.IconSize) / 2
apache-2.0
7da6139093e76bf3ee31d1e32c10c643
40.036918
148
0.698103
4.961188
false
false
false
false
lvtanxi/Study
BootMybatis/src/main/kotlin/com/lv/service/impl/MyUserServiceImpl.kt
1
1004
package com.lv.service.impl import com.lv.enums.ResultEnum import com.lv.exception.ErrorException import com.lv.mapper.MyUserMapper import com.lv.service.MyUserService import com.lv.util.getStringLength import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional /** * Date: 2017-03-21 * Time: 10:53 * Description: */ @Service class MyUserServiceImpl(val myUserMapper: MyUserMapper) : MyUserService { override fun verifyUser(mParam: Map<String, Any>) { val userPassWorldLength = mParam["userPassWorld"].getStringLength() if (userPassWorldLength == 0) throw ErrorException(ResultEnum.EMPTY) else if (userPassWorldLength < 6) throw ErrorException(ResultEnum.SHORT) else print("成") //方法扩展 } @Transactional override fun addUser(mParam: Map<String, Any>) = myUserMapper.addUser(mParam) override fun findAllUser() = myUserMapper.findAllUser() }
apache-2.0
c0dcbdaeebb4acca5eaf68a5f838fe5b
27.428571
81
0.720322
3.944444
false
false
false
false
rosenpin/QuickDrawEverywhere
app/src/main/java/com/tomer/draw/windows/FloatingView.kt
1
707
package com.tomer.draw.windows /** * DrawEverywhere * Created by Tomer Rosenfeld on 7/28/17. */ interface FloatingView { var currentX: Int var currentY: Int val listeners: ArrayList<OnWindowStateChangedListener> fun origHeight(): Int fun origWidth(): Int fun gravity(): Int fun addToWindow(x: Int = 0, y: Int = 0, onWindowAdded: Runnable? = null, listener: OnWindowStateChangedListener? = null){ addListener(listener) } fun removeFromWindow(x: Int = 0, y: Int = 0, onWindowRemoved: Runnable? = null, listener: OnWindowStateChangedListener? = null){ addListener(listener) } fun addListener(listener: OnWindowStateChangedListener?) { if (listener != null) listeners.add(listener) } }
gpl-3.0
43655c12a605b9d0a97bcf719ed52813
28.458333
129
0.734088
3.465686
false
false
false
false
ukhamitov/KotlinExt
src/main/kotlin/com/ukhamitov/kotlinext/Preferences.kt
1
4944
package com.ukhamitov.kotlinext import android.content.Context import android.content.SharedPreferences import kotlin.reflect.KProperty abstract class Preferences { companion object { private var context: Context? = null fun init(context: Context) { this.context = context } } private val prefs: SharedPreferences by lazy { if (context != null) context!!.getSharedPreferences(javaClass.simpleName, Context.MODE_PRIVATE) else throw IllegalStateException("Context was not initialized. Call Preferences.init(context) before using it") } private val listeners = mutableListOf<SharedPrefsListener>() abstract class PrefDelegate<T>(val prefKey: String?) { abstract operator fun getValue(thisRef: Any?, property: KProperty<*>): T abstract operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) } interface SharedPrefsListener { fun onSharedPrefChanged(property: KProperty<*>) } fun addListener(sharedPrefsListener: SharedPrefsListener) { listeners.add(sharedPrefsListener) } fun removeListener(sharedPrefsListener: SharedPrefsListener) { listeners.remove(sharedPrefsListener) } fun clearListeners() = listeners.clear() fun stringPref(prefKey: String? = null, defaultValue: String? = null) = StringPrefDelegate(prefKey, defaultValue) inner class StringPrefDelegate(prefKey: String? = null, val defaultValue: String?) : PrefDelegate<String?>(prefKey) { override fun getValue(thisRef: Any?, property: KProperty<*>): String? = prefs.getString(prefKey ?: property.name, defaultValue) override fun setValue(thisRef: Any?, property: KProperty<*>, value: String?) { prefs.edit().putString(prefKey ?: property.name, value).apply() onPrefChanged(property) } } fun intPref(prefKey: String? = null, defaultValue: Int = 0) = IntPrefDelegate(prefKey, defaultValue) inner class IntPrefDelegate(prefKey: String? = null, val defaultValue: Int) : PrefDelegate<Int>(prefKey) { override fun getValue(thisRef: Any?, property: KProperty<*>) = prefs.getInt(prefKey ?: property.name, defaultValue) override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { prefs.edit().putInt(prefKey ?: property.name, value).apply() onPrefChanged(property) } } fun floatPref(prefKey: String? = null, defaultValue: Float = 0f) = FloatPrefDelegate(prefKey, defaultValue) inner class FloatPrefDelegate(prefKey: String? = null, val defaultValue: Float) : PrefDelegate<Float>(prefKey) { override fun getValue(thisRef: Any?, property: KProperty<*>) = prefs.getFloat(prefKey ?: property.name, defaultValue) override fun setValue(thisRef: Any?, property: KProperty<*>, value: Float) { prefs.edit().putFloat(prefKey ?: property.name, value).apply() onPrefChanged(property) } } fun booleanPref(prefKey: String? = null, defaultValue: Boolean = false) = BooleanPrefDelegate(prefKey, defaultValue) inner class BooleanPrefDelegate(prefKey: String? = null, val defaultValue: Boolean) : PrefDelegate<Boolean>(prefKey) { override fun getValue(thisRef: Any?, property: KProperty<*>) = prefs.getBoolean(prefKey ?: property.name, defaultValue) override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) { prefs.edit().putBoolean(prefKey ?: property.name, value).apply() onPrefChanged(property) } } fun longPref(prefKey: String? = null, defaultValue: Long = 0L) = LongPrefDelegate(prefKey, defaultValue) inner class LongPrefDelegate(prefKey: String? = null, val defaultValue: Long) : PrefDelegate<Long>(prefKey) { override fun getValue(thisRef: Any?, property: KProperty<*>) = prefs.getLong(prefKey ?: property.name, defaultValue) override fun setValue(thisRef: Any?, property: KProperty<*>, value: Long) { prefs.edit().putLong(prefKey ?: property.name, value).apply() onPrefChanged(property) } } fun stringSetPref(prefKey: String? = null, defaultValue: Set<String> = HashSet<String>()) = StringSetPrefDelegate(prefKey, defaultValue) inner class StringSetPrefDelegate(prefKey: String? = null, val defaultValue: Set<String>) : PrefDelegate<Set<String>>(prefKey) { override fun getValue(thisRef: Any?, property: KProperty<*>): Set<String> = prefs.getStringSet(prefKey ?: property.name, defaultValue) override fun setValue(thisRef: Any?, property: KProperty<*>, value: Set<String>) { prefs.edit().putStringSet(prefKey ?: property.name, value).apply() onPrefChanged(property) } } private fun onPrefChanged(property: KProperty<*>) { listeners.forEach { it.onSharedPrefChanged(property) } } }
mit
84e0e1c6ec909376b3f7d10dc69715d7
43.54955
142
0.682241
4.519196
false
false
false
false
MaTriXy/android-topeka
app/src/main/java/com/google/samples/apps/topeka/widget/quiz/AbsQuizView.kt
2
10100
/* * Copyright 2017 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.google.samples.apps.topeka.widget.quiz import android.animation.ArgbEvaluator import android.animation.ObjectAnimator import android.annotation.SuppressLint import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.os.Build import android.os.Bundle import android.os.Handler import android.support.annotation.ColorInt import android.support.annotation.LayoutRes import android.support.v4.content.ContextCompat import android.support.v4.view.MarginLayoutParamsCompat import android.support.v4.view.animation.LinearOutSlowInInterpolator import android.util.Property import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import com.google.samples.apps.topeka.R import com.google.samples.apps.topeka.activity.QuizActivity import com.google.samples.apps.topeka.helper.ApiLevelHelper import com.google.samples.apps.topeka.helper.FOREGROUND_COLOR import com.google.samples.apps.topeka.helper.onLayoutChange import com.google.samples.apps.topeka.model.Category import com.google.samples.apps.topeka.model.quiz.Quiz import com.google.samples.apps.topeka.widget.fab.CheckableFab const val KEY_ANSWER = "answer" /** * This is the base class for displaying a [com.google.samples.apps.topeka.model.quiz.Quiz]. * * * Subclasses need to implement [AbsQuizView.createQuizContentView] * in order to allow solution of a quiz. * * * * Also [AbsQuizView.allowAnswer] needs to be called with * `true` in order to mark the quiz solved. * * @param <Q> The type of [com.google.samples.apps.topeka.model.quiz.Quiz] you want to * display. </Q> */ abstract class AbsQuizView<out Q : Quiz<*>> /** * Enables creation of views for quizzes. * @param context The context for this view. * * @param category The [Category] this view is running in. * * @param quiz The actual [Quiz] that is going to be displayed. */ (context: Context, private val category: Category, val quiz: Q) : FrameLayout(context) { private val layoutInflater: LayoutInflater = LayoutInflater.from(context) val quizContentView: View? init { id = quiz.id val container = createContainerLayout(context) quizContentView = createQuizContentView()?.apply { id = R.id.quiz_content isSaveEnabled = true if (this is ViewGroup) { clipToPadding = false } setMinHeightInternal(this) addContentView(container, this) } onLayoutChange { addFloatingActionButton() } } private val ANSWER_HIDE_DELAY = 500L private val FOREGROUND_COLOR_CHANGE_DELAY = 750L private val doubleSpacing = resources.getDimensionPixelSize(R.dimen.spacing_double) private val linearOutSlowInInterpolator = LinearOutSlowInInterpolator() private val quizHandler = Handler() private val submitAnswer = initCheckableFab() private fun initCheckableFab(): CheckableFab { return (inflate<CheckableFab>(R.layout.answer_submit)).apply { hide() setOnClickListener { submitAnswer() if (inputMethodManager.isAcceptingText) { inputMethodManager.hideSoftInputFromWindow(it.windowToken, 0) } isEnabled = false } } } private val inputMethodManager: InputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager protected var isAnswered = false private set /** * Implementations must make sure that the answer provided is evaluated and correctly rated. * @return `true` if the question has been correctly answered, else * `false`. */ protected abstract val isAnswerCorrect: Boolean /** * Holds the user input for orientation change purposes. */ abstract var userInput: Bundle private fun createContainerLayout(context: Context): LinearLayout { return LinearLayout(context).apply { id = R.id.absQuizViewContainer orientation = LinearLayout.VERTICAL } } private fun addContentView(container: LinearLayout, quizContentView: View) { val layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT) container.run { addView((layoutInflater.inflate(R.layout.question, this, false) as TextView).apply { setBackgroundColor(ContextCompat.getColor(context, category.theme.primaryColor)) text = quiz.question }, layoutParams) addView(quizContentView, layoutParams) } addView(container, layoutParams) } private fun addFloatingActionButton() { val fabSize = resources.getDimensionPixelSize(R.dimen.size_fab) val bottomOfQuestionView = findViewById<View>(R.id.question_view).bottom val fabLayoutParams = FrameLayout.LayoutParams(fabSize, fabSize, Gravity.END or Gravity.TOP) val halfAFab = fabSize / 2 fabLayoutParams.setMargins(0, // left bottomOfQuestionView - halfAFab, // top 0, // right doubleSpacing) // bottom MarginLayoutParamsCompat.setMarginEnd(fabLayoutParams, doubleSpacing) if (ApiLevelHelper.isLowerThan(Build.VERSION_CODES.LOLLIPOP)) { // Account for the fab's emulated shadow. fabLayoutParams.topMargin -= submitAnswer.paddingTop / 2 } addView(submitAnswer, fabLayoutParams) } /** * Implementations should create the content view for the type of * [com.google.samples.apps.topeka.model.quiz.Quiz] they want to display. * @return the created view to solve the quiz. */ protected abstract fun createQuizContentView(): View? /** * Sets the quiz to answered or unanswered. * @param answered `true` if an answer was selected, else `false`. */ protected fun allowAnswer(answered: Boolean = true) { with(submitAnswer) { if (answered) show() else hide() } isAnswered = answered } /** * Allows children to submit an answer via code. */ protected open fun submitAnswer() { quiz.solved = true performScoreAnimation(isAnswerCorrect) } /** * Animates the view when the answer has been submitted. * @param answerCorrect `true` if the answer was correct, else `false`. */ private fun performScoreAnimation(answerCorrect: Boolean) { (context as QuizActivity).lockIdlingResource() // Decide which background color to use. val backgroundColor = ContextCompat.getColor(context, if (answerCorrect) R.color.green else R.color.red) adjustFab(answerCorrect, backgroundColor) resizeView() moveViewOffScreen(answerCorrect) // Animate the foreground color to match the background color. // This overlays all content within the current view. animateForegroundColor(backgroundColor) } @SuppressLint("NewApi") private fun adjustFab(answerCorrect: Boolean, backgroundColor: Int) { with(submitAnswer) { isChecked = answerCorrect backgroundTintList = ColorStateList.valueOf(backgroundColor) } quizHandler.postDelayed({ submitAnswer.hide() }, ANSWER_HIDE_DELAY) } private fun resizeView() { val widthHeightRatio = height.toFloat() / width.toFloat() // Animate X and Y scaling separately to allow different start delays. // object animators for x and y with different durations and then run them independently resizeViewProperty(View.SCALE_X, .5f, 200) resizeViewProperty(View.SCALE_Y, .5f / widthHeightRatio, 300) } private fun resizeViewProperty(property: Property<View, Float>, targetScale: Float, durationOffset: Int) { with(ObjectAnimator.ofFloat(this, property, 1f, targetScale)) { interpolator = linearOutSlowInInterpolator startDelay = (FOREGROUND_COLOR_CHANGE_DELAY + durationOffset) start() } } override fun onDetachedFromWindow() { quizHandler.removeCallbacksAndMessages(null) super.onDetachedFromWindow() } private fun animateForegroundColor(@ColorInt targetColor: Int) { with(ObjectAnimator.ofInt(this, FOREGROUND_COLOR, Color.TRANSPARENT, targetColor)) { setEvaluator(ArgbEvaluator()) startDelay = FOREGROUND_COLOR_CHANGE_DELAY start() } } private fun moveViewOffScreen(answerCorrect: Boolean) { category.setScore(quiz, answerCorrect) // Move the current view off the screen. quizHandler.postDelayed(this::proceed, FOREGROUND_COLOR_CHANGE_DELAY * 2) } private fun setMinHeightInternal(view: View) { view.minimumHeight = resources.getDimensionPixelSize(R.dimen.min_height_question) } private fun proceed() { if (context is QuizActivity) (context as QuizActivity).proceed() } protected fun <T: View> inflate(@LayoutRes resId: Int) = layoutInflater.inflate(resId, this, false) as T }
apache-2.0
f87ae91b828aa16f9c3f8a0cf03ad875
35.075
100
0.688515
4.697674
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/work/WorkPagerActivity.kt
2
8462
package ru.fantlab.android.ui.modules.work import android.app.Application import android.app.Service import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.viewpager.widget.ViewPager import com.evernote.android.state.State import com.google.android.material.tabs.TabLayout import kotlinx.android.synthetic.main.appbar_tabbed_elevation.* import kotlinx.android.synthetic.main.tabbed_pager_layout.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.FragmentPagerAdapterModel import ru.fantlab.android.data.dao.TabsCountStateModel import ru.fantlab.android.helper.ActivityHelper import ru.fantlab.android.helper.BundleConstant import ru.fantlab.android.helper.Bundler import ru.fantlab.android.helper.ViewHelper import ru.fantlab.android.provider.scheme.LinkParserHelper import ru.fantlab.android.ui.adapter.FragmentsPagerAdapter import ru.fantlab.android.ui.base.BaseActivity import ru.fantlab.android.ui.base.BaseFragment import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter import ru.fantlab.android.ui.modules.bookcases.editor.BookcaseEditorActivty import ru.fantlab.android.ui.modules.bookcases.selector.BookcaseSelectorFragment import ru.fantlab.android.ui.modules.editor.EditorActivity import ru.fantlab.android.ui.modules.work.responses.WorkResponsesFragment import java.util.* class WorkPagerActivity : BaseActivity<WorkPagerMvp.View, BasePresenter<WorkPagerMvp.View>>(), WorkPagerMvp.View { @State var index: Int = 0 @State var workId: Int = 0 @State var workName: String = "" @State var mark: Int = 0 @State var tabsCountSet = HashSet<TabsCountStateModel>() private lateinit var toolbarMenu: Menu private var isError = false private var adapter: FragmentsPagerAdapter? = null override fun layout(): Int = R.layout.tabbed_pager_layout override fun isTransparent(): Boolean = true override fun canBack(): Boolean = true override fun providePresenter(): BasePresenter<WorkPagerMvp.View> = BasePresenter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (savedInstanceState == null) { workId = intent?.extras?.getInt(BundleConstant.EXTRA, -1) ?: -1 workName = intent?.extras?.getString(BundleConstant.EXTRA_TWO) ?: "" index = intent?.extras?.getInt(BundleConstant.EXTRA_THREE, -1) ?: -1 } if (workId == -1) { finish() return } setTaskName(workName) title = workName selectMenuItem(R.id.mainView, false) adapter = FragmentsPagerAdapter( supportFragmentManager, FragmentPagerAdapterModel.buildForWork(this, workId) ) pager.adapter = adapter tabs.tabGravity = TabLayout.GRAVITY_FILL tabs.tabMode = TabLayout.MODE_SCROLLABLE tabs.setupWithViewPager(pager) invalidateTabs(adapter) if (savedInstanceState == null) { if (index != -1) { pager.currentItem = index } } tabs.addOnTabSelectedListener(object : TabLayout.ViewPagerOnTabSelectedListener(pager) { override fun onTabReselected(tab: TabLayout.Tab) { super.onTabReselected(tab) onScrollTop(tab.position) } }) pager.addOnPageChangeListener(object : ViewPager.SimpleOnPageChangeListener() { override fun onPageSelected(position: Int) { super.onPageSelected(position) hideShowFab(position) hideShowToolbar(position) } }) if (savedInstanceState != null && !tabsCountSet.isEmpty()) { tabsCountSet.forEach { setupTab(count = it.count, index = it.tabIndex) } } hideShowFab(pager.currentItem) fab.setOnClickListener { onFabClicked() } } private fun invalidateTabs(adapter: FragmentsPagerAdapter?) { for (i in 0 until tabs.tabCount) { val tab = tabs.getTabAt(i) if (tab != null) { val custom = tab.customView if (custom == null) tab.customView = adapter?.getCustomTabView(this) setupTab(0, i) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.work_menu, menu) toolbarMenu = menu hideShowToolbar(pager.currentItem) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.share -> { ActivityHelper.shareUrl(this, Uri.Builder().scheme(LinkParserHelper.PROTOCOL_HTTPS) .authority(LinkParserHelper.HOST_DEFAULT) .appendPath("work$workId") .toString()) return true } R.id.sort -> { val fragment = pager.adapter?.instantiateItem(pager, 1) as? WorkResponsesFragment fragment?.showSortDialog() } } return super.onOptionsItemSelected(item) } override fun onScrollTop(index: Int) { if (pager.adapter == null) return val fragment = pager.adapter?.instantiateItem(pager, index) as? BaseFragment<*, *> if (fragment is BaseFragment) { fragment.onScrollTop(index) } } override fun onSetBadge(tabIndex: Int, count: Int) { tabsCountSet.add(TabsCountStateModel(count = count, tabIndex = tabIndex)) setupTab(count, tabIndex) } override fun onSetTitle(title: String) { this.title = title } private fun hideShowFab(position: Int) { if (isError) { fab.hide() return } when (adapter?.getItemKey(position)) { getString(R.string.responses) -> { if (isLoggedIn()) { fab.setImageResource(R.drawable.ic_response) fab.show() } } else -> fab.hide() } } private fun hideShowToolbar(position: Int) { if (::toolbarMenu.isInitialized) { when (adapter?.getItemKey(position)) { getString(R.string.overview) -> { toolbarMenu.findItem(R.id.sort).isVisible = false toolbarMenu.findItem(R.id.share).isVisible = true } getString(R.string.responses) -> { toolbarMenu.findItem(R.id.share).isVisible = false toolbarMenu.findItem(R.id.sort).isVisible = true } else -> { toolbarMenu.findItem(R.id.share).isVisible = false toolbarMenu.findItem(R.id.sort).isVisible = false } } } } override fun onError() { isError = true fab.hide() } private fun onFabClicked() { when (adapter?.getItemKey(pager.currentItem)) { getString(R.string.responses) -> { startActivityForResult(Intent(this, EditorActivity::class.java) .putExtra(BundleConstant.EXTRA_TYPE, BundleConstant.EDITOR_NEW_RESPONSE) .putExtra(BundleConstant.ID, workId), BundleConstant.REFRESH_RESPONSE_CODE) } } } private fun setupTab(count: Int, index: Int) { val tabView = ViewHelper.getTabView(tabs, index) when (adapter?.getItemKey(index)) { getString(R.string.overview) -> tabView.first.text = getString(R.string.overview) getString(R.string.responses) -> { tabView.first.text = getString(R.string.responses) tabView.second.text = count.toString() } getString(R.string.analogs) -> { tabView.first.text = getString(R.string.analogs) tabView.second.text = count.toString() } } } override fun onScrolled(isUp: Boolean) { if (isUp) { fab.hide() } else { hideShowFab(pager.currentItem) } } override fun onSetMarked(isMarked: Boolean, mark: Int) { this.mark = mark } override fun onGetMark(): Int { return mark } override fun onResponsesRefresh() { val fragment = pager.adapter?.instantiateItem(pager, 1) as? WorkResponsesFragment fragment?.onRefresh() } override fun isCycle(): Boolean = false override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { BundleConstant.REFRESH_RESPONSE_CODE -> { val fragment = pager.adapter?.instantiateItem(pager, 1) as? WorkResponsesFragment fragment?.onRefresh() } BundleConstant.BOOKCASE_EDITOR -> { if (resultCode == RESULT_OK && adapter?.getItemKey(pager.currentItem) == getString(R.string.bookcases)) { val fragment = pager.adapter?.instantiateItem(pager, pager.currentItem) as? BookcaseSelectorFragment fragment?.onRefresh() } } } } companion object { fun startActivity(context: Context, workId: Int, workName: String, index: Int = -1) { val intent = Intent(context, WorkPagerActivity::class.java) intent.putExtras(Bundler.start() .put(BundleConstant.EXTRA, workId) .put(BundleConstant.EXTRA_TWO, workName) .put(BundleConstant.EXTRA_THREE, index) .end()) if (context is Service || context is Application) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } context.startActivity(intent) } } }
gpl-3.0
1c45d68bd1832a7f8a7c6c70e42bf626
29.774545
105
0.729969
3.553969
false
false
false
false
C6H2Cl2/SolidXp
src/main/java/c6h2cl2/solidxp/item/ItemXpChecker.kt
1
2130
package c6h2cl2.solidxp.item import c6h2cl2.solidxp.block.IXpHolderBlock import c6h2cl2.solidxp.MOD_ID import c6h2cl2.solidxp.SolidXpRegistry import c6h2cl2.solidxp.translateToLocal import net.minecraft.entity.player.EntityPlayer import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.util.ActionResult import net.minecraft.util.EnumActionResult import net.minecraft.util.EnumActionResult.PASS import net.minecraft.util.EnumActionResult.SUCCESS import net.minecraft.util.EnumFacing import net.minecraft.util.EnumHand import net.minecraft.util.ResourceLocation import net.minecraft.util.math.BlockPos import net.minecraft.util.text.TextComponentString import net.minecraft.world.World /** * @author C6H2Cl2 */ class ItemXpChecker : Item() { init { unlocalizedName = "xpChecker" registryName = ResourceLocation(MOD_ID, "xp_checker") creativeTab = SolidXpRegistry.tabSolidXp maxStackSize = 1 } override fun onItemRightClick(worldIn: World, playerIn: EntityPlayer, handIn: EnumHand): ActionResult<ItemStack> { if (worldIn.isRemote){ playerIn.sendMessage(TextComponentString("${translateToLocal("solidxp.text.player_xp")}: ${playerIn.experienceTotal} / ${Int.MAX_VALUE}")) } return super.onItemRightClick(worldIn, playerIn, handIn) } override fun onItemUse(player: EntityPlayer, worldIn: World, pos: BlockPos, hand: EnumHand, facing: EnumFacing, hitX: Float, hitY: Float, hitZ: Float): EnumActionResult { val block = worldIn.getBlockState(pos).block as? IXpHolderBlock ?: return PASS if (!worldIn.isRemote){ player.sendMessage(TextComponentString("${translateToLocal(block.getUnlocalizedMachineName())}: ${block.getXpValue(worldIn, pos)} / ${block.getXpLimit(worldIn, pos)}")) } return SUCCESS } override fun addInformation(stack: ItemStack, playerIn: EntityPlayer, tooltip: MutableList<String>, advanced: Boolean) { tooltip.add("Right Click to see your experience") tooltip.add("Using for Xp-Machines, you can see xp value in it") } }
mpl-2.0
3529b37ef256ce9014a6cfcaa3d6d9c8
40.784314
180
0.744601
4.04943
false
false
false
false
helpermethod/membrane-kotlin-dsl
src/main/kotlin/com/predic8/membrane/dsl/Dsl.kt
1
7938
package com.predic8.membrane.dsl import com.predic8.membrane.annot.MCAttribute import com.predic8.membrane.annot.MCChildElement import com.predic8.membrane.annot.MCElement import com.predic8.membrane.annot.MCTextContent import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.LambdaTypeName import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeName import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asTypeName import org.funktionale.composition.andThen import org.funktionale.either.eitherTry import org.funktionale.partials.invoke import org.reflections.ReflectionUtils.getAllMethods import org.reflections.ReflectionUtils.withAnnotation import org.reflections.Reflections import org.springframework.beans.factory.annotation.Required import java.lang.reflect.Method import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.nio.file.Paths data class Parts(val name: String, val constructor: FunSpec, val property: PropertySpec, val functions: List<FunSpec>) data class TypeDesc(val pattern: String, val methodName: String, val type: Type) fun generate(reflections: Reflections = Reflections()) { reflections .getTypesAnnotatedWith(MCElement::class.java) .forEach((::generateParts)(reflections) andThen generateClass andThen ::writeKotlinFile) System.exit(0) } fun generateParts(reflections: Reflections, type: java.lang.Class<*>): Parts { val field = generateField(type) return Parts( "${type.enclosingClass?.simpleName ?: ""}${type.simpleName}Spec", generateConstructor(field), generateProperty(field.name, field.type), generateFuns(reflections, type, field) ) } fun generateProperty(name: String, type: TypeName) = PropertySpec.builder(name, type) .initializer(name) .build() fun generateField(type: java.lang.Class<*>) = ParameterSpec .builder(type.simpleName.toCamelCase(), type) .build() fun generateConstructor(parameter: ParameterSpec) = FunSpec .constructorBuilder() .addParameter(parameter) .build() fun generateFuns(reflections: Reflections, type: java.lang.Class<*>, field: ParameterSpec) = getAllMethods(type, withAnnotation(MCChildElement::class.java)) .flatMap(::determineParameterDesc andThen (::generateSubtypeFuns)(reflections)(field)) fun determineParameterDesc(method: Method): TypeDesc { val parameterizedType = method.parameters.first().parameterizedType return when (parameterizedType) { is ParameterizedType -> TypeDesc("%N.%N.add(%N)", method.name, parameterizedType.actualTypeArguments.first()) else -> TypeDesc("%N.%N = %N", method.name, parameterizedType) } } fun generateSubtypeFuns(reflections: Reflections, field: ParameterSpec, typeDesc: TypeDesc): List<FunSpec> { val (pattern, methodName, type) = typeDesc val subTypes = reflections .getSubTypesOf(type as java.lang.Class<*>) .filter { it.isAnnotationPresent(MCElement::class.java) } return if (subTypes.isEmpty()) listOf(generateFun(field, methodName, pattern, type)) else subTypes.map((::generateFun)(field)(methodName)(pattern)) } fun generateFun(field: ParameterSpec, methodName: String, pattern: String, type: Type): FunSpec { val (reqAttrs, optAttrs) = collectAttrs(type as java.lang.Class<*>) val subTypeName = type.simpleName.toCamelCase() val attrs = reqAttrs.map { it.name to generateParameter(type, it.name, it.parameters.first().type) } + optAttrs.map { it.name to generateParameter(type, it.name, it.parameters.first().type, defaultValue = true) } return FunSpec.builder(type.getAnnotation(MCElement::class.java).name).run { addParameters(attrs.map { (_, parameter) -> parameter }) val hasChildren = type.methods.any { it.isAnnotationPresent(MCChildElement::class.java) } if (hasChildren) { addParameter( ParameterSpec.builder("init", LambdaTypeName.get(receiver = ClassName("com.predic8.membrane.dsl", "${type.enclosingClass?.simpleName ?: ""}${type.simpleName}Spec"), returnType = Unit::class.asTypeName())) .defaultValue("{}") .build() ) } beginControlFlow("val %N = %T()%L", subTypeName, type, if (attrs.size != 0) ".apply {" else "") attrs.forEach { (methodName, parameter) -> addStatement("%N(%N)", methodName, parameter) } endControlFlow() if (hasChildren) { val enclosingClass = type.enclosingClass when { enclosingClass != null -> addStatement("%N%NSpec(%N).init()", type.enclosingClass.simpleName, type.simpleName, subTypeName) else -> addStatement("%NSpec(%N).init()", type.simpleName, subTypeName) } } addStatement(pattern, field, methodName.removePrefix("set").decapitalize(), subTypeName) build() } } fun collectAttrs(type: java.lang.Class<*>): Pair<List<Method>, List<Method>> { val (reqAttributes, optAttributes) = type .methods .filter { it.isAnnotationPresent(MCAttribute::class.java) } .partition { it.isAnnotationPresent(Required::class.java) } val textContents = type .methods .filter { it.isAnnotationPresent(MCTextContent::class.java) } // treat @TextContent as a required attribute return (reqAttributes + textContents) to optAttributes } fun generateParameter(type: Type, name: String, parameterType: Type, defaultValue: Boolean = false): ParameterSpec { val getterName = "${determinePrefix((parameterType as java.lang.Class<*>).simpleName)}${name.removePrefix("set")}" val propertyName = getterName.removePrefix("get").decapitalize() val default = when { (type as Class<*>).methods.find { it.name == getterName } != null -> invokeGetter(type, getterName) else -> invokeField(type, name.removePrefix("set").decapitalize()) } return ParameterSpec .builder(propertyName, convertType(parameterType)) .apply { if (defaultValue) { when (default) { is Boolean, is Int, is Long -> defaultValue("%L", default) is Enum<*> -> defaultValue("%T.%L", default::class, default.name) else -> defaultValue("%S", default) } } } .build() } fun determinePrefix(simpleName: String) = when (simpleName) { "boolean" -> "is" else -> "get" } val convertType = Type::asClassName andThen ::convertToKotlinType fun Type.asClassName() = asTypeName() as ClassName fun convertToKotlinType(className: ClassName): ClassName = when (className.simpleName()) { "boolean" -> ClassName("kotlin", "Boolean") "String" -> ClassName("kotlin", "String").asNullable() "Int", "Boolean", "Long" -> className else -> className.asNullable() } fun invokeField(type: Type, fieldName: String) = tryInvokeField(type, fieldName) .fold({ _ -> null }) { v -> v } fun tryInvokeField(type: Type, fieldName: String) = eitherTry { (type as Class<*>) .getDeclaredField(fieldName) .apply { isAccessible = true } .get(type.newInstance()) } fun invokeGetter(type: Type, getterName: String) = tryInvokeGetter(type, getterName) .fold({ _ -> null }) { v -> v } fun tryInvokeGetter(type: Type, getterName: String) = eitherTry { (type as Class<*>) .getMethod(getterName) .invoke(type.newInstance()) } fun String.toCamelCase(): String { val indexOfLastConsecutiveUppercaseLetter = this.indexOfFirst { it in 'a'..'z' } - 1 return when (indexOfLastConsecutiveUppercaseLetter) { 0 -> this.decapitalize() else -> this.slice(0 until indexOfLastConsecutiveUppercaseLetter).toLowerCase() + this.slice(indexOfLastConsecutiveUppercaseLetter..this.lastIndex) } } val generateClass = { (name, constructor, property, functions): Parts -> TypeSpec .classBuilder(name) .primaryConstructor(constructor) .addProperty(property) .addFunctions(functions) .build() } fun writeKotlinFile(type: TypeSpec) = FileSpec .builder("com.predic8.membrane.dsl", type.name as String) .addType(type) .indent(" ".repeat(4)) .build() .writeTo(Paths.get("build/generated")) fun main(args: Array<String>) { generate() }
apache-2.0
e023b1cac10f29fe42b1c2695fd73738
34.441964
208
0.740993
3.685237
false
false
false
false
mildsauce45/spiffy
src/test/kotlin/com/pinchotsoft/spiffy/SqlHelpersTest.kt
1
1725
package com.pinchotsoft.spiffy import org.junit.Test class SqlHelpersTest { @Test fun sqlHelpers_transformSql_noParams() { val query = "select * from orders where Id = 1" val (transformedSql, _) = transformSql(query, emptyMap()) assert(query == transformedSql) } @Test fun sqlHelpers_transformSql_singleParam() { val (transformedSql, transformedInputs) = transformSql("select * from orders where Id = @id", mapOf("ID" to 1)) assert(transformedSql == "select * from orders where Id = ?") assert(transformedInputs.count() == 1) assert(transformedInputs[1] == 1) } @Test fun sqlHelpers_transformSql_multipleParams() { val (transformedSql, transformedInputs) = transformSql("select * from orders where Id = @id and customerId = @customerId order by Id", mapOf("ID" to 1, "CustomerId" to 3)) assert(transformedSql == "select * from orders where Id = ? and customerId = ? order by Id") assert(transformedInputs.count() == 2) assert(transformedInputs[1] == 1) assert(transformedInputs[2] == 3) } @Test fun sqlHelpers_transformSql_handlesIterables() { val initialQuery = "select * from orders where Id in @Ids" val desiredQuery = "select * from orders where Id in (?,?,?)" val inputs = mapOf("Ids" to listOf(1, 2, 3)) val (transformedSql, transformedInputs) = transformSql(initialQuery, inputs) assert(transformedSql == desiredQuery) assert(transformedInputs.count() == 3) assert(transformedInputs.containsValue(1)) assert(transformedInputs.containsValue(2)) assert(transformedInputs.containsValue(3)) } }
mit
c0e2499c02b00328fcf896f9d7c12552
34.22449
179
0.651014
4.176755
false
true
false
false
HumaneWolf/oslotransportbot
src/twitter/TwitterApi.kt
1
3087
package com.humanewolf.tbanebot.twitter import com.humanewolf.tbanebot.common.Http import com.humanewolf.tbanebot.config.AppConfigLoader import com.humanewolf.tbanebot.telegram.UpdateNotifier import com.humanewolf.tbanebot.twitter.models.StatusResponse import com.humanewolf.tbanebot.twitter.models.TokenResponse import io.ktor.client.request.* import kotlinx.coroutines.runBlocking import mu.KotlinLogging import java.net.URLEncoder import java.nio.charset.Charset import java.util.* import kotlin.concurrent.schedule val logger = KotlinLogging.logger { } object TwitterApi { private val config = AppConfigLoader.getConfig() private var bearerToken: String = "" private var userId: String = "44597892" fun authenticate() = runBlocking { val b64Encoder = Base64.getEncoder() val encodedKey = URLEncoder.encode(config.twitter.key, Charset.forName("utf-8")) val encodedSecret = URLEncoder.encode(config.twitter.secret, Charset.forName("utf-8")) val basicToken = b64Encoder.encode("$encodedKey:$encodedSecret".toByteArray(Charset.forName("utf-8"))).toString( Charset.forName("utf-8")) val response = Http.client.post<TokenResponse> { url("https://api.twitter.com/oauth2/token") header("Authorization", "Basic $basicToken") header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8") body = "grant_type=client_credentials" } bearerToken = response.accessToken logger.info { "Authenticated with Twitter." } } fun getUpdates() = runBlocking { var lastTweet = TwitterDataStore.lastTweet try { val response = Http.client.get<List<StatusResponse>> { url { url("https://api.twitter.com/1.1/statuses/user_timeline.json") parameter("user_id", userId) parameter("since_id", lastTweet) parameter("exclude_replies", "false") } header("Authorization", "Bearer $bearerToken") } for (t in response.reversed()) { lastTweet = t.id // Include reply to other account when counting last seen tweet. if (t.replyToUserId != null && t.replyToUserId != userId) { // Ignore replies to other accounts before sending. logger.info { "Ignored reply to other user, tweet: ${t.id}" } continue } // Send relevant tweets to the bot-part of the app. UpdateNotifier.sendUpdate(t.text, "Twitter") logger.info { "Queued tweet ${t.id}" } } TwitterDataStore.updateLastTweet(lastTweet) } catch (e: Throwable) { logger.error { "Failed to get tweets:\n" } e.printStackTrace() } } fun run() { TwitterDataStore.loadFromFile() authenticate() val timer = Timer() timer.schedule(1000L, 30000L) { getUpdates() } } }
mit
a64a4711fb5e71ab2a603872aa7d8228
35.317647
127
0.619372
4.360169
false
true
false
false
wax911/AniTrendApp
app/src/main/java/com/mxt/anitrend/extension/SupportExt.kt
1
1897
package com.mxt.anitrend.extension /** * No locks are used to synchronize an access to the [Lazy] instance value; if the instance is accessed from multiple threads, * its behavior is undefined. * * This mode should not be used unless the [Lazy] instance is guaranteed never to be initialized from more than one thread. */ val LAZY_MODE_UNSAFE = LazyThreadSafetyMode.NONE /** * Initializer function can be called several times on concurrent access to uninitialized [Lazy] instance value, * but only the first returned value will be used as the value of [Lazy] instance. */ val LAZY_MODE_PUBLICATION = LazyThreadSafetyMode.PUBLICATION /** * Locks are used to ensure that only a single thread can initialize the [Lazy] instance. */ val LAZY_MODE_SYNCHRONIZED = LazyThreadSafetyMode.SYNCHRONIZED /** * Potentially useless but returns an empty string, the signature may change in future * * @see String.isNullOrBlank */ fun String.Companion.empty() = "" /** * Returns a copy of this strings having its first letter uppercase, or the original string, * if it's empty or already starts with an upper case letter. * * @param exceptions words or characters to exclude during capitalization */ fun String?.capitalizeWords(exceptions: List<String>? = null): String = when { !this.isNullOrEmpty() -> { val result = StringBuilder(length) val words = split("_|\\s".toRegex()).dropLastWhile { it.isEmpty() } for ((index, word) in words.withIndex()) { when (word.isNotEmpty()) { true -> { if (!exceptions.isNullOrEmpty() && exceptions.contains(word)) result.append(word) else result.append(word.capitalize()) } } if (index != words.size - 1) result.append(" ") } result.toString() } else -> String.empty() }
lgpl-3.0
e48e7d234ef9821c3d1909b04cded897
32.280702
126
0.665261
4.432243
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/step_quiz_matching/ui/adapter/delegate/MatchingItemTitleAdapterDelegate.kt
2
2269
package org.stepik.android.view.step_quiz_matching.ui.adapter.delegate import android.view.View import android.view.ViewGroup import androidx.core.view.ViewCompat import androidx.core.view.isVisible import kotlinx.android.synthetic.main.item_step_quiz_sorting.view.* import org.stepic.droid.R import org.stepik.android.view.latex.ui.widget.ProgressableWebViewClient import org.stepik.android.view.step_quiz_matching.ui.model.MatchingItem import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class MatchingItemTitleAdapterDelegate : AdapterDelegate<MatchingItem, DelegateViewHolder<MatchingItem>>() { override fun isForViewType(position: Int, data: MatchingItem): Boolean = data is MatchingItem.Title override fun onCreateViewHolder(parent: ViewGroup): DelegateViewHolder<MatchingItem> = ViewHolder(createView(parent, R.layout.item_step_quiz_sorting)) private inner class ViewHolder(root: View) : DelegateViewHolder<MatchingItem>(root) { private val stepQuizSortingOption = root.stepQuizSortingOption private val stepQuizSortingOptionProgress = root.stepQuizSortingOptionProgress private val stepQuizSortingOptionUp = root.stepQuizSortingOptionUp private val stepQuizSortingOptionDown = root.stepQuizSortingOptionDown init { stepQuizSortingOptionUp.isVisible = false stepQuizSortingOptionDown.isVisible = false root.layoutParams = (root.layoutParams as ViewGroup.MarginLayoutParams).apply { rightMargin = context.resources.getDimensionPixelOffset(R.dimen.step_quiz_matching_item_margin) } stepQuizSortingOption.webViewClient = ProgressableWebViewClient(stepQuizSortingOptionProgress, stepQuizSortingOption.webView) } override fun onBind(data: MatchingItem) { data as MatchingItem.Title itemView.isEnabled = data.isEnabled stepQuizSortingOption.setText(data.text) val elevation = if (data.isEnabled) context.resources.getDimension(R.dimen.step_quiz_sorting_item_elevation) else 0f ViewCompat.setElevation(itemView, elevation) } } }
apache-2.0
42a7e91e79bb52171fab49d1f0478b74
43.509804
137
0.751432
4.975877
false
false
false
false
adrielcafe/MoovAndroidApp
app/src/main/java/cafe/adriel/moov/view/activity/SearchActivity.kt
1
4613
package cafe.adriel.moov.view.activity import android.content.Intent import android.os.Bundle import android.support.v4.app.ActivityOptionsCompat import android.support.v7.widget.DefaultItemAnimator import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.SearchView import android.view.Menu import android.view.View import cafe.adriel.moov.Constant import cafe.adriel.moov.R import cafe.adriel.moov.contract.MovieContract import cafe.adriel.moov.model.entity.Movie import cafe.adriel.moov.presenter.MovieSearchPresenter import cafe.adriel.moov.showToast import cafe.adriel.moov.view.adapter.SearchMovieAdapterItem import com.mikepenz.fastadapter.adapters.FooterAdapter import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter import com.mikepenz.fastadapter_extensions.items.ProgressItem import com.mikepenz.fastadapter_extensions.scroll.EndlessRecyclerOnScrollListener import com.tinsuke.icekick.extension.serialState import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.addTo import io.reactivex.rxkotlin.toObservable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_search.* class SearchActivity: BaseActivity(), MovieContract.IMovieSearchView { private lateinit var presenter: MovieContract.IMovieSearchPresenter private lateinit var adapter: FastItemAdapter<SearchMovieAdapterItem> private lateinit var loadingAdapter: FooterAdapter<ProgressItem> private var currentQuery: String? by serialState() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_search) presenter = MovieSearchPresenter(this) setSupportActionBar(vToolbar) supportActionBar?.run { setDisplayHomeAsUpEnabled(true) title = null } adapter = FastItemAdapter() loadingAdapter = FooterAdapter<ProgressItem>() with(adapter) { withSelectable(false) withOnClickListener { v, adapter, item, position -> showMovieDetails(item.movie, v.findViewById(R.id.vPoster)) true } } with(vMovies){ layoutManager = GridLayoutManager(this@SearchActivity, 3) itemAnimator = DefaultItemAnimator() adapter = loadingAdapter.wrap([email protected]) setHasFixedSize(true) addOnScrollListener(object: EndlessRecyclerOnScrollListener(loadingAdapter){ override fun onLoadMore(currentPage: Int) { loadingAdapter.clear() loadingAdapter.add(ProgressItem().withEnabled(false)) currentQuery?.let { presenter.searchMovies(it, currentPage) } } }) } } override fun onDestroy() { super.onDestroy() presenter.onDestroy() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.search, menu) val iSearch = menu.findItem(R.id.action_search) val vSearch = iSearch.actionView as SearchView vSearch.setOnQueryTextListener(object: SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String): Boolean { vSearch.clearFocus() currentQuery = query currentQuery?.let { adapter.clear() presenter.searchMovies(it, 1) } return true } override fun onQueryTextChange(newText: String): Boolean { return false } }) return super.onCreateOptionsMenu(menu) } override fun showMovies(movies: List<Movie>) { movies.toObservable() .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .forEach { movie -> adapter.add(SearchMovieAdapterItem(movie)) } .addTo(disposables) loadingAdapter.clear() } override fun showMovieDetails(movie: Movie, sharedView: View) { val options = ActivityOptionsCompat.makeSceneTransitionAnimation(this, sharedView, "poster") val intent = Intent(this, MovieDetailActivity::class.java) intent.putExtra(Constant.EXTRA_MOVIE, movie) startActivity(intent, options.toBundle()) } override fun showError(error: String) { showToast(error) } }
mit
52e3592b32c5fb1eeb54e01b044d8a7a
35.330709
100
0.673315
5.177329
false
false
false
false
NerdNumber9/TachiyomiEH
app/src/main/java/eu/kanade/tachiyomi/data/track/bangumi/BangumiApi.kt
1
6643
package eu.kanade.tachiyomi.data.track.bangumi import android.net.Uri import com.github.salomonbrys.kotson.array import com.github.salomonbrys.kotson.obj import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonParser import eu.kanade.tachiyomi.data.database.models.Track import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.data.track.model.TrackSearch import eu.kanade.tachiyomi.network.POST import eu.kanade.tachiyomi.network.asObservableSuccess import okhttp3.CacheControl import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import rx.Observable import uy.kohesive.injekt.injectLazy import java.net.URLEncoder class BangumiApi(private val client: OkHttpClient, interceptor: BangumiInterceptor) { private val gson: Gson by injectLazy() private val parser = JsonParser() private val authClient = client.newBuilder().addInterceptor(interceptor).build() fun addLibManga(track: Track): Observable<Track> { val body = FormBody.Builder() .add("rating", track.score.toInt().toString()) .add("status", track.toBangumiStatus()) .build() val request = Request.Builder() .url("$apiUrl/collection/${track.media_id}/update") .post(body) .build() return authClient.newCall(request) .asObservableSuccess() .map { track } } fun updateLibManga(track: Track): Observable<Track> { // chapter update val body = FormBody.Builder() .add("watched_eps", track.last_chapter_read.toString()) .build() val request = Request.Builder() .url("$apiUrl/subject/${track.media_id}/update/watched_eps") .post(body) .build() // read status update val sbody = FormBody.Builder() .add("status", track.toBangumiStatus()) .build() val srequest = Request.Builder() .url("$apiUrl/collection/${track.media_id}/update") .post(sbody) .build() return authClient.newCall(request) .asObservableSuccess() .map { track }.flatMap { authClient.newCall(srequest) .asObservableSuccess() .map { track } } } fun search(search: String): Observable<List<TrackSearch>> { val url = Uri.parse( "$apiUrl/search/subject/${URLEncoder.encode(search, Charsets.UTF_8.name())}").buildUpon() .appendQueryParameter("max_results", "20") .build() val request = Request.Builder() .url(url.toString()) .get() .build() return authClient.newCall(request) .asObservableSuccess() .map { netResponse -> val responseBody = netResponse.body()?.string().orEmpty() if (responseBody.isEmpty()) { throw Exception("Null Response") } val response = parser.parse(responseBody).obj["list"]?.array response?.filter { it.obj["type"].asInt == 1 }?.map { jsonToSearch(it.obj) } } } private fun jsonToSearch(obj: JsonObject): TrackSearch { return TrackSearch.create(TrackManager.BANGUMI).apply { media_id = obj["id"].asInt title = obj["name_cn"].asString cover_url = obj["images"].obj["common"].asString summary = obj["name"].asString tracking_url = obj["url"].asString } } private fun jsonToTrack(mangas: JsonObject): Track { return Track.create(TrackManager.BANGUMI).apply { title = mangas["name"].asString media_id = mangas["id"].asInt score = if (mangas["rating"] != null) (if (mangas["rating"].isJsonObject) mangas["rating"].obj["score"].asFloat else 0f) else 0f status = Bangumi.DEFAULT_STATUS tracking_url = mangas["url"].asString } } fun findLibManga(track: Track): Observable<Track?> { val urlMangas = "$apiUrl/subject/${track.media_id}" val requestMangas = Request.Builder() .url(urlMangas) .get() .build() return authClient.newCall(requestMangas) .asObservableSuccess() .map { netResponse -> // get comic info val responseBody = netResponse.body()?.string().orEmpty() jsonToTrack(parser.parse(responseBody).obj) } } fun statusLibManga(track: Track): Observable<Track?> { val urlUserRead = "$apiUrl/collection/${track.media_id}" val requestUserRead = Request.Builder() .url(urlUserRead) .cacheControl(CacheControl.FORCE_NETWORK) .get() .build() // todo get user readed chapter here return authClient.newCall(requestUserRead) .asObservableSuccess() .map { netResponse -> val resp = netResponse.body()?.string() val coll = gson.fromJson(resp, Collection::class.java) track.status = coll.status?.id!! track.last_chapter_read = coll.ep_status!! track } } fun accessToken(code: String): Observable<OAuth> { return client.newCall(accessTokenRequest(code)).asObservableSuccess().map { netResponse -> val responseBody = netResponse.body()?.string().orEmpty() if (responseBody.isEmpty()) { throw Exception("Null Response") } gson.fromJson(responseBody, OAuth::class.java) } } private fun accessTokenRequest(code: String) = POST(oauthUrl, body = FormBody.Builder() .add("grant_type", "authorization_code") .add("client_id", clientId) .add("client_secret", clientSecret) .add("code", code) .add("redirect_uri", redirectUrl) .build() ) companion object { private const val clientId = "bgm10555cda0762e80ca" private const val clientSecret = "8fff394a8627b4c388cbf349ec865775" private const val baseUrl = "https://bangumi.org" private const val apiUrl = "https://api.bgm.tv" private const val oauthUrl = "https://bgm.tv/oauth/access_token" private const val loginUrl = "https://bgm.tv/oauth/authorize" private const val redirectUrl = "tachiyomi://bangumi-auth" private const val baseMangaUrl = "$apiUrl/mangas" fun mangaUrl(remoteId: Int): String { return "$baseMangaUrl/$remoteId" } fun authUrl() = Uri.parse(loginUrl).buildUpon() .appendQueryParameter("client_id", clientId) .appendQueryParameter("response_type", "code") .appendQueryParameter("redirect_uri", redirectUrl) .build() fun refreshTokenRequest(token: String) = POST(oauthUrl, body = FormBody.Builder() .add("grant_type", "refresh_token") .add("client_id", clientId) .add("client_secret", clientSecret) .add("refresh_token", token) .add("redirect_uri", redirectUrl) .build()) } }
apache-2.0
52afbe0f75d0a56044d920f9a69febc8
30.9375
95
0.652416
4.093038
false
false
false
false
apollostack/apollo-android
composite/samples/kotlin-sample/src/main/java/com/apollographql/apollo3/kotlinsample/repositories/MainActivity.kt
1
3445
package com.apollographql.apollo3.kotlinsample.repositories import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.apollographql.apollo3.kotlinsample.BuildConfig import com.apollographql.apollo3.kotlinsample.KotlinSampleApp import com.apollographql.apollo3.kotlinsample.R import com.apollographql.apollo3.kotlinsample.data.GitHubDataSource import com.apollographql.apollo3.kotlinsample.fragment.RepositoryFragment import com.apollographql.apollo3.kotlinsample.repositoryDetail.RepositoryDetailActivity import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_main.progressBar import kotlinx.android.synthetic.main.activity_main.rvRepositories import kotlinx.android.synthetic.main.activity_main.tvError class MainActivity : AppCompatActivity() { private lateinit var repositoriesAdapter: RepositoriesAdapter private val compositeDisposable = CompositeDisposable() private val dataSource: GitHubDataSource by lazy { (application as KotlinSampleApp).getDataSource() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) if (BuildConfig.GITHUB_OAUTH_TOKEN == "your_token") { tvError.visibility = View.VISIBLE tvError.text = "Please replace \"your_token\" in apollo-kotlin-samples/github_token with an actual token.\n\nhttps://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/" rvRepositories.visibility = View.GONE progressBar.visibility = View.GONE return } tvError.visibility = View.GONE rvRepositories.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false) rvRepositories.addItemDecoration(DividerItemDecoration(this, RecyclerView.VERTICAL)) repositoriesAdapter = RepositoriesAdapter { repositoryFragment -> RepositoryDetailActivity.start(this@MainActivity, repositoryFragment.name) } rvRepositories.adapter = repositoriesAdapter setupDataSource() fetchRepositories() } private fun setupDataSource() { val successDisposable = dataSource.repositories .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleRepositories) val errorDisposable = dataSource.error .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(this::handleError) compositeDisposable.add(successDisposable) compositeDisposable.add(errorDisposable) } private fun handleRepositories(repos: List<RepositoryFragment>) { progressBar.visibility = View.GONE rvRepositories.visibility = View.VISIBLE repositoriesAdapter.setItems(repos) } private fun handleError(error: Throwable?) { tvError.text = error?.localizedMessage tvError.visibility = View.VISIBLE progressBar.visibility = View.GONE error?.printStackTrace() } private fun fetchRepositories() { dataSource.fetchRepositories() } override fun onDestroy() { super.onDestroy() compositeDisposable.dispose() dataSource.cancelFetching() } }
mit
d54a4206e41943229f440b86c58c004c
36.445652
203
0.788679
4.907407
false
false
false
false
Deanveloper/SlaK
src/main/kotlin/com/deanveloper/slak/channel/BaseChannel.kt
1
5670
package com.deanveloper.slak.channel import com.deanveloper.slak.TOKEN import com.deanveloper.slak.User import com.deanveloper.slak.message.Message import com.deanveloper.slak.runMethod import com.deanveloper.slak.runMethodSync import com.deanveloper.slak.util.Cacher import com.deanveloper.slak.util.ErrorHandler import com.google.gson.JsonObject import java.time.LocalDateTime import java.util.* /** * Base class for all channel-type classes * * @author Dean B */ abstract class BaseChannel<T : BaseChannel<T>> protected constructor( id: String, name: String, creator: User, created: LocalDateTime, archived: Boolean, general: Boolean, members: List<User>, topic: OwnedString.Topic?, purpose: OwnedString.Purpose?, handler: ChannelCompanion<T> ) { val id = id var name = name internal set val creator = creator val created = created var archived = archived internal set val general = general var topic = topic internal set var purpose = purpose internal set var members = members internal set val handler = handler private var _history: MutableList<Message>? = null val historyLoaded: Boolean get() = _history != null val history: List<Message> get() = _history?.toList() ?: throw HistoryNotLoadedException() init { this.name = if (name.startsWith('#')) name else "#$name" @Suppress("UNCHECKED_CAST") (this as T) //smart cast handler.put(this.name, this) handler.put(id, this) } abstract class ChannelCompanion<T : BaseChannel<T>>(val methodBase: String) : Cacher<T>() { abstract fun fromJson(json: JsonObject): T fun start() { val json = runMethodSync("$methodBase.list", "token" to TOKEN, "exclude_archived" to "0") for (elem in json["$methodBase"].asJsonArray) { try { fromJson(elem.asJsonObject) //this method never gets called } catch(e: Throwable) { e.printStackTrace() } } } @JvmOverloads fun create(channel: String, cb: (T) -> Unit = { }): ErrorHandler { return runMethod("$methodBase.create", "name" to channel, "token" to TOKEN) { json -> val created = fromJson(json["${methodBase.substring(0, methodBase.length - 1)}"].asJsonObject) cb(created) } } val list: Set<T> get() = this.values.toSet() } @JvmOverloads fun archive(cb: (Boolean) -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.archive", "token" to TOKEN, "channel" to id) { cb(it.has("no_op")) } } fun loadHistory(cb: () -> Unit) { if (historyLoaded) { cb() } else { historyAt { _history = it.toMutableList() cb() } } } @JvmOverloads fun historyAt(latest: Long = -1, oldest: Long = -1, inclusive: Boolean = false, count: Int = -1, unreads: Boolean = false, cb: (List<Message>) -> Unit): ErrorHandler { val params = ArrayList<Pair<String, String>>(5) params.add("token" to TOKEN) params.add("channel" to id) if (latest > 0) params.add("latest" to latest.toString()) if (oldest > 0) params.add("oldest" to oldest.toString()) if (inclusive) params.add("inclusive" to inclusive.toString()) if (count > 0) params.add("count" to count.toString()) if (unreads) params.add("unreads" to unreads.toString()) return runMethod("${handler.methodBase}.history", *params.toTypedArray()) { cb(it["messages"].asJsonArray.map { Message(it.asJsonObject) }) } } @JvmOverloads fun invite(user: User, cb: (T) -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.invite", "token" to TOKEN, "channel" to id, "user" to user.id) { json -> cb(handler[json.getAsJsonObject("channel")["id"].asString]) } } @JvmOverloads fun join(cb: (T) -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.join", "token" to TOKEN, "name" to name) { json -> cb(handler[json.getAsJsonObject("channel")["id"].asString]) } } @JvmOverloads fun kick(user: User, cb: () -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.kick", "token" to TOKEN, "channel" to id, "user" to user.id) { json -> cb() } } @JvmOverloads fun leave(cb: () -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.leave", "token" to TOKEN, "channel" to id) { json -> cb() } } @JvmOverloads fun setPurpose(purpose: String, cb: (String) -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.setPurpose", "token" to TOKEN, "channel" to id, "purpose" to purpose) { json -> cb(json["purpose"].asString) } } @JvmOverloads fun setTopic(topic: String, cb: (String) -> Unit = { }): ErrorHandler { return runMethod("${handler.methodBase}.setTopic", "token" to TOKEN, "channel" to id, "topic" to topic) { json -> cb(json["topic"].asString) } } override fun toString(): String { return "${javaClass.simpleName}[$id|$name]" } } class HistoryNotLoadedException : IllegalStateException("History has not been loaded using the loadHistory function!")
mit
e4671aab645a5c0726bf76fe8de8a886
33.579268
120
0.583774
4.181416
false
false
false
false
Saketme/JRAW
docs/src/main/kotlin/net/dean/jraw/docs/main.kt
2
2106
package net.dean.jraw.docs import java.io.File private const val SAMPLES_DIR_ARG = "--samples-dir" private const val OUT_DIR_ARG = "--output-dir" private const val RESOURCES_DIR_ARG = "--resources-dir" fun main(args: Array<String>) { val cliArgs = parseArgs(args) // Establish a base of operations val samplesDir = File(cliArgs[SAMPLES_DIR_ARG]) val outDir = File(cliArgs[OUT_DIR_ARG]) val resourcesDir = File(cliArgs[RESOURCES_DIR_ARG]) if (!outDir.isDirectory && !outDir.mkdirs()) failAndExit("Could not `mkdir -p` for ${outDir.absolutePath}") val contentDir = File(resourcesDir, "content") BookBuilder(samplesDir, contentDir).build(outDir) } private fun parseArgs(args: Array<String>): Map<String, String> { if (args.size % 2 != 0) failAndExit("Expected an even number of arguments") val required = listOf(SAMPLES_DIR_ARG, OUT_DIR_ARG, RESOURCES_DIR_ARG) // Create a map where all even indexes (and 0) represent keys and all odd indexes represent values for the element // before it val allArgs = mapOf(*(args.indices step 2).map { args[it] to args[it + 1] }.toTypedArray()) val filtered = mutableMapOf<String, String>() // Only return values we care about for (arg in required) { if (arg !in allArgs) failAndExit("Expected argument '$arg' to have a value") filtered.put(arg, allArgs[arg]!!) } return filtered } private fun failAndExit(msg: String, code: Int = 1): Nothing { System.err.println(msg) System.exit(code) // JVM will have exited by now, this is just for Kotlin throw Error() } /** * Simple function to recursively fina all files starting from a given access point */ private fun walkRecursive(base: File): List<File> { val files = mutableListOf<File>() if (base.isDirectory) { base.listFiles()?.forEach { files.addAll(walkRecursive(it)) } ?: throw IllegalStateException("Encounted I/O exception when walking directory $base") } else if (base.isFile) { files.add(base) } return files }
mit
92ceb469efc3f81e1a328c6b7baf3709
29.970588
118
0.667142
3.815217
false
false
false
false
Yubico/yubioath-desktop
android/app/src/main/kotlin/com/yubico/authenticator/logging/Log.kt
1
2813
/* * Copyright (C) 2022 Yubico. * * 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.yubico.authenticator.logging import android.util.Log import com.yubico.authenticator.BuildConfig object Log { enum class LogLevel { TRAFFIC, DEBUG, INFO, WARNING, ERROR } private const val MAX_BUFFER_SIZE = 1000 private val buffer = arrayListOf<String>() fun getBuffer() : List<String> { return buffer } private var level = if (BuildConfig.DEBUG) { LogLevel.DEBUG } else { LogLevel.INFO } private const val TAG = "yubico-authenticator" @Suppress("unused") fun t(tag: String, message: String, error: String? = null) { log(LogLevel.TRAFFIC, tag, message, error) } @Suppress("unused") fun d(tag: String, message: String, error: String? = null) { log(LogLevel.DEBUG, tag, message, error) } @Suppress("unused") fun i(tag: String, message: String, error: String? = null) { log(LogLevel.INFO, tag, message, error) } @Suppress("unused") fun w(tag: String, message: String, error: String? = null) { log(LogLevel.WARNING, tag, message, error) } @Suppress("unused") fun e(tag: String, message: String, error: String? = null) { log(LogLevel.ERROR, tag, message, error) } @Suppress("unused") fun log(level: LogLevel, loggerName: String, message: String, error: String?) { if (level < this.level) { return } if (buffer.size > MAX_BUFFER_SIZE) { buffer.removeAt(0) } val logMessage = "[$loggerName] ${level.name}: $message".also { buffer.add(it) } when (level) { LogLevel.TRAFFIC -> Log.v(TAG, logMessage) LogLevel.DEBUG -> Log.d(TAG, logMessage) LogLevel.INFO -> Log.i(TAG, logMessage) LogLevel.WARNING -> Log.w(TAG, logMessage) LogLevel.ERROR -> Log.e(TAG, logMessage) } error?.let { Log.e(TAG, "[$loggerName] ${level.name}(details): $error".also { buffer.add(it) }) } } @Suppress("unused") fun setLevel(newLevel: LogLevel) { level = newLevel } }
apache-2.0
05815fd9ca61191ff5d6cbff0bab1c36
25.8
83
0.597938
3.973164
false
false
false
false
javaslang/javaslang-circuitbreaker
resilience4j-kotlin/src/test/kotlin/io/github/resilience4j/kotlin/bulkhead/FlowBulkheadTest.kt
3
8075
/* * * Copyright 2019: 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 io.github.resilience4j.kotlin.bulkhead import io.github.resilience4j.bulkhead.Bulkhead import io.github.resilience4j.bulkhead.BulkheadFullException import io.github.resilience4j.kotlin.CoroutineHelloWorldService import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.single import kotlinx.coroutines.flow.toList import org.assertj.core.api.Assertions import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.time.Duration import java.util.concurrent.Phaser class FlowBulkheadTest { private var permittedEvents = 0 private var rejectedEvents = 0 private var finishedEvents = 0 private fun Bulkhead.registerEventListener(): Bulkhead { eventPublisher.apply { onCallPermitted { permittedEvents++ } onCallRejected { rejectedEvents++ } onCallFinished { finishedEvents++ } } return this } @Test fun `should execute successful function`() { runBlocking { val bulkhead = Bulkhead.ofDefaults("testName").registerEventListener() val resultList = mutableListOf<Int>() //When flow { repeat(3) { emit(it) } } .bulkhead(bulkhead) .toList(resultList) //Then repeat(3) { assertThat(resultList[it]).isEqualTo(it) } assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(0) assertThat(finishedEvents).isEqualTo(1) } } @Test fun `should not execute function when full`() { runBlocking { val bulkhead = Bulkhead.of("testName") { BulkheadConfig { maxConcurrentCalls(1) maxWaitDuration(Duration.ZERO) } }.registerEventListener() val resultList = mutableListOf<Int>() //When val sync = Channel<Int>(Channel.RENDEZVOUS) val testFlow = flow { emit(sync.receive()) emit(sync.receive()) }.bulkhead(bulkhead) val firstCall = launch { testFlow.toList(resultList) } // wait until our first coroutine is inside the bulkhead sync.send(1) assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(0) assertThat(finishedEvents).isEqualTo(0) assertThat(resultList.size).isEqualTo(1) assertThat(resultList[0]).isEqualTo(1) val helloWorldService = CoroutineHelloWorldService() //When try { flow { emit(helloWorldService.returnHelloWorld()) } .bulkhead(bulkhead) .single() Assertions.failBecauseExceptionWasNotThrown<Nothing>(BulkheadFullException::class.java) } catch (e: BulkheadFullException) { // nothing - proceed } assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(1) assertThat(finishedEvents).isEqualTo(0) // allow our first call to complete, and then wait for it sync.send(2) firstCall.join() //Then assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(1) assertThat(finishedEvents).isEqualTo(1) assertThat(resultList.size).isEqualTo(2) assertThat(resultList[1]).isEqualTo(2) // Then the helloWorldService should not be invoked assertThat(helloWorldService.invocationCounter).isEqualTo(0) } } @Test fun `should execute unsuccessful function`() { runBlocking { val bulkhead = Bulkhead.ofDefaults("testName").registerEventListener() val resultList = mutableListOf<Int>() //When try { flow { repeat(3) { emit(it) } error("failed") } .bulkhead(bulkhead) .toList(resultList) Assertions.failBecauseExceptionWasNotThrown<Nothing>(IllegalStateException::class.java) } catch (e: IllegalStateException) { // nothing - proceed } //Then repeat(3) { assertThat(resultList[it]).isEqualTo(it) } assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(0) assertThat(finishedEvents).isEqualTo(1) } } @Test fun `should not record call finished when cancelled normally`() { runBlocking { val phaser = Phaser(1) var flowCompleted = false val bulkhead = Bulkhead.of("testName") { BulkheadConfig { maxConcurrentCalls(1) maxWaitDuration(Duration.ZERO) } }.registerEventListener() //When val job = launch(start = CoroutineStart.ATOMIC) { flow { phaser.arrive() delay(5000L) emit(1) flowCompleted = true } .bulkhead(bulkhead) .first() } phaser.awaitAdvance(1) job.cancelAndJoin() //Then assertThat(job.isCompleted).isTrue() assertThat(job.isCancelled).isTrue() assertThat(flowCompleted).isFalse() assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(0) assertThat(finishedEvents).isEqualTo(0) } } @Test fun `should not record call finished when cancelled exceptionally`() { runBlocking(Dispatchers.Default) { val phaser = Phaser(1) val parentJob = Job() var flowCompleted = false val bulkhead = Bulkhead.of("testName") { BulkheadConfig { maxConcurrentCalls(1) maxWaitDuration(Duration.ZERO) } }.registerEventListener() //When val job = launch(parentJob) { launch(start = CoroutineStart.ATOMIC) { flow { phaser.arrive() delay(5000L) emit(1) flowCompleted = true } .bulkhead(bulkhead) .first() } error("exceptional cancellation") } phaser.awaitAdvance(1) parentJob.runCatching { join() } //Then assertThat(job.isCompleted).isTrue() assertThat(job.isCancelled).isTrue() assertThat(flowCompleted).isFalse() assertThat(permittedEvents).isEqualTo(1) assertThat(rejectedEvents).isEqualTo(0) assertThat(finishedEvents).isEqualTo(0) } } }
apache-2.0
7771a79404d965ef098efd7d3a95dd0f
30.791339
103
0.552074
5.166347
false
true
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/uievent/MouseEventMatcher.kt
1
865
package org.hexworks.zircon.api.uievent import org.hexworks.zircon.api.data.Position data class MouseEventMatcher( val type: MouseEventType? = null, val button: Int? = null, val position: Position? = null ) { fun matches(event: MouseEvent): Boolean { var result = true type?.let { result = result && it == event.type } button?.let { result = result && it == event.button } position?.let { result = result && it == event.position } return result } companion object { fun create( type: MouseEventType? = null, button: Int? = null, position: Position? = null ) = MouseEventMatcher( type = type, button = button, position = position ) } }
apache-2.0
91c8ac16937386c4cb50b1baaf658064
21.763158
51
0.523699
4.505208
false
false
false
false
fashare2015/MVVM-JueJin
app/src/main/kotlin/com/fashare/mvvm_juejin/JueJinApp.kt
1
3296
package com.fashare.mvvm_juejin import android.app.Application import android.content.Context import android.util.Log import com.blankj.utilcode.util.DeviceUtils import com.blankj.utilcode.util.Utils import com.fashare.mvvm_juejin.repo.Response import com.fashare.mvvm_juejin.repo.local.LocalUser import com.fashare.net.ApiFactory import com.fashare.net.widget.OkHttpFactory import com.google.gson.Gson import com.google.gson.reflect.TypeToken import okhttp3.Interceptor import okhttp3.ResponseBody /** * <pre> * author : jinliangshan * e-mail : [email protected] * desc : * </pre> */ class JueJinApp: Application() { companion object { lateinit var instance: Context val GSON = Gson() } override fun onCreate() { super.onCreate() instance = this Utils.init(this) initNet() } private fun initNet() { ApiFactory.okhttpClient = OkHttpFactory.create(Interceptor { val originRequest = it.request() // 添加 header 以及公共的 GET 参数 val newRequest = originRequest.newBuilder() .addHeader("X-Juejin-Src", "android") .url(originRequest.url().newBuilder() .addQueryParameter("uid", LocalUser.userToken?.user_id?:"unlogin") .addQueryParameter("token", LocalUser.userToken?.token?:"") .addQueryParameter("device_id", DeviceUtils.getAndroidID()) .addQueryParameter("src", "android") .build() ).build() /** 处理不规范的返回值 * <-- 400 Bad Request * { * "s": 10012, * "m": "密码错误", * "d": [] // 应该返回 空对象{}, 否则 Json 解析异常 * } */ var response = it.proceed(newRequest) response.newBuilder() .apply { val originBody = response.body() var json = originBody?.string() var res : Response<Any>? = null try { res = GSON.fromJson(json, object: TypeToken<Response<Any>>(){}.type) }catch (e: Exception){ Log.e("initNet", "interceptor response" + e) } try { res = GSON.fromJson(json, object: TypeToken<Response<List<Any>>>(){}.type) }catch (e: Exception){ Log.e("initNet", "interceptor response" + e) } // 不成功,则移除 "d" 字段 if(1 != res?.s){ res?.d = null } json = GSON.toJson(res) this.body(ResponseBody.create(originBody?.contentType(), json)) } .apply { this.code(if(response.code() in 400 .. 500) 200 else response.code()) } .build() }) } }
mit
c06c6c7879935619df331a6aa867962e
33.12766
102
0.474751
4.635838
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/suggestion/UserSuggestionSource.kt
1
2689
package org.wordpress.android.ui.suggestion import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.launch import org.greenrobot.eventbus.Subscribe import org.wordpress.android.datasets.UserSuggestionTable import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.modules.BG_THREAD import org.wordpress.android.ui.suggestion.service.SuggestionEvents.SuggestionNameListUpdated import org.wordpress.android.ui.suggestion.util.SuggestionServiceConnectionManager import org.wordpress.android.util.EventBusWrapper import javax.inject.Inject import javax.inject.Named import kotlin.coroutines.CoroutineContext class UserSuggestionSource @Inject constructor( context: Context, override val site: SiteModel, private val eventBusWrapper: EventBusWrapper, @Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher ) : SuggestionSource, CoroutineScope { override val coroutineContext: CoroutineContext = bgDispatcher + Job() private val connectionManager = SuggestionServiceConnectionManager(context, site.siteId) private val _suggestions = MutableLiveData<SuggestionResult>() override val suggestionData: LiveData<SuggestionResult> = _suggestions private var isFetching: Boolean = false override fun initialize() { postSavedSuggestions(false) isFetching = true connectionManager.bindToService() eventBusWrapper.register(this) } private fun postSavedSuggestions(suggestionsWereJustUpdated: Boolean) { launch { val suggestions = Suggestion.fromUserSuggestions( UserSuggestionTable.getSuggestionsForSite(site.siteId) ) // Only send empty suggestions if they are recent if (suggestions.isNotEmpty() || suggestionsWereJustUpdated) { _suggestions.postValue(SuggestionResult(suggestions, false)) } } } override fun refreshSuggestions() { isFetching = true connectionManager.apply { unbindFromService() bindToService() } } @Subscribe fun onEventMainThread(event: SuggestionNameListUpdated) { if (event.mRemoteBlogId == site.siteId) { isFetching = false postSavedSuggestions(true) } } override fun isFetchInProgress(): Boolean = isFetching override fun onCleared() { eventBusWrapper.unregister(this) connectionManager.unbindFromService() } }
gpl-2.0
5712e47dd8a1063e7996afd3e52d7129
33.922078
93
0.736705
5.21124
false
false
false
false
RadiationX/ForPDA
app/src/main/java/forpdateam/ru/forpda/ui/fragments/devdb/device/specs/SpecsFragment.kt
1
1235
package forpdateam.ru.forpda.ui.fragments.devdb.device.specs import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import forpdateam.ru.forpda.App import forpdateam.ru.forpda.R import forpdateam.ru.forpda.ui.fragments.devdb.brand.DevicesFragment import forpdateam.ru.forpda.ui.fragments.devdb.device.SubDeviceFragment /** * Created by radiationx on 08.08.17. */ class SpecsFragment : SubDeviceFragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.device_fragment_specs, container, false) val recyclerView = view.findViewById<View>(R.id.base_list) as androidx.recyclerview.widget.RecyclerView recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(recyclerView.context) val adapter = SpecsAdapter() adapter.addAll(device.specs) recyclerView.adapter = adapter recyclerView.addItemDecoration(DevicesFragment.SpacingItemDecoration(App.px8, true)) return view } }
gpl-3.0
0bc907469a1dd403aec51acbb378b0d6
40.166667
116
0.783806
4.426523
false
false
false
false
DankBots/GN4R
src/main/java/com/gmail/hexragon/gn4rBot/command/general/HelpCommand.kt
1
4172
package com.gmail.hexragon.gn4rBot.command.general import com.gmail.hexragon.gn4rBot.managers.commands.CommandExecutor import com.gmail.hexragon.gn4rBot.managers.commands.annotations.Command import com.gmail.hexragon.gn4rBot.managers.directMessage.PMCommandManager import com.gmail.hexragon.gn4rBot.managers.guildMessage.GuildCommandManager import com.gmail.hexragon.gn4rBot.managers.users.PermissionLevel import com.gmail.hexragon.gn4rBot.util.GnarMessage import com.gmail.hexragon.gn4rBot.util.GnarQuotes import java.util.StringJoiner @Command(aliases = arrayOf("help", "guide"), usage = "[command]", description = "Display GN4R's list of commands.") class HelpCommand : CommandExecutor() { override fun execute(message : GnarMessage?, args : Array<out String>?) { if (args!!.size >= 1) { val cmd : CommandExecutor? = commandManager.getCommand(args[0]) if (cmd == null) { message?.replyRaw("There is no command by the name `${args[0]}` in this guild. :cry:") return } val aliases = commandManager.commandRegistry.entries .filter { it.value == cmd } .map { it.key } val string = listOf( "```", "\u258C Description __ ${cmd.description}", "\u258C Usage ________ ${commandManager.token}${args[0].toLowerCase()} ${cmd.usage}", "\u258C Aliases ______ [${aliases.joinToString(", ")}]", "```" ) message?.replyRaw(string.joinToString("\n")) return } val commandEntries = commandManager.uniqueCommandRegistry val builder = StringBuilder() if (commandManager.javaClass == GuildCommandManager::class.java) builder.append("\nThis is all of GN4R-Bot's currently registered commands on the __**${guild.name}**__ guild.\n\n") else if (commandManager.javaClass == PMCommandManager::class.java) builder.append("\nThis is all of GN4R-Bot's currently registered commands on the __**direct message**__ channel.\n\n") PermissionLevel.values().forEach { val perm = it val count = commandEntries.values.filter { it.permissionLevel() == perm && it.isShownInHelp }.count() if (count < 1) return@forEach val joiner = StringJoiner("", "```xl\n", "```\n") val lineBuilder = StringBuilder() for (i in 0 .. 22 - perm.toString().length) lineBuilder.append('—') joiner.add("\u258c ${it.toString().replace("_", " ")} ${lineBuilder.toString()} $count\n") for ((label, cmd) in commandEntries) { if (cmd.permissionLevel() != perm || !cmd.isShownInHelp) continue joiner.add("\u258C ${commandManager.token}$label ${cmd.usage}\n") } builder.append(joiner.toString()) } builder.append("To view a command's description, do `${commandManager.token}help [command]`.\n") builder.append("You can also chat and execute commands with Gnar privately, try it!\n\n") builder.append("**Bot Commander** commands requires you to have a role named exactly __Bot Commander__.\n") builder.append("**Server Owner** commands requires you to be the __Server Owner__ to execute.\n\n") builder.append("**Latest News:**\n") builder.append(" - Create dank memes with Windows dialog `_dialog (message)`.\n") builder.append(" - Marvel character look-up! Try with `_marvel (character)`.\n\n") builder.append("**Website:** http://gnarbot.xyz\n") builder.append("**Discord Server:** http://discord.gg/NQRpmr2\n") message?.author?.privateChannel?.sendMessage(builder.toString()) message?.reply("**${GnarQuotes.getRandomQuote()}** My commands has been PM'ed to you.") } }
mit
88ffae99b0f1e822a8108fb388a3e882
44.835165
130
0.581295
4.375656
false
false
false
false
Turbo87/intellij-rust
src/main/kotlin/org/rust/ide/documentation/RustDocumentationProvider.kt
1
1711
package org.rust.ide.documentation import com.intellij.lang.documentation.AbstractDocumentationProvider import com.intellij.psi.PsiElement import org.rust.lang.core.psi.RustFnItem import org.rust.lang.core.psi.RustPatBinding import org.rust.lang.core.psi.util.isMut class RustDocumentationProvider : AbstractDocumentationProvider() { override fun getQuickNavigateInfo(element: PsiElement?, originalElement: PsiElement?) = when (element) { is RustPatBinding -> getQuickNavigateInfo(element) is RustFnItem -> getQuickNavigateInfo(element) else -> null } private fun getQuickNavigateInfo(element: RustPatBinding): String { val location = element.locationString val bindingMode = if (element.isMut) "mut " else "" return "let $bindingMode<b>${element.identifier.text}</b>$location" } private fun getQuickNavigateInfo(element: RustFnItem): String { val signature = element.formatSignature() val location = element.locationString return "$signature$location" } private fun RustFnItem.formatSignature(): String { val identStart = identifier.startOffsetInParent val identEnd = identStart + identifier.textLength val signatureLength = block?.startOffsetInParent ?: textLength val beforeIdent = text.subSequence(0, identStart) val identText = text.subSequence(identStart, identEnd) val afterIdent = text.subSequence(identEnd, signatureLength).toString().trimEnd() return "$beforeIdent<b>$identText</b>$afterIdent" } private val PsiElement.locationString: String get() = containingFile?.let { " [${it.name}]" }.orEmpty() }
mit
d83cfdb6e8da45a92ab0c7b969095aaf
37.886364
108
0.710695
4.624324
false
false
false
false
android/architecture-components-samples
WorkManagerSample/lib/src/main/java/com/example/background/ImageOperations.kt
1
3439
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.background import android.annotation.SuppressLint import android.content.Context import android.net.Uri import androidx.work.Data import androidx.work.ExistingWorkPolicy import androidx.work.ListenableWorker import androidx.work.OneTimeWorkRequest import androidx.work.OneTimeWorkRequestBuilder import androidx.work.OutOfQuotaPolicy import androidx.work.WorkContinuation import androidx.work.WorkManager import androidx.work.workDataOf import com.example.background.workers.CleanupWorker import com.example.background.workers.SaveImageToGalleryWorker import com.example.background.workers.UploadWorker import com.example.background.workers.filters.BlurEffectFilterWorker import com.example.background.workers.filters.GrayScaleFilterWorker import com.example.background.workers.filters.WaterColorFilterWorker /** * Builds and holds WorkContinuation based on supplied filters. */ @SuppressLint("EnqueueWork") class ImageOperations( context: Context, imageUri: Uri, waterColor: Boolean = false, grayScale: Boolean = false, blur: Boolean = false, save: Boolean = false ) { private val imageInputData = workDataOf(Constants.KEY_IMAGE_URI to imageUri.toString()) val continuation: WorkContinuation init { continuation = WorkManager.getInstance(context) .beginUniqueWork( Constants.IMAGE_MANIPULATION_WORK_NAME, ExistingWorkPolicy.REPLACE, OneTimeWorkRequest.from(CleanupWorker::class.java) ).thenMaybe<WaterColorFilterWorker>(waterColor) .thenMaybe<GrayScaleFilterWorker>(grayScale) .thenMaybe<BlurEffectFilterWorker>(blur) .then( if (save) { workRequest<SaveImageToGalleryWorker>(tag = Constants.TAG_OUTPUT) } else /* upload */ { workRequest<UploadWorker>(tag = Constants.TAG_OUTPUT) } ) } /** * Applies a [ListenableWorker] to a [WorkContinuation] in case [apply] is `true`. */ private inline fun <reified T : ListenableWorker> WorkContinuation.thenMaybe( apply: Boolean ): WorkContinuation { return if (apply) { then(workRequest<T>()) } else { this } } /** * Creates a [OneTimeWorkRequest] with the given inputData and a [tag] if set. */ private inline fun <reified T : ListenableWorker> workRequest( inputData: Data = imageInputData, tag: String? = null ) = OneTimeWorkRequestBuilder<T>().apply { setInputData(inputData) setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST) if (!tag.isNullOrEmpty()) { addTag(tag) } }.build() }
apache-2.0
d12d66aafe6cdc54f5b7d0eb338f2d87
33.737374
91
0.688863
4.647297
false
false
false
false
mdaniel/intellij-community
platform/statistics/src/com/intellij/internal/statistic/updater/StatisticsJobsScheduler.kt
1
3334
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.updater import com.intellij.ide.ApplicationInitializedListener import com.intellij.ide.StatisticsNotificationManager import com.intellij.internal.statistic.eventLog.StatisticsEventLogMigration import com.intellij.internal.statistic.eventLog.StatisticsEventLogProviderUtil.getEventLogProviders import com.intellij.internal.statistic.eventLog.StatisticsEventLoggerProvider import com.intellij.internal.statistic.eventLog.uploader.EventLogExternalUploader import com.intellij.internal.statistic.eventLog.validator.IntellijSensitiveDataValidator import com.intellij.internal.statistic.utils.StatisticsUploadAssistant import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.extensions.ExtensionNotApplicableException import com.intellij.openapi.extensions.InternalIgnoreDependencyViolation import kotlinx.coroutines.* import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds @InternalIgnoreDependencyViolation internal class StatisticsJobsScheduler : ApplicationInitializedListener { init { if (ApplicationManager.getApplication().isUnitTestMode) { throw ExtensionNotApplicableException.create() } } override suspend fun execute() { val notificationManager = ApplicationManager.getApplication().getService(StatisticsNotificationManager::class.java) notificationManager?.showNotificationIfNeeded() checkPreviousExternalUploadResult() runEventLogStatisticsService() runValidationRulesUpdate() ApplicationManager.getApplication().coroutineScope.launch { delay(5.minutes) withContext(Dispatchers.IO) { StatisticsEventLogMigration.performMigration() } } } } private fun runValidationRulesUpdate() { ApplicationManager.getApplication().coroutineScope.launch { if (!System.getProperty("fus.internal.reduce.initial.delay").toBoolean()) { delay(3.minutes) } while (true) { val providers = getEventLogProviders() for (provider in providers) { if (provider.isRecordEnabled()) { IntellijSensitiveDataValidator.getInstance(provider.recorderId).update() } } delay(180.minutes) } } } private fun checkPreviousExternalUploadResult() { ApplicationManager.getApplication().coroutineScope.launch { delay(3.minutes) val providers = getEventLogProviders().filter(StatisticsEventLoggerProvider::sendLogsOnIdeClose) EventLogExternalUploader.logPreviousExternalUploadResult(providers) } } private fun runEventLogStatisticsService() { ApplicationManager.getApplication().coroutineScope.launch { delay(1.minutes) val providers = getEventLogProviders() coroutineScope { for (provider in providers) { if (!provider.isSendEnabled()) { continue } val statisticsService = StatisticsUploadAssistant.getEventLogStatisticsService(provider.recorderId) launch { delay((5 * 60).seconds) while (true) { statisticsService.send() delay(provider.sendFrequencyMs.milliseconds) } } } } } }
apache-2.0
8e9e2560926e49e1f33af6d1de688e15
34.860215
120
0.768746
5.153014
false
false
false
false
GunoH/intellij-community
plugins/kotlin/completion/impl-k2/src/org/jetbrains/kotlin/idea/completion/impl/k2/lookups/utils.kt
4
3060
// 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.completion.lookups import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.openapi.util.TextRange import com.intellij.refactoring.suggested.endOffset import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol import org.jetbrains.kotlin.idea.base.analysis.api.utils.shortenReferencesInRange import org.jetbrains.kotlin.idea.base.codeInsight.KotlinIconProvider.getIconFor import org.jetbrains.kotlin.idea.completion.contributors.helpers.insertSymbol import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtSuperExpression internal fun KtAnalysisSession.withSymbolInfo( symbol: KtSymbol, elementBuilder: LookupElementBuilder ): LookupElementBuilder = elementBuilder .withPsiElement(symbol.psi) // TODO check if it is a heavy operation and should be postponed .withIcon(getIconFor(symbol)) // FIXME: This is a hack, we should think how we can get rid of it @OptIn(KtAllowAnalysisOnEdt::class) internal inline fun <T> withAllowedResolve(action: () -> T): T { return allowAnalysisOnEdt(action) } internal fun CharSequence.skipSpaces(index: Int): Int = (index until length).firstOrNull { val c = this[it]; c != ' ' && c != '\t' } ?: this.length internal fun CharSequence.indexOfSkippingSpace(c: Char, startIndex: Int): Int? { for (i in startIndex until this.length) { val currentChar = this[i] if (c == currentChar) return i if (currentChar != ' ' && currentChar != '\t') return null } return null } internal fun updateLookupElementBuilderToInsertTypeQualifierOnSuper( builder: LookupElementBuilder, insertionStrategy: CallableInsertionStrategy.WithSuperDisambiguation ) = builder.withInsertHandler { context, item -> builder.insertHandler?.handleInsert(context, item) val superExpression = insertionStrategy.superExpressionPointer.element ?: return@withInsertHandler superExpression.setSuperTypeQualifier(context, insertionStrategy.superClassId) }.appendTailText(" for ${insertionStrategy.superClassId.relativeClassName}", true) private fun KtSuperExpression.setSuperTypeQualifier( context: InsertionContext, superClassId: ClassId ) { superTypeQualifier?.delete() val typeQualifier = "<${superClassId.asFqNameString()}>" context.insertSymbol(typeQualifier, instanceReference.endOffset, moveCaretToEnd = false) context.commitDocument() shortenReferencesInRange(context.file as KtFile, TextRange(this.endOffset, this.endOffset + typeQualifier.length)) }
apache-2.0
6ef2dd885175a3848919a685d4df77bf
43.347826
158
0.784967
4.5
false
false
false
false
kondroid00/SampleProject_Android
app/src/main/java/com/kondroid/sampleproject/viewmodel/BaseViewModel.kt
1
989
package com.kondroid.sampleproject.viewmodel import android.content.Context import android.databinding.ObservableField import android.view.View import io.reactivex.disposables.CompositeDisposable import java.lang.ref.WeakReference /** * Created by kondo on 2017/09/28. */ open class BaseViewModel(context: Context) { val progressBarVisibility: ObservableField<Int> = ObservableField(View.INVISIBLE) val context: WeakReference<Context> = WeakReference(context) protected val compositeDisposable: CompositeDisposable = CompositeDisposable() protected var requesting: Boolean get() { return progressBarVisibility.get() == View.VISIBLE } set(value) { if (value) { progressBarVisibility.set(View.VISIBLE) } else { progressBarVisibility.set(View.INVISIBLE) } } open fun initVM() { } open fun release() { compositeDisposable.clear() } }
mit
219497cdccd88451e6d97c0cdc5c12e0
26.5
85
0.67543
4.89604
false
false
false
false
binaryroot/AndroidArchitecture
app/src/main/java/com/androidarchitecture/core/BaseActivity.kt
1
4998
package com.androidarchitecture.core import android.arch.lifecycle.LifecycleActivity import android.os.Handler import android.os.Message import android.app.ProgressDialog import android.content.Context import android.view.KeyEvent import com.androidarchitecture.App import com.androidarchitecture.di.application.AppComponent import android.support.v4.app.Fragment import com.androidarchitecture.di.HasComponent import com.androidarchitecture.utility.toast /** * Base activity for the whole project. */ abstract class BaseActivity : LifecycleActivity(), Handler.Callback, LoadingUiHandler { private val MSG_SHOW_LOADING_DIALOG = 0x1000 //4096 in dec private val MSG_UPDATE_LOADING_MESSAGE = 0x1001 //4097 in dec private val MSG_HIDE_LOADING_DIALOG = 0x1002 //4098 in dec private val mUIHandler = Handler(this) private var mProgressDialog: ProgressDialog? = null //region BaseActivity /** * Returns instance of {@link AppComponent}. */ protected fun getAppComponent() : AppComponent = (applicationContext as HasComponent<*>).getComponent() as AppComponent //endregion //region Callback override fun handleMessage(msg: Message?): Boolean { var result = false when (msg?.what) { MSG_SHOW_LOADING_DIALOG -> { handleShowLoadingDialog(msg); result = true} MSG_UPDATE_LOADING_MESSAGE -> {handleUpdateLoadingDialog(msg); result = true} MSG_HIDE_LOADING_DIALOG -> {handleHideLoadingDialog(); result = true} } return result } //endregion //region LoadingUiHandler override fun showLoadingDialog(message: String) { val showMessage = Message() showMessage.what = MSG_SHOW_LOADING_DIALOG showMessage.obj = showMessage mUIHandler.sendMessage(showMessage) } override fun updateLoadingDialog(message: String) { val updateMessage = Message() updateMessage.what = MSG_UPDATE_LOADING_MESSAGE updateMessage.obj = updateMessage mUIHandler.sendMessage(updateMessage) } override fun hideLoadingDialog() { val hideMessage = Message() hideMessage.what = MSG_HIDE_LOADING_DIALOG mUIHandler.sendMessage(hideMessage) } //endregion //region FragmentNavigation fun addFragment(containerViewId: Int, fragment: Fragment, addToBackStack: Boolean) { val fragmentTransaction = this.supportFragmentManager.beginTransaction() fragmentTransaction.add(containerViewId, fragment) if (addToBackStack) { fragmentTransaction.addToBackStack(fragment::class.java.name) } fragmentTransaction.commit() } fun addFragment(containerViewId: Int, fragment: Fragment, tag: String, addToBackStack: Boolean) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.add(containerViewId, fragment, tag) if (addToBackStack) { fragmentTransaction.addToBackStack(fragment::class.java.name) } fragmentTransaction.commit() } fun replaceFragment(containerViewId: Int, fragment: Fragment, addToBackStack: Boolean) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.replace(containerViewId, fragment) if (addToBackStack) { fragmentTransaction.addToBackStack(fragment::class.java.name) } fragmentTransaction.commitAllowingStateLoss() } fun removeFragment(fragment: Fragment) { val transaction = supportFragmentManager.beginTransaction() transaction.remove(fragment) transaction.commit() } fun removeFragment(tag: String) { val fragmentTransaction = supportFragmentManager.beginTransaction() fragmentTransaction.remove(supportFragmentManager.findFragmentByTag(tag)).commit() } //endregion //region Utility API private fun isProgressShowing(): Boolean = null != mProgressDialog && mProgressDialog!!.isShowing private fun handleHideLoadingDialog() { if (isProgressShowing()) { mProgressDialog?.dismiss() } } private fun handleUpdateLoadingDialog(message: Message) { if (isProgressShowing()) { mProgressDialog?.setMessage(message.obj as String) } } private fun handleShowLoadingDialog(message: Message): Boolean { if (null == mProgressDialog) { mProgressDialog = ProgressDialog(this@BaseActivity) } mProgressDialog?.let { it.setMessage(message.obj as String) it.setCancelable(false) it.setOnKeyListener { dialog, keyCode, _ -> if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.dismiss() } false } if (!it.isShowing) { it.show() } } return true } //endregion }
mit
79bdfa9a5a4dd6b3e2996601c05968d1
33.006803
107
0.672669
5.25
false
false
false
false
mdanielwork/intellij-community
python/src/com/jetbrains/python/sdk/PySdkExt.kt
3
10080
/* * 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.jetbrains.python.sdk import com.intellij.execution.ExecutionException import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.project.rootManager import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.StandardFileSystems import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtil import com.intellij.webcore.packaging.PackagesNotificationPanel import com.jetbrains.python.packaging.ui.PyPackageManagementService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.sdk.flavors.CondaEnvSdkFlavor import com.jetbrains.python.sdk.flavors.PythonSdkFlavor import com.jetbrains.python.sdk.flavors.VirtualEnvSdkFlavor import java.io.File import java.io.IOException import java.nio.file.Files import java.nio.file.Paths /** * @author vlan */ fun findBaseSdks(existingSdks: List<Sdk>, module: Module?): List<Sdk> { val existing = existingSdks.filter { it.sdkType is PythonSdkType && it.isSystemWide } val detected = detectSystemWideSdks(module, existingSdks) return existing + detected } fun detectSystemWideSdks(module: Module?, existingSdks: List<Sdk>): List<PyDetectedSdk> { val existingPaths = existingSdks.map { it.homePath }.toSet() return PythonSdkFlavor.getApplicableFlavors(false) .asSequence() .flatMap { it.suggestHomePaths(module).asSequence() } .filter { it !in existingPaths } .map { PyDetectedSdk(it) } .sortedWith(compareBy<PyDetectedSdk>({ it.guessedLanguageLevel }, { it.homePath }).reversed()) .toList() } fun detectVirtualEnvs(module: Module?, existingSdks: List<Sdk>): List<PyDetectedSdk> = filterSuggestedPaths(VirtualEnvSdkFlavor.INSTANCE.suggestHomePaths(module), existingSdks, module) fun detectCondaEnvs(module: Module?, existingSdks: List<Sdk>): List<PyDetectedSdk> = filterSuggestedPaths(CondaEnvSdkFlavor.INSTANCE.suggestHomePaths(module), existingSdks, module) fun createSdkByGenerateTask(generateSdkHomePath: Task.WithResult<String, ExecutionException>, existingSdks: List<Sdk>, baseSdk: Sdk?, associatedProjectPath: String?, suggestedSdkName: String?): Sdk? { val homeFile = try { val homePath = ProgressManager.getInstance().run(generateSdkHomePath) StandardFileSystems.local().refreshAndFindFileByPath(homePath) ?: throw ExecutionException("Directory $homePath not found") } catch (e: ExecutionException) { val description = PyPackageManagementService.toErrorDescription(listOf(e), baseSdk) ?: return null PackagesNotificationPanel.showError("Failed to Create Interpreter", description) return null } val suggestedName = suggestedSdkName ?: suggestAssociatedSdkName(homeFile.path, associatedProjectPath) return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeFile, PythonSdkType.getInstance(), false, null, suggestedName) ?: return null } fun Sdk.associateWithModule(module: Module?, newProjectPath: String?) { getOrCreateAdditionalData().apply { when { newProjectPath != null -> associateWithModulePath(newProjectPath) module != null -> associateWithModule(module) } } } fun Sdk.isAssociatedWithModule(module: Module?): Boolean { val basePath = module?.basePath val associatedPath = associatedModulePath if (basePath != null && associatedPath == basePath) return true if (isAssociatedWithAnotherModule(module)) return false return isLocatedInsideModule(module) || containsModuleName(module) } fun Sdk.isAssociatedWithAnotherModule(module: Module?): Boolean { val basePath = module?.basePath ?: return false val associatedPath = associatedModulePath ?: return false return basePath != associatedPath } val Sdk.associatedModulePath: String? // TODO: Support .project associations get() = associatedPathFromAdditionalData /*?: associatedPathFromDotProject*/ val Sdk.associatedModule: Module? get() { val associatedPath = associatedModulePath return ProjectManager.getInstance().openProjects .asSequence() .flatMap { ModuleManager.getInstance(it).modules.asSequence() } .firstOrNull { it?.basePath == associatedPath } } fun Sdk.adminPermissionsNeeded(): Boolean { val homePath = homePath ?: return false return !Files.isWritable(Paths.get(homePath)) } fun PyDetectedSdk.setup(existingSdks: List<Sdk>): Sdk? { val homeDir = homeDirectory ?: return null return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeDir, PythonSdkType.getInstance(), false, null, null) } fun PyDetectedSdk.setupAssociated(existingSdks: List<Sdk>, associatedModulePath: String?): Sdk? { val homeDir = homeDirectory ?: return null val suggestedName = homePath?.let { suggestAssociatedSdkName(it, associatedModulePath) } return SdkConfigurationUtil.setupSdk(existingSdks.toTypedArray(), homeDir, PythonSdkType.getInstance(), false, null, suggestedName) } var Module.pythonSdk: Sdk? get() = PythonSdkType.findPythonSdk(this) set(value) = ModuleRootModificationUtil.setModuleSdk(this, value) var Project.pythonSdk: Sdk? get() { val sdk = ProjectRootManager.getInstance(this).projectSdk return when (sdk?.sdkType) { is PythonSdkType -> sdk else -> null } } set(value) { ApplicationManager.getApplication().runWriteAction { ProjectRootManager.getInstance(this).projectSdk = value } } val Module.baseDir: VirtualFile? get() = rootManager.contentRoots.firstOrNull() val Module.basePath: String? get() = baseDir?.path private fun suggestAssociatedSdkName(sdkHome: String, associatedPath: String?): String? { val baseSdkName = PythonSdkType.suggestBaseSdkName(sdkHome) ?: return null val venvRoot = PythonSdkType.getVirtualEnvRoot(sdkHome)?.path val condaRoot = CondaEnvSdkFlavor.getCondaEnvRoot(sdkHome)?.path val associatedName = when { venvRoot != null && (associatedPath == null || !FileUtil.isAncestor(associatedPath, venvRoot, true)) -> PathUtil.getFileName(venvRoot) condaRoot != null && (associatedPath == null || !FileUtil.isAncestor(associatedPath, condaRoot, true)) -> PathUtil.getFileName(condaRoot) else -> associatedPath?.let { PathUtil.getFileName(associatedPath) } ?: return null } return "$baseSdkName ($associatedName)" } val File.isNotEmptyDirectory: Boolean get() = exists() && isDirectory && list()?.isEmpty()?.not() ?: false val Sdk.isSystemWide: Boolean get() = !PythonSdkType.isRemote(this) && !PythonSdkType.isVirtualEnv( this) && !PythonSdkType.isCondaVirtualEnv(this) @Suppress("unused") private val Sdk.associatedPathFromDotProject: String? get() { val binaryPath = homePath ?: return null val virtualEnvRoot = PythonSdkType.getVirtualEnvRoot(binaryPath) ?: return null val projectFile = File(virtualEnvRoot, ".project") return try { projectFile.readText().trim() } catch (e: IOException) { null } } private val Sdk.associatedPathFromAdditionalData: String? get() = (sdkAdditionalData as? PythonSdkAdditionalData)?.associatedModulePath private fun Sdk.isLocatedInsideModule(module: Module?): Boolean { val homePath = homePath ?: return false val basePath = module?.basePath ?: return false return FileUtil.isAncestor(basePath, homePath, true) } private val PyDetectedSdk.guessedLanguageLevel: LanguageLevel? get() { val path = homePath ?: return null val result = Regex(""".*python(\d\.\d)""").find(path) ?: return null val versionString = result.groupValues.getOrNull(1) ?: return null return LanguageLevel.fromPythonVersion(versionString) } private fun Sdk.containsModuleName(module: Module?): Boolean { val path = homePath ?: return false val name = module?.name ?: return false return path.contains(name, true) } fun Sdk.getOrCreateAdditionalData(): PythonSdkAdditionalData { val existingData = sdkAdditionalData as? PythonSdkAdditionalData if (existingData != null) return existingData val newData = PythonSdkAdditionalData(PythonSdkFlavor.getFlavor(homePath)) val modificator = sdkModificator modificator.sdkAdditionalData = newData ApplicationManager.getApplication().runWriteAction { modificator.commitChanges() } return newData } private fun filterSuggestedPaths(suggestedPaths: MutableCollection<String>, existingSdks: List<Sdk>, module: Module?): List<PyDetectedSdk> { val existingPaths = existingSdks.map { it.homePath }.toSet() return suggestedPaths .asSequence() .filterNot { it in existingPaths } .distinct() .map { PyDetectedSdk(it) } .sortedWith(compareBy<PyDetectedSdk>({ it.isAssociatedWithModule(module) }, { it.homePath }).reversed()) .toList() }
apache-2.0
abeea4a75d3cab56f6f0f00529ffa29d
38.841897
133
0.739583
4.638748
false
false
false
false
cdietze/klay
tripleklay/src/main/kotlin/tripleklay/ui/util/Hierarchy.kt
1
2438
package tripleklay.ui.util import tripleklay.ui.Container import tripleklay.ui.Element /** * A view for the hierarchical structure of an [Element]. */ class Hierarchy /** * Creates a new view focused on the given element. */ ( /** The element that is the focus of this view. */ val elem: Element<*>) { /** * Iterates over the ancestors of an element. See [.ancestors]. */ class Ancestors(var current: Element<*>?) : Iterator<Element<*>> { init { if (current == null) { throw IllegalArgumentException() } } override fun hasNext(): Boolean { return current != null } override fun next(): Element<*> { if (!hasNext()) { throw IllegalStateException() } val next = current current = current!!.parent() return next!! } } /** * Tests if the given element is a proper descendant contained in this hierarchy, or is the * root. */ fun hasDescendant(descendant: Element<*>?): Boolean { if (descendant === elem) return true if (descendant == null) return false return hasDescendant(descendant.parent()) } /** * Returns an object to iterate over the ancestors of this hierarchy, including the root. */ fun ancestors(): Iterable<Element<*>> { return object : Iterable<Element<*>> { override fun iterator(): Iterator<Element<*>> { return Ancestors(elem) } } } /** * Applies the given operation to the root of the hierarchy and to every proper descendant. */ fun apply(op: ElementOp<Element<*>>): Hierarchy { forEachDescendant(elem, op) return this } companion object { /** * Create a new view of the given element. */ fun of(elem: Element<*>): Hierarchy { return Hierarchy(elem) } private fun forEachDescendant(root: Element<*>, op: ElementOp<Element<*>>) { op.apply(root) if (root is Container<*>) { val es = root var ii = 0 val ll = es.childCount() while (ii < ll) { forEachDescendant(es.childAt(ii), op) ++ii } } } } }
apache-2.0
3f27291501e79eb239c666b5741878d8
25.5
95
0.521329
5.00616
false
false
false
false
jasvilladarez/Kotlin_Practice
Notes/app/src/main/kotlin/com/jv/practice/notes/domain/interactors/base/Interactor.kt
1
1772
/* * Copyright 2016 Jasmine Villadarez * * 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.jv.practice.notes.domain.interactors.base import com.jv.practice.notes.domain.executor.ExecutorThread import com.jv.practice.notes.domain.executor.PostExecutorThread import rx.Observable import rx.Subscriber import rx.Subscription import rx.schedulers.Schedulers import rx.subscriptions.Subscriptions abstract class Interactor(executorThread: ExecutorThread, postExecutorThread: PostExecutorThread) { open internal var executorThread: ExecutorThread = executorThread open internal var postExecutorThread: PostExecutorThread = postExecutorThread private final val MAX_RETRY = 3L internal var subscription: Subscription = Subscriptions.empty() internal abstract fun buildObservable(): Observable<*> fun execute(subscriber: Subscriber<kotlin.Any>) { subscription = buildObservable() .observeOn(postExecutorThread.scheduler) .subscribeOn(Schedulers.from (executorThread)) .retry(MAX_RETRY) .subscribe(subscriber); } fun unsubscribe() { if (subscription.isUnsubscribed) { return } subscription.unsubscribe() } }
apache-2.0
d5f7c847212594df4d3f7b4c853f6a8c
33.764706
99
0.731941
4.77628
false
false
false
false
dahlstrom-g/intellij-community
platform/lang-impl/src/com/intellij/formatting/commandLine/FileSetProcessor.kt
9
4506
// 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.formatting.commandLine import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.codeStyle.CodeStyleSettings import java.io.File import java.io.IOException import java.nio.charset.Charset import javax.xml.parsers.DocumentBuilderFactory import javax.xml.xpath.XPathEvaluationResult import javax.xml.xpath.XPathFactory private var LOG = Logger.getInstance(FileSetProcessor::class.java) abstract class FileSetProcessor( val messageOutput: MessageOutput, val isRecursive: Boolean, val charset: Charset? = null ) { private val topEntries = arrayListOf<File>() private val fileMasks = arrayListOf<Regex>() protected val statistics = FileSetProcessingStatistics() val total: Int get() = statistics.getTotal() val processed: Int get() = statistics.getProcessed() val succeeded: Int get() = statistics.getValid() fun addEntry(filePath: String) = addEntry(File(filePath)) fun addEntry(file: File) = file .takeIf { it.exists() } ?.let { topEntries.add(it) } ?: throw IOException("File $file not found.") fun addFileMask(mask: Regex) = fileMasks.add(mask) private fun File.matchesFileMask() = fileMasks.isEmpty() || fileMasks.any { mask -> mask.matches(name) } private fun File.toVirtualFile() = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(this) ?: throw IOException("Can not find $path") fun processFiles() = topEntries.forEach { entry -> val outerProjectSettings = findCodeStyleSettings(entry.getOuterProject()) var innerProjectSettings: CodeStyleSettings? = null var currentProject: File? = null entry .walkTopDown() .maxDepth(if (isRecursive) Int.MAX_VALUE else 1) .onEnter { dir -> if (outerProjectSettings == null && innerProjectSettings == null) { val dotIdea = dir.resolve(".idea") innerProjectSettings = findCodeStyleSettings(dotIdea) ?.also { currentProject = dir LOG.info("Switching to project specific settings for ${dir.path}") } } LOG.info("Scanning directory ${dir.path}") true } .onLeave { if (it == currentProject) { currentProject = null innerProjectSettings = null } } .filter { it.isFile } .filter { it.matchesFileMask() } .map { ioFile -> ioFile.toVirtualFile() } .onEach { vFile -> charset?.let { vFile.charset = it } } .forEach { vFile -> LOG.info("Processing ${vFile.path}") statistics.fileTraversed() processVirtualFile(vFile, outerProjectSettings ?: innerProjectSettings) } } abstract fun processVirtualFile(virtualFile: VirtualFile, projectSettings: CodeStyleSettings?) fun getFileMasks() = fileMasks.toList() fun getEntries() = topEntries.toList() } // Finds nearest enclosing project contains this file private tailrec fun File.getOuterProject(): File? { val parent: File = absoluteFile.parentFile ?: return null val dotIdea = parent.resolve(".idea") if (dotIdea.isDirectory) return dotIdea return parent.getOuterProject() } private val documentBuilderFactory = DocumentBuilderFactory.newInstance() private val xPathFactory = XPathFactory.newInstance() private val usePerProjectSelector = "/component[@name='ProjectCodeStyleConfiguration']/state/option[@name='USE_PER_PROJECT_SETTINGS']/@value='true'" private val usePerProjectXPath = xPathFactory.newXPath().compile(usePerProjectSelector) private fun findCodeStyleSettings(dotIdea: File?): CodeStyleSettings? { if (dotIdea == null) return null if (!dotIdea.isDirectory) return null val codeStyles = dotIdea.resolve("codeStyles") if (!codeStyles.isDirectory) return null val codeStyleConfig = codeStyles.resolve("codeStyleConfig.xml") if (!codeStyleConfig.isFile) return null val doc = documentBuilderFactory .newDocumentBuilder() .parse(codeStyleConfig) usePerProjectXPath .evaluateExpression(doc) .takeIf { it.type() == XPathEvaluationResult.XPathResultType.BOOLEAN } ?.takeIf { it.value() == true } ?: return null return codeStyles .resolve("Project.xml") .takeIf { it.isFile } ?.let { readSettings(it) } }
apache-2.0
132229d60e62bb2744c66bd0cbc32d6a
30.732394
158
0.706613
4.470238
false
false
false
false
dkandalov/katas
kotlin/src/katas/kotlin/parser/v2/ParserTests.kt
1
1359
package katas.kotlin.parser.v2 import datsok.* import org.junit.* class ParserTests { @Test fun `number addition`() { str("hello")(Input("hello")) shouldEqual Output("hello", Input("hello", offset = 5)) str("hello")(Input("world")) shouldEqual null seq(str("hello"), str(" "), str("world"))(Input("hello world"))?.payload shouldEqual listOf("hello", " ", "world") seq(str("hello"), str(" "), str("world"))(Input("hello"))?.payload shouldEqual null eval("1 + 2") shouldEqual 3 } } private typealias Parser = (input: Input) -> Output? data class Input(val s: String, val offset: Int = 0) data class Output(val payload: Any, val input: Input) private fun str(s: String): Parser = { input -> if (input.s.substring(input.offset).startsWith(s)) Output(s, input.copy(offset = input.offset + s.length)) else null } private fun seq(vararg parsers: Parser): Parser = object: Parser { override fun invoke(input: Input): Output? { val payloads = ArrayList<Any>() var lastInput = input parsers.forEach { parser -> val (payload, updatedInput) = parser(lastInput) ?: return null payloads.add(payload) lastInput = updatedInput } return Output(payloads, lastInput) } } private fun eval(input: String): Any { return 3 }
unlicense
8329169829e00c6bdd5f8bb1318e20ec
30.627907
122
0.624724
3.93913
false
false
false
false
airbnb/epoxy
kotlinsample/src/main/java/com/airbnb/epoxy/kotlinsample/helpers/ViewBindingEpoxyModelWithHolder.kt
1
2375
package com.airbnb.epoxy.kotlinsample.helpers import android.view.View import android.view.ViewParent import androidx.viewbinding.ViewBinding import com.airbnb.epoxy.EpoxyHolder import com.airbnb.epoxy.EpoxyModelWithHolder import java.lang.reflect.Method import java.lang.reflect.ParameterizedType import java.util.concurrent.ConcurrentHashMap abstract class ViewBindingEpoxyModelWithHolder<in T : ViewBinding> : EpoxyModelWithHolder<ViewBindingHolder>() { @Suppress("UNCHECKED_CAST") override fun bind(holder: ViewBindingHolder) { (holder.viewBinding as T).bind() } abstract fun T.bind() @Suppress("UNCHECKED_CAST") override fun unbind(holder: ViewBindingHolder) { (holder.viewBinding as T).unbind() } open fun T.unbind() {} override fun createNewHolder(parent: ViewParent): ViewBindingHolder { return ViewBindingHolder(this::class.java) } } // Static cache of a method pointer for each type of item used. private val sBindingMethodByClass = ConcurrentHashMap<Class<*>, Method>() @Suppress("UNCHECKED_CAST") @Synchronized private fun getBindMethodFrom(javaClass: Class<*>): Method = sBindingMethodByClass.getOrPut(javaClass) { val actualTypeOfThis = getSuperclassParameterizedType(javaClass) val viewBindingClass = actualTypeOfThis.actualTypeArguments[0] as Class<ViewBinding> viewBindingClass.getDeclaredMethod("bind", View::class.java) ?: error("The binder class ${javaClass.canonicalName} should have a method bind(View)") } private fun getSuperclassParameterizedType(klass: Class<*>): ParameterizedType { val genericSuperclass = klass.genericSuperclass return (genericSuperclass as? ParameterizedType) ?: getSuperclassParameterizedType(genericSuperclass as Class<*>) } class ViewBindingHolder(private val epoxyModelClass: Class<*>) : EpoxyHolder() { // Using reflection to get the static binding method. // Lazy so it's computed only once by instance, when the 1st ViewHolder is actually created. private val bindingMethod by lazy { getBindMethodFrom(epoxyModelClass) } internal lateinit var viewBinding: ViewBinding override fun bindView(itemView: View) { // The 1st param is null because the binding method is static. viewBinding = bindingMethod.invoke(null, itemView) as ViewBinding } }
apache-2.0
fd59e4865445b828c6eebcd1e2c75e59
36.698413
99
0.749895
4.75
false
false
false
false
oneils/html4email-kotlin
src/test/kotlin/info/idgst/digest/DigestEmailServiceTest.kt
2
1912
package info.idgst.digest import info.idgst.AbstractTest import org.junit.Test import org.mockito.Matchers import org.mockito.Mock import org.mockito.Mockito.* import org.springframework.core.io.FileSystemResource import java.lang.RuntimeException /** * Test for [DigestEmailService] */ class DigestEmailServiceTest : AbstractTest() { @Mock private lateinit var mailService: MailService @Mock private lateinit var digestTemplateProcessor: DigestTemplateProcessor private lateinit var digestEmailService: DigestEmailService override fun before() { super.before() digestEmailService = DigestEmailService(mailService, digestTemplateProcessor) } @Test(expected = RuntimeException::class) fun `sendEmail should not send empty template`() { // Setup `when`(digestTemplateProcessor.generateTemplateDigest(any())).thenReturn("") // Run digestEmailService.sendViaEmail(emptyMap()) // Verify verify(mailService, never()).sendEmail(Matchers.any(), Matchers.any()) } @Test fun `sendEmail should send generated html template via email`() { // Setup val digestNumber = 123 val subject = "Digest Title" val sendTo = "[email protected],[email protected]" val recipients = sendTo.split(",").toTypedArray() val model = mapOf("digestNumber" to digestNumber, "digestTitle" to subject, "sendTo" to sendTo) val digestHtmlTemplate = "generated html content" `when`(digestTemplateProcessor.generateTemplateDigest(any())).thenReturn(digestHtmlTemplate) val digestLogoImg = FileSystemResource("images/logos/$digestNumber.png") // Run digestEmailService.sendViaEmail(model) // Verify verify(mailService).sendEmail(EmailMessage(digestHtmlTemplate, true, subject, EmailAttachment(digestLogoImg)), recipients) } }
apache-2.0
0b3894600ac5b496af71529d41649fe0
31.965517
130
0.709205
4.552381
false
true
false
false
paplorinc/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GithubPullRequestDataProviderImpl.kt
1
6223
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.data import com.intellij.openapi.Disposable import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.util.EventDispatcher import git4idea.GitCommit import git4idea.commands.Git import git4idea.history.GitLogUtil import git4idea.repo.GitRemote import git4idea.repo.GitRepository import org.jetbrains.annotations.CalledInAwt import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.api.GithubApiRequests import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.api.data.GithubCommit import org.jetbrains.plugins.github.api.data.GithubPullRequestDetailedWithHtml import org.jetbrains.plugins.github.api.util.GithubApiPagesLoader import org.jetbrains.plugins.github.util.GithubAsyncUtil import org.jetbrains.plugins.github.util.LazyCancellableBackgroundProcessValue import java.util.concurrent.CancellationException import java.util.concurrent.CompletableFuture import java.util.concurrent.CompletionException internal class GithubPullRequestDataProviderImpl(private val project: Project, private val progressManager: ProgressManager, private val git: Git, private val requestExecutor: GithubApiRequestExecutor, private val repository: GitRepository, private val remote: GitRemote, private val serverPath: GithubServerPath, private val username: String, private val repositoryName: String, override val number: Long) : GithubPullRequestDataProvider, Disposable { private val requestsChangesEventDispatcher = EventDispatcher.create(GithubPullRequestDataProvider.RequestsChangedListener::class.java) private var lastKnownHeadSha: String? = null private val detailsRequestValue = object : LazyCancellableBackgroundProcessValue<GithubPullRequestDetailedWithHtml>(progressManager) { override fun compute(indicator: ProgressIndicator): GithubPullRequestDetailedWithHtml { val details = requestExecutor.execute(indicator, GithubApiRequests.Repos.PullRequests.getHtml(serverPath, username, repositoryName, number)) invokeAndWaitIfNeeded { lastKnownHeadSha?.run { if (this != details.head.sha) reloadCommits() } lastKnownHeadSha = details.head.sha } return details } } override val detailsRequest get() = GithubAsyncUtil.futureOfMutable { invokeAndWaitIfNeeded { detailsRequestValue.value } } private val branchFetchRequestValue = object : LazyCancellableBackgroundProcessValue<Unit>(progressManager) { override fun compute(indicator: ProgressIndicator) { git.fetch(repository, remote, emptyList(), "refs/pull/${number}/head:").throwOnError() } } override val branchFetchRequest get() = GithubAsyncUtil.futureOfMutable { invokeAndWaitIfNeeded { branchFetchRequestValue.value } } private val apiCommitsRequestValue = object : LazyCancellableBackgroundProcessValue<List<GithubCommit>>(progressManager) { override fun compute(indicator: ProgressIndicator) = GithubApiPagesLoader .loadAll(requestExecutor, indicator, GithubApiRequests.Repos.PullRequests.Commits.pages(serverPath, username, repositoryName, number)) } override val apiCommitsRequest get() = GithubAsyncUtil.futureOfMutable { invokeAndWaitIfNeeded { apiCommitsRequestValue.value } } private val logCommitsRequestValue = object : LazyCancellableBackgroundProcessValue<List<GitCommit>>(progressManager) { override fun compute(indicator: ProgressIndicator): List<GitCommit> { branchFetchRequestValue.value.joinCancellable() val commitHashes = apiCommitsRequestValue.value.joinCancellable().map { it.sha } val gitCommits = mutableListOf<GitCommit>() GitLogUtil.readFullDetailsForHashes(project, repository.root, repository.vcs, { gitCommits.add(it) }, commitHashes, false, false, false, true, GitLogUtil.DiffRenameLimit.INFINITY) return gitCommits } } override val logCommitsRequest get() = GithubAsyncUtil.futureOfMutable { invokeAndWaitIfNeeded { logCommitsRequestValue.value } } @CalledInAwt override fun reloadDetails() { detailsRequestValue.drop() requestsChangesEventDispatcher.multicaster.detailsRequestChanged() } @CalledInAwt override fun reloadCommits() { branchFetchRequestValue.drop() apiCommitsRequestValue.drop() logCommitsRequestValue.drop() requestsChangesEventDispatcher.multicaster.commitsRequestChanged() } @CalledInAwt override fun dispose() { detailsRequestValue.drop() branchFetchRequestValue.drop() apiCommitsRequestValue.drop() logCommitsRequestValue.drop() } @Throws(ProcessCanceledException::class) private fun <T> CompletableFuture<T>.joinCancellable(): T { try { return join() } catch (e: CancellationException) { throw ProcessCanceledException(e) } catch (e: CompletionException) { if (GithubAsyncUtil.isCancellation(e)) throw ProcessCanceledException(e) throw e.cause ?: e } } override fun addRequestsChangesListener(listener: GithubPullRequestDataProvider.RequestsChangedListener) = requestsChangesEventDispatcher.addListener(listener) override fun removeRequestsChangesListener(listener: GithubPullRequestDataProvider.RequestsChangedListener) = requestsChangesEventDispatcher.removeListener(listener) }
apache-2.0
8f5b4e30d7b04e0c2204194ccad9e05f
46.876923
140
0.734372
5.492498
false
false
false
false
Zeyad-37/RxRedux
core/src/main/java/com/zeyad/rxredux/core/vm/SimpleRxViewModel.kt
1
2371
package com.zeyad.rxredux.core.vm import com.zeyad.rxredux.core.vm.rxvm.Effect import com.zeyad.rxredux.core.vm.rxvm.EmptyResult import com.zeyad.rxredux.core.vm.rxvm.Error import com.zeyad.rxredux.core.vm.rxvm.Input import com.zeyad.rxredux.core.vm.rxvm.State import io.reactivex.Flowable import io.reactivex.android.schedulers.AndroidSchedulers abstract class SimpleRxViewModel<I : Input, S : State, E : Effect> : BaseRxViewModel<I, S, EmptyResult, E>() { val outcomes: RxOutcomes = RxOutcomes() open inner class RxOutcomes { fun effect(effect: E): RxOutcome = RxEffect(effect) fun empty(): RxOutcome = RxEmpty fun error(error: Throwable): RxOutcome = RxError(Error(error.message.orEmpty(), error)) fun state(state: S): RxOutcome = RxState(state) } override fun processOutcomes(outcomes: Flowable<RxOutcome>) { disposable = outcomes .observeOn(AndroidSchedulers.mainThread()) .doOnNext { trackEvents(it) logEvents(it) if (it is RxState) { trackState(it.state, it.input) logState(it.state) } handleResult(it) } .subscribe() } private fun nextState(state: S, input: I): RxOutcome = RxState(state, input) // Methods to use to render a new state in VM subclasses in handleInputs method // 1. when asynchronous call IS NOT needed to render a new state // for instance: Flowable.just(input.newState { renderNewState(input) }) // where renderNewState is a function returning new State based on input and current state (if applicable) @Deprecated("Use outcomes.state() instead") fun Input.newState(stateCreator: (input: Input) -> S): RxOutcome = nextState(stateCreator.invoke(this), this as I) // 2. when asynchronous call IS needed to render a new state // for instance: input.newRxState { getChangeBackgroundState(input) } // where renderNewState is a function returning Flowable with new State based on input and current state (if applicable) @Deprecated("Use outcomes.state() instead") fun I.newRxState(stateCreator: (I) -> Flowable<S>): Flowable<RxOutcome> = stateCreator.invoke(this).map { nextState(it, this) } }
apache-2.0
fdaf28df9d80aa1cc927d8f2a39a69b2
39.87931
124
0.655841
4.226381
false
false
false
false
akhbulatov/wordkeeper
app/src/main/java/com/akhbulatov/wordkeeper/presentation/ui/global/list/adapters/WordAdapter.kt
1
3440
package com.akhbulatov.wordkeeper.presentation.ui.global.list.adapters import android.graphics.Color import android.util.SparseBooleanArray import android.view.LayoutInflater import android.view.ViewGroup import androidx.core.util.contains import androidx.core.util.forEach import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.akhbulatov.wordkeeper.R import com.akhbulatov.wordkeeper.databinding.ItemWordBinding import com.akhbulatov.wordkeeper.domain.global.models.Word import com.akhbulatov.wordkeeper.presentation.ui.global.list.adapters.WordAdapter.WordViewHolder import com.akhbulatov.wordkeeper.presentation.ui.global.list.viewholders.BaseViewHolder import com.akhbulatov.wordkeeper.presentation.ui.global.utils.color class WordAdapter( private val onItemClickListener: OnItemClickListener? = null ) : ListAdapter<Word, WordViewHolder>(DIFF_CALLBACK) { private val selectedWords = SparseBooleanArray() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder { val inflater = LayoutInflater.from(parent.context) val binding = ItemWordBinding.inflate(inflater, parent, false) return WordViewHolder(binding) } override fun onBindViewHolder(holder: WordViewHolder, position: Int) { holder.bind(getItem(position)) } fun getSelectedWordPositions(): List<Int> { val words = arrayListOf<Int>() selectedWords.forEach { key, _ -> words.add(key) } return words } fun getSelectedWordCount(): Int = selectedWords.size() fun toggleSelection(position: Int) { if (selectedWords[position, false]) { selectedWords.delete(position) } else { selectedWords.put(position, true) } notifyItemChanged(position) } fun clearSelection() { val selection = getSelectedWordPositions() selectedWords.clear() for (i in selection) { notifyItemChanged(i) } } inner class WordViewHolder(private val binding: ItemWordBinding) : BaseViewHolder<Word>(binding.root) { init { itemView.setOnClickListener { onItemClickListener?.onItemClick(bindingAdapterPosition) } itemView.setOnLongClickListener { onItemClickListener?.onItemLongClick(bindingAdapterPosition) ?: false } } override fun bind(item: Word) { with(binding) { val ctx = itemView.context nameTextView.text = item.name translationTextView.text = item.translation val selectedItemColor = if (selectedWords.contains(bindingAdapterPosition)) { ctx.color(R.color.selected_list_item) } else { Color.TRANSPARENT } itemView.setBackgroundColor(selectedItemColor) } } } interface OnItemClickListener { fun onItemClick(position: Int) fun onItemLongClick(position: Int): Boolean } companion object { private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<Word>() { override fun areItemsTheSame(oldItem: Word, newItem: Word): Boolean = oldItem.id == newItem.id override fun areContentsTheSame(oldItem: Word, newItem: Word): Boolean = oldItem == newItem } } }
apache-2.0
fa189004bce00bf226ab1edaa313e1c2
34.102041
117
0.676163
5.073746
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/nbt/lang/format/NbttFormattingModelBuilder.kt
1
2622
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.format import com.demonwav.mcdev.nbt.lang.NbttLanguage import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.formatting.FormattingModel import com.intellij.formatting.FormattingModelBuilder import com.intellij.formatting.FormattingModelProvider import com.intellij.formatting.Indent import com.intellij.formatting.SpacingBuilder import com.intellij.psi.PsiElement import com.intellij.psi.codeStyle.CodeStyleSettings class NbttFormattingModelBuilder : FormattingModelBuilder { override fun createModel(element: PsiElement, settings: CodeStyleSettings): FormattingModel { val block = NbttBlock(element.node, settings, Indent.getNoneIndent(), null) return FormattingModelProvider.createFormattingModelForPsiFile(element.containingFile, block, settings) } companion object { fun createSpacingBuilder(settings: CodeStyleSettings): SpacingBuilder { val nbttSettings = settings.getCustomSettings(NbttCodeStyleSettings::class.java) val commonSettings = settings.getCommonSettings(NbttLanguage) val spacesBeforeComma = if (commonSettings.SPACE_BEFORE_COMMA) 1 else 0 val spacesBeforeColon = if (nbttSettings.SPACE_BEFORE_COLON) 1 else 0 val spacesAfterColon = if (nbttSettings.SPACE_AFTER_COLON) 1 else 0 return SpacingBuilder(settings, NbttLanguage) .before(NbttTypes.COLON).spacing(spacesBeforeColon, spacesBeforeColon, 0, false, 0) .after(NbttTypes.COLON).spacing(spacesAfterColon, spacesAfterColon, 0, false, 0) // Empty blocks .between(NbttTypes.LBRACKET, NbttTypes.RBRACKET).spacing(0, 0, 0, false, 0) .between(NbttTypes.LPAREN, NbttTypes.RPAREN).spacing(0, 0, 0, false, 0) .between(NbttTypes.LBRACE, NbttTypes.RBRACE).spacing(0, 0, 0, false, 0) // Non-empty blocks .withinPair(NbttTypes.LBRACKET, NbttTypes.RBRACKET).spaceIf(commonSettings.SPACE_WITHIN_BRACKETS, true) .withinPair(NbttTypes.LPAREN, NbttTypes.RPAREN).spaceIf(commonSettings.SPACE_WITHIN_PARENTHESES, true) .withinPair(NbttTypes.LBRACE, NbttTypes.RBRACE).spaceIf(commonSettings.SPACE_WITHIN_BRACES, true) .before(NbttTypes.COMMA).spacing(spacesBeforeComma, spacesBeforeComma, 0, false, 0) .after(NbttTypes.COMMA).spaceIf(commonSettings.SPACE_AFTER_COMMA) } } }
mit
8b5db9a790981ac9613151be3f645106
48.471698
119
0.719298
4.46678
false
false
false
false
google/intellij-community
build/src/org/jetbrains/intellij/build/ExternalPluginBundler.kt
5
1518
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build import com.intellij.util.io.Decompressor import java.nio.file.Files import java.nio.file.Path import java.util.* object ExternalPluginBundler { @JvmStatic @JvmOverloads fun bundle(pluginName: String, dependenciesPath: String, context: BuildContext, targetDirectory: String, buildTaskName: String = pluginName) { val dependenciesProjectDir = Path.of(dependenciesPath) GradleRunner(gradleProjectDir = dependenciesProjectDir, options = context.options, communityRoot = context.paths.communityHomeDir, additionalParams = emptyList()) .run("Downloading $pluginName plugin...", "setup${buildTaskName}Plugin") val properties = Properties() Files.newInputStream(dependenciesProjectDir.resolve("gradle.properties")).use { properties.load(it) } val pluginZip = dependenciesProjectDir.resolve( "build/$pluginName/$pluginName-${properties.getProperty("${buildTaskName}PluginVersion")}.zip") check(Files.exists(pluginZip)) { "$pluginName bundled plugin is not found. Plugin path:${pluginZip}" } extractPlugin(pluginZip, targetDirectory) } @JvmStatic fun extractPlugin(pluginZip: Path, targetDirectory: String) { Decompressor.Zip(pluginZip).extract(Path.of(targetDirectory, "plugins")) } }
apache-2.0
4c18a4e67b9cab393714c9e1ed9039d9
36.975
120
0.706851
4.74375
false
false
false
false