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
SkyTreasure/Kotlin-Firebase-Group-Chat
app/src/main/java/io/skytreasure/kotlingroupchat/common/util/SharedPrefManager.kt
1
4835
package io.skytreasure.kotlingroupchat.common.util import android.content.Context import android.content.SharedPreferences import android.util.Base64 import com.google.gson.Gson import io.skytreasure.kotlingroupchat.chat.model.UserModel import io.skytreasure.kotlingroupchat.common.constants.PrefConstants import java.util.* /** * Created by akash on 24/10/17. */ class SharedPrefManager private constructor(context: Context) { @get:Synchronized private val preferences: SharedPreferences private val gson = Gson() init { preferences = context.getSharedPreferences(SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE) } /** * Use this method to save key value pair, can be encrypted * @param key Key to save * * * @param value Value to save * * * @param shouldEncrypt If true, it will encrypt, else it will be saved as usual. */ fun savePreferences(key: String, value: String, shouldEncrypt: Boolean) { if (shouldEncrypt) { val saveText = Base64.encodeToString(value.toByteArray(), Base64.DEFAULT) val editor = preferences.edit() editor.putString(key, saveText) editor.apply() } else { val editor = preferences.edit() editor.putString(key, value) editor.apply() } } /** * Call this method to get the shared preference instance * @param context * * * @return */ fun getInstance(context: Context): SharedPrefManager { if (instance == null) { instance = SharedPrefManager(context) } return instance as SharedPrefManager } @Synchronized private fun getPreferences(): SharedPreferences { return preferences } /** * Use this method to save preferences * @param key * * * @param value */ fun savePreferences(key: String, value: String) { val editor = preferences.edit() editor.putString(key, value) editor.apply() } /** * Returns default value which is passed when called, else returns the actual value * @param key * * * @param defaultValue * * * @return */ fun ifEmptyReturnDefault(key: String, defaultValue: String): String { if (isEmpty(key)) { return defaultValue } else { return getSavedPref(key) } } /** * Get the saved preferences value from shared preference * @param key Key to fetch, returns "" if not found * * * @param isEncrypted if true tries to decrypt the fetched data * * * @return Value */ fun getSavedPref(key: String, isEncrypted: Boolean): String { if (isEncrypted) { val text = preferences.getString(key, null) ?: return "" val converted = String(Base64.decode(text, Base64.DEFAULT)) return converted } else { val text = preferences.getString(key, null) ?: return "" return text } } fun getSavedPref(key: String): String { val text = preferences.getString(key, null) ?: return "" return text } /** * Checks if the value for that key in sharedpref is empty or not * @param key * * * @return */ fun isEmpty(key: String): Boolean { val result = getSavedPref(key, false) return result.equals("", ignoreCase = true) } /** * Pass key and value, compares the value with the value in the sharedpreference * @param key * * * @param value * * * @return */ fun isEqualTo(key: String, value: String): Boolean { val result = getSavedPref(key, false) return result.equals(value, ignoreCase = true) } /** * Clears all the shared preference data */ fun cleanSharedPreferences() { preferences.edit().clear().apply() } /** * @return */ val savedUserModel: UserModel? get() { if (isEmpty(PrefConstants.USER_DATA)) { return null } else { return gson.fromJson(getSavedPref(PrefConstants.USER_DATA, false), UserModel::class.java) } } companion object { private val SHARED_PREFERENCE_NAME = "microland" private var instance: SharedPrefManager? = null /** * Call this method to get the shared preference instance * @param context * * * @return */ fun getInstance(context: Context): SharedPrefManager { if (instance == null) { instance = SharedPrefManager(context) } return instance as SharedPrefManager } } }
mit
5b89cfe345dc7a144ff77d03a54a4e4f
23.543147
105
0.583454
4.666988
false
false
false
false
WhisperSystems/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/search/EmojiSearchViewModel.kt
1
1390
package org.thoughtcrime.securesms.keyboard.emoji.search import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import org.thoughtcrime.securesms.components.emoji.EmojiPageModel import org.thoughtcrime.securesms.components.emoji.RecentEmojiPageModel import org.thoughtcrime.securesms.keyboard.emoji.toMappingModels import org.thoughtcrime.securesms.util.MappingModel import org.thoughtcrime.securesms.util.livedata.LiveDataUtil class EmojiSearchViewModel(private val repository: EmojiSearchRepository) : ViewModel() { private val pageModel = MutableLiveData<EmojiPageModel>() val emojiList: LiveData<EmojiSearchResults> = LiveDataUtil.mapAsync(pageModel) { page -> EmojiSearchResults(page.toMappingModels(), page.key == RecentEmojiPageModel.KEY) } init { onQueryChanged("") } fun onQueryChanged(query: String) { repository.submitQuery(query = query, includeRecents = true, consumer = pageModel::postValue) } data class EmojiSearchResults(val emojiList: List<MappingModel<*>>, val isRecents: Boolean) class Factory(private val repository: EmojiSearchRepository) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return requireNotNull(modelClass.cast(EmojiSearchViewModel(repository))) } } }
gpl-3.0
ffc28e8dbc708fb6b54304f63c09d91d
37.611111
97
0.801439
4.727891
false
false
false
false
bkmioa/NexusRss
app/src/main/java/io/github/bkmioa/nexusrss/ui/TabEditActivity.kt
1
2770
package io.github.bkmioa.nexusrss.ui import android.app.Activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.ActionBar import io.github.bkmioa.nexusrss.R import io.github.bkmioa.nexusrss.base.BaseActivity import io.github.bkmioa.nexusrss.model.Tab import kotlinx.android.synthetic.main.activity_tab_edit.* class TabEditActivity : BaseActivity() { private lateinit var optionFragment: OptionFragment companion object { fun createIntent(context: Context, tab: Tab? = null): Intent { val intent = Intent(context, TabEditActivity::class.java) intent.putExtra("tab", tab) return intent } } private var tab: Tab? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tab_edit) setSupportActionBar(toolBar) supportActionBar?.displayOptions = ActionBar.DISPLAY_HOME_AS_UP or ActionBar.DISPLAY_SHOW_TITLE tab = intent.getParcelableExtra("tab") tab?.apply { editTextTitle.setText(title) } optionFragment = supportFragmentManager.findFragmentByTag("options") as? OptionFragment ?: OptionFragment.newInstance(tab?.path,tab?.options, true, tab?.columnCount ?: 1) supportFragmentManager.beginTransaction() .replace(R.id.optionContainer, optionFragment, "options") .commit() } override fun onCreateOptionsMenu(menu: Menu): Boolean { val menuDone = menu.add("Done") menuDone.setIcon(R.drawable.ic_menu_done) menuDone.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS) menuDone.setOnMenuItemClickListener { done() true } return true } private fun done() { val editable = editTextTitle.text ?: throw IllegalStateException() if (editable.isEmpty()) { editTextTitle.error = "item_empty!!" return } val path = optionFragment.selectedCategory.path val options = optionFragment.selected.toTypedArray() val columnCount = optionFragment.columnCount val tab: Tab if (this.tab == null) { tab = Tab(editable.toString(),path, options, columnCount) } else { tab = this.tab ?: return tab.title = editable.toString() tab.path = path tab.options = options tab.columnCount = columnCount } val intent = Intent() intent.putExtra("tab", tab) setResult(Activity.RESULT_OK, intent) finish() } }
apache-2.0
79117384359dc4a0b6afbbca41f2f065
31.588235
103
0.645848
4.735043
false
false
false
false
ACRA/acra
acra-limiter/src/main/java/org/acra/config/LimitingReportAdministrator.kt
1
5600
/* * Copyright (c) 2017 * * 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.acra.config import android.content.Context import android.os.Build import android.os.Handler import android.os.Looper import android.widget.Toast import com.google.auto.service.AutoService import org.acra.builder.ReportBuilder import org.acra.config.LimiterData.Companion.load import org.acra.config.LimiterData.ReportMetadata import org.acra.data.CrashReportData import org.acra.file.ReportLocator import org.acra.log.debug import org.acra.log.warn import org.acra.plugins.HasConfigPlugin import org.acra.util.ToastSender.sendToast import org.json.JSONException import java.io.IOException import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.Executors /** * @author F43nd1r * @since 26.10.2017 */ @AutoService(ReportingAdministrator::class) class LimitingReportAdministrator : HasConfigPlugin(LimiterConfiguration::class.java), ReportingAdministrator { override fun shouldStartCollecting(context: Context, config: CoreConfiguration, reportBuilder: ReportBuilder): Boolean { try { val limiterConfiguration = config.getPluginConfiguration<LimiterConfiguration>() val reportLocator = ReportLocator(context) if (reportLocator.approvedReports.size + reportLocator.unapprovedReports.size >= limiterConfiguration.failedReportLimit) { debug { "Reached failedReportLimit, not collecting" } return false } val reportMetadata = loadLimiterData(context, limiterConfiguration).reportMetadata if (reportMetadata.size >= limiterConfiguration.overallLimit) { debug { "Reached overallLimit, not collecting" } return false } } catch (e: IOException) { warn(e) { "Failed to load LimiterData" } } return true } override fun shouldSendReport(context: Context, config: CoreConfiguration, crashReportData: CrashReportData): Boolean { try { val limiterConfiguration = config.getPluginConfiguration<LimiterConfiguration>() val limiterData = loadLimiterData(context, limiterConfiguration) var sameTrace = 0 var sameClass = 0 val m = ReportMetadata(crashReportData) for (metadata in limiterData.reportMetadata) { if (m.stacktrace == metadata.stacktrace) { sameTrace++ } if (m.exceptionClass == metadata.exceptionClass) { sameClass++ } } if (sameTrace >= limiterConfiguration.stacktraceLimit) { debug { "Reached stacktraceLimit, not sending" } return false } if (sameClass >= limiterConfiguration.exceptionClassLimit) { debug { "Reached exceptionClassLimit, not sending" } return false } limiterData.reportMetadata.add(m) limiterData.store(context) } catch (e: IOException) { warn(e) { "Failed to load LimiterData" } } catch (e: JSONException) { warn(e) { "Failed to load LimiterData" } } return true } override fun notifyReportDropped(context: Context, config: CoreConfiguration) { val limiterConfiguration = config.getPluginConfiguration<LimiterConfiguration>() if (limiterConfiguration.ignoredCrashToast?.isNotEmpty() == true) { val future = Executors.newSingleThreadExecutor().submit { Looper.prepare() sendToast(context, limiterConfiguration.ignoredCrashToast, Toast.LENGTH_LONG) val looper = Looper.myLooper() if (looper != null) { Handler(looper).postDelayed({ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { looper.quitSafely() } else { looper.quit() } }, 4000) Looper.loop() } } while (!future.isDone) { try { future.get() } catch (ignored: InterruptedException) { } catch (e: ExecutionException) { //ReportInteraction crashed, so ignore it break } } } } @Throws(IOException::class) private fun loadLimiterData(context: Context, limiterConfiguration: LimiterConfiguration): LimiterData { val limiterData = load(context) val keepAfter = Calendar.getInstance() keepAfter.add(Calendar.MINUTE, (-limiterConfiguration.periodUnit.toMinutes(limiterConfiguration.period)).toInt()) debug { "purging reports older than ${keepAfter.time}" } limiterData.purgeOldData(keepAfter) limiterData.store(context) return limiterData } }
apache-2.0
9018e1d4fd6d8da330c470cdd069c5e4
39.883212
134
0.630714
4.823428
false
true
false
false
JavaEden/Orchid-Core
OrchidCore/src/main/kotlin/com/eden/orchid/api/theme/menus/MenuItem.kt
2
6257
package com.eden.orchid.api.theme.menus import com.caseyjbrooks.clog.Clog import com.eden.common.util.EdenUtils import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.indexing.OrchidIndex import com.eden.orchid.api.theme.pages.OrchidPage import java.util.ArrayList import java.util.Comparator class MenuItem private constructor( val context: OrchidContext, val title: String, val page: OrchidPage?, private val _children: List<MenuItem>, val anchor: String, val isSeparator: Boolean, var allData: Map<String, Any>, var indexComparator: Comparator<MenuItem>? ) { val children: List<MenuItem> get() { if (indexComparator != null) { for (child in _children) { child.indexComparator = indexComparator } return _children.sortedWith(indexComparator!!) } return _children } val link: String get() = if (page != null) { if (!EdenUtils.isEmpty(anchor)) { "${page.link}#$anchor" } else { page.link } } else { if (!EdenUtils.isEmpty(anchor)) { "#$anchor" } else { "" } } val isHasChildren: Boolean get() = hasChildren() fun isActive(page: OrchidPage): Boolean { return (!isHasChildren && isActivePage(page)) || (isHasChildren && hasActivePage(page)) } fun isActivePage(page: OrchidPage): Boolean { return this.page === page } fun hasActivePage(page: OrchidPage): Boolean { for (child in children) { if (child.isActivePage(page) || child.hasActivePage(page)) { return true } } return false } @JvmOverloads fun activeClass(page: OrchidPage, className: String = "active"): String { return if (isActive(page)) className else "" } fun hasChildren(): Boolean { return !EdenUtils.isEmpty(children) } fun hasOwnLink(): Boolean { return page != null || anchor.isNotBlank() } fun isExternal(): Boolean { return !link.startsWith(context.baseUrl) } operator fun get(key: String): Any? { return allData[key] } fun toBuilder(): MenuItem.Builder { return MenuItem.Builder(context) .title(title) .page(page) .children(children) .anchor(anchor) .separator(isSeparator) .data(allData) .indexComparator(indexComparator) } // Builder //---------------------------------------------------------------------------------------------------------------------- class Builder(val context: OrchidContext) { var children: MutableList<MenuItem.Builder>? = null var page: OrchidPage? = null var anchor: String? = null var title: String? = null var indexComparator: Comparator<MenuItem>? = null var data: Map<String, Any>? = null var separator: Boolean = false constructor(context: OrchidContext, builder: Builder.() -> Unit) : this(context) { this.builder() } fun fromIndex(index: OrchidIndex): Builder { if (children == null) { children = ArrayList() } if (index.children.isNotEmpty()) { for ((key, value) in index.children) { this.children!!.add(Builder(context).title(key).fromIndex(value)) } } if (!EdenUtils.isEmpty(index.getOwnPages())) { for (page in index.getOwnPages()) { if (page.reference.fileName == "index") { this.title(page.title).page(page) } else { this.children!!.add(Builder(context).page(page)) } } } return this } fun childrenBuilders(children: MutableList<MenuItem.Builder>): Builder { this.children = children return this } fun children(children: List<MenuItem>): Builder { this.children = children.map { it.toBuilder() }.toMutableList() return this } fun child(child: MenuItem.Builder): Builder { if (children == null) { children = ArrayList() } children!!.add(child) return this } fun pages(pages: List<OrchidPage>, transform: (Pair<OrchidPage, Builder>) -> Unit = {}): Builder { this.children = pages.map { page -> Builder(context) .page(page) .also { builder -> transform(page to builder) } }.toMutableList() return this } fun page(page: OrchidPage?): Builder { this.page = page return this } fun anchor(anchor: String): Builder { this.anchor = anchor return this } fun title(title: String): Builder { this.title = title return this } fun separator(separator: Boolean): Builder { this.separator = separator return this } fun indexComparator(indexComparator: Comparator<MenuItem>?): Builder { this.indexComparator = indexComparator return this } fun data(data: Map<String, Any>): Builder { this.data = data return this } fun build(): MenuItem { if (EdenUtils.isEmpty(title) && page != null) { title = page!!.title } if (EdenUtils.isEmpty(title) && !EdenUtils.isEmpty(anchor)) { title = anchor } return MenuItem( context, title ?: "", page, children?.map { it.build() } ?: emptyList(), anchor ?: "", separator, data ?: emptyMap(), indexComparator ) } } }
mit
79b420f85f96ae223664876f90fa23a2
27.312217
120
0.506952
5.017642
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/gradle/hmppImportAndHighlighting/multiModulesHmpp/top-mpp/src/macosMain/kotlin/transitiveStory/bottomActual/mppBeginning/BottomActualDeclarations.kt
8
1967
package transitiveStory.bottomActual.mppBeginning actual open class <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>BottomActualDeclarations<!> { actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>simpleVal<!>: Int = commonInt actual companion object <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>Compainon<!> { actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>inTheCompanionOfBottomActualDeclarations<!>: String = "I'm a string from the companion object of `$this` in `$sourceSetName` module `$moduleName`" } } actual open class <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'"), LINE_MARKER("descr='Is subclassed by ChildOfMPOuterInMacos Click or press ... to navigate'")!>MPOuter<!> { protected actual open val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>b<!>: Int = 4325 internal actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>c<!>: Int = 2345 actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>d<!>: Int = 325 protected actual class <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>MPNested<!> { actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>e<!>: Int = 345 } } class ChildOfCommonInMacos : Outer() { override val <!LINE_MARKER("descr='Overrides property in 'Outer''")!>b<!>: Int get() = super.b + 243 val callAlso = super.c // internal in Outer private val other = Nested() } class ChildOfMPOuterInMacos : MPOuter() { private val sav = MPNested() } actual val <!LINE_MARKER("descr='Has expects in multimod-hmpp.top-mpp.commonMain module'")!>sourceSetName<!>: String = "macosMain"
apache-2.0
1bbe4afb3eef71d672142d2df2fff285
55.2
206
0.705643
3.849315
false
false
false
false
ftomassetti/kolasu
emf/src/test/kotlin/com/strumenta/kolasu/emf/rpgast/data_definitions.kt
1
18407
package com.strumenta.kolasu.emf.rpgast import com.smeup.rpgparser.parsing.ast.Expression import com.strumenta.kolasu.model.* import java.math.BigDecimal import java.util.* abstract class AbstractDataDefinition( override val name: String, open val type: Type, specifiedPosition: Position? = null, private val hashCode: Int = name.hashCode() ) : Node(specifiedPosition), Named { fun numberOfElements() = type.numberOfElements() open fun elementSize() = type.elementSize() open fun isArray(): Boolean { return type is ArrayType } override fun hashCode() = hashCode override fun equals(other: Any?) = if (other is AbstractDataDefinition) name == other.name else false } data class FileDefinition private constructor(override val name: String, val specifiedPosition: Position?) : Node( specifiedPosition ), Named { companion object { operator fun invoke(name: String, specifiedPosition: Position? = null): FileDefinition { return FileDefinition(name.toUpperCase(), specifiedPosition) } } var internalFormatName: String? = null set(value) { field = value?.toUpperCase() } } data class DataDefinition( override val name: String, override val type: Type, var fields: List<FieldDefinition> = emptyList(), val initializationValue: Expression? = null, val inz: Boolean = false, val specifiedPosition: Position? = null ) : AbstractDataDefinition(name, type, specifiedPosition) { override fun isArray() = type is ArrayType fun isCompileTimeArray() = type is ArrayType && type.compileTimeArray() @Deprecated("The start offset should be calculated before defining the FieldDefinition") fun startOffset(fieldDefinition: FieldDefinition): Int { var start = 0 for (f in fields) { if (f == fieldDefinition) { require(start >= 0) return start } start += f.elementSize() } throw IllegalArgumentException("Unknown field $fieldDefinition") } @Deprecated("The end offset should be calculated before defining the FieldDefinition") fun endOffset(fieldDefinition: FieldDefinition): Int { return (startOffset(fieldDefinition) + fieldDefinition.elementSize()) } fun getFieldByName(fieldName: String): FieldDefinition { return this.fields.find { it.name == fieldName } ?: throw java.lang.IllegalArgumentException( "Field not found $fieldName" ) } } data class FieldDefinition( override val name: String, override val type: Type, val explicitStartOffset: Int? = null, val explicitEndOffset: Int? = null, val calculatedStartOffset: Int? = null, val calculatedEndOffset: Int? = null, // In case of using LIKEDS we reuse a FieldDefinition, but specifying a different // container. We basically duplicate it @property:Link var overriddenContainer: DataDefinition? = null, val initializationValue: Expression? = null, val descend: Boolean = false, val specifiedPosition: Position? = null, // true when the FieldDefinition contains a DIM keyword on its line val declaredArrayInLineOnThisField: Int? = null ) : AbstractDataDefinition(name, type, specifiedPosition) { init { require((explicitStartOffset != null) != (calculatedStartOffset != null)) { "Field $name should have either an explicit start offset ($explicitStartOffset) " + "or a calculated one ($calculatedStartOffset)" } require((explicitEndOffset != null) != (calculatedEndOffset != null)) { "Field $name should have either an explicit end offset ($explicitEndOffset) " + "or a calculated one ($calculatedEndOffset)" } } // true when the FieldDefinition contains a DIM keyword on its line // or when the field is overlaying on an a field which has the DIM keyword val declaredArrayInLine: Int? get() = declaredArrayInLineOnThisField ?: (overlayingOn as? FieldDefinition)?.declaredArrayInLine val size: Int = type.size @property:Link var overlayingOn: AbstractDataDefinition? = null internal var overlayTarget: String? = null // when they are arrays, how many bytes should we skip into the DS to find the next element? // normally it would be the same size as an element of the DS, however if they are declared // as on overlay of a field with a DIM keyword, then we should use the size of an element // of such field val stepSize: Int get() { return if (declaredArrayInLineOnThisField != null) { elementSize() } else { (overlayingOn as? FieldDefinition)?.stepSize ?: elementSize() } } override fun elementSize(): Int { return if (container.type is ArrayType) { super.elementSize() } else if (this.declaredArrayInLine != null) { super.elementSize() } else { size } } fun toDataStructureValue(value: Value) = type.toDataStructureValue(value) /** * The fields used through LIKEDS cannot be used unqualified */ fun canBeUsedUnqualified() = this.overriddenContainer == null @Derived val container get() = overriddenContainer ?: this.parent as? DataDefinition ?: throw IllegalStateException( "Parent of field ${this.name} was expected to be a DataDefinition, instead it is ${this.parent} " + "(${this.parent?.javaClass})" ) /** * The start offset is zero based, while in RPG code you could find explicit one-based offsets. * * For example: * 0002.00 DCURTIMSTP DS * 0003.00 DCURTIMDATE 1 8S 0 * * In this case CURTIMDATE will have startOffset 0. */ val startOffset: Int get() { if (explicitStartOffset != null) { return explicitStartOffset } if (calculatedStartOffset != null) { return calculatedStartOffset } return container.startOffset(this) } /** * The end offset is non-inclusive if considered zero based, or inclusive if considered one based. * * For example: * 0002.00 DCURTIMSTP DS * 0003.00 DCURTIMDATE 1 8S 0 * * In this case CURTIMDATE will have endOffset 8. * * In the case of an array endOffset indicates the end of the first element. */ val endOffset: Int get() { if (explicitEndOffset != null) { return explicitEndOffset } if (calculatedEndOffset != null) { return calculatedEndOffset } return container.endOffset(this) } @Derived val offsets: Pair<Int, Int> get() = Pair(startOffset, endOffset) override fun hashCode(): Int { return name.hashCode() * 31 + type.hashCode() * 7 } } // Positions 64 through 68 specify the length of the result field. This entry is optional, but can be used to define a // numeric or character field not defined elsewhere in the program. These definitions of the field entries are allowed // if the result field contains a field name. Other data types must be defined on the definition specification or on the // calculation specification using the *LIKE DEFINE operation. class InStatementDataDefinition( override val name: String, override val type: Type, val specifiedPosition: Position? = null, val initializationValue: Expression? = null ) : AbstractDataDefinition(name, type, specifiedPosition) { override fun toString(): String { return "InStatementDataDefinition name=$name, type=$type, specifiedPosition=$specifiedPosition" } } /** * Encoding/Decoding a binary value for a data structure */ fun encodeBinary(inValue: BigDecimal, size: Int): String { val buffer = ByteArray(size) val lsb = inValue.toInt() if (size == 1) { buffer[0] = (lsb and 0x0000FFFF).toByte() return buffer[0].toChar().toString() } if (size == 2) { buffer[0] = ((lsb shr 8) and 0x000000FF).toByte() buffer[1] = (lsb and 0x000000FF).toByte() return buffer[1].toChar().toString() + buffer[0].toChar().toString() } if (size == 4) { buffer[0] = ((lsb shr 24) and 0x0000FFFF).toByte() buffer[1] = ((lsb shr 16) and 0x0000FFFF).toByte() buffer[2] = ((lsb shr 8) and 0x0000FFFF).toByte() buffer[3] = (lsb and 0x0000FFFF).toByte() return buffer[3].toChar().toString() + buffer[2].toChar().toString() + buffer[1].toChar().toString() + buffer[0].toChar().toString() } if (size == 8) { val llsb = inValue.toLong() buffer[0] = ((llsb shr 56) and 0x0000FFFF).toByte() buffer[1] = ((llsb shr 48) and 0x0000FFFF).toByte() buffer[2] = ((llsb shr 40) and 0x0000FFFF).toByte() buffer[3] = ((llsb shr 32) and 0x0000FFFF).toByte() buffer[4] = ((llsb shr 24) and 0x0000FFFF).toByte() buffer[5] = ((llsb shr 16) and 0x0000FFFF).toByte() buffer[6] = ((llsb shr 8) and 0x0000FFFF).toByte() buffer[7] = (llsb and 0x0000FFFF).toByte() return buffer[7].toChar().toString() + buffer[6].toChar().toString() + buffer[5].toChar().toString() + buffer[4].toChar().toString() + buffer[3].toChar().toString() + buffer[2].toChar().toString() + buffer[1].toChar().toString() + buffer[0].toChar().toString() } TODO("encode binary for $size not implemented") } fun encodeInteger(inValue: BigDecimal, size: Int): String { return encodeBinary(inValue, size) } fun encodeUnsigned(inValue: BigDecimal, size: Int): String { return encodeBinary(inValue, size) } fun decodeBinary(value: String, size: Int): BigDecimal { if (size == 1) { var number: Long = 0x0000000 if (value[0].toInt() and 0x0010 != 0) { number = 0x00000000 } number += (value[0].toInt() and 0x00FF) return BigDecimal(number.toInt().toString()) } if (size == 2) { var number: Long = 0x0000000 if (value[1].toInt() and 0x8000 != 0) { number = 0xFFFF0000 } number += (value[0].toInt() and 0x00FF) + ((value[1].toInt() and 0x00FF) shl 8) return BigDecimal(number.toInt().toString()) } if (size == 4) { val number = (value[0].toLong() and 0x00FF) + ((value[1].toLong() and 0x00FF) shl 8) + ((value[2].toLong() and 0x00FF) shl 16) + ((value[3].toLong() and 0x00FF) shl 24) return BigDecimal(number.toInt().toString()) } if (size == 8) { val number = (value[0].toLong() and 0x00FF) + ((value[1].toLong() and 0x00FF) shl 8) + ((value[2].toLong() and 0x00FF) shl 16) + ((value[3].toLong() and 0x00FF) shl 24) + ((value[4].toLong() and 0x00FF) shl 32) + ((value[5].toLong() and 0x00FF) shl 40) + ((value[6].toLong() and 0x00FF) shl 48) + ((value[7].toLong() and 0x00FF) shl 56) return BigDecimal(number.toInt().toString()) } TODO("decode binary for $size not implemented") } fun decodeInteger(value: String, size: Int): BigDecimal { if (size == 1) { var number: Int = 0x0000000 number += (value[0].toByte()) return BigDecimal(number.toString()) } if (size == 2) { var number: Long = 0x0000000 if (value[1].toInt() and 0x8000 != 0) { number = 0xFFFF0000 } number += (value[0].toInt() and 0x00FF) + ((value[1].toInt() and 0x00FF) shl 8) return BigDecimal(number.toInt().toString()) } if (size == 4) { val number = (value[0].toLong() and 0x00FF) + ((value[1].toLong() and 0x00FF) shl 8) + ((value[2].toLong() and 0x00FF) shl 16) + ((value[3].toLong() and 0x00FF) shl 24) return BigDecimal(number.toInt().toString()) } if (size == 8) { val number = (value[0].toLong() and 0x00FF) + ((value[1].toLong() and 0x00FF) shl 8) + ((value[2].toLong() and 0x00FF) shl 16) + ((value[3].toLong() and 0x00FF) shl 24) + ((value[4].toLong() and 0x00FF) shl 32) + ((value[5].toLong() and 0x00FF) shl 40) + ((value[6].toLong() and 0x00FF) shl 48) + ((value[7].toLong() and 0x00FF) shl 56) return BigDecimal(number.toString()) } TODO("decode binary for $size not implemented") } fun decodeUnsigned(value: String, size: Int): BigDecimal { if (size == 1) { var number: Long = 0x0000000 if (value[0].toInt() and 0x0010 != 0) { number = 0x00000000 } number += (value[0].toInt() and 0x00FF) return BigDecimal(number.toInt().toString()) } if (size == 2) { var number: Long = 0x0000000 if (value[1].toInt() and 0x1000 != 0) { number = 0xFFFF0000 } number += (value[0].toInt() and 0x00FF) + ((value[1].toInt() and 0x00FF) shl 8) // make sure you count onlu 16 bits number = number and 0x0000FFFF return BigDecimal(number.toString()) } if (size == 4) { val number = (value[0].toLong() and 0x00FF) + ((value[1].toLong() and 0x00FF) shl 8) + ((value[2].toLong() and 0x00FF) shl 16) + ((value[3].toLong() and 0x00FF) shl 24) return BigDecimal(number.toString()) } if (size == 8) { val number = (value[0].toLong() and 0x00FF) + ((value[1].toLong() and 0x00FF) shl 8) + ((value[2].toLong() and 0x00FF) shl 16) + ((value[3].toLong() and 0x00FF) shl 24) + ((value[4].toLong() and 0x00FF) shl 32) + ((value[5].toLong() and 0x00FF) shl 40) + ((value[6].toLong() and 0x00FF) shl 48) + ((value[7].toLong() and 0x00FF) shl 56) return BigDecimal(number.toInt().toString()) } TODO("decode binary for $size not implemented") } /** * Encode a zoned value for a data structure */ fun encodeToZoned(inValue: BigDecimal, digits: Int, scale: Int): String { // get just the digits from BigDecimal, "normalize" away sign, decimal place etc. val inChars = inValue.abs().movePointRight(scale).toBigInteger().toString().toCharArray() var buffer = IntArray(inChars.size) // read the sign val sign = inValue.signum() inChars.forEachIndexed { index, char -> val digit = char.toInt() buffer[index] = digit } if (sign < 0) { buffer[inChars.size - 1] = (buffer[inChars.size - 1] - 0x030) + 0x0049 } var s = "" buffer.forEach { byte -> s += byte.toChar() } s = s.padStart(digits, '0') return s } fun decodeFromZoned(value: String, digits: Int, scale: Int): BigDecimal { val builder = StringBuilder() value.forEach { when { it.isDigit() -> builder.append(it) else -> { if (it.toInt() == 0) { builder.append('0') } else { builder.insert(0, '-') builder.append((it.toInt() - 0x0049 + 0x0030).toChar()) } } } } if (scale != 0) { builder.insert(builder.length - scale, ".") } return BigDecimal(builder.toString()) } /** * Encoding/Decoding a numeric value for a data structure */ fun encodeToDS(inValue: BigDecimal, digits: Int, scale: Int): String { // get just the digits from BigDecimal, "normalize" away sign, decimal place etc. val inChars = inValue.abs().movePointRight(scale).toBigInteger().toString().toCharArray() var buffer = IntArray(inChars.size / 2 + 1) // read the sign val sign = inValue.signum() var offset = 0 var inPosition = 0 var firstNibble: Int var secondNibble: Int // place all the digits except last one while (inPosition < inChars.size - 1) { firstNibble = ((inChars[inPosition++].toInt()) and 0x000F) shl 4 secondNibble = (inChars[inPosition++].toInt()) and 0x000F buffer[offset++] = (firstNibble + secondNibble).toInt() } // place last digit and sign nibble firstNibble = if (inPosition == inChars.size) { 0x00F0 } else { (inChars[inChars.size - 1].toInt()) and 0x000F shl 4 } if (sign != -1) { buffer[offset] = (firstNibble + 0x000F).toInt() } else { buffer[offset] = (firstNibble + 0x000D).toInt() } var s = "" buffer.forEach { byte -> s += byte.toChar() } return s } fun decodeFromDS(value: String, digits: Int, scale: Int): BigDecimal { val buffer = IntArray(value.length) for (i in value.indices) { buffer[i] = value[i].code } var sign: String = "" var number: String = "" var nibble = ((buffer[buffer.size - 1]).toInt() and 0x0F) if (nibble == 0x0B || nibble == 0x0D) { sign = "-" } var offset = 0 while (offset < (buffer.size - 1)) { nibble = (buffer[offset].toInt() and 0xFF).ushr(4) number += Character.toString((nibble or 0x30).toChar()) nibble = buffer[offset].toInt() and 0x0F or 0x30 number += Character.toString((nibble or 0x30).toChar()) offset++ } // read last digit nibble = (buffer[offset].toInt() and 0xFF).ushr(4) if (nibble <= 9) { number += Character.toString((nibble or 0x30).toChar()) } // adjust the scale if (scale > 0 && number != "0") { val len = number.length number = buildString { append(number.substring(0, len - scale)) append(".") append(number.substring(len - scale, len)) } } number = sign + number return try { value.toBigDecimal() } catch (e: Exception) { number.toBigDecimal() } } enum class RpgType(val rpgType: String) { PACKED("P"), ZONED("S"), INTEGER("I"), UNSIGNED("U"), BINARY("B") }
apache-2.0
ac7ccd6ed42977942fdf9bb6625e5c33
32.285714
120
0.59184
3.924733
false
false
false
false
google/accompanist
pager/src/sharedTest/kotlin/com/google/accompanist/pager/BaseVerticalPagerTest.kt
1
5815
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.accompanist.pager import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.text.BasicText import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.SemanticsNodeInteraction import androidx.compose.ui.test.assertHeightIsAtLeast import androidx.compose.ui.test.assertLeftPositionInRootIsEqualTo import androidx.compose.ui.test.assertTopPositionInRootIsEqualTo import androidx.compose.ui.test.assertWidthIsEqualTo import androidx.compose.ui.test.getUnclippedBoundsInRoot import androidx.compose.ui.test.onRoot import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.height import androidx.compose.ui.unit.width import com.google.accompanist.testharness.TestHarness /** * Contains the [VerticalPager] tests. This class is extended * in both the `androidTest` and `test` source sets for setup of the relevant * test runner. */ @OptIn(ExperimentalPagerApi::class) // Pager is currently experimental abstract class BaseVerticalPagerTest( private val contentPadding: PaddingValues, // We don't use the Dp type due to https://youtrack.jetbrains.com/issue/KT-35523 private val itemSpacingDp: Int, private val reverseLayout: Boolean, ) : PagerTest() { override fun SemanticsNodeInteraction.swipeAcrossCenter( distancePercentage: Float, velocityPerSec: Dp, ): SemanticsNodeInteraction = swipeAcrossCenterWithVelocity( distancePercentageY = if (reverseLayout) -distancePercentage else distancePercentage, velocityPerSec = velocityPerSec, ) override fun SemanticsNodeInteraction.assertLaidOutItemPosition( page: Int, currentPage: Int, pageCount: Int, offset: Float ): SemanticsNodeInteraction { val rootBounds = composeTestRule.onRoot().getUnclippedBoundsInRoot() val expectedItemHeight = rootBounds.height - contentPadding.calculateTopPadding() - contentPadding.calculateBottomPadding() val expectedItemHeightWithSpacing = expectedItemHeight + itemSpacingDp.dp val expectedItemWidth = rootBounds.width val expectedLeft = (rootBounds.width - expectedItemWidth) / 2 val expectedFirstItemTop = when (reverseLayout) { true -> (rootBounds.height - contentPadding.calculateBottomPadding() - expectedItemHeight) + (expectedItemHeightWithSpacing * offset) false -> contentPadding.calculateTopPadding() - (expectedItemHeightWithSpacing * offset) } return assertWidthIsEqualTo(expectedItemWidth) .assertHeightIsAtLeast(expectedItemHeight) .assertLeftPositionInRootIsEqualTo(expectedLeft) .run { val pageDelta = (expectedItemHeightWithSpacing * (page - currentPage)) if (reverseLayout) { assertTopPositionInRootIsEqualTo(expectedFirstItemTop - pageDelta) } else { assertTopPositionInRootIsEqualTo(expectedFirstItemTop + pageDelta) } } } @Composable override fun AbstractPagerContent( count: () -> Int, pagerState: PagerState, observeStateInContent: Boolean, pageToItem: (Int) -> String, useKeys: Boolean, userScrollEnabled: Boolean, onPageComposed: (Int) -> Unit ) { TestHarness(layoutDirection = LayoutDirection.Ltr) { applierScope = rememberCoroutineScope() Box { if (observeStateInContent) { BasicText(text = "${pagerState.isScrollInProgress}") } VerticalPager( count = count(), state = pagerState, itemSpacing = itemSpacingDp.dp, reverseLayout = reverseLayout, contentPadding = contentPadding, modifier = Modifier.fillMaxSize(), key = if (useKeys) { { pageToItem(it) } } else { null }, userScrollEnabled = userScrollEnabled, ) { page -> onPageComposed(page) val item = pageToItem(page) Box( modifier = Modifier .fillMaxSize() .background(randomColor()) .testTag(item) ) { BasicText( text = item, modifier = Modifier.align(Alignment.Center) ) } } } } } }
apache-2.0
0f7a9bf4603693cbffb593bab0a157ee
38.828767
104
0.646088
5.394249
false
true
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Int/IntVec3.kt
1
24421
package glm data class IntVec3(val x: Int, val y: Int, val z: Int) { // Initializes each element by evaluating init from 0 until 2 constructor(init: (Int) -> Int) : this(init(0), init(1), init(2)) operator fun get(idx: Int): Int = when (idx) { 0 -> x 1 -> y 2 -> z else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun inc(): IntVec3 = IntVec3(x.inc(), y.inc(), z.inc()) operator fun dec(): IntVec3 = IntVec3(x.dec(), y.dec(), z.dec()) operator fun unaryPlus(): IntVec3 = IntVec3(+x, +y, +z) operator fun unaryMinus(): IntVec3 = IntVec3(-x, -y, -z) operator fun plus(rhs: IntVec3): IntVec3 = IntVec3(x + rhs.x, y + rhs.y, z + rhs.z) operator fun minus(rhs: IntVec3): IntVec3 = IntVec3(x - rhs.x, y - rhs.y, z - rhs.z) operator fun times(rhs: IntVec3): IntVec3 = IntVec3(x * rhs.x, y * rhs.y, z * rhs.z) operator fun div(rhs: IntVec3): IntVec3 = IntVec3(x / rhs.x, y / rhs.y, z / rhs.z) operator fun rem(rhs: IntVec3): IntVec3 = IntVec3(x % rhs.x, y % rhs.y, z % rhs.z) operator fun plus(rhs: Int): IntVec3 = IntVec3(x + rhs, y + rhs, z + rhs) operator fun minus(rhs: Int): IntVec3 = IntVec3(x - rhs, y - rhs, z - rhs) operator fun times(rhs: Int): IntVec3 = IntVec3(x * rhs, y * rhs, z * rhs) operator fun div(rhs: Int): IntVec3 = IntVec3(x / rhs, y / rhs, z / rhs) operator fun rem(rhs: Int): IntVec3 = IntVec3(x % rhs, y % rhs, z % rhs) inline fun map(func: (Int) -> Int): IntVec3 = IntVec3(func(x), func(y), func(z)) fun toList(): List<Int> = listOf(x, y, z) // Predefined vector constants companion object Constants { val zero: IntVec3 = IntVec3(0, 0, 0) val ones: IntVec3 = IntVec3(1, 1, 1) val unitX: IntVec3 = IntVec3(1, 0, 0) val unitY: IntVec3 = IntVec3(0, 1, 0) val unitZ: IntVec3 = IntVec3(0, 0, 1) } // Conversions to Float fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec(conv: (Int) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat()) inline fun toVec2(conv: (Int) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec3(conv: (Int) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w) inline fun toVec4(w: Float = 0f, conv: (Int) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w) // Conversions to Float fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec(conv: (Int) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat()) inline fun toMutableVec2(conv: (Int) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec3(conv: (Int) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w) inline fun toMutableVec4(w: Float = 0f, conv: (Int) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toDoubleVec(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toDoubleVec(conv: (Int) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble()) inline fun toDoubleVec2(conv: (Int) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toDoubleVec3(conv: (Int) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w) inline fun toDoubleVec4(w: Double = 0.0, conv: (Int) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toMutableDoubleVec(conv: (Int) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble()) inline fun toMutableDoubleVec2(conv: (Int) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toMutableDoubleVec3(conv: (Int) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w) inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Int) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toIntVec(): IntVec3 = IntVec3(x, y, z) inline fun toIntVec(conv: (Int) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec2(): IntVec2 = IntVec2(x, y) inline fun toIntVec2(conv: (Int) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(): IntVec3 = IntVec3(x, y, z) inline fun toIntVec3(conv: (Int) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x, y, z, w) inline fun toIntVec4(w: Int = 0, conv: (Int) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x, y, z) inline fun toMutableIntVec(conv: (Int) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x, y) inline fun toMutableIntVec2(conv: (Int) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x, y, z) inline fun toMutableIntVec3(conv: (Int) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x, y, z, w) inline fun toMutableIntVec4(w: Int = 0, conv: (Int) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec(conv: (Int) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec2(conv: (Int) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec3(conv: (Int) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w) inline fun toLongVec4(w: Long = 0L, conv: (Int) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec(conv: (Int) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec2(conv: (Int) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec3(conv: (Int) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w) inline fun toMutableLongVec4(w: Long = 0L, conv: (Int) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toShortVec(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec(conv: (Int) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec2(conv: (Int) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec3(conv: (Int) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w) inline fun toShortVec4(w: Short = 0.toShort(), conv: (Int) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec(conv: (Int) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec2(conv: (Int) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec3(conv: (Int) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w) inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Int) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toByteVec(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte()) inline fun toByteVec(conv: (Int) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec2(): ByteVec2 = ByteVec2(x.toByte(), y.toByte()) inline fun toByteVec2(conv: (Int) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(): ByteVec3 = ByteVec3(x.toByte(), y.toByte(), z.toByte()) inline fun toByteVec3(conv: (Int) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x.toByte(), y.toByte(), z.toByte(), w) inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Int) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte()) inline fun toMutableByteVec(conv: (Int) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x.toByte(), y.toByte()) inline fun toMutableByteVec2(conv: (Int) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x.toByte(), y.toByte(), z.toByte()) inline fun toMutableByteVec3(conv: (Int) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x.toByte(), y.toByte(), z.toByte(), w) inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Int) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Char fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec(conv: (Int) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec2(conv: (Int) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec3(conv: (Int) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w) inline fun toCharVec4(w: Char, conv: (Int) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w) // Conversions to Char fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec(conv: (Int) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec2(conv: (Int) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec3(conv: (Int) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w) inline fun toMutableCharVec4(w: Char, conv: (Int) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toBoolVec(): BoolVec3 = BoolVec3(x != 0, y != 0, z != 0) inline fun toBoolVec(conv: (Int) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0, y != 0) inline fun toBoolVec2(conv: (Int) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0, y != 0, z != 0) inline fun toBoolVec3(conv: (Int) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0, y != 0, z != 0, w) inline fun toBoolVec4(w: Boolean = false, conv: (Int) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0, y != 0, z != 0) inline fun toMutableBoolVec(conv: (Int) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0, y != 0) inline fun toMutableBoolVec2(conv: (Int) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0, y != 0, z != 0) inline fun toMutableBoolVec3(conv: (Int) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0, y != 0, z != 0, w) inline fun toMutableBoolVec4(w: Boolean = false, conv: (Int) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec(conv: (Int) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Int) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec3(conv: (Int) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toStringVec4(w: String = "", conv: (Int) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec(conv: (Int) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Int) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec3(conv: (Int) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toMutableStringVec4(w: String = "", conv: (Int) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toTVec(conv: (Int) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec2(conv: (Int) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(conv: (Int) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec4(w: T2, conv: (Int) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Int) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec2(conv: (Int) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(conv: (Int) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec4(w: T2, conv: (Int) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: IntVec2 get() = IntVec2(x, x) val xy: IntVec2 get() = IntVec2(x, y) val xz: IntVec2 get() = IntVec2(x, z) val yx: IntVec2 get() = IntVec2(y, x) val yy: IntVec2 get() = IntVec2(y, y) val yz: IntVec2 get() = IntVec2(y, z) val zx: IntVec2 get() = IntVec2(z, x) val zy: IntVec2 get() = IntVec2(z, y) val zz: IntVec2 get() = IntVec2(z, z) val xxx: IntVec3 get() = IntVec3(x, x, x) val xxy: IntVec3 get() = IntVec3(x, x, y) val xxz: IntVec3 get() = IntVec3(x, x, z) val xyx: IntVec3 get() = IntVec3(x, y, x) val xyy: IntVec3 get() = IntVec3(x, y, y) val xyz: IntVec3 get() = IntVec3(x, y, z) val xzx: IntVec3 get() = IntVec3(x, z, x) val xzy: IntVec3 get() = IntVec3(x, z, y) val xzz: IntVec3 get() = IntVec3(x, z, z) val yxx: IntVec3 get() = IntVec3(y, x, x) val yxy: IntVec3 get() = IntVec3(y, x, y) val yxz: IntVec3 get() = IntVec3(y, x, z) val yyx: IntVec3 get() = IntVec3(y, y, x) val yyy: IntVec3 get() = IntVec3(y, y, y) val yyz: IntVec3 get() = IntVec3(y, y, z) val yzx: IntVec3 get() = IntVec3(y, z, x) val yzy: IntVec3 get() = IntVec3(y, z, y) val yzz: IntVec3 get() = IntVec3(y, z, z) val zxx: IntVec3 get() = IntVec3(z, x, x) val zxy: IntVec3 get() = IntVec3(z, x, y) val zxz: IntVec3 get() = IntVec3(z, x, z) val zyx: IntVec3 get() = IntVec3(z, y, x) val zyy: IntVec3 get() = IntVec3(z, y, y) val zyz: IntVec3 get() = IntVec3(z, y, z) val zzx: IntVec3 get() = IntVec3(z, z, x) val zzy: IntVec3 get() = IntVec3(z, z, y) val zzz: IntVec3 get() = IntVec3(z, z, z) val xxxx: IntVec4 get() = IntVec4(x, x, x, x) val xxxy: IntVec4 get() = IntVec4(x, x, x, y) val xxxz: IntVec4 get() = IntVec4(x, x, x, z) val xxyx: IntVec4 get() = IntVec4(x, x, y, x) val xxyy: IntVec4 get() = IntVec4(x, x, y, y) val xxyz: IntVec4 get() = IntVec4(x, x, y, z) val xxzx: IntVec4 get() = IntVec4(x, x, z, x) val xxzy: IntVec4 get() = IntVec4(x, x, z, y) val xxzz: IntVec4 get() = IntVec4(x, x, z, z) val xyxx: IntVec4 get() = IntVec4(x, y, x, x) val xyxy: IntVec4 get() = IntVec4(x, y, x, y) val xyxz: IntVec4 get() = IntVec4(x, y, x, z) val xyyx: IntVec4 get() = IntVec4(x, y, y, x) val xyyy: IntVec4 get() = IntVec4(x, y, y, y) val xyyz: IntVec4 get() = IntVec4(x, y, y, z) val xyzx: IntVec4 get() = IntVec4(x, y, z, x) val xyzy: IntVec4 get() = IntVec4(x, y, z, y) val xyzz: IntVec4 get() = IntVec4(x, y, z, z) val xzxx: IntVec4 get() = IntVec4(x, z, x, x) val xzxy: IntVec4 get() = IntVec4(x, z, x, y) val xzxz: IntVec4 get() = IntVec4(x, z, x, z) val xzyx: IntVec4 get() = IntVec4(x, z, y, x) val xzyy: IntVec4 get() = IntVec4(x, z, y, y) val xzyz: IntVec4 get() = IntVec4(x, z, y, z) val xzzx: IntVec4 get() = IntVec4(x, z, z, x) val xzzy: IntVec4 get() = IntVec4(x, z, z, y) val xzzz: IntVec4 get() = IntVec4(x, z, z, z) val yxxx: IntVec4 get() = IntVec4(y, x, x, x) val yxxy: IntVec4 get() = IntVec4(y, x, x, y) val yxxz: IntVec4 get() = IntVec4(y, x, x, z) val yxyx: IntVec4 get() = IntVec4(y, x, y, x) val yxyy: IntVec4 get() = IntVec4(y, x, y, y) val yxyz: IntVec4 get() = IntVec4(y, x, y, z) val yxzx: IntVec4 get() = IntVec4(y, x, z, x) val yxzy: IntVec4 get() = IntVec4(y, x, z, y) val yxzz: IntVec4 get() = IntVec4(y, x, z, z) val yyxx: IntVec4 get() = IntVec4(y, y, x, x) val yyxy: IntVec4 get() = IntVec4(y, y, x, y) val yyxz: IntVec4 get() = IntVec4(y, y, x, z) val yyyx: IntVec4 get() = IntVec4(y, y, y, x) val yyyy: IntVec4 get() = IntVec4(y, y, y, y) val yyyz: IntVec4 get() = IntVec4(y, y, y, z) val yyzx: IntVec4 get() = IntVec4(y, y, z, x) val yyzy: IntVec4 get() = IntVec4(y, y, z, y) val yyzz: IntVec4 get() = IntVec4(y, y, z, z) val yzxx: IntVec4 get() = IntVec4(y, z, x, x) val yzxy: IntVec4 get() = IntVec4(y, z, x, y) val yzxz: IntVec4 get() = IntVec4(y, z, x, z) val yzyx: IntVec4 get() = IntVec4(y, z, y, x) val yzyy: IntVec4 get() = IntVec4(y, z, y, y) val yzyz: IntVec4 get() = IntVec4(y, z, y, z) val yzzx: IntVec4 get() = IntVec4(y, z, z, x) val yzzy: IntVec4 get() = IntVec4(y, z, z, y) val yzzz: IntVec4 get() = IntVec4(y, z, z, z) val zxxx: IntVec4 get() = IntVec4(z, x, x, x) val zxxy: IntVec4 get() = IntVec4(z, x, x, y) val zxxz: IntVec4 get() = IntVec4(z, x, x, z) val zxyx: IntVec4 get() = IntVec4(z, x, y, x) val zxyy: IntVec4 get() = IntVec4(z, x, y, y) val zxyz: IntVec4 get() = IntVec4(z, x, y, z) val zxzx: IntVec4 get() = IntVec4(z, x, z, x) val zxzy: IntVec4 get() = IntVec4(z, x, z, y) val zxzz: IntVec4 get() = IntVec4(z, x, z, z) val zyxx: IntVec4 get() = IntVec4(z, y, x, x) val zyxy: IntVec4 get() = IntVec4(z, y, x, y) val zyxz: IntVec4 get() = IntVec4(z, y, x, z) val zyyx: IntVec4 get() = IntVec4(z, y, y, x) val zyyy: IntVec4 get() = IntVec4(z, y, y, y) val zyyz: IntVec4 get() = IntVec4(z, y, y, z) val zyzx: IntVec4 get() = IntVec4(z, y, z, x) val zyzy: IntVec4 get() = IntVec4(z, y, z, y) val zyzz: IntVec4 get() = IntVec4(z, y, z, z) val zzxx: IntVec4 get() = IntVec4(z, z, x, x) val zzxy: IntVec4 get() = IntVec4(z, z, x, y) val zzxz: IntVec4 get() = IntVec4(z, z, x, z) val zzyx: IntVec4 get() = IntVec4(z, z, y, x) val zzyy: IntVec4 get() = IntVec4(z, z, y, y) val zzyz: IntVec4 get() = IntVec4(z, z, y, z) val zzzx: IntVec4 get() = IntVec4(z, z, z, x) val zzzy: IntVec4 get() = IntVec4(z, z, z, y) val zzzz: IntVec4 get() = IntVec4(z, z, z, z) } val swizzle: Swizzle get() = Swizzle() } fun vecOf(x: Int, y: Int, z: Int): IntVec3 = IntVec3(x, y, z) operator fun Int.plus(rhs: IntVec3): IntVec3 = IntVec3(this + rhs.x, this + rhs.y, this + rhs.z) operator fun Int.minus(rhs: IntVec3): IntVec3 = IntVec3(this - rhs.x, this - rhs.y, this - rhs.z) operator fun Int.times(rhs: IntVec3): IntVec3 = IntVec3(this * rhs.x, this * rhs.y, this * rhs.z) operator fun Int.div(rhs: IntVec3): IntVec3 = IntVec3(this / rhs.x, this / rhs.y, this / rhs.z) operator fun Int.rem(rhs: IntVec3): IntVec3 = IntVec3(this % rhs.x, this % rhs.y, this % rhs.z)
mit
3a199b4e07efb82b38a28f54eece5fb7
65.181572
146
0.622988
3.194793
false
false
false
false
inorichi/mangafeed
app/src/main/java/eu/kanade/tachiyomi/data/backup/legacy/serializer/MangaTypeSerializer.kt
2
2115
package eu.kanade.tachiyomi.data.backup.legacy.serializer import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.database.models.MangaImpl import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.descriptors.buildClassSerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlinx.serialization.json.JsonDecoder import kotlinx.serialization.json.JsonEncoder import kotlinx.serialization.json.add import kotlinx.serialization.json.buildJsonArray import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.long /** * JSON Serializer used to write / read [MangaImpl] to / from json */ open class MangaBaseSerializer<T : Manga> : KSerializer<T> { override val descriptor: SerialDescriptor = buildClassSerialDescriptor("Manga") override fun serialize(encoder: Encoder, value: T) { encoder as JsonEncoder encoder.encodeJsonElement( buildJsonArray { add(value.url) add(value.title) add(value.source) add(value.viewer_flags) add(value.chapter_flags) } ) } @Suppress("UNCHECKED_CAST") override fun deserialize(decoder: Decoder): T { // make a manga impl and cast as T so that the serializer accepts it return MangaImpl().apply { decoder as JsonDecoder val array = decoder.decodeJsonElement().jsonArray url = array[0].jsonPrimitive.content title = array[1].jsonPrimitive.content source = array[2].jsonPrimitive.long viewer_flags = array[3].jsonPrimitive.int chapter_flags = array[4].jsonPrimitive.int } as T } } // Allow for serialization of a manga and manga impl object MangaTypeSerializer : MangaBaseSerializer<Manga>() object MangaImplTypeSerializer : MangaBaseSerializer<MangaImpl>()
apache-2.0
1bd8c0703654cf1d82046155dec0c14c
36.767857
83
0.720095
4.752809
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/platform/mixin/config/reference/MixinPackage.kt
1
2405
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.config.reference import com.demonwav.mcdev.platform.mixin.util.MixinConstants.Annotations.MIXIN import com.demonwav.mcdev.util.packageName import com.demonwav.mcdev.util.reference.PackageNameReferenceProvider import com.intellij.codeInsight.lookup.LookupElementBuilder import com.intellij.psi.JavaPsiFacade import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiPackage import com.intellij.psi.search.PackageScope import com.intellij.psi.search.searches.AnnotatedElementsSearch import com.intellij.util.ArrayUtil import com.intellij.util.PlatformIcons object MixinPackage : PackageNameReferenceProvider() { override fun collectVariants(element: PsiElement, context: PsiElement?): Array<Any> { val mixinAnnotation = JavaPsiFacade.getInstance(element.project).findClass(MIXIN, element.resolveScope) ?: return ArrayUtil.EMPTY_OBJECT_ARRAY return if (context == null) { findPackages(mixinAnnotation, element) } else { findChildrenPackages(mixinAnnotation, element, context as PsiPackage) } } private fun findPackages(mixinAnnotation: PsiClass, element: PsiElement): Array<Any> { val packages = HashSet<String>() val list = ArrayList<LookupElementBuilder>() for (mixin in AnnotatedElementsSearch.searchPsiClasses(mixinAnnotation, element.resolveScope)) { val packageName = mixin.packageName ?: continue if (packages.add(packageName)) { list.add(LookupElementBuilder.create(packageName).withIcon(PlatformIcons.PACKAGE_ICON)) } val topLevelPackage = packageName.substringBefore('.') if (packages.add(topLevelPackage)) { list.add(LookupElementBuilder.create(topLevelPackage).withIcon(PlatformIcons.PACKAGE_ICON)) } } return list.toArray() } private fun findChildrenPackages(mixinAnnotation: PsiClass, element: PsiElement, context: PsiPackage): Array<Any> { val scope = PackageScope(context, true, true).intersectWith(element.resolveScope) return collectSubpackages(context, AnnotatedElementsSearch.searchPsiClasses(mixinAnnotation, scope)) } }
mit
f61dd81b219605229af558b265ead339
37.790323
119
0.730561
4.938398
false
false
false
false
DemonWav/MinecraftDev
src/main/kotlin/com/demonwav/mcdev/insight/ColorPicker.kt
1
2265
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.insight import com.intellij.openapi.ui.DialogWrapper import com.intellij.util.ui.ColorIcon import java.awt.Color import java.awt.GridBagConstraints import java.awt.GridBagLayout import java.awt.Insets import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class ColorPicker(private val colorMap: Map<String, Color>, parent: JComponent) { private val panel = JPanel(GridBagLayout()) private var chosenColor: String? = null private val dialog: ColorPickerDialog init { dialog = ColorPickerDialog(parent, panel) } fun showDialog(): String? { init() dialog.show() return chosenColor } private fun init() { val iterator = colorMap.entries.iterator() addToPanel(0, 8, panel, iterator) addToPanel(1, 8, panel, iterator) } private fun addToPanel(row: Int, cols: Int, panel: JPanel, iterator: Iterator<Map.Entry<String, Color>>) { for (i in 0 until cols) { if (!iterator.hasNext()) { break } val entry = iterator.next() val icon = ColorIcon(28, entry.value, true) val label = JLabel(icon) label.addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent?) { chosenColor = entry.key dialog.close(0) } }) val constraints = GridBagConstraints() constraints.gridy = row constraints.fill = GridBagConstraints.NONE constraints.insets = Insets(10, 10, 10, 10) panel.add(label, constraints) } } private class ColorPickerDialog constructor(parent: JComponent, private val component: JComponent) : DialogWrapper(parent, false) { init { title = "Choose Color" setResizable(true) init() } override fun createCenterPanel(): JComponent? { return component } } }
mit
e5ead9ea1c0a5b717fe14a7c9273da60
24.449438
135
0.611921
4.58502
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter10/src/main/kotlin/com/programming/kotlin/chapter10/ListsCollection.kt
1
3906
package com.programming.kotlin.chapter10 import java.math.BigDecimal import java.util.* fun lists(): Unit { val intList: List<Int> = listOf<Int>(20, 29, 40, 10) println("Int list[${intList.javaClass.canonicalName}]:${intList.joinToString(",")}") val emptyList: List<String> = emptyList<String>() println("Empty list[${emptyList.javaClass.canonicalName}]:${emptyList.joinToString(",")}") val nonNulls: List<String> = listOfNotNull<String>(null, "a", "b", "c") println("Non-Null string lists[${nonNulls.javaClass.canonicalName}]:${nonNulls.joinToString(",")}") val doubleList: ArrayList<Double> = arrayListOf(84.88, 100.25, 999.99) println("Double list:${doubleList.joinToString(",")}") val cartoonsList: MutableList<String> = mutableListOf("Tom&Jerry", "Dexter's Laboratory", "Johnny Bravo", "Cow&Chicken") println("Cartoons list[${cartoonsList.javaClass.canonicalName}]: ${cartoonsList.joinToString(",")}") cartoonsList.addAll(arrayOf("Ed, Edd n Eddy", "Courage the Cowardly Dog")) println("Cartoons list[${cartoonsList.javaClass.canonicalName}]: ${cartoonsList.joinToString(",")}") (intList as AbstractList<Int>).set(0, 999999) println("Int list[${intList.javaClass.canonicalName}]:${intList.joinToString(",")}") (nonNulls as java.util.ArrayList).addAll(arrayOf("x", "y")) println("countries list[${nonNulls.javaClass.canonicalName}]:${nonNulls.joinToString(",")}") val hacked: List<Int> = listOfNotNull(0, 1) CollectionsJ.dangerousCall(hacked) println("Hacked list[${hacked.javaClass.canonicalName}]:${hacked.joinToString(",")}") val planets = listOf( Planet("Mercury", 57910000), Planet("Venus", 108200000), Planet("Earth", 149600000), Planet("Mars", 227940000), Planet("Jupiter", 778330000), Planet("Saturn", 1424600000), Planet("Uranus", 2873550000), Planet("Neptune", 4501000000), Planet("Pluto", 5945900000) ) println(planets.last()) //Pluto println(planets.first()) //Mercury println(planets.get(4)) //Jupiter println(planets.isEmpty()) // false println(planets.isNotEmpty()) //true println(planets.asReversed()) //"Pluto", "Neptune" println(planets.elementAtOrNull(10)) //Null planets.zip(arrayOf(4800, 12100, 12750, 6800, 142800, 120660, 51800, 49500, 3300)) .forEach { val (planet, diameter) = it println("${planet.name}'s diameter is $diameter km") } val reversePlanetName = planets.foldRight(StringBuilder()) { planet, builder -> builder.append(planet.name) builder.append(";") } println(reversePlanetName) //Pluto, Neptune..Earth;Venus;Mercury val amount = listOf( ShoppingItem("1", "Intel i7-950 Quad-Core Processor", BigDecimal("319.76"), 1), ShoppingItem("2", "Samsung 750 EVO 250 GB 2.5 inch SDD", BigDecimal("71.21"), 1) ).foldRight(BigDecimal.ZERO) { item, total -> total + BigDecimal(item.quantity) * item.price } println(amount) //390.97 println(planets.map { it.distance }) //List(57910000, ...,5945900000) val list = listOf(listOf(10, 20), listOf(14, 18), emptyList()) val increment = { x: Int -> x + 1 } list.flatMap { it.map(increment) } //11,21,15,10 val chars = listOf('a', 'd', 'c', 'd', 'a') val (c1,c2,c3,c4,c5) = chars println("$c1$c2$c3$c4$c5") val array: Array<Char> = chars.toTypedArray() val arrayBetter: CharArray = chars.toCharArray() val set: Set<Char> = chars.toSet() println(set) val charsMutable = chars.toMutableList() } data class Planet(val name: String, val distance: Long) data class ShoppingItem(val id: String, val name: String, val price: BigDecimal, val quantity: Int)
mit
86bb8a76f453a80013b94bb91f6460e6
38.464646
124
0.635689
3.70237
false
false
false
false
paplorinc/intellij-community
python/src/com/jetbrains/python/codeInsight/typing/PyStubPackagesAdvertiser.kt
2
16835
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.typing import com.google.common.cache.Cache import com.intellij.codeInspection.* import com.intellij.codeInspection.ex.EditInspectionToolsSettingsAction import com.intellij.codeInspection.ex.ProblemDescriptorImpl import com.intellij.codeInspection.ui.ListEditForm import com.intellij.execution.ExecutionException import com.intellij.notification.NotificationDisplayType import com.intellij.notification.NotificationGroup import com.intellij.notification.NotificationType import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.util.Key import com.intellij.profile.codeInspection.ProjectInspectionProfileManager import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.QualifiedName import com.intellij.util.containers.isNullOrEmpty import com.intellij.webcore.packaging.RepoPackage import com.jetbrains.python.inspections.PyInspection import com.jetbrains.python.inspections.PyInspectionVisitor import com.jetbrains.python.inspections.PyPackageRequirementsInspection.PyInstallRequirementsFix import com.jetbrains.python.packaging.* import com.jetbrains.python.packaging.requirement.PyRequirementRelation import com.jetbrains.python.psi.PyFile import com.jetbrains.python.psi.PyFromImportStatement import com.jetbrains.python.psi.PyImportElement import com.jetbrains.python.psi.PyReferenceExpression import com.jetbrains.python.sdk.PythonSdkType import javax.swing.JComponent class PyStubPackagesAdvertiser : PyInspection() { companion object { // file-level suggestion will be shown for packages below private val FORCED = mapOf("django" to "Django", "numpy" to "numpy") // top-level package to package on PyPI // notification will be shown for packages below private val CHECKED = mapOf("coincurve" to "coincurve", "docutils" to "docutils", "ordered_set" to "ordered-set", "gi" to "PyGObject", "PyQt5" to "PyQt5", "pyspark" to "pyspark") // top-level package to package on PyPI, sorted by the latter private val BALLOON_SHOWING = Key.create<Boolean>("showingStubPackagesAdvertiserBalloon") private val BALLOON_NOTIFICATIONS = NotificationGroup("Python Stub Packages Advertiser", NotificationDisplayType.STICKY_BALLOON, false) private val SESSION_KEY = Key.create<MutableSet<String>>("PyStubPackagesAdvertiser.Sources") } @Suppress("MemberVisibilityCanBePrivate") var ignoredPackages: MutableList<String> = mutableListOf() override fun createOptionsPanel(): JComponent = ListEditForm("Ignored packages", ignoredPackages).contentPanel override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { val sources = session.putUserDataIfAbsent(SESSION_KEY, mutableSetOf()) return Visitor(sources, holder, session) } override fun inspectionFinished(session: LocalInspectionToolSession, problemsHolder: ProblemsHolder) { val sources = session.getUserData(SESSION_KEY) if (sources.isNullOrEmpty()) return val file = session.file if (file is PyFile) run(file, sources!!, problemsHolder) } private class Visitor(val sources: MutableSet<String>, holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyFromImportStatement(node: PyFromImportStatement) { super.visitPyFromImportStatement(node) processImport(node.importSource, node.importSourceQName) } override fun visitPyImportElement(node: PyImportElement) { super.visitPyImportElement(node) processImport(node.importReferenceExpression, node.importedQName) } private fun processImport(ref: PyReferenceExpression?, qName: QualifiedName?) { if (qName == null) return if (ref != null && ref.getReference(resolveContext).multiResolve(false).asSequence().mapNotNull { it.element }.any { isInStubPackage(it) }) { return } qName.firstComponent?.let(sources::add) } } private fun run(file: PyFile, sources: Set<String>, problemsHolder: ProblemsHolder) { val module = ModuleUtilCore.findModuleForFile(file) ?: return val sdk = PythonSdkType.findPythonSdk(module) ?: return val installedPackages = PyPackageManager.getInstance(sdk).packages ?: emptyList() if (installedPackages.isEmpty()) return val availablePackages = PyPackageManagers.getInstance().getManagementService(file.project, sdk).allPackagesCached if (availablePackages.isEmpty()) return val cache = ServiceManager.getService(PyStubPackagesAdvertiserCache::class.java).forSdk(sdk) processForcedPackages(file, sources, module, sdk, availablePackages, installedPackages, cache, problemsHolder) processCheckedPackages(file, sources, module, sdk, availablePackages, installedPackages, cache) } private fun processForcedPackages(file: PyFile, sources: Set<String>, module: Module, sdk: Sdk, availablePackages: List<RepoPackage>, installedPackages: List<PyPackage>, cache: Cache<String, Set<RepoPackage>>, problemsHolder: ProblemsHolder) { val (sourcesToLoad, cached) = splitIntoNotCachedAndCached(forcedSourcesToProcess(sources), cache) val sourceToStubPkgsAvailableToInstall = sourceToStubPackagesAvailableToInstall( sourceToInstalledRuntimeAndStubPackages(sourcesToLoad, FORCED, installedPackages), availablePackages ) sourceToStubPkgsAvailableToInstall.forEach { source, stubPkgs -> cache.put(source, stubPkgs) } val (reqs, args) = toRequirementsAndExtraArgs(sourceToStubPkgsAvailableToInstall, cached) if (reqs.isNotEmpty()) { val plural = reqs.size > 1 val reqsToString = PyPackageUtil.requirementsToString(reqs) problemsHolder.registerProblem(file, "Stub package${if (plural) "s" else ""} $reqsToString ${if (plural) "are" else "is"} not installed. " + "${if (plural) "They" else "It"} contain${if (plural) "" else "s"} type hints needed for better code insight.", createInstallStubPackagesQuickFix(reqs, args, module, sdk), createIgnorePackagesQuickFix(reqs, ignoredPackages)) } } private fun processCheckedPackages(file: PyFile, sources: Set<String>, module: Module, sdk: Sdk, availablePackages: List<RepoPackage>, installedPackages: List<PyPackage>, cache: Cache<String, Set<RepoPackage>>) { val project = file.project if (project.getUserData(BALLOON_SHOWING) == true) return val (sourcesToLoad, cached) = splitIntoNotCachedAndCached(checkedSourcesToProcess(sources), cache) val sourceToStubPkgsAvailableToInstall = sourceToStubPackagesAvailableToInstall( sourceToInstalledRuntimeAndStubPackages(sourcesToLoad, CHECKED, installedPackages), availablePackages ) sourceToStubPkgsAvailableToInstall.forEach { source, stubPkgs -> cache.put(source, stubPkgs) } val (reqs, args) = toRequirementsAndExtraArgs(sourceToStubPkgsAvailableToInstall, cached) if (reqs.isNotEmpty()) { val plural = reqs.size > 1 val reqsToString = PyPackageUtil.requirementsToString(reqs) project.putUserData(BALLOON_SHOWING, true) BALLOON_NOTIFICATIONS .createNotification( "Type hints are not installed", "They are needed for better code insight.<br/>" + "<a href=\"#yes\">Install ${if (plural) "stub packages" else reqsToString}</a>&nbsp;&nbsp;&nbsp;&nbsp;" + "<a href=\"#no\">Ignore</a>&nbsp;&nbsp;&nbsp;&nbsp;" + "<a href=\"#settings\">Settings</a>", NotificationType.INFORMATION ) { notification, event -> try { val problemDescriptor = ProblemDescriptorImpl( file, file, "Stub package${if (plural) "s" else ""} $reqsToString ${if (plural) "are" else "is"} not installed", LocalQuickFix.EMPTY_ARRAY, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, true, null, true ) when (event.description) { "#yes" -> { createInstallStubPackagesQuickFix(reqs, args, module, sdk).applyFix(project, problemDescriptor) } "#no" -> createIgnorePackagesQuickFix(reqs, ignoredPackages).applyFix(project, problemDescriptor) "#settings" -> { val profile = ProjectInspectionProfileManager.getInstance(project).currentProfile EditInspectionToolsSettingsAction.editToolSettings(project, profile, PyStubPackagesAdvertiser::class.simpleName) } } } finally { notification.expire() } } .whenExpired { project.putUserData(BALLOON_SHOWING, false) } .notify(project) } } private fun forcedSourcesToProcess(sources: Set<String>) = sources.filterTo(mutableSetOf()) { it in FORCED } private fun checkedSourcesToProcess(sources: Set<String>) = sources.filterTo(mutableSetOf()) { it in CHECKED } private fun splitIntoNotCachedAndCached(sources: Set<String>, cache: Cache<String, Set<RepoPackage>>): Pair<Set<String>, Set<RepoPackage>> { if (sources.isEmpty()) return emptySet<String>() to emptySet() val notCached = mutableSetOf<String>() val cached = mutableSetOf<RepoPackage>() synchronized(cache) { // despite cache is thread-safe, // here we have sync block to guarantee only one reader // and as a result not run processing for sources that are already evaluating sources.forEach { source -> cache.getIfPresent(source).let { if (it == null) { notCached.add(source) // mark this source as evaluating // if source processing failed, this value would mean that such source was handled cache.put(source, emptySet()) } else { cached.addAll(it) } } } } return notCached to cached } private fun sourceToInstalledRuntimeAndStubPackages(sourcesToLoad: Set<String>, sourceToPackage: Map<String, String>, installedPackages: List<PyPackage>): Map<String, List<Pair<PyPackage, PyPackage?>>> { val result = mutableMapOf<String, List<Pair<PyPackage, PyPackage?>>>() for (source in sourcesToLoad) { val pkgName = sourceToPackage[source] ?: continue if (ignoredPackages.contains(pkgName)) continue installedRuntimeAndStubPackages(pkgName, installedPackages)?.let { result.put(source, listOf(it)) } } return result } private fun sourceToStubPackagesAvailableToInstall(sourceToInstalledRuntimeAndStubPkgs: Map<String, List<Pair<PyPackage, PyPackage?>>>, availablePackages: List<RepoPackage>): Map<String, Set<RepoPackage>> { if (sourceToInstalledRuntimeAndStubPkgs.isEmpty()) return emptyMap() val stubPkgsAvailableToInstall = mutableMapOf<String, RepoPackage>() availablePackages.forEach { if (it.name.endsWith(STUBS_SUFFIX)) stubPkgsAvailableToInstall[it.name] = it } val result = mutableMapOf<String, Set<RepoPackage>>() sourceToInstalledRuntimeAndStubPkgs.forEach { source, runtimeAndStubPkgs -> result[source] = runtimeAndStubPkgs .asSequence() .filter { it.second == null } .mapNotNull { stubPkgsAvailableToInstall["${it.first.name}$STUBS_SUFFIX"] } .toSet() } return result } private fun createInstallStubPackagesQuickFix(reqs: List<PyRequirement>, args: List<String>, module: Module, sdk: Sdk): LocalQuickFix { val project = module.project val stubPkgNamesToInstall = reqs.mapTo(mutableSetOf()) { it.name } val installationListener = object : PyPackageManagerUI.Listener { override fun started() { ServiceManager.getService(project, PyStubPackagesInstallingStatus::class.java).markAsInstalling(stubPkgNamesToInstall) } override fun finished(exceptions: MutableList<ExecutionException>?) { val status = ServiceManager.getService(project, PyStubPackagesInstallingStatus::class.java) val stubPkgsToUninstall = PyStubPackagesCompatibilityInspection .findIncompatibleRuntimeToStubPackages(sdk) { it.name in stubPkgNamesToInstall } .map { it.second } if (stubPkgsToUninstall.isNotEmpty()) { val stubPkgNamesToUninstall = stubPkgsToUninstall.mapTo(mutableSetOf()) { it.name } val uninstallationListener = object : PyPackageManagerUI.Listener { override fun started() {} override fun finished(exceptions: MutableList<ExecutionException>?) { status.unmarkAsInstalling(stubPkgNamesToUninstall) } } val plural = stubPkgNamesToUninstall.size > 1 val content = "Suggested ${stubPkgNamesToUninstall.joinToString { "'$it'" }} " + "${if (plural) "are" else "is"} incompatible with your current environment.<br/>" + "${if (plural) "These" else "This"} stub package${if (plural) "s" else ""} will be removed." BALLOON_NOTIFICATIONS.createNotification(content, NotificationType.WARNING).notify(project) PyPackageManagerUI(project, sdk, uninstallationListener).uninstall(stubPkgsToUninstall) stubPkgNamesToInstall.removeAll(stubPkgNamesToUninstall) } status.unmarkAsInstalling(stubPkgNamesToInstall) } } val name = "Install stub package" + if (reqs.size > 1) "s" else "" return PyInstallRequirementsFix(name, module, sdk, reqs, args, installationListener) } private fun createIgnorePackagesQuickFix(reqs: List<PyRequirement>, ignoredPkgs: MutableList<String>): LocalQuickFix { return object : LocalQuickFix { override fun getFamilyName() = "Ignore package" + if (reqs.size > 1) "s" else "" override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val pkgNames = reqs.asSequence().map { it.name.removeSuffix(STUBS_SUFFIX) } if (ignoredPkgs.addAll(pkgNames)) ProjectInspectionProfileManager.getInstance(project).fireProfileChanged() } } } private fun toRequirementsAndExtraArgs(loaded: Map<String, Set<RepoPackage>>, cached: Set<RepoPackage>): Pair<List<PyRequirement>, List<String>> { val reqs = mutableListOf<PyRequirement>() val args = mutableListOf("--no-deps") (cached.asSequence().filterNot { ignoredPackages.contains(it.name.removeSuffix(STUBS_SUFFIX)) } + loaded.values.asSequence().flatten()) .forEach { val version = it.latestVersion val url = it.repoUrl reqs.add(if (version == null) pyRequirement(it.name) else pyRequirement(it.name, PyRequirementRelation.EQ, version)) if (url != null && !PyPIPackageUtil.isPyPIRepository(url)) { with(args) { add("--extra-index-url") add(url) } } } return reqs to args } private fun installedRuntimeAndStubPackages(pkgName: String, installedPackages: List<PyPackage>): Pair<PyPackage, PyPackage?>? { var runtime: PyPackage? = null var stub: PyPackage? = null val stubPkgName = "$pkgName$STUBS_SUFFIX" for (pkg in installedPackages) { val name = pkg.name if (name == pkgName) runtime = pkg if (name == stubPkgName) stub = pkg } return if (runtime == null) null else runtime to stub } }
apache-2.0
9e7f4e20077b7795152e274d19ffaa8d
43.188976
148
0.665637
4.909595
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/completion/testData/basic/common/namedArguments/NotOnlyNamedArguments.kt
1
211
// FIR_IDENTICAL // FIR_COMPARISON fun foo(first: Int, second: Int, third: String) { } fun test(p: Int) = foo(12, <caret>, third = "") // EXIST: p // ABSENT: "first =" // EXIST: "third =" // EXIST: "second ="
apache-2.0
1f79eaa2e027bc2f1b264c3dcbf97be0
18.181818
49
0.582938
2.776316
false
true
false
false
google/j2cl
transpiler/java/com/google/j2cl/transpiler/backend/kotlin/Renderer.kt
1
3703
/* * Copyright 2021 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.j2cl.transpiler.backend.kotlin import com.google.j2cl.common.Problems import com.google.j2cl.transpiler.ast.HasName import com.google.j2cl.transpiler.ast.Type import com.google.j2cl.transpiler.backend.common.SourceBuilder /** Renderer of the Kotlin source code. */ data class Renderer( /** Rendering environment. */ val environment: Environment, /** Output source builder. */ val sourceBuilder: SourceBuilder, /** Rendering problems. */ val problems: Problems, /** Label to render with the return statement. */ val currentReturnLabelIdentifier: String? = null, /** Currently rendered type. */ val currentType: Type? = null, /** Whether to render this reference with explicit qualifier. */ // TODO(b/252138814): Remove when KT-54349 is fixed val renderThisReferenceWithLabel: Boolean = false, /** A set of local names which are potentially shadowing imports. */ val localNames: Set<String> = setOf() ) { fun renderNewLine() { sourceBuilder.newLine() } fun render(string: String) { sourceBuilder.append(string) } fun renderName(hasName: HasName) { renderIdentifier(environment.identifier(hasName)) } fun renderInCurlyBrackets(renderFn: () -> Unit) { sourceBuilder.openBrace() renderFn() sourceBuilder.closeBrace() } fun renderIndented(renderFn: () -> Unit) { sourceBuilder.indent() renderFn() sourceBuilder.unindent() } fun renderIndentedIf(condition: Boolean, renderFn: () -> Unit) { if (condition) renderIndented(renderFn) else renderFn() } fun renderInParentheses(renderFn: () -> Unit) { render("(") renderFn() render(")") } fun renderInSquareBrackets(renderFn: () -> Unit) { render("[") renderFn() render("]") } fun renderInAngleBrackets(renderFn: () -> Unit) { render("<") renderFn() render(">") } fun renderInCommentBrackets(renderFn: () -> Unit) { render("/* ") renderFn() render(" */") } fun renderInBackticks(renderFn: () -> Unit) { render("`") renderFn() render("`") } fun <V> renderSeparatedWith(values: Iterable<V>, separator: String, renderFn: (V) -> Unit) { var first = true for (value in values) { if (first) { first = false } else { render(separator) } renderFn(value) } } fun <V> renderCommaSeparated(values: Iterable<V>, renderFn: (V) -> Unit) { renderSeparatedWith(values, ", ", renderFn) } fun <V> renderDotSeparated(values: Iterable<V>, renderFn: (V) -> Unit) { renderSeparatedWith(values, ".", renderFn) } fun <V> renderStartingWithNewLines(values: Iterable<V>, renderFn: (V) -> Unit) { for (value in values) { renderNewLine() renderFn(value) } } fun <V> renderSeparatedWithEmptyLine(values: Iterable<V>, renderFn: (V) -> Unit) { renderSeparatedWith(values, "\n\n", renderFn) } fun renderTodo(string: String) { render("TODO") renderInParentheses { renderString(string) } } fun renderString(string: String) { render("\"${string.escapedString}\"") } }
apache-2.0
511bd9dfa1f626e5d2b87e053ac5ed8c
24.715278
94
0.665406
3.841286
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2018/Day09.kt
1
1089
package com.nibado.projects.advent.y2018 import com.nibado.projects.advent.Day import java.util.* object Day09 : Day { class Board : ArrayDeque<Int>() { fun rotate(amount: Int) { if (amount >= 0) { for (i in 0 until amount) { addFirst(removeLast()) } } else { for (i in 0 until -amount - 1) { addLast(remove()) } } } } private fun game(players: Int, marbleMaxValue: Int): Long { val board = Board() val scores = LongArray(players) board.addFirst(0) for (marble in (1..marbleMaxValue)) { if (marble % 23 == 0) { board.rotate(-7) scores[marble % players] += board.pop().toLong() + marble } else { board.rotate(2) board.addLast(marble) } } return scores.maxOrNull()!! } override fun part1() = game(459, 71320) override fun part2() = game(459, 71320 * 100) }
mit
8f2640143b64dcfd0b978d574915306f
24.952381
73
0.473829
4.172414
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/fixes/ChangeTypeQuickFixFactories.kt
1
10014
// 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.quickfix.fixes import com.intellij.codeInspection.util.IntentionName import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.util.parentOfType import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.diagnostics.KtDiagnosticWithPsi import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtPropertySymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithMembers import org.jetbrains.kotlin.analysis.api.symbols.psiSafe import org.jetbrains.kotlin.analysis.api.types.KtNonErrorClassType import org.jetbrains.kotlin.analysis.api.types.KtType import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.codeinsight.api.applicable.fixes.AbstractKotlinApplicableQuickFix import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.diagnosticFixFactory import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils import org.jetbrains.kotlin.idea.codeinsights.impl.base.CallableReturnTypeUpdaterUtils.updateType import org.jetbrains.kotlin.idea.quickfix.ChangeTypeFixUtils import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType object ChangeTypeQuickFixFactories { enum class TargetType { CURRENT_DECLARATION, BASE_DECLARATION, ENCLOSING_DECLARATION, CALLED_FUNCTION, VARIABLE, } private class UpdateTypeQuickFix<E : KtCallableDeclaration>( target: E, private val targetType: TargetType, private val typeInfo: CallableReturnTypeUpdaterUtils.TypeInfo, ) : AbstractKotlinApplicableQuickFix<E>(target) { override fun getFamilyName(): String = KotlinBundle.message("fix.change.return.type.family") override fun getActionName(element: E): String = getActionName(element, targetType, typeInfo) override fun apply(element: E, project: Project, editor: Editor?, file: KtFile) = updateType(element, typeInfo, project, editor) } val changeFunctionReturnTypeOnOverride = changeReturnTypeOnOverride<KtFirDiagnostic.ReturnTypeMismatchOnOverride> { it.function as? KtFunctionSymbol } val changePropertyReturnTypeOnOverride = changeReturnTypeOnOverride<KtFirDiagnostic.PropertyTypeMismatchOnOverride> { it.property as? KtPropertySymbol } val changeVariableReturnTypeOnOverride = changeReturnTypeOnOverride<KtFirDiagnostic.VarTypeMismatchOnOverride> { it.variable as? KtPropertySymbol } val returnTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.ReturnTypeMismatch::class) { diagnostic -> val declaration = diagnostic.targetFunction.psi as? KtCallableDeclaration ?: return@diagnosticFixFactory emptyList() listOf(UpdateTypeQuickFix(declaration, TargetType.ENCLOSING_DECLARATION, createTypeInfo(diagnostic.actualType))) } val componentFunctionReturnTypeMismatch = diagnosticFixFactory(KtFirDiagnostic.ComponentFunctionReturnTypeMismatch::class) { diagnostic -> val entryWithWrongType = getDestructuringDeclarationEntryThatTypeMismatchComponentFunction( diagnostic.componentFunctionName, diagnostic.psi ) ?: return@diagnosticFixFactory emptyList() buildList { add(UpdateTypeQuickFix(entryWithWrongType, TargetType.VARIABLE, createTypeInfo(diagnostic.destructingType))) val classSymbol = (diagnostic.psi.getKtType() as? KtNonErrorClassType)?.classSymbol as? KtSymbolWithMembers ?: return@buildList val componentFunction = classSymbol.getMemberScope() .getCallableSymbols { it == diagnostic.componentFunctionName } .firstOrNull()?.psi as? KtCallableDeclaration ?: return@buildList add(UpdateTypeQuickFix(componentFunction, TargetType.CALLED_FUNCTION, createTypeInfo(diagnostic.expectedType))) } } private inline fun <reified DIAGNOSTIC : KtDiagnosticWithPsi<KtNamedDeclaration>> changeReturnTypeOnOverride( crossinline getCallableSymbol: (DIAGNOSTIC) -> KtCallableSymbol? ) = diagnosticFixFactory(DIAGNOSTIC::class) { diagnostic -> val declaration = diagnostic.psi as? KtCallableDeclaration ?: return@diagnosticFixFactory emptyList() val callable = getCallableSymbol(diagnostic) ?: return@diagnosticFixFactory emptyList() listOfNotNull( createChangeCurrentDeclarationQuickFix(callable, declaration), createChangeOverriddenFunctionQuickFix(callable), ) } context(KtAnalysisSession) private fun <PSI : KtCallableDeclaration> createChangeCurrentDeclarationQuickFix( callable: KtCallableSymbol, declaration: PSI ): UpdateTypeQuickFix<PSI>? { val lowerSuperType = findLowerBoundOfOverriddenCallablesReturnTypes(callable) ?: return null return UpdateTypeQuickFix(declaration, TargetType.CURRENT_DECLARATION, createTypeInfo(lowerSuperType)) } context(KtAnalysisSession) private fun createChangeOverriddenFunctionQuickFix(callable: KtCallableSymbol): UpdateTypeQuickFix<KtCallableDeclaration>? { val type = callable.returnType val singleNonMatchingOverriddenFunction = findSingleNonMatchingOverriddenFunction(callable, type) ?: return null val singleMatchingOverriddenFunctionPsi = singleNonMatchingOverriddenFunction.psiSafe<KtCallableDeclaration>() ?: return null if (!singleMatchingOverriddenFunctionPsi.isWritable) return null return UpdateTypeQuickFix(singleMatchingOverriddenFunctionPsi, TargetType.BASE_DECLARATION, createTypeInfo(type)) } context(KtAnalysisSession) private fun findSingleNonMatchingOverriddenFunction( callable: KtCallableSymbol, type: KtType ): KtCallableSymbol? { val overriddenSymbols = callable.getDirectlyOverriddenSymbols() return overriddenSymbols .singleOrNull { overridden -> !type.isSubTypeOf(overridden.returnType) } } context(KtAnalysisSession) private fun createTypeInfo(ktType: KtType) = with(CallableReturnTypeUpdaterUtils.TypeInfo) { createByKtTypes(ktType) } context(KtAnalysisSession) private fun findLowerBoundOfOverriddenCallablesReturnTypes(symbol: KtCallableSymbol): KtType? { var lowestType: KtType? = null for (overridden in symbol.getDirectlyOverriddenSymbols()) { val overriddenType = overridden.returnType when { lowestType == null || overriddenType isSubTypeOf lowestType -> { lowestType = overriddenType } lowestType isNotSubTypeOf overriddenType -> { return null } } } return lowestType } private fun getDestructuringDeclarationEntryThatTypeMismatchComponentFunction( componentName: Name, rhsExpression: KtExpression ): KtDestructuringDeclarationEntry? { val componentIndex = componentName.asString().removePrefix("component").toIntOrNull() ?: return null val destructuringDeclaration = rhsExpression.getParentOfType<KtDestructuringDeclaration>(strict = true) ?: return null return destructuringDeclaration.entries[componentIndex - 1] } @IntentionName private fun getActionName( declaration: KtCallableDeclaration, targetType: TargetType, typeInfo: CallableReturnTypeUpdaterUtils.TypeInfo ) = ChangeTypeFixUtils.getTextForQuickFix( declaration, getPresentation(targetType, declaration), typeInfo.defaultType.isUnit, typeInfo.defaultType.shortTypeRepresentation ) private fun getPresentation( targetType: TargetType, declaration: KtCallableDeclaration ): String? { return when (targetType) { TargetType.CURRENT_DECLARATION -> null TargetType.BASE_DECLARATION -> KotlinBundle.message( "fix.change.return.type.presentation.base", declaration.presentationForQuickfix ?: return null ) TargetType.ENCLOSING_DECLARATION -> KotlinBundle.message( "fix.change.return.type.presentation.enclosing", declaration.presentationForQuickfix ?: return KotlinBundle.message("fix.change.return.type.presentation.enclosing.function") ) TargetType.CALLED_FUNCTION -> { val presentation = declaration.presentationForQuickfix ?: return KotlinBundle.message("fix.change.return.type.presentation.called.function") when (declaration) { is KtParameter -> KotlinBundle.message("fix.change.return.type.presentation.accessed", presentation) else -> KotlinBundle.message("fix.change.return.type.presentation.called", presentation) } } TargetType.VARIABLE -> return "'${declaration.name}'" } } private val KtCallableDeclaration.presentationForQuickfix: String? get() { val containerName = parentOfType<KtNamedDeclaration>()?.nameAsName?.takeUnless { it.isSpecial } return ChangeTypeFixUtils.functionOrConstructorParameterPresentation(this, containerName?.asString()) } }
apache-2.0
48355e4179effbedeff880d5459b6dff
47.61165
158
0.719493
5.575724
false
false
false
false
chetdeva/recyclerview-bindings
app/src/main/java/com/fueled/recyclerviewbindings/widget/swipe/SwipeItemTouchHelperCallback.kt
1
5202
package com.fueled.recyclerviewbindings.widget.swipe import android.graphics.Canvas import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.support.v7.widget.helper.ItemTouchHelper import com.fueled.recyclerviewbindings.util.ViewUtil /** * Reference @link {https://www.learn2crack.com/2016/02/custom-swipe-recyclerview.html} * @author chetansachdeva on 26/07/17 */ class SwipeItemTouchHelperCallback private constructor(dragDirs: Int, swipeDirs: Int) : ItemTouchHelper.SimpleCallback(dragDirs, swipeDirs) { private lateinit var drawableLeft: Drawable private lateinit var drawableRight: Drawable private val paintLeft: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private val paintRight: Paint = Paint(Paint.ANTI_ALIAS_FLAG) private lateinit var onItemSwipeLeftListener: OnItemSwipeListener private lateinit var onItemSwipeRightListener: OnItemSwipeListener private var swipeEnabled: Boolean = false private constructor(builder: Builder) : this(builder.dragDirs, builder.swipeDirs) { setPaintColor(paintLeft, builder.bgColorSwipeLeft) setPaintColor(paintRight, builder.bgColorSwipeRight) drawableLeft = builder.drawableLeft drawableRight = builder.drawableRight swipeEnabled = builder.swipeEnabled onItemSwipeLeftListener = builder.onItemSwipeLeftListener onItemSwipeRightListener = builder.onItemSwipeRightListener } private fun setPaintColor(paint: Paint, color: Int) { paint.color = color } override fun isItemViewSwipeEnabled() = swipeEnabled override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { val position = viewHolder.adapterPosition if (direction == ItemTouchHelper.LEFT) { onItemSwipeLeftListener.onItemSwiped(position) } else if (direction == ItemTouchHelper.RIGHT) { onItemSwipeRightListener.onItemSwiped(position) } } override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { val itemView = viewHolder.itemView val height = itemView.bottom.toFloat() - itemView.top.toFloat() val width = height / 3 if (dX > 0) { val background = RectF(itemView.left.toFloat(), itemView.top.toFloat(), dX, itemView.bottom.toFloat()) val iconDest = RectF(itemView.left.toFloat() + width, itemView.top.toFloat() + width, itemView.left.toFloat() + 2 * width, itemView.bottom.toFloat() - width) c.drawRect(background, paintLeft) c.drawBitmap(ViewUtil.getBitmap(drawableLeft), null, iconDest, paintLeft) } else { val background = RectF(itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat()) val iconDest = RectF(itemView.right.toFloat() - 2 * width, itemView.top.toFloat() + width, itemView.right.toFloat() - width, itemView.bottom.toFloat() - width) c.drawRect(background, paintRight) c.drawBitmap(ViewUtil.getBitmap(drawableRight), null, iconDest, paintRight) } } super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive) } interface OnItemSwipeListener { fun onItemSwiped(position: Int) } class Builder(internal val dragDirs: Int, internal val swipeDirs: Int) { internal lateinit var drawableLeft: Drawable internal lateinit var drawableRight: Drawable internal var bgColorSwipeLeft: Int = 0 internal var bgColorSwipeRight: Int = 0 internal lateinit var onItemSwipeLeftListener: OnItemSwipeListener internal lateinit var onItemSwipeRightListener: OnItemSwipeListener internal var swipeEnabled: Boolean = false fun drawableLeft(value: Drawable): Builder { drawableLeft = value return this } fun drawableRight(value: Drawable): Builder { drawableRight = value return this } fun bgColorSwipeLeft(value: Int): Builder { bgColorSwipeLeft = value return this } fun bgColorSwipeRight(value: Int): Builder { bgColorSwipeRight = value return this } fun onItemSwipeLeftListener(value: OnItemSwipeListener): Builder { onItemSwipeLeftListener = value return this } fun onItemSwipeRightListener(value: OnItemSwipeListener): Builder { onItemSwipeRightListener = value return this } fun swipeEnabled(value: Boolean): Builder { swipeEnabled = value return this } fun build() = SwipeItemTouchHelperCallback(this) } }
mit
3371138f85986b9b5e088c96e36e4829
39.640625
175
0.685313
4.852612
false
false
false
false
exercism/xkotlin
exercises/practice/leap/src/test/kotlin/LeapTest.kt
1
1165
import org.junit.Test import org.junit.Ignore import kotlin.test.assertFalse import kotlin.test.assertTrue class LeapTest { @Test fun `not leap - not divisible by 4`() = assertYearIsCommon(2015) @Ignore @Test fun `not leap - divisible by 2, not divisible by 4`() = assertYearIsCommon(1970) @Ignore @Test fun `leap - divisible by 4, not divisible by 100`() = assertYearIsLeap(1996) @Ignore @Test fun `leap - divisible by 4 and 5`() = assertYearIsLeap(1960) @Ignore @Test fun `not leap - divisible by 100, not divisible by 400`() = assertYearIsCommon(2100) @Ignore @Test fun `not leap - divisible by 100 but not by 3`() = assertYearIsCommon(1900) @Ignore @Test fun `leap - divisible by 400`() = assertYearIsLeap(2000) @Ignore @Test fun `leap - divisible by 400 but not by 125`() = assertYearIsLeap(2400) @Ignore @Test fun `not leap - divisible by 200, not divisible by 400`() = assertYearIsCommon(1800) } private fun assertYearIsLeap(year: Int) = assertTrue(Year(year).isLeap) private fun assertYearIsCommon(year: Int) = assertFalse(Year(year).isLeap)
mit
ee4d708939890ae995d38156ec44e54b
24.888889
88
0.672961
3.562691
false
true
false
false
muntasirsyed/intellij-community
platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/ProcessHandlerWrapper.kt
1
2530
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger import com.intellij.execution.KillableProcess import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.diagnostic.Logger import com.intellij.xdebugger.XDebugProcess class ProcessHandlerWrapper(private val debugProcess: XDebugProcess, private val handler: ProcessHandler) : ProcessHandler(), KillableProcess { init { if (handler.isStartNotified) { super.startNotify() } handler.addProcessListener(object : ProcessAdapter() { override fun startNotified(event: ProcessEvent) { [email protected]() } override fun processTerminated(event: ProcessEvent) { notifyProcessTerminated(event.exitCode) } }) } companion object { private val LOG: Logger = Logger.getInstance(ProcessHandlerWrapper::class.java) } override fun isSilentlyDestroyOnClose() = handler.isSilentlyDestroyOnClose override fun startNotify() { handler.startNotify() } override fun destroyProcessImpl() { stop(true) } override fun detachProcessImpl() { stop(false) } private fun stop(destroy: Boolean) { debugProcess.stopAsync() .done { stopProcess(destroy) } .rejected { try { LOG.error(it) } finally { stopProcess(destroy) } } } private fun stopProcess(destroy: Boolean) { if (destroy) { handler.destroyProcess() } else { handler.detachProcess() } } override fun detachIsDefault() = handler.detachIsDefault() override fun getProcessInput() = handler.processInput override fun canKillProcess() = handler is KillableProcess && handler.canKillProcess() override fun killProcess() { if (handler is KillableProcess) { handler.killProcess() } } }
apache-2.0
478be4dbae813d81f9bbe102d4cf15df
26.215054
143
0.709881
4.525939
false
false
false
false
ursjoss/sipamato
core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/jobs/paper/PaperSyncConfig.kt
2
7811
package ch.difty.scipamato.core.sync.jobs.paper import ch.difty.scipamato.common.DateTimeService import ch.difty.scipamato.core.db.tables.Code import ch.difty.scipamato.core.db.tables.Paper import ch.difty.scipamato.core.db.tables.PaperCode import ch.difty.scipamato.core.sync.PublicPaper import ch.difty.scipamato.core.sync.code.CodeAggregator import ch.difty.scipamato.core.sync.jobs.SyncConfig import ch.difty.scipamato.publ.db.tables.records.PaperRecord import org.jooq.DSLContext import org.jooq.TableField import org.jooq.impl.DSL import org.springframework.batch.core.Job import org.springframework.batch.core.configuration.annotation.JobBuilderFactory import org.springframework.batch.core.configuration.annotation.StepBuilderFactory import org.springframework.batch.item.ItemWriter import org.springframework.beans.factory.annotation.Qualifier import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import java.sql.ResultSet import java.sql.SQLException import java.sql.Timestamp import javax.sql.DataSource /** * Defines the paper synchronization job, applying two steps: * * 1. insertingOrUpdating: inserts new records or updates if already present * 1. purging: removes records that have not been touched by the first step * (within a defined grace time in minutes) * * * @author u.joss */ @Configuration @Profile("!wickettest") @Suppress("LongParameterList") open class PaperSyncConfig( private val codeAggregator: CodeAggregator, @Qualifier("dslContext") jooqCore: DSLContext, @Qualifier("publicDslContext") jooqPublic: DSLContext, @Qualifier("dataSource") coreDataSource: DataSource, jobBuilderFactory: JobBuilderFactory, stepBuilderFactory: StepBuilderFactory, dateTimeService: DateTimeService, private val shortFieldConcatenator: SyncShortFieldConcatenator, ) : SyncConfig<PublicPaper, PaperRecord>(TOPIC, CHUNK_SIZE, jooqCore, jooqPublic, coreDataSource, jobBuilderFactory, stepBuilderFactory, dateTimeService) { init { setInternalCodes() } private fun setInternalCodes() { codeAggregator.setInternalCodes(fetchInternalCodesFromDb()) } private fun fetchInternalCodesFromDb(): List<String> = jooqCore .select() .from(Code.CODE) .where(Code.CODE.INTERNAL.isTrue) .fetch(Code.CODE.CODE_) @Bean open fun syncPaperJob(): Job = createJob() override val jobName: String get() = "syncPaperJob" override fun publicWriter(): ItemWriter<PublicPaper> = PaperItemWriter(jooqPublic) override fun selectSql(): String = jooqCore .select(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED, DSL .arrayAgg(PaperCode.PAPER_CODE.CODE) .`as`(ALIAS_CODES), C_METHOD_STUDY_DESIGN, C_METHOD_OUTCOME, C_EXPOSURE_POLLUTANT, C_EXPOSURE_ASSESSMENT, C_METHOD_STATISTICS, C_METHOD_CONFOUNDERS, C_POPULATION_PLACE, C_POPULATION_PARTICIPANTS, C_POPULATION_DURATION, C_RESULT_EXPOSURE_RANGE, C_RESULT_EFFECT_ESTIMATE, C_RESULT_MEASURED_OUTCOME, C_CONCLUSION) .from(Paper.PAPER) .innerJoin(PaperCode.PAPER_CODE) .on(Paper.PAPER.ID.eq(PaperCode.PAPER_CODE.PAPER_ID)) .innerJoin(Code.CODE) .on(PaperCode.PAPER_CODE.CODE.eq(Code.CODE.CODE_)) .groupBy(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED, C_METHOD_STUDY_DESIGN, C_METHOD_OUTCOME, C_EXPOSURE_POLLUTANT, C_EXPOSURE_ASSESSMENT, C_METHOD_STATISTICS, C_METHOD_CONFOUNDERS, C_POPULATION_PLACE, C_POPULATION_PARTICIPANTS, C_POPULATION_DURATION, C_RESULT_EXPOSURE_RANGE, C_RESULT_EFFECT_ESTIMATE, C_RESULT_MEASURED_OUTCOME, C_CONCLUSION) .sql @Throws(SQLException::class) override fun makeEntity(rs: ResultSet): PublicPaper { val paper: PublicPaper = PublicPaper( id = getLong(C_ID, rs), number = getLong(C_NUMBER, rs), pmId = getInteger(C_PM_ID, rs), authors = getString(C_AUTHORS, rs), title = getString(C_TITLE, rs), location = getString(C_LOCATION, rs), publicationYear = getInteger(C_PUB_YEAR, rs), goals = getString(C_GOALS, rs), methods = shortFieldConcatenator.methodsFrom(rs), population = shortFieldConcatenator.populationFrom(rs), result = shortFieldConcatenator.resultFrom(rs), comment = getString(C_COMMENT, rs), version = getInteger(C_VERSION, rs), created = getTimestamp(C_CREATED, rs), lastModified = getTimestamp(C_LAST_MODIFIED, rs), codesPopulation = null, codesStudyDesign = null, codes = extractCodes(ALIAS_CODES, rs), lastSynched = getNow(), ) codeAggregator.load(paper.codes) paper.codesPopulation = codeAggregator.codesPopulation paper.codesStudyDesign = codeAggregator.codesStudyDesign paper.codes = codeAggregator.aggregatedCodes return paper } @Suppress("SameParameterValue", "UNCHECKED_CAST") @Throws(SQLException::class) private fun extractCodes(alias: String, rs: ResultSet): Array<String> = rs .getArray(alias) .array as Array<String> override fun lastSynchedField(): TableField<PaperRecord, Timestamp> = ch.difty.scipamato.publ.db.tables.Paper.PAPER.LAST_SYNCHED companion object { private const val TOPIC = "paper" private const val CHUNK_SIZE = 500 private const val ALIAS_CODES = "codes" // relevant fields of the core Paper record private val C_ID = Paper.PAPER.ID private val C_NUMBER = Paper.PAPER.NUMBER private val C_PM_ID = Paper.PAPER.PM_ID private val C_AUTHORS = Paper.PAPER.AUTHORS private val C_TITLE = Paper.PAPER.TITLE private val C_LOCATION = Paper.PAPER.LOCATION private val C_PUB_YEAR = Paper.PAPER.PUBLICATION_YEAR private val C_GOALS = Paper.PAPER.GOALS private val C_METHODS = Paper.PAPER.METHODS private val C_POPULATION = Paper.PAPER.POPULATION private val C_RESULT = Paper.PAPER.RESULT private val C_COMMENT = Paper.PAPER.COMMENT private val C_VERSION = Paper.PAPER.VERSION private val C_CREATED = Paper.PAPER.CREATED private val C_LAST_MODIFIED = Paper.PAPER.LAST_MODIFIED // short fields (Kurzerfassung) private val C_METHOD_STUDY_DESIGN = Paper.PAPER.METHOD_STUDY_DESIGN private val C_METHOD_OUTCOME = Paper.PAPER.METHOD_OUTCOME private val C_EXPOSURE_POLLUTANT = Paper.PAPER.EXPOSURE_POLLUTANT private val C_EXPOSURE_ASSESSMENT = Paper.PAPER.EXPOSURE_ASSESSMENT private val C_METHOD_STATISTICS = Paper.PAPER.METHOD_STATISTICS private val C_METHOD_CONFOUNDERS = Paper.PAPER.METHOD_CONFOUNDERS private val C_POPULATION_PLACE = Paper.PAPER.POPULATION_PLACE private val C_POPULATION_PARTICIPANTS = Paper.PAPER.POPULATION_PARTICIPANTS private val C_POPULATION_DURATION = Paper.PAPER.POPULATION_DURATION private val C_RESULT_EXPOSURE_RANGE = Paper.PAPER.RESULT_EXPOSURE_RANGE private val C_RESULT_EFFECT_ESTIMATE = Paper.PAPER.RESULT_EFFECT_ESTIMATE private val C_RESULT_MEASURED_OUTCOME = Paper.PAPER.RESULT_MEASURED_OUTCOME private val C_CONCLUSION = Paper.PAPER.CONCLUSION } }
gpl-3.0
749eef793418c147d2db45df16ddf9a8
42.882022
132
0.698886
3.944949
false
false
false
false
allotria/intellij-community
python/src/com/jetbrains/python/packaging/PyRequirementsFileVisitor.kt
3
6800
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.packaging import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import com.jetbrains.python.PyBundle class PyRequirementsFileVisitor(private val importedPackages: MutableMap<String, PyPackage>, private val settings: PyPackageRequirementsSettings) { private val collectedOutput: MutableMap<VirtualFile, MutableList<String>> = mutableMapOf() private val unmatchedLines: MutableList<String> = mutableListOf() private val unchangedInBaseFiles: MutableList<String> = mutableListOf() fun visitRequirementsFile(requirementsFile: PsiFile): PyRequirementsAnalysisResult { doVisitFile(requirementsFile, mutableSetOf(requirementsFile.virtualFile)) val currentFileOutput = collectedOutput.remove(requirementsFile.virtualFile)!! importedPackages.values.asSequence() .map { if (settings.specifyVersion) "${it.name}${settings.versionSpecifier.separator}${it.version}" else it.name } .forEach { currentFileOutput.add(it) } return PyRequirementsAnalysisResult(currentFileOutput, collectedOutput, unmatchedLines, unchangedInBaseFiles) } private fun doVisitFile(requirementsFile: PsiFile, visitedFiles: MutableSet<VirtualFile>) { val outputLines = mutableListOf<String>() val entries = splitByRequirementsEntries(requirementsFile.text) for (lines in entries) { if (lines.size == 1) { val firstLine = lines.first() if (firstLine.startsWith("#") || firstLine.isBlank()) { outputLines.add(firstLine) continue } } val line = lines.asSequence() .map { it.trim() } .map { it.removeSuffix("\\") } .joinToString(" ") if (isSkipableInstallOption(line)) { outputLines.addAll(lines) continue } if (settings.modifyBaseFiles && isFileReference(line)) { // collecting requirements from base files for modification val filename = line.split(" ")[1] visitBaseFile(filename, requirementsFile.containingDirectory, visitedFiles) outputLines.addAll(lines) // always keeping base file reference continue } val parsed = PyRequirementParser.fromText(line, requirementsFile.virtualFile, mutableSetOf()) if (isFileReference(line)) { if (parsed.isEmpty()) { if (!settings.removeUnused) outputLines.addAll(lines) continue } // base files cannot be modified, so we report requirements with different version parsed.asSequence() .filter { it.name.toLowerCase() in importedPackages } .map { it to importedPackages.remove(it.name.toLowerCase()) } .filterNot { compatibleVersion(it.first, it.second!!.version, settings.specifyVersion) } .forEach { unchangedInBaseFiles.add(it.first.name) } outputLines.addAll(lines) } else if (parsed.isEmpty()) { if (settings.removeUnused) unmatchedLines.add(line) else outputLines.addAll(lines) } else { val requirement = parsed.first() val name = requirement.name.toLowerCase() if (name in importedPackages) { val pkg = importedPackages.remove(name)!! val formatted = formatRequirement(requirement, pkg, lines) outputLines.addAll(formatted) } else if (!settings.removeUnused) { outputLines.addAll(lines) } } } collectedOutput[requirementsFile.virtualFile] = outputLines } private fun formatRequirement(requirement: PyRequirement, pkg: PyPackage, lines: List<String>): List<String> = when { // keeping editable and vcs requirements requirement.isEditable || vcsPrefixes.any { lines.first().startsWith(it) } -> lines // existing version separators match the current package version settings.keepMatchingSpecifier && compatibleVersion(requirement, pkg.version, settings.specifyVersion) -> lines // requirement does not match package version and settings else -> listOf(convertToRequirementsEntry(requirement, settings, pkg.version)) } private fun visitBaseFile(filename: String, directory: PsiDirectory, visitedFiles: MutableSet<VirtualFile>) { val referencedFile = directory.virtualFile.findFileByRelativePath(filename) if (referencedFile != null && visitedFiles.add(referencedFile)) { val baseRequirementsFile = directory.manager.findFile(referencedFile)!! doVisitFile(baseRequirementsFile, visitedFiles) visitedFiles.remove(referencedFile) } } private fun splitByRequirementsEntries(requirementsText: String): MutableList<List<String>> { var splitList = mutableListOf<String>() val resultList = mutableListOf<List<String>>() if (requirementsText.isNotBlank()) { requirementsText.lines().forEach { splitList.add(it) if (!it.endsWith("\\")) { resultList.add(splitList) splitList = mutableListOf() } } } if (splitList.isNotEmpty()) error(PyBundle.message("python.requirements.error.ends.with.slash")) return resultList } private fun compatibleVersion(requirement: PyRequirement, version: String, specifyVersion: Boolean): Boolean = when { specifyVersion -> requirement.versionSpecs.isNotEmpty() && requirement.versionSpecs.all { it.matches(version) } else -> requirement.versionSpecs.isEmpty() } private fun convertToRequirementsEntry(requirement: PyRequirement, settings: PyPackageRequirementsSettings, version: String? = null): String { val packageName = when { settings.specifyVersion -> when { version != null -> requirement.name + requirement.extras + settings.versionSpecifier.separator + version else -> requirement.presentableText } else -> requirement.name + requirement.extras } if (requirement.installOptions.size == 1) return packageName val offset = " ".repeat(packageName.length + 1) val installOptions = requirement.installOptions.drop(1).joinToString(separator = "\\\n$offset") return "$packageName $installOptions" } private fun isSkipableInstallOption(line: String): Boolean = isEditableSelf(line) || (line.startsWith("--") && !line.startsWith("--editable") && !isFileReference(line)) private fun isFileReference(line: String): Boolean = line.startsWith("-r ") || line.startsWith("--requirement ") private fun isEditableSelf(line: String): Boolean = line.startsWith("--editable .") || line.startsWith("-e .") companion object { private val vcsPrefixes = listOf("git:", "git+", "svn+", "hg+", "bzr+") } }
apache-2.0
6ee222a32c70e631348da660c3b3290b
42.044304
144
0.699412
4.819277
false
false
false
false
allotria/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/refactorings/PythonRenameLesson.kt
1
6113
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.refactorings import com.intellij.ide.DataManager import com.intellij.ide.actions.exclusion.ExclusionHandler import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.ui.NameSuggestionsField import com.intellij.ui.tree.TreeVisitor import com.intellij.usageView.UsageViewBundle import com.intellij.util.ui.tree.TreeUtil import com.jetbrains.python.ift.PythonLessonsBundle import org.fest.swing.fixture.JTreeFixture import training.dsl.* import training.learn.LessonsBundle import training.learn.course.KLesson import javax.swing.JButton import javax.swing.JTree import javax.swing.tree.TreePath class PythonRenameLesson : KLesson("Rename", LessonsBundle.message("rename.lesson.name")) { override val testScriptProperties = TaskTestContext.TestScriptProperties(10) private val template = """ class Championship: def __init__(self): self.<name> = 0 def matches_count(self): return self.<name> * (self.<name> - 1) / 2 def add_new_team(self): self.<name> += 1 def team_matches(champ): champ.<name>() - 1 class Company: def __init__(self, t): self.teams = t def company_members(company): map(lambda team : team.name, company.teams) def teams(): return 16 c = Championship() c.<caret><name> = teams() print(c.<name>) """.trimIndent() + '\n' private val sample = parseLessonSample(template.replace("<name>", "teams")) override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) val dynamicWord = UsageViewBundle.message("usage.view.results.node.dynamic") var replace: String? = null var dynamicItem: String? = null task("RenameElement") { text(PythonLessonsBundle.message("python.rename.press.rename", action(it), code("teams"), code("teams_number"))) triggerByUiComponentAndHighlight(false, false) { ui: NameSuggestionsField -> ui.addDataChangedListener { replace = ui.enteredName } true } triggerByFoundPathAndHighlight { _: JTree, path: TreePath -> val pathStr = path.getPathComponent(1).toString() if (path.pathCount == 2 && pathStr.contains(dynamicWord)) { dynamicItem = pathStr true } else false } test { actions(it) dialog { type("teams_number") button("Refactor").click() } } } task { // Increase deterministic: collapse nodes before { (previous.ui as? JTree)?.let { tree -> TreeUtil.collapseAll(tree, 1) } } val dynamicReferencesString = "[$dynamicWord]" text(PythonLessonsBundle.message("python.rename.expand.dynamic.references", code("teams"), strong(dynamicReferencesString))) triggerByFoundPathAndHighlight { _: JTree, path: TreePath -> path.pathCount == 6 && path.getPathComponent(5).toString().contains("company_members") } showWarningIfFindToolbarClosed() test { //TODO: Fix tree access val jTree = previous.ui as? JTree ?: return@test val di = dynamicItem ?: return@test ideFrame { val jTreeFixture = JTreeFixture(robot, jTree) jTreeFixture.replaceSeparator("@@@") jTreeFixture.expandPath(di) // WARNING: several exception will be here because of UsageNode#toString inside info output during this operation } } } task { text(PythonLessonsBundle.message("python.rename.exclude.item", code("company_members"), action("EditorDelete"))) stateCheck { val tree = previous.ui as? JTree ?: return@stateCheck false val last = pathToExclude(tree) ?: return@stateCheck false val dataContext = DataManager.getInstance().getDataContext(tree) val exclusionProcessor: ExclusionHandler<*> = ExclusionHandler.EXCLUSION_HANDLER.getData(dataContext) ?: return@stateCheck false val leafToBeExcluded = last.lastPathComponent @Suppress("UNCHECKED_CAST") fun <T : Any?> castHack(processor: ExclusionHandler<T>): Boolean { return processor.isNodeExclusionAvailable(leafToBeExcluded as T) && processor.isNodeExcluded(leafToBeExcluded as T) } castHack(exclusionProcessor) } showWarningIfFindToolbarClosed() test { ideFrame { type("come") invokeActionViaShortcut("DELETE") } } } val confirmRefactoringButton = RefactoringBundle.message("usageView.doAction").dropMnemonic() task { triggerByUiComponentAndHighlight(highlightInside = false) { button: JButton -> button.text.contains(confirmRefactoringButton) } } task { val result = replace?.let { template.replace("<name>", it).replace("<caret>", "") } text(PythonLessonsBundle.message("python.rename.finish.refactoring", strong(confirmRefactoringButton))) stateCheck { editor.document.text == result } showWarningIfFindToolbarClosed() test(waitEditorToBeReady = false) { ideFrame { button(confirmRefactoringButton).click() } } } } private fun pathToExclude(tree: JTree): TreePath? { return TreeUtil.promiseVisit(tree, TreeVisitor { path -> if (path.pathCount == 7 && path.getPathComponent(6).toString().contains("lambda")) TreeVisitor.Action.INTERRUPT else TreeVisitor.Action.CONTINUE }).blockingGet(200) } private fun TaskContext.showWarningIfFindToolbarClosed() { showWarning(PythonLessonsBundle.message("python.rename.find.window.closed.warning", action("ActivateFindToolWindow")), restoreTaskWhenResolved = true) { previous.ui?.isShowing != true } } }
apache-2.0
79bf8684c5e00decca2a11dce8e092cb
34.33526
140
0.650744
4.695084
false
true
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/AbstractListsEntriesFragment.kt
1
4581
/* * Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte import android.os.Bundle import com.github.moko256.latte.client.base.entity.ListEntry import com.github.moko256.twitlatte.database.CachedListEntriesSQLiteOpenHelper import com.github.moko256.twitlatte.entity.Client import com.github.moko256.twitlatte.widget.MaterialListTopMarginDecoration import io.reactivex.Single import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers /** * Created by moko256 on 2019/01/02. * * @author moko256 */ abstract class AbstractListsEntriesFragment : BaseListFragment(), ToolbarTitleInterface { private var userId = -1L private lateinit var adapter: ListsEntriesAdapter private var list = ArrayList<ListEntry>(20) private lateinit var disposable: CompositeDisposable private lateinit var client: Client private lateinit var helper: CachedListEntriesSQLiteOpenHelper override val titleResourceId = R.string.lists override fun onCreate(savedInstanceState: Bundle?) { if (userId == -1L) { userId = arguments!!.getLong("listId", -1L) } super.onCreate(savedInstanceState) disposable = CompositeDisposable() client = requireActivity().getClient()!! helper = CachedListEntriesSQLiteOpenHelper( requireContext().applicationContext, client.accessToken, userId ) val listEntries = helper.getListEntries() if (listEntries.isNotEmpty()) { list.addAll(listEntries) isRefreshing = false } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) recyclerView.addItemDecoration(MaterialListTopMarginDecoration(resources)) adapter = ListsEntriesAdapter(requireContext(), list) disposable.add( adapter.onClickObservable.subscribe { onClickList(it) } ) recyclerView.adapter = adapter if (!isInitializedList) { adapter.notifyDataSetChanged() } } override fun onDestroyView() { recyclerView.swapAdapter(null, true) super.onDestroyView() } override fun onDestroy() { disposable.dispose() helper.close() super.onDestroy() } override fun onInitializeList() { isRefreshing = true disposable.add( getResponseSingle() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { result -> list.clear() list.addAll(result) adapter.notifyDataSetChanged() isRefreshing = false }, { e -> e.printStackTrace() notifyErrorBySnackBar(e).show() isRefreshing = false } ) ) } private fun getResponseSingle(): Single<List<ListEntry>> { return Single.create { subscriber -> try { val listEntries = client.apiClient.getLists(userId) helper.setListEntries(listEntries) subscriber.onSuccess(listEntries) } catch (e: Throwable) { subscriber.tryOnError(e) } } } override fun onUpdateList() { onInitializeList() } override fun onLoadMoreList() {} override fun isInitializedList(): Boolean { return list.isNotEmpty() } abstract fun onClickList(listEntry: ListEntry) }
apache-2.0
e627696a20fea7f93c4726d9b2f683f7
30.383562
89
0.604235
5.4994
false
false
false
false
leafclick/intellij-community
platform/platform-impl/src/com/intellij/ui/colorpicker/ColorPickerModel.kt
1
2367
/* * Copyright (C) 2018 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.intellij.ui.colorpicker import com.intellij.openapi.application.ApplicationManager import com.intellij.ui.picker.ColorListener import java.awt.Color val DEFAULT_PICKER_COLOR = Color(0xFF, 0xFF, 0xFF, 0xFF) class ColorPickerModel(originalColor: Color = DEFAULT_PICKER_COLOR) { private val listeners = mutableSetOf<ColorListener>() private val instantListeners = mutableSetOf<ColorListener>() var color: Color = originalColor private set fun setColor(newColor: Color, source: Any? = null) { color = newColor Color.RGBtoHSB(color.red, color.green, color.blue, hsb) instantListeners.forEach { it.colorChanged(color, source) } } fun onClose() { ApplicationManager.getApplication().invokeLater { listeners.forEach { it.colorChanged(color, this) } } } fun onCancel() { } fun applyColorToSource(newColor: Color, source: Any? = null) { setColor(newColor, source) listeners.forEach { it.colorChanged(color, source) } } private val hsb: FloatArray = Color.RGBtoHSB(color.red, color.green, color.blue, null) val red get() = color.red val green get() = color.green val blue get() = color.blue val alpha get() = color.alpha val hex: String get() = Integer.toHexString(color.rgb) val hue get() = hsb[0] val saturation get() = hsb[1] val brightness get() = hsb[2] fun addListener(listener: ColorListener) = addListener(listener, true) fun addListener(listener: ColorListener, invokeOnEveryColorChange: Boolean) { listeners.add(listener) if (invokeOnEveryColorChange) { instantListeners.add(listener) } } fun removeListener(listener: ColorListener) { listeners.remove(listener) instantListeners.remove(listener) } }
apache-2.0
b93f7f963bfa4d9e28d12a0a53c97756
27.178571
88
0.721589
4.02551
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/features/Findable.kt
1
2398
package slatekit.data.features import slatekit.query.Op import slatekit.query.Select /** * Supports finding records by conditions */ interface Findable<TId, T> : Inspectable<TId, T> where TId : Comparable<TId>, T : Any { /** * finds items based on the field * @param field: name of field * @param value: value of field to search against * @return */ fun findByField(field: String, value: Any?): List<T> = findByField(field, Op.Eq, value) /** * finds items based on the field * @param field: name of field * @param op : operator e.g. "=" * @param value: value of field to search against * @return */ fun findByField(field: String, op: Op, value: Any?): List<T> = findByQuery(select().where(field, op, value)) /** * finds first item based on the field * @param field: name of field * @param op : operator e.g. "=" * @param value: value of field to search against * @return */ fun findOneByField(field: String, value: Any): T? = findOneByField(field, Op.Eq, value) /** * finds first item based on the field * @param field: name of field * @param op : operator e.g. "=" * @param value: value of field to search against * @return */ fun findOneByField(field: String, op: Op, value: Any): T? = findByQuery(select().where(field, op, value).limit(1)).firstOrNull() /** * finds items based on the field in the values provided * @param field: name of field * @param value: values of field to search against * @return */ fun findIn(field: String, value: List<Any>): List<T> = findByQuery(select().where(field, Op.In, value)) /** * finds one item using a query builder * select { where("level", Op.Eq, 3).and("active", Op.Eq, true) } */ fun findOne(builder: Select.() -> Unit): T? { return this.find(builder).firstOrNull() } /** * finds items using a query builder * select { where("level", Op.Eq, 3).and("active", Op.Eq, true) } */ fun find(builder: Select.() -> Unit): List<T> { val q = select() builder(q) return findByQuery(q) } /** * finds items based on the conditions * @param query: The list of filters "id = 2" e.g. listOf( Filter("id", Op.Eq, "2" ) */ fun findByQuery(builder: Select): List<T> }
apache-2.0
1912ae8ddafca179632a90e3ed9e23bf
28.975
132
0.597164
3.694915
false
false
false
false
TonicArtos/SuperSLiM
library/src/main/kotlin/com/tonicartos/superslim/graph.kt
1
7594
package com.tonicartos.superslim import com.tonicartos.superslim.adapter.FooterStyle import com.tonicartos.superslim.adapter.HeaderStyle import com.tonicartos.superslim.internal.SectionState inline fun <T : Child, R> T.use(block: (T) -> R): R { var done = false try { return block(this) } catch (e: Exception) { done = true this.done() throw e } finally { if (!done) { this.done() } } } // TODO: Make TrimChild version which wraps a section or attached view. interface Child { companion object { const val INVALID = 0 const val ANIM_NONE = 0 const val ANIM_APPEARING = 1 const val ANIM_DISAPPEARING = 2 } fun done() val numViews get() = 1 /** * True if the child is being removed in this layout. */ val isRemoved: Boolean val measuredWidth: Int val measuredHeight: Int /** * Measure child. This should be done after [addToRecyclerView] as some views like ViewPager expect to be attached * before measurement. */ fun measure(usedWidth: Int = 0, usedHeight: Int = 0) val left: Int val top: Int val right: Int val bottom: Int /** * Layout the child. A backing view will have the dimensions specified. A subsection will have bounds defined by * left, top, and right, however will ignore bottom and may fill any remaining space to the bottom of the viewable * area. */ fun layout(left: Int, top: Int, right: Int, bottom: Int, numViewsBefore: Int = 0) /** * Fill distance dy at top of the child. The child will attempt to extend into this space; only if it is a section. * * @param dy Distance to fill. Value will be -ve. * @param left Left edge of area to fill. * @param top Top edge of area to fill. * @param right Right edge of area to fill. * @param bottom Bottom edge of area to fill. * * @return How much of dy filled. */ fun fillTop(dy: Int, left: Int, top: Int, right: Int, bottom: Int, numViewsBefore: Int = 0): Int fun trimTop(scrolled: Int, top: Int, helper: LayoutHelper, numViewsBefore: Int = 0): Int /** * Fill distance dy at bottom of the child. The child will attempt to extend into this space; only if it is a section. * * @param dy Distance to fill. Value will be +ve. * @param left Left edge of area to fill. * @param top Top edge of area to fill. * @param right Right edge of area to fill. * @param bottom Bottom edge of area to fill. * * @return How much of dy filled. */ fun fillBottom(dy: Int, left: Int, top: Int, right: Int, bottom: Int, numViewsBefore: Int = 0): Int fun trimBottom(scrolled: Int, top: Int, helper: LayoutHelper, numViewsBefore: Int = 0): Int val width: Int val height: Int val disappearedHeight: Int /** * Adds child to the recycler view. */ fun addToRecyclerView() = addToRecyclerView(-1) /** * Adds child to the recycler view. */ fun addToRecyclerView(i: Int) } /** * Configuration of a section. */ abstract class SectionConfig(gutterStart: Int = SectionConfig.DEFAULT_GUTTER, gutterEnd: Int = SectionConfig.DEFAULT_GUTTER, @HeaderStyle @JvmField var headerStyle: Int = SectionConfig.DEFAULT_HEADER_STYLE, @FooterStyle @JvmField var footerStyle: Int = SectionConfig.DEFAULT_FOOTER_STYLE, paddingStart: Int = 0, paddingTop: Int = 0, paddingEnd: Int = 0, paddingBottom: Int = 0) { var gutterStart = 0 get() = field set(value) { field = if (value < 0) GUTTER_AUTO else value } var gutterEnd = 0 get() = field set(value) { field = if (value < 0) GUTTER_AUTO else value } var paddingLeft = 0 var paddingTop = 0 var paddingRight = 0 var paddingBottom = 0 init { this.gutterStart = gutterStart this.gutterEnd = gutterEnd this.paddingLeft = paddingStart this.paddingTop = paddingTop this.paddingRight = paddingEnd this.paddingBottom = paddingBottom } // Remap names since internally left and right are used since section coordinates are LTR, TTB. The start and // end intention will be applied correctly (from left and right) through the config transformations. internal var gutterLeft: Int get() = gutterStart set(value) { gutterStart = value } internal var gutterRight: Int get() = gutterEnd set(value) { gutterEnd = value } internal fun makeSection(oldState: SectionState? = null) = onMakeSection(oldState) abstract protected fun onMakeSection(oldState: SectionState?): SectionState /** * Copy the configuration. Section configs are always copied when they are passed to the layout manager. */ fun copy(): SectionConfig { return onCopy() } abstract protected fun onCopy(): SectionConfig companion object { /** * Header is positioned at the head of the section content. Content starts below the header. Sticky headers * stick to the top of the layout area until the entire area has scrolled off the screen. Use HEADER_INLINE for * a header style which is otherwise the same without the sticky property. */ const val HEADER_STICKY = 1 /** * Header is positioned at the head of the section content. Content starts below the header, but the header * never becomes sticky. Linear headers can not float and ignores that flag if set. */ const val HEADER_INLINE = 1 shl 1 /** * Header is placed inside the gutter at the start edge of the section. This is the left for LTR locales. * Gutter headers are always sticky. */ const val HEADER_START = 1 shl 2 /** * Header is placed inside the gutter at the end edge of the section. This is the right for LTR locales. * Gutter headers are always sticky. */ const val HEADER_END = 1 shl 3 /** * Footer is positioned at the head of the section content. Content starts below the footer. Sticky footers * stick to the top of the layout area until the entire area has scrolled off the screen. Use FOOTER_INLINE for * a footer style which is otherwise the same without the sticky property. */ const val FOOTER_STICKY = 1 /** * Footer is positioned at the head of the section content. Content starts below the footer, but the footer * never becomes sticky. Linear footers can not float and ignores that flag if set. */ const val FOOTER_INLINE = 1 shl 1 /** * Footer is placed inside the gutter at the start edge of the section. This is the left for LTR locales. * Gutter footers are always sticky. */ const val FOOTER_START = 1 shl 2 /** * Footer is placed inside the gutter at the end edge of the section. This is the right for LTR locales. * Gutter footers are always sticky. */ const val FOOTER_END = 1 shl 3 const val GUTTER_AUTO = -1 internal const val DEFAULT_GUTTER = GUTTER_AUTO internal const val DEFAULT_HEADER_STYLE = HEADER_STICKY internal const val DEFAULT_FOOTER_STYLE = FOOTER_STICKY } }
apache-2.0
8270279b8c69a1c828b22137891d45e4
33.361991
122
0.625362
4.493491
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/NavigationDrawerFragment.kt
1
22373
package com.habitrpg.android.habitica.ui.fragments import android.content.Intent import android.content.res.ColorStateList import android.graphics.drawable.GradientDrawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.content.ContextCompat import androidx.core.os.bundleOf import androidx.core.view.GravityCompat import androidx.fragment.app.DialogFragment import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.InventoryRepository import com.habitrpg.android.habitica.data.SocialRepository import com.habitrpg.android.habitica.data.UserRepository import com.habitrpg.android.habitica.extensions.getRemainingString import com.habitrpg.android.habitica.extensions.getThemeColor import com.habitrpg.android.habitica.extensions.subscribeWithErrorHandler import com.habitrpg.android.habitica.helpers.AppConfigManager import com.habitrpg.android.habitica.helpers.MainNavigationController import com.habitrpg.android.habitica.helpers.RxErrorHandler import com.habitrpg.android.habitica.models.inventory.Quest import com.habitrpg.android.habitica.models.inventory.QuestContent import com.habitrpg.android.habitica.models.social.Group import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.activities.MainActivity.Companion.NOTIFICATION_CLICK import com.habitrpg.android.habitica.ui.activities.NotificationsActivity import com.habitrpg.android.habitica.ui.adapter.NavigationDrawerAdapter import com.habitrpg.android.habitica.ui.fragments.social.TavernDetailFragment import com.habitrpg.android.habitica.ui.menu.HabiticaDrawerItem import com.habitrpg.android.habitica.ui.viewmodels.NotificationsViewModel import com.habitrpg.android.habitica.ui.views.HabiticaSnackbar import io.reactivex.disposables.CompositeDisposable import io.reactivex.functions.Consumer import kotlinx.android.synthetic.main.drawer_main.* import java.util.* import java.util.concurrent.TimeUnit import javax.inject.Inject import kotlin.collections.ArrayList /** * Fragment used for managing interactions for and presentation of a navigation drawer. * See the [ * design guidelines](https://developer.android.com/design/patterns/navigation-drawer.html#Interaction) for a complete explanation of the behaviors implemented here. */ class NavigationDrawerFragment : DialogFragment() { @Inject lateinit var socialRepository: SocialRepository @Inject lateinit var inventoryRepository: InventoryRepository @Inject lateinit var userRepository: UserRepository @Inject lateinit var configManager: AppConfigManager private var drawerLayout: androidx.drawerlayout.widget.DrawerLayout? = null private var fragmentContainerView: View? = null private var mCurrentSelectedPosition = 0 private var mFromSavedInstanceState: Boolean = false private lateinit var adapter: NavigationDrawerAdapter private var subscriptions: CompositeDisposable? = null val isDrawerOpen: Boolean get() = drawerLayout?.isDrawerOpen(GravityCompat.START) ?: false private var questContent: QuestContent? = null set(value) { field = value updateQuestDisplay() } private var quest: Quest? = null set(value) { field = value updateQuestDisplay() } private fun updateQuestDisplay() { val quest = this.quest val questContent = this.questContent if (quest == null || questContent == null || !quest.active) { questMenuView.visibility = View.GONE context?.let { adapter.tintColor = it.getThemeColor(R.attr.colorPrimary) adapter.backgroundTintColor = it.getThemeColor(R.attr.colorPrimary) } adapter.items.filter { it.identifier == SIDEBAR_TAVERN }.forEach { it.subtitle = null } return } questMenuView.visibility = View.VISIBLE menuHeaderView.setBackgroundColor(questContent.colors?.darkColor ?: 0) questMenuView.configure(quest) questMenuView.configure(questContent) adapter.tintColor = questContent.colors?.extraLightColor ?: 0 adapter.backgroundTintColor = questContent.colors?.darkColor ?: 0 messagesBadge.visibility = View.GONE settingsBadge.visibility = View.GONE notificationsBadge.visibility = View.GONE /* Reenable this once the boss art can be displayed correctly. val preferences = context?.getSharedPreferences("collapsible_sections", 0) if (preferences?.getBoolean("boss_art_collapsed", false) == true) { questMenuView.hideBossArt() } else { questMenuView.showBossArt() }*/ questMenuView.hideBossArt() adapter.items.filter { it.identifier == SIDEBAR_TAVERN }.forEach { it.subtitle = context?.getString(R.string.active_world_boss) } adapter.notifyDataSetChanged() questMenuView.setOnClickListener { val context = this.context if (context != null) { TavernDetailFragment.showWorldBossInfoDialog(context, questContent) } } } override fun onCreate(savedInstanceState: Bundle?) { val context = context adapter = if (context != null) { NavigationDrawerAdapter(context.getThemeColor(R.attr.colorPrimary), context.getThemeColor(R.attr.colorPrimaryOffset)) } else { NavigationDrawerAdapter(0, 0) } subscriptions = CompositeDisposable() HabiticaBaseApplication.userComponent?.inject(this) super.onCreate(savedInstanceState) if (savedInstanceState != null) { mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION) mFromSavedInstanceState = true } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) // Indicate that this fragment would like to influence the set of actions in the action bar. setHasOptionsMenu(true) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.drawer_main, container, false) as? ViewGroup override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) recyclerView.adapter = adapter recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) initializeMenuItems() subscriptions?.add(adapter.getItemSelectionEvents().subscribe(Consumer { setSelection(it.transitionId, it.bundle, true) }, RxErrorHandler.handleEmptyError())) subscriptions?.add(socialRepository.getGroup(Group.TAVERN_ID) .doOnNext { quest = it.quest } .filter { it.hasActiveQuest } .flatMapMaybe { inventoryRepository.getQuestContent(it.quest?.key ?: "").firstElement() } .subscribe(Consumer { questContent = it }, RxErrorHandler.handleEmptyError())) subscriptions?.add(userRepository.getUser().subscribe(Consumer { updateUser(it) }, RxErrorHandler.handleEmptyError())) messagesButtonWrapper.setOnClickListener { setSelection(R.id.inboxFragment) } settingsButtonWrapper.setOnClickListener { setSelection(R.id.prefsActivity) } notificationsButtonWrapper.setOnClickListener { startNotificationsActivity() } } private fun updateUser(user: User) { setMessagesCount(user.inbox?.newMessages ?: 0) setSettingsCount(if (user.flags?.isVerifiedUsername != true) 1 else 0 ) setDisplayName(user.profile?.name) setUsername(user.formattedUsername) avatarView.setAvatar(user) questMenuView.configure(user) val tavernItem = getItemWithIdentifier(SIDEBAR_TAVERN) if (user.preferences?.sleep == true) { tavernItem?.subtitle = context?.getString(R.string.damage_paused) } else { tavernItem?.subtitle = null } val specialItems = user.items?.special var hasSpecialItems = false if (specialItems != null) { hasSpecialItems = specialItems.hasSpecialItems() } val item = getItemWithIdentifier(SIDEBAR_SKILLS) if (item != null) { if (!user.hasClass() && !hasSpecialItems) { item.isVisible = false } else { if (user.stats?.lvl ?: 0 < HabiticaSnackbar.MIN_LEVEL_FOR_SKILLS && (!hasSpecialItems)) { item.pillText = getString(R.string.unlock_lvl_11) } else { item.pillText = null } item.isVisible = true } updateItem(item) } val statsItem = getItemWithIdentifier(SIDEBAR_STATS) if (statsItem != null) { if (user.preferences?.disableClasses != true) { if (user.stats?.lvl ?: 0 >= 10 && user.stats?.points ?: 0 > 0) { statsItem.pillText = user.stats?.points.toString() } else { statsItem.pillText = null } statsItem.isVisible = true } else { statsItem.isVisible = false } updateItem(statsItem) } val subscriptionItem = getItemWithIdentifier(SIDEBAR_SUBSCRIPTION) if (user.isSubscribed && user.purchased?.plan?.dateTerminated != null) { val terminatedCalendar = Calendar.getInstance() terminatedCalendar.time = user.purchased?.plan?.dateTerminated ?: Date() val msDiff = terminatedCalendar.timeInMillis - Calendar.getInstance().timeInMillis val daysDiff = TimeUnit.MILLISECONDS.toDays(msDiff) if (daysDiff <= 30) { context?.let { subscriptionItem?.subtitle = user.purchased?.plan?.dateTerminated?.getRemainingString(it.resources) subscriptionItem?.subtitleTextColor = when { daysDiff <= 2 -> ContextCompat.getColor(it, R.color.red_100) daysDiff <= 7 -> ContextCompat.getColor(it, R.color.brand_400) else -> it.getThemeColor(R.attr.textColorSecondary) } } } } else if (user.isSubscribed) { subscriptionItem?.subtitle = null } else { subscriptionItem?.subtitle = context?.getString(R.string.more_out_of_habitica) } if (configManager.enableGiftOneGetOne()) { subscriptionItem?.pillText = context?.getString(R.string.sale) context?.let { subscriptionItem?.pillBackground = ContextCompat.getDrawable(it, R.drawable.pill_bg_teal) } } subscriptionItem?.let { updateItem(it) } val promoItem = getItemWithIdentifier(SIDEBAR_SUBSCRIPTION_PROMO) if (promoItem != null) { promoItem.isVisible = !user.isSubscribed updateItem(promoItem) } getItemWithIdentifier(SIDEBAR_NEWS)?.let { it.showBubble = user.flags?.newStuff ?: false } val partyMenuItem = getItemWithIdentifier(SIDEBAR_PARTY) if (user.hasParty() && partyMenuItem?.bundle == null) { partyMenuItem?.transitionId = R.id.partyFragment partyMenuItem?.bundle = bundleOf(Pair("partyID", user.party?.id)) } else if (!user.hasParty()) { partyMenuItem?.transitionId = R.id.noPartyFragment partyMenuItem?.bundle = null } } override fun onDestroy() { subscriptions?.dispose() socialRepository.close() inventoryRepository.close() userRepository.close() super.onDestroy() } private fun initializeMenuItems() { val items = ArrayList<HabiticaDrawerItem>() context?.let {context -> items.add(HabiticaDrawerItem(R.id.tasksFragment, SIDEBAR_TASKS, context.getString(R.string.sidebar_tasks))) items.add(HabiticaDrawerItem(R.id.skillsFragment, SIDEBAR_SKILLS, context.getString(R.string.sidebar_skills))) items.add(HabiticaDrawerItem(R.id.statsFragment, SIDEBAR_STATS, context.getString(R.string.sidebar_stats))) items.add(HabiticaDrawerItem(R.id.achievementsFragment, SIDEBAR_ACHIEVEMENTS, context.getString(R.string.sidebar_achievements))) items.add(HabiticaDrawerItem(0, SIDEBAR_SOCIAL, context.getString(R.string.sidebar_section_social), true)) items.add(HabiticaDrawerItem(R.id.tavernFragment, SIDEBAR_TAVERN, context.getString(R.string.sidebar_tavern), isHeader = false)) items.add(HabiticaDrawerItem(R.id.partyFragment, SIDEBAR_PARTY, context.getString(R.string.sidebar_party))) items.add(HabiticaDrawerItem(R.id.guildsOverviewFragment, SIDEBAR_GUILDS, context.getString(R.string.sidebar_guilds))) items.add(HabiticaDrawerItem(R.id.challengesOverviewFragment, SIDEBAR_CHALLENGES, context.getString(R.string.sidebar_challenges))) if (configManager.raiseShops()) { items.add(HabiticaDrawerItem(0, SIDEBAR_INVENTORY, context.getString(R.string.sidebar_shops), true)) items.add(HabiticaDrawerItem(R.id.marketFragment, SIDEBAR_SHOPS_MARKET, context.getString(R.string.market))) items.add(HabiticaDrawerItem(R.id.questShopFragment, SIDEBAR_SHOPS_QUEST, context.getString(R.string.questShop))) items.add(HabiticaDrawerItem(R.id.seasonalShopFragment, SIDEBAR_SHOPS_SEASONAL, context.getString(R.string.seasonalShop))) items.add(HabiticaDrawerItem(R.id.timeTravelersShopFragment, SIDEBAR_SHOPS_TIMETRAVEL, context.getString(R.string.timeTravelers))) } items.add(HabiticaDrawerItem(0, SIDEBAR_INVENTORY, context.getString(R.string.sidebar_section_inventory), true)) if (!configManager.raiseShops()) { items.add(HabiticaDrawerItem(R.id.shopsFragment, SIDEBAR_SHOPS, context.getString(R.string.sidebar_shops))) } items.add(HabiticaDrawerItem(R.id.avatarOverviewFragment, SIDEBAR_AVATAR, context.getString(R.string.sidebar_avatar))) items.add(HabiticaDrawerItem(R.id.equipmentOverviewFragment, SIDEBAR_EQUIPMENT, context.getString(R.string.sidebar_equipment))) items.add(HabiticaDrawerItem(R.id.itemsFragment, SIDEBAR_ITEMS, context.getString(R.string.sidebar_items))) items.add(HabiticaDrawerItem(R.id.stableFragment, SIDEBAR_STABLE, context.getString(R.string.sidebar_stable))) items.add(HabiticaDrawerItem(R.id.gemPurchaseActivity, SIDEBAR_GEMS, context.getString(R.string.sidebar_gems))) items.add(HabiticaDrawerItem(R.id.subscriptionPurchaseActivity, SIDEBAR_SUBSCRIPTION, context.getString(R.string.sidebar_subscription), isHeader = false)) items.add(HabiticaDrawerItem(0, SIDEBAR_ABOUT_HEADER, context.getString(R.string.sidebar_about), true)) items.add(HabiticaDrawerItem(R.id.newsFragment, SIDEBAR_NEWS, context.getString(R.string.sidebar_news))) items.add(HabiticaDrawerItem(R.id.supportMainFragment, SIDEBAR_HELP, context.getString(R.string.sidebar_help))) items.add(HabiticaDrawerItem(R.id.aboutFragment, SIDEBAR_ABOUT, context.getString(R.string.sidebar_about))) } if (configManager.enableGiftOneGetOne()) { val item = HabiticaDrawerItem(R.id.subscriptionPurchaseActivity, SIDEBAR_G1G1_PROMO) item.itemViewType = 3 items.add(item) } else if (configManager.showSubscriptionBanner()) { val item = HabiticaDrawerItem(R.id.subscriptionPurchaseActivity, SIDEBAR_SUBSCRIPTION_PROMO) item.itemViewType = 2 items.add(item) } adapter.updateItems(items) } fun setSelection(transitionId: Int?, bundle: Bundle? = null, openSelection: Boolean = true) { adapter.selectedItem = transitionId closeDrawer() if (!openSelection) { return } if (transitionId != null) { if (bundle != null) { MainNavigationController.navigate(transitionId, bundle) } else { MainNavigationController.navigate(transitionId) } } } private fun startNotificationsActivity() { closeDrawer() val activity = activity as? MainActivity if (activity != null) { // NotificationsActivity will return a result intent with a notificationId if a // notification item was clicked val intent = Intent(activity, NotificationsActivity::class.java) activity.startActivityForResult(intent, NOTIFICATION_CLICK) } } /** * Users of this fragment must call this method to set UP the navigation drawer interactions. * * @param fragmentId The android:id of this fragment in its activity's layout. * @param drawerLayout The DrawerLayout containing this fragment's UI. */ fun setUp(fragmentId: Int, drawerLayout: androidx.drawerlayout.widget.DrawerLayout, viewModel: NotificationsViewModel) { fragmentContainerView = activity?.findViewById(fragmentId) this.drawerLayout = drawerLayout // set a custom shadow that overlays the main content when the drawer opens this.drawerLayout?.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START) // set UP the drawer's list view with items and click listener subscriptions?.add(viewModel.getNotificationCount().subscribeWithErrorHandler(Consumer { setNotificationsCount(it) })) subscriptions?.add(viewModel.allNotificationsSeen().subscribeWithErrorHandler(Consumer { setNotificationsSeen(it) })) subscriptions?.add(viewModel.getHasPartyNotification().subscribeWithErrorHandler(Consumer { val partyMenuItem = getItemWithIdentifier(SIDEBAR_PARTY) partyMenuItem?.showBubble = it })) } fun openDrawer() { val containerView = fragmentContainerView if (containerView != null) { drawerLayout?.openDrawer(containerView) } } fun closeDrawer() { val containerView = fragmentContainerView if (containerView != null) { drawerLayout?.closeDrawer(containerView) } } private fun getItemWithIdentifier(identifier: String): HabiticaDrawerItem? = adapter.getItemWithIdentifier(identifier) private fun updateItem(item: HabiticaDrawerItem) { adapter.updateItem(item) } private fun setDisplayName(name: String?) { if (toolbarTitle != null) { if (name != null && name.isNotEmpty()) { toolbarTitle.text = name } else { toolbarTitle.text = context?.getString(R.string.app_name) } } } private fun setUsername(name: String?) { usernameTextView.text = name } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition) } private fun setNotificationsCount(unreadNotifications: Int) { if (unreadNotifications == 0) { notificationsBadge.visibility = View.GONE } else { notificationsBadge.visibility = View.VISIBLE notificationsBadge.text = unreadNotifications.toString() } } private fun setNotificationsSeen(allSeen: Boolean) { context?.let { val color = if (allSeen) { ContextCompat.getColor(it, R.color.gray_200) } else { it.getThemeColor(R.attr.colorAccent) } val bg = notificationsBadge.background as? GradientDrawable bg?.color = ColorStateList.valueOf(color) } } private fun setMessagesCount(unreadMessages: Int) { if (unreadMessages == 0) { messagesBadge.visibility = View.GONE } else { messagesBadge.visibility = View.VISIBLE messagesBadge.text = unreadMessages.toString() } } private fun setSettingsCount(count: Int) { if (count == 0) { settingsBadge.visibility = View.GONE } else { settingsBadge.visibility = View.VISIBLE settingsBadge.text = count.toString() } } companion object { const val SIDEBAR_TASKS = "tasks" const val SIDEBAR_SKILLS = "skills" const val SIDEBAR_STATS = "stats" const val SIDEBAR_ACHIEVEMENTS = "achievements" const val SIDEBAR_SOCIAL = "social" const val SIDEBAR_TAVERN = "tavern" const val SIDEBAR_PARTY = "party" const val SIDEBAR_GUILDS = "guilds" const val SIDEBAR_CHALLENGES = "challenges" const val SIDEBAR_INVENTORY = "inventory" const val SIDEBAR_SHOPS = "shops" const val SIDEBAR_SHOPS_MARKET = "market" const val SIDEBAR_SHOPS_QUEST = "questShop" const val SIDEBAR_SHOPS_SEASONAL = "seasonalShop" const val SIDEBAR_SHOPS_TIMETRAVEL = "timeTravelersShop" const val SIDEBAR_AVATAR = "avatar" const val SIDEBAR_EQUIPMENT = "equipment" const val SIDEBAR_ITEMS = "items" const val SIDEBAR_STABLE = "stable" const val SIDEBAR_GEMS = "gems" const val SIDEBAR_SUBSCRIPTION = "subscription" const val SIDEBAR_SUBSCRIPTION_PROMO = "subscriptionpromo" const val SIDEBAR_G1G1_PROMO = "g1g1promo" const val SIDEBAR_ABOUT_HEADER = "about_header" const val SIDEBAR_NEWS = "news" const val SIDEBAR_HELP = "help" const val SIDEBAR_ABOUT = "about" private const val STATE_SELECTED_POSITION = "selected_navigation_drawer_position" } }
gpl-3.0
87a91bb95f01cac3a810e0eafd016db9
43.041339
166
0.668663
4.717057
false
false
false
false
kivensolo/UiUsingListView
module-Common/src/main/java/com/kingz/module/common/utils/encode/EncodeUtils.kt
1
2406
package com.kingz.module.common.utils.encode import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.util.* /** * author:ZekeWang * date:2021/8/16 * description:加解密工具类 */ object EncodeUtils { private val DIGITS_LOWER = charArrayOf( '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' ) private val threadHashMap: WeakHashMap<Thread, MessageDigestCtx> = WeakHashMap<Thread, MessageDigestCtx>() /** * 对字节数组进行md5加密 * @return md5的字符串 */ fun calMD5(data: ByteArray?): String{ val md5: MessageDigestCtx? = getMD5() return String(md5?.digest(data)?: CharArray(0)) } private fun getMD5(): MessageDigestCtx? { synchronized(threadHashMap) { val thread = Thread.currentThread() val messageDigest = threadHashMap[thread] ?: return try { val md5 = MessageDigest.getInstance("md5") val digestCtx = MessageDigestCtx(md5) threadHashMap[thread] = digestCtx digestCtx } catch (e: NoSuchAlgorithmException) { e.printStackTrace() null } messageDigest.reset() return messageDigest } } /** * 使用MessageDigest进行加密 * * 使用方式: * //MD5 * MessageDigest md5 = MessageDigest.getInstance("md5"); * MessageDigestCtx digestCtx = new MessageDigestCtx(md5); * * //SHA-1 * MessageDigest md_sha = MessageDigest.getInstance("SHA-1"); * MessageDigestCtx digestCtx = new MessageDigestCtx(md_sha); * */ private class MessageDigestCtx(private var digest: MessageDigest) { private var digestStr = CharArray(32) fun reset() { digest.reset() } /** * 加密算法, 把密文转成16进制的字符数组形式 */ fun digest(data: ByteArray?): CharArray { val digestVal = digest.digest(data) for (i in 0..15) { val b: Int = digestVal[i].toInt() and 0xFF digestStr[i * 2] = DIGITS_LOWER[b / 16] digestStr[i * 2 + 1] = DIGITS_LOWER[b % 16] } return digestStr } } }
gpl-2.0
37a0abdc15f59229336dd13471a49cac
27.8125
110
0.546007
4.129032
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/KotlinChangeSignatureHandler.kt
3
11485
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.changeSignature import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.project.Project import com.intellij.psi.PsiClass import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiMethod import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.parentOfType import com.intellij.refactoring.HelpID import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.changeSignature.ChangeSignatureHandler import com.intellij.refactoring.changeSignature.ChangeSignatureUtil import com.intellij.refactoring.util.CommonRefactoringUtil import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor.Kind.SYNTHESIZED import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeInsight.DescriptorToSourceUtilsIde import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.intentions.isInvokeOperator import org.jetbrains.kotlin.idea.util.expectedDescriptor import org.jetbrains.kotlin.load.java.descriptors.JavaCallableMemberDescriptor import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.calls.tasks.isDynamic import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments class KotlinChangeSignatureHandler : ChangeSignatureHandler { override fun findTargetMember(element: PsiElement) = findTargetForRefactoring(element) override fun invoke(project: Project, editor: Editor, file: PsiFile, dataContext: DataContext) { editor.scrollingModel.scrollToCaret(ScrollType.MAKE_VISIBLE) val element = findTargetMember(file, editor) ?: CommonDataKeys.PSI_ELEMENT.getData(dataContext) ?: return val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return if (element !is KtElement) throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}") .withAttachment("element", element) invokeChangeSignature(element, elementAtCaret, project, editor) } override fun invoke(project: Project, elements: Array<PsiElement>, dataContext: DataContext?) { val element = elements.singleOrNull()?.unwrapped ?: return if (element !is KtElement) { throw KotlinExceptionWithAttachments("This handler must be invoked for Kotlin elements only: ${element::class.java}") .withAttachment("element", element) } val editor = dataContext?.let { CommonDataKeys.EDITOR.getData(it) } invokeChangeSignature(element, element, project, editor) } override fun getTargetNotFoundMessage() = KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name") companion object { fun findTargetForRefactoring(element: PsiElement): PsiElement? { val elementParent = element.parent if ((elementParent is KtNamedFunction || elementParent is KtClass || elementParent is KtProperty) && (elementParent as KtNamedDeclaration).nameIdentifier === element ) return elementParent if (elementParent is KtParameter && elementParent.hasValOrVar() && elementParent.parentOfType<KtPrimaryConstructor>()?.valueParameterList === elementParent.parent ) return elementParent if (elementParent is KtProperty && elementParent.valOrVarKeyword === element) return elementParent if (elementParent is KtConstructor<*> && elementParent.getConstructorKeyword() === element) return elementParent element.parentOfType<KtParameterList>()?.let { parameterList -> return PsiTreeUtil.getParentOfType(parameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java) } element.parentOfType<KtTypeParameterList>()?.let { typeParameterList -> return PsiTreeUtil.getParentOfType(typeParameterList, KtFunction::class.java, KtProperty::class.java, KtClass::class.java) } val call: KtCallElement? = PsiTreeUtil.getParentOfType( element, KtCallExpression::class.java, KtSuperTypeCallEntry::class.java, KtConstructorDelegationCall::class.java ) val calleeExpr = call?.let { val callee = it.calleeExpression (callee as? KtConstructorCalleeExpression)?.constructorReferenceExpression ?: callee } ?: element.parentOfType<KtSimpleNameExpression>() if (calleeExpr is KtSimpleNameExpression || calleeExpr is KtConstructorDelegationReferenceExpression) { val bindingContext = element.parentOfType<KtElement>()?.analyze(BodyResolveMode.FULL) ?: return null if (call?.getResolvedCall(bindingContext)?.resultingDescriptor?.isInvokeOperator == true) return call val descriptor = bindingContext[BindingContext.REFERENCE_TARGET, calleeExpr as KtReferenceExpression] if (descriptor is ClassDescriptor || descriptor is CallableDescriptor) return calleeExpr } return null } fun invokeChangeSignature(element: KtElement, context: PsiElement, project: Project, editor: Editor?) { val bindingContext = element.analyze(BodyResolveMode.FULL) val callableDescriptor = findDescriptor(element, project, editor, bindingContext) ?: return if (callableDescriptor is DeserializedDescriptor) { return CommonRefactoringUtil.showErrorHint( project, editor, KotlinBundle.message("error.hint.the.read.only.declaration.cannot.be.changed"), RefactoringBundle.message("changeSignature.refactoring.name"), "refactoring.changeSignature", ) } if (callableDescriptor is JavaCallableMemberDescriptor) { val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, callableDescriptor) if (declaration is PsiClass) { val message = RefactoringBundle.getCannotRefactorMessage( RefactoringBundle.message("error.wrong.caret.position.method.or.class.name") ) CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), "refactoring.changeSignature", ) return } assert(declaration is PsiMethod) { "PsiMethod expected: $callableDescriptor" } ChangeSignatureUtil.invokeChangeSignatureOn(declaration as PsiMethod, project) return } if (callableDescriptor.isDynamic()) { if (editor != null) { CodeInsightUtils.showErrorHint( project, editor, KotlinBundle.message("message.change.signature.is.not.applicable.to.dynamically.invoked.functions"), RefactoringBundle.message("changeSignature.refactoring.name"), null ) } return } runChangeSignature(project, editor, callableDescriptor, KotlinChangeSignatureConfiguration.Empty, context, null) } private fun getDescriptor(bindingContext: BindingContext, element: PsiElement): DeclarationDescriptor? { val descriptor = when { element is KtParameter && element.hasValOrVar() -> bindingContext[BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, element] element is KtReferenceExpression -> bindingContext[BindingContext.REFERENCE_TARGET, element] element is KtCallExpression -> element.getResolvedCall(bindingContext)?.resultingDescriptor else -> bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element] } return if (descriptor is ClassDescriptor) descriptor.unsubstitutedPrimaryConstructor else descriptor } fun findDescriptor(element: PsiElement, project: Project, editor: Editor?, bindingContext: BindingContext): CallableDescriptor? { if (!CommonRefactoringUtil.checkReadOnlyStatus(project, element)) return null var descriptor = getDescriptor(bindingContext, element) if (descriptor is MemberDescriptor && descriptor.isActual) { descriptor = descriptor.expectedDescriptor() ?: descriptor } return when (descriptor) { is PropertyDescriptor -> descriptor is FunctionDescriptor -> { if (descriptor.valueParameters.any { it.varargElementType != null }) { val message = KotlinBundle.message("error.cant.refactor.vararg.functions") CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), HelpID.CHANGE_SIGNATURE ) return null } if (descriptor.kind === SYNTHESIZED) { val message = KotlinBundle.message("cannot.refactor.synthesized.function", descriptor.name) CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), HelpID.CHANGE_SIGNATURE ) return null } descriptor } else -> { val message = RefactoringBundle.getCannotRefactorMessage( KotlinBundle.message("error.wrong.caret.position.function.or.constructor.name") ) CommonRefactoringUtil.showErrorHint( project, editor, message, RefactoringBundle.message("changeSignature.refactoring.name"), HelpID.CHANGE_SIGNATURE ) null } } } } }
apache-2.0
02d00c20d62bd3bb36ce8d509f2ab3df
48.934783
158
0.643361
6.22156
false
false
false
false
jwren/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pushDown/KotlinPushDownProcessor.kt
3
9156
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.refactoring.pushDown import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.refactoring.BaseRefactoringProcessor import com.intellij.refactoring.RefactoringBundle import com.intellij.refactoring.listeners.RefactoringEventData import com.intellij.usageView.UsageInfo import com.intellij.usageView.UsageViewBundle import com.intellij.usageView.UsageViewDescriptor import org.jetbrains.kotlin.asJava.unwrapped import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo import org.jetbrains.kotlin.idea.refactoring.memberInfo.KtPsiClassWrapper import org.jetbrains.kotlin.idea.refactoring.pullUp.* import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.idea.util.getTypeSubstitution import org.jetbrains.kotlin.idea.util.orEmpty import org.jetbrains.kotlin.idea.util.toSubstitutor import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.types.TypeSubstitutor import org.jetbrains.kotlin.utils.keysToMap class KotlinPushDownContext( val sourceClass: KtClass, val membersToMove: List<KotlinMemberInfo> ) { val resolutionFacade = sourceClass.getResolutionFacade() val sourceClassContext = resolutionFacade.analyzeWithAllCompilerChecks(sourceClass).bindingContext val sourceClassDescriptor = sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, sourceClass] as ClassDescriptor val memberDescriptors = membersToMove.map { it.member }.keysToMap { when (it) { is KtPsiClassWrapper -> it.psiClass.getJavaClassDescriptor(resolutionFacade)!! else -> sourceClassContext[BindingContext.DECLARATION_TO_DESCRIPTOR, it]!! } } } class KotlinPushDownProcessor( project: Project, sourceClass: KtClass, membersToMove: List<KotlinMemberInfo> ) : BaseRefactoringProcessor(project) { private val context = KotlinPushDownContext(sourceClass, membersToMove) inner class UsageViewDescriptorImpl : UsageViewDescriptor { override fun getProcessedElementsHeader() = RefactoringBundle.message("push.down.members.elements.header") override fun getElements() = arrayOf(context.sourceClass) override fun getCodeReferencesText(usagesCount: Int, filesCount: Int) = RefactoringBundle.message("classes.to.push.down.members.to", UsageViewBundle.getReferencesString(usagesCount, filesCount)) override fun getCommentReferencesText(usagesCount: Int, filesCount: Int) = null } class SubclassUsage(element: PsiElement) : UsageInfo(element) override fun getCommandName() = PUSH_MEMBERS_DOWN override fun createUsageViewDescriptor(usages: Array<out UsageInfo>) = UsageViewDescriptorImpl() override fun getBeforeData() = RefactoringEventData().apply { addElement(context.sourceClass) addElements(context.membersToMove.map { it.member }.toTypedArray()) } override fun getAfterData(usages: Array<out UsageInfo>) = RefactoringEventData().apply { addElements(usages.mapNotNull { it.element as? KtClassOrObject }) } override fun findUsages(): Array<out UsageInfo> { return HierarchySearchRequest(context.sourceClass, context.sourceClass.useScope, false).searchInheritors() .mapNotNull { it.unwrapped } .map(::SubclassUsage) .toTypedArray() } override fun preprocessUsages(refUsages: Ref<Array<UsageInfo>>): Boolean { val usages = refUsages.get() ?: UsageInfo.EMPTY_ARRAY if (usages.isEmpty()) { val message = KotlinBundle.message("text.0.have.no.inheritors.warning", context.sourceClassDescriptor.renderForConflicts()) val answer = Messages.showYesNoDialog(message.capitalize(), PUSH_MEMBERS_DOWN, Messages.getWarningIcon()) if (answer == Messages.NO) return false } val conflicts = myProject.runSynchronouslyWithProgress(RefactoringBundle.message("detecting.possible.conflicts"), true) { runReadAction { analyzePushDownConflicts(context, usages) } } ?: return false return showConflicts(conflicts, usages) } private fun pushDownToClass(targetClass: KtClassOrObject) { val sourceClassType = context.sourceClassDescriptor.defaultType val targetClassDescriptor = context.resolutionFacade.resolveToDescriptor(targetClass) as ClassDescriptor val substitutor = getTypeSubstitution(sourceClassType, targetClassDescriptor.defaultType)?.toSubstitutor().orEmpty() members@ for (memberInfo in context.membersToMove) { val member = memberInfo.member val memberDescriptor = context.memberDescriptors[member] ?: continue val movedMember = when (member) { is KtProperty, is KtNamedFunction -> { memberDescriptor as CallableMemberDescriptor moveCallableMemberToClass( member as KtCallableDeclaration, memberDescriptor, targetClass, targetClassDescriptor, substitutor, memberInfo.isToAbstract ) } is KtClassOrObject, is KtPsiClassWrapper -> { if (memberInfo.overrides != null) { context.sourceClass.getSuperTypeEntryByDescriptor( memberDescriptor as ClassDescriptor, context.sourceClassContext )?.let { addSuperTypeEntry(it, targetClass, targetClassDescriptor, context.sourceClassContext, substitutor) } continue@members } else { addMemberToTarget(member, targetClass) } } else -> continue@members } applyMarking(movedMember, substitutor, targetClassDescriptor) } } private fun removeOriginalMembers() { for (memberInfo in context.membersToMove) { val member = memberInfo.member val memberDescriptor = context.memberDescriptors[member] ?: continue when (member) { is KtProperty, is KtNamedFunction -> { member as KtCallableDeclaration memberDescriptor as CallableMemberDescriptor if (memberDescriptor.modality != Modality.ABSTRACT && memberInfo.isToAbstract) { if (member.hasModifier(KtTokens.PRIVATE_KEYWORD)) { member.addModifier(KtTokens.PROTECTED_KEYWORD) } makeAbstract(member, memberDescriptor, TypeSubstitutor.EMPTY, context.sourceClass) member.typeReference?.addToShorteningWaitSet() } else { member.delete() } } is KtClassOrObject, is KtPsiClassWrapper -> { if (memberInfo.overrides != null) { context.sourceClass.getSuperTypeEntryByDescriptor( memberDescriptor as ClassDescriptor, context.sourceClassContext )?.let { context.sourceClass.removeSuperTypeListEntry(it) } } else { member.delete() } } } } } override fun performRefactoring(usages: Array<out UsageInfo>) { val markedElements = ArrayList<KtElement>() try { context.membersToMove.forEach { markedElements += markElements(it.member, context.sourceClassContext, context.sourceClassDescriptor, null) } usages.forEach { (it.element as? KtClassOrObject)?.let { pushDownToClass(it) } } removeOriginalMembers() } finally { clearMarking(markedElements) } } }
apache-2.0
e23ea89003f33f88acdd50b33d376b5f
44.557214
158
0.6718
5.69403
false
false
false
false
ZhangQinglian/dcapp
src/main/kotlin/com/zqlite/android/diycode/device/view/custom/DCImageGetter.kt
1
3809
/* * Copyright 2017 zhangqinglian * * 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.zqlite.android.diycode.device.view.custom import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Drawable import android.graphics.drawable.BitmapDrawable import android.os.AsyncTask import android.text.Html.ImageGetter import android.view.View import android.widget.TextView import okhttp3.OkHttpClient import java.io.BufferedInputStream import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.MalformedURLException import java.net.URL /** * Created by scott on 2017/8/16. */ class URLDrawable : BitmapDrawable() { // the drawable that you need to set, you could set the initial drawing // with the loading image if you need to var drawable: Drawable? = null override fun draw(canvas: Canvas) { // override the draw to facilitate refresh function later if (drawable != null) { drawable!!.draw(canvas) } } } class URLImageParser(internal var container: View, internal var c: Context) : ImageGetter { override fun getDrawable(source: String): Drawable { val urlDrawable = URLDrawable() // get the actual source val asyncTask = ImageGetterAsyncTask(urlDrawable) asyncTask.execute(source) // return reference to URLDrawable where I will change with actual image from // the src tag return urlDrawable } inner class ImageGetterAsyncTask(internal var urlDrawable: URLDrawable) : AsyncTask<String, Void, Drawable>() { override fun doInBackground(vararg params: String): Drawable? { val source = params[0] return fetchDrawable(source) } override fun onPostExecute(result: Drawable?) { if(result == null) return // set the correct bound according to the result from HTTP call urlDrawable.setBounds(0, 0, 0 + result.intrinsicWidth, 0 + result.intrinsicHeight) // change the reference of the current drawable to the result // from the HTTP call urlDrawable.drawable = result // redraw the image by invalidating the container val textview = [email protected] as TextView textview.text = textview.text } /*** * Get the Drawable from URL * @param urlString * * * @return */ fun fetchDrawable(urlString: String): Drawable? { try { val `is` = fetch(urlString) val drawable = Drawable.createFromStream(`is`, "src") drawable.setBounds(0, 0, 0 + drawable.intrinsicWidth, 0 + drawable.intrinsicHeight) return drawable } catch (e: Exception) { return null } } @Throws(MalformedURLException::class, IOException::class) private fun fetch(urlString: String): InputStream { val url = URL(urlString) val connection = url.openConnection() val inputStream = BufferedInputStream(connection.getInputStream()) return inputStream } } }
apache-2.0
3d382cebec67bce1aaa6c62216e6cdf0
32.421053
115
0.656078
4.803279
false
false
false
false
paslavsky/spek
spek-core/src/main/kotlin/org/jetbrains/spek/api/Incomplete.kt
1
452
package org.jetbrains.spek.api fun Specification.given(description: String): Unit = given(description) { pending("Not implemented.") } fun Given.on(description: String): Unit = on(description) { pending("Not implemented.") } fun On.it(description: String): Unit = it(description) { pending("Not implemented.") } fun pending(message: String): Unit = throw PendingException(message) fun skip(message: String): Unit = throw SkippedException(message)
bsd-3-clause
204ed6213f214425d145f9e72236f2e1
40.090909
103
0.75
4.035714
false
false
false
false
matt-richardson/TeamCity.Node
server/src/com/jonnyzzz/teamcity/plugins/node/server/NVM.kt
2
4318
/* * Copyright 2013-2013 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.server import jetbrains.buildServer.web.openapi.PluginDescriptor import com.jonnyzzz.teamcity.plugins.node.common.* import jetbrains.buildServer.serverSide.PropertiesProcessor import jetbrains.buildServer.serverSide.InvalidProperty import jetbrains.buildServer.requirements.Requirement import jetbrains.buildServer.serverSide.buildDistribution.StartingBuildAgentsFilter import jetbrains.buildServer.serverSide.buildDistribution.AgentsFilterContext import jetbrains.buildServer.serverSide.buildDistribution.AgentsFilterResult import jetbrains.buildServer.serverSide.BuildPromotionManager import jetbrains.buildServer.requirements.RequirementType import jetbrains.buildServer.serverSide.buildDistribution.SimpleWaitReason /** * @author Eugene Petrenko ([email protected]) * Date: 16.08.13 21:43 */ public class NVMRunType(val plugin : PluginDescriptor) : RunTypeBase() { private val bean = NVMBean() public override fun getType(): String = bean.NVMFeatureType public override fun getDisplayName(): String = "Node.js NVM Installer" public override fun getDescription(): String = "Install Node.js of specified version using NVM" protected override fun getEditJsp(): String = "node.nvm.edit.jsp" protected override fun getViewJsp(): String = "node.nvm.view.jsp" public override fun getRunnerPropertiesProcessor(): PropertiesProcessor = PropertiesProcessor{ arrayListOf<InvalidProperty>() } public override fun getDefaultRunnerProperties(): MutableMap<String, String>? = hashMapOf(bean.NVMVersion to "0.10") public override fun describeParameters(parameters: Map<String, String>): String = "Install Node.js v" + parameters[bean.NVMVersion] public override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> { return arrayListOf(Requirement(bean.NVMAvailable, null, RequirementType.EXISTS)) } } public class NVMBuildStartPrecondition(val promos : BuildPromotionManager) : StartingBuildAgentsFilter { private val nodeBean = NodeBean() private val npmBean = NPMBean() private val nvmBean = NVMBean() private val runTypes = hashSetOf(nodeBean.runTypeNameNodeJs, npmBean.runTypeName) public override fun filterAgents(context: AgentsFilterContext): AgentsFilterResult { val result = AgentsFilterResult() val promoId = context.getStartingBuild().getBuildPromotionInfo().getId() val buildType = promos.findPromotionById(promoId)?.getBuildType() if (buildType == null) return result val runners = buildType.getBuildRunners() filter { buildType.isEnabled(it.getId()) } //if nothing found => skip if (runners.isEmpty()) return result //if our nodeJS and NPM runners are not used if (!runners.any { runner -> runTypes.contains(runner.getType())}) return result val version = runners.firstOrNull { it.getType() == nvmBean.NVMFeatureType } ?.getParameters() ?.get(nvmBean.NVMVersion) //skip checks if NVM feature version was specified if (version != null) return result //if not, let's filter unwanted agents val agents = context.getAgentsForStartingBuild() filter { agent -> //allow only if there were truly-detected NVM/NPM on the agent with(agent.getConfigurationParameters()) { get(nodeBean.nodeJSConfigurationParameter) != nvmBean.NVMUsed && get(npmBean.nodeJSNPMConfigurationParameter) != nvmBean.NVMUsed } } if (agents.isEmpty()) { result setWaitReason SimpleWaitReason("Please add 'Node.js NVM Installer' build runner") } else { result setFilteredConnectedAgents agents } return result } }
apache-2.0
fb19e4167a7bfdb2768be167e1e20c30
39.735849
115
0.758221
4.554852
false
false
false
false
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/topic/fabmenu/FabMenuItemSecondary.kt
1
1556
package com.sedsoftware.yaptalker.presentation.feature.topic.fabmenu import android.animation.Animator import android.animation.AnimatorInflater import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.content.Context import android.view.View import android.view.animation.OvershootInterpolator import androidx.core.view.isGone import androidx.core.view.isVisible import com.sedsoftware.yaptalker.R class FabMenuItemSecondary( private val context: Context?, private val view: View ) : FabMenuItem { override fun show() { val animator = AnimatorInflater.loadAnimator(context, R.animator.fab_menu_vertical_show) as AnimatorSet animator.interpolator = OvershootInterpolator() animator.setTarget(view) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator?) { super.onAnimationStart(animation) view.isVisible = true } }) animator.start() } override fun hide() { val animator = AnimatorInflater.loadAnimator(context, R.animator.fab_menu_vertical_hide) as AnimatorSet animator.interpolator = OvershootInterpolator() animator.setTarget(view) animator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator?) { super.onAnimationEnd(animation) view.isGone = true } }) animator.start() } }
apache-2.0
6ee84857875c66b608ac89c176e790a0
34.363636
111
0.703085
5.084967
false
false
false
false
androidx/androidx
buildSrc/public/src/main/kotlin/androidx/build/SdkResourceGenerator.kt
3
6187
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.build import androidx.build.dependencies.AGP_LATEST import androidx.build.dependencies.KOTLIN_STDLIB import androidx.build.dependencies.KOTLIN_VERSION import androidx.build.dependencies.KSP_VERSION import com.google.common.annotations.VisibleForTesting import java.io.File import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.artifacts.repositories.MavenArtifactRepository import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.RegularFileProperty import org.gradle.api.plugins.JavaPluginExtension import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.PathSensitive import org.gradle.api.tasks.PathSensitivity import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.TaskProvider import org.gradle.kotlin.dsl.getByType import org.gradle.work.DisableCachingByDefault @DisableCachingByDefault(because = "Simply generates a small file and doesn't benefit from caching") abstract class SdkResourceGenerator : DefaultTask() { @get:Input lateinit var tipOfTreeMavenRepoRelativePath: String /** * project-relative path to folder where outputs from buildSrc builds can be found * (perhaps something like ../out/buildSrc) */ @get:Input lateinit var buildSrcOutRelativePath: String @get:[InputFile PathSensitive(PathSensitivity.NONE)] abstract val debugKeystore: RegularFileProperty @get:Input val compileSdkVersion: String = SupportConfig.COMPILE_SDK_VERSION @get:Input val buildToolsVersion: String = SupportConfig.BUILD_TOOLS_VERSION @get:Input val minSdkVersion: Int = SupportConfig.DEFAULT_MIN_SDK_VERSION @get:Input val agpDependency: String = AGP_LATEST @get:Input val navigationRuntime: String = "androidx.navigation:navigation-runtime:2.4.0-alpha01" @get:Input val kotlinStdlib: String = KOTLIN_STDLIB @get:Input val kotlinVersion: String = KOTLIN_VERSION @get:Input val kspVersion: String = KSP_VERSION @get:Input lateinit var repositoryUrls: List<String> @get:Input val rootProjectRelativePath: String = project.rootProject.rootDir.toRelativeString(project.projectDir) private val projectDir: File = project.projectDir @get:OutputDirectory abstract val outputDir: DirectoryProperty @TaskAction fun generateFile() { // Note all the paths in sdk.prop have to be relative to projectDir to make this task // cacheable between different computers val outputFile = outputDir.file("sdk.prop") outputFile.get().asFile.writer().use { writer -> writer.write("tipOfTreeMavenRepoRelativePath=$tipOfTreeMavenRepoRelativePath\n") writer.write( "debugKeystoreRelativePath=${ debugKeystore.get().asFile.toRelativeString(projectDir) }\n" ) writer.write("rootProjectRelativePath=$rootProjectRelativePath\n") val encodedRepositoryUrls = repositoryUrls.joinToString(",") writer.write("repositoryUrls=$encodedRepositoryUrls\n") writer.write("agpDependency=$agpDependency\n") writer.write("navigationRuntime=$navigationRuntime\n") writer.write("kotlinStdlib=$kotlinStdlib\n") writer.write("compileSdkVersion=$compileSdkVersion\n") writer.write("buildToolsVersion=$buildToolsVersion\n") writer.write("minSdkVersion=$minSdkVersion\n") writer.write("kotlinVersion=$kotlinVersion\n") writer.write("kspVersion=$kspVersion\n") writer.write("buildSrcOutRelativePath=$buildSrcOutRelativePath\n") } } companion object { const val TASK_NAME = "generateSdkResource" @JvmStatic fun generateForHostTest(project: Project) { val provider = registerSdkResourceGeneratorTask(project) val extension = project.extensions.getByType<JavaPluginExtension>() val testSources = extension.sourceSets.getByName("test") testSources.output.dir(provider.flatMap { it.outputDir }) } @VisibleForTesting fun registerSdkResourceGeneratorTask(project: Project): TaskProvider<SdkResourceGenerator> { val generatedDirectory = File(project.buildDir, "generated/resources") return project.tasks.register(TASK_NAME, SdkResourceGenerator::class.java) { it.tipOfTreeMavenRepoRelativePath = project.getRepositoryDirectory().toRelativeString(project.projectDir) it.debugKeystore.set(project.getKeystore()) it.outputDir.set(generatedDirectory) it.buildSrcOutRelativePath = (project.properties["buildSrcOut"] as File).toRelativeString(project.projectDir) // Copy repositories used for the library project so that it can replicate the same // maven structure in test. it.repositoryUrls = project.repositories.filterIsInstance<MavenArtifactRepository>() .map { if (it.url.scheme == "file") { // Make file paths relative to projectDir File(it.url.path).toRelativeString(project.projectDir) } else { it.url.toString() } } } } } }
apache-2.0
1eeb464c0089ae80a86392317fe07c48
38.916129
100
0.689834
4.833594
false
true
false
false
androidx/androidx
compose/foundation/foundation/samples/src/main/java/androidx/compose/foundation/samples/BasicTextFieldSamples.kt
3
6283
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.samples import androidx.annotation.Sampled import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MailOutline import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp @Sampled @Composable fun BasicTextFieldSample() { var value by rememberSaveable(stateSaver = TextFieldValue.Saver) { mutableStateOf(TextFieldValue()) } BasicTextField( value = value, onValueChange = { // it is crucial that the update is fed back into BasicTextField in order to // see updates on the text value = it } ) } @Sampled @Composable fun BasicTextFieldWithStringSample() { var value by rememberSaveable { mutableStateOf("initial value") } BasicTextField( value = value, onValueChange = { // it is crucial that the update is fed back into BasicTextField in order to // see updates on the text value = it } ) } @Sampled @Composable @OptIn(ExperimentalFoundationApi::class) fun PlaceholderBasicTextFieldSample() { var value by rememberSaveable { mutableStateOf("initial value") } Box { BasicTextField( value = value, onValueChange = { value = it } ) if (value.isEmpty()) { Text(text = "Placeholder") } } } @Sampled @Composable @OptIn(ExperimentalFoundationApi::class) fun TextFieldWithIconSample() { var value by rememberSaveable { mutableStateOf("initial value") } BasicTextField( value = value, onValueChange = { value = it }, decorationBox = { innerTextField -> // Because the decorationBox is used, the whole Row gets the same behaviour as the // internal input field would have otherwise. For example, there is no need to add a // Modifier.clickable to the Row anymore to bring the text field into focus when user // taps on a larger text field area which includes paddings and the icon areas. Row( Modifier .background(Color.LightGray, RoundedCornerShape(percent = 30)) .padding(16.dp) ) { Icon(Icons.Default.MailOutline, contentDescription = null) Spacer(Modifier.width(16.dp)) innerTextField() } } ) } @Sampled @Composable fun CreditCardSample() { /** The offset translator used for credit card input field */ val creditCardOffsetTranslator = object : OffsetMapping { override fun originalToTransformed(offset: Int): Int { return when { offset < 4 -> offset offset < 8 -> offset + 1 offset < 12 -> offset + 2 offset <= 16 -> offset + 3 else -> 19 } } override fun transformedToOriginal(offset: Int): Int { return when { offset <= 4 -> offset offset <= 9 -> offset - 1 offset <= 14 -> offset - 2 offset <= 19 -> offset - 3 else -> 16 } } } /** * Converts up to 16 digits to hyphen connected 4 digits string. For example, * "1234567890123456" will be shown as "1234-5678-9012-3456" */ val creditCardTransformation = VisualTransformation { text -> val trimmedText = if (text.text.length > 16) text.text.substring(0..15) else text.text var transformedText = "" trimmedText.forEachIndexed { index, char -> transformedText += char if ((index + 1) % 4 == 0 && index != 15) transformedText += "-" } TransformedText(AnnotatedString(transformedText), creditCardOffsetTranslator) } var text by rememberSaveable { mutableStateOf("") } BasicTextField( value = text, onValueChange = { input -> if (input.length <= 16 && input.none { !it.isDigit() }) { text = input } }, modifier = Modifier.size(170.dp, 30.dp).background(Color.LightGray).wrapContentSize(), singleLine = true, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), visualTransformation = creditCardTransformation ) }
apache-2.0
f1a50215d456a0b76adee9dad3e3b4f5
34.704545
97
0.666083
4.785225
false
false
false
false
fuzz-productions/Salvage
salvage-processor/src/main/java/com/fuzz/android/salvage/ProcessorManager.kt
1
2319
package com.fuzz.android.salvage import javax.annotation.processing.FilerException import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.RoundEnvironment import javax.lang.model.util.Elements import javax.lang.model.util.Types import javax.tools.Diagnostic import kotlin.reflect.KClass /** * Description: * * @author Andrew Grosner (Fuzz) */ class ProcessorManager(val processingEnvironment: ProcessingEnvironment) : Handler { val messager: Messager = processingEnvironment.messager val typeUtils: Types = processingEnvironment.typeUtils val elements: Elements = processingEnvironment.elementUtils val persistenceDefinitions: MutableList<PersistenceDefinition> = arrayListOf() val handlers: List<Handler> = mutableListOf(PersistenceHandler()) fun logError(callingClass: KClass<*>?, error: String?, vararg args: Any?) { messager.printMessage(Diagnostic.Kind.ERROR, String.format("*==========*$callingClass :" + error?.trim { it <= ' ' } + "*==========*", *args)) var stackTraceElements = Thread.currentThread().stackTrace if (stackTraceElements.size > 8) { stackTraceElements = stackTraceElements.copyOf(8) } for (stackTrace in stackTraceElements) { messager.printMessage(Diagnostic.Kind.ERROR, stackTrace.toString()) } } fun logError(error: String?, vararg args: Any?) = logError(callingClass = null, error = error, args = args) fun logWarning(error: String, vararg args: Any?) { messager.printMessage(Diagnostic.Kind.WARNING, String.format("*==========*\n$error\n*==========*", *args)) } fun logWarning(callingClass: KClass<*>, error: String, vararg args: Any?) { logWarning("$callingClass : $error", *args) } override fun handle(processorManager: ProcessorManager, roundEnvironment: RoundEnvironment) { handlers.forEach { it.handle(processorManager, roundEnvironment) } persistenceDefinitions.forEach { writeBaseDefinition(it, this) try { it.writePackageHelper(processingEnvironment) } catch (e: FilerException) { /*Ignored intentionally to allow multi-round table generation*/ } } } }
apache-2.0
4508a5a49086bb936a380a8e7b6e1188
36.419355
150
0.692971
4.723014
false
false
false
false
GunoH/intellij-community
plugins/gitlab/src/org/jetbrains/plugins/gitlab/mergerequest/data/loaders/GitLabMergeRequestsListLoader.kt
2
2240
// 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.plugins.gitlab.mergerequest.data.loaders import com.intellij.collaboration.api.page.SequentialListLoader import com.intellij.collaboration.api.page.SequentialListLoader.ListBatch import com.intellij.collaboration.api.util.LinkHttpHeaderValue import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import org.jetbrains.plugins.gitlab.api.GitLabApi import org.jetbrains.plugins.gitlab.api.GitLabProjectCoordinates import org.jetbrains.plugins.gitlab.mergerequest.api.dto.GitLabMergeRequestShortDTO import org.jetbrains.plugins.gitlab.mergerequest.api.request.loadMergeRequests internal class GitLabMergeRequestsListLoader( private val api: GitLabApi, private val project: GitLabProjectCoordinates, private val searchQuery: String ) : SequentialListLoader<GitLabMergeRequestShortDTO> { private val loadingMutex = Mutex() @Volatile private var nextRequest: (suspend () -> Pair<List<GitLabMergeRequestShortDTO>, String?>)? init { nextRequest = { loadMergeRequests(null) } } private suspend fun loadMergeRequests(nextUri: String?): Pair<List<GitLabMergeRequestShortDTO>, String?> { val response = if (nextUri == null) api.loadMergeRequests(project, searchQuery) else api.loadMergeRequests(nextUri) val linkHeader = response.headers().firstValue(LinkHttpHeaderValue.HEADER_NAME).orElse(null)?.let(LinkHttpHeaderValue::parse) return response.body() to linkHeader?.nextLink } override suspend fun loadNext(): ListBatch<GitLabMergeRequestShortDTO> = withContext(Dispatchers.IO) { doLoad() } private suspend fun doLoad(): ListBatch<GitLabMergeRequestShortDTO> { loadingMutex.withLock { val request = nextRequest if (request == null) { return ListBatch(emptyList(), false) } else { val (data, nextLink) = request() nextRequest = nextLink?.let { { loadMergeRequests(nextLink) } } return ListBatch(data, nextLink != null) } } } }
apache-2.0
232c6960e2c5f18613a4346b287ca452
35.737705
129
0.751339
4.383562
false
false
false
false
siosio/intellij-community
plugins/kotlin/frontend-fir/src/org/jetbrains/kotlin/idea/frontend/api/fir/KtFirAnalysisSession.kt
2
5909
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.frontend.api.fir import com.intellij.openapi.project.Project import org.jetbrains.kotlin.fir.declarations.FirFile import org.jetbrains.kotlin.fir.resolve.firSymbolProvider import org.jetbrains.kotlin.idea.fir.low.level.api.api.FirModuleResolveState import org.jetbrains.kotlin.idea.fir.low.level.api.api.LowLevelFirApiFacadeForCompletion import org.jetbrains.kotlin.idea.fir.low.level.api.api.getFirFile import org.jetbrains.kotlin.idea.fir.low.level.api.api.getResolveState import org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSession import org.jetbrains.kotlin.idea.frontend.api.ReadActionConfinementValidityToken import org.jetbrains.kotlin.idea.frontend.api.ValidityToken import org.jetbrains.kotlin.idea.frontend.api.assertIsValidAndAccessible import org.jetbrains.kotlin.idea.frontend.api.components.* import org.jetbrains.kotlin.idea.frontend.api.fir.components.* import org.jetbrains.kotlin.idea.frontend.api.fir.symbols.KtFirSymbolProvider import org.jetbrains.kotlin.idea.frontend.api.fir.utils.EnclosingDeclarationContext import org.jetbrains.kotlin.idea.frontend.api.fir.utils.recordCompletionContext import org.jetbrains.kotlin.idea.frontend.api.fir.utils.threadLocal import org.jetbrains.kotlin.idea.frontend.api.symbols.KtSymbolProvider import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile internal class KtFirAnalysisSession private constructor( private val project: Project, val firResolveState: FirModuleResolveState, internal val firSymbolBuilder: KtSymbolByFirBuilder, token: ValidityToken, val context: KtFirAnalysisSessionContext, ) : KtAnalysisSession(token) { init { assertIsValidAndAccessible() } override val smartCastProvider: KtSmartCastProvider = KtFirSmartcastProvider(this, token) override val expressionTypeProvider: KtExpressionTypeProvider = KtFirExpressionTypeProvider(this, token) override val diagnosticProvider: KtDiagnosticProvider = KtFirDiagnosticProvider(this, token) override val containingDeclarationProvider = KtFirSymbolContainingDeclarationProvider(this, token) override val callResolver: KtCallResolver = KtFirCallResolver(this, token) override val scopeProvider by threadLocal { KtFirScopeProvider(this, firSymbolBuilder, project, firResolveState, token) } override val symbolProvider: KtSymbolProvider = KtFirSymbolProvider(this, firResolveState.rootModuleSession.firSymbolProvider, firResolveState, firSymbolBuilder, token) override val completionCandidateChecker: KtCompletionCandidateChecker = KtFirCompletionCandidateChecker(this, token) override val symbolDeclarationOverridesProvider: KtSymbolDeclarationOverridesProvider = KtFirSymbolDeclarationOverridesProvider(this, token) override val expressionHandlingComponent: KtExpressionHandlingComponent = KtFirExpressionHandlingComponent(this, token) override val typeProvider: KtTypeProvider = KtFirTypeProvider(this, token) override val subtypingComponent: KtSubtypingComponent = KtFirSubtypingComponent(this, token) override fun createContextDependentCopy(originalKtFile: KtFile, fakeKtElement: KtElement): KtAnalysisSession { check(context == KtFirAnalysisSessionContext.DefaultContext) { "Cannot create context-dependent copy of KtAnalysis session from a context dependent one" } val contextResolveState = LowLevelFirApiFacadeForCompletion.getResolveStateForCompletion(firResolveState) val originalFirFile = originalKtFile.getFirFile(firResolveState) val context = KtFirAnalysisSessionContext.FakeFileContext(originalKtFile, originalFirFile, fakeKtElement, contextResolveState) return KtFirAnalysisSession( project, contextResolveState, firSymbolBuilder.createReadOnlyCopy(contextResolveState), token, context ) } companion object { @Deprecated("Please use org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSessionProviderKt.analyze") internal fun createForElement(element: KtElement): KtFirAnalysisSession { val firResolveState = element.getResolveState() return createAnalysisSessionByResolveState(firResolveState) } @Deprecated("Please use org.jetbrains.kotlin.idea.frontend.api.KtAnalysisSessionProviderKt.analyze") internal fun createAnalysisSessionByResolveState(firResolveState: FirModuleResolveState): KtFirAnalysisSession { val project = firResolveState.project val token = ReadActionConfinementValidityToken(project) val firSymbolBuilder = KtSymbolByFirBuilder( firResolveState, project, token ) return KtFirAnalysisSession( project, firResolveState, firSymbolBuilder, token, KtFirAnalysisSessionContext.DefaultContext ) } } } internal sealed class KtFirAnalysisSessionContext { object DefaultContext : KtFirAnalysisSessionContext() class FakeFileContext( originalFile: KtFile, firFile: FirFile, fakeContextElement: KtElement, fakeModuleResolveState: FirModuleResolveState ) : KtFirAnalysisSessionContext() { init { require(!fakeContextElement.isPhysical) val enclosingContext = EnclosingDeclarationContext.detect(originalFile, fakeContextElement) enclosingContext.recordCompletionContext(firFile, fakeModuleResolveState) } val fakeKtFile = fakeContextElement.containingKtFile } }
apache-2.0
4f6b144084401e7f4cb32bda18f6bfb8
48.655462
134
0.768996
5.120451
false
false
false
false
GunoH/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/state/DontShowAgainKotlinAdditionPluginSuggestionService.kt
9
1340
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradle.configuration.state import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage @State( name = "DontShowAgainKotlinAdditionPluginSuggestionService", reloadable = true, storages = [Storage("dontShowAgainKotlinAdditionPluginSuggestionService.xml")] ) class DontShowAgainKotlinAdditionPluginSuggestionService: PersistentStateComponent<DontShowAgainKotlinAdditionPluginSuggestionState> { companion object { @JvmStatic fun getInstance(): DontShowAgainKotlinAdditionPluginSuggestionService { return ApplicationManager.getApplication().getService(DontShowAgainKotlinAdditionPluginSuggestionService::class.java) } } private var state: DontShowAgainKotlinAdditionPluginSuggestionState = DontShowAgainKotlinAdditionPluginSuggestionState() override fun getState(): DontShowAgainKotlinAdditionPluginSuggestionState { return state } override fun loadState(state: DontShowAgainKotlinAdditionPluginSuggestionState) { this.state = state } }
apache-2.0
289a539cea33294d475a8cced2e4b668
40.875
134
0.802985
5.1341
false
false
false
false
GunoH/intellij-community
java/java-impl/src/com/intellij/lang/java/actions/CreateFieldAction.kt
1
5163
// 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.lang.java.actions import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate import com.intellij.codeInsight.daemon.impl.quickfix.JavaCreateFieldFromUsageHelper import com.intellij.codeInsight.intention.preview.IntentionPreviewUtils import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.lang.java.request.CreateFieldFromJavaUsageRequest import com.intellij.lang.jvm.JvmLong import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.CreateFieldActionGroup import com.intellij.lang.jvm.actions.CreateFieldRequest import com.intellij.lang.jvm.actions.JvmActionGroup import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass import com.intellij.psi.util.JavaElementKind import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil internal class CreateFieldAction(target: PsiClass, request: CreateFieldRequest) : CreateFieldActionBase(target, request) { override fun getActionGroup(): JvmActionGroup = CreateFieldActionGroup override fun getText(): String = message("create.element.in.class", JavaElementKind.FIELD.`object`(), request.fieldName, getNameForClass(target, false)) } internal val constantModifiers = setOf( JvmModifier.STATIC, JvmModifier.FINAL ) internal class JavaFieldRenderer( private val project: Project, private val constantField: Boolean, private val targetClass: PsiClass, private val request: CreateFieldRequest ) { private val helper = JavaCreateFieldFromUsageHelper() // TODO get rid of it private val javaUsage = request as? CreateFieldFromJavaUsageRequest private val expectedTypes = extractExpectedTypes(project, request.fieldType).toTypedArray() private val modifiersToRender: Collection<JvmModifier> get() { return if (constantField) { if (targetClass.isInterface) { // interface fields are public static final implicitly, so modifiers don't have to be rendered request.modifiers - constantModifiers - visibilityModifiers } else { // render static final explicitly request.modifiers + constantModifiers } } else { // render as is request.modifiers } } fun doRender() { var field = renderField() field = insertField(field, javaUsage?.anchor) startTemplate(field) } fun renderField(): PsiField { val field = JavaPsiFacade.getElementFactory(project).createField(request.fieldName, PsiType.INT) // clean template modifiers field.modifierList?.let { list -> list.firstChild?.let { list.deleteChildRange(it, list.lastChild) } } // setup actual modifiers for (modifier in modifiersToRender.map(JvmModifier::toPsiModifier)) { PsiUtil.setModifierProperty(field, modifier, true) } field.modifierList?.let { modifierList -> for (annRequest in request.annotations) { modifierList.addAnnotation(annRequest.qualifiedName) } } val requestInitializer = request.initializer if (requestInitializer is JvmLong) { field.initializer = PsiElementFactory.getInstance(project).createExpressionFromText("${requestInitializer.longValue}L", null) } return field } internal fun insertField(field: PsiField, anchor: PsiElement?): PsiField { return helper.insertFieldImpl(targetClass, field, anchor) } internal fun startTemplate(field: PsiField) { val targetFile = targetClass.containingFile ?: return val newEditor = positionCursor(field.project, targetFile, field) ?: return val substitutor = request.targetSubstitutor.toPsiSubstitutor(project) val template = helper.setupTemplateImpl(field, expectedTypes, targetClass, newEditor, javaUsage?.reference, constantField, substitutor) val listener = MyTemplateListener(project, newEditor, targetFile) startTemplate(newEditor, template, project, listener, null) } } private class MyTemplateListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { PsiDocumentManager.getInstance(project).commitDocument(editor.document) val offset = editor.caretModel.offset val psiField = PsiTreeUtil.findElementOfClassAtOffset(file, offset, PsiField::class.java, false) ?: return IntentionPreviewUtils.write<RuntimeException> { CodeStyleManager.getInstance(project).reformat(psiField) } editor.caretModel.moveToOffset(psiField.textRange.endOffset - 1) } }
apache-2.0
d73c8286e1d281cf4badf6e5bb989167
39.335938
158
0.762735
4.798327
false
false
false
false
pacmancoder/krayser
src/main/kotlin/org/krayser/frontend/LWJGLApp.kt
1
7922
package org.krayser.frontend import org.krayser.core.Chunk import org.krayser.core.defaultHeight import org.krayser.core.defaultWidth import org.lwjgl.BufferUtils import org.lwjgl.opengl.* import org.lwjgl.glfw.Callbacks.glfwFreeCallbacks import org.lwjgl.glfw.GLFW.* import org.lwjgl.system.MemoryUtil.NULL as LWJGL_NULL import kotlin.system.measureNanoTime /** * Frontend class implementation for LWJGL as singletone * * use [run(handler)][run] to run application with you handler * TODO: Divide surface on quads and assign different textures */ object LWJGLApp: Frontend { // window constants private const val windowWidth = defaultWidth private const val windowHeight = defaultHeight // flag to prevent multiple LWJGL initializations private var running = false // LWJGL vars private var windowHandle = LWJGL_NULL // OpenGL vars private var tex = 0 private var program = 0 private var vbo = 0 private var vao = 0 private val vertexes = floatArrayOf( -1f, -1f, 0f, 0f, 1f, -1f, 1f, 0f, 1f, 1f, 1f, 1f, -1f, 1f, 0f, 1f ) override fun changeTitle(title: String) { glfwSetWindowTitle(windowHandle, title) } override fun drawChunk(chunk: Chunk) { val surface = chunk.obtainSurface() if (surface != null) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex) with (chunk.workGroup) { val buff = BufferUtils.createByteBuffer(w * h * 3) buff.put(surface) buff.flip() GL11.glTexSubImage2D(GL11.GL_TEXTURE_2D, 0, x, y, w, h, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, buff) } } } override fun clearSurface() { GL11.glClear(GL11.GL_COLOR_BUFFER_BIT or GL11.GL_DEPTH_BUFFER_BIT) } private fun lwjglInit() { if (!glfwInit()) { throw IllegalStateException("GLFW init error") } // set window hints glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); // create window and check errors windowHandle = glfwCreateWindow( windowWidth, windowHeight, "krayser v0.1.0", LWJGL_NULL, LWJGL_NULL) if (windowHandle == LWJGL_NULL) { throw RuntimeException("Error during glfw window creation") } // place window in center val videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor()) glfwSetWindowPos( windowHandle, (videoMode.width() - windowWidth) / 2, (videoMode.height() - windowHeight) / 2) // Activate OpenGL context glfwMakeContextCurrent(windowHandle) // V-Sync on glfwSwapInterval(1) glfwShowWindow(windowHandle) GL.createCapabilities() // boring stuff to init openGL for quad drawing val vertShader = GL20.glCreateShader(GL20.GL_VERTEX_SHADER) GL20.glShaderSource(vertShader, """ #version 130 in vec2 position; in vec2 texcoord; out vec2 tCoord; void main() { tCoord = texcoord; gl_Position = vec4(position, 0.0, 1.0); } """) GL20.glCompileShader(vertShader) val fragShader = GL20.glCreateShader(GL20.GL_FRAGMENT_SHADER) GL20.glShaderSource(fragShader, """ #version 130 in vec2 tCoord; out vec4 outColor; uniform sampler2D tex; void main() { vec4 texColor = texture(tex, tCoord); outColor = vec4(texColor.xyz, 1.0); } """) GL20.glCompileShader(fragShader) program = GL20.glCreateProgram() GL20.glAttachShader(program, vertShader) GL20.glAttachShader(program, fragShader) GL20.glBindAttribLocation(program, 0, "position") GL20.glBindAttribLocation(program, 1, "texcoord") GL20.glLinkProgram(program) GL20.glUniform1i(GL20.glGetUniformLocation(program, "tex"), 0) // delete separate shaders, they are already compiled and linked to shader GL20.glDeleteShader(vertShader) GL20.glDeleteShader(fragShader) val buff = BufferUtils.createFloatBuffer(vertexes.size) buff.put(vertexes) buff.flip() vbo = GL15.glGenBuffers() GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo) GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buff, GL15.GL_STATIC_DRAW) vao = GL30.glGenVertexArrays() GL30.glBindVertexArray(vao) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo) GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 4 * 4, 0) GL20.glVertexAttribPointer(1, 2, GL11.GL_FLOAT, false, 4 * 4, 4 * 2) GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0) GL30.glBindVertexArray(0) // make texture tex = GL11.glGenTextures() GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex) val texBuff = BufferUtils.createByteBuffer(windowWidth * windowHeight * 3) texBuff.flip() GL11.glTexImage2D( GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, windowWidth, windowHeight, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, texBuff) GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST) GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST) } private fun lwjglLoop(procFunction: (Double) -> Unit) { GL11.glClearColor(0.0f, 0.0f, 0.0f, 1.0f) var dt = .0 while (!glfwWindowShouldClose(windowHandle)) { // execute frame processing and return delta time val dt_nano = measureNanoTime { clearSurface() GL13.glActiveTexture(GL13.GL_TEXTURE0) GL11.glBindTexture(GL11.GL_TEXTURE_2D, tex) GL20.glUniform1i(GL20.glGetUniformLocation(program, "tex"), 0) GL20.glUseProgram(program) GL30.glBindVertexArray(vao) GL20.glEnableVertexAttribArray(0) GL20.glEnableVertexAttribArray(1) GL11.glDrawArrays(GL11.GL_TRIANGLE_FAN, 0, 4) GL20.glEnableVertexAttribArray(1) GL20.glDisableVertexAttribArray(0) procFunction(dt) glfwSwapBuffers(windowHandle) glfwPollEvents() } // convert nanos to ms dt = dt_nano.toDouble() / 1000000.0 } } /** * Launches application * @param handler handler of application loop, implementor of [AppHandler] */ fun run(handler: AppHandler) { if (!running) { running = true try { // main application life cycle lwjglInit() handler.init(this) lwjglLoop { handler.proc(this, it) } handler.exit(this) // free all glfw-related things GL15.glDeleteBuffers(vbo) GL30.glDeleteVertexArrays(vao) GL11.glDeleteTextures(tex) GL20.glDeleteProgram(program) glfwFreeCallbacks(windowHandle) glfwDestroyWindow(windowHandle) } finally { // Terminate GLFW and free the error callback glfwTerminate() // we are done. application can be launched again running = false } } else { throw IllegalStateException("Can't run LWJGL frontend more than one time during app life cycle") } } }
mit
332546fd8c03588a9b0b42b5e5f2b0d1
33.593886
113
0.581419
4.268319
false
false
false
false
smmribeiro/intellij-community
python/python-features-trainer/src/com/jetbrains/python/ift/lesson/completion/FStringCompletionLesson.kt
1
3498
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.ift.lesson.completion import com.jetbrains.python.ift.PythonLessonsBundle import com.jetbrains.python.ift.PythonLessonsUtil.showWarningIfPython3NotFound import training.dsl.LessonContext import training.dsl.LessonUtil import training.dsl.LessonUtil.checkExpectedStateOfEditor import training.dsl.parseLessonSample import training.learn.course.KLesson import training.util.isToStringContains class FStringCompletionLesson : KLesson("completion.f.string", PythonLessonsBundle.message("python.f.string.completion.lesson.name")) { private val template = """ import sys class Car: def __init__(self, speed=0): self.speed = speed self.odometer = 0 self.time = 0 def say_state(self): print("I'm going kph!".format(self.speed)) def accelerate(self): self.speed += 5 def brake(self): self.speed -= 5 def step(self): self.odometer += self.speed self.time += 1 def average_speed(self): return self.odometer / self.time if __name__ == '__main__': my_car_show_distance = sys.argv[1] my_car = Car() print("I'm a car!") while True: action = input("What should I do? [A]ccelerate, [B]rake, " "show [O]dometer, or show average [S]peed?").upper() if action not in "ABOS" or len(action) != 1: print("I don't know how to do that") if my_car_show_distance == "yes": print(<f-place>"The car has driven <caret> kilometers") """.trimIndent() + '\n' private val completionItem = "my_car" private val sample = parseLessonSample(template.replace("<f-place>", "")) override val lessonContent: LessonContext.() -> Unit = { prepareSample(sample) showWarningIfPython3NotFound() task("{my") { text(PythonLessonsBundle.message("python.f.string.completion.type.prefix", code(it))) runtimeText { val prefixTyped = checkExpectedStateOfEditor(sample) { change -> "{my_car".startsWith(change) && change.startsWith(it) } == null if (prefixTyped) PythonLessonsBundle.message("python.f.string.completion.invoke.manually", action("CodeCompletion")) else null } triggerByListItemAndHighlight(highlightBorder = false) { item -> item.isToStringContains(completionItem) } proposeRestore { checkExpectedStateOfEditor(sample) { change -> "{my_car".startsWith(change) } } test { type(it) } } task { text(PythonLessonsBundle.message("python.f.string.completion.complete.it", code(completionItem), action("EditorChooseLookupItem"))) val result = template.replace("<f-place>", "f").replace("<caret>", "{$completionItem}") restoreByUi() stateCheck { editor.document.text == result } test(waitEditorToBeReady = false) { invokeActionViaShortcut("ENTER") } } text(PythonLessonsBundle.message("python.f.string.completion.result.message")) } override val helpLinks: Map<String, String> get() = mapOf( Pair(PythonLessonsBundle.message("python.f.string.completion.help.link"), LessonUtil.getHelpLink("pycharm", "auto-completing-code.html#f-string-completion")), ) }
apache-2.0
80b74dd78d7b498b8aef18e82712e7da
38.303371
140
0.646655
4.318519
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SendIntentAction.kt
1
7470
package ch.rmy.android.http_shortcuts.scripting.actions.types import android.content.ActivityNotFoundException import android.content.Intent import android.os.Build import android.os.FileUriExposedException import androidx.core.net.toUri import ch.rmy.android.framework.extensions.logException import ch.rmy.android.framework.extensions.takeUnlessEmpty import ch.rmy.android.http_shortcuts.R import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent import ch.rmy.android.http_shortcuts.exceptions.ActionException import ch.rmy.android.http_shortcuts.extensions.toListOfObjects import ch.rmy.android.http_shortcuts.extensions.toListOfStrings import ch.rmy.android.http_shortcuts.scripting.ExecutionContext import ch.rmy.android.http_shortcuts.utils.ActivityProvider import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.json.JSONObject import javax.inject.Inject class SendIntentAction(private val jsonData: String) : BaseAction() { @Inject lateinit var activityProvider: ActivityProvider override fun inject(applicationComponent: ApplicationComponent) { applicationComponent.inject(this) } override suspend fun execute(executionContext: ExecutionContext) { val parameters = JSONObject(jsonData) val intent = constructIntent(parameters) withContext(Dispatchers.Main) { val activity = activityProvider.getActivity() try { when (parameters.optString(KEY_TYPE).lowercase()) { TYPE_ACTIVITY -> { activity.startActivity(intent) } TYPE_SERVICE -> { activity.startService(intent) } else -> { activity.sendBroadcast(intent) } } } catch (e: Exception) { if (shouldLogException(e)) { logException(e) } throw ActionException { getString(R.string.error_action_type_send_intent_failed, e.message) } } } } companion object { private const val KEY_TYPE = "type" private const val KEY_ACTION = "action" private const val KEY_CATEGORY = "category" private const val KEY_CATEGORIES = "categories" private const val KEY_DATA_URI = "dataUri" private const val KEY_DATA_TYPE = "dataType" private const val KEY_CLASS_NAME = "className" private const val KEY_PACKAGE_NAME = "packageName" private const val KEY_EXTRAS = "extras" private const val KEY_FLAG_CLEAR_TASK = "clearTask" private const val KEY_FLAG_EXCLUDE_FROM_RECENTS = "excludeFromRecents" private const val KEY_FLAG_NEW_TASK = "newTask" private const val KEY_FLAG_NO_HISTORY = "noHistory" private const val KEY_EXTRA_NAME = "name" private const val KEY_EXTRA_VALUE = "value" private const val KEY_EXTRA_TYPE = "type" private const val EXTRA_TYPE_BOOLEAN = "boolean" private const val EXTRA_TYPE_INT = "int" private const val EXTRA_TYPE_LONG = "long" private const val EXTRA_TYPE_DOUBLE = "double" private const val EXTRA_TYPE_FLOAT = "float" private const val TYPE_ACTIVITY = "activity" private const val TYPE_SERVICE = "service" fun constructIntent(parameters: JSONObject): Intent = Intent(parameters.optString(KEY_ACTION)).apply { parameters.optString(KEY_DATA_URI) .takeUnlessEmpty() ?.toUri() ?.let { dataUri -> parameters.optString(KEY_DATA_TYPE) .takeUnlessEmpty() ?.let { dataType -> setDataAndType(dataUri, dataType) } ?: run { setData(dataUri) } } parameters.optString(KEY_CATEGORY) .takeUnlessEmpty() ?.let { category -> addCategory(category) } parameters.optJSONArray(KEY_CATEGORIES) ?.toListOfStrings() ?.forEach { category -> addCategory(category) } parameters.optString(KEY_PACKAGE_NAME) .takeUnlessEmpty() ?.let { packageName -> parameters.optString(KEY_CLASS_NAME) .takeUnlessEmpty() ?.let { className -> setClassName(packageName, className) } ?: run { `package` = packageName } } if (parameters.optBoolean(KEY_FLAG_CLEAR_TASK)) { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK) } if (parameters.optBoolean(KEY_FLAG_EXCLUDE_FROM_RECENTS)) { addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) } if (parameters.optBoolean(KEY_FLAG_NEW_TASK)) { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } if (parameters.optBoolean(KEY_FLAG_NO_HISTORY)) { addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY) } parameters.optJSONArray(KEY_EXTRAS) ?.toListOfObjects() ?.forEach { extra -> val name = extra.optString(KEY_EXTRA_NAME) .takeUnlessEmpty() ?: return@forEach when (extra.optString(KEY_EXTRA_TYPE)) { EXTRA_TYPE_BOOLEAN -> { putExtra(name, extra.optBoolean(KEY_EXTRA_VALUE)) } EXTRA_TYPE_FLOAT -> { putExtra(name, extra.optDouble(KEY_EXTRA_VALUE).toFloat()) } EXTRA_TYPE_DOUBLE -> { putExtra(name, extra.optDouble(KEY_EXTRA_VALUE)) } EXTRA_TYPE_INT -> { putExtra(name, extra.optInt(KEY_EXTRA_VALUE)) } EXTRA_TYPE_LONG -> { putExtra(name, extra.optLong(KEY_EXTRA_VALUE)) } else -> { putExtra(name, extra.optString(KEY_EXTRA_VALUE)) } } } } private fun shouldLogException(e: Exception): Boolean = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && e is FileUriExposedException) { false } else { when (e) { is ActivityNotFoundException, is SecurityException, -> false else -> true } } } }
mit
9b94e35a99d055e46a0d30370b30389a
40.966292
97
0.50656
5.436681
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/tools/manager/NetworkCallbacksConnectivityStateProvider.kt
1
2623
/** * BreadWallet * * Created by Ahsan Butt <[email protected]> on 9/25/20. * Copyright (c) 2020 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.tools.manager import android.annotation.TargetApi import android.net.ConnectivityManager import android.net.Network import android.net.NetworkCapabilities import android.os.Build import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @TargetApi(Build.VERSION_CODES.N) class NetworkCallbacksConnectivityStateProvider( private val connectivityManager: ConnectivityManager ) : ConnectivityStateProvider, ConnectivityManager.NetworkCallback() { private val _state = MutableStateFlow(getConnectivityState()) init { connectivityManager.registerDefaultNetworkCallback(this) } override fun state(): Flow<ConnectivityState> = _state override fun close() { connectivityManager.unregisterNetworkCallback(this) } override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) { _state.value = getConnectivityState(capabilities) } override fun onLost(network: Network) { _state.value = ConnectivityState.Disconnected } private fun getConnectivityState() = getConnectivityState(connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)) private fun getConnectivityState(capabilities: NetworkCapabilities?) = if (capabilities != null) { ConnectivityState.Connected } else { ConnectivityState.Disconnected } }
mit
1d24b78c0d8094dd0853e9ce692bccf3
37.588235
107
0.765917
4.911985
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/database/actor.kt
1
3113
package link.continuum.desktop.database import io.requery.Persistable import io.requery.kotlin.Logical import io.requery.kotlin.desc import io.requery.kotlin.eq import io.requery.kotlin.lte import io.requery.sql.KotlinEntityDataStore import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.actor import link.continuum.database.models.RoomEventRow class KDataStore( @Deprecated("internal") val _dataStore: KotlinEntityDataStore<Persistable> ) { private val scope = CoroutineScope(Dispatchers.IO) val actor = scope.actor<DbMsg>(capacity = 8) { for (msg in channel) { @Suppress("DEPRECATION") when (msg) { is DbMsg.Operation -> { msg.operation(_dataStore) } is DbMsg.UpdateEvents -> { _dataStore.upsert(msg.events) } is DbMsg.LoadEvents -> { var condition: Logical<*, *> = RoomEventRow::room_id.eq(msg.roomId) if (msg.upto!=null) { val c1 = RoomEventRow::server_time.lte(msg.upto) condition = condition.and(c1) } val r = _dataStore.select(RoomEventRow::class).where(condition) .orderBy(RoomEventRow::server_time.desc()).limit(msg.limit).get().reversed() msg.response.complete(r) } } } } suspend inline fun <T> runOp(crossinline op: suspend KotlinEntityDataStore<Persistable>.() -> T): T { val deferred = CompletableDeferred<T>() val msg = DbMsg.Operation { deferred.complete(it.op()) } actor.send(msg) val v = deferred.await() return v } suspend inline fun <T> letOp(crossinline op: suspend (KotlinEntityDataStore<Persistable>) -> T): T { return runOp { op(this) } } suspend fun updateEvents(events: List<RoomEventRow>) { actor.send(DbMsg.UpdateEvents(events)) } /** * get events not newer than upto */ suspend fun loadEvents(roomId: String, upto: Long?, limit: Int ):List<RoomEventRow> { val deferred = CompletableDeferred<List<RoomEventRow>>() actor.send(DbMsg.LoadEvents(roomId, upto, limit, deferred)) val v = deferred.await() return v } fun close() { @Suppress("DEPRECATION") _dataStore.close() } sealed class DbMsg { class Operation( val operation: suspend (KotlinEntityDataStore<Persistable>) -> Unit ) : DbMsg() class UpdateEvents(val events: List<RoomEventRow>): DbMsg() class LoadEvents(val roomId: String, val upto: Long?, val limit: Int, val response: CompletableDeferred<List<RoomEventRow>> ): DbMsg() } }
gpl-3.0
044112805897ceb4299f73910f0f3b2b
33.588889
105
0.568583
4.524709
false
false
false
false
suitougreentea/f-c-p-l-c
src/io/github/suitougreentea/fcplc/FieldRandomizer.kt
1
1560
package io.github.suitougreentea.fcplc class FieldRandomizer(val color: Int, val width: Int) { init { if(color <= 2) throw UnsupportedOperationException() } var firstCache: Array<Int> var secondCache: Array<Int> init { firstCache = Array(width, {0}) secondCache = Array(width, {0}) for (i in 0..width - 1) { if(i >= 2) { do { firstCache[i] = (Math.random() * color).toInt() + 1 } while (firstCache[i] == firstCache[i - 1] && firstCache[i] == firstCache[i - 2]) do { secondCache[i] = (Math.random() * color).toInt() + 1 } while (secondCache[i] == secondCache[i - 1] && secondCache[i] == secondCache[i - 2]) } else { firstCache[i] = (Math.random() * color).toInt() + 1 secondCache[i] = (Math.random() * color).toInt() + 1 } } } fun next(): Array<Int> { var nextSecondCache = Array(width, {0}) for (i in 0..width - 1) { if(i >= 2) { do { nextSecondCache[i] = (Math.random() * color).toInt() + 1 } while ((nextSecondCache[i] == nextSecondCache[i - 1] && nextSecondCache[i] == nextSecondCache[i - 2]) || (nextSecondCache[i] == firstCache[i] && nextSecondCache[i] == secondCache[i])) } else { do { nextSecondCache[i] = (Math.random() * color).toInt() + 1 } while (nextSecondCache[i] == firstCache[i] && nextSecondCache[i] == secondCache[i]) } } val result = firstCache firstCache = secondCache secondCache = nextSecondCache return result } }
mit
65dc2aec07fca52de9bf5eb1c12978b8
32.191489
193
0.564103
3.256785
false
false
false
false
seventhroot/elysium
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/hide/CharacterHideCommand.kt
1
3204
/* * Copyright 2016 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character.hide import com.rpkit.characters.bukkit.RPKCharactersBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Character hide command. * Parent command for commands to hide different character card fields. */ class CharacterHideCommand(private val plugin: RPKCharactersBukkit): CommandExecutor { private val characterHidePlayerCommand = CharacterHidePlayerCommand(plugin) private val characterHideProfileCommand = CharacterHideProfileCommand(plugin) private val characterHideNameCommand = CharacterHideNameCommand(plugin) private val characterHideGenderCommand = CharacterHideGenderCommand(plugin) private val characterHideAgeCommand = CharacterHideAgeCommand(plugin) private val characterHideRaceCommand = CharacterHideRaceCommand(plugin) private val characterHideDescriptionCommand = CharacterHideDescriptionCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() if (args[0].equals("player", ignoreCase = true)) { return characterHidePlayerCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("profile", ignoreCase = true)) { return characterHideProfileCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("name", ignoreCase = true)) { return characterHideNameCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("gender", ignoreCase = true)) { return characterHideGenderCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("age", ignoreCase = true)) { return characterHideAgeCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("race", ignoreCase = true)) { return characterHideRaceCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("description", ignoreCase = true) || args[0].equals("desc", ignoreCase = true)) { return characterHideDescriptionCommand.onCommand(sender, command, label, newArgs) } else { sender.sendMessage(plugin.messages["character-hide-usage"]) } } else { sender.sendMessage(plugin.messages["character-hide-usage"]) } return true } }
apache-2.0
17093de203689d61a293bfe98fa1c6be
49.0625
119
0.706305
4.677372
false
false
false
false
seventhroot/elysium
bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/account/AccountLinkMinecraftCommand.kt
1
3090
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.players.bukkit.command.account import com.rpkit.players.bukkit.RPKPlayersBukkit import com.rpkit.players.bukkit.profile.* import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender import org.bukkit.entity.Player class AccountLinkMinecraftCommand(private val plugin: RPKPlayersBukkit): CommandExecutor { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean { if (sender !is Player) { sender.sendMessage(plugin.messages["not-from-console"]) return true } if (!sender.hasPermission("rpkit.players.command.account.link.minecraft")) { sender.sendMessage(plugin.messages["no-permission-account-link-minecraft"]) return true } if (args.isEmpty()) { sender.sendMessage(plugin.messages["account-link-minecraft-usage"]) return true } val minecraftUsername = args[0] val bukkitPlayer = plugin.server.getOfflinePlayer(minecraftUsername) val minecraftProfileProvider = plugin.core.serviceManager.getServiceProvider(RPKMinecraftProfileProvider::class) var minecraftProfile = minecraftProfileProvider.getMinecraftProfile(bukkitPlayer) if (minecraftProfile != null) { sender.sendMessage(plugin.messages["account-link-minecraft-invalid-minecraft-profile"]) return true } val senderMinecraftProfile = minecraftProfileProvider.getMinecraftProfile(sender) if (senderMinecraftProfile == null) { sender.sendMessage(plugin.messages["no-minecraft-profile-self"]) return true } val profile = senderMinecraftProfile.profile if (profile !is RPKProfile) { sender.sendMessage(plugin.messages["no-profile-self"]) return true } minecraftProfile = RPKMinecraftProfileImpl(profile = RPKThinProfileImpl(bukkitPlayer.name ?: "Unknown Minecraft user"), minecraftUUID = bukkitPlayer.uniqueId) minecraftProfileProvider.addMinecraftProfile(minecraftProfile) val minecraftProfileLinkRequest = RPKMinecraftProfileLinkRequestImpl(profile = profile, minecraftProfile = minecraftProfile) minecraftProfileProvider.addMinecraftProfileLinkRequest(minecraftProfileLinkRequest) sender.sendMessage(plugin.messages["account-link-minecraft-valid"]) return true } }
apache-2.0
23a5e8660693e7996bd5504529d24c2a
45.833333
166
0.721683
5.073892
false
false
false
false
davidbuzz/ardupilot
libraries/AP_HAL_ESP32/utils/FontConverter.kt
18
2130
import java.io.File import java.io.Writer import java.util.* import kotlin.collections.ArrayList const val char_width = 12 const val char_height = 18 data class Symbol( var code: Int, var levl: ArrayList<Boolean>, var mask: ArrayList<Boolean> ) var symbols = ArrayList<Symbol>() fun readSymbols(fileName: String) { var data = ArrayList<Int>() Scanner(File(fileName)).use { scanner -> scanner.next() while (scanner.hasNext()) { data.add(Integer.parseInt(scanner.next(), 2)) } } for (ch in 0 until 256) { var levl = ArrayList<Boolean>() var mask = ArrayList<Boolean>() for (y in 0 until char_height) { for (x in 0 until char_width) { var bitoffset = (y * char_width + x) * 2 var byteoffset = 64 * ch + bitoffset / 8 var bitshift = 6 - (bitoffset % 8) var v = (data[byteoffset] ushr bitshift) and 3 levl.add(v and 2 != 0) mask.add(v and 1 == 0) } } symbols.add(Symbol(ch, levl, mask)) } } fun printSymbols(fileName: String) { File(fileName).bufferedWriter().use { out -> out.write("#include <AP_OSD/AP_OSD_INT.h>\n") out.write("#ifdef WITH_INT_OSD\n") out.write("const uint32_t AP_OSD_INT::font_data[256 * 18] = {\n") for (code in 0 until 256) { val s = symbols[code] for (y in 0 until char_height) { var v: Int = 0 var gr = "" for(x in 0 until char_width) { if(s.levl[y * char_width + x]) { v = v or (1 shl (31 - x)) gr += "*" } else { gr += "-" } } out.write("0x%08x,\t//\t%s\n".format(v, gr)) print(gr + "\n") } out.write("\n") print("\n") } out.write("};\n#endif\n") } } fun main() { readSymbols("bold.mcm") printSymbols("Symbols.cpp") }
gpl-3.0
3f0fc7b269296ce59f80eaa06c84a934
26.307692
73
0.475587
3.672414
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/a_新手/DataClassTest.kt
1
641
package a_新手 import gson学习与反射.gson.gsonList等测试.GsonUtils import ktshare.second.cls_.User import java.io.Serializable data class User(var name: String, var name2:String?):Serializable data class User2(var name: String="", var name2:String=""):Serializable interface I{ fun a() } fun main(args: Array<String>) { val user = User("name",null) val toJson = GsonUtils.toJson(user) val fromJson = GsonUtils.fromJson(toJson, User2::class.java) println() var a= create() var b= create() println() } private fun create(): I { return object : I { override fun a() { } } }
epl-1.0
4f5586fb66c9b25f3a43f06fab838c75
20.448276
71
0.661836
3.356757
false
false
false
false
kpspemu/kpspemu
src/commonMain/kotlin/com/soywiz/kpspemu/hle/modules/ModuleMgrForUser.kt
1
5487
package com.soywiz.kpspemu.hle.modules import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.hle.* import com.soywiz.kpspemu.mem.* import com.soywiz.krypto.encoding.* @Suppress("MemberVisibilityCanPrivate", "UNUSED_PARAMETER") class ModuleMgrForUser(emulator: Emulator) : SceModule(emulator, "ModuleMgrForUser", 0x40010011, "modulemgr.prx", "sceModuleManager") { fun sceKernelLoadModule(path: String, flags: Int, sceKernelLMOption: Ptr): Int { logger.error { "Not implemented sceKernelLoadModule: $path" } return 0x08900000 // Module address } fun sceKernelStartModule( moduleId: Int, argumentSize: Int, argumentPointer: Ptr, status: Ptr, sceKernelSMOption: Ptr ): Int { logger.error { "Not implemented sceKernelStartModule: $moduleId" } return 0 } fun sceKernelGetModuleIdByAddress(addr: Int): Int { logger.error { "Not implemented sceKernelGetModuleIdByAddress: ${addr.hex}" } return 2 } fun sceKernelGetModuleId(): Int { logger.error { "Not implemented sceKernelGetModuleId" } return 1 } fun sceKernelLoadModuleBufferMs(cpu: CpuState): Unit = UNIMPLEMENTED(0x1196472E) fun sceKernelLoadModuleBufferApp(cpu: CpuState): Unit = UNIMPLEMENTED(0x24EC0641) fun sceKernelUnloadModule(cpu: CpuState): Unit = UNIMPLEMENTED(0x2E0911AA) fun sceKernelGetModuleIdList(cpu: CpuState): Unit = UNIMPLEMENTED(0x644395E2) fun sceKernelLoadModuleMs(cpu: CpuState): Unit = UNIMPLEMENTED(0x710F61B5) fun sceKernelQueryModuleInfo(cpu: CpuState): Unit = UNIMPLEMENTED(0x748CBED9) fun ModuleMgrForUser_8F2DF740(cpu: CpuState): Unit = UNIMPLEMENTED(0x8F2DF740) fun sceKernelLoadModuleByID(cpu: CpuState): Unit = UNIMPLEMENTED(0xB7F46618) fun sceKernelStopUnloadSelfModule(cpu: CpuState): Unit = UNIMPLEMENTED(0xCC1D3699) fun sceKernelStopModule(cpu: CpuState): Unit = UNIMPLEMENTED(0xD1FF982A) fun sceKernelGetModuleGPByAddress(cpu: CpuState): Unit = UNIMPLEMENTED(0xD2FBC957) fun sceKernelSelfStopUnloadModule(cpu: CpuState): Unit = UNIMPLEMENTED(0xD675EBB8) fun ModuleMgrForUser_E4C4211C(cpu: CpuState): Unit = UNIMPLEMENTED(0xE4C4211C) fun ModuleMgrForUser_F2D8D1B4(cpu: CpuState): Unit = UNIMPLEMENTED(0xF2D8D1B4) fun sceKernelLoadModuleBufferUsbWlan(cpu: CpuState): Unit = UNIMPLEMENTED(0xF9275D98) fun ModuleMgrForUser_FBE27467(cpu: CpuState): Unit = UNIMPLEMENTED(0xFBE27467) fun ModuleMgrForUser_FEF27DC1(cpu: CpuState): Unit = UNIMPLEMENTED(0xFEF27DC1) override fun registerModule() { registerFunctionInt("sceKernelLoadModule", 0x977DE386, since = 150) { sceKernelLoadModule(istr, int, ptr) } registerFunctionInt("sceKernelStartModule", 0x50F0C1EC, since = 150) { sceKernelStartModule( int, int, ptr, ptr, ptr ) } registerFunctionInt("sceKernelGetModuleIdByAddress", 0xD8B73127, since = 150) { sceKernelGetModuleIdByAddress( int ) } registerFunctionInt("sceKernelGetModuleId", 0xF0A26395, since = 150) { sceKernelGetModuleId() } registerFunctionRaw("sceKernelLoadModuleBufferMs", 0x1196472E, since = 150) { sceKernelLoadModuleBufferMs(it) } registerFunctionRaw( "sceKernelLoadModuleBufferApp", 0x24EC0641, since = 150 ) { sceKernelLoadModuleBufferApp(it) } registerFunctionRaw("sceKernelUnloadModule", 0x2E0911AA, since = 150) { sceKernelUnloadModule(it) } registerFunctionRaw("sceKernelGetModuleIdList", 0x644395E2, since = 150) { sceKernelGetModuleIdList(it) } registerFunctionRaw("sceKernelLoadModuleMs", 0x710F61B5, since = 150) { sceKernelLoadModuleMs(it) } registerFunctionRaw("sceKernelQueryModuleInfo", 0x748CBED9, since = 150) { sceKernelQueryModuleInfo(it) } registerFunctionRaw("ModuleMgrForUser_8F2DF740", 0x8F2DF740, since = 150) { ModuleMgrForUser_8F2DF740(it) } registerFunctionRaw("sceKernelLoadModuleByID", 0xB7F46618, since = 150) { sceKernelLoadModuleByID(it) } registerFunctionRaw( "sceKernelStopUnloadSelfModule", 0xCC1D3699, since = 150 ) { sceKernelStopUnloadSelfModule(it) } registerFunctionRaw("sceKernelStopModule", 0xD1FF982A, since = 150) { sceKernelStopModule(it) } registerFunctionRaw( "sceKernelGetModuleGPByAddress", 0xD2FBC957, since = 150 ) { sceKernelGetModuleGPByAddress(it) } registerFunctionRaw( "sceKernelSelfStopUnloadModule", 0xD675EBB8, since = 150 ) { sceKernelSelfStopUnloadModule(it) } registerFunctionRaw("ModuleMgrForUser_E4C4211C", 0xE4C4211C, since = 150) { ModuleMgrForUser_E4C4211C(it) } registerFunctionRaw("ModuleMgrForUser_F2D8D1B4", 0xF2D8D1B4, since = 150) { ModuleMgrForUser_F2D8D1B4(it) } registerFunctionRaw( "sceKernelLoadModuleBufferUsbWlan", 0xF9275D98, since = 150 ) { sceKernelLoadModuleBufferUsbWlan(it) } registerFunctionRaw("ModuleMgrForUser_FBE27467", 0xFBE27467, since = 150) { ModuleMgrForUser_FBE27467(it) } registerFunctionRaw("ModuleMgrForUser_FEF27DC1", 0xFEF27DC1, since = 150) { ModuleMgrForUser_FEF27DC1(it) } } }
mit
cf524e64edb1cf6408fdaf8b23bc948c
47.557522
119
0.695826
3.905338
false
false
false
false
myunusov/sofarc
sofarc-core/src/main/kotlin/org/maxur/sofarc/core/service/grizzly/CLStaticHttpHandler.kt
1
16966
package org.maxur.sofarc.core.service.grizzly /** * @author myunusov * @version 1.0 * @since <pre>20.06.2017</pre> */ import org.glassfish.grizzly.Buffer import org.glassfish.grizzly.Grizzly import org.glassfish.grizzly.WriteHandler import org.glassfish.grizzly.http.Method import org.glassfish.grizzly.http.io.NIOOutputStream import org.glassfish.grizzly.http.server.HttpHandler import org.glassfish.grizzly.http.server.Request import org.glassfish.grizzly.http.server.Response import org.glassfish.grizzly.http.server.StaticHttpHandlerBase import org.glassfish.grizzly.http.util.Header import org.glassfish.grizzly.http.util.HttpStatus import org.glassfish.grizzly.memory.MemoryManager import org.glassfish.grizzly.utils.ArraySet import org.maxur.sofarc.core.service.grizzly.config.StaticContent import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.io.InputStream import java.net.* import java.util.jar.JarEntry import java.util.jar.JarFile import java.util.logging.Level /** * [HttpHandler], which processes requests to a static resources resolved * by a given [ClassLoader]. * * Create <tt>HttpHandler</tt>, which will handle requests * to the static resources resolved by the given class loader. * * @param classLoader [ClassLoader] to be used to resolve the resources * @param staticContent is the static content configuration * * @author Grizzly Team * @author Maxim Yunusov */ class CLStaticHttpHandler(val classLoader: ClassLoader, staticContent: StaticContent) : AbstractStaticHttpHandler() { // path prefixes to be used private val docRoots = ArraySet(String::class.java) /** * default page */ private val defaultPage: String /** * This staticContent is the static content configuration * with * the root(s) - the doc roots (path prefixes), which will be used * to find resources. Effectively each docRoot will be prepended * to a resource path before passing it to [ClassLoader.getResource]. * If no <tt>docRoots</tt> are set - the resources will be searched starting * from [ClassLoader]'s root. * the path - url related to base url * and default page (index.html by default) * If the <tt>root</tt> is <tt>null</tt> - static pages won't be served by this <tt>HttpHandler</tt> * * IllegalArgumentException if one of the docRoots doesn't end with slash ('/') */ init { defaultPage = staticContent.page val docRoots = staticContent.roots if (docRoots.any({ !it.endsWith("/") })) { throw IllegalArgumentException("Doc root should end with slash ('/')") } if (docRoots.isNotEmpty()) { this.docRoots.addAll(*docRoots) } else { this.docRoots.add("/") } } /** * {@inheritDoc} */ @Throws(Exception::class) override fun handle(resourcePath: String, request: Request, response: Response): Boolean { var path = resourcePath if (path.startsWith(SLASH_STR)) { path = path.substring(1) } val mayBeFolder: Boolean var url: URL? if (path.isEmpty() || path.endsWith("/")) { path += defaultPage mayBeFolder = false url = lookupResource(path) } else { url = lookupResource(path) if (url == null && CHECK_NON_SLASH_TERMINATED_FOLDERS) { // So try to add index.html to double-check. // For example null will be returned for a folder inside a jar file. url = lookupResource("$path/$defaultPage") // some ClassLoaders return null if a URL points to a folder. mayBeFolder = false } else { mayBeFolder = true } } if (url == null) { fine("Resource not found $path") return false } // url may point to a folder or a file if ("file" == url.protocol) { return onFile(url, request, response, path) } else { return onNotFile(url, mayBeFolder, path, request, response) } } private fun onNotFile(url: URL, mayBeFolder: Boolean, path: String, request: Request, response: Response): Boolean { var url1 = url var urlInputStream: InputStream? = null var found = false var urlConnection: URLConnection? = url1.openConnection() var filePath: String? = null if ("jar" == url1.protocol) { val jarUrlConnection = urlConnection as JarURLConnection? var jarEntry: JarEntry? = jarUrlConnection!!.jarEntry val jarFile = jarUrlConnection.jarFile // check if this is not a folder // we can't rely on jarEntry.isDirectory() because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6233323 var iinputStream: InputStream? = jarFile.getInputStream(jarEntry) if (jarEntry!!.isDirectory || iinputStream == null) { // it's probably a folder val welcomeResource = if (jarEntry.name.endsWith("/")) "${jarEntry.name}$defaultPage" else "${jarEntry.name}/$defaultPage" jarEntry = jarFile.getJarEntry(welcomeResource) if (jarEntry != null) { iinputStream = jarFile.getInputStream(jarEntry) } } if (iinputStream != null) { urlInputStream = JarURLInputStream(jarUrlConnection, jarFile, iinputStream) assert(jarEntry != null) filePath = jarEntry!!.name found = true } else { closeJarFileIfNeeded(jarUrlConnection, jarFile) } } else if ("bundle" == url1.protocol) { // OSGi resource // it might be either folder or file if (mayBeFolder && urlConnection!!.contentLength <= 0) { // looks like a folder? // check if there's a welcome resource val welcomeUrl = classLoader.getResource("${url1.path}/$defaultPage") if (welcomeUrl != null) { url1 = welcomeUrl urlConnection = welcomeUrl.openConnection() } } found = true } else { found = true } if (!found) { fine("Resource not found $path") return false } // If it's not HTTP GET - return method is not supported status if (Method.GET != request.method) { returnMethodIsNotAllowed(path, request, response) return true } pickupContentType(response, if (filePath != null) filePath else url1.path) assert(urlConnection != null) // if it's not a jar file - we don't know what to do with that // so not adding it to the file cache if ("jar" == url1.protocol) { val jarFile = getJarFile( // we need that because url.getPath() may have url encoded symbols, // which are getting decoded when calling uri.getPath() URI(url1.path).path ) addTimeStampEntryToFileCache(request, response, jarFile) } sendResource(response, if (urlInputStream != null) urlInputStream else urlConnection!!.getInputStream()) return true } private fun onFile(url: URL, request: Request, response: Response, path: String): Boolean { val result: File? = respondedFile(url) if (result != null) { processFile(request, result, response) return true } else { fine("Resource not found $path") return false } } private fun respondedFile(url: URL): File? { val file = File(url.toURI()) if (file.exists()) { if (file.isDirectory) { val welcomeFile = File(file, "/$defaultPage") if (welcomeFile.exists() && welcomeFile.isFile) { return welcomeFile } } else { return file } } return null } private fun lookupResource(resourcePath: String): URL? { val docRootsLocal = docRoots.array if (docRootsLocal == null || docRootsLocal.isEmpty()) { fine("No doc roots registered -> resource $resourcePath is not found ") return null } for (docRoot in docRootsLocal) { val docRootPart: String when { SLASH_STR == docRoot -> docRootPart = EMPTY_STR docRoot.startsWith(SLASH_STR) -> docRootPart = docRoot.substring(1) else -> docRootPart = docRoot } val fullPath = docRootPart + resourcePath val url = classLoader.getResource(fullPath) if (url != null) { return url } } return null } private fun addTimeStampEntryToFileCache(req: Request, res: Response?, archive: File): Boolean { if (isFileCacheEnabled) { val fcContext = req.context val fileCacheFilter = lookupFileCache(fcContext) if (fileCacheFilter != null) { val fileCache = fileCacheFilter.fileCache if (fileCache.isEnabled) { if (res != null) { StaticHttpHandlerBase.addCachingHeaders(res, archive) } fileCache.add(req.request, archive.lastModified()) return true } } } return false } @Throws(MalformedURLException::class, FileNotFoundException::class) private fun getJarFile(path: String): File { val jarDelimIdx = path.indexOf("!/") if (jarDelimIdx == -1) { throw MalformedURLException("The jar file delimeter were not found") } val file = File(path.substring(0, jarDelimIdx)) if (!file.exists() || !file.isFile) { throw FileNotFoundException("The jar file was not found") } return file } private class NonBlockingDownloadHandler internal constructor(private val response: Response, private val outputStream: NIOOutputStream, private val inputStream: InputStream, private val chunkSize: Int ) : WriteHandler { companion object { private val log = Grizzly.logger(NonBlockingDownloadHandler::class.java) } private val mm: MemoryManager<*> init { mm = response.request.context.memoryManager } @Throws(Exception::class) override fun onWritePossible() { log.log(Level.FINE, "[onWritePossible]") // send CHUNK of data val isWriteMore = sendChunk() if (isWriteMore) { // if there are more bytes to be sent - reregister this WriteHandler outputStream.notifyCanWrite(this) } } override fun onError(t: Throwable) { log.log(Level.FINE, "[onError] ", t) response.setStatus(500, t.message) complete(true) } /** * Send next CHUNK_SIZE of file */ @Throws(IOException::class) private fun sendChunk(): Boolean { // allocate Buffer var buffer: Buffer? = null if (!mm.willAllocateDirect(chunkSize)) { buffer = mm.allocate(chunkSize) val len: Int if (!buffer!!.isComposite) { len = inputStream.read(buffer.array(), buffer.position() + buffer.arrayOffset(), chunkSize) } else { val bufferArray = buffer.toBufferArray() val size = bufferArray.size() val buffers = bufferArray.array var lenCounter = 0 for (i in 0..size - 1) { val subBuffer = buffers[i] val subBufferLen = subBuffer.remaining() val justReadLen = inputStream.read(subBuffer.array(), subBuffer.position() + subBuffer.arrayOffset(), subBufferLen) if (justReadLen > 0) { lenCounter += justReadLen } if (justReadLen < subBufferLen) { break } } bufferArray.restore() bufferArray.recycle() len = if (lenCounter > 0) lenCounter else -1 } if (len > 0) { buffer.position(buffer.position() + len) } else { buffer.dispose() buffer = null } } else { val buf = ByteArray(chunkSize) val len = inputStream.read(buf) if (len > 0) { buffer = mm.allocate(len) buffer!!.put(buf) } } if (buffer == null) { complete(false) return false } // mark it available for disposal after content is written buffer.allowBufferDispose(true) buffer.trim() // write the Buffer outputStream.write(buffer) return true } /** * Complete the download */ private fun complete(isError: Boolean) { try { inputStream.close() } catch (e: IOException) { if (!isError) { response.setStatus(500, e.message) } } try { outputStream.close() } catch (e: IOException) { if (!isError) { response.setStatus(500, e.message) } } if (response.isSuspended) { response.resume() } else { response.finish() } } } internal class JarURLInputStream(private val jarConnection: JarURLConnection, private val jarFile: JarFile, src: InputStream) : java.io.FilterInputStream(src) { @Throws(IOException::class) override fun close() { try { super.close() } finally { closeJarFileIfNeeded(jarConnection, jarFile) } } } companion object { protected val CHECK_NON_SLASH_TERMINATED_FOLDERS_PROP = CLStaticHttpHandler::class.java.name + ".check-non-slash-terminated-folders" /** * <tt>true</tt> (default) if we want to double-check the resource requests, * that don't have terminating slash if they represent a folder and try * to retrieve a welcome resource from the folder. */ private val CHECK_NON_SLASH_TERMINATED_FOLDERS = System.getProperty(CHECK_NON_SLASH_TERMINATED_FOLDERS_PROP) == null || java.lang.Boolean.getBoolean(CHECK_NON_SLASH_TERMINATED_FOLDERS_PROP) private val SLASH_STR = "/" private val EMPTY_STR = "" @Throws(IOException::class) private fun sendResource(response: Response, input: InputStream) { response.setStatus(HttpStatus.OK_200) response.addDateHeader(Header.Date, System.currentTimeMillis()) val chunkSize = 8192 response.suspend() val outputStream = response.nioOutputStream outputStream.notifyCanWrite( NonBlockingDownloadHandler(response, outputStream, input, chunkSize)) } @Throws(IOException::class) private fun closeJarFileIfNeeded(jarConnection: JarURLConnection, jarFile: JarFile) { if (!jarConnection.useCaches) { jarFile.close() } } } }
apache-2.0
392a1bec34d77cf4e9bbc1ac966e497a
33.34413
124
0.532712
5.010632
false
false
false
false
terracotta-ko/Android_Treasure_House
MVP/system/user_database/src/main/java/com/ko/user_database/User.kt
1
632
package com.ko.user_database import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey internal const val TABLE_NAME = "users_table" private const val COLUMN_USER_ID = "column_user_id" private const val COLUMN_USER_NAME = "column_user_name" private const val COLUMN_USER_IS_VERIFIED = "column_user_is_verified" @Entity(tableName = TABLE_NAME) internal data class User( @PrimaryKey @ColumnInfo(name = COLUMN_USER_ID) val userId: Long, @ColumnInfo(name = COLUMN_USER_NAME) val userName: String, @ColumnInfo(name = COLUMN_USER_IS_VERIFIED) val isVerified: Boolean )
mit
5648d53bbd7c547a3d015be95ad27f7c
24.28
69
0.742089
3.550562
false
false
false
false
xwiki-contrib/android-authenticator
app/src/main/java/org/xwiki/android/sync/activities/OIDC/OIDCAccountAdapter.kt
1
1847
package org.xwiki.android.sync.activities.OIDC import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.LinearLayout import android.widget.TextView import org.xwiki.android.sync.R import org.xwiki.android.sync.contactdb.UserAccount import org.xwiki.android.sync.utils.AccountClickListener class OIDCAccountAdapter ( private val mContext: Context, private var availableAccounts : List<UserAccount>, private val listener : AccountClickListener ) : BaseAdapter() { override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View { val view = convertView ?:let { val inflater = LayoutInflater.from(mContext) inflater.inflate(R.layout.oidc_account_list_layout, null) } val viewHolder = AccountListViewHolder(view) view.tag = viewHolder val account = getItem(position) viewHolder.tvOIDCAccountName.text = account.accountName viewHolder.tvOIDCAccountServerAddress.text = account.serverAddress viewHolder.llOIDCAccountItem.setOnClickListener { listener(account) } return view } override fun getItem(position: Int): UserAccount { return availableAccounts[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun getCount(): Int { return availableAccounts.size } } private class AccountListViewHolder (view: View) { val tvOIDCAccountName : TextView = view.findViewById(R.id.tvOIDCAccountName) val llOIDCAccountItem : LinearLayout = view.findViewById(R.id.llOIDCAccountItem) val tvOIDCAccountServerAddress: TextView = view.findViewById(R.id.tvOIDCAccountServerAddress) }
lgpl-2.1
dbf500fdd41725d3bc3edfffd8e05ae2
30.862069
97
0.730915
4.6175
false
false
false
false
wizardofos/Protozoo
extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/Alias.kt
1
4090
package org.jetbrains.exposed.sql import java.lang.UnsupportedOperationException class Alias<out T:Table>(val delegate: T, val alias: String) : Table() { override val tableName: String get() = alias val tableNameWithAlias: String = "${delegate.tableName} AS $alias" private fun <T:Any?> Column<T>.clone() = Column<T>(this@Alias, name, columnType) override val columns: List<Column<*>> = delegate.columns.map { it.clone() } override val fields: List<Expression<*>> = columns override fun createStatement() = throw UnsupportedOperationException("Unsupported for aliases") override fun dropStatement() = throw UnsupportedOperationException("Unsupported for aliases") override fun modifyStatement() = throw UnsupportedOperationException("Unsupported for aliases") override fun equals(other: Any?): Boolean { if (other !is Alias<*>) return false return this.tableNameWithAlias == other.tableNameWithAlias } override fun hashCode(): Int = tableNameWithAlias.hashCode() @Suppress("UNCHECKED_CAST") operator fun <T: Any?> get(original: Column<T>): Column<T> = delegate.columns.find { it == original }?.let { it.clone() as? Column<T> } ?: error("Column not found in original table") } class ExpressionAlias<out T: Any?>(val delegate: Expression<T>, val alias: String) : Expression<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = "${delegate.toSQL(queryBuilder)} $alias" fun aliasOnlyExpression() = object: Expression<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = alias } } class QueryAlias(val query: Query, val alias: String): ColumnSet() { override fun describe(s: Transaction): String = "(${query.prepareSQL(QueryBuilder(false))}) $alias" override val columns: List<Column<*>> get() = query.set.source.columns.filter { it in query.set.fields }.map { it.clone() } private fun <T:Any?> Column<T>.clone() = Column<T>(table.alias(alias), name, columnType) @Suppress("UNCHECKED_CAST") operator fun <T: Any?> get(original: Column<T>): Column<T> = query.set.source.columns.find { it == original }?. let { it.clone() as? Column<T> } ?: error("Column not found in original table") @Suppress("UNCHECKED_CAST") operator fun <T: Any?> get(original: Expression<T>): Expression<T> = (query.set.fields.find { it == original } as? ExpressionAlias<T>)?.aliasOnlyExpression() ?: error("Field not found in original table fields") override fun join(otherTable: ColumnSet, joinType: JoinType, onColumn: Expression<*>?, otherColumn: Expression<*>?, additionalConstraint: (SqlExpressionBuilder.()->Op<Boolean>)? ) : Join = Join (this, otherTable, joinType, onColumn, otherColumn, additionalConstraint) override infix fun innerJoin(otherTable: ColumnSet) : Join = Join (this, otherTable, JoinType.INNER) override infix fun leftJoin(otherTable: ColumnSet) : Join = Join (this, otherTable, JoinType.LEFT) override infix fun crossJoin(otherTable: ColumnSet) : Join = Join (this, otherTable, JoinType.CROSS) } fun <T:Table> T.alias(alias: String) = Alias(this, alias) fun <T:Query> T.alias(alias: String) = QueryAlias(this, alias) fun <T:Expression<*>> T.alias(alias: String) = ExpressionAlias(this, alias) fun Join.joinQuery(on: (SqlExpressionBuilder.(QueryAlias)->Op<Boolean>), joinType: JoinType = JoinType.INNER, joinPart: () -> Query): Join { val qAlias = joinPart().alias("q${joinParts.count { it.joinPart is QueryAlias }}") return join (qAlias, joinType, additionalConstraint = { on(qAlias) } ) } fun Table.joinQuery(on: (SqlExpressionBuilder.(QueryAlias)->Op<Boolean>), joinType: JoinType = JoinType.INNER, joinPart: () -> Query) = Join(this).joinQuery(on, joinType, joinPart) val Join.lastQueryAlias: QueryAlias? get() = joinParts.map { it.joinPart as? QueryAlias }.firstOrNull() fun <T:Any> wrapAsExpression(query: Query) = object : Expression<T>() { override fun toSQL(queryBuilder: QueryBuilder): String = "(" + query.prepareSQL(queryBuilder) + ")" }
mit
5b2cc91bbdefc47aca8a7129cc18cdc1
45.488636
192
0.699756
3.917625
false
false
false
false
prgpascal/android-qr-data-transfer
android-qr-data-transfer/src/main/java/com/prgpascal/qrdatatransfer/utils/Utils.kt
1
5007
/* * Copyright (C) 2016 Riccardo Leschiutta * * 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.prgpascal.qrdatatransfer.utils import android.app.Activity import android.content.Context import android.content.pm.ActivityInfo import android.content.res.Configuration import android.graphics.Bitmap import android.view.Surface import android.view.WindowManager import com.google.zxing.BarcodeFormat import com.google.zxing.EncodeHintType import com.google.zxing.MultiFormatWriter import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel import java.io.UnsupportedEncodingException import java.security.MessageDigest import java.security.NoSuchAlgorithmException import java.security.SecureRandom import java.util.* const val WHITE = -0x1 const val BLACK = -0x1000000 const val CHARACTER_SET_EXPANDED = "ISO-8859-1" const val CHARACTER_SET = "ISO8859_1" const val SHA_ALGORITHM = "SHA-256" val T_UUID: UUID = UUID.fromString("974e8deb-2232-40fd-b56c-7a4c9b298248") const val TAG_EOT = "OTP_EOT" // End Of Transmission message const val DIGEST_LENGTH = 32 // Number of bytes (characters) of the digest const val ACK_LENGTH = 2 // Number of bytes of the ACK fun encodeAsBitmap(width: Int, height: Int, message: String): Bitmap { try { val hints: MutableMap<EncodeHintType, Any?> = EnumMap<EncodeHintType, Any>(EncodeHintType::class.java) hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H // high correction level hints[EncodeHintType.CHARACTER_SET] = CHARACTER_SET val result = MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, width, height, hints) val w = result.width val h = result.height val pixels = IntArray(w * h) for (y in 0 until h) { val offset = y * w for (x in 0 until w) { pixels[offset + x] = if (result[x, y]) BLACK else WHITE } } val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) bitmap.setPixels(pixels, 0, w, 0, 0, w, h) return bitmap } catch (e: Exception) { throw EncodeException(e) } } fun calculateDigest(message: String): String? { try { val sha256 = MessageDigest.getInstance(SHA_ALGORITHM) val messageBytes = message.toByteArray(charset(CHARACTER_SET_EXPANDED)) val hash = sha256.digest(messageBytes) return encodeISO88591(hash) } catch (ue: UnsupportedEncodingException) { ue.printStackTrace() } catch (e: NoSuchAlgorithmException) { e.printStackTrace() } return null } fun encodeISO88591(bytes: ByteArray?): String? { try { return String(bytes!!, charset(CHARACTER_SET_EXPANDED)) } catch (e: UnsupportedEncodingException) { e.printStackTrace() } return null } fun getAckFromMessage(message: String): String { return message.substring(0, ACK_LENGTH) } fun getDigestFromMessage(message: String): String { return message.substring(message.length - DIGEST_LENGTH) } fun getContentFromMessage(message: String): String { return message.substring(ACK_LENGTH, message.length - DIGEST_LENGTH) } fun createRandomString(numberOfBytes: Int): String? { val random = SecureRandom() val bytes = ByteArray(numberOfBytes) random.nextBytes(bytes) return encodeISO88591(bytes) } fun preventScreenRotation(context: Activity) { context.requestedOrientation = currentScreenOrientation(context) } private fun currentScreenOrientation(context: Context): Int { val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager return when (context.resources.configuration.orientation) { Configuration.ORIENTATION_PORTRAIT -> { val rotation = windowManager.defaultDisplay.rotation if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_180) { ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT } else { ActivityInfo.SCREEN_ORIENTATION_PORTRAIT } } Configuration.ORIENTATION_LANDSCAPE -> { val rotation = windowManager.defaultDisplay.rotation if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_90) { ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE } else { ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE } } else -> ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED } }
apache-2.0
9e6131524536e238acfb9de299d8c53e
34.771429
110
0.699621
4.196982
false
false
false
false
commons-app/apps-android-commons
app/src/main/java/fr/free/nrw/commons/customselector/ui/adapter/ImageAdapter.kt
2
18126
package fr.free.nrw.commons.customselector.ui.adapter import android.content.Context import android.content.SharedPreferences import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.constraintlayout.widget.Group import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView import fr.free.nrw.commons.R import fr.free.nrw.commons.customselector.helper.ImageHelper import fr.free.nrw.commons.customselector.helper.ImageHelper.CUSTOM_SELECTOR_PREFERENCE_KEY import fr.free.nrw.commons.customselector.helper.ImageHelper.SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY import fr.free.nrw.commons.customselector.listeners.ImageSelectListener import fr.free.nrw.commons.customselector.model.Image import fr.free.nrw.commons.customselector.ui.selector.ImageLoader import kotlinx.coroutines.* import java.util.* import kotlin.collections.ArrayList /** * Custom selector ImageAdapter. */ class ImageAdapter( /** * Application Context. */ context: Context, /** * Image select listener for click events on image. */ private var imageSelectListener: ImageSelectListener, /** * ImageLoader queries images. */ private var imageLoader: ImageLoader ): RecyclerViewAdapter<ImageAdapter.ImageViewHolder>(context), FastScrollRecyclerView.SectionedAdapter { /** * ImageSelectedOrUpdated payload class. */ class ImageSelectedOrUpdated /** * ImageUnselected payload class. */ class ImageUnselected /** * Determines whether addition of all actionable images is done or not */ private var reachedEndOfFolder: Boolean = false /** * Currently selected images. */ private var selectedImages = arrayListOf<Image>() /** * Number of selected images that are marked as not for upload */ private var numberOfSelectedImagesMarkedAsNotForUpload = 0 /** * List of all images in adapter. */ private var images: ArrayList<Image> = ArrayList() /** * Stores all images */ private var allImages: List<Image> = ArrayList() /** * Map to store actionable images */ private var actionableImagesMap: TreeMap<Int, Image> = TreeMap() /** * Stores already added positions of actionable images */ private var alreadyAddedPositions: ArrayList<Int> = ArrayList() /** * Next starting index to initiate query to find next actionable image */ private var nextImagePosition = 0 /** * Helps to maintain the increasing sequence of the position. eg- 0, 1, 2, 3 */ private var imagePositionAsPerIncreasingOrder = 0 /** * Coroutine Dispatchers and Scope. */ private var defaultDispatcher : CoroutineDispatcher = Dispatchers.Default private var ioDispatcher : CoroutineDispatcher = Dispatchers.IO private val scope : CoroutineScope = MainScope() /** * Create View holder. */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder { val itemView = inflater.inflate(R.layout.item_custom_selector_image, parent, false) return ImageViewHolder(itemView) } /** * Bind View holder, load image, selected view, click listeners. */ override fun onBindViewHolder(holder: ImageViewHolder, position: Int) { var image=images[position] holder.image.setImageDrawable (null) if (context.contentResolver.getType(image.uri) == null) { // Image does not exist anymore, update adapter. holder.itemView.post { val updatedPosition = images.indexOf(image) images.remove(image) notifyItemRemoved(updatedPosition) notifyItemRangeChanged(updatedPosition, images.size) } } else { val sharedPreferences: SharedPreferences = context.getSharedPreferences(CUSTOM_SELECTOR_PREFERENCE_KEY, 0) val showAlreadyActionedImages = sharedPreferences.getBoolean(SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY, true) // Getting selected index when switch is on val selectedIndex: Int = if (showAlreadyActionedImages) { ImageHelper.getIndex(selectedImages, image) // Getting selected index when switch is off } else if (actionableImagesMap.size > position) { ImageHelper .getIndex(selectedImages, ArrayList(actionableImagesMap.values)[position]) // For any other case return -1 } else { -1 } val isSelected = selectedIndex != -1 if (isSelected) { holder.itemSelected(selectedImages.size) } else { holder.itemUnselected() } imageLoader.queryAndSetView( holder, image, ioDispatcher, defaultDispatcher ) scope.launch { val sharedPreferences: SharedPreferences = context.getSharedPreferences(CUSTOM_SELECTOR_PREFERENCE_KEY, 0) val showAlreadyActionedImages = sharedPreferences.getBoolean(SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY, true) if (!showAlreadyActionedImages) { // If the position is not already visited, that means the position is new then // finds the next actionable image position from all images if (!alreadyAddedPositions.contains(position)) { processThumbnailForActionedImage(holder, position) // If the position is already visited, that means the image is already present // inside map, so it will fetch the image from the map and load in the holder } else { val actionableImages: List<Image> = ArrayList(actionableImagesMap.values) image = actionableImages[position] Glide.with(holder.image).load(image.uri) .thumbnail(0.3f).into(holder.image) } // If switch is turned off, it just fetches the image from all images without any // further operations } else { Glide.with(holder.image).load(image.uri) .thumbnail(0.3f).into(holder.image) } } holder.itemView.setOnClickListener { onThumbnailClicked(position, holder) } // launch media preview on long click. holder.itemView.setOnLongClickListener { imageSelectListener.onLongPress(images.indexOf(image), images, selectedImages) true } } } /** * Process thumbnail for actioned image */ suspend fun processThumbnailForActionedImage( holder: ImageViewHolder, position: Int ) { val next = imageLoader.nextActionableImage( allImages, ioDispatcher, defaultDispatcher, nextImagePosition ) // If next actionable image is found, saves it, as the the search for // finding next actionable image will start from this position if (next > -1) { nextImagePosition = next + 1 // If map doesn't contains the next actionable image, that means it's a // new actionable image, it will put it to the map as actionable images // and it will load the new image in the view holder if (!actionableImagesMap.containsKey(next)) { actionableImagesMap[next] = allImages[next] alreadyAddedPositions.add(imagePositionAsPerIncreasingOrder) imagePositionAsPerIncreasingOrder++ Glide.with(holder.image).load(allImages[next].uri) .thumbnail(0.3f).into(holder.image) notifyItemInserted(position) notifyItemRangeChanged(position, itemCount + 1) } // If next actionable image is not found, that means searching is // complete till end, and it will stop searching. } else { reachedEndOfFolder = true notifyItemRemoved(position) } } /** * Handles click on thumbnail */ private fun onThumbnailClicked( position: Int, holder: ImageViewHolder ) { val sharedPreferences: SharedPreferences = context.getSharedPreferences(CUSTOM_SELECTOR_PREFERENCE_KEY, 0) val switchState = sharedPreferences.getBoolean(SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY, true) // While switch is turned off, lets user click on image only if the position is // added inside map if (!switchState) { if (actionableImagesMap.size > position) { selectOrRemoveImage(holder, position) } } else { selectOrRemoveImage(holder, position) } } /** * Handle click event on an image, update counter on images. */ private fun selectOrRemoveImage(holder: ImageViewHolder, position: Int){ val sharedPreferences: SharedPreferences = context.getSharedPreferences(CUSTOM_SELECTOR_PREFERENCE_KEY, 0) val showAlreadyActionedImages = sharedPreferences.getBoolean(SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY, true) // Getting clicked index from all images index when show_already_actioned_images // switch is on val clickedIndex: Int = if(showAlreadyActionedImages) { ImageHelper.getIndex(selectedImages, images[position]) // Getting clicked index from actionable images when show_already_actioned_images // switch is off } else { ImageHelper.getIndex(selectedImages, ArrayList(actionableImagesMap.values)[position]) } if (clickedIndex != -1) { selectedImages.removeAt(clickedIndex) if (holder.isItemNotForUpload()) { numberOfSelectedImagesMarkedAsNotForUpload-- } notifyItemChanged(position, ImageUnselected()) // Getting index from all images index when switch is on val indexes = if (showAlreadyActionedImages) { ImageHelper.getIndexList(selectedImages, images) // Getting index from actionable images when switch is off } else { ImageHelper.getIndexList(selectedImages, ArrayList(actionableImagesMap.values)) } for (index in indexes) { notifyItemChanged(index, ImageSelectedOrUpdated()) } } else { if (holder.isItemUploaded()) { Toast.makeText(context, R.string.custom_selector_already_uploaded_image_text, Toast.LENGTH_SHORT).show() } else { if (holder.isItemNotForUpload()) { numberOfSelectedImagesMarkedAsNotForUpload++ } // Getting index from all images index when switch is on val indexes: ArrayList<Int> = if (showAlreadyActionedImages) { selectedImages.add(images[position]) ImageHelper.getIndexList(selectedImages, images) // Getting index from actionable images when switch is off } else { selectedImages.add(ArrayList(actionableImagesMap.values)[position]) ImageHelper.getIndexList(selectedImages, ArrayList(actionableImagesMap.values)) } for (index in indexes) { notifyItemChanged(index, ImageSelectedOrUpdated()) } } } imageSelectListener.onSelectedImagesChanged(selectedImages, numberOfSelectedImagesMarkedAsNotForUpload) } /** * Initialize the data set. */ fun init(newImages: List<Image>, fixedImages: List<Image>, emptyMap: TreeMap<Int, Image>) { allImages = fixedImages val oldImageList:ArrayList<Image> = images val newImageList:ArrayList<Image> = ArrayList(newImages) actionableImagesMap = emptyMap alreadyAddedPositions = ArrayList() nextImagePosition = 0 reachedEndOfFolder = false selectedImages = ArrayList() imagePositionAsPerIncreasingOrder = 0 val diffResult = DiffUtil.calculateDiff( ImagesDiffCallback(oldImageList, newImageList) ) images = newImageList diffResult.dispatchUpdatesTo(this) } /** * Set new selected images */ fun setSelectedImages(newSelectedImages: ArrayList<Image>){ selectedImages = ArrayList(newSelectedImages) imageSelectListener.onSelectedImagesChanged(selectedImages, 0) } /** * Refresh the data in the adapter */ fun refresh(newImages: List<Image>, fixedImages: List<Image>) { numberOfSelectedImagesMarkedAsNotForUpload = 0 selectedImages.clear() images.clear() selectedImages = arrayListOf() init(newImages, fixedImages, TreeMap()) notifyDataSetChanged() } /** * Returns the total number of items in the data set held by the adapter. * * @return The total number of items in this adapter. */ override fun getItemCount(): Int { val sharedPreferences: SharedPreferences = context.getSharedPreferences(CUSTOM_SELECTOR_PREFERENCE_KEY, 0) val showAlreadyActionedImages = sharedPreferences.getBoolean(SHOW_ALREADY_ACTIONED_IMAGES_PREFERENCE_KEY, true) // While switch is on initializes the holder with all images size return if(showAlreadyActionedImages) { allImages.size // While switch is off and searching for next actionable has ended, initializes the holder // with size of all actionable images } else if (actionableImagesMap.size == allImages.size || reachedEndOfFolder) { actionableImagesMap.size // While switch is off, initializes the holder with and extra view holder so that finding // and addition of the next actionable image in the adapter can be continued } else { actionableImagesMap.size + 1 } } fun getImageIdAt(position: Int): Long { return images.get(position).id } /** * CleanUp function. */ fun cleanUp() { scope.cancel() } /** * Image view holder. */ class ImageViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val image: ImageView = itemView.findViewById(R.id.image_thumbnail) private val selectedNumber: TextView = itemView.findViewById(R.id.selected_count) private val uploadedGroup: Group = itemView.findViewById(R.id.uploaded_group) private val notForUploadGroup: Group = itemView.findViewById(R.id.not_for_upload_group) private val selectedGroup: Group = itemView.findViewById(R.id.selected_group) /** * Item selected view. */ fun itemSelected(index: Int) { selectedGroup.visibility = View.VISIBLE selectedNumber.text = index.toString() } /** * Item Unselected view. */ fun itemUnselected() { selectedGroup.visibility = View.GONE } /** * Item Uploaded view. */ fun itemUploaded() { uploadedGroup.visibility = View.VISIBLE } /** * Item is not for upload view */ fun itemNotForUpload() { notForUploadGroup.visibility = View.VISIBLE } fun isItemUploaded():Boolean { return uploadedGroup.visibility == View.VISIBLE } /** * Item is not for upload */ fun isItemNotForUpload():Boolean { return notForUploadGroup.visibility == View.VISIBLE } /** * Item Not Uploaded view. */ fun itemNotUploaded() { uploadedGroup.visibility = View.GONE } /** * Item can be uploaded view */ fun itemForUpload() { notForUploadGroup.visibility = View.GONE } } /** * DiffUtilCallback. */ class ImagesDiffCallback( var oldImageList: ArrayList<Image>, var newImageList: ArrayList<Image> ) : DiffUtil.Callback(){ /** * Returns the size of the old list. */ override fun getOldListSize(): Int { return oldImageList.size } /** * Returns the size of the new list. */ override fun getNewListSize(): Int { return newImageList.size } /** * Called by the DiffUtil to decide whether two object represent the same Item. */ override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return newImageList[newItemPosition].id == oldImageList[oldItemPosition].id } /** * Called by the DiffUtil when it wants to check whether two items have the same data. * DiffUtil uses this information to detect if the contents of an item has changed. */ override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { return oldImageList[oldItemPosition].equals(newImageList[newItemPosition]) } } /** * Returns the text for showing inside the bubble during bubble scroll. */ override fun getSectionName(position: Int): String { return images[position].date } }
apache-2.0
982692a2b60ab4d1e1bea7795fb7a7a5
34.129845
120
0.62049
5.131937
false
false
false
false
quarck/CalendarNotification
app/src/main/java/com/github/quarck/calnotify/eventsstorage/EventsStorageImplV9.kt
1
21179
// // Calendar Notifications Plus // Copyright (C) 2016 Sergey Parshin ([email protected]) // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // package com.github.quarck.calnotify.eventsstorage import android.content.ContentValues import android.content.Context import android.database.Cursor import android.database.SQLException import android.database.sqlite.SQLiteConstraintException import android.database.sqlite.SQLiteDatabase import com.github.quarck.calnotify.Consts import com.github.quarck.calnotify.calendar.* import com.github.quarck.calnotify.logs.DevLog import com.github.quarck.calnotify.utils.detailed //import com.github.quarck.calnotify.logs.Logger import java.util.* @Suppress("VARIABLE_WITH_REDUNDANT_INITIALIZER") class EventsStorageImplV9(val context: Context) : EventsStorageImplInterface { @Suppress("ConvertToStringTemplate") override fun createDb(db: SQLiteDatabase) { val CREATE_PKG_TABLE = "CREATE " + "TABLE $TABLE_NAME " + "( " + "$KEY_CALENDAR_ID INTEGER, " + "$KEY_EVENTID INTEGER, " + "$KEY_ALERT_TIME INTEGER, " + "$KEY_NOTIFICATIONID INTEGER, " + "$KEY_TITLE TEXT, " + "$KEY_DESCRIPTION TEXT, " + "$KEY_START INTEGER, " + "$KEY_END INTEGER, " + "$KEY_INSTANCE_START INTEGER, " + "$KEY_INSTANCE_END INTEGER, " + "$KEY_LOCATION TEXT, " + "$KEY_SNOOZED_UNTIL INTEGER, " + "$KEY_LAST_EVENT_VISIBILITY INTEGER, " + "$KEY_DISPLAY_STATUS INTEGER, " + "$KEY_COLOR INTEGER, " + "$KEY_IS_REPEATING INTEGER, " + "$KEY_ALL_DAY INTEGER, " + "$KEY_EVENT_ORIGIN INTEGER, " + "$KEY_TIME_FIRST_SEEN INTEGER, " + "$KEY_EVENT_STATUS INTEGER, " + "$KEY_EVENT_ATTENDANCE_STATUS INTEGER, " + "$KEY_FLAGS INTEGER, " + "$KEY_RESERVED_INT2 INTEGER, " + "$KEY_RESERVED_INT3 INTEGER, " + "$KEY_RESERVED_INT4 INTEGER, " + "$KEY_RESERVED_INT5 INTEGER, " + "$KEY_RESERVED_INT6 INTEGER, " + "$KEY_RESERVED_INT7 INTEGER, " + "$KEY_RESERVED_INT8 INTEGER, " + "$KEY_RESERVED_STR2 TEXT, " + "PRIMARY KEY ($KEY_EVENTID, $KEY_INSTANCE_START)" + " )" DevLog.debug(LOG_TAG, "Creating DB TABLE using query: " + CREATE_PKG_TABLE) db.execSQL(CREATE_PKG_TABLE) val CREATE_INDEX = "CREATE UNIQUE INDEX $INDEX_NAME ON $TABLE_NAME ($KEY_EVENTID, $KEY_INSTANCE_START)" DevLog.debug(LOG_TAG, "Creating DB INDEX using query: " + CREATE_INDEX) db.execSQL(CREATE_INDEX) } override fun dropAll(db: SQLiteDatabase): Boolean { var ret = false try { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME) db.execSQL("DROP INDEX IF EXISTS " + INDEX_NAME) ret = true } catch (ex: SQLException) { DevLog.error(LOG_TAG, "dropAll: ${ex.detailed}") } // if (!ret) { // DevLog.debug(LOG_TAG, "debug_me_here"); // } return ret } override fun addEventImpl(db: SQLiteDatabase, event: EventAlertRecord): Boolean { // DevLog.debug(LOG_TAG, "addEventImpl " + event.eventId) var ret = false if (event.notificationId == 0) event.notificationId = nextNotificationId(db) val values = eventRecordToContentValues(event, true) try { val id = db.insertOrThrow(TABLE_NAME, // table null, // nullColumnHack values) // key/value -> keys = column names/ values = column ret = id != -1L // values } catch (ex: SQLiteConstraintException) { DevLog.debug(LOG_TAG, "This entry (${event.eventId}) is already in the DB, updating!") // persist original notification id in this case val originalEvent = getEventImpl(db, event.eventId, event.instanceStartTime) if (originalEvent != null) { event.notificationId = originalEvent.notificationId ret = updateEventImpl(db, event) } else { ret = false } } return ret } override fun addEventsImpl(db: SQLiteDatabase, events: List<EventAlertRecord>): Boolean { var ret = true try { db.beginTransaction() for (event in events) { if (!addEventImpl(db, event)) { ret = false break } } if (ret) db.setTransactionSuccessful() } finally { db.endTransaction() } return ret } private fun nextNotificationId(db: SQLiteDatabase): Int { var ret = 0 val query = "SELECT MAX($KEY_NOTIFICATIONID) FROM " + TABLE_NAME val cursor = db.rawQuery(query, null) if (cursor != null && cursor.moveToFirst()) { try { ret = cursor.getString(0).toInt() + 1 } catch (ex: Exception) { ret = 0 } } cursor?.close() if (ret == 0) ret = Consts.NOTIFICATION_ID_DYNAMIC_FROM // DevLog.debug(LOG_TAG, "nextNotificationId, returning $ret") return ret } override fun updateEventImpl(db: SQLiteDatabase, event: EventAlertRecord): Boolean { val values = eventRecordToContentValues(event) //DevLog.debug(LOG_TAG, "Updating event, eventId=${event.eventId}, instance=${event.instanceStartTime}"); val numRowsAffected = db.update(TABLE_NAME, // table values, // column/value "$KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?", // selections arrayOf(event.eventId.toString(), event.instanceStartTime.toString())) // selection args return numRowsAffected == 1 } override fun updateEventsImpl(db: SQLiteDatabase, events: List<EventAlertRecord>): Boolean { //DevLog.debug(LOG_TAG, "Updating ${requests.size} requests"); var ret = true try { db.beginTransaction() for (event in events) { val values = eventRecordToContentValues(event) val numRowsAffected = db.update(TABLE_NAME, // table values, // column/value "$KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?", // selections arrayOf(event.eventId.toString(), event.instanceStartTime.toString())) // selection args if (numRowsAffected != 1) { ret = false break } } if (ret) db.setTransactionSuccessful() } finally { db.endTransaction() } return ret } override fun updateEventAndInstanceTimesImpl(db: SQLiteDatabase, event: EventAlertRecord, instanceStart: Long, instanceEnd: Long): Boolean { val values = eventRecordToContentValues( event = event.copy(instanceStartTime = instanceStart, instanceEndTime = instanceEnd), includeKeyValues = true) //DevLog.debug(LOG_TAG, "Updating event, eventId=${event.eventId}, instance=${event.instanceStartTime}->$instanceStart"); val numRowsAffected = db.update(TABLE_NAME, // table values, // column/value "$KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?", // selections arrayOf(event.eventId.toString(), event.instanceStartTime.toString())) // selection args return numRowsAffected == 1 } override fun updateEventsAndInstanceTimesImpl(db: SQLiteDatabase, events: Collection<EventWithNewInstanceTime>): Boolean { var ret = true try { db.beginTransaction() for ((event, instanceStart, instanceEnd) in events) { val values = eventRecordToContentValues( event = event.copy(instanceStartTime = instanceStart, instanceEndTime = instanceEnd), includeKeyValues = true) val numRowsAffected = db.update(TABLE_NAME, // table values, // column/value "$KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?", // selections arrayOf(event.eventId.toString(), event.instanceStartTime.toString())) // selection args if (numRowsAffected != 1) { ret = false break } } if (ret) db.setTransactionSuccessful() } catch (ex: SQLiteConstraintException) { // Ignore -- it is already there DevLog.error(LOG_TAG, "updateEventsAndInstanceTimesImpl: hit SQLiteConstraintException: ${ex.detailed}") } finally { db.endTransaction() } return ret } override fun getEventImpl(db: SQLiteDatabase, eventId: Long, instanceStartTime: Long): EventAlertRecord? { val cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names " $KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?", // c. selections arrayOf(eventId.toString(), instanceStartTime.toString()), // d. selections args null, // e. group by null, // f. having null, // g. order by null) // h. limit var event: EventAlertRecord? = null if (cursor != null) { if (cursor.moveToFirst()) event = cursorToEventRecord(cursor) cursor.close() } return event } override fun getEventsImpl(db: SQLiteDatabase): List<EventAlertRecord> { val ret = LinkedList<EventAlertRecord>() val cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names null, // c. selections null, null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor.moveToFirst()) { do { ret.add(cursorToEventRecord(cursor)) } while (cursor.moveToNext()) } cursor.close() //DevLog.debug(LOG_TAG, "eventsImpl, returnint ${ret.size} requests") return ret } override fun getEventInstancesImpl(db: SQLiteDatabase, eventId: Long): List<EventAlertRecord> { val ret = LinkedList<EventAlertRecord>() val cursor = db.query(TABLE_NAME, // a. table SELECT_COLUMNS, // b. column names " $KEY_EVENTID = ?", // c. selections arrayOf(eventId.toString()), // d. selections args null, // e. group by null, // f. h aving null, // g. order by null) // h. limit if (cursor.moveToFirst()) { do { ret.add(cursorToEventRecord(cursor)) } while (cursor.moveToNext()) } cursor.close() //DevLog.debug(LOG_TAG, "eventsImpl, returnint ${ret.size} requests") return ret } override fun deleteEventImpl(db: SQLiteDatabase, eventId: Long, instanceStartTime: Long): Boolean { val rowsAffected = db.delete( TABLE_NAME, " $KEY_EVENTID = ? AND $KEY_INSTANCE_START = ?", arrayOf(eventId.toString(), instanceStartTime.toString())) return rowsAffected == 1 } override fun deleteEventsImpl(db: SQLiteDatabase, events: Collection<EventAlertRecord>): Int { var numRemoved = 0 try { db.beginTransaction() for (event in events) { if (deleteEventImpl(db, event.eventId, event.instanceStartTime)) { ++numRemoved } } if (numRemoved > 0) db.setTransactionSuccessful() } finally { db.endTransaction() } return numRemoved } private fun eventRecordToContentValues(event: EventAlertRecord, includeKeyValues: Boolean = false): ContentValues { val values = ContentValues() values.put(KEY_CALENDAR_ID, event.calendarId) if (includeKeyValues) values.put(KEY_EVENTID, event.eventId) values.put(KEY_ALERT_TIME, event.alertTime) values.put(KEY_NOTIFICATIONID, event.notificationId) values.put(KEY_TITLE, event.title) values.put(KEY_DESCRIPTION, event.desc) values.put(KEY_START, event.startTime) values.put(KEY_END, event.endTime) if (includeKeyValues) values.put(KEY_INSTANCE_START, event.instanceStartTime) values.put(KEY_INSTANCE_END, event.instanceEndTime) values.put(KEY_LOCATION, event.location) values.put(KEY_SNOOZED_UNTIL, event.snoozedUntil) values.put(KEY_LAST_EVENT_VISIBILITY, event.lastStatusChangeTime) values.put(KEY_DISPLAY_STATUS, event.displayStatus.code) values.put(KEY_COLOR, event.color) values.put(KEY_IS_REPEATING, event.isRepeating) values.put(KEY_ALL_DAY, if (event.isAllDay) 1 else 0) values.put(KEY_EVENT_ORIGIN, event.origin.code) values.put(KEY_TIME_FIRST_SEEN, event.timeFirstSeen) values.put(KEY_EVENT_STATUS, event.eventStatus.code) values.put(KEY_EVENT_ATTENDANCE_STATUS, event.attendanceStatus.code) values.put(KEY_FLAGS, event.flags) // reserved - must be filled also values.put(KEY_RESERVED_INT2, 0) values.put(KEY_RESERVED_INT3, 0) values.put(KEY_RESERVED_INT4, 0) values.put(KEY_RESERVED_INT5, 0) values.put(KEY_RESERVED_INT6, 0) values.put(KEY_RESERVED_INT7, 0) values.put(KEY_RESERVED_INT8, 0) values.put(KEY_RESERVED_STR2, "") return values } private fun cursorToEventRecord(cursor: Cursor): EventAlertRecord { return EventAlertRecord( calendarId = (cursor.getLong(PROJECTION_KEY_CALENDAR_ID) as Long?) ?: -1L, eventId = cursor.getLong(PROJECTION_KEY_EVENTID), alertTime = cursor.getLong(PROJECTION_KEY_ALERT_TIME), notificationId = cursor.getInt(PROJECTION_KEY_NOTIFICATIONID), title = cursor.getString(PROJECTION_KEY_TITLE), desc = cursor.getString(PROJECTION_KEY_DESCRIPTION), startTime = cursor.getLong(PROJECTION_KEY_START), endTime = cursor.getLong(PROJECTION_KEY_END), instanceStartTime = cursor.getLong(PROJECTION_KEY_INSTANCE_START), instanceEndTime = cursor.getLong(PROJECTION_KEY_INSTANCE_END), location = cursor.getString(PROJECTION_KEY_LOCATION), snoozedUntil = cursor.getLong(PROJECTION_KEY_SNOOZED_UNTIL), lastStatusChangeTime = cursor.getLong(PROJECTION_KEY_LAST_EVENT_VISIBILITY), displayStatus = EventDisplayStatus.fromInt(cursor.getInt(PROJECTION_KEY_DISPLAY_STATUS)), color = cursor.getInt(PROJECTION_KEY_COLOR), isRepeating = cursor.getInt(PROJECTION_KEY_IS_REPEATING) != 0, isAllDay = cursor.getInt(PROJECTION_KEY_ALL_DAY) != 0, origin = EventOrigin.fromInt(cursor.getInt(PROJECTION_KEY_EVENT_ORIGIN)), timeFirstSeen = cursor.getLong(PROJECTION_KEY_TIME_FIRST_SEEN), eventStatus = EventStatus.fromInt(cursor.getInt(PROJECTION_KEY_EVENT_STATUS)), attendanceStatus = AttendanceStatus.fromInt(cursor.getInt(PROJECTION_KEY_EVENT_ATTENDANCE_STATUS)), flags = cursor.getLong(PROJECTION_KEY_FLAGS) ) } companion object { private val LOG_TAG = "EventsStorageImplV9" private const val TABLE_NAME = "eventsV9" private const val INDEX_NAME = "eventsIdxV9" // No one is going to read this SQLite manually. use column names that // are faster to process by computer (==shorter names) private const val KEY_CALENDAR_ID = "cid" private const val KEY_EVENTID = "id" private const val KEY_IS_REPEATING = "rep" private const val KEY_ALL_DAY = "alld" private const val KEY_NOTIFICATIONID = "nid" private const val KEY_TITLE = "ttl" private const val KEY_DESCRIPTION = "s1" private const val KEY_START = "estart" private const val KEY_END = "eend" private const val KEY_INSTANCE_START = "istart" private const val KEY_INSTANCE_END = "iend" private const val KEY_LOCATION = "loc" private const val KEY_SNOOZED_UNTIL = "snz" private const val KEY_DISPLAY_STATUS = "dsts" private const val KEY_LAST_EVENT_VISIBILITY = "ls" private const val KEY_COLOR = "clr" private const val KEY_ALERT_TIME = "altm" private const val KEY_EVENT_ORIGIN = "ogn" private const val KEY_TIME_FIRST_SEEN = "fsn" private const val KEY_EVENT_STATUS = "attsts" private const val KEY_EVENT_ATTENDANCE_STATUS = "oattsts" private const val KEY_FLAGS = "i1" private const val KEY_RESERVED_INT2 = "i2" private const val KEY_RESERVED_INT3 = "i3" private const val KEY_RESERVED_INT4 = "i4" private const val KEY_RESERVED_INT5 = "i5" private const val KEY_RESERVED_INT6 = "i6" private const val KEY_RESERVED_INT7 = "i7" private const val KEY_RESERVED_INT8 = "i8" private const val KEY_RESERVED_STR2 = "s2" private val SELECT_COLUMNS = arrayOf<String>( KEY_CALENDAR_ID, KEY_EVENTID, KEY_ALERT_TIME, KEY_NOTIFICATIONID, KEY_TITLE, KEY_DESCRIPTION, KEY_START, KEY_END, KEY_INSTANCE_START, KEY_INSTANCE_END, KEY_LOCATION, KEY_SNOOZED_UNTIL, KEY_LAST_EVENT_VISIBILITY, KEY_DISPLAY_STATUS, KEY_COLOR, KEY_IS_REPEATING, KEY_ALL_DAY, KEY_EVENT_ORIGIN, KEY_TIME_FIRST_SEEN, KEY_EVENT_STATUS, KEY_EVENT_ATTENDANCE_STATUS, KEY_FLAGS ) const val PROJECTION_KEY_CALENDAR_ID = 0 const val PROJECTION_KEY_EVENTID = 1 const val PROJECTION_KEY_ALERT_TIME = 2 const val PROJECTION_KEY_NOTIFICATIONID = 3 const val PROJECTION_KEY_TITLE = 4 const val PROJECTION_KEY_DESCRIPTION = 5 const val PROJECTION_KEY_START = 6 const val PROJECTION_KEY_END = 7 const val PROJECTION_KEY_INSTANCE_START = 8 const val PROJECTION_KEY_INSTANCE_END = 9 const val PROJECTION_KEY_LOCATION = 10 const val PROJECTION_KEY_SNOOZED_UNTIL = 11 const val PROJECTION_KEY_LAST_EVENT_VISIBILITY = 12 const val PROJECTION_KEY_DISPLAY_STATUS = 13 const val PROJECTION_KEY_COLOR = 14 const val PROJECTION_KEY_IS_REPEATING = 15 const val PROJECTION_KEY_ALL_DAY = 16 const val PROJECTION_KEY_EVENT_ORIGIN = 17 const val PROJECTION_KEY_TIME_FIRST_SEEN = 18 const val PROJECTION_KEY_EVENT_STATUS = 19 const val PROJECTION_KEY_EVENT_ATTENDANCE_STATUS = 20 const val PROJECTION_KEY_FLAGS = 21 } }
gpl-3.0
d3e13a2d9fabec74180099194dadad17
34.957555
144
0.562774
4.517705
false
false
false
false
konrad-jamrozik/droidmate
dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/ClickFrequencyTable.kt
1
2733
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2016 Konrad Jamrozik // // 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/>. // // email: [email protected] // web: www.droidmate.org package org.droidmate.report import com.google.common.collect.Table import com.konradjamrozik.frequencies import com.konradjamrozik.transpose import org.droidmate.device.datatypes.Widget import org.droidmate.exploration.data_aggregators.IApkExplorationOutput2 class ClickFrequencyTable private constructor(val table: Table<Int, String, Int>) : Table<Int, String, Int> by table { constructor(data: IApkExplorationOutput2) : this(ClickFrequencyTable.build(data)) companion object { val headerNoOfClicks = "No_of_clicks" val headerViewsCount = "Views_count" fun build(data: IApkExplorationOutput2): Table<Int, String, Int> { val countOfViewsHavingNoOfClicks: Map<Int, Int> = data.countOfViewsHavingNoOfClicks return buildTable( headers = listOf(headerNoOfClicks, headerViewsCount), rowCount = countOfViewsHavingNoOfClicks.keys.size, computeRow = { rowIndex -> check(countOfViewsHavingNoOfClicks.containsKey(rowIndex)) val noOfClicks = rowIndex listOf( noOfClicks, countOfViewsHavingNoOfClicks[noOfClicks]!! ) } ) } private val IApkExplorationOutput2.countOfViewsHavingNoOfClicks: Map<Int, Int> get() { val clickedWidgets: List<Widget> = this.actRess.flatMap { it.clickedWidget } val noOfClicksPerWidget: Map<Widget, Int> = clickedWidgets.frequencies val widgetsHavingNoOfClicks: Map<Int, Set<Widget>> = noOfClicksPerWidget.transpose val widgetsCountPerNoOfClicks: Map<Int, Int> = widgetsHavingNoOfClicks.mapValues { it.value.size } val maxNoOfClicks = noOfClicksPerWidget.values.max() ?: 0 val noOfClicksProgression = 0..maxNoOfClicks step 1 val zeroWidgetsCountsPerNoOfClicks = noOfClicksProgression.associate { Pair(it, 0) } return zeroWidgetsCountsPerNoOfClicks + widgetsCountPerNoOfClicks } } }
gpl-3.0
77ed867875e80e329572179fb193b06c
39.80597
118
0.736187
4.054896
false
false
false
false
j2ghz/tachiyomi-extensions
src/en/dynasty/src/eu/kanade/tachiyomi/extension/en/dynasty/DynastySeries.kt
1
916
package eu.kanade.tachiyomi.extension.en.dynasty import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.SManga import okhttp3.Request import org.jsoup.nodes.Document class DynastySeries : DynastyScans() { override val name = "Dynasty-Series" override fun popularMangaInitialUrl() = "$baseUrl/series?view=cover" override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { return GET("$baseUrl/search?q=$query&classes%5B%5D=Series&sort=", headers) } override fun mangaDetailsParse(document: Document): SManga { val manga = SManga.create() manga.thumbnail_url = baseUrl + document.select("div.span2 > img").attr("src") parseHeader(document, manga) parseGenres(document, manga) parseDescription(document, manga) return manga } }
apache-2.0
f283b79da9dd276798190294ab9736d9
31.75
93
0.720524
4.089286
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/fun/texttransform/TextVaporwaveExecutor.kt
1
1533
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.texttransform import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.cleanUpForOutput import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.ApplicationCommandContext import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CinnamonSlashCommandExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.options.LocalizedApplicationCommandOptions import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.`fun`.declarations.TextTransformCommand import net.perfectdreams.loritta.common.utils.text.VaporwaveUtils class TextVaporwaveExecutor(loritta: LorittaBot) : CinnamonSlashCommandExecutor(loritta) { inner class Options : LocalizedApplicationCommandOptions(loritta) { val text = string("text", TextTransformCommand.I18N_PREFIX.Vaporwave.Description) } override val options = Options() override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { val text = cleanUpForOutput(context, args[options.text]) // We will clean up before, because after vaporwaving the text, it won't be possible to clean it up val vaporwave = VaporwaveUtils.vaporwave(text) context.sendReply( content = vaporwave, prefix = "✍" ) } }
agpl-3.0
691a27cfc42cfedd38cf3de0080300b6
53.714286
164
0.805356
4.696319
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/magic/LoriBanIpExecutor.kt
1
910
package net.perfectdreams.loritta.morenitta.commands.vanilla.magic import net.perfectdreams.loritta.morenitta.api.commands.CommandContext import net.perfectdreams.loritta.morenitta.messages.LorittaReply import net.perfectdreams.loritta.morenitta.tables.BannedIps import org.jetbrains.exposed.sql.insert object LoriBanIpExecutor : LoriToolsCommand.LoriToolsExecutor { override val args = "ban ip <ip> <reason>" override fun executes(): suspend CommandContext.() -> Boolean = task@{ if (args.getOrNull(0) != "ban") return@task false if (args.getOrNull(1) != "ip") return@task false val ip = args[2] val reason = args.drop(3).joinToString(" ") loritta.pudding.transaction { BannedIps.insert { it[BannedIps.ip] = ip it[bannedAt] = System.currentTimeMillis() it[BannedIps.reason] = reason } } reply( LorittaReply( "IP banido!" ) ) return@task true } }
agpl-3.0
4f3122f5927a179b4a9edd98ff9023bb
25.794118
71
0.724176
3.3829
false
false
false
false
AlmasB/GroupNet
src/test/kotlin/icurves/description/AbstractZoneTest.kt
1
3683
package icurves.description import icurves.util.Bug import org.hamcrest.CoreMatchers.`is` import org.hamcrest.CoreMatchers.not import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class AbstractZoneTest { private lateinit var zone1: AbstractZone private lateinit var zone2: AbstractZone private lateinit var zone3: AbstractZone @BeforeEach fun setUp() { zone1 = az("a") zone2 = az("ab") zone3 = az("a") } @Test fun `Creation`() { assertThrows(Bug::class.java, { az("a b") }) } @Test fun `Equality`() { assertThat(zone1, `is`(zone3)) assertThat(zone1.hashCode(), `is`(zone3.hashCode())) assertThat(zone1, `is`(not(zone2))) assertThat(zone3, `is`(not(zone2))) assertThat(zone1, `is`(AbstractZone(setOf("a")))) assertThat(zone2, `is`(AbstractZone(setOf("a", "b")))) assertThat(zone2, `is`(AbstractZone(setOf("b", "a")))) } @Test fun `Number of labels`() { assertThat(azEmpty.getNumLabels(), `is`(0)) assertThat(zone1.getNumLabels(), `is`(1)) assertThat(zone2.getNumLabels(), `is`(2)) assertThat(zone3.getNumLabels(), `is`(1)) } @Test fun `Label in abstract zone`() { assertTrue(zone1.contains(("a"))) assertTrue(zone2.contains(("a"))) assertTrue(zone3.contains(("a"))) assertFalse(zone1.contains(("b"))) assertTrue(zone2.contains(("b"))) assertFalse(zone3.contains(("b"))) } @Test fun `az + label`() { assertEquals(zone1, azEmpty + "a") assertEquals(zone3, azEmpty + "a") assertEquals(zone2, zone1 + "b") assertEquals(zone2, zone3 + "b") assertThat(azEmpty + "b", `is`(not(zone2))) } @Test fun `az - label`() { assertThat(zone2 - "b", `is`(zone1)) assertThat(zone2 - "b", `is`(zone3)) assertThat(zone2 - "b", `is`(az("a"))) assertThat(zone1 - "a", `is`(azEmpty)) assertThat(zone3 - "a", `is`(azEmpty)) assertThat(zone2 - "b" - "a", `is`(azEmpty)) assertThat(zone2 - "a" - "b", `is`(azEmpty)) // pre-condition: "c" !in zone2 assertThat(zone2 - "c", `is`(zone2)) } @Test fun testStraddledContour() { assertTrue(!zone1.getStraddledLabel(zone3).isPresent) assertTrue(!zone2.getStraddledLabel(AbstractZone.OUTSIDE).isPresent) assertEquals(("a"), zone1.getStraddledLabel(AbstractZone.OUTSIDE).get()) assertEquals(("a"), AbstractZone.OUTSIDE.getStraddledLabel(zone1).get()) assertEquals(("b"), zone1.getStraddledLabel(zone2).get()) assertEquals(("b"), zone2.getStraddledLabel(zone1).get()) assertEquals(("b"), zone3.getStraddledLabel(zone2).get()) } @Test fun `Formal`() { val az1 = az("ab") assertThat(az1.toFormal(), `is`("{a,b}")) val az2 = az("bca") assertThat(az2.toFormal(), `is`("{a,b,c}")) assertThat(azEmpty.toFormal(), `is`("{}")) } @Test fun `Informal`() { val az1 = az("ab") assertThat(az1.toInformal(), `is`("ab")) val az2 = az("bca") assertThat(az2.toInformal(), `is`("abc")) assertThat(azEmpty.toInformal(), `is`("")) } @Test fun testToString() { assertNotEquals(zone1.toString(), zone2.toString()) assertEquals(zone1.toString(), zone3.toString()) assertEquals("{a}", zone1.toString()) assertEquals("{a,b}", zone2.toString()) } }
apache-2.0
349bcb6f98a463ebbddedf2796b9f5d7
26.699248
80
0.577247
3.600196
false
true
false
false
mcxiaoke/kotlin-koi
core/src/main/kotlin/com/mcxiaoke/koi/ext/View.kt
1
4269
package com.mcxiaoke.koi.ext import android.app.Activity import android.app.Fragment import android.content.Context import android.content.res.Resources import android.text.Editable import android.text.TextWatcher import android.util.DisplayMetrics import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.* import android.support.v4.app.Fragment as SupportFragment /** * User: mcxiaoke * Date: 16/1/26 * Time: 17:38 */ val View.dm: DisplayMetrics get() = resources.displayMetrics fun Float.pxToDp(): Int { val metrics = Resources.getSystem().displayMetrics val dp = this / (metrics.densityDpi / 160f) return Math.round(dp) } fun Float.dpToPx(): Int { val metrics = Resources.getSystem().displayMetrics val px = this * (metrics.densityDpi / 160f) return Math.round(px) } fun Int.pxToDp(): Int { val metrics = Resources.getSystem().displayMetrics val dp = this / (metrics.densityDpi / 160f) return Math.round(dp) } fun Int.dpToPx(): Int { val metrics = Resources.getSystem().displayMetrics val px = this * (metrics.densityDpi / 160f) return Math.round(px) } fun View.dpToPx(dp: Int): Int { return (dp * this.dm.density + 0.5).toInt() } fun View.pxToDp(px: Int): Int { return (px / this.dm.density + 0.5).toInt() } fun View.hideSoftKeyboard() { context.getInputMethodManager().hideSoftInputFromWindow(this.windowToken, 0) } fun EditText.showSoftKeyboard() { if (this.requestFocus()) { context.getInputMethodManager().showSoftInput(this, InputMethodManager.SHOW_IMPLICIT) } } fun EditText.toggleSoftKeyboard() { if (this.requestFocus()) { context.getInputMethodManager().toggleSoftInput(0, 0) } } fun View.onClick(f: (View) -> Unit) { this.setOnClickListener(f) } fun View.onLongClick(f: (View) -> Boolean) { this.setOnLongClickListener(f) } fun View.onTouchEvent(f: (View, MotionEvent) -> Boolean) { this.setOnTouchListener(f) } fun View.onKeyEvent(f: (View, Int, KeyEvent) -> Boolean) { this.setOnKeyListener(f) } fun View.onFocusChange(f: (View, Boolean) -> Unit) { this.setOnFocusChangeListener(f) } fun CompoundButton.onCheckedChanged(f: (CompoundButton, Boolean) -> Unit) { this.setOnCheckedChangeListener(f) } fun AdapterView<*>.onItemClick(f: (AdapterView<*>, View, Int, Long) -> Unit) { this.setOnItemClickListener(f) } inline fun <T : AbsListView> T.onScrollChanged( crossinline stateChanged: (View, Int) -> Unit) { val listener = object : AbsListView.OnScrollListener { override fun onScrollStateChanged(view: AbsListView, scrollState: Int) { stateChanged(view, scrollState) } override fun onScroll(view: AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) { } } this.setOnScrollListener(listener) } inline fun EditText.onTextChange(crossinline f: (CharSequence, Int, Int, Int) -> Unit) { val listener = object : KoiTextWatcher() { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { f(s, start, before, count) } } this.addTextChangedListener(listener) } fun SeekBar.onProgressChanged(f: (SeekBar, Int, Boolean) -> Unit) { val listener = object : KoiSeekBarChangeListener() { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { super.onProgressChanged(seekBar, progress, fromUser) f(seekBar, progress, fromUser) } } this.setOnSeekBarChangeListener(listener) } abstract class KoiTextWatcher : TextWatcher { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { } override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun afterTextChanged(s: Editable) { } } abstract class KoiSeekBarChangeListener : SeekBar.OnSeekBarChangeListener { override fun onStopTrackingTouch(seekBar: SeekBar) { } override fun onStartTrackingTouch(seekBar: SeekBar) { } override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { } }
apache-2.0
ad1269c68371ad07c63190ba7766927b
26.371795
93
0.686578
4.061846
false
false
false
false
cypressious/learning-spaces
app/src/main/java/de/maxvogler/learningspaces/fragments/LocationMapFragment.kt
1
4325
package de.maxvogler.learningspaces.fragments import android.os.Bundle import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Marker import com.google.android.gms.maps.model.MarkerOptions import com.squareup.otto.Subscribe import de.maxvogler.learningspaces.events.LocationFocusChangeEvent import de.maxvogler.learningspaces.events.PanelVisibilityChangedEvent import de.maxvogler.learningspaces.events.UpdateLocationsEvent import de.maxvogler.learningspaces.models.Location import de.maxvogler.learningspaces.services.BusProvider import de.maxvogler.learningspaces.services.MarkerFactory import kotlin.properties.Delegates /** * A Fragment, displaying all [Location]s in a [GoogleMap]. */ public class LocationMapFragment : SupportMapFragment() { private val bus = BusProvider.instance private var markers: Map<Location, Marker> = emptyMap() private var markerFactory: MarkerFactory by Delegates.notNull() private var selectedMarker: Marker? = null private var selectedLocation: Location? = null private var mapView: GoogleMap? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) markerFactory = MarkerFactory(activity) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) getMapAsync { this.mapView = it val pos = LatLng(49.011019, 8.414874) it.uiSettings.isZoomControlsEnabled = false it.uiSettings.isMyLocationButtonEnabled = false it.uiSettings.isCompassEnabled = false it.isMyLocationEnabled = true it.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 14f)) it.setOnMarkerClickListener { marker -> val location = markers.entrySet().firstOrNull { it.getValue() == marker }?.key if (location != null) { showSelectedMarker(markerFactory.createSelectedMarker(location)) bus.post(LocationFocusChangeEvent(location)) } true } it.setOnMapClickListener { bus post LocationFocusChangeEvent(null) } } } override fun onResume() { super.onResume() bus.register(this) } override fun onPause() { bus.unregister(this) super.onPause() } @Subscribe public fun onReceiveLocations(event: UpdateLocationsEvent) { val locations = event.locations removeSelectedMarker() mapView?.clear() markers = locations.values().toMap({ it }, { it }) .mapValues { markerFactory.createMarker(it.getValue()) } .mapValues { mapView?.addMarker(it.getValue()) } .filter { it.getValue() != null } .mapValues { it.getValue()!! } val oldSelected = selectedLocation if (oldSelected != null) { val newSelected = locations.get(oldSelected.id) if (newSelected != null) { selectedLocation = newSelected showSelectedMarker(markerFactory.createSelectedMarker(newSelected)) } } } @Subscribe public fun onLocationFocusChange(event: LocationFocusChangeEvent) { removeSelectedMarker() selectedLocation = event.location if (event.location != null) { val marker = markerFactory.createSelectedMarker(event.location) showSelectedMarker(marker) if (event.animateMap) { mapView?.animateCamera(CameraUpdateFactory.newLatLng(marker.position)) } } } @Subscribe public fun onPanelVisibilityChanged(event: PanelVisibilityChangedEvent) { mapView?.uiSettings?.setAllGesturesEnabled(!event.visible) } private fun removeSelectedMarker() { selectedMarker?.remove() selectedMarker = null } private fun showSelectedMarker(options: MarkerOptions) { removeSelectedMarker() selectedMarker = mapView?.addMarker(options) } }
gpl-2.0
4b63805f3622e8057f43d8d1a3e9739c
31.518797
94
0.665665
5.082256
false
false
false
false
MobileToolkit/updater-android
updater/src/main/java/org/mobiletoolkit/updater/Updater.kt
1
11945
package org.mobiletoolkit.updater import android.app.Activity import android.app.AlertDialog import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.util.Log import org.mobiletoolkit.updater.model.UpdatePromptData import org.mobiletoolkit.updater.model.VersionData import org.mobiletoolkit.updater.model.VersionsInfo /** * Created by Sebastian Owodzin on 07/05/2016. * Copyright © 2016 mobiletoolkit.org. All rights reserved. */ class Updater( private val activity: Activity, private val applicationId: String, private val versionName: String, private val promptToRunLatestVersion: Boolean = true, private val promptToUninstallUnsupportedVersions: Boolean = false, private val callback: Callback? = null ) { companion object { private val TAG = "Updater" private val UNSUPPORTED_VERSION_UNINSTALL_REQUEST_CODE = 999 private val SHARED_PREFERENCES_FILE_NAME_PREFIX = "com.mobiletoolkit.updater" private val SHARED_PREFERENCES_KEY = "unsupported_versions_uninstall_done" } private lateinit var versionsInfo: VersionsInfo private lateinit var versionCheckResult: VersionCheck.Result fun execute(versionsInfo: VersionsInfo) { this.versionsInfo = versionsInfo versionCheckResult = VersionCheck(applicationId, versionName, versionsInfo).result // check if the latest app version is already installed & if it's not the current one then propose to start it instead Log.v(TAG, "is applicationId running: ${versionsInfo.latestVersionData.applicationId == applicationId}") if (isPackageInstalled(activity, versionsInfo.latestVersionData) && versionsInfo.latestVersionData.applicationId != applicationId) { if (promptToRunLatestVersion) { showRunLatestVersionAlertDialog(activity) } } else { when (versionCheckResult) { VersionCheck.Result.UP_TO_DATE -> uninstallUnsupportedVersionsIfNeeded(activity) VersionCheck.Result.OUTDATED -> showOutdatedVersionAlertDialog(activity) VersionCheck.Result.UNSUPPORTED -> showUnsupportedVersionAlertDialog(activity) } } } fun onActivityResult(requestCode: Int, resultCode: Int): Boolean = if (requestCode == UNSUPPORTED_VERSION_UNINSTALL_REQUEST_CODE) { when (resultCode) { Activity.RESULT_OK -> { Log.v(TAG, "onActivityResult: user accepted the uninstall") uninstallUnsupportedVersionsIfNeeded(activity) } Activity.RESULT_CANCELED -> { Log.d(TAG, "onActivityResult: user canceled the uninstall") markUninstallUnsupportedVersionsDone(activity) } else -> { Log.d(TAG, "onActivityResult: failed to uninstall") } } true } else { false } private fun isPackageInstalled(context: Context, versionData: VersionData): Boolean = try { val packageInfo = context.packageManager.getPackageInfo(versionData.applicationId, PackageManager.GET_META_DATA) val result = packageInfo != null Log.v(TAG, "isPackageInstalled: $result\n" + " * versionData: $versionData") result } catch (e: PackageManager.NameNotFoundException) { Log.v(TAG, "isPackageInstalled: false\n" + "versionData: $versionData") false } private fun launchApplication(context: Context, applicationId: String) { context.startActivity(context.packageManager.getLaunchIntentForPackage(applicationId)) } private fun initializeUpdate(context: Context, versionData: VersionData) { if (versionData.installUrl != null) { Log.v(TAG, "initializeUpdate -> opening url: ${versionData.installUrl}") val intent = Intent(Intent.ACTION_VIEW, Uri.parse("${versionData.installUrl}")) context.startActivity(intent) } else { try { Log.v(TAG, "initializeUpdate -> trying to open market://details?id=${versionData.applicationId}") val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=${versionData.applicationId}")) context.startActivity(intent) } catch (exception: ActivityNotFoundException) { Log.v(TAG, "initializeUpdate -> opening https://play.google.com/store/apps/details?id=${versionData.applicationId}") val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=${versionData.applicationId}")) context.startActivity(intent) } } } private fun showRunLatestVersionAlertDialog(context: Context) { AlertDialog.Builder(context, R.style.MobileToolkit_Updater_Dialog_Alert) .setTitle(R.string.mobiletoolkit_updater_run_latest_version_title) .setMessage(R.string.mobiletoolkit_updater_run_latest_version_message) .setPositiveButton(R.string.mobiletoolkit_updater_run_latest_version_yes_button) { dialog, _ -> dialog.dismiss() launchApplication(context, versionsInfo.latestVersionData.applicationId) } .setNegativeButton(R.string.mobiletoolkit_updater_run_latest_version_no_button) { dialog, _ -> dialog.dismiss() callback?.onLatestVersionLaunchCancelled(versionCheckResult) } .show() } private fun showOutdatedVersionAlertDialog(context: Context) { val builder = AlertDialog.Builder(context, R.style.MobileToolkit_Updater_Dialog_Alert) .setTitle(R.string.mobiletoolkit_updater_outdated_version_title) .setMessage(R.string.mobiletoolkit_updater_outdated_version_message) .setPositiveButton(R.string.mobiletoolkit_updater_outdated_version_update_button) { dialog, _ -> dialog.dismiss() callback?.onVersionUpdateStarted(versionCheckResult) initializeUpdate(context, versionsInfo.latestVersionData) } .setNegativeButton(R.string.mobiletoolkit_updater_outdated_version_cancel_button) { dialog, _ -> dialog.dismiss() callback?.onVersionUpdateCancelled(versionCheckResult) } if (null != versionsInfo.outdatedVersionUpdatePromptData) { builder.setTitle((versionsInfo.outdatedVersionUpdatePromptData as UpdatePromptData).title) builder.setMessage((versionsInfo.outdatedVersionUpdatePromptData as UpdatePromptData).message) } builder.show() } private fun showUnsupportedVersionAlertDialog(context: Context) { val builder = AlertDialog.Builder(context, R.style.MobileToolkit_Updater_Dialog_Alert) .setTitle(R.string.mobiletoolkit_updater_unsupported_version_title) .setMessage(R.string.mobiletoolkit_updater_unsupported_version_message) .setPositiveButton(R.string.mobiletoolkit_updater_unsupported_version_update_button) { dialog, _ -> dialog.dismiss() callback?.onVersionUpdateStarted(versionCheckResult) initializeUpdate(context, versionsInfo.latestVersionData) } if (null != versionsInfo.unsupportedVersionUpdatePromptData) { builder.setTitle((versionsInfo.unsupportedVersionUpdatePromptData as UpdatePromptData).title) builder.setMessage((versionsInfo.unsupportedVersionUpdatePromptData as UpdatePromptData).message) } builder.show() } private fun isNotMarkedUninstallUnsupportedVersionsDone(context: Context): Boolean = context.getSharedPreferences( "${SHARED_PREFERENCES_FILE_NAME_PREFIX}_$applicationId", Context.MODE_PRIVATE ).getBoolean(SHARED_PREFERENCES_KEY, false).not() private fun shouldUninstallUnsupportedVersions(context: Context): Boolean { Log.v(TAG, "shouldUninstallUnsupportedVersions\n" + " * promptToUninstallUnsupportedVersions: $promptToUninstallUnsupportedVersions\n" + " * promptToUninstallUnsupportedVersions: isNotMarkedUninstallUnsupportedVersionsDone: ${isNotMarkedUninstallUnsupportedVersionsDone(context)}\n" + " * shouldUninstallUnsupportedVersions -> versionsInfo.uninstallUnsupportedVersions: ${versionsInfo.uninstallUnsupportedVersions}") return promptToUninstallUnsupportedVersions || (isNotMarkedUninstallUnsupportedVersionsDone(context) && versionsInfo.uninstallUnsupportedVersions) } private fun markUninstallUnsupportedVersionsDone(context: Context) { context.getSharedPreferences( "${SHARED_PREFERENCES_FILE_NAME_PREFIX}_$applicationId", Context.MODE_PRIVATE ).edit().putBoolean(SHARED_PREFERENCES_KEY, true).apply() } private fun existingUnsupportedVersions(context: Context): List<VersionData> = versionsInfo.unsupportedVersions.filter { it.applicationId != applicationId && isPackageInstalled(context, it) } private fun uninstallUnsupportedVersionsIfNeeded(activity: Activity) { if (shouldUninstallUnsupportedVersions(activity)) { val versionsToUninstall = existingUnsupportedVersions(activity) Log.v(TAG, "uninstallUnsupportedVersionsIfNeeded\n" + " * versionsToUninstall: $versionsToUninstall") if (versionsToUninstall.isEmpty()) { markUninstallUnsupportedVersionsDone(activity) callback?.onUninstallUnsupportedVersionsFinished() } else { callback?.onUninstallUnsupportedVersionsStarted() showUninstallUnsupportedVersionAlertDialog(activity, versionsToUninstall.first().applicationId) } } else { callback?.onUninstallUnsupportedVersionsSkipped() } } private fun showUninstallUnsupportedVersionAlertDialog(activity: Activity, applicationId: String) { val builder = AlertDialog.Builder(activity, R.style.MobileToolkit_Updater_Dialog_Alert) .setTitle(R.string.mobiletoolkit_updater_unsupported_versions_installed_title) .setMessage(R.string.mobiletoolkit_updater_unsupported_versions_installed_message) .setPositiveButton(R.string.mobiletoolkit_updater_ok_button) { dialog, _ -> dialog.dismiss() uninstallApplication(activity, applicationId) callback?.onUninstallUnsupportedVersionStarted(applicationId) } .setNegativeButton(R.string.mobiletoolkit_updater_cancel_button) { dialog, _ -> dialog.dismiss() markUninstallUnsupportedVersionsDone(activity) callback?.onUninstallUnsupportedVersionCancelled(applicationId) } builder.show() } private fun uninstallApplication(activity: Activity, applicationId: String) { val intent = Intent(Intent.ACTION_UNINSTALL_PACKAGE, Uri.parse("package:$applicationId")) .putExtra(Intent.EXTRA_RETURN_RESULT, true) activity.startActivityForResult(intent, UNSUPPORTED_VERSION_UNINSTALL_REQUEST_CODE) } }
mit
91fa079da6b27b3420b5d4e7592f910f
45.119691
163
0.657234
5.252419
false
true
false
false
google-developer-training/android-demos
DonutTracker/NavigationUI/app/src/main/java/com/android/samples/donuttracker/donut/DonutListAdapter.kt
2
2969
/* * Copyright (C) 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.android.samples.donuttracker.donut import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.android.samples.donuttracker.R import com.android.samples.donuttracker.databinding.DonutItemBinding import com.android.samples.donuttracker.model.Donut /** * The adapter used by the RecyclerView to display the current list of donuts */ class DonutListAdapter( private var onEdit: (Donut) -> Unit, private var onDelete: (Donut) -> Unit ) : ListAdapter<Donut, DonutListAdapter.DonutListViewHolder>(DonutDiffCallback()) { class DonutListViewHolder( private val binding: DonutItemBinding, private var onEdit: (Donut) -> Unit, private var onDelete: (Donut) -> Unit ) : RecyclerView.ViewHolder(binding.root) { private var donutId: Long = -1 private var nameView = binding.name private var description = binding.description private var thumbnail = binding.thumbnail private var rating = binding.rating private var donut: Donut? = null fun bind(donut: Donut) { donutId = donut.id nameView.text = donut.name description.text = donut.description rating.text = donut.rating.toString() thumbnail.setImageResource(R.drawable.donut_with_sprinkles) this.donut = donut binding.deleteButton.setOnClickListener { onDelete(donut) } binding.root.setOnClickListener { onEdit(donut) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = DonutListViewHolder( DonutItemBinding.inflate(LayoutInflater.from(parent.context), parent, false), onEdit, onDelete ) override fun onBindViewHolder(holder: DonutListViewHolder, position: Int) { holder.bind(getItem(position)) } } class DonutDiffCallback : DiffUtil.ItemCallback<Donut>() { override fun areItemsTheSame(oldItem: Donut, newItem: Donut): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Donut, newItem: Donut): Boolean { return oldItem == newItem } }
apache-2.0
0f4facb35ea3c366a9f1e7df086f3b3c
35.207317
92
0.69552
4.712698
false
false
false
false
square/leakcanary
shark-graph/src/main/java/shark/internal/UnsortedByteEntries.kt
2
5839
package shark.internal import shark.internal.aosp.ByteArrayTimSort /** * Wraps a byte array of entries where each entry is an id followed by bytes for the value. * `id` is a long if [longIdentifiers] is true and an int otherwise. Each entry has [bytesPerValue] * value bytes. Entries are appended into the array via [append]. Once done, the backing array * is sorted and turned into a [SortedBytesMap] by calling [moveToSortedMap]. */ internal class UnsortedByteEntries( private val bytesPerValue: Int, private val longIdentifiers: Boolean, private val initialCapacity: Int = 4, private val growthFactor: Double = 2.0 ) { private val bytesPerEntry = bytesPerValue + if (longIdentifiers) 8 else 4 private var entries: ByteArray? = null private val subArray = MutableByteSubArray() private var subArrayIndex = 0 private var assigned: Int = 0 private var currentCapacity = 0 fun append( key: Long ): MutableByteSubArray { if (entries == null) { currentCapacity = initialCapacity entries = ByteArray(currentCapacity * bytesPerEntry) } else { if (currentCapacity == assigned) { val newCapacity = (currentCapacity * growthFactor).toInt() growEntries(newCapacity) currentCapacity = newCapacity } } assigned++ subArrayIndex = 0 subArray.writeId(key) return subArray } fun moveToSortedMap(): SortedBytesMap { if (assigned == 0) { return SortedBytesMap(longIdentifiers, bytesPerValue, ByteArray(0)) } val entries = entries!! // Sort entries by keys, which are ids of 4 or 8 bytes. ByteArrayTimSort.sort(entries, 0, assigned, bytesPerEntry) { entrySize, o1Array, o1Index, o2Array, o2Index -> if (longIdentifiers) { readLong(o1Array, o1Index * entrySize) .compareTo( readLong(o2Array, o2Index * entrySize) ) } else { readInt(o1Array, o1Index * entrySize) .compareTo( readInt(o2Array, o2Index * entrySize) ) } } val sortedEntries = if (entries.size > assigned * bytesPerEntry) { entries.copyOf(assigned * bytesPerEntry) } else entries this.entries = null assigned = 0 return SortedBytesMap( longIdentifiers, bytesPerValue, sortedEntries ) } private fun readInt( array: ByteArray, index: Int ): Int { var pos = index return (array[pos++] and 0xff shl 24 or (array[pos++] and 0xff shl 16) or (array[pos++] and 0xff shl 8) or (array[pos] and 0xff)) } @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. private inline infix fun Byte.and(other: Long): Long = toLong() and other @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. private inline infix fun Byte.and(other: Int): Int = toInt() and other private fun readLong( array: ByteArray, index: Int ): Long { var pos = index return (array[pos++] and 0xffL shl 56 or (array[pos++] and 0xffL shl 48) or (array[pos++] and 0xffL shl 40) or (array[pos++] and 0xffL shl 32) or (array[pos++] and 0xffL shl 24) or (array[pos++] and 0xffL shl 16) or (array[pos++] and 0xffL shl 8) or (array[pos] and 0xffL)) } private fun growEntries(newCapacity: Int) { val newEntries = ByteArray(newCapacity * bytesPerEntry) System.arraycopy(entries, 0, newEntries, 0, assigned * bytesPerEntry) entries = newEntries } internal inner class MutableByteSubArray { fun writeByte(value: Byte) { val index = subArrayIndex subArrayIndex++ require(index in 0..bytesPerEntry) { "Index $index should be between 0 and $bytesPerEntry" } val valuesIndex = ((assigned - 1) * bytesPerEntry) + index entries!![valuesIndex] = value } fun writeId(value: Long) { if (longIdentifiers) { writeLong(value) } else { writeInt(value.toInt()) } } fun writeInt(value: Int) { val index = subArrayIndex subArrayIndex += 4 require(index >= 0 && index <= bytesPerEntry - 4) { "Index $index should be between 0 and ${bytesPerEntry - 4}" } var pos = ((assigned - 1) * bytesPerEntry) + index val values = entries!! values[pos++] = (value ushr 24 and 0xff).toByte() values[pos++] = (value ushr 16 and 0xff).toByte() values[pos++] = (value ushr 8 and 0xff).toByte() values[pos] = (value and 0xff).toByte() } fun writeTruncatedLong( value: Long, byteCount: Int ) { val index = subArrayIndex subArrayIndex += byteCount require(index >= 0 && index <= bytesPerEntry - byteCount) { "Index $index should be between 0 and ${bytesPerEntry - byteCount}" } var pos = ((assigned - 1) * bytesPerEntry) + index val values = entries!! var shift = (byteCount - 1) * 8 while (shift >= 8) { values[pos++] = (value ushr shift and 0xffL).toByte() shift -= 8 } values[pos] = (value and 0xffL).toByte() } fun writeLong(value: Long) { val index = subArrayIndex subArrayIndex += 8 require(index >= 0 && index <= bytesPerEntry - 8) { "Index $index should be between 0 and ${bytesPerEntry - 8}" } var pos = ((assigned - 1) * bytesPerEntry) + index val values = entries!! values[pos++] = (value ushr 56 and 0xffL).toByte() values[pos++] = (value ushr 48 and 0xffL).toByte() values[pos++] = (value ushr 40 and 0xffL).toByte() values[pos++] = (value ushr 32 and 0xffL).toByte() values[pos++] = (value ushr 24 and 0xffL).toByte() values[pos++] = (value ushr 16 and 0xffL).toByte() values[pos++] = (value ushr 8 and 0xffL).toByte() values[pos] = (value and 0xffL).toByte() } } }
apache-2.0
3c7fc9ce9e4b9e9a82281af6c954395e
30.392473
99
0.624593
3.903075
false
false
false
false
Deletescape-Media/Lawnchair
lawnchair/src/app/lawnchair/font/FontCache.kt
1
17779
/* * This file is part of Lawnchair Launcher. * * Lawnchair Launcher 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. * * Lawnchair Launcher 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 Lawnchair Launcher. If not, see <https://www.gnu.org/licenses/>. */ package app.lawnchair.font import android.content.Context import android.content.res.AssetManager import android.graphics.Typeface import android.net.Uri import androidx.annotation.Keep import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import androidx.core.content.res.ResourcesCompat import androidx.core.provider.FontRequest import androidx.core.provider.FontsContractCompat import app.lawnchair.font.googlefonts.GoogleFontsListing import app.lawnchair.util.getDisplayName import app.lawnchair.util.subscribeFiles import app.lawnchair.util.uiHelperHandler import com.android.launcher3.R import com.android.launcher3.util.MainThreadInitializedObject import kotlinx.coroutines.* import kotlinx.coroutines.flow.map import org.json.JSONArray import org.json.JSONObject import java.io.File import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine import androidx.compose.ui.text.font.Font as ComposeFont import androidx.compose.ui.text.googlefonts.GoogleFont as ComposeGoogleFont class FontCache private constructor(private val context: Context) { private val scope = MainScope() + CoroutineName("FontCache") private val deferredFonts = mutableMapOf<Font, Deferred<LoadedFont?>>() private val cacheDir = context.cacheDir.apply { mkdirs() } private val customFontsDir = TTFFont.getFontsDir(context) val customFonts = customFontsDir.subscribeFiles() .map { files -> files .sortedByDescending { it.lastModified() } .map { TTFFont(context, it) } .filter { it.isAvailable } .map { Family(it) } } val uiRegular = ResourceFont(context, R.font.inter_regular, "Inter") val uiMedium = ResourceFont(context, R.font.inter_medium, "Inter Medium") val uiText = ResourceFont(context, R.font.inter_regular, "Inter") val uiTextMedium = ResourceFont(context, R.font.inter_medium, "Inter Medium") suspend fun getTypeface(font: Font): Typeface? { return loadFontAsync(font).await()?.typeface } fun preloadFont(font: Font) { @Suppress("DeferredResultUnused") loadFontAsync(font) } @OptIn(ExperimentalCoroutinesApi::class) fun getLoadedFont(font: Font): LoadedFont? { val deferredFont = deferredFonts[font] ?: return null if (!deferredFont.isCompleted) return null return deferredFont.getCompleted() } private fun loadFontAsync(font: Font): Deferred<LoadedFont?> { return deferredFonts.getOrPut(font) { scope.async { font.load()?.let { LoadedFont(it) } } } } fun addCustomFont(uri: Uri) { val name = context.contentResolver.getDisplayName(uri) ?: throw AddFontException("Couldn't get file name") val file = TTFFont.getFile(context, name) val tmpFile = File(cacheDir.apply { mkdirs() }, file.name) if (file.exists()) return context.contentResolver.openInputStream(uri)?.use { input -> tmpFile.outputStream().use { output -> input.copyTo(output) } } ?: throw AddFontException("Couldn't open file") if (Typeface.createFromFile(tmpFile) === Typeface.DEFAULT) { tmpFile.delete() throw AddFontException("Not a valid font file") } tmpFile.setLastModified(System.currentTimeMillis()) tmpFile.renameTo(file) @Suppress("DeferredResultUnused") deferredFonts.remove(TTFFont(context, file)) } class Family(val displayName: String, val variants: Map<String, Font>) { constructor(font: Font) : this(font.displayName, mapOf(Pair("regular", font))) val default = variants.getOrElse("regular") { variants.values.first() } val sortedVariants by lazy { variants.values.sortedBy { it.familySorter } } } class TypefaceFamily(val variants: Map<String, Typeface?>) { val default = variants.getOrElse("regular") { variants.values.firstOrNull() } } abstract class Font { abstract val fullDisplayName: String abstract val displayName: String open val familySorter get() = fullDisplayName open val isAvailable get() = true abstract val composeFontFamily: FontFamily abstract suspend fun load(): Typeface? open fun saveToJson(obj: JSONObject) { obj.put(KEY_CLASS_NAME, this::class.java.name) } open fun createWithWeight(weight: Int): Font { return this } fun toJsonString(): String { val obj = JSONObject() saveToJson(obj) return obj.toString() } interface LoadCallback { fun onFontLoaded(typeface: Typeface?) } companion object { fun fromJsonString(context: Context, jsonString: String): Font { val obj = JSONObject(jsonString) val className = obj.getString(KEY_CLASS_NAME) val clazz = Class.forName(className) val constructor = clazz.getMethod("fromJson", Context::class.java, JSONObject::class.java) return constructor.invoke(null, context, obj) as Font } } } abstract class TypefaceFont(protected val typeface: Typeface?) : Font() { override val fullDisplayName = typeface.toString() override val displayName get() = fullDisplayName override suspend fun load(): Typeface? { return typeface } override fun equals(other: Any?): Boolean { return other is TypefaceFont && typeface == other.typeface } override fun hashCode(): Int { return fullDisplayName.hashCode() } } class DummyFont : TypefaceFont(null) { private val hashCode = "DummyFont".hashCode() override val composeFontFamily = FontFamily(Typeface.DEFAULT) override fun equals(other: Any?): Boolean { return other is DummyFont } override fun hashCode(): Int { return hashCode } companion object { @Keep @JvmStatic fun fromJson(context: Context, obj: JSONObject): Font { return DummyFont() } } } class TTFFont(context: Context, private val file: File) : TypefaceFont(createTypeface(file)) { private val actualName: String = Uri.decode(file.name) override val isAvailable = typeface != null override val fullDisplayName: String = if (typeface == null) context.getString(R.string.pref_fonts_missing_font) else actualName override val composeFontFamily = FontFamily(typeface!!) fun delete() = file.delete() override fun saveToJson(obj: JSONObject) { super.saveToJson(obj) obj.put(KEY_FONT_NAME, fullDisplayName) } override fun equals(other: Any?): Boolean { return other is TTFFont && actualName == other.actualName } override fun hashCode() = actualName.hashCode() companion object { fun createTypeface(file: File): Typeface? { return try { Typeface.createFromFile(file) } catch (e: Exception) { null } } fun getFontsDir(context: Context): File { return File(context.filesDir, "customFonts").apply { mkdirs() } } fun getFile(context: Context, name: String): File { return File(getFontsDir(context), Uri.encode(name)) } @Keep @JvmStatic fun fromJson(context: Context, obj: JSONObject): Font { val fontName = obj.getString(KEY_FONT_NAME) return TTFFont(context, getFile(context, fontName)) } } } class SystemFont( val family: String, val style: Int = Typeface.NORMAL) : TypefaceFont(Typeface.create(family, style)) { private val hashCode = "SystemFont|$family|$style".hashCode() override val fullDisplayName = family override val composeFontFamily = FontFamily(typeface!!) override fun saveToJson(obj: JSONObject) { super.saveToJson(obj) obj.put(KEY_FAMILY_NAME, family) obj.put(KEY_STYLE, style) } override fun equals(other: Any?): Boolean { return other is SystemFont && family == other.family && style == other.style } override fun hashCode(): Int { return hashCode } override fun createWithWeight(weight: Int): Font { if (weight >= 700) { return SystemFont(family, Typeface.BOLD) } return super.createWithWeight(weight) } companion object { @Keep @JvmStatic fun fromJson(context: Context, obj: JSONObject): Font { val family = obj.getString(KEY_FAMILY_NAME) val style = obj.getInt(KEY_STYLE) return SystemFont(family, style) } } } class AssetFont( assets: AssetManager, private val name: String) : TypefaceFont(Typeface.createFromAsset(assets, "$name.ttf")) { private val hashCode = "AssetFont|$name".hashCode() override val fullDisplayName = name @OptIn(ExperimentalTextApi::class) override val composeFontFamily = FontFamily(ComposeFont("$name.ttf", assets)) override fun equals(other: Any?): Boolean { return other is AssetFont && name == other.name } override fun hashCode(): Int { return hashCode } } class ResourceFont( context: Context, resId: Int, private val name: String ) : TypefaceFont(ResourcesCompat.getFont(context, resId)) { private val hashCode = "ResourceFont|$name".hashCode() override val fullDisplayName = name override val composeFontFamily = FontFamily(ComposeFont(resId)) override fun equals(other: Any?): Boolean { return other is ResourceFont && name == other.name } override fun hashCode(): Int { return hashCode } } @OptIn(ExperimentalTextApi::class) class GoogleFont( private val context: Context, private val family: String, private val variant: String = "regular", private val variants: Array<String> = emptyArray()) : Font() { private val hashCode = "GoogleFont|$family|$variant".hashCode() override val displayName = createVariantName() override val fullDisplayName = "$family $displayName" override val familySorter = "${GoogleFontsListing.getWeight(variant)}${GoogleFontsListing.isItalic(variant)}" override val composeFontFamily = FontFamily( androidx.compose.ui.text.googlefonts.Font( googleFont = ComposeGoogleFont(family), fontProvider = provider, weight = FontWeight(GoogleFontsListing.getWeight(variant).toInt()), style = if (GoogleFontsListing.isItalic(variant)) FontStyle.Italic else FontStyle.Normal ) ) private fun createVariantName(): String { if (variant == "italic") return context.getString(R.string.font_variant_italic) val weight = GoogleFontsListing.getWeight(variant) val weightString = weightNameMap[weight]?.let(context::getString) ?: weight val italicString = if (GoogleFontsListing.isItalic(variant)) " " + context.getString(R.string.font_variant_italic) else "" return "$weightString$italicString" } override suspend fun load(): Typeface? { val request = FontRequest( "com.google.android.gms.fonts", // ProviderAuthority "com.google.android.gms", // ProviderPackage GoogleFontsListing.buildQuery(family, variant), // Query R.array.com_google_android_gms_fonts_certs) return suspendCoroutine { FontsContractCompat.requestFont(context, request, object: FontsContractCompat.FontRequestCallback() { override fun onTypefaceRetrieved(typeface: Typeface) { it.resume(typeface) } override fun onTypefaceRequestFailed(reason: Int) { it.resume(null) } }, uiHelperHandler) } } override fun saveToJson(obj: JSONObject) { super.saveToJson(obj) obj.put(KEY_FAMILY_NAME, family) obj.put(KEY_VARIANT, variant) val variantsArray = JSONArray() variants.forEach { variantsArray.put(it) } obj.put(KEY_VARIANTS, variantsArray) } override fun equals(other: Any?): Boolean { return other is GoogleFont && family == other.family && variant == other.variant } override fun hashCode(): Int { return hashCode } override fun createWithWeight(weight: Int): Font { if (weight == -1) return this val currentWeight = GoogleFontsListing.getWeight(variant).toInt() if (weight == currentWeight) return this val newVariant = if (weight > currentWeight) findHeavier(weight, currentWeight, GoogleFontsListing.isItalic(variant)) else findLighter(weight, currentWeight, GoogleFontsListing.isItalic(variant)) if (newVariant != null) { return GoogleFont(context, family, newVariant, variants) } return super.createWithWeight(weight) } private fun findHeavier(weight: Int, minWeight: Int, italic: Boolean): String? { val variants = variants.filter { it.contains("italic") == italic } return variants.lastOrNull { val variantWeight = GoogleFontsListing.getWeight(it).toInt() variantWeight in minWeight..weight } ?: variants.firstOrNull { GoogleFontsListing.getWeight(it).toInt() >= minWeight } } private fun findLighter(weight: Int, maxWeight: Int, italic: Boolean): String? { val variants = variants.filter { it.contains("italic") == italic } return variants.firstOrNull { val variantWeight = GoogleFontsListing.getWeight(it).toInt() variantWeight in weight..maxWeight } ?: variants.lastOrNull { GoogleFontsListing.getWeight(it).toInt() <= maxWeight } } companion object { @Keep @JvmStatic fun fromJson(context: Context, obj: JSONObject): Font { val family = obj.getString(KEY_FAMILY_NAME) val variant = obj.getString(KEY_VARIANT) val variantsArray = obj.optJSONArray(KEY_VARIANTS) ?: JSONArray() val variants = Array<String>(variantsArray.length()) { variantsArray.getString(it) } return GoogleFont(context, family, variant, variants) } } } class LoadedFont internal constructor(val typeface: Typeface) companion object { @JvmField val INSTANCE = MainThreadInitializedObject(::FontCache) private const val KEY_CLASS_NAME = "className" private const val KEY_FAMILY_NAME = "family" private const val KEY_STYLE = "style" private const val KEY_VARIANT = "variant" private const val KEY_VARIANTS = "variants" private const val KEY_FONT_NAME = "font" private val weightNameMap: Map<String, Int> = mapOf( Pair("100", R.string.font_weight_thin), Pair("200", R.string.font_weight_extra_light), Pair("300", R.string.font_weight_light), Pair("400", R.string.font_weight_regular), Pair("500", R.string.font_weight_medium), Pair("600", R.string.font_weight_semi_bold), Pair("700", R.string.font_weight_bold), Pair("800", R.string.font_weight_extra_bold), Pair("900", R.string.font_weight_extra_black) ) @OptIn(ExperimentalTextApi::class) val provider = ComposeGoogleFont.Provider( providerAuthority = "com.google.android.gms.fonts", providerPackage = "com.google.android.gms", certificates = R.array.com_google_android_gms_fonts_certs ) } class AddFontException(message: String) : Exception(message) }
gpl-3.0
785e0a4ca70b1a2ffc6067360ad1fd8a
34.772636
117
0.614658
4.733493
false
false
false
false
jdinkla/groovy-java-ray-tracer
src/main/kotlin/net/dinkla/raytracer/math/Vector2D.kt
1
655
package net.dinkla.raytracer.math class Vector2D(x: Double, y: Double) : Element2D(x, y) { operator fun plus(v: Vector2D) = Vector2D(x + v.x, y + v.y) operator fun minus(v: Vector2D) = Vector2D(x - v.x, y - v.y) operator fun times(s: Double) = Vector2D(s * x, s * y) infix fun dot(v: Vector2D): Double = x * v.x + y * v.y infix fun dot(v: Normal): Double = x * v.x + y * v.y operator fun unaryMinus() = Vector2D(-x, -y) fun normalize(): Vector2D { val l = length() return Vector2D(x / l, y / l) } } operator fun Double.times(v: Vector2D) = Vector2D(this * v.x, this * v.y)
apache-2.0
f09f31aa3f47de2e21385620da91b61d
25.291667
73
0.566412
2.763713
false
false
false
false
youlookwhat/CloudReader
app/src/main/java/com/example/jingbin/cloudreader/app/Constants.kt
1
1669
package com.example.jingbin.cloudreader.app /** * Created by jingbin on 2016/11/26. * 固定参数 */ open class Constants { companion object { // 下载的链接 const val DOWNLOAD_URL = "https://www.coolapk.com/apk/127875" // 隐私政策 const val PRIVATE_URL = "https://jingbin127.gitee.io/apiserver/privacy.html" // 深色模式 const val KEY_MODE_NIGHT = "mode-night" // 跟随系统 const val KEY_MODE_SYSTEM = "mode-system" // 是否打开过酷安应用市场 const val SHOW_MARKET = "show_market" // 酷安包名 const val COOLAPK_PACKAGE = "com.coolapk.market" // 热映缓存 const val ONE_HOT_MOVIE = "one_hot_movie" // 保存每日推荐轮播图url const val BANNER_PIC = "gank_banner_pic" // 保存每日推荐轮播图的跳转数据 const val BANNER_PIC_DATA = "gank_banner_data" // 保存每日推荐recyclerview内容 const val EVERYDAY_CONTENT = "everyday_content" // 干货订制类别 const val GANK_TYPE = "gank_type" // 是否登录 const val IS_LOGIN = "is_login" // 是否第一次收藏网址 const val IS_FIRST_COLLECTURL = "isFirstCollectUrl" // 问题反馈消息提示 const val MESSAGE_READ_TIP = "message_read_tip" // 深色模式消息提示 const val MESSAGE_READ_NIGHT_TIP = "message_read_night_tip" // 发现页内容角标 const val FIND_POSITION = "find_position" // 是否同意隐私政策 const val IS_AGREE_PRIVATE = "is_agree_private" } }
apache-2.0
0bab7cee9aceb7d1dae84905fd601654
30.043478
84
0.585844
3.062232
false
false
false
false
yshrsmz/monotweety
app/src/main/java/net/yslibrary/monotweety/setting/SettingController.kt
1
10129
package net.yslibrary.monotweety.setting import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.SwitchCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import com.bluelinelabs.conductor.ControllerChangeHandler import com.bluelinelabs.conductor.ControllerChangeType import com.bluelinelabs.conductor.RouterTransaction import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler import com.gojuno.koptional.rxjava2.filterSome import com.jakewharton.rxbinding3.widget.checkedChanges import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.rxkotlin.subscribeBy import net.yslibrary.monotweety.App import net.yslibrary.monotweety.Navigator import net.yslibrary.monotweety.R import net.yslibrary.monotweety.analytics.Analytics import net.yslibrary.monotweety.appdata.appinfo.AppInfo import net.yslibrary.monotweety.base.ActionBarController import net.yslibrary.monotweety.base.HasComponent import net.yslibrary.monotweety.base.ObjectWatcherDelegate import net.yslibrary.monotweety.base.findById import net.yslibrary.monotweety.changelog.ChangelogController import net.yslibrary.monotweety.license.LicenseController import net.yslibrary.monotweety.setting.adapter.SettingAdapter import net.yslibrary.monotweety.setting.adapter.SubHeaderDividerDecoration import timber.log.Timber import javax.inject.Inject import kotlin.properties.Delegates class SettingController : ActionBarController(), HasComponent<SettingComponent> { @set:[Inject] var navigator by Delegates.notNull<Navigator>() @set:[Inject] var viewModel by Delegates.notNull<SettingViewModel>() @set:[Inject] var refWatcherDelegate by Delegates.notNull<ObjectWatcherDelegate>() lateinit var bindings: Bindings val settingAdapter by lazy { SettingAdapter(applicationContext!!.resources, adapterListener) } val adapterListener = object : SettingAdapter.Listener { override fun onPrivacyPolicyClick() { viewModel.onPrivacyPolicyRequested() } override fun onAppVersionClick() { viewModel.onChangelogRequested() } override fun onDeveloperClick() { viewModel.onDeveloperRequested() } override fun onShareClick() { viewModel.onShareRequested() } override fun onGooglePlayClick() { viewModel.onGooglePlayRequested() } override fun onGitHubClick() { viewModel.onGitHubRequested() } override fun onLicenseClick() { viewModel.onLicenseRequested() } override fun onFooterStateChanged(enabled: Boolean, text: String) { viewModel.onFooterStateChanged(enabled, text) } override fun onTimelineAppChanged(selectedApp: AppInfo) { viewModel.onTimelineAppChanged(selectedApp) } override fun onLogoutClick() { activity?.let { Timber.tag("Dialog").i("onLogoutClick") AlertDialog.Builder(it) .setTitle(R.string.label_confirm) .setMessage(R.string.label_logout_confirm) .setCancelable(true) .setPositiveButton(R.string.label_logout) { dialog, _ -> viewModel.onLogoutRequested() dialog.dismiss() } .setNegativeButton(R.string.label_no) { dialog, _ -> dialog.cancel() } .show() } } override fun onOpenProfileClick() { viewModel.onOpenProfileRequested() } } override val title: String? get() = getString(R.string.title_setting) override val component: SettingComponent by lazy { val provider = getComponentProvider<SettingViewModule.DependencyProvider>(activity!!) val activityBus = provider.activityBus() val navigator = provider.navigator() DaggerSettingComponent.builder() .userComponent(App.userComponent(applicationContext!!)) .settingViewModule(SettingViewModule(activityBus, navigator)) .build() } override fun onContextAvailable(context: Context) { super.onContextAvailable(context) component.inject(this) analytics.viewEvent(Analytics.VIEW_SETTING) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val view = inflater.inflate(R.layout.controller_setting, container, false) bindings = Bindings(view) bindings.list.apply { if (itemAnimator is SimpleItemAnimator) { (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false } layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) setHasFixedSize(true) addItemDecoration(SubHeaderDividerDecoration(activity!!)) adapter = settingAdapter } setEvents() return view } fun setEvents() { // make sure to get saved status before subscribes to view events viewModel.notificationEnabledChanged .bindToLifecycle() .doOnNext { val res = if (it) R.string.label_on else R.string.label_off bindings.notificationSwitch.text = getString(R.string.label_notificatoin_state, getString(res)) bindings.notificationSwitch.isChecked = it } .subscribe { Timber.d("notification enabled: $it") if (it) startNotificationService() else stopNotificationService() } viewModel.footerState .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { settingAdapter.updateFooterState(it.enabled, it.text) } viewModel.selectedTimelineApp .switchMap { app -> viewModel.installedSupportedApps .map { Pair(app, it) }.toObservable() } .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { settingAdapter.updateTimelineApp(it.first, it.second) } viewModel.user .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .filterSome() .subscribeBy { Timber.d("user: $it") it.let { settingAdapter.updateProfile(it) } } viewModel.openProfileRequests .bindToLifecycle() .subscribe { navigator.openProfileWithTwitterApp(it) } viewModel.logoutRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { logout() } viewModel.privacyPolicyRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { navigator.openExternalAppWithUrl(it) } viewModel.licenseRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { showLicense() } viewModel.developerRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { navigator.openExternalAppWithUrl(it) } viewModel.shareRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { navigator.openExternalAppWithShareIntent( getString( R.string.message_share, it ) ) } viewModel.googlePlayRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { navigator.openExternalAppWithUrl(it) } viewModel.githubRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { navigator.openExternalAppWithUrl(it) } viewModel.changelogRequests .bindToLifecycle() .observeOn(AndroidSchedulers.mainThread()) .subscribe { showChangelog() } bindings.notificationSwitch .checkedChanges() .bindToLifecycle() .subscribe { viewModel.onNotificationEnabledChanged(it) } } fun startNotificationService() { navigator.startNotificationService() } fun stopNotificationService() { navigator.stopNotificationService() } fun logout() { navigator.startLogoutService() activity?.finish() } fun showLicense() { router.pushController( RouterTransaction.with(LicenseController()) .pushChangeHandler(HorizontalChangeHandler()) .popChangeHandler(HorizontalChangeHandler()) ) } fun showChangelog() { router.pushController( RouterTransaction.with(ChangelogController()) .pushChangeHandler(HorizontalChangeHandler()) .popChangeHandler(HorizontalChangeHandler()) ) } override fun onChangeEnded( changeHandler: ControllerChangeHandler, changeType: ControllerChangeType ) { super.onChangeEnded(changeHandler, changeType) refWatcherDelegate.handleOnChangeEnded(isDestroyed, changeType) } override fun onDestroy() { super.onDestroy() refWatcherDelegate.handleOnDestroy() } inner class Bindings(view: View) { val notificationSwitch = view.findById<SwitchCompat>(R.id.notification_switch) val list = view.findById<RecyclerView>(R.id.list) } }
apache-2.0
a71a85739e892499b4452c8a1e8c95f6
33.104377
98
0.644684
5.541028
false
false
false
false
Kiskae/Twitch-Archiver
ui/src/main/kotlin/net/serverpeon/twitcharchiver/fx/sections/OAuthInput.kt
1
4819
package net.serverpeon.twitcharchiver.fx.sections import com.google.common.io.Files import javafx.beans.binding.When import javafx.beans.property.ReadOnlyStringProperty import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleStringProperty import javafx.event.Event import javafx.event.EventHandler import javafx.geometry.Orientation import javafx.geometry.Pos import javafx.scene.Node import javafx.scene.control.Button import javafx.scene.control.Label import javafx.scene.control.Separator import javafx.scene.control.TitledPane import javafx.stage.FileChooser import javafx.stage.Window import net.serverpeon.twitcharchiver.OAuthFile import net.serverpeon.twitcharchiver.fx.hbox import net.serverpeon.twitcharchiver.network.ApiWrapper import net.serverpeon.twitcharchiver.twitch.OAuthToken import java.io.File class OAuthInput(val api: ApiWrapper, val token: OAuthToken) : TitledPane() { private val processingValue = SimpleBooleanProperty(false) private val username = SimpleStringProperty(null) private val authorizeButton = Button("Authorize").apply { onAction = EventHandler { val result = AuthenticateDialog(AUTH_STATE_TOKEN).showAndWait() result.ifPresent { attemptAuth(it) } } } private val importButton = Button("Import").apply { onAction = EventHandler { val key = importOauthKey(it.window()) if (key != null) { attemptAuth(key) } } } private val exportButton = Button("Export").apply { disableProperty().bind(username.isEmpty) onAction = EventHandler { exportOauthKey( token.value!!, username.get(), it.window() ) } } val apiBinding = api.hasAccess(this) val usernameProp: ReadOnlyStringProperty get() = username init { text = "OAuth Token" content = hbox { +Label("Current status: ") +Label().apply { style = "-fx-font-weight: bold" textProperty().bind(When(username.isEmpty).then("Unauthorized").otherwise("Authorized")) } +Separator(Orientation.VERTICAL) +authorizeButton +importButton +exportButton init { alignment = Pos.CENTER_RIGHT } } disableProperty().bind(apiBinding.not().or(processingValue)) } private fun attemptAuth(oauthKey: String) { processingValue.set(true) api.request(this) { username.set(null) token.value = oauthKey this.retrieveUser().toObservable() }.doOnTerminate { processingValue.set(false) }.subscribe { if (it.isPresent) { username.set(it.get()) } else { println("Invalid token") //TODO: dialog, invalid token } } } companion object { private val OAUTH_EXTENSION_FILTER = FileChooser.ExtensionFilter("OAuth key files", "*.oauth") private val TWITCH_ARCHIVER_DIRECTORY = File(System.getProperty("user.home"), "twitch-archiver").apply { mkdirs() } private val AUTH_STATE_TOKEN = System.getProperty("auth_token", "Kappa") private fun Event.window(): Window { return (this.target as Node).scene.window } private fun exportOauthKey(key: String, suggestedName: String, window: Window) { val outputFile = FileChooser().apply { this.extensionFilters.clear() this.extensionFilters.add(OAUTH_EXTENSION_FILTER) this.initialFileName = suggestedName this.initialDirectory = TWITCH_ARCHIVER_DIRECTORY }.showSaveDialog(window) if (outputFile != null) { OAuthFile.from(key).write(Files.asCharSink(outputFile, Charsets.UTF_8)) } } private fun importOauthKey(window: Window): String? { val inputFile = FileChooser().apply { this.extensionFilters.clear() this.extensionFilters.add(OAUTH_EXTENSION_FILTER) this.initialDirectory = TWITCH_ARCHIVER_DIRECTORY }.showOpenDialog(window) return if (inputFile != null) { val keyFile = OAuthFile.read(Files.asCharSource(inputFile, Charsets.UTF_8)) if (keyFile.isValid()) { keyFile.oauthKey() } else { keyFile.invalidationReason().printStackTrace() null } } else { null } } } }
mit
6b9f25a2643277a0e199c199a9be441a
31.567568
112
0.599709
4.862765
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/view/ui/actors/AdvancedTouchpad.kt
1
2081
package ru.icarumbas.bagel.view.ui.actors import com.badlogic.gdx.Gdx import com.badlogic.gdx.math.Vector2 import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.ui.Touchpad import ru.icarumbas.bagel.engine.controller.PlayerMoveController class AdvancedTouchpad : Touchpad, PlayerMoveController { // Touch event to work properly private val screenPos = Vector2() private var localPos = Vector2() private val fakeTouchDownEvent = InputEvent() // Make invisible when not pressed var changeVisible = true constructor(deadZone: Float, style: TouchpadStyle) : super(deadZone, style) { fakeTouchDownEvent.type = InputEvent.Type.touchDown } override fun act(delta: Float) { super.act(delta) getDirection() } private fun getDirection() { if (Gdx.input.justTouched()) { // Get the touch point in screen coordinates. screenPos.set(Gdx.input.x.toFloat(), Gdx.input.y.toFloat()) if (screenPos.x < Gdx.graphics.width / 2) { // Convert the touch point into local coordinates, place the touchpad and show it. localPos.set(screenPos) localPos = parent.screenToLocalCoordinates(localPos) setPosition(localPos.x - width / 2, localPos.y - height / 2) // Fire a touch down event to get the touchpad working. val stagePos = stage.screenToStageCoordinates(screenPos) fakeTouchDownEvent.stageX = stagePos.x fakeTouchDownEvent.stageY = stagePos.y fire(fakeTouchDownEvent) isVisible = true } } else if (!Gdx.input.isTouched && changeVisible) { isVisible = false } } override fun isUpPressed() = knobY > height / 2 + width / 10 override fun isRightPressed() = knobX > width / 2 + width / 20 override fun isDownPressed() = knobY < height / 2f - width / 6f override fun isLeftPressed() = knobX < width / 2 - width / 20 }
apache-2.0
c380941d9a8462c73b4459824d7427c0
29.617647
98
0.640077
4.290722
false
false
false
false
google/ksp
integration-tests/src/test/resources/init-plus-provider/provider-processor/src/main/kotlin/TestProcessor.kt
1
1359
import com.google.devtools.ksp.processing.* import com.google.devtools.ksp.symbol.* import java.io.OutputStream fun OutputStream.appendText(str: String) { this.write(str.toByteArray()) } class TestProcessor(options: Map<String, String>, val codeGenerator: CodeGenerator) : SymbolProcessor { val file: OutputStream = codeGenerator.createNewFile(Dependencies(false), "", "TestProcessor", "log") init { file.appendText("TestProcessor: init($options)\n") val javaFile = codeGenerator.createNewFile(Dependencies(false), "", "GeneratedFromProvider", "java") javaFile.appendText("class GeneratedFromProvider {}") } var invoked = false override fun process(resolver: Resolver): List<KSAnnotated> { if (invoked) { return emptyList() } val fileKt = codeGenerator.createNewFile(Dependencies(false), "", "HelloFromProvider", "java") fileKt.appendText("public class HelloFromProvider{\n") fileKt.appendText(" public int foo() { return 5678; }\n") fileKt.appendText("}") invoked = true return emptyList() } class Provider : SymbolProcessorProvider { override fun create( environment: SymbolProcessorEnvironment ): SymbolProcessor = TestProcessor(environment.options, environment.codeGenerator) } }
apache-2.0
5525990849aace31d8b9436e92d6e04e
32.146341
108
0.679912
4.853571
false
true
false
false
google/ksp
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/ReferenceElementProcessor.kt
1
3386
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.processor import com.google.devtools.ksp.getPropertyDeclarationByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.visitor.KSTopDownVisitor open class ReferenceElementProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() val collector = ReferenceCollector() val references = mutableSetOf<KSTypeReference>() override fun process(resolver: Resolver): List<KSAnnotated> { val files = resolver.getNewFiles() files.forEach { it.accept(collector, references) } resolver.getPropertyDeclarationByName("z", true)!!.accept(collector, references) resolver.getPropertyDeclarationByName("w", true)!!.accept(collector, references) fun refName(it: KSTypeReference) = (it.element as KSClassifierReference).referencedName() val sortedReferences = references.filter { it.element is KSClassifierReference && it.origin == Origin.KOTLIN }.sortedBy(::refName) for (i in sortedReferences) results.add( "KSClassifierReferenceImpl: Qualifier of ${i.element} is ${ (i.element as KSClassifierReference).qualifier }" ) // FIXME: References in getters and type arguments are not compared to equal. val descriptorReferences = references.filter { it.element is KSClassifierReference && it.origin == Origin.KOTLIN_LIB } .distinctBy(::refName).sortedBy(::refName) for (i in descriptorReferences) { results.add( "KSClassifierReferenceDescriptorImpl: Qualifier of ${i.element} is ${ (i.element as KSClassifierReference).qualifier }" ) } val javaReferences = references.filter { it.element is KSClassifierReference && it.origin == Origin.JAVA } .sortedBy(::refName) for (i in javaReferences) { results.add( "KSClassifierReferenceJavaImpl: Qualifier of ${i.element} is ${ (i.element as KSClassifierReference).qualifier}" ) } return emptyList() } override fun toResult(): List<String> { return results } } class ReferenceCollector : KSTopDownVisitor<MutableSet<KSTypeReference>, Unit>() { override fun defaultHandler(node: KSNode, data: MutableSet<KSTypeReference>) = Unit override fun visitTypeReference(typeReference: KSTypeReference, data: MutableSet<KSTypeReference>) { super.visitTypeReference(typeReference, data) data.add(typeReference) } }
apache-2.0
29a2092ac1ffcb9aa48739222d634c8e
38.372093
119
0.676905
4.802837
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/lang/core/psi/RsFile.kt
1
8374
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.psi import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.fileTypes.FileType import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.FileViewProvider import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import com.intellij.psi.util.PsiTreeUtil import org.rust.lang.RsFileType import org.rust.lang.RsLanguage import org.rust.lang.core.psi.ext.RsInnerAttributeOwner import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.cargoWorkspace import org.rust.lang.core.psi.ext.queryAttributes import org.rust.lang.core.resolve.ref.RsReference import org.rust.lang.core.stubs.RsFileStub import org.rust.lang.core.stubs.index.RsModulesIndex class RsFile( fileViewProvider: FileViewProvider ) : PsiFileBase(fileViewProvider, RsLanguage), RsMod, RsInnerAttributeOwner { override fun getReference(): RsReference? = null override val containingMod: RsMod get() = this override fun getFileType(): FileType = RsFileType override fun getStub(): RsFileStub? = super.getStub() as RsFileStub? override fun getOriginalFile(): RsFile = super.getOriginalFile() as RsFile override fun setName(name: String): PsiElement { val nameWithExtension = if ('.' !in name) "$name.rs" else name return super.setName(nameWithExtension) } override val `super`: RsMod? get() { // XXX: without this we'll close over `thisFile`, and it's verboten // to store references to PSI inside `CachedValueProvider` other than // the key PSI element val originalFile = originalFile return CachedValuesManager.getCachedValue(originalFile, { CachedValueProvider.Result.create( RsModulesIndex.getSuperFor(originalFile), PsiModificationTracker.MODIFICATION_COUNT ) }) } override val modName: String? = if (name != RsMod.MOD_RS) FileUtil.getNameWithoutExtension(name) else parent?.name override val crateRelativePath: String? get() = RsPsiImplUtil.modCrateRelativePath(this) override val ownsDirectory: Boolean get() = name == RsMod.MOD_RS || isCrateRoot override val ownedDirectory: PsiDirectory? get() = originalFile.parent override val isCrateRoot: Boolean get() { val file = originalFile.virtualFile ?: return false return cargoWorkspace?.isCrateRoot(file) ?: false } override val innerAttrList: List<RsInnerAttr> get() = PsiTreeUtil.getChildrenOfTypeAsList(this, RsInnerAttr::class.java) val attributes: Attributes get() { val stub = stub if (stub != null) return stub.attributes if (queryAttributes.hasAtomAttribute("no_core")) return Attributes.NO_CORE if (queryAttributes.hasAtomAttribute("no_std")) return Attributes.NO_STD return Attributes.NONE } enum class Attributes { NO_CORE, NO_STD, NONE } override val functionList: List<RsFunction> get() = itemsCache.functionList override val modItemList: List<RsModItem> get() = itemsCache.modItemList override val constantList: List<RsConstant> get() = itemsCache.constantList override val structItemList: List<RsStructItem> get() = itemsCache.structItemList override val enumItemList: List<RsEnumItem> get() = itemsCache.enumItemList override val implItemList: List<RsImplItem> get() = itemsCache.implItemList override val traitItemList: List<RsTraitItem> get() = itemsCache.traitItemList override val typeAliasList: List<RsTypeAlias> get() = itemsCache.typeAliasList override val useItemList: List<RsUseItem> get() = itemsCache.useItemList override val modDeclItemList: List<RsModDeclItem> get() = itemsCache.modDeclItemList override val externCrateItemList: List<RsExternCrateItem> get() = itemsCache.externCrateItemList override val foreignModItemList: List<RsForeignModItem> get() = itemsCache.foreignModItemList override val macroDefinitionList: List<RsMacroDefinition> get() = itemsCache.macroDefinitionList private class ItemsCache( val functionList: List<RsFunction>, val modItemList: List<RsModItem>, val constantList: List<RsConstant>, val structItemList: List<RsStructItem>, val enumItemList: List<RsEnumItem>, val implItemList: List<RsImplItem>, val traitItemList: List<RsTraitItem>, val typeAliasList: List<RsTypeAlias>, val useItemList: List<RsUseItem>, val modDeclItemList: List<RsModDeclItem>, val externCrateItemList: List<RsExternCrateItem>, val foreignModItemList: List<RsForeignModItem>, val macroDefinitionList: List<RsMacroDefinition> ) @Volatile private var _itemsCache: ItemsCache? = null override fun subtreeChanged() { super.subtreeChanged() _itemsCache = null } private val itemsCache: ItemsCache get() { var cached = _itemsCache if (cached != null) return cached // Might calculate cache twice concurrently, but that's ok. // Can't race with subtreeChanged. val functionList = mutableListOf<RsFunction>() val modItemList = mutableListOf<RsModItem>() val constantList = mutableListOf<RsConstant>() val structItemList = mutableListOf<RsStructItem>() val enumItemList = mutableListOf<RsEnumItem>() val implItemList = mutableListOf<RsImplItem>() val traitItemList = mutableListOf<RsTraitItem>() val typeAliasList = mutableListOf<RsTypeAlias>() val useItemList = mutableListOf<RsUseItem>() val modDeclItemList = mutableListOf<RsModDeclItem>() val externCrateItemList = mutableListOf<RsExternCrateItem>() val foreignModItemList = mutableListOf<RsForeignModItem>() val macroDefinitionList = mutableListOf<RsMacroDefinition>() fun add(psi: PsiElement) { when (psi) { is RsFunction -> functionList.add(psi) is RsModItem -> modItemList.add(psi) is RsConstant -> constantList.add(psi) is RsStructItem -> structItemList.add(psi) is RsEnumItem -> enumItemList.add(psi) is RsImplItem -> implItemList.add(psi) is RsTraitItem -> traitItemList.add(psi) is RsTypeAlias -> typeAliasList.add(psi) is RsUseItem -> useItemList.add(psi) is RsModDeclItem -> modDeclItemList.add(psi) is RsExternCrateItem -> externCrateItemList.add(psi) is RsForeignModItem -> foreignModItemList.add(psi) is RsMacroDefinition -> macroDefinitionList.add(psi) } } val stub = stub if (stub != null) { stub.childrenStubs.forEach { add(it.psi) } } else { var child = firstChild while (child != null) { add(child) child = child.nextSibling } } cached = ItemsCache( functionList, modItemList, constantList, structItemList, enumItemList, implItemList, traitItemList, typeAliasList, useItemList, modDeclItemList, externCrateItemList, foreignModItemList, macroDefinitionList ) _itemsCache = cached return cached } } val PsiFile.rustMod: RsMod? get() = this as? RsFile val VirtualFile.isNotRustFile: Boolean get() = !isRustFile val VirtualFile.isRustFile: Boolean get() = fileType == RsFileType
mit
f0f449741eac52e0f0cdc120b2fda632
39.259615
118
0.652376
5.014371
false
false
false
false
rumboalla/apkupdater
app/src/main/java/com/apkupdater/util/app/AlarmUtil.kt
1
2171
package com.apkupdater.util.app import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import com.apkupdater.receiver.AlarmReceiver import org.koin.core.KoinComponent import java.util.Calendar class AlarmUtil(private val context: Context, private val prefs: AppPrefs): KoinComponent { private val alarmManager get() = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager private var pendingIntent: PendingIntent? = null fun setupAlarm(context: Context) = if (isEnabled()) enableAlarm(context) else cancelAlarm() private fun cancelAlarm() = pendingIntent?.let { alarmManager.cancel(it) } private fun enableAlarm(context: Context, interval: Long = getInterval()) { pendingIntent = PendingIntent.getBroadcast(context, 0, Intent(context, AlarmReceiver::class.java), PendingIntent.FLAG_UPDATE_CURRENT) val now = System.currentTimeMillis() val time = Calendar.getInstance().apply { timeInMillis = now } when(prefs.settings.checkForUpdates) { "0" -> { // Daily setHour(time) if (time.timeInMillis < now) { time.add(Calendar.MILLISECOND, interval.toInt()) } } "1" -> { // Weekly setHour(time) time.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY) if (time.timeInMillis < now) { time.add(Calendar.MILLISECOND, interval.toInt()) } } else -> { setHour(time, time.get(Calendar.HOUR_OF_DAY)) time.add(Calendar.MILLISECOND, interval.toInt()) } } alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, time.timeInMillis, interval, pendingIntent) } private fun getInterval() = when(prefs.settings.checkForUpdates) { "0" -> AlarmManager.INTERVAL_DAY "1" -> AlarmManager.INTERVAL_DAY * 7 "2" -> AlarmManager.INTERVAL_HOUR "3" -> AlarmManager.INTERVAL_HOUR * 12 "4" -> AlarmManager.INTERVAL_HOUR * 6 else -> Long.MAX_VALUE } private fun setHour(time: Calendar, hour: Int = prefs.settings.updateHour) = time.apply { set(Calendar.HOUR_OF_DAY, hour) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) } private fun isEnabled() = prefs.settings.checkForUpdates != "5" }
gpl-3.0
3c11bcc30484c68b5d4728e6b60f2136
31.41791
135
0.729157
3.576606
false
false
false
false
millross/millross-vertx-servo
src/main/kotlin/com/millross/vertx/servo/TestWebServer.kt
1
1949
package com.millross.vertx.servo import com.netflix.servo.annotations.DataSourceType.COUNTER import com.netflix.servo.annotations.Monitor import com.netflix.servo.monitor.Monitors import com.netflix.servo.publish.* import com.netflix.servo.publish.graphite.GraphiteMetricObserver import io.vertx.core.AbstractVerticle import io.vertx.core.Future import io.vertx.ext.web.Router import io.vertx.ext.web.RoutingContext import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger /** * Simple test webserver verticle to try and collect some trivial metrics via servo */ class TestWebServer : AbstractVerticle() { // Servo monitoring of the invocation count @Monitor(name="invocation.count", type=COUNTER) private val invocationCount = AtomicInteger(0) override fun start(startFuture: Future<Void>?) { super.start(startFuture) val router = Router.router(vertx) router.get("/testMetric").handler { handleMetricTest(it) } router.get("/").handler { index(it) } Monitors.registerObject("TestWebServer", this) // Set up a graphite observer val prefix = "servo" val addr = "localhost:2003" val observer = GraphiteMetricObserver(prefix, addr) PollScheduler.getInstance().start() schedule(MonitorRegistryMetricPoller(), observer) vertx.createHttpServer() .requestHandler { router.accept(it) } .listen(8080) } fun handleMetricTest(rc: RoutingContext) { invocationCount.incrementAndGet() rc.response().end("Metric triggered") } fun index(rc: RoutingContext) { rc.response().sendFile("webroot/index.html") } fun schedule(poller: MetricPoller, observer: MetricObserver) { val task = PollRunnable(poller, BasicMetricFilter.MATCH_ALL, observer) PollScheduler.getInstance().addPoller(task, 10, TimeUnit.SECONDS) } }
mit
192307a86344ccc83dd03d913a50efeb
30.967213
83
0.707029
4.209503
false
true
false
false
jtransc/jtransc
jtransc-utils/src/com/jtransc/template/Minitemplate.kt
1
15983
package com.jtransc.template import com.jtransc.ds.ListReader import com.jtransc.error.invalidOp import com.jtransc.imaging.ImagePropsDecoder import com.jtransc.json.Json import com.jtransc.lang.Dynamic import com.jtransc.text.* import java.io.File class Minitemplate(val template: String, val config: Config = Config()) { val templateTokens = Token.tokenize(template) val node = BlockNode.parse(templateTokens, config) class Config( private val extraTags: List<Tag> = listOf(), private val extraFilters: List<Filter> = listOf() ) { val integratedFilters = listOf( Filter("length") { subject, args -> Dynamic.length(subject) }, Filter("capitalize") { subject, args -> Dynamic.toString(subject).toLowerCase().capitalize() }, Filter("upper") { subject, args -> Dynamic.toString(subject).toUpperCase() }, Filter("lower") { subject, args -> Dynamic.toString(subject).toLowerCase() }, Filter("trim") { subject, args -> Dynamic.toString(subject).trim() }, Filter("quote") { subject, args -> Dynamic.toString(subject).quote() }, Filter("escape") { subject, args -> Dynamic.toString(subject).escape() }, Filter("json") { subject, args -> Json.encodeAny(subject) }, Filter("join") { subject, args -> Dynamic.toIterable(subject).map { Dynamic.toString(it) }.joinToString(Dynamic.toString(args[0])) }, Filter("file_exists") { subject, args -> File(Dynamic.toString(subject)).exists() }, Filter("image_info") { subject, args -> if (subject is ByteArray) { ImagePropsDecoder.tryDecodeHeader(subject) } else { val file = when (subject) { is File -> subject else -> File(Dynamic.toString(subject)) } ImagePropsDecoder.tryDecodeHeader(file) } } ) private val allTags = listOf(Tag.EMPTY, Tag.IF, Tag.FOR, Tag.SET, Tag.DEBUG) + extraTags private val allFilters = integratedFilters + extraFilters val tags = hashMapOf<String, Tag>().apply { for (tag in allTags) { this[tag.name] = tag for (alias in tag.aliases) this[alias] = tag } } val filters = hashMapOf<String, Filter>().apply { for (filter in allFilters) this[filter.name] = filter } } data class Filter(val name: String, val eval: (subject: Any?, args: List<Any?>) -> Any?) class Scope(val map: Any?, val parent: Scope? = null) { operator fun get(key: Any?): Any? { return Dynamic.accessAny(map, key) ?: parent?.get(key) } operator fun set(key: Any?, value: Any?) { Dynamic.setAny(map, key, value) } } operator fun invoke(args: Any?): String { val str = StringBuilder() val context = Context(Scope(args), config) { str.append(it) } context.createScope { node.eval(context) } return str.toString() } class Context constructor(var scope: Scope, val config: Config, val write: (str: String) -> Unit) { inline fun createScope(callback: () -> Unit) = this.apply { val old = this.scope this.scope = Scope(hashMapOf<Any?, Any?>(), old) callback() this.scope = old } } interface ExprNode { fun eval(context: Context): Any? data class VAR(val name: String) : ExprNode { override fun eval(context: Context): Any? = context.scope[name] } data class LIT(val value: Any?) : ExprNode { override fun eval(context: Context): Any? = value } data class ARRAY_LIT(val items: List<ExprNode>) : ExprNode { override fun eval(context: Context): Any? = items.map { it.eval(context) } } data class FILTER(val name: String, val expr: ExprNode, val params: List<ExprNode>) : ExprNode { override fun eval(context: Context): Any? { val filter = context.config.filters[name] ?: invalidOp("Unknown filter '$name'") return filter.eval(expr.eval(context), params.map { it.eval(context) }) } } data class ACCESS(val expr: ExprNode, val name: ExprNode) : ExprNode { override fun eval(context: Context): Any? { val obj = expr.eval(context) val key = name.eval(context) try { return Dynamic.accessAny(obj, key) } catch (t: Throwable) { try { return Dynamic.callAny(obj, key, listOf()) } catch (t: Throwable) { return null } } } } data class CALL(val method: ExprNode, val args: List<ExprNode>) : ExprNode { override fun eval(context: Context): Any? { if (method !is ACCESS) { return Dynamic.callAny(method.eval(context), args.map { it.eval(context) }) } else { return Dynamic.callAny(method.expr.eval(context), method.name.eval(context), args.map { it.eval(context) }) } } } data class BINOP(val l: ExprNode, val r: ExprNode, val op: String) : ExprNode { override fun eval(context: Context): Any? = Dynamic.binop(l.eval(context), r.eval(context), op) } data class UNOP(val r: ExprNode, val op: String) : ExprNode { override fun eval(context: Context): Any? = Dynamic.unop(r.eval(context), op) } companion object { fun ListReader<Token>.expectPeek(vararg types: String): Token { val token = this.peek() if (token.text !in types) throw RuntimeException("Expected ${types.joinToString(", ")}") return token } fun ListReader<Token>.expect(vararg types: String): Token { val token = this.read() if (token.text !in types) throw RuntimeException("Expected ${types.joinToString(", ")}") return token } fun parse(str: String): ExprNode { return parseFullExpr(Token.tokenize(str)) } fun parseId(r: ListReader<ExprNode.Token>): String { return r.read().text } fun expect(r: ListReader<ExprNode.Token>, vararg tokens: String) { val token = r.read() if (token.text !in tokens) invalidOp("Expected ${tokens.joinToString(", ")} but found $token") } fun parseFullExpr(r: ListReader<Token>): ExprNode { val result = parseExpr(r) if (r.hasMore && r.peek() !is Token.TEnd) { invalidOp("Expected expression at " + r.peek() + " :: " + r.list.map { it.text }.joinToString("")) } return result } private val BINOPS = setOf( "+", "-", "*", "/", "%", "==", "!=", "<", ">", "<=", ">=", "<=>", "&&", "||" ) fun parseExpr(r: ListReader<Token>): ExprNode { var result = parseFinal(r) while (r.hasMore) { if (r.peek() !is Token.TOperator || r.peek().text !in BINOPS) break val operator = r.read().text val right = parseFinal(r) result = ExprNode.BINOP(result, right, operator) } // @TODO: Fix order! return result } private fun parseFinal(r: ListReader<Token>): ExprNode { var construct: ExprNode = when (r.peek().text) { "!", "~", "-", "+" -> { val op = r.read().text ExprNode.UNOP(parseFinal(r), op) } "(" -> { r.read() val result = parseExpr(r) if (r.read().text != ")") throw RuntimeException("Expected ')'") result } // Array literal "[" -> { val items = arrayListOf<ExprNode>() r.read() loop@ while (r.hasMore && r.peek().text != "]") { items += parseExpr(r) when (r.peek().text) { "," -> r.read() "]" -> continue@loop else -> invalidOp("Expected , or ]") } } r.expect("]") ExprNode.ARRAY_LIT(items) } else -> { if (r.peek() is Token.TNumber) { ExprNode.LIT(r.read().text.toDouble()) } else if (r.peek() is Token.TString) { ExprNode.LIT((r.read() as Token.TString).processedValue) } else { ExprNode.VAR(r.read().text) } } } loop@ while (r.hasMore) { when (r.peek().text) { "." -> { r.read() val id = r.read().text construct = ExprNode.ACCESS(construct, ExprNode.LIT(id)) continue@loop } "[" -> { r.read() val expr = parseExpr(r) construct = ExprNode.ACCESS(construct, expr) val end = r.read() if (end.text != "]") throw RuntimeException("Expected ']' but found $end") } "|" -> { r.read() val name = r.read().text val args = arrayListOf<ExprNode>() if (r.peek().text == "(") { r.read() callargsloop@ while (r.hasMore && r.peek().text != ")") { args += parseExpr(r) when (r.expectPeek(",", ")").text) { "," -> r.read() ")" -> break@callargsloop } } r.expect(")") } construct = ExprNode.FILTER(name, construct, args) } "(" -> { r.read() val args = arrayListOf<ExprNode>() callargsloop@ while (r.hasMore && r.peek().text != ")") { args += parseExpr(r) when (r.expectPeek(",", ")").text) { "," -> r.read() ")" -> break@callargsloop } } r.expect(")") construct = ExprNode.CALL(construct, args) } else -> break@loop } } return construct } } interface Token { val text: String data class TId(override val text: String) : Token data class TNumber(override val text: String) : Token data class TString(override val text: String, val processedValue: String) : Token data class TOperator(override val text: String) : Token data class TEnd(override val text: String = "") : Token companion object { private val OPERATORS = setOf( "(", ")", "[", "]", "{", "}", "&&", "||", "&", "|", "^", "==", "!=", "<", ">", "<=", ">=", "<=>", "+", "-", "*", "/", "%", "**", "!", "~", ".", ",", ";", ":", "=" ) fun tokenize(str: String): ListReader<Token> { val r = StrReader(str) val out = arrayListOf<Token>() fun emit(str: Token) { out += str } while (r.hasMore) { val start = r.offset r.skipSpaces() val id = r.readWhile { it.isLetterDigitOrUnderscore() } if (id != null) { if (id[0].isDigit()) emit(TNumber(id)) else emit(TId(id)) } r.skipSpaces() if (r.peek(3) in OPERATORS) emit(TOperator(r.read(3))) if (r.peek(2) in OPERATORS) emit(TOperator(r.read(2))) if (r.peek(1) in OPERATORS) emit(TOperator(r.read(1))) if (r.peekch() == '\'' || r.peekch() == '"') { val strStart = r.readch() val strBody = r.readUntil { it == strStart } ?: "" val strEnd = r.readch() emit(TString(strStart + strBody + strEnd, strBody)) } val end = r.offset if (end == start) invalidOp("Don't know how to handle '${r.peekch()}'") } emit(TEnd()) return ListReader(out) } } } } interface BlockNode { fun eval(context: Context): Unit data class GROUP(val children: List<BlockNode>) : BlockNode { override fun eval(context: Context) = Unit.apply { for (n in children) n.eval(context) } } data class TEXT(val content: String) : BlockNode { override fun eval(context: Context) = Unit.apply { context.write(content) } } data class EXPR(val expr: ExprNode) : BlockNode { override fun eval(context: Context) = Unit.apply { context.write(Dynamic.toString(expr.eval(context))) } } data class IF(val cond: ExprNode, val trueContent: BlockNode, val falseContent: BlockNode?) : BlockNode { override fun eval(context: Context) = Unit.apply { if (Dynamic.toBool(cond.eval(context))) { trueContent.eval(context) } else { falseContent?.eval(context) } } } data class FOR(val varname: String, val expr: ExprNode, val loop: BlockNode) : BlockNode { override fun eval(context: Context) = Unit.apply { context.createScope { for (v in Dynamic.toIterable(expr.eval(context))) { context.scope[varname] = v loop.eval(context) } } } } data class SET(val varname: String, val expr: ExprNode) : BlockNode { override fun eval(context: Context) = Unit.apply { context.scope[varname] = expr.eval(context) } } data class DEBUG(val expr: ExprNode) : BlockNode { override fun eval(context: Context) = Unit.apply { println(expr.eval(context)) } } companion object { fun group(children: List<BlockNode>): BlockNode = if (children.size == 1) children[0] else GROUP(children) fun parse(tokens: List<Token>, config: Config): BlockNode { val tr = ListReader(tokens) fun handle(tag: Tag, token: Token.TTag): BlockNode { val parts = arrayListOf<TagPart>() var currentToken = token val mutableChildren = arrayListOf<BlockNode>() fun emitPart() { val clonedChildren = mutableChildren.toList() parts += TagPart(currentToken, BlockNode.group(clonedChildren)) } loop@ while (!tr.eof) { val it = tr.read() when (it) { is Token.TLiteral -> mutableChildren += BlockNode.TEXT(it.content) is Token.TExpr -> mutableChildren += BlockNode.EXPR(ExprNode.parse(it.content)) is Token.TTag -> { when (it.name) { tag.end -> break@loop in tag.nextList -> { emitPart() currentToken = it mutableChildren.clear() } else -> { val newtag = config.tags[it.name] ?: invalidOp("Can't find tag ${it.name}") if (newtag.end != null) { mutableChildren += handle(newtag, it) } else { mutableChildren += newtag.buildNode(listOf(TagPart(it, BlockNode.TEXT("")))) } } } } else -> break@loop } } emitPart() return tag.buildNode(parts) } return handle(Tag.EMPTY, Token.TTag("", "")) } } } data class TagPart(val token: Token.TTag, val body: BlockNode) data class Tag(val name: String, val nextList: Set<String>, val end: String?, val aliases: List<String> = listOf(), val buildNode: (parts: List<TagPart>) -> BlockNode) { companion object { val EMPTY = Tag("", setOf(""), "") { parts -> BlockNode.group(parts.map { it.body }) } val IF = Tag("if", setOf("else"), "end") { parts -> val main = parts[0] val elseBlock = parts.getOrNull(1) BlockNode.IF(ExprNode.parse(main.token.content), main.body, elseBlock?.body) } val FOR = Tag("for", setOf(), "end") { parts -> val main = parts[0] val tr = ExprNode.Token.tokenize(main.token.content) val varname = ExprNode.parseId(tr) ExprNode.expect(tr, "in") val expr = ExprNode.parseExpr(tr) BlockNode.FOR(varname, expr, main.body) } val DEBUG = Tag("debug", setOf(), null) { parts -> BlockNode.DEBUG(ExprNode.parse(parts[0].token.content)) } val SET = Tag("set", setOf(), null) { parts -> val main = parts[0] val tr = ExprNode.Token.tokenize(main.token.content) val varname = ExprNode.parseId(tr) ExprNode.expect(tr, "=") val expr = ExprNode.parseExpr(tr) BlockNode.SET(varname, expr) } } } interface Token { data class TLiteral(val content: String) : Token data class TExpr(val content: String) : Token data class TTag(val name: String, val content: String) : Token companion object { fun tokenize(str: String): List<Token> { val out = arrayListOf<Token>() var lastPos = 0 fun emit(token: Token) { if (token is TLiteral && token.content.isEmpty()) return out += token } var pos = 0 while (pos < str.length) { val c = str[pos++] if (c == '{') { if (pos >= str.length) break val c2 = str[pos++] if (c2 == '{' || c2 == '%') { val startPos = pos - 2 val pos2 = if (c2 == '{') str.indexOf("}}", pos) else str.indexOf("%}", pos) if (pos2 < 0) break val content = str.substring(pos, pos2).trim() if (lastPos != startPos) { emit(TLiteral(str.substring(lastPos until startPos))) } if (c2 == '{') { //println("expr: '$content'") emit(TExpr(content)) } else { val parts = content.split(' ', limit = 2) //println("tag: '$content'") emit(TTag(parts[0], parts.getOrElse(1) { "" })) } pos = pos2 + 2 lastPos = pos } } } emit(TLiteral(str.substring(lastPos, str.length))) return out } } } }
apache-2.0
89359fdbda83eda4d454e96e6c5b45ac
29.328273
170
0.590565
3.24133
false
false
false
false
http4k/http4k
http4k-client/fuel/src/main/kotlin/org/http4k/client/Fuel.kt
1
2493
package org.http4k.client import com.github.kittinunf.fuel.core.FuelError import com.github.kittinunf.fuel.core.Method import com.github.kittinunf.fuel.core.ResponseResultOf import org.http4k.core.* import java.net.ConnectException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.time.Duration private typealias FuelRequest = com.github.kittinunf.fuel.core.Request private typealias FuelResponse = com.github.kittinunf.fuel.core.Response private typealias FuelResult = com.github.kittinunf.result.Result<ByteArray, FuelError> private typealias FuelFuel = com.github.kittinunf.fuel.Fuel class Fuel( private val bodyMode: BodyMode = BodyMode.Memory, private val timeout: Duration = Duration.ofSeconds(15) ) : DualSyncAsyncHttpHandler { override fun invoke(request: Request): Response = request.toFuel().response().toHttp4k() override fun invoke(request: Request, fn: (Response) -> Unit) { request.toFuel().response { fuelRequest: FuelRequest, response: FuelResponse, result: FuelResult -> fn(Triple(fuelRequest, response, result).toHttp4k()) } } private fun ResponseResultOf<ByteArray>.toHttp4k(): Response { val (_, response, result) = this val (_, error) = result when (error?.exception) { is ConnectException -> return Response(Status.CONNECTION_REFUSED.toClientStatus(error.exception as ConnectException)) is UnknownHostException -> return Response(Status.UNKNOWN_HOST.toClientStatus(error.exception as UnknownHostException)) is SocketTimeoutException -> return Response(Status.CLIENT_TIMEOUT.toClientStatus(error.exception as SocketTimeoutException)) } val headers: Parameters = response.headers.toList().fold(listOf()) { acc, next -> acc + next.second.fold(listOf()) { keyAcc, nextValue -> keyAcc + (next.first to nextValue) } } return Response(Status(response.statusCode, response.responseMessage)) .headers(headers) .body(bodyMode(response.body().toStream())) } private fun Request.toFuel(): com.github.kittinunf.fuel.core.Request = FuelFuel.request(Method.valueOf(method.toString()), uri.toString(), emptyList()) .allowRedirects(false) .timeout(timeout.toMillisPart()) .timeoutRead(timeout.toMillisPart()) .header(headers.toParametersMap()) .body(bodyMode(body.stream).stream) }
apache-2.0
6fbc7701395cbb8cdc1f98c3d9e65151
45.166667
137
0.713197
4.404594
false
false
false
false
vhromada/Catalog-Swing
src/main/kotlin/cz/vhromada/catalog/gui/show/ShowDataPanel.kt
1
9563
package cz.vhromada.catalog.gui.show import cz.vhromada.catalog.entity.Show import cz.vhromada.catalog.facade.EpisodeFacade import cz.vhromada.catalog.facade.PictureFacade import cz.vhromada.catalog.facade.SeasonFacade import cz.vhromada.catalog.gui.common.AbstractDataPanel import cz.vhromada.catalog.gui.common.WebPageButtonType import cz.vhromada.common.entity.Time import cz.vhromada.common.result.Status import javax.swing.GroupLayout import javax.swing.JButton import javax.swing.JLabel /** * A class represents panel with show data. * * @author Vladimir Hromada */ class ShowDataPanel( show: Show, private val seasonFacade: SeasonFacade, private val episodeFacade: EpisodeFacade, private val pictureFacade: PictureFacade) : AbstractDataPanel<Show>() { /** * Label for picture */ private val pictureData = JLabel() /** * Label for czech name */ private val czechNameLabel = JLabel("Czech name") /** * Label with czech name */ private val czechNameData = JLabel() /** * Label for original name */ private val originalNameLabel = JLabel("Original name") /** * Label with original name */ private val originalNameData = JLabel() /** * Label for genre */ private val genreLabel = JLabel("Genre") /** * Label with genre */ private val genreData = JLabel() /** * Label for count of seasons */ private val seasonsCountLabel = JLabel("Count of seasons") /** * Label with count of seasons */ private val seasonsCountData = JLabel() /** * Label for count of episodes */ private val episodesCountLabel = JLabel("Count of episodes") /** * Label with count of episodes */ private val episodesCountData = JLabel() /** * Label for total length */ private val totalLengthLabel = JLabel("Total length") /** * Label with total length */ private val totalLengthData = JLabel() /** * Label for note */ private val noteLabel = JLabel("Note") /** * Label with note */ private val noteData = JLabel() /** * Button for showing show ČSFD page */ private val csfdButton = JButton("ČSFD") /** * Button for showing show IMDB page */ private val imdbButton = JButton("IMDB") /** * Button for showing show czech Wikipedia page */ private val wikiCzButton = JButton("Czech Wikipedia") /** * Button for showing show english Wikipedia page */ private val wikiEnButton = JButton("English Wikipedia") /** * URL to ČSFD page about show */ private var csfd: String? = null /** * IMDB code */ private var imdb: Int? = null /** * URL to czech Wikipedia page about show */ private var wikiCz: String? = null /** * URL to english Wikipedia page about show */ private var wikiEn: String? = null init { updateData(show) pictureData.isFocusable = false initData(czechNameLabel, czechNameData) initData(originalNameLabel, originalNameData) initData(genreLabel, genreData) initData(seasonsCountLabel, seasonsCountData) initData(episodesCountLabel, episodesCountData) initData(totalLengthLabel, totalLengthData) initData(noteLabel, noteData) initButton(csfdButton, WebPageButtonType.CSFD) initButton(imdbButton, WebPageButtonType.IMDB) initButton(wikiCzButton, WebPageButtonType.WIKI_CZ) initButton(wikiEnButton, WebPageButtonType.WIKI_EN) createLayout() } @Suppress("DuplicatedCode") override fun updateComponentData(data: Show) { loadPicture(data.picture, pictureFacade, pictureData) czechNameData.text = data.czechName originalNameData.text = data.originalName genreData.text = getGenres(data.genres) seasonsCountData.text = getSeasonsCount(data) episodesCountData.text = getEpisodesCount(data) totalLengthData.text = getShowLength(data) noteData.text = data.note csfd = data.csfd imdb = data.imdbCode wikiCz = data.wikiCz wikiEn = data.wikiEn csfdButton.isEnabled = !csfd.isNullOrBlank() imdbButton.isEnabled = imdb!! > 0 wikiCzButton.isEnabled = !wikiCz.isNullOrBlank() wikiEnButton.isEnabled = !wikiEn.isNullOrBlank() } override fun getCzWikiUrl(): String { return wikiCz!! } override fun getEnWikiUrl(): String { return wikiEn!! } override fun getCsfdUrl(): String { return csfd!! } override fun getImdbUrl(): Int { return imdb!! } override fun getHorizontalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group { return group .addComponent(pictureData, HORIZONTAL_PICTURE_SIZE, HORIZONTAL_PICTURE_SIZE, HORIZONTAL_PICTURE_SIZE) .addGroup(createHorizontalDataComponents(layout, czechNameLabel, czechNameData)) .addGroup(createHorizontalDataComponents(layout, originalNameLabel, originalNameData)) .addGroup(createHorizontalDataComponents(layout, genreLabel, genreData)) .addGroup(createHorizontalDataComponents(layout, seasonsCountLabel, seasonsCountData)) .addGroup(createHorizontalDataComponents(layout, episodesCountLabel, episodesCountData)) .addGroup(createHorizontalDataComponents(layout, totalLengthLabel, totalLengthData)) .addGroup(createHorizontalDataComponents(layout, noteLabel, noteData)) .addGroup(createHorizontalButtons(layout, csfdButton, imdbButton, wikiCzButton, wikiEnButton)) } @Suppress("DuplicatedCode") override fun getVerticalLayoutWithComponents(layout: GroupLayout, group: GroupLayout.Group): GroupLayout.Group { return group .addComponent(pictureData, VERTICAL_PICTURE_SIZE, VERTICAL_PICTURE_SIZE, VERTICAL_PICTURE_SIZE) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, czechNameLabel, czechNameData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, originalNameLabel, originalNameData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, genreLabel, genreData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, seasonsCountLabel, seasonsCountData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, episodesCountLabel, episodesCountData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, totalLengthLabel, totalLengthData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalComponents(layout, noteLabel, noteData)) .addGap(VERTICAL_GAP_SIZE) .addGroup(createVerticalButtons(layout, csfdButton, imdbButton, wikiCzButton, wikiEnButton)) } /** * Returns count of show seasons. * * @param show show * @return count of show seasons */ private fun getSeasonsCount(show: Show): String { val result = seasonFacade.find(show) if (Status.OK == result.status) { return result.data!!.size.toString() } throw IllegalArgumentException(RESULT_WITH_ERROR_MESSAGE + result) } /** * Returns count of show episodes. * * @param show show * @return count of show episodes */ private fun getEpisodesCount(show: Show): String { val seasonsResult = seasonFacade.find(show) if (Status.OK == seasonsResult.status) { var totalCount = 0 for (season in seasonsResult.data!!) { val episodesResult = episodeFacade.find(season) if (Status.OK == episodesResult.status) { totalCount += episodesResult.data!!.size } else { throw IllegalArgumentException(RESULT_WITH_ERROR_MESSAGE + episodesResult) } } return totalCount.toString() } throw IllegalArgumentException(RESULT_WITH_ERROR_MESSAGE + seasonsResult) } /** * Returns total length of all show seasons. * * @param show show * @return total length of all show seasons */ private fun getShowLength(show: Show): String { val seasonsResult = seasonFacade.find(show) if (Status.OK == seasonsResult.status) { var totalLength = 0 for (season in seasonsResult.data!!) { val episodesResult = episodeFacade.find(season) if (Status.OK == episodesResult.status) { totalLength += episodesResult.data!!.sumBy { it.length!! } } else { throw IllegalArgumentException(RESULT_WITH_ERROR_MESSAGE + episodesResult) } } return Time(totalLength).toString() } throw IllegalArgumentException(RESULT_WITH_ERROR_MESSAGE + seasonsResult) } companion object { /** * Error message for result with errors */ private const val RESULT_WITH_ERROR_MESSAGE = "Can't get data. " } }
mit
318733d0aae63b387862c912ec45af79
30.038961
118
0.634728
4.932921
false
false
false
false
icanit/mangafeed
app/src/main/java/eu/kanade/tachiyomi/ui/manga/MangaPresenter.kt
1
1850
package eu.kanade.tachiyomi.ui.manga import android.os.Bundle import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Manga import eu.kanade.tachiyomi.data.mangasync.MangaSyncManager import eu.kanade.tachiyomi.event.ChapterCountEvent import eu.kanade.tachiyomi.event.MangaEvent import eu.kanade.tachiyomi.ui.base.presenter.BasePresenter import eu.kanade.tachiyomi.util.SharedData import rx.Observable import javax.inject.Inject /** * Presenter of [MangaActivity]. */ class MangaPresenter : BasePresenter<MangaActivity>() { /** * Database helper. */ @Inject lateinit var db: DatabaseHelper /** * Manga sync manager. */ @Inject lateinit var syncManager: MangaSyncManager /** * Manga associated with this instance. */ lateinit var manga: Manga /** * Key to save and restore [manga] from a bundle. */ private val MANGA_KEY = "manga_key" override fun onCreate(savedState: Bundle?) { super.onCreate(savedState) if (savedState == null) { manga = SharedData.get(MangaEvent::class.java)!!.manga } else { manga = savedState.getSerializable(MANGA_KEY) as Manga SharedData.put(MangaEvent(manga)) } // Prepare a subject to communicate the chapters and info presenters for the chapter count. SharedData.put(ChapterCountEvent()) Observable.just(manga) .subscribeLatestCache({ view, manga -> view.onSetManga(manga) }) } override fun onDestroy() { SharedData.remove(MangaEvent::class.java) SharedData.remove(ChapterCountEvent::class.java) super.onDestroy() } override fun onSave(state: Bundle) { state.putSerializable(MANGA_KEY, manga) super.onSave(state) } }
apache-2.0
1e8d2a9b6a62f308ef79af4a78892142
26.61194
99
0.676757
4.292343
false
false
false
false
EasySpringBoot/picture-crawler
src/main/kotlin/com/easy/kotlin/picturecrawler/controller/SearchKeyWordController.kt
1
2576
package com.easy.kotlin.picturecrawler.controller import com.easy.kotlin.picturecrawler.dao.SearchKeyWordRepository import com.easy.kotlin.picturecrawler.entity.SearchKeyWord import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Page import org.springframework.data.domain.PageRequest import org.springframework.data.domain.Sort import org.springframework.stereotype.Controller import org.springframework.transaction.annotation.Transactional import org.springframework.ui.Model import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.ResponseBody import org.springframework.web.servlet.ModelAndView import javax.servlet.http.HttpServletRequest /** * Created by jack on 2017/7/22. */ @Controller class SearchKeyWordController { @Autowired lateinit var searchKeyWordRepository: SearchKeyWordRepository @RequestMapping(value = ["search_keyword_view"], method = arrayOf(RequestMethod.GET)) fun sotuView(model: Model, request: HttpServletRequest): ModelAndView { model.addAttribute("requestURI", request.requestURI) return ModelAndView("search_keyword_view") } @RequestMapping(value = ["searchKeyWordJson"], method = arrayOf(RequestMethod.GET)) @ResponseBody fun sotuSearchJson(@RequestParam(value = "page", defaultValue = "0") page: Int, @RequestParam(value = "size", defaultValue = "10") size: Int, @RequestParam(value = "searchText", defaultValue = "") searchText: String): Page<SearchKeyWord> { return getPageResult(page, size, searchText) } private fun getPageResult(page: Int, size: Int, searchText: String): Page<SearchKeyWord> { val sort = Sort(Sort.Direction.DESC, "id") // 注意:PageRequest.of(page,size,sort) page 默认是从0开始 val pageable = PageRequest.of(page, size, sort) if (searchText == "") { return searchKeyWordRepository.findAll(pageable) } else { return searchKeyWordRepository.search(searchText, pageable) } } @RequestMapping(value = ["save_keyword"], method = arrayOf(RequestMethod.GET, RequestMethod.POST)) @ResponseBody fun save(@RequestParam(value = "keyWord") keyWord: String): String { if (keyWord == "") { return "0" } else { searchKeyWordRepository.saveOnNoDuplicateKey(keyWord) return "1" } } }
apache-2.0
1a0a79a053fb52a4ce0af8e81ea49e9e
39.603175
243
0.73534
4.425606
false
false
false
false
rock3r/detekt
detekt-rules/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/coroutines/GlobalCoroutineUsageSpec.kt
2
2189
package io.gitlab.arturbosch.detekt.rules.coroutines import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.test.assertThat import io.gitlab.arturbosch.detekt.test.compileAndLint import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object GlobalCoroutineUsageSpec : Spek({ val subject by memoized { GlobalCoroutineUsage(Config.empty) } describe("GlobalCoroutineUsage rule") { it("should report GlobalScope.launch") { val code = """ import kotlinx.coroutines.delay import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch fun foo() { GlobalScope.launch { delay(1_000L) } } """ assertThat(subject.compileAndLint(code)).hasSize(1) } it("should report GlobalScope.async") { val code = """ import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.GlobalScope fun foo() { GlobalScope.async { delay(1_000L) } } """ assertThat(subject.compileAndLint(code)).hasSize(1) } it("should not report bar(GlobalScope)") { val code = """ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope fun bar(scope: CoroutineScope) = Unit fun foo() { bar(GlobalScope) } """ assertThat(subject.compileAndLint(code)).isEmpty() } it("should not report `val scope = GlobalScope`") { val code = """ import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.GlobalScope fun bar(scope: CoroutineScope) = Unit fun foo() { val scope = GlobalScope bar(scope) } """ assertThat(subject.compileAndLint(code)).isEmpty() } } })
apache-2.0
6597019d9e82156cbb4335a9bb79608a
30.724638
66
0.549566
5.445274
false
false
false
false
pdvrieze/ProcessManager
PEUserMessageHandler/src/main/kotlin/nl/adaptivity/process/userMessageHandler/server/ExternalEndpoint.kt
1
12354
/* * Copyright (c) 2018. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.userMessageHandler.server import net.devrieze.util.Handle import net.devrieze.util.HandleNotFoundException import net.devrieze.util.Transaction import net.devrieze.util.security.SYSTEMPRINCIPAL import nl.adaptivity.messaging.EndpointDescriptor import nl.adaptivity.messaging.HttpResponseException import nl.adaptivity.messaging.MessagingRegistry import nl.adaptivity.process.engine.processModel.NodeInstanceState import nl.adaptivity.process.messaging.GenericEndpoint import nl.adaptivity.process.util.Constants import nl.adaptivity.rest.annotations.HttpMethod import nl.adaptivity.rest.annotations.RestMethod import nl.adaptivity.rest.annotations.RestParam import nl.adaptivity.rest.annotations.RestParamType import nl.adaptivity.util.multiplatform.URI import java.net.URISyntaxException import java.security.Principal import java.sql.SQLException import java.util.logging.Level import java.util.logging.Logger import javax.servlet.ServletConfig import javax.servlet.http.HttpServletResponse import javax.xml.bind.annotation.XmlElementWrapper import javax.xml.bind.annotation.XmlSeeAlso import javax.xml.namespace.QName import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract /** * The external interface to the user task management system. This is for interacting with tasks, not for the process * engine to use. The process engine uses the [internal endpoint][InternalEndpoint]. * The default context path for the methods in this endpoind is `/PEUserMessageHandler/UserMessageService` * Note that task states are ordered and ultimately determined by the process engine. Task states may not always be * downgraded. */ @XmlSeeAlso(XmlTask::class) class ExternalEndpoint @JvmOverloads constructor(private val mService: UserMessageService<out Transaction> = UserMessageService.instance) : GenericEndpoint { private var endpointUri: URI? = null override val serviceName: QName get() = SERVICENAME override val endpointName: String get() = ENDPOINT override val endpointLocation: URI? get() { return endpointUri } override fun isSameService(other: EndpointDescriptor?): Boolean { return other != null && Constants.USER_MESSAGE_HANDLER_NS == other.serviceName?.namespaceURI && SERVICE_LOCALNAME == other.serviceName?.localPart && endpointName == other.endpointName } override fun initEndpoint(config: ServletConfig) { val path = StringBuilder(config.servletContext.contextPath) path.append("/UserMessageService") try { endpointUri = URI(null, null, path.toString(), null) } catch (e: URISyntaxException) { throw RuntimeException(e) // Should never happen } MessagingRegistry.getMessenger().registerEndpoint(this) } /** * Get a list of pending tasks. * @return All tasks available * * @throws SQLException * */ @XmlElementWrapper(name = "tasks", namespace = Constants.USER_MESSAGE_HANDLER_NS) @RestMethod(method = HttpMethod.GET, path = "/allPendingTasks") @Deprecated("The version that takes the user should be used.", ReplaceWith("getPendingTasks(user)")) fun getPendingTasks() = getPendingTasks(mService, SYSTEMPRINCIPAL) /** * Get a list of pending tasks. * @param user The user whose tasks to display. * * @return All tasks available * * @throws SQLException */ @XmlElementWrapper(name = "tasks", namespace = Constants.USER_MESSAGE_HANDLER_NS) @RestMethod(method = HttpMethod.GET, path = "/pendingTasks") @Throws(SQLException::class) fun getPendingTasks(@RestParam(type = RestParamType.PRINCIPAL) user: Principal): Collection<XmlTask> { return getPendingTasks(mService, user) } /** * Update a task. This takes an xml task whose values will be used to update this one. Task items get * overwritten with their new values, as well as the state. Missing items in the update will be ignored (the old value * used. The item state is a draft state, not the final version that the process engine gets until it has a * completed state. * @param handle The handle/id of the task * * @param partialNewTask The partial task to use for updating. * * @param user The user whose task state to update. * * @return The Updated, complete, task. * * @throws SQLException When something went wrong with the query. * * @throws FileNotFoundException When the task handle is not valid. This will be translated into a 404 error. */ @RestMethod(method = HttpMethod.POST, path = "/pendingTasks/\${handle}") @Throws(SQLException::class) fun updateTask( @RestParam(name = "handle", type = RestParamType.VAR) handle: String, @RestParam(type = RestParamType.BODY) partialNewTask: XmlTask, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): XmlTask = translateExceptions { return updateTask(mService, handle, partialNewTask, user) } /** * Retrieve the current pending task for the given handle. * @param handle The task handle (as recorded in the task handler, not the process engine handle). * * @param user The user whose task to retrieve. * * @return The task. */ @RestMethod(method = HttpMethod.GET, path = "/pendingTasks/\${handle}") @Throws(SQLException::class) fun getPendingTask( @RestParam(name = "handle", type = RestParamType.VAR) handle: String, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): XmlTask = translateExceptions { mService.inTransaction { return commit { val handle1 = java.lang.Long.parseLong(handle) getPendingTask( if (handle1 < 0) Handle.invalid() else Handle(handle1), user ) } ?: throw HandleNotFoundException("The task with handle $handle does not exist") } } /** * Mark a task as started. * @param handle The task handle. * * @param user The owner. * * @return The new state of the task after completion of the request. */ @RestMethod(method = HttpMethod.POST, path = "/pendingTasks/\${handle}", post = arrayOf("state=Started")) @Throws(SQLException::class) fun startTask( @RestParam(name = "handle", type = RestParamType.VAR) handle: String, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): NodeInstanceState = translateExceptions { mService.inTransaction { return startTask(Handle(handleString = handle), user) } } /** * Mark a task as Taken. * @param handle The task handle. * * @param user The owner. * * @return The new state of the task after completion of the request. */ @RestMethod(method = HttpMethod.POST, path = "/pendingTasks/\${handle}", post = arrayOf("state=Taken")) @Throws(SQLException::class) fun takeTask( @RestParam(name = "handle", type = RestParamType.VAR) handle: String, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): NodeInstanceState = translateExceptions { mService.inTransaction { return commit { takeTask(Handle(handleString = handle), user) } } } /** * Mark a task as Finished. This will allow the process engine to take the data, and transition it to completed once * it has fully handled the finishing of the task. * @param handle The task handle. * * @param user The owner. * * @return The new state of the task after completion of the request. */ @RestMethod(method = HttpMethod.POST, path = "/pendingTasks/\${handle}", post = arrayOf("state=Finished")) @Throws(SQLException::class) fun finishTask( @RestParam(name = "handle", type = RestParamType.VAR) handle: String, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): NodeInstanceState = translateExceptions { mService.inTransaction { return commit { val handle1 = java.lang.Long.parseLong(handle) finishTask( if (handle1 < 0) Handle.invalid() else Handle(handle1), user ) } } } @RestMethod(method = HttpMethod.POST, path = "/pendingTasks/\${handle}", post = arrayOf("state=Cancelled")) fun cancelTask( @RestParam(name = "handle", type = RestParamType.VAR) handle: String, @RestParam(type = RestParamType.PRINCIPAL) user: Principal ): NodeInstanceState = translateExceptions { mService.inTransaction { return commit { val handle1 = java.lang.Long.parseLong(handle) cancelTask( if (handle1 < 0) Handle.invalid() else Handle(handle1), user ) } } } override fun destroy() { mService.destroy() MessagingRegistry.getMessenger().registerEndpoint(this) } companion object { val ENDPOINT = "external" val SERVICE_LOCALNAME = "userMessageHandler" val SERVICENAME = QName(Constants.USER_MESSAGE_HANDLER_NS, SERVICE_LOCALNAME) /** * Helper method that is generic that can record the "right" transaction type. */ @Throws(SQLException::class) private fun <T : Transaction> getPendingTasks( service: UserMessageService<T>, user: Principal ): Collection<XmlTask> { try { service.newTransaction().use { transaction -> return transaction.commit( service.getPendingTasks( transaction, user ) ) } } catch (e: Exception) { Logger.getAnonymousLogger().log(Level.WARNING, "Error retrieving tasks", e) throw e } } @Throws(SQLException::class) private fun <T : Transaction> GenericEndpoint.updateTask( service: UserMessageService<T>, handleString: String, partialNewTask: XmlTask?, user: Principal ): XmlTask = translateExceptions { if (partialNewTask == null) { throw IllegalArgumentException("No task information provided") } try { service.newTransaction().use { transaction -> val result = service.updateTask( transaction, Handle(handleString), partialNewTask, user ) ?: throw HandleNotFoundException() transaction.commit() return result } } catch (e: Exception) { Logger.getAnonymousLogger().log(Level.WARNING, "Error updating task", e) throw e } } } } @OptIn(ExperimentalContracts::class) internal inline fun <E : GenericEndpoint, R> E.translateExceptions(body: () -> R): R { contract { callsInPlace(body, InvocationKind.EXACTLY_ONCE) } try { return body() } catch (e: HandleNotFoundException) { throw HttpResponseException(HttpServletResponse.SC_NOT_FOUND, e) } }
lgpl-3.0
414d47f99b672fa21dc028727ca35d71
36.323263
139
0.643516
4.814497
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/ui/CategoriesFragment.kt
1
3551
package com.boardgamegeek.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.RecyclerView import com.boardgamegeek.R import com.boardgamegeek.databinding.FragmentCategoriesBinding import com.boardgamegeek.databinding.RowCategoryBinding import com.boardgamegeek.entities.CategoryEntity import com.boardgamegeek.extensions.inflate import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter import com.boardgamegeek.ui.viewmodel.CategoriesViewModel import kotlin.properties.Delegates class CategoriesFragment : Fragment() { private var _binding: FragmentCategoriesBinding? = null private val binding get() = _binding!! private val viewModel by activityViewModels<CategoriesViewModel>() private val adapter: CategoriesAdapter by lazy { CategoriesAdapter() } @Suppress("RedundantNullableReturnType") override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = FragmentCategoriesBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.recyclerView.setHasFixedSize(true) binding.recyclerView.adapter = adapter binding.swipeRefresh.setOnRefreshListener { viewModel.refresh() } viewModel.categories.observe(viewLifecycleOwner) { adapter.categories = it binding.recyclerView.isVisible = adapter.itemCount > 0 binding.emptyTextView.isVisible = adapter.itemCount == 0 binding.progressBar.hide() binding.swipeRefresh.isRefreshing = false } } override fun onDestroyView() { super.onDestroyView() _binding = null } class CategoriesAdapter : RecyclerView.Adapter<CategoriesAdapter.CategoryViewHolder>(), AutoUpdatableAdapter { var categories: List<CategoryEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue -> autoNotify(oldValue, newValue) { old, new -> old.id == new.id } } init { setHasStableIds(true) } override fun getItemCount() = categories.size override fun getItemId(position: Int) = categories.getOrNull(position)?.id?.toLong() ?: RecyclerView.NO_ID override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryViewHolder { return CategoryViewHolder(parent.inflate(R.layout.row_category)) } override fun onBindViewHolder(holder: CategoryViewHolder, position: Int) { holder.bind(categories.getOrNull(position)) } inner class CategoryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val binding = RowCategoryBinding.bind(itemView) fun bind(category: CategoryEntity?) { category?.let { c -> binding.nameView.text = c.name binding.countView.text = itemView.context.resources.getQuantityString(R.plurals.games_suffix, c.itemCount, c.itemCount) itemView.setOnClickListener { CategoryActivity.start(itemView.context, c.id, c.name) } } } } } }
gpl-3.0
0bcfb8e25c75f83f0e4454463bea7a64
38.021978
139
0.693607
5.199122
false
false
false
false
lure0xaos/CoffeeTime
util/src/main/kotlin/gargoyle/ct/util/resource/internal/LocalResource.kt
1
4039
package gargoyle.ct.util.resource.internal import gargoyle.ct.util.util.ResourceException import java.io.File import java.net.MalformedURLException import java.net.URL import java.text.MessageFormat /** * local filesystem [Resource] from different locations */ open class LocalResource protected constructor(url: URL) : VirtualResource<LocalResource>(url.toExternalForm()) { fun toFile(): File { val url = toURL() val path = url.path return File(if (path.startsWith(File.separator)) path.substring(1) else path) // XXX hacky } private class LocalLocation(private val url: URL, val readPriority: Int, val writePriority: Int) { fun getUrl(): URL { return url } override fun hashCode(): Int { return url.toExternalForm().hashCode() } override fun equals(other: Any?): Boolean = when { this === other -> true other == null || javaClass != other.javaClass -> false else -> { val that = other as LocalLocation url.toExternalForm() == that.url.toExternalForm() } } } private class LocalLocationReadPriority : Comparator<LocalLocation> { override fun compare(o1: LocalLocation, o2: LocalLocation): Int { return o1.readPriority.compareTo(o2.readPriority) } } private class LocalLocationWritePriority : Comparator<LocalLocation> { override fun compare(o1: LocalLocation, o2: LocalLocation): Int = o1.writePriority.compareTo(o2.writePriority) } companion object { private const val ENV_USER_DIR = "user.dir" private const val ENV_USER_HOME = "user.home" private const val MSG_CANNOT_CREATE_ROOTS = "Cannot create roots" private const val MSG_CANNOT_USE_0_AS_ROOT = "Cannot use {0} as root" fun findLocal(name: String): LocalResource { var writable: LocalResource? = null var writablePriority = Int.MIN_VALUE for (root in readableLocations) { try { val resource = LocalResource(URL(root.getUrl(), name)) if (resource.exists()) { return resource } val writePriority: Int = root.writePriority if (resource.isWritable && (writable == null || writablePriority < writePriority)) { writable = resource writablePriority = writePriority } } catch (ex: MalformedURLException) { throw ResourceException(MessageFormat.format(MSG_CANNOT_USE_0_AS_ROOT, root), ex) } } return writable!! } private val readableLocations: Array<LocalLocation> get() = locations private val locations: Array<LocalLocation> get() = try { arrayOf( LocalLocation(File(".").toURI().toURL(), 0, 0), LocalLocation(File(System.getProperty(ENV_USER_DIR, ".")).toURI().toURL(), 0, 0), LocalLocation(homeDirectoryLocation, 0, 1), //FIXME // LocalLocation( // URL( // LocalLocation::class.getResource("/").toExternalForm().substringBeforeLast('/') // ), 0, 0 // ) ) } catch (ex: MalformedURLException) { throw ResourceException(MSG_CANNOT_CREATE_ROOTS, ex) } private val writableLocations: Array<LocalLocation> get() = locations val homeDirectoryLocation: URL get() = try { File(System.getProperty(ENV_USER_HOME, ".")).toURI().toURL() } catch (e: MalformedURLException) { throw ResourceException(e.localizedMessage, e) } } }
unlicense
f80e44c14222857f0c271aacc531c369
38.213592
118
0.554098
4.955828
false
false
false
false
Nearsoft/nearbooks-android
app/src/main/java/com/nearsoft/nearbooks/ws/responses/googlebooks/VolumeInfo.kt
2
1722
package com.nearsoft.nearbooks.ws.responses.googlebooks import com.google.gson.annotations.SerializedName data class VolumeInfo( @SerializedName("title") var title: String? = null, @SerializedName("subtitle") var subtitle: String? = null, @SerializedName("authors") var authors: List<String> = mutableListOf(), @SerializedName("publisher") var publisher: String? = null, @SerializedName("publishedDate") var publishedDate: String? = null, @SerializedName("description") var description: String? = null, @SerializedName("industryIdentifiers") var industryIdentifiers: List<IndustryIdentifier> = mutableListOf(), @SerializedName("readingModes") var readingModes: ReadingModes? = null, @SerializedName("pageCount") var pageCount: Int = 0, @SerializedName("printType") var printType: String? = null, @SerializedName("categories") var categories: List<String> = mutableListOf(), @SerializedName("averageRating") var averageRating: Double = 0.toDouble(), @SerializedName("ratingsCount") var ratingsCount: Int = 0, @SerializedName("maturityRating") var maturityRating: String? = null, @SerializedName("allowAnonLogging") var isAllowAnonLogging: Boolean = false, @SerializedName("contentVersion") var contentVersion: String? = null, @SerializedName("imageLinks") var imageLinks: ImageLinks? = null, @SerializedName("language") var language: String? = null, @SerializedName("previewLink") var previewLink: String? = null, @SerializedName("infoLink") var infoLink: String? = null, @SerializedName("canonicalVolumeLink") var canonicalVolumeLink: String? = null )
mit
4236f8c5e4968a7ca61d21767e74394a
62.777778
115
0.703252
4.704918
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientTabCompleteHandler.kt
1
3837
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.handler.play import org.lanternpowered.api.text.textOf import org.lanternpowered.server.network.NetworkContext import org.lanternpowered.server.network.packet.PacketHandler import org.lanternpowered.server.network.vanilla.packet.type.play.ClientTabCompletePacket import org.lanternpowered.server.network.vanilla.packet.type.play.TabCompletePacket object ClientTabCompleteHandler : PacketHandler<ClientTabCompletePacket> { override fun handle(ctx: NetworkContext, packet: ClientTabCompletePacket) { val text = packet.input val player = ctx.session.player player.sendMessage(textOf("Received tab completion (" + packet.id + "): " + text)) player.connection.send(TabCompletePacket(listOf( TabCompletePacket.Match("Avalue", null), TabCompletePacket.Match("Btest", null), TabCompletePacket.Match("Cwhy", null)), packet.id, 0, 20)) // TODO: Update this /* // The content with normalized spaces, the spaces are trimmed // from the ends and there are never two spaces directly after each other final String textNormalized = StringUtils.normalizeSpace(text); final boolean hasPrefix = textNormalized.startsWith("/"); if (hasPrefix) { String command = textNormalized; // Don't include the '/' if (hasPrefix) { command = command.substring(1); } // Keep the last space, it must be there! if (text.endsWith(" ")) { command = command + " "; } // Get the suggestions List<String> suggestions = ((LanternCommandManager) Sponge.getCommandManager()) .getCustomSuggestions(player, command, null, false); // If the suggestions are for the command and there was a prefix, then append the prefix if (command.split(" ").length == 1 && !command.endsWith(" ")) { suggestions = suggestions.stream() .map(suggestion -> '/' + suggestion) .collect(ImmutableList.toImmutableList()); } context.getSession().send(new MessagePlayOutTabComplete(suggestions)); } else { // Vanilla mc will complete user names if // no command is being completed final int index = text.lastIndexOf(' '); final String part; if (index == -1) { part = text; } else { part = text.substring(index + 1); } if (part.isEmpty()) { return; } final String part1 = part.toLowerCase(); final List<String> suggestions = Sponge.getServer().getOnlinePlayers().stream() .map(CommandSource::getName) .filter(n -> n.toLowerCase().startsWith(part1)) .collect(Collectors.toList()); final Cause cause = Cause.of(EventContext.empty(), context.getSession().getPlayer()); final TabCompleteEvent.Chat event = SpongeEventFactory.createTabCompleteEventChat( cause, ImmutableList.copyOf(suggestions), suggestions, text, Optional.empty(), false); if (!Sponge.getEventManager().post(event)) { context.getSession().send(new MessagePlayOutTabComplete(suggestions)); } }*/ } }
mit
0b3ecf7d147cc8834ebf9e88612385cf
42.602273
106
0.608548
4.912932
false
false
false
false
googlecodelabs/watchnext-for-movie-tv-episodes
step_4_completed/src/main/java/com/android/tv/reference/auth/RemoteAuthClient.kt
9
2411
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tv.reference.auth import com.android.tv.reference.shared.util.Result import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.Body import retrofit2.http.POST /** * An auth client that connects to a real server. */ class RemoteAuthClient : AuthClient { companion object { const val BASE_URL = "https://example.com" } private val service = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(MoshiConverterFactory.create()) .build() .create(IdentityService::class.java) override suspend fun validateToken(token: String) = wrapResult { service.validateToken(token) } override suspend fun authWithPassword(username: String, password: String) = wrapResult { service.authWithPassword(username, password) } override suspend fun authWithGoogleIdToken(idToken: String) = wrapResult { service.authWithGoogleIdToken(idToken) } override suspend fun invalidateToken(token: String) = wrapResult { service.invalidateToken(token) } private suspend fun <T> wrapResult(f: suspend () -> T): Result<T> = try { Result.Success(f()) } catch (exception: Exception) { Result.Error(AuthClientError.ServerError(exception)) } private interface IdentityService { @POST("/validateToken") suspend fun validateToken(@Body token: String): UserInfo @POST("/authWithPassword") suspend fun authWithPassword(@Body username: String, @Body password: String): UserInfo @POST("/validateToken") suspend fun authWithGoogleIdToken(@Body idToken: String): UserInfo @POST("/invalidateToken") suspend fun invalidateToken(@Body token: String): Unit } }
apache-2.0
e36fbdb994ae238bcf8871a75a60d337
33.442857
94
0.700539
4.506542
false
false
false
false
Mithrandir21/Duopoints
app/src/main/java/com/duopoints/android/ui/views/ActionButton.kt
1
1305
package com.duopoints.android.ui.views import android.content.Context import android.support.v7.widget.AppCompatButton import android.util.AttributeSet import com.duopoints.android.R class ActionButton @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, private var actionable: Boolean = false) : AppCompatButton(context, attrs, defStyleAttr) { private val invalidResourceID = -1 private var resourceId: Int = invalidResourceID init { attrs?.let { val ta = context.obtainStyledAttributes(it, R.styleable.ActionButton, 0, 0) try { actionable = ta.getBoolean(R.styleable.ActionButton_actionable, true) resourceId = ta.getResourceId(R.styleable.ActionButton_action_button_background, invalidResourceID) } finally { ta.recycle() } } if (resourceId == invalidResourceID) { setActionable(actionable) } else { setBackgroundResource(resourceId) } } fun setActionable(actionable: Boolean) { this.actionable = actionable setBackgroundResource(if (actionable) R.drawable.custom_view_rounded_button_blue else R.drawable.custom_view_rounded_button_green) } }
gpl-3.0
f9d3319604338f1ee85d51606a28eb54
34.27027
157
0.672031
4.562937
false
false
false
false
andreyfomenkov/green-cat
plugin/src/ru/fomenkov/plugin/repository/ClassFileRepository.kt
1
3276
package ru.fomenkov.plugin.repository import ru.fomenkov.plugin.repository.data.RepositoryResource import ru.fomenkov.plugin.resolver.ProjectResolver import ru.fomenkov.plugin.util.Telemetry import ru.fomenkov.plugin.util.exec import ru.fomenkov.plugin.util.timeMillis import java.io.File import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors class ClassFileRepository : ResourceRepository<RepositoryResource.ClassResource>() { private val buildDirs = listOf( // TODO "build/intermediates/javac/debug/classes", "build/intermediates/javac/debugAndroidTest/classes", "build/tmp/kotlin-classes/debug", "build/tmp/kotlin-classes/main", "build/tmp/kapt3/classes/debug", "build/generated/res/resValues/debug", "build/generated/res/rs/debug", "build/generated/crashlytics/res/debug", "build/generated/res/google-services/debug", "build/classes/java/main", "build/classes/java/debug", ) override fun scan() { val time = timeMillis { val resolver = ProjectResolver( propertiesFileName = "gradle.properties", // TODO settingsFileName = "settings.gradle", ignoredModules = emptySet(), ignoredLibs = emptySet(), ) val declarations = resolver.parseModuleDeclarations() val tasksCount = declarations.size * buildDirs.size val countDownLatch = CountDownLatch(tasksCount) val cpus = Runtime.getRuntime().availableProcessors() val executor = Executors.newFixedThreadPool(cpus) val output = ConcurrentHashMap<String, RepositoryResource.ClassResource>() declarations.forEach { (name, path) -> buildDirs.forEach { buildDir -> executor.submit { scanBuildDirectory("$path/$buildDir", output) countDownLatch.countDown() } } } countDownLatch.await() executor.shutdown() output.forEach(this::add) } Telemetry.log("Scan class files: $time ms") } private fun scanBuildDirectory(moduleBuildPath: String, output: MutableMap<String, RepositoryResource.ClassResource>) { if (!File(moduleBuildPath).exists()) { return } val classFilePaths = exec("find $moduleBuildPath -name '*.class'") .filterNot { path -> path.contains("$") } // TODO: need? classFilePaths.forEach { path -> val packageName = getPackageName(moduleBuildPath, path) val resource = RepositoryResource.ClassResource( packageName = packageName, classFilePath = path, buildDirPath = moduleBuildPath, ) output += packageName to resource } } private fun getPackageName(moduleBuildPath: String, classFilePath: String): String { val startIndex = moduleBuildPath.length + 1 val endIndex = classFilePath.length - 6 return classFilePath.substring(startIndex, endIndex) .replace('/', '.') } }
apache-2.0
3f49dbccdaf48c3875d61852b9f337b9
38.481928
123
0.626679
4.926316
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/fragment/FriendListFragment.kt
1
2000
package me.ykrank.s1next.view.fragment import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import android.view.View import com.github.ykrank.androidtools.ui.vm.LoadingViewModel import io.reactivex.Single import me.ykrank.s1next.data.api.model.collection.Friends import me.ykrank.s1next.data.api.model.wrapper.BaseDataWrapper import me.ykrank.s1next.view.adapter.FriendRecyclerViewAdapter /** * Created by ykrank on 2017/1/16. */ class FriendListFragment : BaseRecyclerViewFragment<BaseDataWrapper<Friends>>() { private var uid: String? = null private lateinit var mRecyclerAdapter: FriendRecyclerViewAdapter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) uid = arguments?.getString(ARG_UID) leavePageMsg("FriendListFragment##Uid:$uid") val recyclerView = recyclerView val activity = activity recyclerView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(activity) mRecyclerAdapter = FriendRecyclerViewAdapter(activity) recyclerView.adapter = mRecyclerAdapter } override fun getSourceObservable(@LoadingViewModel.LoadingDef loading: Int): Single<BaseDataWrapper<Friends>> { return mS1Service.getFriends(uid) } override fun onNext(data: BaseDataWrapper<Friends>) { val friends = data.data?.friendList if (friends.isNullOrEmpty()) { //No data } else { super.onNext(data) mRecyclerAdapter.diffNewDataSet(friends, true) } } companion object { val TAG = FriendListFragment::class.java.name private val ARG_UID = "uid" fun newInstance(uid: String): FriendListFragment { val fragment = FriendListFragment() val bundle = Bundle() bundle.putString(ARG_UID, uid) fragment.arguments = bundle return fragment } } }
apache-2.0
22606dec6b5b4a1a1addf69eb64b75a6
32.898305
115
0.701
4.716981
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/data/api/model/Favourite.kt
1
1275
package me.ykrank.s1next.data.api.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import com.github.ykrank.androidtools.ui.adapter.StableIdModel import org.apache.commons.lang3.StringEscapeUtils @JsonIgnoreProperties(ignoreUnknown = true) class Favourite : StableIdModel { @JsonProperty("id") var id: String? = null @JsonProperty("favid") var favId: String? = null @JsonProperty("title") // unescape some basic XML entities var title: String? = null set(title) { field = StringEscapeUtils.unescapeXml(title) } override val stableId: Long get() = favId?.toLongOrNull() ?: 0 override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Favourite if (id != other.id) return false if (favId != other.favId) return false if (title != other.title) return false return true } override fun hashCode(): Int { var result = id?.hashCode() ?: 0 result = 31 * result + (favId?.hashCode() ?: 0) result = 31 * result + (title?.hashCode() ?: 0) return result } }
apache-2.0
dc66ec480cfe39e587bd78d3a86f013e
26.12766
62
0.641569
4.221854
false
false
false
false
c4software/Android-Password-Store
app/src/main/java/com/zeapo/pwdstore/crypto/PgpActivity.kt
1
36983
/* * Copyright © 2014-2019 The Android Password Store Authors. All Rights Reserved. * SPDX-License-Identifier: GPL-2.0 */ package com.zeapo.pwdstore.crypto import android.app.PendingIntent import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.content.IntentSender import android.content.SharedPreferences import android.graphics.Typeface import android.os.AsyncTask import android.os.Bundle import android.os.ConditionVariable import android.os.Handler import android.text.TextUtils import android.text.format.DateUtils import android.text.method.PasswordTransformationMethod import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import android.view.View import android.view.WindowManager import android.widget.Button import android.widget.CheckBox import android.widget.LinearLayout import android.widget.ProgressBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.zeapo.pwdstore.PasswordEntry import com.zeapo.pwdstore.PasswordGeneratorDialogFragment import com.zeapo.pwdstore.R import com.zeapo.pwdstore.UserPreference import com.zeapo.pwdstore.utils.Otp import kotlinx.android.synthetic.main.decrypt_layout.* import kotlinx.android.synthetic.main.encrypt_layout.crypto_extra_edit import kotlinx.android.synthetic.main.encrypt_layout.crypto_password_category import kotlinx.android.synthetic.main.encrypt_layout.crypto_password_edit import kotlinx.android.synthetic.main.encrypt_layout.crypto_password_file_edit import kotlinx.android.synthetic.main.encrypt_layout.generate_password import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils import org.openintents.openpgp.IOpenPgpService2 import org.openintents.openpgp.OpenPgpError import org.openintents.openpgp.util.OpenPgpApi import org.openintents.openpgp.util.OpenPgpApi.ACTION_DECRYPT_VERIFY import org.openintents.openpgp.util.OpenPgpApi.RESULT_CODE import org.openintents.openpgp.util.OpenPgpApi.RESULT_CODE_ERROR import org.openintents.openpgp.util.OpenPgpApi.RESULT_CODE_SUCCESS import org.openintents.openpgp.util.OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED import org.openintents.openpgp.util.OpenPgpApi.RESULT_ERROR import org.openintents.openpgp.util.OpenPgpApi.RESULT_INTENT import org.openintents.openpgp.util.OpenPgpServiceConnection import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.File import java.nio.charset.Charset import java.util.Date class PgpActivity : AppCompatActivity(), OpenPgpServiceConnection.OnBound { private val clipboard: ClipboardManager by lazy { getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager } private var passwordEntry: PasswordEntry? = null private var api: OpenPgpApi? = null private var editName: String? = null private var editPass: String? = null private var editExtra: String? = null private val operation: String by lazy { intent.getStringExtra("OPERATION") } private val repoPath: String by lazy { intent.getStringExtra("REPO_PATH") } private val fullPath: String by lazy { intent.getStringExtra("FILE_PATH") } private val name: String by lazy { getName(fullPath) } private val lastChangedString: CharSequence by lazy { getLastChangedString( intent.getLongExtra( "LAST_CHANGED_TIMESTAMP", -1L ) ) } private val relativeParentPath: String by lazy { getParentPath(fullPath, repoPath) } val settings: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) } private val keyIDs: MutableSet<String> by lazy { settings.getStringSet("openpgp_key_ids_set", mutableSetOf()) ?: emptySet() } private var mServiceConnection: OpenPgpServiceConnection? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE) // some persistence val providerPackageName = settings.getString("openpgp_provider_list", "") if (TextUtils.isEmpty(providerPackageName)) { Toast.makeText(this, this.resources.getString(R.string.provider_toast_text), Toast.LENGTH_LONG).show() val intent = Intent(this, UserPreference::class.java) startActivityForResult(intent, OPEN_PGP_BOUND) } else { // bind to service mServiceConnection = OpenPgpServiceConnection(this, providerPackageName, this) mServiceConnection?.bindToService() supportActionBar?.setDisplayHomeAsUpEnabled(true) } when (operation) { "DECRYPT", "EDIT" -> { setContentView(R.layout.decrypt_layout) crypto_password_category_decrypt.text = relativeParentPath crypto_password_file.text = name crypto_password_last_changed.text = try { this.resources.getString(R.string.last_changed, lastChangedString) } catch (e: RuntimeException) { showToast(getString(R.string.get_last_changed_failed)) "" } } "ENCRYPT" -> { setContentView(R.layout.encrypt_layout) generate_password?.setOnClickListener { PasswordGeneratorDialogFragment().show(supportFragmentManager, "generator") } title = getString(R.string.new_password_title) crypto_password_category.text = getRelativePath(fullPath, repoPath) } } } override fun onDestroy() { checkAndIncrementHotp() super.onDestroy() mServiceConnection?.unbindFromService() } override fun onCreateOptionsMenu(menu: Menu?): Boolean { // Inflate the menu; this adds items to the action bar if it is present. // Do not use the value `operation` in this case as it is not valid when editing val menuId = when (intent.getStringExtra("OPERATION")) { "ENCRYPT", "EDIT" -> R.menu.pgp_handler_new_password "DECRYPT" -> R.menu.pgp_handler else -> R.menu.pgp_handler } menuInflater.inflate(menuId, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { if (passwordEntry?.hotpIsIncremented() == false) { setResult(RESULT_CANCELED) } finish() } R.id.copy_password -> copyPasswordToClipBoard() R.id.share_password_as_plaintext -> shareAsPlaintext() R.id.edit_password -> editPassword() R.id.crypto_confirm_add -> encrypt() R.id.crypto_confirm_add_and_copy -> encrypt(true) R.id.crypto_cancel_add -> { if (passwordEntry?.hotpIsIncremented() == false) { setResult(RESULT_CANCELED) } finish() } else -> return super.onOptionsItemSelected(item) } return true } /** * Shows a simple toast message */ private fun showToast(message: String) { runOnUiThread { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } /** * Handle the case where OpenKeychain returns that it needs to interact with the user * * @param result The intent returned by OpenKeychain * @param requestCode The code we'd like to use to identify the behaviour */ private fun handleUserInteractionRequest(result: Intent, requestCode: Int) { Log.i(TAG, "RESULT_CODE_USER_INTERACTION_REQUIRED") val pi: PendingIntent? = result.getParcelableExtra(RESULT_INTENT) try { [email protected]( this@PgpActivity, pi?.intentSender, requestCode, null, 0, 0, 0 ) } catch (e: IntentSender.SendIntentException) { Log.e(TAG, "SendIntentException", e) } } /** * Handle the error returned by OpenKeychain * * @param result The intent returned by OpenKeychain */ private fun handleError(result: Intent) { // TODO show what kind of error it is /* For example: * No suitable key found -> no key in OpenKeyChain * * Check in open-pgp-lib how their definitions and error code */ val error: OpenPgpError? = result.getParcelableExtra(RESULT_ERROR) if (error != null) { showToast("Error from OpenKeyChain : " + error.message) Log.e(TAG, "onError getErrorId:" + error.errorId) Log.e(TAG, "onError getMessage:" + error.message) } } private fun initOpenPgpApi() { api = api ?: OpenPgpApi(this, mServiceConnection?.service) } private fun decryptAndVerify(receivedIntent: Intent? = null) { val data = receivedIntent ?: Intent() data.action = ACTION_DECRYPT_VERIFY val iStream = FileUtils.openInputStream(File(fullPath)) val oStream = ByteArrayOutputStream() api?.executeApiAsync(data, iStream, oStream) { result: Intent? -> when (result?.getIntExtra(RESULT_CODE, RESULT_CODE_ERROR)) { RESULT_CODE_SUCCESS -> { try { val showPassword = settings.getBoolean("show_password", true) val showExtraContent = settings.getBoolean("show_extra_content", true) crypto_container_decrypt.visibility = View.VISIBLE val monoTypeface = Typeface.createFromAsset(assets, "fonts/sourcecodepro.ttf") val entry = PasswordEntry(oStream) passwordEntry = entry if (intent.getStringExtra("OPERATION") == "EDIT") { editPassword() return@executeApiAsync } if (entry.password.isEmpty()) { crypto_password_show.visibility = View.GONE crypto_password_show_label.visibility = View.GONE } else { crypto_password_show.visibility = View.VISIBLE crypto_password_show_label.visibility = View.VISIBLE crypto_password_show.typeface = monoTypeface crypto_password_show.text = entry.password } crypto_password_show.typeface = monoTypeface crypto_password_show.text = entry.password crypto_password_toggle_show.visibility = if (showPassword) View.GONE else View.VISIBLE crypto_password_show.transformationMethod = if (showPassword) { null } else { HoldToShowPasswordTransformation( crypto_password_toggle_show, Runnable { crypto_password_show.text = entry.password } ) } if (entry.hasExtraContent()) { crypto_extra_show.typeface = monoTypeface crypto_extra_show.text = entry.extraContent if (showExtraContent) { crypto_extra_show_layout.visibility = View.VISIBLE crypto_extra_toggle_show.visibility = View.GONE crypto_extra_show.transformationMethod = null } else { crypto_extra_show_layout.visibility = View.GONE crypto_extra_toggle_show.visibility = View.VISIBLE crypto_extra_toggle_show.setOnCheckedChangeListener { _, _ -> crypto_extra_show.text = entry.extraContent } crypto_extra_show.transformationMethod = object : PasswordTransformationMethod() { override fun getTransformation(source: CharSequence, view: View): CharSequence { return if (crypto_extra_toggle_show.isChecked) source else super.getTransformation(source, view) } } } if (entry.hasUsername()) { crypto_username_show.visibility = View.VISIBLE crypto_username_show_label.visibility = View.VISIBLE crypto_copy_username.visibility = View.VISIBLE crypto_copy_username.setOnClickListener { copyUsernameToClipBoard(entry.username!!) } crypto_username_show.typeface = monoTypeface crypto_username_show.text = entry.username } else { crypto_username_show.visibility = View.GONE crypto_username_show_label.visibility = View.GONE crypto_copy_username.visibility = View.GONE } } if (entry.hasTotp() || entry.hasHotp()) { crypto_extra_show_layout.visibility = View.VISIBLE crypto_extra_show.typeface = monoTypeface crypto_extra_show.text = entry.extraContent crypto_otp_show.visibility = View.VISIBLE crypto_otp_show_label.visibility = View.VISIBLE crypto_copy_otp.visibility = View.VISIBLE if (entry.hasTotp()) { crypto_copy_otp.setOnClickListener { copyOtpToClipBoard( Otp.calculateCode( entry.totpSecret, Date().time / (1000 * entry.totpPeriod), entry.totpAlgorithm, entry.digits) ) } crypto_otp_show.text = Otp.calculateCode( entry.totpSecret, Date().time / (1000 * entry.totpPeriod), entry.totpAlgorithm, entry.digits) } else { // we only want to calculate and show HOTP if the user requests it crypto_copy_otp.setOnClickListener { if (settings.getBoolean("hotp_remember_check", false)) { if (settings.getBoolean("hotp_remember_choice", false)) { calculateAndCommitHotp(entry) } else { calculateHotp(entry) } } else { // show a dialog asking permission to update the HOTP counter in the entry val checkInflater = LayoutInflater.from(this) val checkLayout = checkInflater.inflate(R.layout.otp_confirm_layout, null) val rememberCheck: CheckBox = checkLayout.findViewById(R.id.hotp_remember_checkbox) val dialogBuilder = MaterialAlertDialogBuilder(this) dialogBuilder.setView(checkLayout) dialogBuilder.setMessage(R.string.dialog_update_body) .setCancelable(false) .setPositiveButton(R.string.dialog_update_positive) { _, _ -> run { calculateAndCommitHotp(entry) if (rememberCheck.isChecked) { val editor = settings.edit() editor.putBoolean("hotp_remember_check", true) editor.putBoolean("hotp_remember_choice", true) editor.apply() } } } .setNegativeButton(R.string.dialog_update_negative) { _, _ -> run { calculateHotp(entry) val editor = settings.edit() editor.putBoolean("hotp_remember_check", true) editor.putBoolean("hotp_remember_choice", false) editor.apply() } } val updateDialog = dialogBuilder.create() updateDialog.setTitle(R.string.dialog_update_title) updateDialog.show() } } crypto_otp_show.setText(R.string.hotp_pending) } crypto_otp_show.typeface = monoTypeface } else { crypto_otp_show.visibility = View.GONE crypto_otp_show_label.visibility = View.GONE crypto_copy_otp.visibility = View.GONE } if (settings.getBoolean("copy_on_decrypt", true)) { copyPasswordToClipBoard() } } catch (e: Exception) { Log.e(TAG, "An Exception occurred", e) } } RESULT_CODE_USER_INTERACTION_REQUIRED -> handleUserInteractionRequest(result, REQUEST_DECRYPT) RESULT_CODE_ERROR -> handleError(result) } } } /** * Encrypts the password and the extra content */ private fun encrypt(copy: Boolean = false) { // if HOTP was incremented, we leave fields as is; they have already been set if (intent.getStringExtra("OPERATION") != "INCREMENT") { editName = crypto_password_file_edit.text.toString().trim() editPass = crypto_password_edit.text.toString() editExtra = crypto_extra_edit.text.toString() } if (editName?.isEmpty() == true) { showToast(resources.getString(R.string.file_toast_text)) return } if (editPass?.isEmpty() == true && editExtra?.isEmpty() == true) { showToast(resources.getString(R.string.empty_toast_text)) return } if (copy) { copyPasswordToClipBoard() } val data = Intent() data.action = OpenPgpApi.ACTION_ENCRYPT // EXTRA_KEY_IDS requires long[] val longKeys = keyIDs.map { it.toLong() } data.putExtra(OpenPgpApi.EXTRA_KEY_IDS, longKeys.toLongArray()) data.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true) // TODO Check if we could use PasswordEntry to generate the file val iStream = ByteArrayInputStream("$editPass\n$editExtra".toByteArray(Charset.forName("UTF-8"))) val oStream = ByteArrayOutputStream() val path = if (intent.getBooleanExtra("fromDecrypt", false)) fullPath else "$fullPath/$editName.gpg" api?.executeApiAsync(data, iStream, oStream) { result: Intent? -> when (result?.getIntExtra(RESULT_CODE, RESULT_CODE_ERROR)) { RESULT_CODE_SUCCESS -> { try { // TODO This might fail, we should check that the write is successful val outputStream = FileUtils.openOutputStream(File(path)) outputStream.write(oStream.toByteArray()) outputStream.close() val returnIntent = Intent() returnIntent.putExtra("CREATED_FILE", path) returnIntent.putExtra("NAME", editName) returnIntent.putExtra("LONG_NAME", getLongName(fullPath, repoPath, this.editName!!)) // if coming from decrypt screen->edit button if (intent.getBooleanExtra("fromDecrypt", false)) { returnIntent.putExtra("OPERATION", "EDIT") returnIntent.putExtra("needCommit", true) } setResult(RESULT_OK, returnIntent) finish() } catch (e: Exception) { Log.e(TAG, "An Exception occurred", e) } } RESULT_CODE_ERROR -> handleError(result) } } } /** * Opens EncryptActivity with the information for this file to be edited */ private fun editPassword() { setContentView(R.layout.encrypt_layout) generate_password?.setOnClickListener { PasswordGeneratorDialogFragment().show(supportFragmentManager, "generator") } title = getString(R.string.edit_password_title) val monoTypeface = Typeface.createFromAsset(assets, "fonts/sourcecodepro.ttf") crypto_password_edit.setText(passwordEntry?.password) crypto_password_edit.typeface = monoTypeface crypto_extra_edit.setText(passwordEntry?.extraContent) crypto_extra_edit.typeface = monoTypeface crypto_password_category.text = relativeParentPath crypto_password_file_edit.setText(name) crypto_password_file_edit.isEnabled = false delayTask?.cancelAndSignal(true) val data = Intent(this, PgpActivity::class.java) data.putExtra("OPERATION", "EDIT") data.putExtra("fromDecrypt", true) intent = data invalidateOptionsMenu() } /** * Writes updated HOTP counter to edit fields and encrypts */ private fun checkAndIncrementHotp() { // we do not want to increment the HOTP counter if the user has edited the entry or has not // generated an HOTP code if (intent.getStringExtra("OPERATION") != "EDIT" && passwordEntry?.hotpIsIncremented() == true) { editName = name.trim() editPass = passwordEntry?.password editExtra = passwordEntry?.extraContent val data = Intent(this, PgpActivity::class.java) data.putExtra("OPERATION", "INCREMENT") data.putExtra("fromDecrypt", true) intent = data encrypt() } } private fun calculateHotp(entry: PasswordEntry) { copyOtpToClipBoard(Otp.calculateCode(entry.hotpSecret, entry.hotpCounter!! + 1, "sha1", entry.digits)) crypto_otp_show.text = Otp.calculateCode(entry.hotpSecret, entry.hotpCounter + 1, "sha1", entry.digits) crypto_extra_show.text = entry.extraContent } private fun calculateAndCommitHotp(entry: PasswordEntry) { calculateHotp(entry) entry.incrementHotp() // we must set the result before encrypt() is called, since in // some cases it is called during the finish() sequence val returnIntent = Intent() returnIntent.putExtra("NAME", name.trim()) returnIntent.putExtra("OPERATION", "INCREMENT") returnIntent.putExtra("needCommit", true) setResult(RESULT_OK, returnIntent) } /** * Get the Key ids from OpenKeychain */ private fun getKeyIds(receivedIntent: Intent? = null) { val data = receivedIntent ?: Intent() data.action = OpenPgpApi.ACTION_GET_KEY_IDS api?.executeApiAsync(data, null, null) { result: Intent? -> when (result?.getIntExtra(RESULT_CODE, RESULT_CODE_ERROR)) { RESULT_CODE_SUCCESS -> { try { val ids = result.getLongArrayExtra(OpenPgpApi.RESULT_KEY_IDS) ?: LongArray(0) val keys = ids.map { it.toString() }.toSet() // use Long settings.edit().putStringSet("openpgp_key_ids_set", keys).apply() showToast("PGP keys selected") setResult(RESULT_OK) finish() } catch (e: Exception) { Log.e(TAG, "An Exception occurred", e) } } RESULT_CODE_USER_INTERACTION_REQUIRED -> handleUserInteractionRequest(result, REQUEST_KEY_ID) RESULT_CODE_ERROR -> handleError(result) } } } override fun onError(e: Exception?) {} /** * The action to take when the PGP service is bound */ override fun onBound(service: IOpenPgpService2?) { initOpenPgpApi() when (operation) { "EDIT", "DECRYPT" -> decryptAndVerify() "GET_KEY_ID" -> getKeyIds() } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (data == null) { setResult(RESULT_CANCELED, null) finish() return } // try again after user interaction if (resultCode == RESULT_OK) { when (requestCode) { REQUEST_DECRYPT -> decryptAndVerify(data) REQUEST_KEY_ID -> getKeyIds(data) else -> { setResult(RESULT_OK) finish() } } } else if (resultCode == RESULT_CANCELED) { setResult(RESULT_CANCELED, data) finish() } } private inner class HoldToShowPasswordTransformation constructor(button: Button, private val onToggle: Runnable) : PasswordTransformationMethod(), View.OnTouchListener { private var shown = false init { button.setOnTouchListener(this) } override fun getTransformation(charSequence: CharSequence, view: View): CharSequence { return if (shown) charSequence else super.getTransformation("12345", view) } @Suppress("ClickableViewAccessibility") override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { when (motionEvent.action) { MotionEvent.ACTION_DOWN -> { shown = true onToggle.run() } MotionEvent.ACTION_UP -> { shown = false onToggle.run() } } return false } } private fun copyPasswordToClipBoard() { var pass = passwordEntry?.password if (findViewById<TextView>(R.id.crypto_password_show) == null) { if (editPass == null) { return } else { pass = editPass } } val clip = ClipData.newPlainText("pgp_handler_result_pm", pass) clipboard.setPrimaryClip(clip) var clearAfter = 45 try { clearAfter = Integer.parseInt(settings.getString("general_show_time", "45") as String) } catch (e: NumberFormatException) { // ignore and keep default } if (settings.getBoolean("clear_after_copy", true) && clearAfter != 0) { setTimer() showToast(this.resources.getString(R.string.clipboard_password_toast_text, clearAfter)) } else { showToast(this.resources.getString(R.string.clipboard_password_no_clear_toast_text)) } } private fun copyUsernameToClipBoard(username: String) { val clip = ClipData.newPlainText("pgp_handler_result_pm", username) clipboard.setPrimaryClip(clip) showToast(resources.getString(R.string.clipboard_username_toast_text)) } private fun copyOtpToClipBoard(code: String) { val clip = ClipData.newPlainText("pgp_handler_result_pm", code) clipboard.setPrimaryClip(clip) showToast(resources.getString(R.string.clipboard_otp_toast_text)) } private fun shareAsPlaintext() { if (findViewById<View>(R.id.share_password_as_plaintext) == null) return val sendIntent = Intent() sendIntent.action = Intent.ACTION_SEND sendIntent.putExtra(Intent.EXTRA_TEXT, passwordEntry?.password) sendIntent.type = "text/plain" startActivity( Intent.createChooser( sendIntent, resources.getText(R.string.send_plaintext_password_to) ) ) // Always show a picker to give the user a chance to cancel } private fun setTimer() { // make sure to cancel any running tasks as soon as possible // if the previous task is still running, do not ask it to clear the password delayTask?.cancelAndSignal(true) // launch a new one delayTask = DelayShow(this) delayTask?.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR) } /** * Gets a relative string describing when this shape was last changed * (e.g. "one hour ago") */ private fun getLastChangedString(timeStamp: Long): CharSequence { if (timeStamp < 0) { throw RuntimeException() } return DateUtils.getRelativeTimeSpanString(this, timeStamp, true) } @Suppress("StaticFieldLeak") inner class DelayShow(val activity: PgpActivity) : AsyncTask<Void, Int, Boolean>() { private val pb: ProgressBar? by lazy { pbLoading } private var skip = false private var cancelNotify = ConditionVariable() private var showTime: Int = 0 // Custom cancellation that can be triggered from another thread. // // This signals the DelayShow task to stop and avoids it having // to poll the AsyncTask.isCancelled() excessively. If skipClearing // is true, the cancelled task won't clear the clipboard. fun cancelAndSignal(skipClearing: Boolean) { skip = skipClearing cancelNotify.open() } val settings: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(activity) } override fun onPreExecute() { showTime = try { Integer.parseInt(settings.getString("general_show_time", "45") as String) } catch (e: NumberFormatException) { 45 } val container = findViewById<LinearLayout>(R.id.crypto_container_decrypt) container?.visibility = View.VISIBLE val extraText = findViewById<TextView>(R.id.crypto_extra_show) if (extraText?.text?.isNotEmpty() == true) findViewById<View>(R.id.crypto_extra_show_layout)?.visibility = View.VISIBLE if (showTime == 0) { // treat 0 as forever, and the user must exit and/or clear clipboard on their own cancel(true) } else { this.pb?.max = showTime } } override fun doInBackground(vararg params: Void): Boolean? { var current = 0 while (current < showTime) { // Block for 1s or until cancel is signalled if (cancelNotify.block(1000)) { return true } current++ publishProgress(current) } return true } override fun onPostExecute(b: Boolean?) { if (skip) return checkAndIncrementHotp() // No need to validate clear_after_copy. It was validated in copyPasswordToClipBoard() Log.d("DELAY_SHOW", "Clearing the clipboard") val clip = ClipData.newPlainText("pgp_handler_result_pm", "") clipboard.setPrimaryClip(clip) if (settings.getBoolean("clear_clipboard_20x", false)) { val handler = Handler() for (i in 0..19) { val count = i.toString() handler.postDelayed( { clipboard.setPrimaryClip(ClipData.newPlainText(count, count)) }, (i * 500).toLong() ) } } if (crypto_password_show != null) { // clear password; if decrypt changed to encrypt layout via edit button, no need if (passwordEntry?.hotpIsIncremented() == false) { setResult(RESULT_CANCELED) } passwordEntry = null crypto_password_show.text = "" crypto_extra_show.text = "" crypto_extra_show_layout.visibility = View.INVISIBLE crypto_container_decrypt.visibility = View.INVISIBLE finish() } } override fun onProgressUpdate(vararg values: Int?) { this.pb?.progress = values[0] ?: 0 } } companion object { const val OPEN_PGP_BOUND = 101 const val REQUEST_DECRYPT = 202 const val REQUEST_KEY_ID = 203 const val TAG = "PgpActivity" private var delayTask: DelayShow? = null /** * Gets the relative path to the repository */ fun getRelativePath(fullPath: String, repositoryPath: String): String = fullPath.replace(repositoryPath, "").replace("/+".toRegex(), "/") /** * Gets the Parent path, relative to the repository */ fun getParentPath(fullPath: String, repositoryPath: String): String { val relativePath = getRelativePath(fullPath, repositoryPath) val index = relativePath.lastIndexOf("/") return "/${relativePath.substring(startIndex = 0, endIndex = index + 1)}/".replace("/+".toRegex(), "/") } /** * Gets the name of the password (excluding .gpg) */ fun getName(fullPath: String): String { return FilenameUtils.getBaseName(fullPath) } /** * /path/to/store/social/facebook.gpg -> social/facebook */ @JvmStatic fun getLongName(fullPath: String, repositoryPath: String, basename: String): String { var relativePath = getRelativePath(fullPath, repositoryPath) return if (relativePath.isNotEmpty() && relativePath != "/") { // remove preceding '/' relativePath = relativePath.substring(1) if (relativePath.endsWith('/')) { relativePath + basename } else { "$relativePath/$basename" } } else { basename } } } }
gpl-3.0
3ff7b0ba80561fbad9ee2e01bdd1dfd0
41.265143
136
0.545319
5.295246
false
false
false
false
FHannes/intellij-community
platform/configuration-store-impl/src/schemeLoader.kt
6
3200
package com.intellij.configurationStore import com.intellij.openapi.application.runUndoTransparentWriteAction import com.intellij.openapi.project.ProjectBundle import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.io.createDirectories import com.intellij.util.io.systemIndependentPath import org.xmlpull.mxp1.MXParser import org.xmlpull.v1.XmlPullParser import java.io.IOException import java.nio.file.Path import java.util.* internal inline fun lazyPreloadScheme(bytes: ByteArray, isUseOldFileNameSanitize: Boolean, consumer: (name: String?, parser: XmlPullParser) -> Unit) { val parser = MXParser() parser.setInput(bytes.inputStream().reader()) consumer(preload(isUseOldFileNameSanitize, parser), parser) } private fun preload(isUseOldFileNameSanitize: Boolean, parser: MXParser): String? { var eventType = parser.eventType fun findName(): String? { eventType = parser.next() while (eventType != XmlPullParser.END_DOCUMENT) { when (eventType) { XmlPullParser.START_TAG -> { if (parser.name == "option" && parser.getAttributeValue(null, "name") == "myName") { return parser.getAttributeValue(null, "value") } } } eventType = parser.next() } return null } do { when (eventType) { XmlPullParser.START_TAG -> { if (!isUseOldFileNameSanitize || parser.name != "component") { if (parser.name == "profile" || (isUseOldFileNameSanitize && parser.name == "copyright")) { return findName() } else if (parser.name == "inspections") { // backward compatibility - we don't write PROFILE_NAME_TAG anymore return parser.getAttributeValue(null, "profile_name") ?: findName() } else { return null } } } } eventType = parser.next() } while (eventType != XmlPullParser.END_DOCUMENT) return null } internal class ExternalInfo(var fileNameWithoutExtension: String, var fileExtension: String?) { // we keep it to detect rename var schemeName: String? = null var digest: ByteArray? = null val fileName: String get() = "$fileNameWithoutExtension$fileExtension" fun setFileNameWithoutExtension(nameWithoutExtension: String, extension: String) { fileNameWithoutExtension = nameWithoutExtension fileExtension = extension } fun isDigestEquals(newDigest: ByteArray) = Arrays.equals(digest, newDigest) override fun toString() = fileName } internal fun VirtualFile.getOrCreateChild(fileName: String, requestor: Any): VirtualFile { return findChild(fileName) ?: runUndoTransparentWriteAction { createChildData(requestor, fileName) } } internal fun createDir(ioDir: Path, requestor: Any): VirtualFile { ioDir.createDirectories() val parentFile = ioDir.parent val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile.systemIndependentPath)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)) return parentVirtualFile.getOrCreateChild(ioDir.fileName.toString(), requestor) }
apache-2.0
7abc2f3a64b5d9437596aee1ccf5de43
33.793478
150
0.7125
4.664723
false
false
false
false