content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package uk.co.ribot.androidboilerplate.util.extension import android.database.Cursor fun Cursor.getString(columnName: String, defaultValue: String = ""): String { val index = getColumnIndex(columnName) return getString(index) ?: defaultValue } fun Cursor.getInt(columnName: String, defaultValue: Int = 0): Int { val index = getColumnIndex(columnName) return if (index >= 0) getInt(index) else defaultValue } fun Cursor.getLong(columnName: String, defaultValue: Long = 0): Long { val index = getColumnIndex(columnName) return if (index >= 0) getLong(index) else defaultValue } fun Cursor.getBoolean(columnName: String, defaultValue: Boolean = false): Boolean { val index = getColumnIndex(columnName) return if (index >= 0) getInt(index) == 1 else defaultValue }
app/src/main/kotlin/uk/co/ribot/androidboilerplate/util/extension/CursorExtension.kt
2666944172
package com.flexpoker.pushnotificationhandlers import com.flexpoker.framework.pushnotifier.PushNotificationHandler import com.flexpoker.game.query.repository.OpenGameForPlayerRepository import com.flexpoker.login.repository.LoginRepository import com.flexpoker.pushnotifications.OpenGamesForPlayerUpdatedPushNotification import com.flexpoker.util.MessagingConstants import org.springframework.messaging.simp.SimpMessageSendingOperations import org.springframework.scheduling.annotation.Async import org.springframework.stereotype.Component import javax.inject.Inject @Component class OpenGamesForPlayerUpdatedPushNotificationHandler @Inject constructor( private val loginRepository: LoginRepository, private val openGameForUserRepository: OpenGameForPlayerRepository, private val messagingTemplate: SimpMessageSendingOperations ) : PushNotificationHandler<OpenGamesForPlayerUpdatedPushNotification> { @Async override fun handle(pushNotification: OpenGamesForPlayerUpdatedPushNotification) { val username = loginRepository.fetchUsernameByAggregateId(pushNotification.playerId) val allOpenGames = openGameForUserRepository.fetchAllOpenGamesForPlayer(pushNotification.playerId) messagingTemplate.convertAndSendToUser(username, MessagingConstants.OPEN_GAMES_FOR_USER, allOpenGames) } }
src/main/kotlin/com/flexpoker/pushnotificationhandlers/OpenGamesForPlayerUpdatedPushNotificationHandler.kt
2707647732
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.gui import javafx.scene.Node import javafx.scene.input.* open class SimpleDragHelper<T>( val dataFormat: DataFormat, allowCopy: Boolean = true, allowMove: Boolean = true, allowLink: Boolean = true, val onMoved: ((T) -> Unit)? = null, val obj: () -> (T)) : DragHelper { val modes = modes(allowCopy, allowMove, allowLink) override fun applyTo(node: Node) { node.setOnDragDetected { onDragDetected(it) } node.setOnDragDone { onDone(it) } } fun addContentToClipboard(clipboard: ClipboardContent): Boolean { obj()?.let { clipboard.put(dataFormat, it) return true } return false } open fun onDragDetected(event: MouseEvent) { val dragboard = event.pickResult.intersectedNode.startDragAndDrop(* modes) val clipboard = ClipboardContent() if (addContentToClipboard(clipboard)) { dragboard.setContent(clipboard) } event.consume() } open fun onDone(event: DragEvent) { val content = content(event) if (content != null && event.transferMode == TransferMode.MOVE) { onMoved?.let { it(content) } } event.consume() } fun content(event: DragEvent): T? { @Suppress("UNCHECKED_CAST") return event.dragboard.getContent(dataFormat) as T } companion object { fun modes(allowCopy: Boolean, allowMove: Boolean, allowLink: Boolean): Array<TransferMode> { val set = mutableSetOf<TransferMode>() if (allowCopy) { set.add(TransferMode.COPY) } if (allowMove) { set.add(TransferMode.MOVE) } if (allowLink) { set.add(TransferMode.LINK) } return set.toTypedArray() } } }
paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/gui/SimpleDragHelper.kt
1648686392
package net.nemerosa.ontrack.extension.elastic.metrics import org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchProperties import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.convert.DurationUnit import org.springframework.stereotype.Component import java.time.Duration import java.time.temporal.ChronoUnit @ConfigurationProperties(prefix = ElasticMetricsConfigProperties.ELASTIC_METRICS_PREFIX) @Component class ElasticMetricsConfigProperties { companion object { /** * Prefix for the Elastic metrics configuration. */ const val ELASTIC_METRICS_PREFIX = "ontrack.extension.elastic.metrics" } /** * Is the export of metrics to Elastic enabled? */ var enabled: Boolean = false /** * Must we trace the behaviour of the export of the metrics in the logs? */ var debug: Boolean = false /** * Defines where the Elastic metrics should be sent. */ var target: ElasticMetricsTarget = ElasticMetricsTarget.MAIN /** * Index properties */ var index = IndexConfigProperties() /** * Custom connection */ var custom = ElasticsearchProperties() /** * Set to true to enable the API Compatibility mode when accessing a 8.x ES server. * * See https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.17/java-rest-high-compatibility.html */ var apiCompatibilityMode: Boolean = false /** * Set to false to disable the possibility to clear the index in case of re-indexation */ var allowDrop: Boolean = true /** * Index properties */ class IndexConfigProperties { /** * Name of the index to contains all Ontrack metrics */ var name = "ontrack_metrics" /** * Flag to enable immediate re-indexation after items are added into the index (used mostly * for testing). */ var immediate = false } /** * Queue configuration */ var queue = QueueConfigProperties() /** * Queue configuration */ class QueueConfigProperties { /** * Maximum capacity for the queue */ var capacity: UInt = 1024U /** * Maximum buffer for the queue before flushing */ var buffer: UInt = 512U /** * Interval between the regular flushing of the queue of events */ @DurationUnit(ChronoUnit.MINUTES) var flushing: Duration = Duration.ofMinutes(1) } }
ontrack-extension-elastic/src/main/java/net/nemerosa/ontrack/extension/elastic/metrics/ElasticMetricsConfigProperties.kt
1320585039
package net.bjoernpetersen.musicbot.api.loader /** * This exception is thrown if a song could not be loaded. */ class SongLoadingException : Exception { constructor() : super() constructor(message: String) : super(message) constructor(message: String, cause: Throwable) : super(message, cause) constructor(cause: Throwable) : super(cause) }
src/main/kotlin/net/bjoernpetersen/musicbot/api/loader/SongLoadingException.kt
1658844608
package com.iyanuadelekan.kanary.app.framework.lifecycle import com.iyanuadelekan.kanary.app.LifeCycleEvent /** * @author Iyanu Adelekan on 25/11/2018. */ internal interface LifeCycle { /** * Adds application start event. * * @param event */ fun onStart(event: LifeCycleEvent) /** * Adds application stop event. * * @param event */ fun onStop(event: LifeCycleEvent) }
src/main/com/iyanuadelekan/kanary/app/framework/lifecycle/LifeCycle.kt
1545627707
package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings import android.os.Bundle import android.view.* import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProvider import org.tvheadend.data.entity.TimerRecording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.databinding.TimerRecordingDetailsFragmentBinding import org.tvheadend.tvhclient.ui.base.BaseFragment import org.tvheadend.tvhclient.ui.common.* import org.tvheadend.tvhclient.ui.common.interfaces.ClearSearchResultsOrPopBackStackInterface import org.tvheadend.tvhclient.ui.common.interfaces.RecordingRemovedInterface import org.tvheadend.tvhclient.util.extensions.gone import org.tvheadend.tvhclient.util.extensions.visible class TimerRecordingDetailsFragment : BaseFragment(), RecordingRemovedInterface, ClearSearchResultsOrPopBackStackInterface { private lateinit var timerRecordingViewModel: TimerRecordingViewModel private var recording: TimerRecording? = null private lateinit var binding: TimerRecordingDetailsFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = DataBindingUtil.inflate(inflater, R.layout.timer_recording_details_fragment, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) timerRecordingViewModel = ViewModelProvider(requireActivity())[TimerRecordingViewModel::class.java] if (!isDualPane) { toolbarInterface.setTitle(getString(R.string.details)) toolbarInterface.setSubtitle("") } arguments?.let { timerRecordingViewModel.currentIdLiveData.value = it.getString("id", "") } timerRecordingViewModel.recordingLiveData.observe(viewLifecycleOwner, { recording = it showRecordingDetails() }) } private fun showRecordingDetails() { if (recording != null) { binding.recording = recording binding.htspVersion = htspVersion binding.isDualPane = isDualPane // The toolbar is hidden as a default to prevent pressing any icons if no recording // has been loaded yet. The toolbar is shown here because a recording was loaded binding.nestedToolbar.visible() activity?.invalidateOptionsMenu() } else { binding.scrollview.gone() binding.status.text = getString(R.string.error_loading_recording_details) binding.status.visible() } } override fun onPrepareOptionsMenu(menu: Menu) { val recording = this.recording ?: return preparePopupOrToolbarSearchMenu(menu, recording.title, isConnectionToServerAvailable) binding.nestedToolbar.menu.findItem(R.id.menu_edit_recording)?.isVisible = true binding.nestedToolbar.menu.findItem(R.id.menu_remove_recording)?.isVisible = true } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.external_search_options_menu, menu) binding.nestedToolbar.inflateMenu(R.menu.recording_details_toolbar_menu) binding.nestedToolbar.setOnMenuItemClickListener { this.onOptionsItemSelected(it) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val ctx = context ?: return super.onOptionsItemSelected(item) val recording = this.recording ?: return super.onOptionsItemSelected(item) return when (item.itemId) { R.id.menu_edit_recording -> editSelectedTimerRecording(requireActivity(), recording.id) R.id.menu_remove_recording -> showConfirmationToRemoveSelectedTimerRecording(ctx, recording, this) R.id.menu_search_imdb -> return searchTitleOnImdbWebsite(ctx, recording.title) R.id.menu_search_fileaffinity -> return searchTitleOnFileAffinityWebsite(ctx, recording.title) R.id.menu_search_youtube -> return searchTitleOnYoutube(ctx, recording.title) R.id.menu_search_google -> return searchTitleOnGoogle(ctx, recording.title) R.id.menu_search_epg -> return searchTitleInTheLocalDatabase(requireActivity(), baseViewModel, recording.title) else -> super.onOptionsItemSelected(item) } } override fun onRecordingRemoved() { if (!isDualPane) { activity?.onBackPressed() } else { val detailsFragment = activity?.supportFragmentManager?.findFragmentById(R.id.details) if (detailsFragment != null) { activity?.supportFragmentManager?.beginTransaction()?.also { it.remove(detailsFragment) it.commit() } } } } companion object { fun newInstance(id: String): TimerRecordingDetailsFragment { val f = TimerRecordingDetailsFragment() val args = Bundle() args.putString("id", id) f.arguments = args return f } } }
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingDetailsFragment.kt
3683780177
package apoc.nlp.azure import org.neo4j.graphdb.Node interface AzureClient { fun entities(nodes: List<Node>, batchId: Int): List<Map<String, Any>> fun sentiment(nodes: List<Node>, batchId: Int): List<Map<String, Any>> fun keyPhrases(nodes: List<Node>, batchId: Int): List<Map<String, Any>> }
extended/src/main/kotlin/apoc/nlp/azure/AzureClient.kt
998165781
package com.jraska.github.client import com.jraska.github.client.logging.CrashReporter object EmptyCrashReporter : CrashReporter { override fun report(error: Throwable, vararg messages: String): CrashReporter { return this } }
core-testing/src/main/java/com/jraska/github/client/EmptyCrashReporter.kt
4288262849
package graphql.execution.instrumentation.parameters import graphql.execution.instrumentation.Instrumentation import graphql.language.Document /** * Parameters sent to [Instrumentation] methods */ class ValidationParameters(query: String, operation: String?, context: Any, arguments: Map<String, Any>, val document: Document) : ExecutionParameters(query, operation, context, arguments)
src/main/kotlin/graphql/execution/instrumentation/parameters/ValidationParameters.kt
2125423272
package com.xiaojinzi.component.fragment import androidx.annotation.UiThread import com.xiaojinzi.component.support.IBaseLifecycle import com.xiaojinzi.component.support.IHost /** * 每个模块的接口,需要有生命周期的通知 */ interface IComponentHostFragment : IBaseLifecycle, IHost { /** * 主要用于检查模块和模块之间的重复 * 这个 map 不可能有重复的. * 第一:因为这是一个 Map, 有重复的也会被覆盖 * 第二:在注解驱动器中, 做了避免重复的操作 */ @get:UiThread val fragmentNameSet: Set<String> }
ComponentImpl/src/main/java/com/xiaojinzi/component/fragment/IComponentHostFragment.kt
3629629706
/* * Copyright 2017 Yonghoon Kim * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pickth.gachi.view.main.fragments.festival.adapter import android.support.v7.widget.RecyclerView import android.view.View import com.bumptech.glide.Glide import com.pickth.gachi.util.OnFestivalClickListener import kotlinx.android.synthetic.main.item_main_festival.view.* class FestivalViewHolder(view: View, val listener: OnFestivalClickListener?): RecyclerView.ViewHolder(view) { fun onBind(item: Festival, position: Int) { with(itemView) { if(item.imageUrl != "") Glide.with(itemView.context) .load(item.imageUrl) .into(iv_main_festival) tv_main_festival_title.text = item.title tv_main_festival_date.text = item.date } itemView.setOnClickListener { if(item.type == "popular") { listener?.onPopularFestivalClick(position) } else { listener?.onImmediateFestivalClick(position) } } } }
Gachi/app/src/main/kotlin/com/pickth/gachi/view/main/fragments/festival/adapter/FestivalViewHolder.kt
3425172672
package t.masahide.android.croudia.entitiy import java.util.* import android.os.Parcel import android.os.Parcelable import com.squareup.moshi.Json /** * Created with IntelliJ IDEA. * User: masahide * Date: 2013/08/12 * Time: 23:47 * To change this template use File | Settings | File Templates. */ data class User( @Json(name = "description") val description: String, @Json(name = "favorites_count") val favoritesCount: Int = 0, @Json(name = "follow_request_sent") val followRequestSent: Boolean = false, @Json(name = "following") val following: Boolean = false, @Json(name = "followers_count") val followersCount: Int = 0, @Json(name = "friends_count") val friendsCount: Int = 0, @Json(name = "id_str") val id: String, @Json(name = "location") val location: String, @Json(name = "name") val name: String, @Json(name = "screen_name") val screenName: String, @Json(name = "profile_image_url_https") val profileImageUrl: String, @Json(name = "cover_image_url_https") val coverImageUrl: String, @Json(name = "protected") val isProtected: Boolean = false, @Json(name = "statuses_count") val statuesCount: Int = 0, @Json(name = "url") val url: String? = null) : Parcelable { constructor(source: Parcel): this(source.readString(), source.readInt(), 1.toByte().equals(source.readByte()), 1.toByte().equals(source.readByte()), source.readInt(), source.readInt(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), source.readString(), 1.toByte().equals(source.readByte()), source.readInt(), source.readSerializable() as String?) override fun describeContents(): Int { return 0 } override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeString(description) dest?.writeInt(favoritesCount) dest?.writeByte((if (followRequestSent) 1 else 0).toByte()) dest?.writeByte((if (following) 1 else 0).toByte()) dest?.writeInt(followersCount) dest?.writeInt(friendsCount) dest?.writeString(id) dest?.writeString(location) dest?.writeString(name) dest?.writeString(screenName) dest?.writeString(profileImageUrl) dest?.writeString(coverImageUrl) dest?.writeByte((if (isProtected) 1 else 0).toByte()) dest?.writeInt(statuesCount) dest?.writeSerializable(url) } companion object { @JvmField final val CREATOR: Parcelable.Creator<User> = object : Parcelable.Creator<User> { override fun createFromParcel(source: Parcel): User { return User(source) } override fun newArray(size: Int): Array<User?> { return arrayOfNulls(size) } } } }
app/src/main/kotlin/t/masahide/android/croudia/entitiy/User.kt
2965085263
package com.sinnerschrader.s2b.accounttool.presentation.validation import com.sinnerschrader.s2b.accounttool.logic.component.security.PasswordAnalyzeService import com.sinnerschrader.s2b.accounttool.logic.component.security.PwnedPasswordService import com.sinnerschrader.s2b.accounttool.presentation.RequestUtils import com.sinnerschrader.s2b.accounttool.presentation.controller.ProfileController import com.sinnerschrader.s2b.accounttool.presentation.controller.ProfileController.Edit.* import com.sinnerschrader.s2b.accounttool.presentation.model.ChangeProfile import org.apache.commons.codec.binary.Base64 import org.apache.commons.lang3.StringUtils import org.apache.sshd.common.util.buffer.ByteArrayBuffer import org.slf4j.LoggerFactory import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Component import org.springframework.validation.Errors import org.springframework.validation.ValidationUtils.rejectIfEmptyOrWhitespace import org.springframework.validation.Validator import java.security.interfaces.DSAPublicKey import java.security.interfaces.ECPublicKey import java.security.interfaces.RSAPublicKey import javax.servlet.http.HttpServletRequest @Component(value = "changeProfileFormValidator") class ChangeProfileFormValidator : Validator { @Autowired private lateinit var passwordAnalyzeService: PasswordAnalyzeService @Autowired private lateinit var request: HttpServletRequest override fun supports(clazz: Class<*>) =ChangeProfile::class.java.isAssignableFrom(clazz) private fun validateAndSanitizeSSHKey(form: ChangeProfile, errors: Errors) { val formAttribute = "publicKey" rejectIfEmptyOrWhitespace(errors, "publicKey", "required") if (errors.hasErrors()) return var sanitizedKey = "" val parts = StringUtils.split(form.publicKey, " ") if (parts.size >= 2) { try { val base64Key = parts[1] val binary = Base64.decodeBase64(base64Key) val publicKey = ByteArrayBuffer(binary).rawPublicKey if (StringUtils.equals(publicKey.algorithm, "EC")) { val ecKey = publicKey as ECPublicKey if (ecKey.params.order.bitLength() < 256) { errors.rejectValue(formAttribute, "publicKey.ec.insecure", "ec key with minimum of 256 bit required") return } sanitizedKey = "ecdsa-sha2-nistp" + ecKey.params.order.bitLength() + " " } else if (StringUtils.equals(publicKey.algorithm, "RSA")) { val rsaPublicKey = publicKey as RSAPublicKey if (rsaPublicKey.modulus.bitLength() < 2048) { errors.rejectValue(formAttribute, "publicKey.rsa.insecure", "rsa key with minimum of 2048 bit required") return } sanitizedKey = "ssh-rsa " } else if (StringUtils.equals(publicKey.algorithm, "DSA")) { val dsaPublicKey = publicKey as DSAPublicKey if (dsaPublicKey.params.p.bitLength() < 2048) { errors.rejectValue(formAttribute, "publicKey.dsa.insecure", "dsa key with minimum of 2048 bit required") return } sanitizedKey = "ssh-dss " } val buffer = ByteArrayBuffer() buffer.putRawPublicKey(publicKey) sanitizedKey += Base64.encodeBase64String(buffer.compactData) form.publicKey = sanitizedKey } catch (e: Exception) { val msg = "Could not parse public key" errors.rejectValue(formAttribute, "publicKey.invalid", "The defined public can't be parsed") LOG.error(msg) if (LOG.isDebugEnabled) { LOG.error(msg, e) } } } else { errors.rejectValue(formAttribute, "publicKey.invalid", "The defined public can't be parsed") } } private fun validatePassword(form: ChangeProfile, errors: Errors) { rejectIfEmptyOrWhitespace(errors, "oldPassword", "required", "Please enter your current password") rejectIfEmptyOrWhitespace(errors, "password", "required", "Please enter a password") if (errors.hasErrors()) return rejectIfEmptyOrWhitespace(errors, "passwordRepeat", "required", "Please repeat the password") if (form.password != form.passwordRepeat) errors.reject("passwordRepeat", "Passwords don't match") if (form.password.length < 10) errors.reject("password", "The password required at least 10 characters") if (errors.hasErrors()) return val currentUser = RequestUtils.currentUserDetails!! if (currentUser.password != form.oldPassword) { errors.rejectValue("oldPassword", "password.previous.notMatch") } if (currentUser.password == form.password) { errors.rejectValue("password", "password.noChange") } val result = passwordAnalyzeService.analyze(form.password, currentUser.uid, currentUser.username) if (!result.isValid) { val codes = result.errorCodes if (codes.isEmpty()) { // this is a fallback, if no message and no suggestions are provided errors.rejectValue("password", "passwordValidation.general.error", "The password is too weak") } else { for (code in result.errorCodes) { errors.rejectValue("password", code, "Your password violates a rule.") } } } else if (PwnedPasswordService.isPwned(form.password)) { errors.rejectValue("password", "passwordValidation.isPwned.error", "The password has previously appeared in a security breach") } } override fun validate(target: Any, errors: Errors) { with(target as ChangeProfile){ when(edit){ SSH_KEY -> validateAndSanitizeSSHKey(this, errors) PASSWORD -> validatePassword(this, errors) else -> Unit } } } companion object { private val LOG = LoggerFactory.getLogger(ChangeProfileFormValidator::class.java) } }
src/main/kotlin/com/sinnerschrader/s2b/accounttool/presentation/validation/ChangeProfileFormValidator.kt
743622470
package org.equeim.tremotesf.torrentfile import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestDispatcher import org.equeim.tremotesf.common.TremotesfDispatchers @OptIn(ExperimentalCoroutinesApi::class) class TestDispatchers constructor(dispatcher: TestDispatcher) : TremotesfDispatchers { override val Default = dispatcher override val IO = dispatcher override val Main = dispatcher override val Unconfined = dispatcher }
torrentfile/src/test/kotlin/org/equeim/tremotesf/torrentfile/TestDispatchers.kt
517575111
package pl.mareklangiewicz.myintent import android.content.ContentValues import android.database.Cursor import android.database.sqlite.SQLiteDatabase import androidx.test.InstrumentationRegistry import androidx.test.runner.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import pl.mareklangiewicz.myloggers.MY_DEFAULT_ANDRO_LOGGER import pl.mareklangiewicz.myutils.i /** * Created by Marek Langiewicz on 09.10.15. */ @RunWith(AndroidJUnit4::class) class MIDBHelperTest { val log = MY_DEFAULT_ANDRO_LOGGER val context = InstrumentationRegistry.getTargetContext()!! private var mMIDBHelper: MIDBHelper? = null @Before fun setUp() { context.deleteDatabase(MIDBHelper.DATABASE_NAME) mMIDBHelper = MIDBHelper(context) } @After fun tearDown() { mMIDBHelper!!.close() mMIDBHelper = null context.deleteDatabase(MIDBHelper.DATABASE_NAME) } @Test fun testGetReadableDatabase() { val db = mMIDBHelper!!.readableDatabase!! assertThat(db.isOpen).isTrue() } @Test fun testGetWritableDatabase() { val db = mMIDBHelper!!.writableDatabase!! assertThat(db.isOpen).isTrue() } fun logCursor(c: Cursor) { val columns = c.columnNames log.i("column names:") for (i in columns.indices) { log.i("col $i: ${columns[i]}") } var r = 0 c.moveToFirst() while (!c.isAfterLast) { log.i("row $r:") for (i in 0..c.columnCount - 1) { log.i("val ${columns[i]}: ${c.getString(i)}") } r++ c.moveToNext() } } fun logTable(db: SQLiteDatabase, table: String) { log.i("Table: $table") val c = db.rawQuery("SELECT * FROM $table", null) logCursor(c) c.close() } @Test fun testCmdRecent() { val db = mMIDBHelper!!.writableDatabase!! val values = ContentValues() values.put(MIContract.CmdRecent.COL_COMMAND, "bla bla commbla") values.put(MIContract.CmdRecent.COL_TIME, System.currentTimeMillis()) var rowid = db.insert(MIContract.CmdRecent.TABLE_NAME, null, values) assertThat(rowid).isAtLeast(0) values.put(MIContract.CmdRecent.COL_COMMAND, "ble ble bleeee") values.put(MIContract.CmdRecent.COL_TIME, System.currentTimeMillis()) rowid = db.insert(MIContract.CmdRecent.TABLE_NAME, null, values) assertThat(rowid).isAtLeast(0) logTable(db, "CmdRecent") logTable(db, "CmdSuggest") } @Test fun testRuleUser() { val db = mMIDBHelper!!.writableDatabase!! val values = ContentValues() values.put(MIContract.RuleUser.COL_POSITION, 666) values.put(MIContract.RuleUser.COL_EDITABLE, true) values.put(MIContract.RuleUser.COL_NAME, "Test rule naaaame") values.put(MIContract.RuleUser.COL_DESCRIPTION, "Test rule description") values.put(MIContract.RuleUser.COL_MATCH, "Matchfdjsklafj") values.put(MIContract.RuleUser.COL_REPLACE, "REplace") var rowid = db.insert(MIContract.RuleUser.TABLE_NAME, null, values) assertThat(rowid).isAtLeast(0) values.put(MIContract.RuleUser.COL_POSITION, 667) values.put(MIContract.RuleUser.COL_EDITABLE, false) values.put(MIContract.RuleUser.COL_NAME, "second name") values.put(MIContract.RuleUser.COL_DESCRIPTION, "second description") values.put(MIContract.RuleUser.COL_MATCH, "Match second rule..") values.put(MIContract.RuleUser.COL_REPLACE, "Replace second rule") rowid = db.insert(MIContract.RuleUser.TABLE_NAME, null, values) assertThat(rowid).isAtLeast(0) logTable(db, "RuleUser") } @Test fun testLogTables() { val db = mMIDBHelper!!.readableDatabase!! logTable(db, "sqlite_master") logTable(db, "CmdRecent") logTable(db, "CmdExample") logTable(db, "CmdSuggest") logTable(db, "RuleUser") logTable(db, "android_metadata") } }
myintent/src/androidTest/java/pl/mareklangiewicz/myintent/MIDBHelperTest.kt
11546259
import java.util.* @ExperimentalStdlibApi fun main() { val s = Scanner(System.`in`).useDelimiter("""\s->\s|\n\n|\n""") val input = s.next() var polymers = (0 until input.length - 1).map { input.slice(it..(it + 1)) }.groupBy { it }.mapValues { it.value.size } val rules = buildMap<String, String> { while (s.hasNext()) { put(s.next(), s.next()) } } repeat(10) { val newPolymers = mutableMapOf<String, Int>() for ((str, count) in polymers) { val n = rules[str]!! newPolymers[str[0] + n] = newPolymers.getOrDefault(str[0] + n, 0) + count newPolymers[n + str[1]] = newPolymers.getOrDefault(n + str[1], 0) + count } polymers = newPolymers } val counts = mutableMapOf(input.last() to 1) for ((str, count) in polymers) { counts[str[0]] = counts.getOrDefault(str[0], 0) + count } println(counts.maxOf { it.value } - counts.minOf { it.value }) }
problems/2021adventofcode14a/submissions/accepted/Stefan.kt
444751861
package com.google.firebase.samples.apps.mlkit.kotlin.imagelabeling import android.graphics.Bitmap import android.util.Log import com.google.android.gms.tasks.Task import com.google.firebase.ml.vision.FirebaseVision import com.google.firebase.ml.vision.common.FirebaseVisionImage import com.google.firebase.ml.vision.label.FirebaseVisionImageLabel import com.google.firebase.ml.vision.label.FirebaseVisionImageLabeler import com.google.firebase.samples.apps.mlkit.common.CameraImageGraphic import com.google.firebase.samples.apps.mlkit.common.FrameMetadata import com.google.firebase.samples.apps.mlkit.common.GraphicOverlay import com.google.firebase.samples.apps.mlkit.kotlin.VisionProcessorBase import java.io.IOException /** Custom Image Classifier Demo. */ class ImageLabelingProcessor : VisionProcessorBase<List<FirebaseVisionImageLabel>>() { private val detector: FirebaseVisionImageLabeler = FirebaseVision.getInstance().onDeviceImageLabeler override fun stop() { try { detector.close() } catch (e: IOException) { Log.e(TAG, "Exception thrown while trying to close Text Detector: $e") } } override fun detectInImage(image: FirebaseVisionImage): Task<List<FirebaseVisionImageLabel>> { return detector.processImage(image) } override fun onSuccess( originalCameraImage: Bitmap?, labels: List<FirebaseVisionImageLabel>, frameMetadata: FrameMetadata, graphicOverlay: GraphicOverlay ) { graphicOverlay.clear() originalCameraImage.let { image -> val imageGraphic = CameraImageGraphic(graphicOverlay, image) graphicOverlay.add(imageGraphic) } val labelGraphic = LabelGraphic(graphicOverlay, labels) graphicOverlay.add(labelGraphic) graphicOverlay.postInvalidate() } override fun onFailure(e: Exception) { Log.w(TAG, "Label detection failed.$e") } companion object { private const val TAG = "ImageLabelingProcessor" } }
mlkit/app/src/main/java/com/google/firebase/samples/apps/mlkit/kotlin/imagelabeling/ImageLabelingProcessor.kt
385402253
package net.dean.jraw.test.integration import com.winterbe.expekt.should import net.dean.jraw.test.TestConfig.reddit import net.dean.jraw.test.randomName import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import java.util.* class InboxReferenceTest : Spek({ val inbox = reddit.me().inbox() describe("iterate") { val whereValues = listOf("inbox", "unread", "messages", "comments", "selfreply", "mentions") for (where in whereValues) { it("should be able to iterate '$where'") { val p = inbox.iterate(where).build() val messages = p.accumulate(maxPages = 2) if (messages.size > 1 && messages[0].isNotEmpty() && messages[1].isNotEmpty()) // Make sure BarebonesPaginator is working correctly as far as dealing with multiple pages messages[0][0].fullName.should.not.equal(messages[1][0].fullName) } } } describe("fetch") { it("should return a Message when the ID is valid") { val id = inbox.iterate("messages").build().next().first().id inbox.fetch(id).should.not.be.`null` } it("should return null when the Message with that ID doesn\'t exist") { inbox.fetch("fdafdafdsaffdsa").should.be.`null` } } describe("compose/markRead/delete") { it("should be able to send a message") { val body = "random ID: ${randomName()}" inbox.compose(reddit.requireAuthenticatedUser(), "test PM", body) // Make sure it appeared in our inbox. Messages sent to yourself are always marked as read, regardless of // calls to POST /api/unread_message. There's not much we can in this situation besides make sure that the // response doesn't contain any errors val message = inbox.iterate("messages").build().next().firstOrNull { it.body == body } message.should.not.be.`null` inbox.markRead(false, message!!.fullName) inbox.markRead(true, message.fullName) // Jst make sure it doesn't fail inbox.delete(message.fullName) } } describe("markAllRead") { it("should mark all messages as read") { // Again, there's no way we can really test this without involving another testing user inbox.markAllRead() } } describe("replyTo") { it("should reply to a PM") { // Send a message to ourselves inbox.compose(reddit.requireAuthenticatedUser(), "Test PM", Date().toString()) // Find that message val message = inbox.iterate("messages").build().next().first { it.author == reddit.requireAuthenticatedUser() } val reply = inbox.replyTo(message.fullName, "Test PM reply at ${Date()}") reply.isComment.should.be.`false` } } })
lib/src/test/kotlin/net/dean/jraw/test/integration/InboxReferenceTest.kt
4264042698
/* * Copyright (c) 2017-2022 by Oliver Boehm * * 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. * * (c)reated 21.02.2017 by oboehm ([email protected]) */ package de.jfachwert.pruefung import de.jfachwert.PruefzifferVerfahren import de.jfachwert.pruefung.exception.InvalidLengthException import de.jfachwert.pruefung.exception.LocalizedIllegalArgumentException import java.io.Serializable import java.util.* /** * Bei der Laengen-Validierung wird nur die Laenge des Fachwertes geprueft, ob * er zwischen der erlaubten Minimal- und Maximallaenge liegt. Ist die * Minimallaenge 0, sind leere Werte erlaubt, ist die Maximallaenge unendlich * (bzw. groesster Integer-Wert), gibt es keine Laengenbeschraenkung. * * Urspruenglich besass diese Klasse rein statisiche Methoden fuer die * Laengenvaliderung. Ab v0.3.1 kann sie auch anstelle eines * Pruefziffernverfahrens eingesetzt werden. * * @author oboehm * @since 0.2 (20.04.2017) */ open class LengthValidator<T : Serializable> @JvmOverloads constructor(private val min: Int, private val max: Int = Int.MAX_VALUE) : NoopVerfahren<T>() { /** * Liefert true zurueck, wenn der uebergebene Wert innerhalb der erlaubten * Laenge liegt. * * @param wert Fachwert oder gekapselter Wert * @return true oder false */ override fun isValid(wert: T): Boolean { val length = Objects.toString(wert, "").length return length >= min && length <= max } /** * Ueberprueft, ob der uebergebenen Werte innerhalb der min/max-Werte * liegt. * * @param wert zu ueberpruefender Wert * @return den ueberprueften Wert (zur Weiterverarbeitung) */ override fun validate(wert: T): T { if (!isValid(wert)) { throw InvalidLengthException(Objects.toString(wert), min, max) } return wert } companion object { val NOT_EMPTY_VALIDATOR: PruefzifferVerfahren<String> = LengthValidator(1) /** * Validiert die Laenge des uebergebenen Wertes. * * @param value zu pruefender Wert * @param expected erwartete Laenge * @return der gepruefte Wert (zur evtl. Weiterverarbeitung) */ fun validate(value: String, expected: Int): String { if (value.length != expected) { throw InvalidLengthException(value, expected) } return value } /** * Validiert die Laenge des uebergebenen Wertes. * * @param value zu pruefender Wert * @param min geforderte Minimal-Laenge * @param max Maximal-Laenge * @return der gepruefte Wert (zur evtl. Weiterverarbeitung) */ fun validate(value: String, min: Int, max: Int): String { if (min == max) { return validate(value, min) } if (value.length < min || value.length > max) { throw InvalidLengthException(value, min, max) } return value } /** * Verifziert die Laenge des uebergebenen Wertes. Im Gegensatz zur * [.validate]-Methode wird herbei eine * [IllegalArgumentException] geworfen. * * @param value zu pruefender Wert * @param min geforderte Minimal-Laenge * @param max Maximal-Laenge * @return der gepruefte Wert (zur evtl. Weiterverarbeitung) */ fun verify(value: String, min: Int, max: Int): String { return try { validate(value, min, max) } catch (ex: IllegalArgumentException) { throw LocalizedIllegalArgumentException(ex) } } } }
src/main/kotlin/de/jfachwert/pruefung/LengthValidator.kt
3234670091
/* * Created by Orchextra * * Copyright (C) 2017 Gigigo Mobile Services SL * * 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.gigigo.orchextra.core.data.datasources.network.models class ApiOxDevice( val instanceId: String, val secureId: String? = null, val serialNumber: String? = null, val bluetoothMacAddress: String? = null, val wifiMacAddress: String? = null, val clientApp: ApiClientApp? = null, val notificationPush: ApiNotificationPush? = null, val device: ApiDeviceInfo? = null, val tags: List<String>? = null, val businessUnits: List<String>? = null) class ApiDeviceInfo( val timeZone: String?, val osVersion: String?, val language: String?, val handset: String?, val type: String?) class ApiClientApp( val bundleId: String, val buildVersion: String, val appVersion: String, val sdkVersion: String, val sdkDevice: String) class ApiNotificationPush( val senderId: String = "DEPRECATED", val token: String)
core/src/main/java/com/gigigo/orchextra/core/data/datasources/network/models/ApiOxDevice.kt
715560992
package hypr.hypergan.com.hypr.ModelFragmnt import android.graphics.* import hypr.hypergan.com.hypr.Util.scaleBitmap class InlineImage{ var widthRatio: Float = 0.0f var heightRatio: Float = 0.0f var isOldCoppedImageBigger = false val paint = Paint() init{ paint.style = Paint.Style.STROKE paint.color = Color.RED } fun setBeforeAfterCropSizingRatio(oldCroppedImage: Bitmap, newCroppedImage: Bitmap){ if(oldCroppedImage.byteCount < newCroppedImage.byteCount){ isOldCoppedImageBigger = true widthRatio = newCroppedImage.width.toFloat() / oldCroppedImage.width.toFloat() heightRatio = newCroppedImage.height.toFloat() / oldCroppedImage.height.toFloat() }else{ widthRatio = oldCroppedImage.width.toFloat() / newCroppedImage.width.toFloat() heightRatio = oldCroppedImage.height.toFloat() / newCroppedImage.height.toFloat() } } fun inlineCroppedImageToFullImage(croppedImage: Bitmap, fullImage: Bitmap, croppedPoint: Rect): Bitmap { val mutableFullImage = fullImage.copy(Bitmap.Config.ARGB_8888, true) val scaledCroppedImage = croppedImage.scaleBitmap(croppedPoint.width(), croppedPoint.height()) insertCroppedImageWithinFullImage(mutableFullImage, scaledCroppedImage, croppedPoint) return mutableFullImage } private fun insertCroppedImageWithinFullImage(fullImageMutable: Bitmap, scaledCropped: Bitmap, croppedPoint: Rect): Bitmap { val fullImageCanvas = Canvas(fullImageMutable) fullImageCanvas.drawBitmap(scaledCropped, croppedPoint.left.toFloat(), croppedPoint.top.toFloat(), Paint()) return fullImageMutable } }
app/src/main/java/hypr/hypergan/com/hypr/ModelFragmnt/InlineImage.kt
2322212997
package com.github.ivan_osipov.clabo.api.model.inline_mode.contents import com.google.gson.annotations.SerializedName class InputContactMessageContent : InputMessageContent() { @SerializedName("phone_number") lateinit var phoneNumber: String @SerializedName("first_name") lateinit var firstName: String @SerializedName("last_name") var lastName: String? = null }
src/main/kotlin/com/github/ivan_osipov/clabo/api/model/inline_mode/contents/InputContactMessageContent.kt
3865296463
/* * Copyright 2019 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.example.filelocker import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
FileLocker/app/src/test/java/com/android/example/filelocker/ExampleUnitTest.kt
1795731023
package fr.bmartel.bboxapi.router.sample import com.github.kittinunf.result.Result import fr.bmartel.bboxapi.router.BboxApiRouter import fr.bmartel.bboxapi.router.model.MacFilterRule import java.util.concurrent.CountDownLatch fun main(args: Array<String>) { val bboxapi = BboxApiRouter() bboxapi.init() bboxapi.password = "admin" /** * Get wifi mac filter */ //asynchronous call var latch = CountDownLatch(1) bboxapi.getWifiMacFilter { _, _, result -> when (result) { is Result.Failure -> { val ex = result.getException() println(ex) } is Result.Success -> { val data = result.get() println(data) } } latch.countDown() } latch.await() //synchronous call val (_, _, wifiMacFilter) = bboxapi.getWifiMacFilterSync() when (wifiMacFilter) { is Result.Failure -> { val ex = wifiMacFilter.getException() println(ex) } is Result.Success -> { val data = wifiMacFilter.get() println(data) } } /** * enable/disable wifi mac filter */ //asynchronous call latch = CountDownLatch(1) bboxapi.setWifiMacFilter(state = false) { _, res, result -> when (result) { is Result.Failure -> { val ex = result.getException() println(ex) } is Result.Success -> { println("wifi mac filter enabled ${res.statusCode}") } } latch.countDown() } latch.await() //synchronous call val (_, res, stateResult) = bboxapi.setWifiMacFilterSync(state = false) when (stateResult) { is Result.Failure -> { val ex = stateResult.getException() println(ex) } is Result.Success -> { println("wifi mac filter enabled ${res.statusCode}") } } /** * delete wifi mac filter rules */ deleteAllRules(bboxapi = bboxapi, size = wifiMacFilter.get()[0].acl?.rules?.size ?: 0) showNewSize(bboxapi = bboxapi) /** * create wifi mac filter rule */ //asynchronous call val rule1 = MacFilterRule(enable = true, macaddress = "01:23:45:67:89:01", ip = "") latch = CountDownLatch(1) bboxapi.createMacFilterRule(rule = rule1) { _, res, result -> when (result) { is Result.Failure -> { val ex = result.getException() println(ex) } is Result.Success -> { println("create rule 1 ${res.statusCode}") } } latch.countDown() } latch.await() //synchronous call val rule2 = MacFilterRule(enable = true, macaddress = "34:56:78:90:12:34", ip = "") val (_, res2, createResult) = bboxapi.createMacFilterRuleSync(rule = rule2) when (createResult) { is Result.Failure -> { val ex = createResult.getException() println(ex) } is Result.Success -> { println("create rule 2 ${res2.statusCode}") } } showNewSize(bboxapi = bboxapi) /** * update rule */ //asynchronous call latch = CountDownLatch(1) bboxapi.updateMacFilterRule(ruleIndex = 1, rule = rule2) { _, res, result -> when (result) { is Result.Failure -> { val ex = result.getException() println(ex) } is Result.Success -> { println("updated rule 1 ${res.statusCode}") } } latch.countDown() } latch.await() //synchronous call val (_, res3, updateResult) = bboxapi.updateMacFilterRuleSync(ruleIndex = 2, rule = rule1) when (updateResult) { is Result.Failure -> { val ex = updateResult.getException() println(ex) } is Result.Success -> { println("updated rule 2 ${res3.statusCode}") } } showNewSize(bboxapi = bboxapi) deleteAllRules(bboxapi = bboxapi, size = 2) } fun showNewSize(bboxapi: BboxApiRouter) { val (_, _, wifiMacFilter2) = bboxapi.getWifiMacFilterSync() when (wifiMacFilter2) { is Result.Failure -> { val ex = wifiMacFilter2.getException() println(ex) } is Result.Success -> { println("new size : ${wifiMacFilter2.get()[0].acl?.rules?.size}") } } } fun deleteAllRules(bboxapi: BboxApiRouter, size: Int) { for (i in 1..size) { val (_, res, stateResult) = bboxapi.deleteMacFilterRuleSync(ruleIndex = i) when (stateResult) { is Result.Failure -> { val ex = stateResult.getException() println("failed to delete rule with id $i") println(ex) } is Result.Success -> { println("deleted rule with id $i") } } } }
sample/src/main/kotlin/fr/bmartel/bboxapi/router/sample/WifiMacFilter.kt
4093055446
package com.austinv11.planner.core.json.responses data class UserInfoResponse(var session: Long, var username: String, var email: String, var verified: Boolean, var plugins: Array<String>)
Core/src/main/kotlin/com/austinv11/planner/core/json/responses/UserInfoResponse.kt
1952758714
package com.sapuseven.untis.helpers.api import com.sapuseven.untis.R import com.sapuseven.untis.data.connectivity.UntisApiConstants import com.sapuseven.untis.data.connectivity.UntisAuthentication import com.sapuseven.untis.data.connectivity.UntisRequest import com.sapuseven.untis.helpers.ErrorMessageDictionary import com.sapuseven.untis.helpers.SerializationUtils import com.sapuseven.untis.models.UntisSchoolInfo import com.sapuseven.untis.models.untis.params.AppSharedSecretParams import com.sapuseven.untis.models.untis.params.SchoolSearchParams import com.sapuseven.untis.models.untis.params.UserDataParams import com.sapuseven.untis.models.untis.response.AppSharedSecretResponse import com.sapuseven.untis.models.untis.response.SchoolSearchResponse import com.sapuseven.untis.models.untis.response.UserDataResponse import com.sapuseven.untis.models.untis.response.UserDataResult import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.SerializationException import kotlinx.serialization.decodeFromString import java.net.UnknownHostException class LoginHelper( val loginData: LoginDataInfo, val onStatusUpdate: (statusStringRes: Int) -> Unit, val onError: (error: LoginErrorInfo) -> Unit ) { private val api: UntisRequest = UntisRequest() private val proxyHost: String? = null // TODO: Pass proxy host init { onStatusUpdate(R.string.logindatainput_connecting) } @ExperimentalSerializationApi suspend fun loadSchoolInfo(school: String): UntisSchoolInfo? { onStatusUpdate(R.string.logindatainput_aquiring_schoolid) val schoolId = school.toIntOrNull() val query = UntisRequest.UntisRequestQuery() query.data.method = UntisApiConstants.METHOD_SEARCH_SCHOOLS query.url = UntisApiConstants.SCHOOL_SEARCH_URL query.proxyHost = proxyHost query.data.params = if (schoolId != null) listOf(SchoolSearchParams(schoolid = schoolId)) else listOf(SchoolSearchParams(search = school)) val result = api.request(query) result.fold({ data -> try { val untisResponse = SerializationUtils.getJSON().decodeFromString<SchoolSearchResponse>(data) untisResponse.result?.let { if (it.schools.isNotEmpty()) { val schoolResult = it.schools.find { schoolInfoResult -> schoolInfoResult.schoolId == schoolId || schoolInfoResult.loginName.equals( school, true ) } // TODO: Show manual selection dialog when there are more than one results are returned if (schoolResult != null) return schoolResult } onError(LoginErrorInfo(errorMessageStringRes = R.string.logindatainput_error_invalid_school)) } ?: run { onError( LoginErrorInfo( errorCode = untisResponse.error?.code, errorMessage = untisResponse.error?.message ) ) } } catch (e: SerializationException) { onError( LoginErrorInfo( errorMessageStringRes = R.string.logindatainput_error_generic, errorMessage = e.message ) ) } }, { error -> onError( LoginErrorInfo( errorMessageStringRes = R.string.logindatainput_error_generic, errorMessage = error.message ) ) }) return null } suspend fun loadAppSharedSecret(apiUrl: String): String? { onStatusUpdate(R.string.logindatainput_aquiring_app_secret) val query = UntisRequest.UntisRequestQuery() query.url = apiUrl query.proxyHost = proxyHost query.data.method = UntisApiConstants.METHOD_GET_APP_SHARED_SECRET query.data.params = listOf(AppSharedSecretParams(loginData.user, loginData.password)) val appSharedSecretResult = api.request(query) appSharedSecretResult.fold({ data -> try { val untisResponse = SerializationUtils.getJSON().decodeFromString<AppSharedSecretResponse>(data) if (untisResponse.error?.code == ErrorMessageDictionary.ERROR_CODE_INVALID_CREDENTIALS) return loginData.password if (untisResponse.result.isNullOrEmpty()) onError( LoginErrorInfo( errorCode = untisResponse.error?.code, errorMessage = untisResponse.error?.message ) ) else return untisResponse.result } catch (e: SerializationException) { onError( LoginErrorInfo( errorMessageStringRes = R.string.logindatainput_error_generic, errorMessage = e.message ) ) } }, { error -> when (error.exception) { is UnknownHostException -> onError(LoginErrorInfo(errorCode = ErrorMessageDictionary.ERROR_CODE_NO_SERVER_FOUND)) else -> onError( LoginErrorInfo( errorMessageStringRes = R.string.logindatainput_error_generic, errorMessage = error.message ) ) } }) return null } suspend fun loadUserData(apiUrl: String, key: String?): UserDataResult? { onStatusUpdate(R.string.logindatainput_loading_user_data) val query = UntisRequest.UntisRequestQuery() query.url = apiUrl query.proxyHost = proxyHost query.data.method = UntisApiConstants.METHOD_GET_USER_DATA if (loginData.anonymous) query.data.params = listOf(UserDataParams(auth = UntisAuthentication.createAuthObject())) else { if (key == null) return null query.data.params = listOf( UserDataParams( auth = UntisAuthentication.createAuthObject( loginData.user, key ) ) ) } val userDataResult = api.request(query) userDataResult.fold({ data -> try { val untisResponse = SerializationUtils.getJSON().decodeFromString<UserDataResponse>(data) if (untisResponse.result != null) { return untisResponse.result } else { onError( LoginErrorInfo( errorCode = untisResponse.error?.code, errorMessage = untisResponse.error?.message ) ) } } catch (e: SerializationException) { onError( LoginErrorInfo( errorMessageStringRes = R.string.logindatainput_error_generic, errorMessage = e.message ) ) } }, { error -> onError( LoginErrorInfo( errorMessageStringRes = R.string.logindatainput_error_generic, errorMessage = error.message ) ) }) return null } }
app/src/main/java/com/sapuseven/untis/helpers/api/LoginHelper.kt
1395686079
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <[email protected]> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.provider import android.content.ContentProvider import android.content.ContentValues import android.content.SharedPreferences import android.database.Cursor import android.database.MatrixCursor import android.database.SQLException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteFullException import android.net.Uri import android.os.Handler import android.os.Looper import android.support.v4.text.BidiFormatter import com.squareup.otto.Bus import okhttp3.Dns import org.mariotaku.ktextension.isNullOrEmpty import org.mariotaku.ktextension.toNulls import org.mariotaku.sqliteqb.library.Columns.Column import org.mariotaku.sqliteqb.library.Expression import org.mariotaku.sqliteqb.library.RawItemArray import de.vanita5.twittnuker.TwittnukerConstants.* import de.vanita5.twittnuker.annotation.ReadPositionTag import de.vanita5.twittnuker.app.TwittnukerApplication import de.vanita5.twittnuker.extension.withAppendedPath import de.vanita5.twittnuker.model.AccountPreferences import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.event.UnreadCountUpdatedEvent import de.vanita5.twittnuker.provider.TwidereDataStore.* import de.vanita5.twittnuker.util.* import de.vanita5.twittnuker.util.SQLiteDatabaseWrapper.LazyLoadCallback import de.vanita5.twittnuker.util.dagger.GeneralComponent import de.vanita5.twittnuker.util.database.CachedUsersQueryBuilder import de.vanita5.twittnuker.util.database.SuggestionsCursorCreator import de.vanita5.twittnuker.util.notification.ContentNotificationManager import java.util.concurrent.Executor import java.util.concurrent.Executors import javax.inject.Inject class TwidereDataProvider : ContentProvider(), LazyLoadCallback { @Inject lateinit internal var readStateManager: ReadStateManager @Inject lateinit internal var twitterWrapper: AsyncTwitterWrapper @Inject lateinit internal var notificationManager: NotificationManagerWrapper @Inject lateinit internal var preferences: SharedPreferences @Inject lateinit internal var dns: Dns @Inject lateinit internal var bus: Bus @Inject lateinit internal var userColorNameManager: UserColorNameManager @Inject lateinit internal var bidiFormatter: BidiFormatter @Inject lateinit internal var contentNotificationManager: ContentNotificationManager private lateinit var databaseWrapper: SQLiteDatabaseWrapper private lateinit var backgroundExecutor: Executor private lateinit var handler: Handler override fun onCreate(): Boolean { val context = context!! GeneralComponent.get(context).inject(this) handler = Handler(Looper.getMainLooper()) databaseWrapper = SQLiteDatabaseWrapper(this) backgroundExecutor = Executors.newSingleThreadExecutor() // final GetWritableDatabaseTask task = new // GetWritableDatabaseTask(context, helper, mDatabaseWrapper); // task.executeTask(); return true } override fun onCreateSQLiteDatabase(): SQLiteDatabase { val app = TwittnukerApplication.getInstance(context!!) val helper = app.sqLiteOpenHelper return helper.writableDatabase } override fun insert(uri: Uri, values: ContentValues?): Uri? { try { return insertInternal(uri, values) } catch (e: SQLException) { if (handleSQLException(e)) { try { return insertInternal(uri, values) } catch (e1: SQLException) { throw IllegalStateException(e1) } } throw IllegalStateException(e) } } override fun bulkInsert(uri: Uri, valuesArray: Array<ContentValues>): Int { try { return bulkInsertInternal(uri, valuesArray) } catch (e: SQLException) { if (handleSQLException(e)) { try { return bulkInsertInternal(uri, valuesArray) } catch (e1: SQLException) { throw IllegalStateException(e1) } } throw IllegalStateException(e) } } override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? { try { val tableId = DataStoreUtils.getTableId(uri) val table = DataStoreUtils.getTableNameById(tableId) when (tableId) { VIRTUAL_TABLE_ID_DATABASE_PREPARE -> { databaseWrapper.prepare() return MatrixCursor(projection ?: arrayOfNulls<String>(0)) } VIRTUAL_TABLE_ID_CACHED_USERS_WITH_RELATIONSHIP -> { val accountKey = UserKey.valueOf(uri.lastPathSegment) val accountHost = uri.getQueryParameter(EXTRA_ACCOUNT_HOST) val accountType = uri.getQueryParameter(EXTRA_ACCOUNT_TYPE) val query = CachedUsersQueryBuilder.withRelationship(projection, Expression(selection), selectionArgs, sortOrder, accountKey, accountHost, accountType) val c = databaseWrapper.rawQuery(query.first.sql, query.second) c?.setNotificationUri(context.contentResolver, CachedUsers.CONTENT_URI) return c } VIRTUAL_TABLE_ID_CACHED_USERS_WITH_SCORE -> { val accountKey = UserKey.valueOf(uri.lastPathSegment) val accountHost = uri.getQueryParameter(EXTRA_ACCOUNT_HOST) val accountType = uri.getQueryParameter(EXTRA_ACCOUNT_TYPE) val query = CachedUsersQueryBuilder.withScore(projection, Expression(selection), selectionArgs, sortOrder, accountKey, accountHost, accountType, 0) val c = databaseWrapper.rawQuery(query.first.sql, query.second) c?.setNotificationUri(context.contentResolver, CachedUsers.CONTENT_URI) return c } VIRTUAL_TABLE_ID_DRAFTS_UNSENT -> { val twitter = twitterWrapper val sendingIds = RawItemArray(twitter.getSendingDraftIds()) val where: Expression if (selection != null) { where = Expression.and(Expression(selection), Expression.notIn(Column(Drafts._ID), sendingIds)) } else { where = Expression.and(Expression.notIn(Column(Drafts._ID), sendingIds)) } val c = databaseWrapper.query(Drafts.TABLE_NAME, projection, where.sql, selectionArgs, null, null, sortOrder) c?.setNotificationUri(context.contentResolver, uri) return c } VIRTUAL_TABLE_ID_SUGGESTIONS_AUTO_COMPLETE -> { return SuggestionsCursorCreator.forAutoComplete(databaseWrapper, userColorNameManager, uri, projection) } VIRTUAL_TABLE_ID_SUGGESTIONS_SEARCH -> { return SuggestionsCursorCreator.forSearch(databaseWrapper, userColorNameManager, uri, projection) } VIRTUAL_TABLE_ID_NULL -> { return null } VIRTUAL_TABLE_ID_EMPTY -> { return MatrixCursor(projection ?: arrayOfNulls<String>(0)) } VIRTUAL_TABLE_ID_RAW_QUERY -> { if (projection != null || selection != null || sortOrder != null) { throw IllegalArgumentException() } val c = databaseWrapper.rawQuery(uri.lastPathSegment, selectionArgs) uri.getQueryParameter(QUERY_PARAM_NOTIFY_URI)?.let { c?.setNotificationUri(context.contentResolver, Uri.parse(it)) } return c } } if (table == null) return null val limit = uri.getQueryParameter(QUERY_PARAM_LIMIT) val c = databaseWrapper.query(table, projection, selection, selectionArgs, null, null, sortOrder, limit) c?.setNotificationUri(context.contentResolver, uri) return c } catch (e: SQLException) { throw IllegalStateException(e) } } override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { try { return updateInternal(uri, values, selection, selectionArgs) } catch (e: SQLException) { if (handleSQLException(e)) { try { return updateInternal(uri, values, selection, selectionArgs) } catch (e1: SQLException) { throw IllegalStateException(e1) } } throw IllegalStateException(e) } } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { try { return deleteInternal(uri, selection, selectionArgs) } catch (e: SQLException) { if (handleSQLException(e)) { try { return deleteInternal(uri, selection, selectionArgs) } catch (e1: SQLException) { throw IllegalStateException(e1) } } throw IllegalStateException(e) } } override fun getType(uri: Uri): String? { return null } private fun handleSQLException(e: SQLException): Boolean { try { if (e is SQLiteFullException) { // Drop cached databases databaseWrapper.delete(CachedUsers.TABLE_NAME, null, null) databaseWrapper.delete(CachedStatuses.TABLE_NAME, null, null) databaseWrapper.delete(CachedHashtags.TABLE_NAME, null, null) databaseWrapper.execSQL("VACUUM") return true } } catch (ee: SQLException) { throw IllegalStateException(ee) } throw IllegalStateException(e) } private fun bulkInsertInternal(uri: Uri, valuesArray: Array<ContentValues>): Int { val tableId = DataStoreUtils.getTableId(uri) val table = DataStoreUtils.getTableNameById(tableId) var result = 0 val newIds = LongArray(valuesArray.size) if (table != null && valuesArray.isNotEmpty()) { databaseWrapper.beginTransaction() if (tableId == TABLE_ID_CACHED_USERS) { for (values in valuesArray) { val where = Expression.equalsArgs(CachedUsers.USER_KEY) databaseWrapper.update(table, values, where.sql, arrayOf(values.getAsString(CachedUsers.USER_KEY))) newIds[result++] = databaseWrapper.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE) } } else if (tableId == TABLE_ID_SEARCH_HISTORY) { for (values in valuesArray) { values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis()) val where = Expression.equalsArgs(SearchHistory.QUERY) val args = arrayOf(values.getAsString(SearchHistory.QUERY)) databaseWrapper.update(table, values, where.sql, args) newIds[result++] = databaseWrapper.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_IGNORE) } } else { val conflictAlgorithm = getConflictAlgorithm(tableId) if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) { for (values in valuesArray) { newIds[result++] = databaseWrapper.insertWithOnConflict(table, null, values, conflictAlgorithm) } } else { for (values in valuesArray) { newIds[result++] = databaseWrapper.insert(table, null, values) } } } databaseWrapper.setTransactionSuccessful() databaseWrapper.endTransaction() } if (result > 0) { onDatabaseUpdated(tableId, uri) } onNewItemsInserted(uri, tableId, valuesArray.toNulls()) return result } private fun deleteInternal(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { val tableId = DataStoreUtils.getTableId(uri) when (tableId) { VIRTUAL_TABLE_ID_DRAFTS_NOTIFICATIONS -> { notificationManager.cancel(uri.toString(), NOTIFICATION_ID_DRAFTS) return 1 } else -> { val table = DataStoreUtils.getTableNameById(tableId) ?: return 0 val result = databaseWrapper.delete(table, selection, selectionArgs) if (result > 0) { onDatabaseUpdated(tableId, uri) } onItemDeleted(uri, tableId) return result } } } private fun insertInternal(uri: Uri, values: ContentValues?): Uri? { val tableId = DataStoreUtils.getTableId(uri) val table = DataStoreUtils.getTableNameById(tableId) var rowId: Long = -1 when (tableId) { TABLE_ID_CACHED_USERS -> { if (values != null) { val where = Expression.equalsArgs(CachedUsers.USER_KEY) val whereArgs = arrayOf(values.getAsString(CachedUsers.USER_KEY)) databaseWrapper.update(table, values, where.sql, whereArgs) } rowId = databaseWrapper.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_IGNORE) } TABLE_ID_SEARCH_HISTORY -> { if (values != null) { values.put(SearchHistory.RECENT_QUERY, System.currentTimeMillis()) val where = Expression.equalsArgs(SearchHistory.QUERY) val args = arrayOf(values.getAsString(SearchHistory.QUERY)) databaseWrapper.update(table, values, where.sql, args) } rowId = databaseWrapper.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_IGNORE) } TABLE_ID_CACHED_RELATIONSHIPS -> { var updated = false if (values != null) { val accountKey = values.getAsString(CachedRelationships.ACCOUNT_KEY) val userKey = values.getAsString(CachedRelationships.USER_KEY) val where = Expression.and(Expression.equalsArgs(CachedRelationships.ACCOUNT_KEY), Expression.equalsArgs(CachedRelationships.USER_KEY)) if (databaseWrapper.update(table, values, where.sql, arrayOf(accountKey, userKey)) > 0) { val projection = arrayOf(CachedRelationships._ID) val c = databaseWrapper.query(table, projection, where.sql, null, null, null, null) if (c.moveToFirst()) { rowId = c.getLong(0) } c.close() updated = true } } if (!updated) { rowId = databaseWrapper.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_IGNORE) } } VIRTUAL_TABLE_ID_DRAFTS_NOTIFICATIONS -> { rowId = contentNotificationManager.showDraft(uri) } else -> { val conflictAlgorithm = getConflictAlgorithm(tableId) if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) { rowId = databaseWrapper.insertWithOnConflict(table, null, values, conflictAlgorithm) } else if (table != null) { rowId = databaseWrapper.insert(table, null, values) } else { return null } } } onDatabaseUpdated(tableId, uri) onNewItemsInserted(uri, tableId, arrayOf(values)) return uri.withAppendedPath(rowId.toString()) } private fun updateInternal(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int { val tableId = DataStoreUtils.getTableId(uri) val table = DataStoreUtils.getTableNameById(tableId) var result = 0 if (table != null) { result = databaseWrapper.update(table, values, selection, selectionArgs) } if (result > 0) { onDatabaseUpdated(tableId, uri) } return result } private fun notifyContentObserver(uri: Uri) { if (!uri.getBooleanQueryParameter(QUERY_PARAM_NOTIFY_CHANGE, true)) return handler.post { context?.contentResolver?.notifyChange(uri, null) } } private fun notifyUnreadCountChanged(position: Int) { handler.post { bus.post(UnreadCountUpdatedEvent(position)) } } private fun onDatabaseUpdated(tableId: Int, uri: Uri?) { if (uri == null) return notifyContentObserver(uri) } private fun onItemDeleted(uri: Uri, tableId: Int) { } private fun onNewItemsInserted(uri: Uri, tableId: Int, valuesArray: Array<ContentValues?>?) { val context = context ?: return if (valuesArray.isNullOrEmpty()) return when (tableId) { // TABLE_ID_STATUSES -> { // if (!uri.getBooleanQueryParameter(QUERY_PARAM_SHOW_NOTIFICATION, true)) return // backgroundExecutor.execute { // val prefs = AccountPreferences.getAccountPreferences(context, preferences, // DataStoreUtils.getAccountKeys(context)) // prefs.filter { it.isNotificationEnabled && it.isHomeTimelineNotificationEnabled }.forEach { // val positionTag = getPositionTag(CustomTabType.HOME_TIMELINE, it.accountKey) // contentNotificationManager.showTimeline(it, positionTag) // } // notifyUnreadCountChanged(NOTIFICATION_ID_HOME_TIMELINE) // } // } TABLE_ID_ACTIVITIES_ABOUT_ME -> { if (!uri.getBooleanQueryParameter(QUERY_PARAM_SHOW_NOTIFICATION, true)) return backgroundExecutor.execute { val prefs = AccountPreferences.getAccountPreferences(context, preferences, DataStoreUtils.getAccountKeys(context)) prefs.filter { it.isNotificationEnabled && it.isInteractionsNotificationEnabled }.forEach { val positionTag = getPositionTag(ReadPositionTag.ACTIVITIES_ABOUT_ME, it.accountKey) contentNotificationManager.showInteractions(it, positionTag) } notifyUnreadCountChanged(NOTIFICATION_ID_INTERACTIONS_TIMELINE) } } TABLE_ID_MESSAGES_CONVERSATIONS -> { if (!uri.getBooleanQueryParameter(QUERY_PARAM_SHOW_NOTIFICATION, true)) return backgroundExecutor.execute { val prefs = AccountPreferences.getAccountPreferences(context, preferences, DataStoreUtils.getAccountKeys(context)) prefs.filter { it.isNotificationEnabled && it.isDirectMessagesNotificationEnabled }.forEach { contentNotificationManager.showMessages(it) } notifyUnreadCountChanged(NOTIFICATION_ID_DIRECT_MESSAGES) } } TABLE_ID_DRAFTS -> { } } } private fun getPositionTag(tag: String, accountKey: UserKey): Long { val position = readStateManager.getPosition(Utils.getReadPositionTagWithAccount(tag, accountKey)) if (position != -1L) return position return readStateManager.getPosition(tag) } companion object { private fun getConflictAlgorithm(tableId: Int): Int { when (tableId) { TABLE_ID_CACHED_HASHTAGS, TABLE_ID_CACHED_STATUSES, TABLE_ID_CACHED_USERS, TABLE_ID_CACHED_RELATIONSHIPS, TABLE_ID_SEARCH_HISTORY, TABLE_ID_MESSAGES, TABLE_ID_MESSAGES_CONVERSATIONS -> { return SQLiteDatabase.CONFLICT_REPLACE } TABLE_ID_FILTERED_USERS, TABLE_ID_FILTERED_KEYWORDS, TABLE_ID_FILTERED_SOURCES, TABLE_ID_FILTERED_LINKS -> { return SQLiteDatabase.CONFLICT_IGNORE } } return SQLiteDatabase.CONFLICT_NONE } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/provider/TwidereDataProvider.kt
1712563311
package org.softeg.slartus.forpdaplus.fragments.topic.editpost import android.content.Context import org.softeg.slartus.forpdaapi.post.EditAttach import org.softeg.slartus.forpdaapi.post.EditPost interface EditPostFragmentListener { fun getContext(): Context? fun onLoadTaskSuccess(editPost: EditPost?) fun onUpdateTaskSuccess(editAttach: EditAttach?) fun onDeleteAttachTaskSuccess(attachId:String) fun onAcceptEditTaskSuccess(editPost:EditPost?) fun onPostTaskSuccess(editPost:EditPost?, error:String?) }
app/src/main/java/org/softeg/slartus/forpdaplus/fragments/topic/editpost/EditPostFragmentListener.kt
2309713986
package com.github.kotlinz.kotlinz.type.monad import com.github.kotlinz.kotlinz.K1 interface MonadZip<T>: Monad<T> { fun <A, B> mzip(m1: K1<T, A>, m2: K1<T, B>): K1<T, Pair<A, B>> fun <A, B, C> mzipWith(m1: K1<T, A>, m2: K1<T, B>, f: (A, B) -> C): K1<T, C> fun <A, B> munzip(m : K1<T, Pair<A, B>>): Pair<K1<T, A>, K1<T, B>> }
src/main/kotlin/com/github/kotlinz/kotlinz/type/monad/MonadZip.kt
3756457474
package sample.library import com.jaynewstrom.composite.runtime.LibraryModule @LibraryModule(NavigationRegistrable::class) class NavigationFooLibraryModule : NavigationRegistrable { override fun name(): String { return "Foo" } override fun action(): () -> Unit { return { System.out.println("Foo!") } } }
integration-test-library-kotlin/src/main/kotlin/sample/library/NavigationFooLibraryModule.kt
925352634
package com.bl_lia.kirakiratter.domain.entity.realm import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import java.util.* open class RealmTimeline( @PrimaryKey open var scope: String = "", open var statusList: RealmList<RealmStatus> = RealmList(), open var created: Date = Date() ): RealmObject()
app/src/main/kotlin/com/bl_lia/kirakiratter/domain/entity/realm/RealmTimeline.kt
3792377957
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.compiler.plugins.kotlin.lower import androidx.compose.compiler.plugins.kotlin.ComposeClassIds import androidx.compose.compiler.plugins.kotlin.ComposeFqNames import androidx.compose.compiler.plugins.kotlin.KtxNameConventions import androidx.compose.compiler.plugins.kotlin.ModuleMetrics import androidx.compose.compiler.plugins.kotlin.analysis.ComposeWritableSlices import androidx.compose.compiler.plugins.kotlin.inference.ApplierInferencer import androidx.compose.compiler.plugins.kotlin.inference.ErrorReporter import androidx.compose.compiler.plugins.kotlin.inference.TypeAdapter import androidx.compose.compiler.plugins.kotlin.inference.Item import androidx.compose.compiler.plugins.kotlin.inference.LazyScheme import androidx.compose.compiler.plugins.kotlin.inference.LazySchemeStorage import androidx.compose.compiler.plugins.kotlin.inference.NodeAdapter import androidx.compose.compiler.plugins.kotlin.inference.NodeKind import androidx.compose.compiler.plugins.kotlin.inference.Open import androidx.compose.compiler.plugins.kotlin.inference.Scheme import androidx.compose.compiler.plugins.kotlin.inference.Token import androidx.compose.compiler.plugins.kotlin.inference.deserializeScheme import androidx.compose.compiler.plugins.kotlin.irTrace import androidx.compose.compiler.plugins.kotlin.mergeWith import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext import org.jetbrains.kotlin.descriptors.ClassKind import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET import org.jetbrains.kotlin.ir.declarations.IrFile import org.jetbrains.kotlin.ir.declarations.IrFunction import org.jetbrains.kotlin.ir.declarations.IrLocalDelegatedProperty import org.jetbrains.kotlin.ir.declarations.IrModuleFragment import org.jetbrains.kotlin.ir.declarations.IrSimpleFunction import org.jetbrains.kotlin.ir.declarations.IrValueParameter import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.declarations.name import org.jetbrains.kotlin.ir.expressions.IrBlock import org.jetbrains.kotlin.ir.expressions.IrBody import org.jetbrains.kotlin.ir.expressions.IrCall import org.jetbrains.kotlin.ir.expressions.IrConst import org.jetbrains.kotlin.ir.expressions.IrConstructorCall import org.jetbrains.kotlin.ir.expressions.IrContainerExpression import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrFunctionExpression import org.jetbrains.kotlin.ir.expressions.IrGetField import org.jetbrains.kotlin.ir.expressions.IrGetValue import org.jetbrains.kotlin.ir.expressions.IrReturn import org.jetbrains.kotlin.ir.expressions.IrStatementOrigin import org.jetbrains.kotlin.ir.expressions.IrTypeOperatorCall import org.jetbrains.kotlin.ir.expressions.impl.IrConstructorCallImpl import org.jetbrains.kotlin.ir.interpreter.getLastOverridden import org.jetbrains.kotlin.ir.symbols.IrClassSymbol import org.jetbrains.kotlin.ir.symbols.IrSimpleFunctionSymbol import org.jetbrains.kotlin.ir.symbols.IrSymbol import org.jetbrains.kotlin.ir.types.IrSimpleType import org.jetbrains.kotlin.ir.types.IrType import org.jetbrains.kotlin.ir.types.IrTypeArgument import org.jetbrains.kotlin.ir.types.IrTypeProjection import org.jetbrains.kotlin.ir.types.classFqName import org.jetbrains.kotlin.ir.types.classOrNull import org.jetbrains.kotlin.ir.types.defaultType import org.jetbrains.kotlin.ir.types.impl.buildSimpleType import org.jetbrains.kotlin.ir.types.impl.toBuilder import org.jetbrains.kotlin.ir.types.isAny import org.jetbrains.kotlin.ir.types.isClassWithFqName import org.jetbrains.kotlin.ir.types.isNullableAny import org.jetbrains.kotlin.ir.types.typeOrNull import org.jetbrains.kotlin.ir.util.constructors import org.jetbrains.kotlin.ir.util.dump import org.jetbrains.kotlin.ir.util.file import org.jetbrains.kotlin.ir.util.fqNameWhenAvailable import org.jetbrains.kotlin.ir.util.functions import org.jetbrains.kotlin.ir.util.hasAnnotation import org.jetbrains.kotlin.ir.util.isFunction import org.jetbrains.kotlin.ir.util.isNullConst import org.jetbrains.kotlin.ir.util.isTypeParameter import org.jetbrains.kotlin.ir.util.parentAsClass import org.jetbrains.kotlin.ir.util.statements import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid /** * This transformer walks the IR tree to infer the applier annotations such as ComposableTarget, * ComposableOpenTarget, and */ class ComposableTargetAnnotationsTransformer( context: IrPluginContext, symbolRemapper: ComposableSymbolRemapper, metrics: ModuleMetrics ) : AbstractComposeLowering(context, symbolRemapper, metrics) { private val ComposableTargetClass = symbolRemapper.getReferencedClassOrNull( getTopLevelClassOrNull(ComposeClassIds.ComposableTarget) ) private val ComposableOpenTargetClass = symbolRemapper.getReferencedClassOrNull( getTopLevelClassOrNull(ComposeClassIds.ComposableOpenTarget) ) private val ComposableInferredTargetClass = symbolRemapper.getReferencedClassOrNull( getTopLevelClassOrNull(ComposeClassIds.ComposableInferredTarget) ) /** * A map of element to the owning function of the element. */ private val ownerMap = mutableMapOf<IrElement, IrFunction>() /** * Map of a parameter symbol to its function and parameter index. */ private val parameterOwners = mutableMapOf<IrSymbol, Pair<IrFunction, Int>>() /** * A map of variables to their corresponding inference node. */ private val variableDeclarations = mutableMapOf<IrSymbol, InferenceVariable>() private var currentOwner: IrFunction? = null private var currentFile: IrFile? = null private val transformer get() = this private fun lineInfoOf(element: IrElement?): String { val file = currentFile if (element != null && file != null) { return " ${file.name}:${ file.fileEntry.getLineNumber(element.startOffset) + 1 }:${ file.fileEntry.getColumnNumber(element.startOffset) + 1 }" } return "" } private val infer = ApplierInferencer( typeAdapter = object : TypeAdapter<InferenceFunction> { val current = mutableMapOf<InferenceFunction, Scheme>() override fun declaredSchemaOf(type: InferenceFunction): Scheme = type.toDeclaredScheme().also { type.recordScheme(it) } override fun currentInferredSchemeOf(type: InferenceFunction): Scheme? = if (type.schemeIsUpdatable) current[type] ?: declaredSchemaOf(type) else null override fun updatedInferredScheme(type: InferenceFunction, scheme: Scheme) { type.recordScheme(scheme) type.updateScheme(scheme) current[type] = scheme } }, nodeAdapter = object : NodeAdapter<InferenceFunction, InferenceNode> { override fun containerOf(node: InferenceNode): InferenceNode = ownerMap[node.element]?.let { inferenceNodeOf(it, transformer) } ?: (node as? InferenceResolvedParameter)?.referenceContainer ?: node override fun kindOf(node: InferenceNode): NodeKind = node.kind override fun schemeParameterIndexOf( node: InferenceNode, container: InferenceNode ): Int = node.parameterIndex(container) override fun typeOf(node: InferenceNode): InferenceFunction? = node.function override fun referencedContainerOf(node: InferenceNode): InferenceNode? = node.referenceContainer }, lazySchemeStorage = object : LazySchemeStorage<InferenceNode> { // The transformer is transitory so we can just store this in a map. val map = mutableMapOf<InferenceNode, LazyScheme>() override fun getLazyScheme(node: InferenceNode): LazyScheme? = map[node] override fun storeLazyScheme(node: InferenceNode, value: LazyScheme) { map[node] = value } }, errorReporter = object : ErrorReporter<InferenceNode> { override fun reportCallError(node: InferenceNode, expected: String, received: String) { // Ignored, should be reported by the front-end } override fun reportParameterError( node: InferenceNode, index: Int, expected: String, received: String ) { // Ignored, should be reported by the front-end } override fun log(node: InferenceNode?, message: String) { val element = node?.element if (!metrics.isEmpty) metrics.log("applier inference${lineInfoOf(element)}: $message") } } ) override fun lower(module: IrModuleFragment) { // Only transform if the attributes being inferred are in the runtime if ( ComposableTargetClass != null && ComposableInferredTargetClass != null && ComposableOpenTargetClass != null ) { module.transformChildrenVoid(this) } } override fun visitFile(declaration: IrFile): IrFile { includeFileNameInExceptionTrace(declaration) { currentFile = declaration return super.visitFile(declaration).also { currentFile = null } } } override fun visitFunction(declaration: IrFunction): IrStatement { if ( declaration.hasSchemeSpecified() || (!declaration.isComposable && !declaration.hasComposableParameter()) || declaration.hasOverlyWideParameters() || declaration.hasOpenTypeParameters() ) { return super.visitFunction(declaration) } val oldOwner = currentOwner currentOwner = declaration var currentParameter = 0 fun recordParameter(parameter: IrValueParameter) { if (parameter.type.isOrHasComposableLambda) { parameterOwners[parameter.symbol] = declaration to currentParameter++ } } declaration.valueParameters.forEach { recordParameter(it) } declaration.extensionReceiverParameter?.let { recordParameter(it) } val result = super.visitFunction(declaration) currentOwner = oldOwner return result } override fun visitVariable(declaration: IrVariable): IrStatement { if (declaration.type.isOrHasComposableLambda) { currentOwner?.let { ownerMap[declaration] = it } val initializerNode = declaration.initializer if (initializerNode != null) { val initializer = resolveExpressionOrNull(initializerNode) ?: InferenceElementExpression(transformer, initializerNode) val variable = InferenceVariable(this, declaration) variableDeclarations[declaration.symbol] = variable infer.visitVariable(variable, initializer) } } return super.visitVariable(declaration) } override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty): IrStatement { val result = super.visitLocalDelegatedProperty(declaration) if (declaration.type.isOrHasComposableLambda) { // Find the inference variable for the delegate which should have been created // when visiting the delegate node. If not, then ignore this declaration val variable = variableDeclarations[declaration.delegate.symbol] ?: return result // Allow the variable to be found from the getter as this is what is used to access // the variable, not the delegate directly. variableDeclarations[declaration.getter.symbol] = variable } return result } override fun visitCall(expression: IrCall): IrExpression { val owner = currentOwner if ( owner == null || ( !expression.isTransformedComposableCall() && !expression.hasComposableArguments() ) || when (expression.symbol.owner.fqNameWhenAvailable) { ComposeFqNames.getCurrentComposerFullName, ComposeFqNames.composableLambdaFullName -> true else -> false } ) { return super.visitCall(expression) } ownerMap[expression] = owner val result = super.visitCall(expression) val target = ( if ( expression.isInvoke() || expression.dispatchReceiver?.type?.isSamComposable == true ) { expression.dispatchReceiver?.let { resolveExpressionOrNull(it) } } else resolveExpressionOrNull(expression) ) ?: InferenceCallTargetNode(this, expression) if (target.isOverlyWide()) return result val arguments = expression.arguments.filterIndexed { index, argument -> argument?.let { it.isComposableLambda || it.isComposableParameter || ( if ( // There are three cases where the expression type is not good enough here, // one, the type is a default parameter and there is no actual expression // and, two, when the expression is a SAM conversion where the type is // too specific (it is the class) and we need the SAM interface, and three // the value is null for a nullable type. ( argument is IrContainerExpression && argument.origin == IrStatementOrigin.DEFAULT_VALUE ) || ( argument is IrBlock ) || ( argument.isNullConst() ) ) { // If the parameter is a default value, grab the type from the function // being called. expression.symbol.owner.valueParameters.let { parameters -> if (index < parameters.size) parameters[index].type else null } } else it.type)?.isOrHasComposableLambda == true } == true }.filterNotNull().toMutableList() fun recordArgument(argument: IrExpression?) { if ( argument != null && ( argument.isComposableLambda || argument.isComposableParameter || argument.type.isOrHasComposableLambda ) ) { arguments.add(argument) } } recordArgument(expression.extensionReceiver) infer.visitCall( call = inferenceNodeOf(expression, transformer), target = target, arguments = arguments.map { resolveExpressionOrNull(it) ?: inferenceNodeOf(it, transformer) } ) return result } private fun inferenceParameterOrNull(getValue: IrGetValue): InferenceResolvedParameter? = parameterOwners[getValue.symbol]?.let { InferenceResolvedParameter( getValue, inferenceFunctionOf(it.first), inferenceNodeOf(it.first, this), it.second ) } /** * Resolve references to local variables and parameters. */ private fun resolveExpressionOrNull(expression: IrElement?): InferenceNode? = when (expression) { is IrGetValue -> // Get the inference node for referencing a local variable or parameter if this // expression does. inferenceParameterOrNull(expression) ?: variableDeclarations[expression.symbol] is IrCall -> // If this call is a call to the getter of a local delegate get the inference // node of the delegate. variableDeclarations[expression.symbol] else -> null } val List<IrConstructorCall>.target: Item get() = firstOrNull { it.isComposableTarget }?.let { constructor -> constructor.firstParameterOrNull<String>()?.let { Token(it) } } ?: firstOrNull { it.isComposableOpenTarget }?.let { constructor -> constructor.firstParameterOrNull<Int>()?.let { Open(it) } } ?: firstOrNull { it.isComposableTargetMarked }?.let { constructor -> val fqName = constructor.symbol.owner.parentAsClass.fqNameWhenAvailable fqName?.let { Token(it.asString()) } } ?: Open(-1, isUnspecified = true) val IrFunction.scheme: Scheme? get() = annotations.firstOrNull { it.isComposableInferredTarget }?.let { constructor -> constructor.firstParameterOrNull<String>()?.let { deserializeScheme(it) } } fun IrFunction.hasSchemeSpecified(): Boolean = annotations.any { it.isComposableTarget || it.isComposableOpenTarget || it.isComposableInferredTarget || it.isComposableTargetMarked } fun IrType.toScheme(defaultTarget: Item): Scheme = when { this is IrSimpleType && isFunction() -> arguments else -> emptyList() }.let { typeArguments -> val target = annotations.target.let { if (it.isUnspecified) defaultTarget else it } fun toScheme(argument: IrTypeArgument): Scheme? = if (argument is IrTypeProjection && argument.type.isOrHasComposableLambda) argument.type.toScheme(defaultTarget) else null val parameters = typeArguments.takeUpTo(typeArguments.size - 1).mapNotNull { argument -> toScheme(argument) } val result = typeArguments.lastOrNull()?.let { argument -> toScheme(argument) } Scheme(target, parameters, result) } private val IrElement?.isComposableLambda: Boolean get() = when (this) { is IrFunctionExpression -> function.isComposable is IrCall -> isComposableSingletonGetter() || hasTransformedLambda() is IrGetField -> symbol.owner.initializer?.findTransformedLambda() != null else -> false } private val IrElement?.isComposableParameter: Boolean get() = when (this) { is IrGetValue -> parameterOwners[symbol] != null && type.isComposable else -> false } internal fun IrCall.hasTransformedLambda() = context.irTrace[ComposeWritableSlices.HAS_TRANSFORMED_LAMBDA, this] == true private fun IrElement.findTransformedLambda(): IrFunctionExpression? = when (this) { is IrCall -> arguments.firstNotNullOfOrNull { it?.findTransformedLambda() } is IrGetField -> symbol.owner.initializer?.findTransformedLambda() is IrBody -> statements.firstNotNullOfOrNull { it.findTransformedLambda() } is IrReturn -> value.findTransformedLambda() is IrFunctionExpression -> if (isTransformedLambda()) this else null else -> null } private fun IrFunctionExpression.isTransformedLambda() = context.irTrace[ComposeWritableSlices.IS_TRANSFORMED_LAMBDA, this] == true internal fun IrElement.transformedLambda(): IrFunctionExpression = findTransformedLambda() ?: error("Could not find the lambda for ${dump()}") // If this function throws an error it is because the IR transformation for singleton functions // changed. This function should be updated to account for the change. internal fun IrCall.singletonFunctionExpression(): IrFunctionExpression = symbol.owner.body?.findTransformedLambda() ?: error("Could not find the singleton lambda for ${dump()}") private fun Item.toAnnotation(): IrConstructorCall? = if (ComposableTargetClass != null && ComposableOpenTargetClass != null) { when (this) { is Token -> annotation(ComposableTargetClass).also { it.putValueArgument(0, irConst(value)) } is Open -> if (index < 0) null else annotation( ComposableOpenTargetClass ).also { it.putValueArgument(0, irConst(index)) } } } else null private fun Item.toAnnotations(): List<IrConstructorCall> = toAnnotation()?.let { listOf(it) } ?: emptyList() private fun Scheme.toAnnotations(): List<IrConstructorCall> = if (ComposableInferredTargetClass != null) { listOf( annotation(ComposableInferredTargetClass).also { it.putValueArgument(0, irConst(serialize())) } ) } else emptyList() private fun annotation(classSymbol: IrClassSymbol) = IrConstructorCallImpl( UNDEFINED_OFFSET, UNDEFINED_OFFSET, classSymbol.defaultType, classSymbol.constructors.first(), 0, 0, 1, null ) private fun filteredAnnotations(annotations: List<IrConstructorCall>) = annotations .filter { !it.isComposableTarget && !it.isComposableOpenTarget && !it.isComposableInferredTarget } fun updatedAnnotations(annotations: List<IrConstructorCall>, target: Item) = filteredAnnotations(annotations) + target.toAnnotations() fun updatedAnnotations(annotations: List<IrConstructorCall>, scheme: Scheme) = filteredAnnotations(annotations) + scheme.toAnnotations() fun inferenceFunctionOf(function: IrFunction) = InferenceFunctionDeclaration(this, function) fun inferenceFunctionTypeOf(type: IrType) = InferenceFunctionType(this, type) /** * A function is composable if it has a composer parameter added by the * [ComposerParamTransformer] or it still has the @Composable annotation which * can be because it is external and hasn't been transformed as the symbol remapper * only remaps what is referenced as a symbol this method might not have been * referenced directly in this module. */ private val IrFunction.isComposable get() = valueParameters.any { it.name == KtxNameConventions.COMPOSER_PARAMETER } || annotations.hasAnnotation(ComposeFqNames.Composable) private val IrType.isSamComposable get() = samOwnerOrNull()?.isComposable == true private val IrType.isComposableLambda get() = (this.classFqName == ComposeFqNames.composableLambdaType) || (this as? IrSimpleType) ?.arguments ?.any { it.typeOrNull?.classFqName == ComposeFqNames.Composer } == true internal val IrType.isOrHasComposableLambda: Boolean get() = isComposableLambda || isSamComposable || (this as? IrSimpleType)?.arguments?.any { it.typeOrNull?.isOrHasComposableLambda == true } == true private val IrType.isComposable get() = isComposableLambda || isSamComposable private fun IrFunction.hasComposableParameter() = valueParameters.any { it.type.isComposable } private fun IrCall.hasComposableArguments() = arguments.any { argument -> argument?.type?.let { type -> (type.isOrHasComposableLambda || type.isSamComposable) } == true } } /** * An [InferenceFunction] is an abstraction to allow inference to translate a type into a scheme * and update the declaration of a type if inference determines a more accurate scheme. */ sealed class InferenceFunction( val transformer: ComposableTargetAnnotationsTransformer ) { /** * The name of the function. This is only supplied for debugging. */ abstract val name: String /** * Can the scheme be updated. If not, tell inference not to track it. */ abstract val schemeIsUpdatable: Boolean /** * Record a scheme for the function in metrics (if applicable). */ open fun recordScheme(scheme: Scheme) { } /** * The scheme has changed so the corresponding attributes should be updated to match the * scheme provided. */ abstract fun updateScheme(scheme: Scheme) /** * Return a declared scheme for the function. */ abstract fun toDeclaredScheme(defaultTarget: Item = Open(0)): Scheme /** * Return true if this is a type with overly wide parameter types such as Any or * unconstrained or insufficiently constrained type parameters. */ open fun isOverlyWide(): Boolean = false /** * Helper routine to produce an updated annotations list. */ fun updatedAnnotations(annotations: List<IrConstructorCall>, target: Item) = transformer.updatedAnnotations(annotations, target) /** * Helper routine to produce an updated annotations list. */ fun updatedAnnotations(annotations: List<IrConstructorCall>, scheme: Scheme) = transformer.updatedAnnotations(annotations, scheme) } /** * An [InferenceFunctionDeclaration] refers to the type implied by a function declaration. * * Storing [Scheme] information is complicated by the current IR transformer limitation that * annotations added to types are not serialized. Instead of updating the parameter types * directly (for example adding a annotation to the IrType of the parameter declaration) the * [Scheme] is serialized into a string and stored on the function declaration. */ class InferenceFunctionDeclaration( transformer: ComposableTargetAnnotationsTransformer, val function: IrFunction ) : InferenceFunction(transformer) { override val name: String get() = function.name.toString() override val schemeIsUpdatable: Boolean get() = true override fun recordScheme(scheme: Scheme) { if (!scheme.allAnonymous()) { with(transformer) { metricsFor(function).recordScheme(scheme.toString()) } } } override fun updateScheme(scheme: Scheme) { if (scheme.shouldSerialize) { function.annotations = updatedAnnotations(function.annotations, scheme) } else { function.annotations = updatedAnnotations(function.annotations, scheme.target) parameters().zip(scheme.parameters) { parameter, parameterScheme -> parameter.updateScheme(parameterScheme) } } } override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) { function.scheme ?: function.toScheme(defaultTarget) } private fun IrFunction.toScheme(defaultTarget: Item): Scheme = with(transformer) { val target = function.annotations.target.let { target -> if (target.isUnspecified && function.body == null) { defaultTarget } else if (target.isUnspecified) { // Default to the target specified at the file scope, if one. function.file.annotations.target } else target } val effectiveDefault = if (function.body == null) defaultTarget else Open(-1, isUnspecified = true) val result = function.returnType.let { resultType -> if (resultType.isOrHasComposableLambda) resultType.toScheme(effectiveDefault) else null } Scheme( target, parameters().map { it.toDeclaredScheme(effectiveDefault) }, result ).let { scheme -> ancestorScheme(defaultTarget)?.let { scheme.mergeWith(listOf(it)) } ?: scheme } } private fun IrFunction.ancestorScheme(defaultTarget: Item): Scheme? = if (this is IrSimpleFunction && this.overriddenSymbols.isNotEmpty()) { getLastOverridden().toScheme(defaultTarget) } else null override fun hashCode(): Int = function.hashCode() * 31 override fun equals(other: Any?) = other is InferenceFunctionDeclaration && other.function == function private fun parameters(): List<InferenceFunction> = with(transformer) { function.valueParameters.filter { it.type.isOrHasComposableLambda }.map { parameter -> InferenceFunctionParameter(transformer, parameter) }.let { parameters -> function.extensionReceiverParameter?.let { if (it.type.isOrHasComposableLambda) { parameters + listOf(InferenceFunctionParameter(transformer, it)) } else parameters } ?: parameters } } private val Scheme.shouldSerialize get(): Boolean = parameters.isNotEmpty() private fun Scheme.allAnonymous(): Boolean = target.isAnonymous && (result == null || result.allAnonymous()) && parameters.all { it.allAnonymous() } } /** * An [InferenceFunctionCallType] is the type abstraction for a call. This is used for [IrCall] * because it has the substituted types for generic types and the function's symbol has the original * unsubstituted types. It is important, for example for calls to [let], that the arguments * and result are after generic resolution so calls like `content?.let { it.invoke() }` correctly * infer that the scheme is `[0[0]]` if `content` is a of type `(@Composable () -> Unit)?. This * can only be determined after the generic parameters have been substituted. */ class InferenceFunctionCallType( transformer: ComposableTargetAnnotationsTransformer, private val call: IrCall ) : InferenceFunction(transformer) { override val name: String get() = "Call(${call.symbol.owner.name})" override val schemeIsUpdatable: Boolean get() = false override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) { val target = call.symbol.owner.annotations.target.let { target -> if (target.isUnspecified) defaultTarget else target } val parameters = call.arguments.filterNotNull().filter { it.type.isOrHasComposableLambda }.map { it.type.toScheme(defaultTarget) }.toMutableList() fun recordParameter(expression: IrExpression?) { if (expression != null && expression.type.isOrHasComposableLambda) { parameters.add(expression.type.toScheme(defaultTarget)) } } recordParameter(call.extensionReceiver) val result = if (call.type.isOrHasComposableLambda) call.type.toScheme(defaultTarget) else null Scheme(target, parameters, result) } override fun isOverlyWide(): Boolean = call.symbol.owner.hasOverlyWideParameters() override fun updateScheme(scheme: Scheme) { // Ignore the updated scheme for the call as it can always be re-inferred. } } /** * Produce the scheme from a function type. */ class InferenceFunctionType( transformer: ComposableTargetAnnotationsTransformer, private val type: IrType ) : InferenceFunction(transformer) { override val name: String get() = "<type>" override val schemeIsUpdatable: Boolean get() = false override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) { type.toScheme(defaultTarget) } override fun updateScheme(scheme: Scheme) { // Cannot update the scheme of a type yet. This is worked around for parameters by recording // the inferred scheme for the parameter in a serialized scheme for the function. For other // types we don't need to record the inference we just need the declared scheme. } } /** * The type of a function parameter. The parameter of a function needs to update where it came from. */ class InferenceFunctionParameter( transformer: ComposableTargetAnnotationsTransformer, val parameter: IrValueParameter ) : InferenceFunction(transformer) { override val name: String get() = "<parameter>" override fun hashCode(): Int = parameter.hashCode() * 31 override fun equals(other: Any?) = other is InferenceFunctionParameter && other.parameter == parameter override val schemeIsUpdatable: Boolean get() = false override fun toDeclaredScheme(defaultTarget: Item): Scheme = with(transformer) { val samAnnotations = parameter.type.samOwnerOrNull()?.annotations ?: emptyList() val annotations = parameter.type.annotations + samAnnotations val target = annotations.target.let { if (it.isUnspecified) defaultTarget else it } parameter.type.toScheme(target) } override fun updateScheme(scheme: Scheme) { // Note that this is currently not called. Type annotations are serialized into an // ComposableInferredAnnotation. This is kept here as example of how the type should // be updated once such a modification is correctly serialized by Kotlin. val type = parameter.type if (type is IrSimpleType) { val newType = type.toBuilder().apply { annotations = updatedAnnotations(annotations, scheme.target) }.buildSimpleType() parameter.type = newType } } } /** * A wrapper around IrElement to return the information requested by inference. */ sealed class InferenceNode { /** * The element being wrapped */ abstract val element: IrElement /** * The node kind of the node */ abstract val kind: NodeKind /** * The function type abstraction used by inference */ abstract val function: InferenceFunction? /** * The container node being referred to by the this node, if there is one. For example, if this * is a parameter reference then this is the function that contains the parameter (which * parameterIndex can be used to determine the parameter index). If it is a call to a static * function then the reference is to the IrFunction that is being called. */ open val referenceContainer: InferenceNode? = null /** * [node] is one of the parameters of this container node then return its index. -1 indicates * that [node] is not a parameter of this container (or this is not a container). */ open fun parameterIndex(node: InferenceNode): Int = -1 /** * An overly wide function (a function with Any types) is too wide to use for to infer an * applier (that is it contains parameters of type Any or Any?). */ open fun isOverlyWide(): Boolean = function?.isOverlyWide() == true override fun hashCode() = element.hashCode() * 31 override fun equals(other: Any?) = other is InferenceNode && other.element == element } val IrSimpleFunctionSymbol.isGenericFunction get(): Boolean = owner.typeParameters.isNotEmpty() || owner.dispatchReceiverParameter?.type?.let { it is IrSimpleType && it.arguments.isNotEmpty() } == true /** * An [InferenceCallTargetNode] is a wrapper around an [IrCall] which represents the target of * the call, not the call itself. That its type is the type of the target of the call not the * result of the call. */ class InferenceCallTargetNode( private val transformer: ComposableTargetAnnotationsTransformer, override val element: IrCall ) : InferenceNode() { override fun equals(other: Any?): Boolean = other is InferenceCallTargetNode && super.equals(other) override fun hashCode(): Int = super.hashCode() * 31 override val kind: NodeKind get() = NodeKind.Function override val function = with(transformer) { if (element.symbol.owner.hasSchemeSpecified()) InferenceFunctionDeclaration(transformer, element.symbol.owner) else InferenceFunctionCallType(transformer, element) } override val referenceContainer: InferenceNode? = // If this is a generic function then don't redirect the scheme to the declaration if (element.symbol.isGenericFunction) null else with(transformer) { val function = when { element.isComposableSingletonGetter() -> // If this was a lambda transformed into a singleton, find the singleton function element.singletonFunctionExpression().function element.hasTransformedLambda() -> // If this is a normal lambda, find the lambda's IrFunction element.transformedLambda().function else -> element.symbol.owner } // If this is a call to a non-generic function with a body (e.g. non-abstract), return its // function. Generic or abstract functions (interface members, lambdas, open methods, etc.) // do not contain a body to infer anything from so we just use the declared scheme if // there is one. Returning null from this function cause the scheme to be determined from // the target expression (using, for example, the substituted type parameters) instead of // the definition. function.takeIf { it.body != null && it.typeParameters.isEmpty() }?.let { inferenceNodeOf(function, transformer) } } } /** * A node representing a variable declaration. */ class InferenceVariable( private val transformer: ComposableTargetAnnotationsTransformer, override val element: IrVariable, ) : InferenceNode() { override val kind: NodeKind get() = NodeKind.Variable override val function: InferenceFunction get() = transformer.inferenceFunctionTypeOf(element.type) override val referenceContainer: InferenceNode? get() = null } fun inferenceNodeOf( element: IrElement, transformer: ComposableTargetAnnotationsTransformer ): InferenceNode = when (element) { is IrFunction -> InferenceFunctionDeclarationNode(transformer, element) is IrFunctionExpression -> InferenceFunctionExpressionNode(transformer, element) is IrTypeOperatorCall -> inferenceNodeOf(element.argument, transformer) is IrCall -> InferenceCallExpression(transformer, element) is IrExpression -> InferenceElementExpression(transformer, element) else -> InferenceUnknownElement(element) } /** * A node wrapper for function declarations. */ class InferenceFunctionDeclarationNode( transformer: ComposableTargetAnnotationsTransformer, override val element: IrFunction ) : InferenceNode() { override val kind: NodeKind get() = NodeKind.Function override val function: InferenceFunction = transformer.inferenceFunctionOf(element) override val referenceContainer: InferenceNode? get() = this.takeIf { element.body != null } } /** * A node wrapper for function expressions (i.e. lambdas). */ class InferenceFunctionExpressionNode( private val transformer: ComposableTargetAnnotationsTransformer, override val element: IrFunctionExpression ) : InferenceNode() { override val kind: NodeKind get() = NodeKind.Lambda override val function: InferenceFunction = transformer.inferenceFunctionOf(element.function) override val referenceContainer: InferenceNode get() = inferenceNodeOf(element.function, transformer) } /** * A node wrapper for a call. This represents the result of a call. Use [InferenceCallTargetNode] * to represent the target of a call. */ class InferenceCallExpression( private val transformer: ComposableTargetAnnotationsTransformer, override val element: IrCall ) : InferenceNode() { private val isSingletonLambda = with(transformer) { element.isComposableSingletonGetter() } private val isTransformedLambda = with(transformer) { element.hasTransformedLambda() } override val kind: NodeKind get() = if (isSingletonLambda || isTransformedLambda) NodeKind.Lambda else NodeKind.Expression override val function: InferenceFunction = with(transformer) { when { isSingletonLambda -> inferenceFunctionOf(element.singletonFunctionExpression().function) isTransformedLambda -> inferenceFunctionOf(element.transformedLambda().function) else -> transformer.inferenceFunctionTypeOf(element.type) } } override val referenceContainer: InferenceNode? get() = with(transformer) { when { isSingletonLambda -> inferenceNodeOf(element.singletonFunctionExpression().function, transformer) isTransformedLambda -> inferenceNodeOf(element.transformedLambda().function, transformer) else -> null } } } /** * An expression node whose scheme is determined by the type of the node. */ class InferenceElementExpression( transformer: ComposableTargetAnnotationsTransformer, override val element: IrExpression, ) : InferenceNode() { override val kind: NodeKind get() = NodeKind.Expression override val function: InferenceFunction = transformer.inferenceFunctionTypeOf(element.type) } /** * An [InferenceUnknownElement] is a general wrapper around function declarations and lambda. */ class InferenceUnknownElement( override val element: IrElement, ) : InferenceNode() { override val kind: NodeKind get() = NodeKind.Expression override val function: InferenceFunction? get() = null override val referenceContainer: InferenceNode? get() = null } /** * An [InferenceResolvedParameter] is a node that references a parameter of a container of this * node. For example, if the parameter is captured by a nested lambda this is resolved to the * captured parameter. */ class InferenceResolvedParameter( override val element: IrGetValue, override val function: InferenceFunction, val container: InferenceNode, val index: Int ) : InferenceNode() { override val kind: NodeKind get() = NodeKind.ParameterReference override fun parameterIndex(node: InferenceNode): Int = if (node.function == function) index else -1 override val referenceContainer: InferenceNode get() = container override fun equals(other: Any?): Boolean = other is InferenceResolvedParameter && other.element == element override fun hashCode(): Int = element.hashCode() * 31 + 103 } private inline fun <reified T> IrConstructorCall.firstParameterOrNull() = if (valueArgumentsCount >= 1) { (getValueArgument(0) as? IrConst<*>)?.value as? T } else null private val IrConstructorCall.isComposableTarget get() = annotationClass?.isClassWithFqName( ComposeFqNames.ComposableTarget.toUnsafe() ) == true private val IrConstructorCall.isComposableTargetMarked: Boolean get() = annotationClass?.owner?.annotations?.hasAnnotation( ComposeFqNames.ComposableTargetMarker ) == true private val IrConstructorCall.isComposableInferredTarget get() = annotationClass?.isClassWithFqName( ComposeFqNames.ComposableInferredTarget.toUnsafe() ) == true private val IrConstructorCall.isComposableOpenTarget get() = annotationClass?.isClassWithFqName( ComposeFqNames.ComposableOpenTarget.toUnsafe() ) == true private fun IrType.samOwnerOrNull() = classOrNull?.let { cls -> if (cls.owner.kind == ClassKind.INTERFACE) { cls.functions.singleOrNull { it.owner.modality == Modality.ABSTRACT }?.owner } else null } private val IrCall.arguments get() = Array(valueArgumentsCount) { getValueArgument(it) }.toList() private fun <T> Iterable<T>.takeUpTo(n: Int): List<T> = if (n <= 0) emptyList() else take(n) /** * A function with overly wide parameters should be ignored for traversal as well as when * it is called. */ private fun IrFunction.hasOverlyWideParameters(): Boolean = valueParameters.any { it.type.isAny() || it.type.isNullableAny() } private fun IrFunction.hasOpenTypeParameters(): Boolean = valueParameters.any { it.type.isTypeParameter() } || dispatchReceiverParameter?.type?.isTypeParameter() == true || extensionReceiverParameter?.type?.isTypeParameter() == true
compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/ComposableTargetAnnotationsTransformer.kt
1796546725
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.gestures.snapping import androidx.compose.animation.core.DecayAnimationSpec import androidx.compose.animation.core.calculateTargetValue import androidx.compose.animation.splineBasedDecay import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.FlingBehavior import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.lazy.LazyListItemInfo import androidx.compose.foundation.lazy.LazyListLayoutInfo import androidx.compose.foundation.lazy.LazyListState import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.unit.Density import androidx.compose.ui.util.fastForEach import androidx.compose.ui.util.fastSumBy import kotlin.math.absoluteValue import kotlin.math.sign /** * A [SnapLayoutInfoProvider] for LazyLists. * * @param lazyListState The [LazyListState] with information about the current state of the list * @param positionInLayout The desired positioning of the snapped item within the main layout. * This position should be considered with regard to the start edge of the item and the placement * within the viewport. * * @return A [SnapLayoutInfoProvider] that can be used with [SnapFlingBehavior] */ @ExperimentalFoundationApi fun SnapLayoutInfoProvider( lazyListState: LazyListState, positionInLayout: Density.(layoutSize: Float, itemSize: Float) -> Float = { layoutSize, itemSize -> (layoutSize / 2f - itemSize / 2f) } ): SnapLayoutInfoProvider = object : SnapLayoutInfoProvider { private val layoutInfo: LazyListLayoutInfo get() = lazyListState.layoutInfo // Decayed page snapping is the default override fun Density.calculateApproachOffset(initialVelocity: Float): Float { val decayAnimationSpec: DecayAnimationSpec<Float> = splineBasedDecay(this) val offset = decayAnimationSpec.calculateTargetValue(NoDistance, initialVelocity).absoluteValue val finalDecayOffset = (offset - calculateSnapStepSize()).coerceAtLeast(0f) return if (finalDecayOffset == 0f) { finalDecayOffset } else { finalDecayOffset * initialVelocity.sign } } override fun Density.calculateSnappingOffsetBounds(): ClosedFloatingPointRange<Float> { var lowerBoundOffset = Float.NEGATIVE_INFINITY var upperBoundOffset = Float.POSITIVE_INFINITY layoutInfo.visibleItemsInfo.fastForEach { item -> val offset = calculateDistanceToDesiredSnapPosition(layoutInfo, item, positionInLayout) // Find item that is closest to the center if (offset <= 0 && offset > lowerBoundOffset) { lowerBoundOffset = offset } // Find item that is closest to center, but after it if (offset >= 0 && offset < upperBoundOffset) { upperBoundOffset = offset } } return lowerBoundOffset.rangeTo(upperBoundOffset) } override fun Density.calculateSnapStepSize(): Float = with(layoutInfo) { if (visibleItemsInfo.isNotEmpty()) { visibleItemsInfo.fastSumBy { it.size } / visibleItemsInfo.size.toFloat() } else { 0f } } } /** * Create and remember a FlingBehavior for decayed snapping in Lazy Lists. This will snap * the item's center to the center of the viewport. * * @param lazyListState The [LazyListState] from the LazyList where this [FlingBehavior] will * be used. */ @ExperimentalFoundationApi @Composable fun rememberSnapFlingBehavior(lazyListState: LazyListState): FlingBehavior { val snappingLayout = remember(lazyListState) { SnapLayoutInfoProvider(lazyListState) } return rememberSnapFlingBehavior(snappingLayout) } internal fun Density.calculateDistanceToDesiredSnapPosition( layoutInfo: LazyListLayoutInfo, item: LazyListItemInfo, positionInLayout: Density.(layoutSize: Float, itemSize: Float) -> Float ): Float { val containerSize = with(layoutInfo) { singleAxisViewportSize - beforeContentPadding - afterContentPadding } val desiredDistance = positionInLayout(containerSize.toFloat(), item.size.toFloat()) val itemCurrentPosition = item.offset return itemCurrentPosition - desiredDistance } private val LazyListLayoutInfo.singleAxisViewportSize: Int get() = if (orientation == Orientation.Vertical) viewportSize.height else viewportSize.width
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/snapping/LazyListSnapLayoutInfoProvider.kt
1017488343
package com.vimeo.networking2.enums /** * The type of the object that is contained within a ProjectItem. */ enum class ProjectItemType(override val value: String?) : StringValue { /** * The ProjectItem contains a folder. */ FOLDER("folder"), /** * The ProjectItem contains a video. */ VIDEO("video"), /** * The ProjectItem contains an unknown type. */ UNKNOWN(null) }
models/src/main/java/com/vimeo/networking2/enums/ProjectItemType.kt
1655343121
/* * SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least. * Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. */ package de.sudoq.model.solverGenerator import de.sudoq.model.solverGenerator.solution.Solution import de.sudoq.model.sudoku.Sudoku /** * Dieses Interface muss implementiert werden, um die generate-Methode des * Generator zu benutzen. Dieser führt die Generierung in einem anderen Thread * aus und ruft die generationFinished-Methode dieses Callback-Objektes auf, * sobald er fertig ist. */ interface GeneratorCallback { /* Methods */ /** * Diese Methode wird vom Generator aufgerufen, nachdem er die Generierung * eines Sudokus abgeschlossen hat. Das übergebene Sudoku soll dabei ein * generiertes, valides Sudoku sein. Ist das spezifizierte Sudoku null, so * wird nichts ausgeführt. * * @param sudoku * Das vom Generator erzeugte, valide Sudoku */ fun generationFinished(sudoku: Sudoku) fun generationFinished(sudoku: Sudoku, sl: List<Solution>) }
sudoq-app/sudoqmodel/src/main/kotlin/de/sudoq/model/solverGenerator/GeneratorCallback.kt
3552869584
package de.reiss.bible2net.theword.note.details import android.content.Context import android.content.Intent import android.os.Bundle import de.reiss.bible2net.theword.R import de.reiss.bible2net.theword.architecture.AppActivity import de.reiss.bible2net.theword.databinding.NoteDetailsActivityBinding import de.reiss.bible2net.theword.model.Note import de.reiss.bible2net.theword.util.extensions.findFragmentIn import de.reiss.bible2net.theword.util.extensions.replaceFragmentIn class NoteDetailsActivity : AppActivity(), ConfirmDeleteDialog.Listener { companion object { private const val KEY_NOTE = "KEY_NOTE" fun createIntent(context: Context, note: Note): Intent = Intent(context, NoteDetailsActivity::class.java) .putExtra(KEY_NOTE, note) } private lateinit var binding: NoteDetailsActivityBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = NoteDetailsActivityBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.noteDetailsToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (findNoteDetailsFragment() == null) { replaceFragmentIn( container = R.id.note_details_fragment, fragment = NoteDetailsFragment.createInstance(intent.getParcelableExtra(KEY_NOTE)!!) ) } } override fun onDeleteConfirmed() { findNoteDetailsFragment()?.tryDeleteNote() } private fun findNoteDetailsFragment() = findFragmentIn(R.id.note_details_fragment) as? NoteDetailsFragment }
app/src/main/java/de/reiss/bible2net/theword/note/details/NoteDetailsActivity.kt
1100011129
@file:Suppress("BlockingMethodInNonBlockingContext") package com.sksamuel.scrimage.core.ops import com.sksamuel.scrimage.ImmutableImage import com.sksamuel.scrimage.ScaleMethod import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.doubles.shouldBeLessThan import io.kotest.matchers.shouldBe class ScaleTest : FunSpec({ val image = ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/bird.jpg") test("Bicubic scale test") { image.scaleTo(486, 324) shouldBe ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/scale/bird_486_324_bicubic.png") } test("Bilinear scale test") { image.scaleTo(486, 324, ScaleMethod.Bilinear) shouldBe ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/scale/bird_486_324_bilinear.png") } test("Progressive bilinear scale down test") { image.scaleTo(486, 324, ScaleMethod.Progressive) shouldBe ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/scale/bird_486_324_prog_bilinear.png") } test("Progressive bilinear scale up test should complete") { image.scaleTo(3000, 3000, ScaleMethod.Progressive).width shouldBe 3000 image.scaleTo(3000, 100, ScaleMethod.Progressive).height shouldBe 100 image.scaleTo(100, 3000, ScaleMethod.Progressive).width shouldBe 100 } test("when scaling an image the output image should match as expected") { val scaled = image.scale(0.25) val expected = ImmutableImage.loader().fromResource("/com/sksamuel/scrimage/bird_scale_025.png") expected.width shouldBe scaled.width expected.height shouldBe scaled.height } test("when scaling an image the output image should have specified dimensions") { val scaled = image.scaleTo(900, 300) scaled.width shouldBe 900 scaled.height shouldBe 300 } test("when scaling by width then target image maintains aspect ratio") { val scaled = image.scaleToWidth(500) scaled.width shouldBe 500 scaled.ratio() - image.ratio() shouldBeLessThan 0.01 } test("when scaling by height then target image maintains aspect ratio") { val scaled = image.scaleToHeight(400) scaled.height shouldBe 400 scaled.ratio() - image.ratio() shouldBeLessThan 0.01 } })
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/ops/ScaleTest.kt
299105663
package br.com.bumblebee.configuration.feign.decoder import feign.Response import feign.codec.ErrorDecoder import mu.KotlinLogging import java.lang.Exception class FeignErrorDecoder : ErrorDecoder { private val logger = KotlinLogging.logger {} override fun decode(methodKey: String, response: Response): Exception { logger.error { errorMessage(methodKey, response) } return RuntimeException("External API failure") } private fun errorMessage(methodKey: String, response: Response): String { val responseBody = response.body().asReader() return "Error Status: ${response.status()} Error body: $responseBody Executing: $methodKey" } }
src/main/kotlin/br/com/bumblebee/configuration/feign/decoder/FeignErrorDecoder.kt
2537707205
package com.twitter.meil_mitu.twitter4hk.api.blocks import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.AbsPost import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.converter.IUserConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException class Destroy<TUser>( oauth: AbsOauth, protected val json: IUserConverter<TUser>) : AbsPost<TUser>(oauth) { var screenName: String? by stringParam("screen_name") var userId: Long? by longParam("user_id") var includeEntities: Boolean? by booleanParam("include_entities") var skipStatus: Boolean? by booleanParam("skip_status") override val url = "https://api.twitter.com/1.1/blocks/destroy.json" override val allowOauthType = OauthType.oauth1 override val isAuthorization = true @Throws(Twitter4HKException::class) override fun call(): TUser { return json.toUser(oauth.post(this)) } }
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/blocks/Destroy.kt
3090555928
/* Copyright 2017-2020 Charles Korn. 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 batect.os import java.nio.file.Files import java.nio.file.InvalidPathException import java.nio.file.Path import java.util.Properties data class PathResolver(val relativeTo: Path, private val systemProperties: Properties = System.getProperties()) { private val homeDir = getPath(systemProperties.getProperty("user.home")) fun resolve(path: String): PathResolutionResult { try { val originalPath = resolveHomeDir(getPath(path)) val resolvedPath = relativeTo.resolve(originalPath).normalize().toAbsolutePath() return PathResolutionResult.Resolved(path, resolvedPath, pathType(resolvedPath)) } catch (e: InvalidPathException) { return PathResolutionResult.InvalidPath(path) } } private fun getPath(path: String): Path = relativeTo.fileSystem.getPath(path) private fun resolveHomeDir(path: Path): Path { val homeSymbol = getPath("~") if (path.startsWith(homeSymbol)) { return homeDir.resolve(homeSymbol.relativize(path)) } else { return path } } private fun pathType(path: Path): PathType { return when { !Files.exists(path) -> PathType.DoesNotExist Files.isRegularFile(path) -> PathType.File Files.isDirectory(path) -> PathType.Directory else -> PathType.Other } } } sealed class PathResolutionResult(open val originalPath: String) { data class Resolved(override val originalPath: String, val absolutePath: Path, val pathType: PathType) : PathResolutionResult(originalPath) data class InvalidPath(override val originalPath: String) : PathResolutionResult(originalPath) } enum class PathType { DoesNotExist, File, Directory, Other }
app/src/main/kotlin/batect/os/PathResolver.kt
3500311076
package org.jetbrains.dokka.tests import org.jetbrains.dokka.DokkaConsoleLogger import org.jetbrains.dokka.KotlinLanguageService import org.jetbrains.dokka.KotlinWebsiteRunnableSamplesFormatService import org.junit.Ignore import org.junit.Test @Ignore class KotlinWebSiteRunnableSamplesFormatTest { // private val kwsService = KotlinWebsiteRunnableSamplesFormatService(InMemoryLocationService, KotlinLanguageService(), listOf(), DokkaConsoleLogger) // // // @Test fun dropImport() { // verifyKWSNodeByName("dropImport", "foo") // } // // @Test fun sample() { // verifyKWSNodeByName("sample", "foo") // } // // @Test fun sampleWithAsserts() { // verifyKWSNodeByName("sampleWithAsserts", "a") // } // // @Test fun newLinesInSamples() { // verifyKWSNodeByName("newLinesInSamples", "foo") // } // // @Test fun newLinesInImportList() { // verifyKWSNodeByName("newLinesInImportList", "foo") // } // // private fun verifyKWSNodeByName(fileName: String, name: String) { // verifyOutput("testdata/format/website-samples/$fileName.kt", ".md", format = "kotlin-website-samples") { model, output -> // kwsService.createOutputBuilder(output, tempLocation).appendNodes(model.members.single().members.filter { it.name == name }) // } // } }
core/src/test/kotlin/format/KotlinWebSiteRunnableSamplesFormatTest.kt
1740227158
/* Copyright 2017-2020 Charles Korn. 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 batect.logging import batect.testutils.on import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import kotlinx.serialization.internal.BooleanSerializer import kotlinx.serialization.internal.IntSerializer import kotlinx.serialization.internal.StringSerializer import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.io.OutputStream import java.io.PrintStream import java.nio.file.Files import java.time.ZoneOffset import java.time.ZonedDateTime object FileLogSinkSpec : Spek({ describe("a file log sink") { val fileSystem = Jimfs.newFileSystem(Configuration.unix()) val path = fileSystem.getPath("/someLogFile.log") val writer = mock<LogMessageWriter> { on { writeTo(any(), any()) } doAnswer { invocation -> val outputStream = invocation.arguments[1] as OutputStream PrintStream(outputStream).print("The value written by the writer") null } } val standardAdditionalDataSource = mock<StandardAdditionalDataSource> { on { getAdditionalData() } doReturn mapOf("someStandardInfo" to JsonableObject(false, BooleanSerializer)) } val timestampToUse = ZonedDateTime.of(2017, 9, 25, 15, 51, 0, 0, ZoneOffset.UTC) val timestampSource = { timestampToUse } val sink = FileLogSink(path, writer, standardAdditionalDataSource, timestampSource) on("writing a log message") { sink.write(Severity.Info, mapOf("someAdditionalInfo" to JsonableObject("someValue", StringSerializer))) { message("This is the message") data("someLocalInfo", 888) } val expectedMessage = LogMessage(Severity.Info, "This is the message", timestampToUse, mapOf( "someAdditionalInfo" to JsonableObject("someValue", StringSerializer), "someLocalInfo" to JsonableObject(888, IntSerializer), "someStandardInfo" to JsonableObject(false, BooleanSerializer) )) it("calls the builder function to create the log message and passes it to the writer") { verify(writer).writeTo(eq(expectedMessage), any()) } it("passes a stream to the writer that writes to the path provided") { val content = String(Files.readAllBytes(path)) assertThat(content, equalTo("The value written by the writer")) } } } })
app/src/unitTest/kotlin/batect/logging/FileLogSinkSpec.kt
2930433209
/* Copyright 2017-2020 Charles Korn. 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 batect.docker.api import batect.docker.DockerException class ContainerInspectionFailedException(message: String) : DockerException(message) class ContainerRemovalFailedException(val containerId: String, val outputFromDocker: String) : DockerException("Removal of container '$containerId' failed: $outputFromDocker") class ContainerStartFailedException(val containerId: String, val outputFromDocker: String) : DockerException("Starting container '$containerId' failed: $outputFromDocker") class ContainerStopFailedException(val containerId: String, val outputFromDocker: String) : DockerException("Stopping container '$containerId' failed: $outputFromDocker") class DockerVersionInfoRetrievalException(message: String) : DockerException(message) class NetworkCreationFailedException(val outputFromDocker: String) : DockerException("Creation of network failed: $outputFromDocker") class NetworkDeletionFailedException(val networkId: String, val outputFromDocker: String) : DockerException("Deletion of network '$networkId' failed: $outputFromDocker") class ContainerStoppedException(message: String) : DockerException(message) class ExecInstanceInspectionFailedException(message: String) : DockerException(message)
app/src/main/kotlin/batect/docker/api/Exceptions.kt
7467744
/* * 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.ui.test.selectors import androidx.test.filters.MediumTest import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.hasTestTag import androidx.compose.ui.test.onChildren import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.util.BoundaryNode import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 @MediumTest @RunWith(AndroidJUnit4::class) class ChildrenSelectorTest { @get:Rule val rule = createComposeRule() @Test fun twoChildren() { rule.setContent { BoundaryNode(testTag = "Parent") { BoundaryNode(testTag = "Child1") BoundaryNode(testTag = "Child2") } } rule.onNodeWithTag("Parent") .onChildren() .assertCountEquals(2) .apply { get(0).assert(hasTestTag("Child1")) get(1).assert(hasTestTag("Child2")) } } @Test fun noChildren() { rule.setContent { BoundaryNode(testTag = "Parent") } rule.onNodeWithTag("Parent") .onChildren() .assertCountEquals(0) } }
compose/ui/ui-test/src/androidAndroidTest/kotlin/androidx/compose/ui/test/selectors/ChildrenSelectorTest.kt
1146168145
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room /** * The list of warnings that are produced by Room. * * You can use these values inside a [SuppressWarnings] annotation to disable the warnings. */ // If you change this, don't forget to change androidx.room.vo.Warning @SuppressWarnings("unused", "WeakerAccess") public open class RoomWarnings { public companion object { /** * The warning dispatched by Room when the return value of a [Query] method does not * exactly match the fields in the query result. */ public const val CURSOR_MISMATCH: String = "ROOM_CURSOR_MISMATCH" /** * The warning dispatched by Room when the object in the provided method's multimap return * type does not implement equals() and hashCode(). */ public const val DOES_NOT_IMPLEMENT_EQUALS_HASHCODE: String = "ROOM_TYPE_DOES_NOT_IMPLEMENT_EQUALS_HASHCODE" /** * Reported when Room cannot verify database queries during compilation due to lack of * tmp dir access in JVM. */ public const val MISSING_JAVA_TMP_DIR: String = "ROOM_MISSING_JAVA_TMP_DIR" /** * Reported when Room cannot verify database queries during compilation. This usually * happens when it cannot find the SQLite JDBC driver on the host machine. * * Room can function without query verification but its functionality will be limited. */ public const val CANNOT_CREATE_VERIFICATION_DATABASE: String = "ROOM_CANNOT_CREATE_VERIFICATION_DATABASE" /** * Reported when an [Entity] field that is annotated with [Embedded] has a * sub field which is annotated with [PrimaryKey] but the [PrimaryKey] is dropped * while composing it into the parent object. */ public const val PRIMARY_KEY_FROM_EMBEDDED_IS_DROPPED: String = "ROOM_EMBEDDED_PRIMARY_KEY_IS_DROPPED" /** * Reported when an [Entity] field that is annotated with [Embedded] has a * sub field which has a [ColumnInfo] annotation with `index = true`. * * You can re-define the index in the containing [Entity]. */ public const val INDEX_FROM_EMBEDDED_FIELD_IS_DROPPED: String = "ROOM_EMBEDDED_INDEX_IS_DROPPED" /** * Reported when an [Entity] that has a [Embedded] field whose type is another * [Entity] and that [Entity] has some indices defined. * These indices will NOT be created in the containing [Entity]. If you want to preserve * them, you can re-define them in the containing [Entity]. */ public const val INDEX_FROM_EMBEDDED_ENTITY_IS_DROPPED: String = "ROOM_EMBEDDED_ENTITY_INDEX_IS_DROPPED" /** * Reported when an [Entity]'s parent declares an [Index]. Room does not * automatically inherit these indices to avoid hidden costs or unexpected constraints. * * If you want your child class to have the indices of the parent, you must re-declare * them in the child class. Alternatively, you can set [Entity.inheritSuperIndices] * to `true`. */ public const val INDEX_FROM_PARENT_IS_DROPPED: String = "ROOM_PARENT_INDEX_IS_DROPPED" /** * Reported when an [Entity] inherits a field from its super class and the field has a * [ColumnInfo] annotation with `index = true`. * * These indices are dropped for the [Entity] and you would need to re-declare them if * you want to keep them. Alternatively, you can set [Entity.inheritSuperIndices] * to `true`. */ public const val INDEX_FROM_PARENT_FIELD_IS_DROPPED: String = "ROOM_PARENT_FIELD_INDEX_IS_DROPPED" /** * Reported when a [Relation] [Entity]'s SQLite column type does not match the type * in the parent. Room will still do the matching using `String` representations. */ public const val RELATION_TYPE_MISMATCH: String = "ROOM_RELATION_TYPE_MISMATCH" /** * Reported when a `room.schemaLocation` argument is not provided into the annotation * processor. * You can either set [Database.exportSchema] to `false` or provide * `room.schemaLocation` to the annotation processor. You are strongly advised to provide it * and also commit them into your version control system. */ public const val MISSING_SCHEMA_LOCATION: String = "ROOM_MISSING_SCHEMA_LOCATION" /** * When there is a foreign key from Entity A to Entity B, it is a good idea to index the * reference columns in B, otherwise, each modification on Entity A will trigger a full table * scan on Entity B. * * If Room cannot find a proper index in the child entity (Entity B in this case), Room will * print this warning. */ public const val MISSING_INDEX_ON_FOREIGN_KEY_CHILD: String = "ROOM_MISSING_FOREIGN_KEY_CHILD_INDEX" /** * Reported when a junction entity whose column is used in a `@Relation` field with a * `@Junction` does not contain an index. If the column is not covered by any index then a * full table scan might be performed when resolving the relationship. * * It is recommended that columns on entities used as junctions contain indices, otherwise Room * will print this warning. */ public const val MISSING_INDEX_ON_JUNCTION: String = "MISSING_INDEX_ON_JUNCTION" /** * Reported when a POJO has multiple constructors, one of which is a no-arg constructor. Room * will pick that one by default but will print this warning in case the constructor choice is * important. You can always guide Room to use the right constructor using the @Ignore * annotation. */ public const val DEFAULT_CONSTRUCTOR: String = "ROOM_DEFAULT_CONSTRUCTOR" /** * Reported when a @Query method returns a POJO that has relations but the method is not * annotated with @Transaction. Relations are run as separate queries and if the query is not * run inside a transaction, it might return inconsistent results from the database. */ public const val RELATION_QUERY_WITHOUT_TRANSACTION: String = "ROOM_RELATION_QUERY_WITHOUT_TRANSACTION" /** * Reported when an `@Entity` field's type do not exactly match the getter type. * For instance, in the following class: * * ``` * @Entity * class Foo { * ... * private val value: Boolean * public fun getValue(): Boolean { * return value == null ? false : value * } * } * ``` * * Trying to insert this entity into database will always set `value` column to * `false` when `Foo.value` is `null` since Room will use the `getValue` * method to read the value. So even thought the database column is nullable, it will never * be inserted as `null` if inserted as a `Foo` instance. */ public const val MISMATCHED_GETTER: String = "ROOM_MISMATCHED_GETTER_TYPE" /** * Reported when an `@Entity` field's type do not exactly match the setter type. * For instance, in the following class: * * ``` * @Entity * class Foo { * ... * private val value: Boolean * public fun setValue(value: Boolean) { * this.value = value * } * } * ``` * * If Room reads this entity from the database, it will always set `Foo.value` to * `false` when the column value is `null` since Room will use the `setValue` * method to write the value. */ public const val MISMATCHED_SETTER: String = "ROOM_MISMATCHED_SETTER_TYPE" /** * Reported when there is an ambiguous column on the result of a multimap query. */ public const val AMBIGUOUS_COLUMN_IN_RESULT: String = "ROOM_AMBIGUOUS_COLUMN_IN_RESULT" } @Deprecated("This type should not be instantiated as it contains only static methods. ") @SuppressWarnings("PrivateConstructorForUtilityClass") public constructor() }
room/room-common/src/main/java/androidx/room/RoomWarnings.kt
1468073587
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java package androidx.camera.camera2.pipe.testing import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.CameraId import androidx.camera.camera2.pipe.FrameNumber import androidx.camera.camera2.pipe.Request import androidx.camera.camera2.pipe.RequestMetadata import androidx.camera.camera2.pipe.CaptureSequence import androidx.camera.camera2.pipe.CaptureSequences.invokeOnRequests /** A CaptureSequence used for testing interactions with a [FakeCaptureSequenceProcessor] **/ data class FakeCaptureSequence( override val repeating: Boolean, override val cameraId: CameraId, override val captureRequestList: List<Request>, override val captureMetadataList: List<RequestMetadata>, val requestMetadata: Map<Request, RequestMetadata>, val defaultParameters: Map<*, Any?>, val requiredParameters: Map<*, Any?>, override val listeners: List<Request.Listener>, override val sequenceListener: CaptureSequence.CaptureSequenceListener, override var sequenceNumber: Int, ) : CaptureSequence<Request> { fun invokeOnSequenceCreated() = invokeOnRequests { requestMetadata, _, listener -> listener.onRequestSequenceCreated(requestMetadata) } fun invokeOnSequenceSubmitted() = invokeOnRequests { requestMetadata, _, listener -> listener.onRequestSequenceSubmitted(requestMetadata) } fun invokeOnSequenceAborted() = invokeOnRequests { requestMetadata, _, listener -> listener.onRequestSequenceAborted(requestMetadata) } fun invokeOnSequenceCompleted(frameNumber: FrameNumber) = invokeOnRequests { requestMetadata, _, listener -> listener.onRequestSequenceCompleted(requestMetadata, frameNumber) } }
camera/camera-camera2-pipe-testing/src/main/java/androidx/camera/camera2/pipe/testing/FakeCaptureSequence.kt
2710159522
package com.mooveit.kotlin.kotlintemplateproject.presentation.common.extensions infix fun Boolean.then(param: () -> Unit) = if (this) param else { }
app/src/main/java/com/mooveit/kotlin/kotlintemplateproject/presentation/common/extensions/BooleanExtension.kt
3967032093
package com.antyzero.cardcheck.localization import android.content.Context import android.os.Build import dagger.Module import dagger.Provides import java.util.* import javax.inject.Singleton @Singleton @Module class LocalizationModule { @Provides @Singleton fun provideLocalization(context: Context): Localization { return when (getLocale(context)) { Locale("pl", "PL") -> LocalizationPl() else -> LocalizationEn() } } private fun getLocale(context: Context): Locale { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { context.resources.configuration.locales.get(0) } else { @Suppress("DEPRECATION") context.resources.configuration.locale } } }
app/src/main/kotlin/com/antyzero/cardcheck/localization/LocalizationModule.kt
3771281326
package com.joyouskim.http import com.joyouskim.git.VertOutputStream import java.io.IOException import java.io.OutputStream /** * Created by jinyunzhe on 16/4/6. */ fun HttpRequest.consumeBody() { val header = this.getHeader(CONTENT_LENGTH) if ( 0 < this.getContentLength() || this.isChunked()) { val inputStream = this.getInputStream() try { while (0 < inputStream.skip(2048) || 0 <= inputStream.read()) { } } catch(e: IOException) { } finally { try { inputStream.close() } catch(e: IOException) { } } } } fun HttpRequest.isChunked(): Boolean { return "chunked" == this.getHeader(TRANSFER_ENCODING) } fun HttpRequest.getRemoteHost(): String { return this.remoteAddress().host() } fun HttpRequest.getContentType(): String { return this.getHeader(CONTENT_TYPE) } fun HttpResponse.setContentType(str: String) { this.putHeader(CONTENT_TYPE, str) } fun HttpRequest.getContentLength(): Int { return this.getHeader(CONTENT_LENGTH)?.toInt() ?: 0 } fun HttpResponse.getOut(): OutputStream { return VertOutputStream(this) } fun HttpResponse.reset(){ }
src/main/kotlin/com/joyouskim/http/HttpExtension.kt
3008953184
package com.percolate.sdk.api.request.vendor.instagram import com.percolate.sdk.api.BaseApiTest import com.percolate.sdk.api.request.vendor.instagram.params.InstagramMediaVendorParams import org.junit.Assert import org.junit.Test class InstagramVendorRequestTest : BaseApiTest() { @Test fun testMedia() { val instagramMedia = percolateApi .vendorInstagram() .media(InstagramMediaVendorParams("123")) .execute() .body(); val data = instagramMedia?.data?.comments?.data Assert.assertNotNull(data) Assert.assertEquals(3, data!!.size.toLong()) } @Test fun testComments() { val instagramMediaComments = percolateApi .vendorInstagram() .comments(InstagramMediaVendorParams("123")) .execute() .body(); val data = instagramMediaComments?.data Assert.assertNotNull(data) Assert.assertEquals(3, data!!.size.toLong()) } }
api/src/test/java/com/percolate/sdk/api/request/vendor/instagram/InstagramVendorRequestTest.kt
4051935685
/* * MaybeKt.kt * * Copyright (C) 2017 Retrograde Project * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.codebutler.retrograde.common.rx import com.gojuno.koptional.None import com.gojuno.koptional.Optional import com.gojuno.koptional.toOptional import io.reactivex.Maybe import io.reactivex.Single fun <T : Any> Maybe<T>.toSingleAsOptional(): Single<Optional<T>> = this.map { it.toOptional() }.toSingle(None)
retrograde-util/src/main/java/com/codebutler/retrograde/common/rx/MaybeKt.kt
3691942358
package org.jmailen.gradle.kotlinter.functional import org.gradle.testkit.runner.TaskOutcome.FAILED import org.gradle.testkit.runner.TaskOutcome.SUCCESS import org.gradle.testkit.runner.TaskOutcome.UP_TO_DATE import org.jmailen.gradle.kotlinter.functional.utils.editorConfig import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import java.io.File internal class KotlinProjectTest : WithGradleTest.Kotlin() { private lateinit var settingsFile: File private lateinit var buildFile: File private lateinit var sourceDir: File private lateinit var editorconfigFile: File private val pathPattern = "(.*\\.kt):\\d+:\\d+".toRegex() @BeforeEach fun setup() { settingsFile = testProjectDir.resolve("settings.gradle") buildFile = testProjectDir.resolve("build.gradle") sourceDir = testProjectDir.resolve("src/main/kotlin/").also(File::mkdirs) editorconfigFile = testProjectDir.resolve(".editorconfig") } @Test fun `lintKotlinMain fails when lint errors detected`() { settingsFile() buildFile() val className = "KotlinClass" kotlinSourceFile( "$className.kt", """ class $className { private fun hi(){ println ("hi") } } """.trimIndent(), ) buildAndFail("lintKotlinMain").apply { assertTrue(output.contains(".*$className.kt.* Lint error > \\[.*] Missing spacing before \"\\{\"".toRegex())) assertTrue(output.contains(".*$className.kt.* Lint error > \\[.*] Unexpected spacing before \"\\(\"".toRegex())) output.lines().filter { it.contains("Lint error") }.forEach { line -> val filePath = pathPattern.find(line)?.groups?.get(1)?.value.orEmpty() assertTrue(File(filePath).exists()) } assertEquals(FAILED, task(":lintKotlinMain")?.outcome) } } @Test fun `lintKotlinMain succeeds when no lint errors detected`() { settingsFile() buildFile() kotlinSourceFile( "KotlinClass.kt", """ class KotlinClass { private fun hi() { println("hi") } } """.trimIndent(), ) build("lintKotlinMain").apply { assertEquals(SUCCESS, task(":lintKotlinMain")?.outcome) } } @Test fun `formatKotlin reports formatted and unformatted files`() { settingsFile() buildFile() // language=kotlin val kotlinClass = """ import System.* class KotlinClass{ private fun hi() { out.println("Hello") } } """.trimIndent() kotlinSourceFile("KotlinClass.kt", kotlinClass) build("formatKotlin").apply { assertEquals(SUCCESS, task(":formatKotlinMain")?.outcome) output.lines().filter { it.contains("Format could not fix") }.forEach { line -> val filePath = pathPattern.find(line)?.groups?.get(1)?.value.orEmpty() assertTrue(File(filePath).exists()) } } } @Test fun `check task runs lintFormat`() { settingsFile() buildFile() kotlinSourceFile( "CustomObject.kt", """ object CustomObject """.trimIndent(), ) build("check").apply { assertEquals(SUCCESS, task(":lintKotlin")?.outcome) } } @Test fun `tasks up-to-date checks`() { settingsFile() buildFile() editorConfig() kotlinSourceFile( "CustomObject.kt", """ object CustomObject """.trimIndent(), ) build("lintKotlin").apply { assertEquals(SUCCESS, task(":lintKotlin")?.outcome) } build("lintKotlin").apply { assertEquals(UP_TO_DATE, task(":lintKotlin")?.outcome) } build("formatKotlin").apply { assertEquals(SUCCESS, task(":formatKotlin")?.outcome) } build("formatKotlin").apply { assertEquals(SUCCESS, task(":formatKotlin")?.outcome) } editorconfigFile.appendText("content=updated") build("lintKotlin").apply { assertEquals(SUCCESS, task(":lintKotlin")?.outcome) } build("lintKotlin").apply { assertEquals(UP_TO_DATE, task(":lintKotlin")?.outcome) } } @Test fun `plugin is compatible with configuration cache`() { settingsFile() buildFile() kotlinSourceFile( "CustomObject.kt", """ object CustomObject """.trimIndent(), ) build("lintKotlin", "--configuration-cache").apply { assertEquals(SUCCESS, task(":lintKotlin")?.outcome) assertTrue(output.contains("Configuration cache entry stored")) } build("lintKotlin", "--configuration-cache").apply { assertEquals(UP_TO_DATE, task(":lintKotlin")?.outcome) assertTrue(output.contains("Configuration cache entry reused.")) } build("formatKotlin", "--configuration-cache").apply { assertEquals(SUCCESS, task(":formatKotlin")?.outcome) assertTrue(output.contains("Configuration cache entry stored")) } build("formatKotlin", "--configuration-cache").apply { assertEquals(SUCCESS, task(":formatKotlin")?.outcome) assertTrue(output.contains("Configuration cache entry reused.")) } } private fun settingsFile() = settingsFile.apply { writeText("rootProject.name = 'kotlinter'") } private fun editorConfig() = editorconfigFile.apply { writeText(editorConfig) } private fun buildFile() = buildFile.apply { // language=groovy val buildscript = """ plugins { id 'org.jetbrains.kotlin.jvm' id 'org.jmailen.kotlinter' } repositories { mavenCentral() } """.trimIndent() writeText(buildscript) } private fun kotlinSourceFile(name: String, content: String) = File(sourceDir, name).apply { writeText(content) } }
src/test/kotlin/org/jmailen/gradle/kotlinter/functional/KotlinProjectTest.kt
3842552197
/* * Copyright (c) 2013 yvolk (Yuri Volkov), http://yurivolkov.com * * 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 MyDatabaseConverterExecutor 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.andstatus.app.data.converter import android.app.Activity import org.andstatus.app.backup.ProgressLogger import org.andstatus.app.context.MyContextHolder import org.andstatus.app.util.MyLog import org.andstatus.app.util.Taggable import java.util.concurrent.TimeUnit object DatabaseConverterController { val TAG: String = DatabaseConverterController::class.simpleName!! // TODO: Should be one object for atomic updates. start --- internal val upgradeLock: Any = Any() @Volatile internal var shouldTriggerDatabaseUpgrade = false /** Semaphore enabling uninterrupted system upgrade */ internal var upgradeEndTime = 0L internal var upgradeStarted = false private var upgradeEnded = false internal var upgradeEndedSuccessfully = false @Volatile internal var mProgressLogger: ProgressLogger = ProgressLogger.getEmpty(TAG) // end --- private const val SECONDS_BEFORE_UPGRADE_TRIGGERED = 5L private const val UPGRADE_LENGTH_SECONDS_MAX = 90 fun onUpgrade(upgradeParams: DatabaseUpgradeParams) { if (!shouldTriggerDatabaseUpgrade) { MyLog.v(this, "onUpgrade - Trigger not set yet") throw IllegalStateException("onUpgrade - Trigger not set yet") } synchronized(upgradeLock) { shouldTriggerDatabaseUpgrade = false stillUpgrading() } MyContextHolder.myContextHolder.getNow().isInForeground = true val databaseConverter = DatabaseConverter(mProgressLogger) val success = databaseConverter.execute(upgradeParams) synchronized(upgradeLock) { upgradeEnded = true upgradeEndedSuccessfully = success } if (!success) { throw ApplicationUpgradeException(databaseConverter.converterError) } } fun attemptToTriggerDatabaseUpgrade(upgradeRequestorIn: Activity) { val requestorName: String = Taggable.anyToTag(upgradeRequestorIn) var skip = false if (isUpgrading()) { MyLog.v( TAG, "Attempt to trigger database upgrade by " + requestorName + ": already upgrading" ) skip = true } if (!skip && !MyContextHolder.myContextHolder.getNow().initialized) { MyLog.v( TAG, "Attempt to trigger database upgrade by " + requestorName + ": not initialized yet" ) skip = true } if (!skip && acquireUpgradeLock(requestorName)) { val asyncUpgrade = AsyncUpgrade(upgradeRequestorIn, MyContextHolder.myContextHolder.isOnRestore()) if (MyContextHolder.myContextHolder.isOnRestore()) { asyncUpgrade.syncUpgrade() } else { asyncUpgrade.execute(TAG, Unit) } } } private fun acquireUpgradeLock(requestorName: String?): Boolean { var skip = false synchronized(upgradeLock) { if (isUpgrading()) { MyLog.v( TAG, "Attempt to trigger database upgrade by " + requestorName + ": already upgrading" ) skip = true } if (!skip && upgradeEnded) { MyLog.v( TAG, "Attempt to trigger database upgrade by " + requestorName + ": already completed " + if (upgradeEndedSuccessfully) " successfully" else "(failed)" ) skip = true if (!upgradeEndedSuccessfully) { upgradeEnded = false } } if (!skip) { MyLog.v(TAG, "Upgrade lock acquired for $requestorName") val startTime = System.currentTimeMillis() upgradeEndTime = startTime + TimeUnit.SECONDS.toMillis(SECONDS_BEFORE_UPGRADE_TRIGGERED) shouldTriggerDatabaseUpgrade = true } } return !skip } fun stillUpgrading() { var wasStarted: Boolean synchronized(upgradeLock) { wasStarted = upgradeStarted upgradeStarted = true upgradeEndTime = System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(UPGRADE_LENGTH_SECONDS_MAX.toLong()) } MyLog.w( TAG, (if (wasStarted) "Still upgrading" else "Upgrade started") + ". Wait " + UPGRADE_LENGTH_SECONDS_MAX + " seconds" ) } fun isUpgradeError(): Boolean { synchronized(upgradeLock) { if (upgradeEnded && !upgradeEndedSuccessfully) { return true } } return false } fun isUpgrading(): Boolean { synchronized(upgradeLock) { if (upgradeEndTime == 0L) { return false } val currentTime = System.currentTimeMillis() if (currentTime > upgradeEndTime) { MyLog.v(TAG, "Upgrade end time came") upgradeEndTime = 0L return false } } return true } }
app/src/main/kotlin/org/andstatus/app/data/converter/DatabaseConverterController.kt
491429564
package at.ac.tuwien.caa.docscan.ui.docviewer.documents import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import at.ac.tuwien.caa.docscan.databinding.FragmentDocumentsBinding import at.ac.tuwien.caa.docscan.logic.ConsumableEvent import at.ac.tuwien.caa.docscan.logic.DocumentPage import at.ac.tuwien.caa.docscan.logic.extractDocWithPages import at.ac.tuwien.caa.docscan.ui.base.BaseFragment import at.ac.tuwien.caa.docscan.ui.dialog.ADialog import at.ac.tuwien.caa.docscan.ui.dialog.DialogViewModel import at.ac.tuwien.caa.docscan.ui.dialog.isPositive import at.ac.tuwien.caa.docscan.ui.docviewer.DocumentViewerViewModel import org.koin.androidx.viewmodel.ext.android.sharedViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class DocumentsFragment : BaseFragment() { private var scroll = true private lateinit var adapter: DocumentAdapter private lateinit var binding: FragmentDocumentsBinding private val viewModel: DocumentsViewModel by viewModel() private val dialogViewModel: DialogViewModel by viewModel() private val sharedViewModel: DocumentViewerViewModel by sharedViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentDocumentsBinding.inflate(inflater, container, false) adapter = DocumentAdapter({ findNavController().navigate( DocumentsFragmentDirections.actionViewerDocumentsToViewerImages( DocumentPage( it.document.id, null ) ) ) }, { sharedViewModel.initDocumentOptions(it) }) binding.documentsList.adapter = adapter binding.documentsList.layoutManager = LinearLayoutManager(context) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observe() } private fun observe() { viewModel.observableDocuments.observe(viewLifecycleOwner) { adapter.submitList(it) if (it.isEmpty()) { binding.documentsEmptyLayout.visibility = View.VISIBLE binding.documentsList.visibility = View.INVISIBLE } else { binding.documentsList.visibility = View.VISIBLE binding.documentsEmptyLayout.visibility = View.INVISIBLE } if (scroll) { val position = (it.indexOfFirst { doc -> doc.document.isActive }) if (position != -1) { binding.documentsList.smoothScrollToPosition(position) } scroll = false } } dialogViewModel.observableDialogAction.observe( viewLifecycleOwner, ConsumableEvent { result -> when (result.dialogAction) { ADialog.DialogAction.CONFIRM_DELETE_DOCUMENT -> { if (result.isPositive()) { result.arguments.extractDocWithPages()?.let { doc -> viewModel.deleteDocument(doc) } } } else -> { // ignore } } }) } }
app/src/main/java/at/ac/tuwien/caa/docscan/ui/docviewer/documents/DocumentsFragment.kt
1683128580
package io.github.yusaka39.reversi.game.interfaces import io.github.yusaka39.reversi.game.Board import io.github.yusaka39.reversi.game.Grid import io.github.yusaka39.reversi.game.constants.Sides interface Player { val name: String val side: Sides fun handleTurn(board: Board, validMoves: List<Grid>): Grid }
game/src/main/kotlin/io/github/yusaka39/reversi/game/interfaces/Player.kt
22513324
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.messages.dto import com.google.gson.annotations.SerializedName import com.vk.sdk.api.base.dto.BaseLinkChat import kotlin.String /** * Item of a suggestions block * @param chat * @param trackCode */ data class MessagesChatSuggestion( @SerializedName("chat") val chat: BaseLinkChat, @SerializedName("track_code") val trackCode: String? = null )
api/src/main/java/com/vk/sdk/api/messages/dto/MessagesChatSuggestion.kt
3674932063
/* * Copyright (c) 2016 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.upnp.cds import net.mm2d.android.upnp.ControlPointWrapper import net.mm2d.upnp.Adapter.discoveryListener import net.mm2d.upnp.Adapter.eventListener import net.mm2d.upnp.ControlPoint import net.mm2d.upnp.Device import java.util.* import java.util.concurrent.atomic.AtomicBoolean /** * MediaServerのControlPoint機能。 * * ControlPointは継承しておらず、MediaServerとしてのインターフェースのみを提供する。 * * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ class MsControlPoint : ControlPointWrapper { private val discoveryListener = discoveryListener( { discoverDevice(it) }, { lostDevice(it) } ) private val eventListener = eventListener { service, _, properties -> val udn = service.device.udn val server = getDevice(udn) if (server == null || service.serviceId != Cds.CDS_SERVICE_ID) { return@eventListener } properties.forEach { if (it.first == Cds.CONTAINER_UPDATE_IDS) { onNotifyContainerUpdateIds(server, it.second) } else if (it.first == Cds.SYSTEM_UPDATE_ID) { onNotifySystemUpdateId(server, it.second) } } } private val initialized = AtomicBoolean() private val mediaServerMap: MutableMap<String, MediaServer> = Collections.synchronizedMap(LinkedHashMap()) private var msDiscoveryListener: MsDiscoveryListener? = null private var containerUpdateIdsListener: ContainerUpdateIdsListener? = null private var systemUpdateIdListener: SystemUpdateIdListener? = null /** * 保持しているMediaServerの個数を返す。 * * @return MediaServerの個数 */ override val deviceListSize: Int get() = mediaServerMap.size /** * MediaServerのリストを返す。 * * 内部Mapのコピーを返すため使用注意。 * * @return MediaServerのリスト。 */ override val deviceList: List<MediaServer> get() = synchronized(mediaServerMap) { mediaServerMap.values.toList() } /** * 機器発見のイベントを通知するリスナー。 */ interface MsDiscoveryListener { /** * 機器発見時に通知される。 * * @param server 発見したMediaServer */ fun onDiscover(server: MediaServer) /** * 機器喪失時に通知される。 * * @param server 喪失したMediaServer */ fun onLost(server: MediaServer) } /** * ContainerUpdateIDsのsubscribeイベントを通知するリスナー。 */ interface ContainerUpdateIdsListener { /** * ContainerUpdateIDsが通知されたときにコールされる。 * * @param server イベントを発行したMediaServer * @param ids 更新のあったID */ fun onContainerUpdateIds( server: MediaServer, ids: List<String> ) } /** * SystemUpdateIDのsubscribeイベントを通知するリスナー。 */ interface SystemUpdateIdListener { /** * SystemUpdateIDが通知されたときにコールされる。 * * @param server イベントを発行したMediaServer * @param id UpdateID */ fun onSystemUpdateId( server: MediaServer, id: String ) } private fun onNotifyContainerUpdateIds( server: MediaServer, value: String ) { containerUpdateIdsListener?.let { it -> val values = value.split(',') if (values.isEmpty() || values.size % 2 != 0) { return } it.onContainerUpdateIds(server, values.chunked(2) { it[0] }) } } private fun onNotifySystemUpdateId( server: MediaServer, value: String ) { systemUpdateIdListener?.onSystemUpdateId(server, value) } /** * MediaServerのファクトリーメソッド。 * * @param device Device * @return MediaServer */ private fun createMediaServer(device: Device): MediaServer = MediaServer(device) private fun discoverDevice(device: Device) { if (device.deviceType.startsWith(Cds.MS_DEVICE_TYPE)) { discoverMsDevice(device) return } for (embeddedDevice in device.deviceList) { discoverMsDevice(embeddedDevice) } } private fun discoverMsDevice(device: Device) { val server: MediaServer try { server = createMediaServer(device) } catch (ignored: IllegalArgumentException) { return } mediaServerMap[server.udn] = server msDiscoveryListener?.onDiscover(server) } private fun lostDevice(device: Device) { val server = mediaServerMap.remove(device.udn) ?: return msDiscoveryListener?.onLost(server) } /** * 機器発見の通知リスナーを登録する。 * * @param listener リスナー */ fun setMsDiscoveryListener(listener: MsDiscoveryListener?) { msDiscoveryListener = listener } /** * ContainerUpdateIdsの通知リスナーを登録する。 * * @param listener リスナー */ fun setContainerUpdateIdsListener(listener: ContainerUpdateIdsListener?) { containerUpdateIdsListener = listener } /** * SystemUpdateIdの通知リスナーを登録する。 * * @param listener リスナー */ fun setSystemUpdateIdListener(listener: SystemUpdateIdListener) { systemUpdateIdListener = listener } /** * 指定UDNに対応したMediaServerを返す。 * * @param udn UDN * @return MediaServer、見つからない場合null */ override fun getDevice(udn: String?): MediaServer? { return mediaServerMap[udn] } /** * 初期化する。 * * @param controlPoint ControlPoint */ override fun initialize(controlPoint: ControlPoint) { if (initialized.get()) { terminate(controlPoint) } initialized.set(true) mediaServerMap.clear() controlPoint.addDiscoveryListener(discoveryListener) controlPoint.addEventListener(eventListener) } /** * 終了する。 * * @param controlPoint ControlPoint */ override fun terminate(controlPoint: ControlPoint) { if (!initialized.getAndSet(false)) { return } controlPoint.removeDiscoveryListener(discoveryListener) controlPoint.removeEventListener(eventListener) mediaServerMap.clear() } }
mobile/src/main/java/net/mm2d/android/upnp/cds/MsControlPoint.kt
725882695
package com.secuso.privacyfriendlycodescanner.qrscanner import android.util.Log import androidx.multidex.MultiDexApplication import androidx.work.Configuration import com.secuso.privacyfriendlycodescanner.qrscanner.backup.BackupCreator import com.secuso.privacyfriendlycodescanner.qrscanner.backup.BackupRestorer import org.secuso.privacyfriendlybackup.api.pfa.BackupManager class PFACodeScannerApplication : MultiDexApplication(), Configuration.Provider { override fun onCreate() { super.onCreate() BackupManager.backupCreator = BackupCreator() BackupManager.backupRestorer = BackupRestorer() } override fun getWorkManagerConfiguration(): Configuration { return Configuration.Builder().setMinimumLoggingLevel(Log.INFO).build(); } }
app/src/main/java/com/secuso/privacyfriendlycodescanner/qrscanner/PFACodeScannerApplication.kt
2475570211
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2018, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ package assimp.postProcess import assimp.* import glm_.glm import glm_.max import glm_.vec2.Vec2 import glm_.vec3.Vec3 import kotlin.math.abs import kotlin.math.acos /** @file Defines a post processing step to triangulate all faces with more than three vertices. */ /** The TriangulateProcess splits up all faces with more than three indices * into triangles. You usually want this to happen because the graphics cards * need their data as triangles. */ class TriangulateProcess : BaseProcess() { /** Returns whether the processing step is present in the given flag field. * @param flags The processing flags the importer was called with. A bitwise combination of AiPostProcessStep. * @return true if the process is present in this flag fields, false if not. */ override fun isActive(flags: AiPostProcessStepsFlags): Boolean = flags has AiPostProcessStep.Triangulate /** Executes the post processing step on the given imported data. * At the moment a process is not supposed to fail. * @param scene The imported data to work at. */ override fun execute(scene: AiScene) { logger.debug("TriangulateProcess begin") var has = false for (a in 0 until scene.numMeshes) if (triangulateMesh(scene.meshes[a])) has = true if (has) logger.info("TriangulateProcess finished. All polygons have been triangulated.") else logger.debug("TriangulateProcess finished. There was nothing to be done.") } /** Triangulates the given mesh. * @param mesh The mesh to triangulate. */ fun triangulateMesh(mesh: AiMesh): Boolean { // TODO bug // Now we have aiMesh::mPrimitiveTypes, so this is only here for test cases if (mesh.primitiveTypes == 0) { var need = false for (a in 0 until mesh.numFaces) if (mesh.faces[a].size != 3) need = true if (!need) return false } else if (mesh.primitiveTypes hasnt AiPrimitiveType.POLYGON) return false // Find out how many output faces we'll get var numOut = 0 var maxOut = 0 var getNormals = true for (a in 0 until mesh.numFaces) { val face = mesh.faces[a] if (face.size <= 4) getNormals = false if (face.size <= 3) numOut++ else { numOut += face.size - 2 maxOut = maxOut max face.size } } // Just another check whether aiMesh::mPrimitiveTypes is correct assert(numOut != mesh.numFaces) var norOut: Array<Vec3>? = null // if we don't have normals yet, but expect them to be a cheap side product of triangulation anyway, allocate storage for them. if (!mesh.normals.isNotEmpty() && getNormals) { // XXX need a mechanism to inform the GenVertexNormals process to treat these normals as preprocessed per-face normals norOut = Array(mesh.numVertices) { Vec3(0) } mesh.normals = norOut.toMutableList() } // the output mesh will contain triangles, but no polys anymore mesh.primitiveTypes = mesh.primitiveTypes or AiPrimitiveType.TRIANGLE mesh.primitiveTypes = mesh.primitiveTypes wo AiPrimitiveType.POLYGON val out: Array<AiFace> = Array(numOut) { mutableListOf<Int>() } var curOut = 0 val tempVerts3d = Array(maxOut + 2) { Vec3() } /* temporary storage for vertices */ val tempVerts = Array(maxOut + 2) { Vec2() } // Apply vertex colors to represent the face winding? // #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING TODO // if (!pMesh->mColors[0]) // pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices] // else // new(pMesh->mColors[0]) aiColor4D[pMesh->mNumVertices] // // aiColor4D * clr = pMesh->mColors[0] // #endif // // #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS // FILE * fout = fopen(POLY_OUTPUT_FILE, "a") // #endif val verts = mesh.vertices // use std::unique_ptr to avoid slow std::vector<bool> specialiations val done = BooleanArray(maxOut) for (a in 0 until mesh.numFaces) { val face = mesh.faces[a] val idx = face var num = face.size var next = 0 var tmp = 0 var prev = num - 1 val max = num // Apply vertex colors to represent the face winding? // #ifdef AI_BUILD_TRIANGULATE_COLOR_FACE_WINDING // for (unsigned int i = 0; i < face.mNumIndices; ++i) { // aiColor4D& c = clr[idx[i]] // c.r = (i + 1) / (float) max // c.b = 1.f - c.r // } // #endif val lastFace = curOut // if it's a simple point,line or triangle: just copy it if (face.size <= 3) { val nFace = out[curOut++] nFace.clear() nFace += face face.clear() continue } // optimized code for quadrilaterals else if (face.size == 4) { /* quads can have at maximum one concave vertex. Determine this vertex (if it exists) and start tri-fanning from it. */ var startVertex = 0 for (i in 0..3) { val v0 = verts[face[(i + 3) % 4]] val v1 = verts[face[(i + 2) % 4]] val v2 = verts[face[(i + 1) % 4]] val v = verts[face[i]] val left = v0 - v val diag = v1 - v val right = v2 - v left.normalizeAssign() diag.normalizeAssign() right.normalizeAssign() val angle = acos(left dot diag) + acos(right dot diag) if (angle > glm.PIf) { // this is the concave point startVertex = i break } } val temp = IntArray(4) { face[it] } val nFace = out[curOut++] nFace.clear() nFace += temp[startVertex] nFace += temp[(startVertex + 1) % 4] nFace += temp[(startVertex + 2) % 4] val sFace = out[curOut++] sFace.clear() sFace += temp[startVertex] sFace += temp[(startVertex + 2) % 4] sFace += temp[(startVertex + 3) % 4] // prevent double deletion of the indices field face.clear() continue } else { /* A polygon with more than 3 vertices can be either concave or convex. Usually everything we're getting is convex and we could easily triangulate by tri-fanning. However, LightWave is probably the only modeling suite to make extensive use of highly concave, monster polygons ... so we need to apply the full 'ear cutting' algorithm to get it right. REQUIREMENT: polygon is expected to be simple and *nearly* planar. We project it onto a plane to get a 2d triangle. */ // Collect all vertices of of the polygon. tmp = 0 while (tmp < max) tempVerts3d[tmp] = verts[idx[tmp++]] // Get newell normal of the polygon. Store it for future use if it's a polygon-only mesh val n = Vec3() newellNormal(n, max, tempVerts3d) norOut?.let { tmp = 0 while (tmp < max) it[idx[tmp++]] = n } // Select largest normal coordinate to ignore for projection val aX = if (n.x > 0) n.x else -n.x val aY = if (n.y > 0) n.y else -n.y val aZ = if (n.z > 0) n.z else -n.z var ac = 0 var bc = 1 /* no z coord. projection to xy */ var inv = n.z if (aX > aY) { if (aX > aZ) { /* no x coord. projection to yz */ ac = 1; bc = 2 inv = n.x } } else if (aY > aZ) { /* no y coord. projection to zy */ ac = 2; bc = 0 inv = n.y } // Swap projection axes to take the negated projection vector into account if (inv < 0f) { val t = ac ac = bc bc = t } tmp = 0 while (tmp < max) { tempVerts[tmp][0] = verts[idx[tmp]][ac] tempVerts[tmp][1] = verts[idx[tmp]][bc] done[tmp++] = false } // #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS // // plot the plane onto which we mapped the polygon to a 2D ASCII pic // aiVector2D bmin, bmax // ArrayBounds(& temp_verts [0], max, bmin, bmax) // // char grid [POLY_GRID_Y][POLY_GRID_X + POLY_GRID_XPAD] // std::fill_n((char *) grid, POLY_GRID_Y * (POLY_GRID_X + POLY_GRID_XPAD), ' ') // // for (int i = 0; i < max; ++i) { // const aiVector2D & v =(tempVerts[i] - bmin) / (bmax - bmin) // const size_t x = static_cast<size_t>(v.x * (POLY_GRID_X - 1)), y = static_cast<size_t>(v.y*(POLY_GRID_Y-1)) // char * loc = grid[y] + x // if (grid[y][x] != ' ') { // for (;* loc != ' '; ++loc) // *loc++ = '_' // } // *(loc + ::ai_snprintf(loc, POLY_GRID_XPAD, "%i", i)) = ' ' // } // // // for (size_t y = 0; y < POLY_GRID_Y; ++y) { // grid[y][POLY_GRID_X + POLY_GRID_XPAD - 1] = '\0' // fprintf(fout, "%s\n", grid[y]) // } // // fprintf(fout, "\ntriangulation sequence: ") // #endif // FIXME: currently this is the slow O(kn) variant with a worst case // complexity of O(n^2) (I think). Can be done in O(n). while (num > 3) { // Find the next ear of the polygon var numFound = 0 var ear = next while (true) { // break after we looped two times without a positive match next = ear + 1 while (done[if (next >= max) 0.also { next = 0 } else next]) ++next if (next < ear) if (++numFound == 2) break val pnt1 = tempVerts[ear] val pnt0 = tempVerts[prev] val pnt2 = tempVerts[next] // Must be a convex point. Assuming ccw winding, it must be on the right of the line between p-1 and p+1. if (onLeftSideOfLine2D(pnt0, pnt2, pnt1)) { prev = ear ear = next continue } // and no other point may be contained in this triangle tmp = 0 while (tmp < max) { /* We need to compare the actual values because it's possible that multiple indexes in the polygon are referring to the same position. concave_polygon.obj is a sample FIXME: Use 'epsiloned' comparisons instead? Due to numeric inaccuracies in PointInTriangle() I'm guessing that it's actually possible to construct input data that would cause us to end up with no ears. The problem is, which epsilon? If we chose a too large value, we'd get wrong results */ val vtmp = tempVerts[tmp] if (vtmp !== pnt1 && vtmp !== pnt2 && vtmp !== pnt0 && pointInTriangle2D(pnt0, pnt1, pnt2, vtmp)) break ++tmp } if (tmp != max) { prev = ear ear = next continue } // this vertex is an ear break } if (numFound == 2) { /* Due to the 'two ear theorem', every simple polygon with more than three points must have 2 'ears'. Here's definitely something wrong ... but we don't give up yet. Instead we're continuing with the standard tri-fanning algorithm which we'd use if we had only convex polygons. That's life. */ logger.error("Failed to triangulate polygon (no ear found). Probably not a simple polygon?") // #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS // fprintf(fout, "critical error here, no ear found! ") // #endif num = 0 break // TODO unreachable // curOut -= (max - num) /* undo all previous work */ // for (tmp = 0; tmp < max - 2; ++tmp) { // aiFace& nface = *curOut++ // // nface.mNumIndices = 3 // if (!nface.mIndices) // nface.mIndices = new unsigned int[3] // // nface.mIndices[0] = 0 // nface.mIndices[1] = tmp + 1 // nface.mIndices[2] = tmp + 2 // // } // num = 0 // break } val nFace = out[curOut++] if (nFace.isEmpty()) for (i in 0..2) nFace += 0 // setup indices for the new triangle ... nFace[0] = prev nFace[1] = ear nFace[2] = next // exclude the ear from most further processing done[ear] = true --num } if (num > 0) { // We have three indices forming the last 'ear' remaining. Collect them. val nFace = out[curOut++] if (nFace.isEmpty()) for (i in 0..2) nFace += 0 tmp = 0 while (done[tmp]) ++tmp nFace[0] = tmp ++tmp while (done[tmp]) ++tmp nFace[1] = tmp ++tmp while (done[tmp]) ++tmp nFace[2] = tmp } } // #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS // // for (aiFace* f = lastFace; f != curOut; ++f) { // unsigned int * i = f->mIndices // fprintf(fout, " (%i %i %i)", i[0], i[1], i[2]) // } // // fprintf(fout, "\n*********************************************************************\n") // fflush(fout) // // #endif var f = lastFace while (f != curOut) { val i = out[f] // drop dumb 0-area triangles val abs = abs(getArea2D(tempVerts[i[0]], tempVerts[i[1]], tempVerts[i[2]])) if (abs < 1e-5f) { logger.debug("Dropping triangle with area 0") --curOut out[f].clear() var ff = f while (ff != curOut) { out[ff].clear() out[ff].addAll(out[ff + 1]) out[ff + 1].clear() ++ff } continue } i[0] = idx[i[0]] i[1] = idx[i[1]] i[2] = idx[i[2]] ++f } face.clear() } // #ifdef AI_BUILD_TRIANGULATE_DEBUG_POLYS TODO // fclose(fout) // #endif // kill the old faces mesh.faces.clear() // ... and store the new ones mesh.faces.addAll(out) mesh.numFaces = curOut /* not necessarily equal to numOut */ return true } }
src/main/kotlin/assimp/postProcess/TriangulateProcess.kt
2861055463
/* * Copyright (C) 2019-2020 Reece H. Dunn * * 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 uk.co.reecedunn.intellij.plugin.core.lang import com.intellij.lang.Language import com.intellij.lang.LanguageParserDefinitions import com.intellij.lang.ParserDefinition import com.intellij.openapi.fileTypes.FileNameMatcher import com.intellij.openapi.fileTypes.FileTypeManager import com.intellij.openapi.util.Key interface LanguageData { companion object { val KEY: Key<LanguageData> = Key.create("uk.co.reecedunn.intellij.plugin.key.languageData") } val associations: List<FileNameMatcher> val mimeTypes: Array<String> } fun Language.getAssociations(): List<FileNameMatcher> { val associations = associatedFileType?.let { FileTypeManager.getInstance().getAssociations(it) } ?: listOf() return if (associations.isEmpty()) this.getUserData(LanguageData.KEY)?.associations ?: listOf() else associations } fun Array<out Language>.getAssociations(): List<FileNameMatcher> { return asSequence().flatMap { language -> language.getAssociations().asSequence() }.toList() } fun Array<out Language>.findByAssociations(path: String): Language? = find { language -> language.getAssociations().find { association -> association.acceptsCharSequence(path) } != null } fun Language.getLanguageMimeTypes(): Array<String> { val mimeTypes = mimeTypes return if (mimeTypes.isEmpty()) this.getUserData(LanguageData.KEY)?.mimeTypes ?: mimeTypes else mimeTypes } fun Array<out Language>.findByMimeType(predicate: (String) -> Boolean): Language? = find { language -> language.getLanguageMimeTypes().find { predicate(it) } != null } val Language.parserDefinition: ParserDefinition get() = LanguageParserDefinitions.INSTANCE.forLanguage(this)
src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/lang/Language.kt
291457894
package org.stepik.android.view.course_reviews.ui.dialog import android.app.Activity import android.app.Dialog import android.content.Intent import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.core.widget.doAfterTextChanged import androidx.fragment.app.DialogFragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import kotlinx.android.synthetic.main.dialog_compose_course_review.* import kotlinx.android.synthetic.main.view_centered_toolbar.* import org.stepic.droid.R import org.stepic.droid.base.App import org.stepic.droid.ui.dialogs.LoadingProgressDialogFragment import org.stepic.droid.ui.util.setTintedNavigationIcon import org.stepic.droid.ui.util.snackbar import org.stepic.droid.util.ProgressHelper import org.stepik.android.domain.course_reviews.model.CourseReview import org.stepik.android.presentation.course_reviews.ComposeCourseReviewPresenter import org.stepik.android.presentation.course_reviews.ComposeCourseReviewView import ru.nobird.android.view.base.ui.extension.argument import ru.nobird.android.view.base.ui.extension.hideKeyboard import javax.inject.Inject class ComposeCourseReviewDialogFragment : DialogFragment(), ComposeCourseReviewView { companion object { const val TAG = "ComposeCourseReviewDialogFragment" const val CREATE_REVIEW_REQUEST_CODE = 3412 const val EDIT_REVIEW_REQUEST_CODE = CREATE_REVIEW_REQUEST_CODE + 1 const val ARG_COURSE_REVIEW = "course_review" fun newInstance(courseId: Long, courseReviewViewSource: String, courseReview: CourseReview?, courseRating: Float = -1f): DialogFragment = ComposeCourseReviewDialogFragment().apply { this.arguments = Bundle(2) .also { it.putParcelable(ARG_COURSE_REVIEW, courseReview) } this.courseId = courseId this.courseReviewViewSource = courseReviewViewSource this.courseRating = courseRating } } @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory private val composeCourseReviewPresenter: ComposeCourseReviewPresenter by viewModels { viewModelFactory } private var courseId: Long by argument() private var courseReviewViewSource: String by argument() private val courseReview: CourseReview? by lazy { arguments?.getParcelable<CourseReview>(ARG_COURSE_REVIEW) } private var courseRating: Float by argument() private val progressDialogFragment: DialogFragment = LoadingProgressDialogFragment.newInstance() override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.setCanceledOnTouchOutside(false) dialog.setCancelable(false) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) return dialog } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setStyle(STYLE_NO_TITLE, R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen) injectComponent() } private fun injectComponent() { App.component() .composeCourseReviewComponentBuilder() .build() .inject(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.dialog_compose_course_review, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { centeredToolbarTitle.setText(R.string.course_reviews_compose_title) centeredToolbar.setNavigationOnClickListener { dismiss() } centeredToolbar.setTintedNavigationIcon(R.drawable.ic_close_dark) centeredToolbar.inflateMenu(R.menu.compose_course_review_menu) centeredToolbar.setOnMenuItemClickListener { menuItem -> if (menuItem.itemId == R.id.course_review_submit) { submitCourseReview() true } else { false } } if (savedInstanceState == null) { courseRating .takeIf { it > -1 } ?.let { courseReviewRating.rating = courseRating } courseReview?.let { courseReviewEditText.setText(it.text) courseReviewRating.rating = it.score.toFloat() } } invalidateMenuState() courseReviewEditText.doAfterTextChanged { invalidateMenuState() } courseReviewRating.setOnRatingBarChangeListener { _, _, _ -> invalidateMenuState() } } override fun onStart() { super.onStart() dialog ?.window ?.let { window -> window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) window.setWindowAnimations(R.style.ThemeOverlay_AppTheme_Dialog_Fullscreen) } composeCourseReviewPresenter.attachView(this) } override fun onStop() { composeCourseReviewPresenter.detachView(this) super.onStop() } private fun submitCourseReview() { courseReviewEditText.hideKeyboard() val oldCourseReview = courseReview val text = courseReviewEditText.text?.toString() val score = courseReviewRating.rating.toInt() if (oldCourseReview == null) { val courseReview = CourseReview( course = courseId, text = text, score = score ) composeCourseReviewPresenter.createCourseReview(courseReview, courseReviewViewSource) } else { val courseReview = oldCourseReview .copy( text = text, score = score ) composeCourseReviewPresenter.updateCourseReview(oldCourseReview, courseReview, courseReviewViewSource) } } private fun invalidateMenuState() { centeredToolbar.menu.findItem(R.id.course_review_submit)?.isEnabled = !courseReviewEditText.text.isNullOrEmpty() && courseReviewRating.rating > 0 } override fun setState(state: ComposeCourseReviewView.State) { when (state) { ComposeCourseReviewView.State.Idle -> ProgressHelper.dismiss(childFragmentManager, LoadingProgressDialogFragment.TAG) ComposeCourseReviewView.State.Loading -> ProgressHelper.activate(progressDialogFragment, childFragmentManager, LoadingProgressDialogFragment.TAG) is ComposeCourseReviewView.State.Complete -> { ProgressHelper.dismiss(childFragmentManager, LoadingProgressDialogFragment.TAG) targetFragment ?.onActivityResult( targetRequestCode, Activity.RESULT_OK, Intent().putExtra(ARG_COURSE_REVIEW, state.courseReview) ) dismiss() } } } override fun showNetworkError() { view?.snackbar(messageRes = R.string.connectionProblems) } }
app/src/main/java/org/stepik/android/view/course_reviews/ui/dialog/ComposeCourseReviewDialogFragment.kt
3178143761
package org.stepik.android.view.step_quiz_sorting.ui.fragment import android.view.View import androidx.fragment.app.Fragment import kotlinx.android.synthetic.main.layout_step_quiz_sorting.* import org.stepic.droid.R import org.stepik.android.presentation.step_quiz.StepQuizFeature import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFormDelegate import org.stepik.android.view.step_quiz.ui.fragment.DefaultStepQuizFragment import org.stepik.android.view.step_quiz_sorting.ui.delegate.SortingStepQuizFormDelegate import ru.nobird.android.presentation.redux.container.ReduxView class SortingStepQuizFragment : DefaultStepQuizFragment(), ReduxView<StepQuizFeature.State, StepQuizFeature.Action.ViewAction> { companion object { fun newInstance(stepId: Long): Fragment = SortingStepQuizFragment() .apply { this.stepId = stepId } } override val quizLayoutRes: Int = R.layout.layout_step_quiz_sorting override val quizViews: Array<View> get() = arrayOf(sortingRecycler) override fun createStepQuizFormDelegate(view: View): StepQuizFormDelegate = SortingStepQuizFormDelegate(view, onQuizChanged = ::syncReplyState) }
app/src/main/java/org/stepik/android/view/step_quiz_sorting/ui/fragment/SortingStepQuizFragment.kt
686420184
class Book(val name: String) : Comparable<Book> { override fun compareTo(other: Book) = name.compareTo(other.name) } fun box() = if(Book("239").compareTo(Book("932")) != 0) "OK" else "fail"
backend.native/tests/external/codegen/box/primitiveTypes/kt887.kt
676597789
@Suppress("NOTHING_TO_INLINE") inline fun bar(block: () -> String) : String { return block() } fun bar2() : String { return bar { return "def" } } fun main(args: Array<String>) { println(bar2()) }
backend.native/tests/codegen/inline/inline20.kt
709978647
/* * Copyright (c) 2017 Evident Solutions Oy * * 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 fi.evident.dalesbred.plugin.idea.utils import com.intellij.patterns.ElementPattern import com.intellij.patterns.PsiJavaPatterns.psiClass import com.intellij.patterns.PsiJavaPatterns.psiMethod import com.intellij.patterns.PsiMethodPattern import com.intellij.patterns.StandardPatterns import com.intellij.patterns.StandardPatterns.or import com.intellij.patterns.StandardPatterns.string import com.intellij.psi.PsiMethod private object ClassNames { val CLASS = "java.lang.Class" val STRING = "java.lang.String" val OBJECT_ARGS = "java.lang.Object..." val DATABASE = "org.dalesbred.Database" val SQL_QUERY = "org.dalesbred.query.SqlQuery" val ROW_MAPPER = "org.dalesbred.result.RowMapper" val RESULT_SET_PROCESSOR = "org.dalesbred.result.ResultSetProcessor" } private val QUERY_AND_ARGS = arrayOf(ClassNames.STRING, ClassNames.OBJECT_ARGS) private val databaseClass = psiClass().withQualifiedName(ClassNames.DATABASE) private val sqlQueryClass = psiClass().withQualifiedName(ClassNames.SQL_QUERY) val findMethod: ElementPattern<PsiMethod> by lazy { val generalName = string().oneOf("findUnique", "findUniqueOrNull", "findOptional", "findAll") val withoutRowMapperName = string().oneOf("findUniqueInt", "findUniqueLong", "findUniqueBoolean", "findTable") or( databaseMethod(generalName).withParameters(ClassNames.CLASS, *QUERY_AND_ARGS), databaseMethod(generalName).withParameters(ClassNames.CLASS, ClassNames.SQL_QUERY), databaseMethod(generalName).withParameters(ClassNames.ROW_MAPPER, *QUERY_AND_ARGS), databaseMethod(generalName).withParameters(ClassNames.ROW_MAPPER, ClassNames.SQL_QUERY), databaseMethod(withoutRowMapperName).withParameters(*QUERY_AND_ARGS), databaseMethod(withoutRowMapperName).withParameters(ClassNames.SQL_QUERY), databaseMethod("findMap").withParameters(ClassNames.CLASS, ClassNames.CLASS, *QUERY_AND_ARGS), databaseMethod("findMap").withParameters(ClassNames.CLASS, ClassNames.CLASS, ClassNames.SQL_QUERY)) } val sqlQueryMethod: ElementPattern<PsiMethod> = psiMethod().definedInClass(sqlQueryClass).withName("query").withParameters(*QUERY_AND_ARGS) val executeQueryMethod: ElementPattern<PsiMethod> = or( databaseMethod("executeQuery").withParameters(ClassNames.RESULT_SET_PROCESSOR, *QUERY_AND_ARGS), databaseMethod("executeQuery").withParameters(ClassNames.RESULT_SET_PROCESSOR, ClassNames.SQL_QUERY)) val updateMethod: ElementPattern<PsiMethod> = databaseMethod("update").withParameters(*QUERY_AND_ARGS) val updateAndProcessGeneratedKeysMethod: ElementPattern<PsiMethod> = or( databaseMethod("updateAndProcessGeneratedKeys").withParameters(ClassNames.RESULT_SET_PROCESSOR, *QUERY_AND_ARGS), databaseMethod("updateAndProcessGeneratedKeys").withParameters(ClassNames.RESULT_SET_PROCESSOR, ClassNames.SQL_QUERY)) private fun findMethodGeneral(): ElementPattern<PsiMethod> { val namePattern = string().oneOf("findUnique", "findUniqueOrNull", "findOptional", "findAll") return or( databaseMethod(namePattern).withParameters(ClassNames.CLASS, *QUERY_AND_ARGS), databaseMethod(namePattern).withParameters(ClassNames.CLASS, ClassNames.SQL_QUERY), databaseMethod(namePattern).withParameters(ClassNames.ROW_MAPPER, *QUERY_AND_ARGS), databaseMethod(namePattern).withParameters(ClassNames.ROW_MAPPER, ClassNames.SQL_QUERY)) } private fun databaseMethod(name: String): PsiMethodPattern = databaseMethod(StandardPatterns.`object`(name)) private fun databaseMethod(name: ElementPattern<String>): PsiMethodPattern = psiMethod().definedInClass(databaseClass).withName(name)
src/main/kotlin/fi/evident/dalesbred/plugin/idea/utils/DalesbredPatterns.kt
504350248
package su.jfdev.anci.event import su.jfdev.anci.service.* @Service interface EventService { fun createLoop(): EventLoop fun <E: Any> createBus(eventLoop: EventLoop): EventBus<E> companion object: EventService by service() }
event/src/api/kotlin/su/jfdev/anci/event/EventService.kt
4201253437
package eu.kanade.tachiyomi.ui.browse.source import androidx.compose.runtime.Composable import eu.kanade.domain.source.model.Source import eu.kanade.presentation.browse.SourcesFilterScreen import eu.kanade.tachiyomi.ui.base.controller.FullComposeController class SourceFilterController : FullComposeController<SourcesFilterPresenter>() { override fun createPresenter(): SourcesFilterPresenter = SourcesFilterPresenter() @Composable override fun ComposeContent() { SourcesFilterScreen( navigateUp = router::popCurrentController, presenter = presenter, onClickLang = { language -> presenter.toggleLanguage(language) }, onClickSource = { source -> presenter.toggleSource(source) }, ) } } sealed class FilterUiModel { data class Header(val language: String, val enabled: Boolean) : FilterUiModel() data class Item(val source: Source, val enabled: Boolean) : FilterUiModel() }
app/src/main/java/eu/kanade/tachiyomi/ui/browse/source/SourcesFilterController.kt
3959364064
package com.apollographql.apollo3 import com.apollographql.apollo3.api.cache.http.HttpCacheRecord import com.apollographql.apollo3.api.cache.http.HttpCacheRecordEditor import com.apollographql.apollo3.api.cache.http.HttpCacheStore import com.apollographql.apollo3.cache.http.internal.DiskLruCache import com.apollographql.apollo3.cache.http.internal.FileSystem import okio.Buffer import okio.Sink import okio.Source import okio.Timeout import java.io.File import java.io.IOException class FaultyHttpCacheStore(fileSystem: FileSystem) : HttpCacheStore { private val cache: DiskLruCache val faultySource = FaultySource() val faultySink = FaultySink() var failStrategy: FailStrategy? = null @Throws(IOException::class) override fun cacheRecord(cacheKey: String): HttpCacheRecord? { val snapshot = cache[cacheKey] ?: return null return object : HttpCacheRecord { override fun headerSource(): Source { return if (failStrategy == FailStrategy.FAIL_HEADER_READ) { faultySource } else { snapshot.getSource(ENTRY_HEADERS) } } override fun bodySource(): Source { return if (failStrategy == FailStrategy.FAIL_BODY_READ) { faultySource } else { snapshot.getSource(ENTRY_BODY) } } override fun close() { snapshot.close() } } } @Throws(IOException::class) override fun cacheRecordEditor(cacheKey: String): HttpCacheRecordEditor? { val editor = cache.edit(cacheKey) ?: return null return object : HttpCacheRecordEditor { override fun headerSink(): Sink { return if (failStrategy == FailStrategy.FAIL_HEADER_WRITE) { faultySink } else { editor.newSink(ENTRY_HEADERS) } } override fun bodySink(): Sink { return if (failStrategy == FailStrategy.FAIL_BODY_WRITE) { faultySink } else { editor.newSink(ENTRY_BODY) } } @Throws(IOException::class) override fun abort() { editor.abort() } @Throws(IOException::class) override fun commit() { editor.commit() } } } @Throws(IOException::class) override fun delete() { cache.delete() } @Throws(IOException::class) override fun remove(cacheKey: String) { cache.remove(cacheKey) } fun failStrategy(failStrategy: FailStrategy?) { this.failStrategy = failStrategy } enum class FailStrategy { FAIL_HEADER_READ, FAIL_BODY_READ, FAIL_HEADER_WRITE, FAIL_BODY_WRITE } class FaultySource : Source { @Throws(IOException::class) override fun read(sink: Buffer, byteCount: Long): Long { throw IOException("failed to read") } override fun timeout(): Timeout { return Timeout() } @Throws(IOException::class) override fun close() { } } class FaultySink : Sink { @Throws(IOException::class) override fun write(source: Buffer, byteCount: Long) { throw IOException("failed to write") } @Throws(IOException::class) override fun flush() { } override fun timeout(): Timeout { return Timeout() } @Throws(IOException::class) override fun close() { } } companion object { private const val VERSION = 99991 private const val ENTRY_HEADERS = 0 private const val ENTRY_BODY = 1 private const val ENTRY_COUNT = 2 } init { cache = DiskLruCache.create(fileSystem, File("/cache/"), VERSION, ENTRY_COUNT, Int.MAX_VALUE.toLong()) } }
composite/integration-tests/src/testShared/kotlin/com/apollographql/apollo3/FaultyHttpCacheStore.kt
2574624275
package xyz.capybara.clamav.commands.scan import java.nio.ByteBuffer import java.nio.charset.StandardCharsets internal class ContScan(private val path: String) : ScanCommand() { override val commandString get() = "CONTSCAN" override val format get() = CommandFormat.NEW_LINE override val rawCommand: ByteBuffer get() = ByteBuffer.wrap("${format.prefix}$commandString $path${format.terminator}".toByteArray(StandardCharsets.US_ASCII)) }
src/main/kotlin/xyz/capybara/clamav/commands/scan/ContScan.kt
4026618030
package br.com.maiconhellmann.pomodoro.injection.component import android.app.Application import android.content.Context import br.com.maiconhellmann.pomodoro.data.DataManager import br.com.maiconhellmann.pomodoro.data.local.DatabaseHelper import br.com.maiconhellmann.pomodoro.injection.ApplicationContext import br.com.maiconhellmann.pomodoro.injection.module.ApplicationModule import br.com.maiconhellmann.pomodoro.injection.module.DataModule import br.com.maiconhellmann.pomodoro.injection.module.PresenterModule import dagger.Component import javax.inject.Singleton @Singleton @Component(modules = arrayOf(ApplicationModule::class, DataModule::class)) interface ApplicationComponent { //services @ApplicationContext fun context(): Context fun application(): Application fun databaseHelper(): DatabaseHelper fun dataManager(): DataManager operator fun plus(presenterModule: PresenterModule): ConfigPersistentComponent }
app/src/main/kotlin/br/com/maiconhellmann/pomodoro/injection/component/ApplicationComponent.kt
3456560653
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.core.moveCaret import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.SelfTargetingIntention import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.startOffset class FlattenWhenIntention : SelfTargetingIntention<KtWhenExpression>( KtWhenExpression::class.java, KotlinBundle.lazyMessage("flatten.when.expression") ) { override fun isApplicableTo(element: KtWhenExpression, caretOffset: Int): Boolean { val subject = element.subjectExpression if (subject != null && subject !is KtNameReferenceExpression) return false if (!KtPsiUtil.checkWhenExpressionHasSingleElse(element)) return false val elseEntry = element.entries.singleOrNull { it.isElse } ?: return false val innerWhen = elseEntry.expression as? KtWhenExpression ?: return false if (!subject.matches(innerWhen.subjectExpression)) return false if (!KtPsiUtil.checkWhenExpressionHasSingleElse(innerWhen)) return false return elseEntry.startOffset <= caretOffset && caretOffset <= innerWhen.whenKeyword.endOffset } override fun applyTo(element: KtWhenExpression, editor: Editor?) { val subjectExpression = element.subjectExpression val nestedWhen = element.elseExpression as KtWhenExpression val outerEntries = element.entries val innerEntries = nestedWhen.entries val whenExpression = KtPsiFactory(element).buildExpression { appendFixedText("when") if (subjectExpression != null) { appendFixedText("(").appendExpression(subjectExpression).appendFixedText(")") } appendFixedText("{\n") for (entry in outerEntries) { if (entry.isElse) continue appendNonFormattedText(entry.text) appendFixedText("\n") } for (entry in innerEntries) { appendNonFormattedText(entry.text) appendFixedText("\n") } appendFixedText("}") } as KtWhenExpression val newWhen = element.replaced(whenExpression) val firstNewEntry = newWhen.entries[outerEntries.size - 1] editor?.moveCaret(firstNewEntry.textOffset) } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FlattenWhenIntention.kt
338893152
package com.intellij.ide.starter.runner import com.intellij.ide.starter.ci.CIServer import com.intellij.ide.starter.di.di import com.intellij.ide.starter.ide.* import com.intellij.ide.starter.models.IdeInfo import com.intellij.ide.starter.models.IdeProduct import com.intellij.ide.starter.models.TestCase import com.intellij.ide.starter.path.GlobalPaths import com.intellij.ide.starter.path.IDEDataPaths import com.intellij.ide.starter.utils.catchAll import com.intellij.ide.starter.utils.logOutput import org.kodein.di.direct import org.kodein.di.factory import org.kodein.di.instance import java.io.Closeable import kotlin.io.path.div /** * [ciServer] - use [NoCIServer] for only local run. Otherwise - pass implementation of CIServer */ interface TestContainer<T> : Closeable { val ciServer: CIServer var useLatestDownloadedIdeBuild: Boolean val allContexts: MutableList<IDETestContext> val setupHooks: MutableList<IDETestContext.() -> IDETestContext> override fun close() { for (context in allContexts) { catchAll { context.paths.close() } } } /** * Allows to apply the common configuration to all created IDETestContext instances */ fun withSetupHook(hook: IDETestContext.() -> IDETestContext): T = apply { setupHooks += hook } as T /** * Makes the test use the latest available locally IDE build for testing. */ fun useLatestDownloadedIdeBuild(): T = apply { assert(!ciServer.isBuildRunningOnCI) useLatestDownloadedIdeBuild = true } as T fun resolveIDE(ideInfo: IdeInfo): Pair<String, InstalledIDE> { return di.direct.factory<IdeInfo, IdeInstallator>().invoke(ideInfo).install(ideInfo) } /** Starting point to run your test */ fun initializeTestRunner(testName: String, testCase: TestCase): IDETestContext { check(allContexts.none { it.testName == testName }) { "Test $testName is already initialized. Use another name." } logOutput("Resolving IDE build for $testName...") val (buildNumber, ide) = resolveIDE(testCase.ideInfo) require(ide.productCode == testCase.ideInfo.productCode) { "Product code of $ide must be the same as for $testCase" } val testDirectory = (di.direct.instance<GlobalPaths>().testsDirectory / "${testCase.ideInfo.productCode}-$buildNumber") / testName val paths = IDEDataPaths.createPaths(testName, testDirectory, testCase.useInMemoryFileSystem) logOutput("Using IDE paths for $testName: $paths") logOutput("IDE to run for $testName: $ide") val projectHome = testCase.projectInfo?.resolveProjectHome() val context = IDETestContext(paths, ide, testCase, testName, projectHome, patchVMOptions = { this }, ciServer = ciServer) allContexts += context val baseContext = when (testCase.ideInfo == IdeProduct.AI.ideInfo) { true -> context .addVMOptionsPatch { overrideDirectories(paths) .withEnv("STUDIO_VM_OPTIONS", ide.patchedVMOptionsFile.toString()) } false -> context .disableInstantIdeShutdown() .disableFusSendingOnIdeClose() .disableJcef() .disableLinuxNativeMenuForce() .withGtk2OnLinux() .disableGitLogIndexing() .enableSlowOperationsInEdtInTests() .collectOpenTelemetry() .addVMOptionsPatch { overrideDirectories(paths) } } return setupHooks.fold(baseContext.updateGeneralSettings()) { acc, hook -> acc.hook() } } }
tools/intellij.ide.starter/src/com/intellij/ide/starter/runner/TestContainer.kt
3644647758
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ide.actions.navbar import com.intellij.ide.ui.NavBarLocation import com.intellij.ide.ui.UISettings import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.ToggleAction import com.intellij.openapi.project.DumbAware import com.intellij.ui.ExperimentalUI abstract class NavBarLocationAction(private val location: NavBarLocation) : ToggleAction(), DumbAware { override fun isSelected(e: AnActionEvent): Boolean { val settings = UISettings.getInstance() return settings.showNavigationBar && settings.navBarLocation == location } override fun setSelected(e: AnActionEvent, state: Boolean) { UISettings.getInstance().let { it.navBarLocation = location it.showNavigationBar = true it.fireUISettingsChanged() } } override fun update(e: AnActionEvent) { if (!ExperimentalUI.isNewUI()) { e.presentation.isEnabledAndVisible = false return } super.update(e) } } class NavBarTopLocationAction : NavBarLocationAction(NavBarLocation.TOP) class NavBarBottomLocationAction : NavBarLocationAction(NavBarLocation.BOTTOM) class HideNavBarAction : ToggleAction(), DumbAware { override fun isSelected(e: AnActionEvent): Boolean = !UISettings.getInstance().showNavigationBar override fun setSelected(e: AnActionEvent, state: Boolean) { UISettings.getInstance().let { it.showNavigationBar = false it.fireUISettingsChanged() } } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } }
platform/lang-impl/src/com/intellij/ide/actions/navbar/NavBarLocationAction.kt
2486461835
/* * 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 androidx.test.espresso.device.dagger import androidx.test.espresso.device.context.ActionContext import androidx.test.espresso.device.context.InstrumentationTestActionContext import androidx.test.espresso.device.controller.DeviceControllerOperationException import androidx.test.espresso.device.controller.emulator.EmulatorController import androidx.test.espresso.device.controller.PhysicalDeviceController import androidx.test.espresso.device.controller.emulator.EmulatorGrpcConn import androidx.test.espresso.device.controller.emulator.EmulatorGrpcConnImpl import androidx.test.espresso.device.util.isTestDeviceAnEmulator import androidx.test.internal.platform.ServiceLoaderWrapper import androidx.test.platform.app.InstrumentationRegistry import androidx.test.platform.device.DeviceController import dagger.Module import dagger.Provides import java.lang.reflect.Method import javax.inject.Singleton /** Dagger module for DeviceController. */ @Module internal class DeviceControllerModule { @Provides @Singleton fun provideActionContext(): ActionContext { return InstrumentationTestActionContext() } @Provides @Singleton fun provideDeviceController(): DeviceController { val platformDeviceController: androidx.test.platform.device.DeviceController? = ServiceLoaderWrapper.loadSingleServiceOrNull( androidx.test.platform.device.DeviceController::class.java ) if (platformDeviceController == null) { if (isTestDeviceAnEmulator()) { val connection = getEmulatorConnection() return EmulatorController(connection.emulatorController()) } else { return PhysicalDeviceController() } } else { return EspressoDeviceControllerAdpater(platformDeviceController) } } private fun getEmulatorConnection(): EmulatorGrpcConn { val args = InstrumentationRegistry.getArguments() var grpcPortString = args.getString(EmulatorGrpcConn.ARGS_GRPC_PORT) var grpcPort = if (grpcPortString != null && grpcPortString.toInt() > 0) { grpcPortString.toInt() } else { getEmulatorGRPCPort() } return EmulatorGrpcConnImpl( EmulatorGrpcConn.EMULATOR_ADDRESS, grpcPort, args.getString(EmulatorGrpcConn.ARGS_GRPC_TOKEN, ""), args.getString(EmulatorGrpcConn.ARGS_GRPC_CER, ""), args.getString(EmulatorGrpcConn.ARGS_GRPC_KEY, ""), args.getString(EmulatorGrpcConn.ARGS_GRPC_CA, "") ) } /* Gets the emulator gRPC port for emulators running in g3 */ private fun getEmulatorGRPCPort(): Int { val clazz = Class.forName("android.os.SystemProperties") val getter: Method = clazz.getMethod("get", String::class.java) var gRpcPort = getter.invoke(clazz, "mdevx.grpc_guest_port") as String if (gRpcPort.isBlank()) { throw DeviceControllerOperationException( "Unable to connect to Emulator gRPC port. Please make sure the controller gRPC service is" + " enabled on the emulator." ) } return gRpcPort.toInt() } private class EspressoDeviceControllerAdpater( val deviceController: androidx.test.platform.device.DeviceController ) : DeviceController { override fun setDeviceMode(deviceMode: Int) { deviceController.setDeviceMode(deviceMode) } override fun setScreenOrientation(screenOrientation: Int) { deviceController.setScreenOrientation(screenOrientation) } } }
espresso/device/java/androidx/test/espresso/device/dagger/DeviceControllerModule.kt
4065304457
package nl.jstege.adventofcode.aoc2017.days import nl.jstege.adventofcode.aoccommon.days.Day /** * * @author Jelle Stege */ class Day18 : Day(title = "Duet") { override fun first(input: Sequence<String>): Any {//TODO: implement return 3188 } override fun second(input: Sequence<String>): Any {//TODO: implement return 7112 } }
aoc-2017/src/main/kotlin/nl/jstege/adventofcode/aoc2017/days/Day18.kt
1145888490
package nl.jstege.adventofcode.aoc2017.days import nl.jstege.adventofcode.aoccommon.utils.DayTester /** * Test for Day19 * @author Jelle Stege */ class Day19Test : DayTester(Day19())
aoc-2017/src/test/kotlin/nl/jstege/adventofcode/aoc2017/days/Day19Test.kt
1041101898
package org.hexworks.zircon.examples.fragments.table enum class Height { TALL, SHORT }
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/fragments/table/Height.kt
2407727479
/* Copyright (C) 2018 Daniel Vrátil <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cz.dvratil.fbeventsync import android.accounts.Account import android.accounts.AccountManager import android.accounts.OnAccountsUpdateListener import android.app.Activity import android.content.ContentResolver import android.content.Context import android.provider.CalendarContract import android.support.v7.widget.RecyclerView import android.view.View import android.view.ViewGroup import android.widget.TextView import android.view.LayoutInflater import android.widget.Button import android.widget.ImageView import android.widget.ProgressBar class AccountAdapter(private var mContext: Context) : RecyclerView.Adapter<AccountAdapter.ViewHolder>() , OnAccountsUpdateListener { class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { var name = view.findViewById<TextView>(R.id.account_card_name) var syncBtn = view.findViewById<Button>(R.id.account_card_sync_btn) var removeBtn = view.findViewById<Button>(R.id.account_card_remove_btn) var syncIndicator = view.findViewById<ProgressBar>(R.id.account_card_sync_progress) var avatarView = view.findViewById<ImageView>(R.id.account_card_avatar) } data class AccountData(var account: Account, var isSyncing: Boolean) { fun id() = account.name.hashCode().toLong() } private val mAccountManager = AccountManager.get(mContext) private var mAccounts: MutableList<AccountData> init { setHasStableIds(true) ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE) { // FIXME: Is this safe? (mContext as Activity).runOnUiThread(Runnable { checkSyncStatus() }) } mAccounts = mutableListOf() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.account_card, parent, false)) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val account = mAccounts[position] holder.name.text = account.account.name holder.syncBtn.isEnabled = !account.isSyncing holder.syncIndicator.visibility = if (account.isSyncing) View.VISIBLE else View.GONE /*AvatarProvider.getAvatar(mContext, account.account, { holder.avatarView.setImageDrawable(it) })*/ holder.syncBtn.setOnClickListener { CalendarSyncAdapter.requestSync(mContext, account.account) } holder.removeBtn.setOnClickListener{ Authenticator.removeAccount(mContext, account.account) } } override fun getItemCount(): Int = mAccounts.count() // OnAccountUpdateListener interface override fun onAccountsUpdated(accounts: Array<out Account>) { val accountType = mContext.getString(R.string.account_type) mAccounts.clear() for (account in accounts.filter { it.type == accountType }) { mAccounts.add(AccountData(account, ContentResolver.isSyncActive(account, CalendarContract.AUTHORITY))) } notifyDataSetChanged() } private fun checkSyncStatus() { for (i in 0..(mAccounts.count() - 1)) { val syncing = ContentResolver.isSyncActive(mAccounts[i].account, CalendarContract.AUTHORITY) if (mAccounts[i].isSyncing != syncing) { mAccounts[i].isSyncing = syncing notifyItemChanged(i) } } } override fun getItemId(position: Int): Long = mAccounts[position].id() }
app/src/main/java/cz/dvratil/fbeventsync/AccountAdapter.kt
2109298565
// 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.run import com.intellij.execution.application.JvmMainMethodRunConfigurationOptions import com.intellij.execution.configurations.ConfigurationTypeUtil.findConfigurationType import com.intellij.execution.configurations.JavaRunConfigurationModule import com.intellij.execution.configurations.SimpleConfigurationType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NotNullLazyValue import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.KotlinRunConfigurationsBundle.message class KotlinRunConfigurationType : SimpleConfigurationType( "JetRunConfigurationType", message("language.name.kotlin"), message("language.name.kotlin"), NotNullLazyValue.createValue { KotlinIcons.SMALL_LOGO } ) { override fun createTemplateConfiguration(project: Project): KotlinRunConfiguration { return KotlinRunConfiguration("", JavaRunConfigurationModule(project, true), this) } override fun isDumbAware(): Boolean = true override fun isEditableInDumbMode(): Boolean = true override fun getOptionsClass() = JvmMainMethodRunConfigurationOptions::class.java companion object { val instance: KotlinRunConfigurationType get() = findConfigurationType(KotlinRunConfigurationType::class.java) } }
plugins/kotlin/run-configurations/jvm/src/org/jetbrains/kotlin/idea/run/KotlinRunConfigurationType.kt
2092715035
package io.github.bkmioa.nexusrss.ui.viewModel import com.airbnb.epoxy.EpoxyModelClass import com.airbnb.epoxy.SimpleEpoxyModel import io.github.bkmioa.nexusrss.R @EpoxyModelClass abstract class EmptyViewModel : SimpleEpoxyModel(R.layout.item_empty) { init { id(layout) } override fun getSpanSize(totalSpanCount: Int, position: Int, itemCount: Int): Int { return totalSpanCount } }
app/src/main/java/io/github/bkmioa/nexusrss/ui/viewModel/EmptyViewModel.kt
698599297
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.core.network.model import com.google.samples.apps.nowinandroid.core.model.data.Topic import kotlinx.serialization.Serializable /** * Network representation of [Topic] */ @Serializable data class NetworkTopic( val id: String, val name: String = "", val shortDescription: String = "", val longDescription: String = "", val url: String = "", val imageUrl: String = "", val followed: Boolean = false, )
core/network/src/main/java/com/google/samples/apps/nowinandroid/core/network/model/NetworkTopic.kt
252536705
package com.eden.orchid.bitbucket import com.eden.orchid.api.publication.OrchidPublisher import com.eden.orchid.api.registration.OrchidModule import com.eden.orchid.bitbucket.publication.BitbucketCloudPublisher import com.eden.orchid.utilities.addToSet class BitbucketModule : OrchidModule() { override fun configure() { addToSet<OrchidPublisher, BitbucketCloudPublisher>() // addToSet<WikiAdapter, BitbucketWikiAdapter>() } }
integrations/OrchidBitbucket/src/main/kotlin/com/eden/orchid/bitbucket/BitbucketModule.kt
1328333704
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.notifications class AlwaysUnlockedNotificationClusterLock : NotificationClusterLock { override fun tryAcquireLock(notificationType: String, lockTimeoutSeconds: Long): Boolean = true }
orca-core/src/main/java/com/netflix/spinnaker/orca/notifications/AlwaysUnlockedNotificationClusterLock.kt
1965261214
/* * Copyright (C) 2019. Zac Sweers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE") package io.sweers.catchup.util inline infix fun String.truncateAt(length: Int): String = if (length > length) substring(0, length) else this inline fun String.nullIfBlank() = if (isBlank()) null else this inline fun CharSequence?.ifNotEmpty(body: () -> Unit) { if (!isNullOrEmpty()) { body() } }
libraries/util/src/main/kotlin/io/sweers/catchup/util/StringExt.kt
1325720967
package database import activities.Activity /** * Main source of interaction with database. * @param T type of object to be stored */ interface DatabaseConnection <T> where T : Activity { /** * Store [obj] in the file. Creates new file if * it didn't exist before. * @param obj stored objects * @param holderName name of the file that holds data, * for example holderJson.txt, sqliteHolder.db */ fun save(obj : Set<T>, holderName : String) /** * Reading objects from file * @param holderName name of the file that holds data. * @throws NoSuchFileException no file to read json * @return retrieved object */ fun read(holderName: String) : Set<T> }
src/database/DatabaseConnection.kt
663653735
package org.jetbrains.completion.full.line.language import org.jetbrains.completion.full.line.FullLineCompletionMode import org.jetbrains.completion.full.line.ProposalTransformer import org.jetbrains.completion.full.line.ProposalsFilter import org.jetbrains.completion.full.line.TextProposalsAnalyzer interface FullLineConfiguration { val mode: FullLineCompletionMode val filters: List<ProposalsFilter> val transformer: ProposalTransformer val analyzers: List<TextProposalsAnalyzer> object Line : FullLineConfiguration { override val mode: FullLineCompletionMode = FullLineCompletionMode.FULL_LINE override val filters: List<ProposalsFilter> get() = emptyList() override val transformer: ProposalTransformer = ProposalTransformer.identity() override val analyzers: List<TextProposalsAnalyzer> get() = emptyList() } companion object { fun oneToken(supporter: FullLineLanguageSupporter): FullLineConfiguration { return object : FullLineConfiguration { override val mode: FullLineCompletionMode = FullLineCompletionMode.ONE_TOKEN override val filters: List<ProposalsFilter> get() = emptyList() override val transformer: ProposalTransformer get() = ProposalTransformer.firstToken(supporter) override val analyzers: List<TextProposalsAnalyzer> get() = emptyList() } } } }
plugins/full-line/core/src/org/jetbrains/completion/full/line/language/FullLineConfiguration.kt
2654888129
package com.intellij.xdebugger.impl.ui.attach.dialog import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.DataKey import com.intellij.openapi.project.Project import com.intellij.util.application import com.intellij.util.ui.UIUtil import com.intellij.xdebugger.attach.XAttachDebuggerProvider import com.intellij.xdebugger.attach.XAttachHost import com.intellij.xdebugger.attach.XAttachHostProvider import com.intellij.xdebugger.impl.util.isAlive import com.intellij.xdebugger.impl.util.onTermination class AttachToProcessDialogFactory(private val project: Project) { companion object { val IS_LOCAL_VIEW_DEFAULT_KEY = DataKey.create<Boolean>("ATTACH_DIALOG_VIEW_TYPE") private fun isLocalViewDefault(dataContext: DataContext): Boolean = dataContext.getData(IS_LOCAL_VIEW_DEFAULT_KEY) ?: true } private var currentDialog: AttachToProcessDialog? = null fun showDialog(attachDebuggerProviders: List<XAttachDebuggerProvider>, attachHosts: List<XAttachHostProvider<XAttachHost>>, context: DataContext) { application.assertIsDispatchThread() val isLocalViewDefault = isLocalViewDefault(context) val currentDialogInstance = currentDialog if (currentDialogInstance != null && currentDialogInstance.isShowing && currentDialogInstance.disposable.isAlive) { currentDialogInstance.setShowLocalView(isLocalViewDefault) return } val dialog = AttachToProcessDialog(project, attachDebuggerProviders, attachHosts, isLocalViewDefault, null) dialog.disposable.onTermination { UIUtil.invokeLaterIfNeeded { if (currentDialog == dialog) currentDialog = null } } currentDialog = dialog dialog.show() } }
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/attach/dialog/AttachToProcessDialogFactory.kt
4107301855
// 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.base.fir.codeInsight.tooling import org.jetbrains.kotlin.idea.base.codeInsight.tooling.AbstractGenericTestIconProvider import org.jetbrains.kotlin.idea.base.codeInsight.tooling.AbstractJvmIdePlatformKindTooling class FirJvmIdePlatformKindTooling : AbstractJvmIdePlatformKindTooling() { override val testIconProvider: AbstractGenericTestIconProvider get() = SymbolBasedGenericTestIconProvider }
plugins/kotlin/base/fir/code-insight/src/org/jetbrains/kotlin/idea/base/fir/codeInsight/tooling/FirJvmIdePlatformKindTooling.kt
4182887341
// WITH_STDLIB // INTENTION_TEXT: "Replace with 'sumOf{}'" // IS_APPLICABLE_2: false fun foo(list: List<String>): Double { var s = 0.0 <caret>for (item in list) { s += item.length } return s }
plugins/kotlin/idea/tests/testData/intentions/loopToCallChain/sum/sumOfDouble.kt
1766536760
// 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.uast.kotlin import com.intellij.psi.* import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.descriptors.annotations.AnnotationUseSiteTarget import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.uast.UElement import org.jetbrains.uast.UParameter import org.jetbrains.uast.UParameterEx @ApiStatus.Internal open class KotlinUParameter( psi: PsiParameter, final override val sourcePsi: KtElement?, givenParent: UElement? ) : AbstractKotlinUVariable(givenParent), UParameterEx, PsiParameter by psi { final override val javaPsi = unwrap<UParameter, PsiParameter>(psi) override val psi = javaPsi private val isLightConstructorParam by lz { psi.getParentOfType<PsiMethod>(true)?.isConstructor } private val isKtConstructorParam by lz { sourcePsi?.getParentOfType<KtCallableDeclaration>(true)?.let { it is KtConstructor<*> } } override fun acceptsAnnotationTarget(target: AnnotationUseSiteTarget?): Boolean { if (sourcePsi !is KtParameter) return false if (isKtConstructorParam == isLightConstructorParam && target == null) return true if (sourcePsi.parent.parent is KtCatchClause && target == null) return true when (target) { AnnotationUseSiteTarget.CONSTRUCTOR_PARAMETER -> return isLightConstructorParam == true AnnotationUseSiteTarget.SETTER_PARAMETER -> return isLightConstructorParam != true else -> return false } } override fun getInitializer(): PsiExpression? { return super<AbstractKotlinUVariable>.getInitializer() } override fun getOriginalElement(): PsiElement? { return super<AbstractKotlinUVariable>.getOriginalElement() } override fun getNameIdentifier(): PsiIdentifier { return super.getNameIdentifier() } override fun getContainingFile(): PsiFile { return super.getContainingFile() } }
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/declarations/KotlinUParameter.kt
2908531316
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.index.ui import com.intellij.openapi.Disposable import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vcs.VcsBundle import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.containers.DisposableWrapperList import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.vcs.commit.CommitProgressPanel import com.intellij.vcs.commit.EditedCommitDetails import com.intellij.vcs.commit.NonModalCommitPanel import git4idea.i18n.GitBundle import git4idea.index.ContentVersion import git4idea.index.GitFileStatus import git4idea.index.GitStageTracker import git4idea.index.createChange import org.jetbrains.concurrency.resolvedPromise import kotlin.properties.Delegates.observable private fun GitStageTracker.State.getStaged(): Set<GitFileStatus> = rootStates.values.flatMapTo(mutableSetOf()) { it.getStaged() } private fun GitStageTracker.RootState.getStaged(): Set<GitFileStatus> = statuses.values.filterTo(mutableSetOf()) { it.getStagedStatus() != null } private fun GitStageTracker.RootState.getStagedChanges(project: Project): List<Change> = getStaged().mapNotNull { createChange(project, root, it, ContentVersion.HEAD, ContentVersion.STAGED) } class GitStageCommitPanel(project: Project) : NonModalCommitPanel(project) { private val progressPanel = GitStageCommitProgressPanel() override val commitProgressUi: GitStageCommitProgressPanel get() = progressPanel @Volatile private var state: InclusionState = InclusionState(emptySet(), GitStageTracker.State.EMPTY) val rootsToCommit get() = state.rootsToCommit val includedRoots get() = state.includedRoots val conflictedRoots get() = state.conflictedRoots private val editedCommitListeners = DisposableWrapperList<() -> Unit>() override var editedCommit: EditedCommitDetails? by observable(null) { _, _, _ -> editedCommitListeners.forEach { it() } } init { Disposer.register(this, commitMessage) commitMessage.setChangesSupplier { state.stagedChanges } progressPanel.setup(this, commitMessage.editorField, empty(6)) bottomPanel.add(progressPanel.component) bottomPanel.add(commitAuthorComponent.apply { border = empty(0, 5, 4, 0) }) bottomPanel.add(commitActionsPanel) } fun setIncludedRoots(includedRoots: Collection<VirtualFile>) { setState(includedRoots, state.trackerState) } fun setTrackerState(trackerState: GitStageTracker.State) { setState(state.includedRoots, trackerState) } private fun setState(includedRoots: Collection<VirtualFile>, trackerState: GitStageTracker.State) { val newState = InclusionState(includedRoots, trackerState) if (state != newState) { state = newState fireInclusionChanged() } } fun addEditedCommitListener(listener: () -> Unit, parent: Disposable) { editedCommitListeners.add(listener, parent) } override fun activate(): Boolean = true override fun refreshData() = resolvedPromise<Unit>() override fun getDisplayedChanges(): List<Change> = emptyList() override fun getIncludedChanges(): List<Change> = state.stagedChanges override fun getDisplayedUnversionedFiles(): List<FilePath> = emptyList() override fun getIncludedUnversionedFiles(): List<FilePath> = emptyList() private inner class InclusionState(val includedRoots: Collection<VirtualFile>, val trackerState: GitStageTracker.State) { private val stagedStatuses: Set<GitFileStatus> = trackerState.getStaged() val conflictedRoots: Set<VirtualFile> = trackerState.rootStates.filter { it.value.hasConflictedFiles() }.keys val stagedChanges by lazy { trackerState.rootStates.filterKeys { includedRoots.contains(it) }.values.flatMap { it.getStagedChanges(project) } } val rootsToCommit get() = trackerState.stagedRoots.intersect(includedRoots) override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as InclusionState if (includedRoots != other.includedRoots) return false if (stagedStatuses != other.stagedStatuses) return false if (conflictedRoots != other.conflictedRoots) return false return true } override fun hashCode(): Int { var result = includedRoots.hashCode() result = 31 * result + stagedStatuses.hashCode() result = 31 * result + conflictedRoots.hashCode() return result } } } class GitStageCommitProgressPanel : CommitProgressPanel() { var isEmptyRoots by stateFlag() var isUnmerged by stateFlag() override fun clearError() { super.clearError() isEmptyRoots = false isUnmerged = false } override fun buildErrorText(): String? = when { isEmptyRoots -> GitBundle.message("error.no.selected.roots.to.commit") isUnmerged -> GitBundle.message("error.unresolved.conflicts") isEmptyChanges && isEmptyMessage -> GitBundle.message("error.no.staged.changes.no.commit.message") isEmptyChanges -> GitBundle.message("error.no.staged.changes.to.commit") isEmptyMessage -> VcsBundle.message("error.no.commit.message") else -> null } }
plugins/git4idea/src/git4idea/index/ui/GitStageCommitPanel.kt
1065706540
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.scale import com.intellij.diagnostic.runActivity import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.SystemInfoRt import com.intellij.ui.JreHiDpiUtil import com.intellij.util.concurrency.SynchronizedClearableLazy import com.intellij.util.ui.JBScalableIcon import org.jetbrains.annotations.ApiStatus.Internal import org.jetbrains.annotations.TestOnly import java.awt.* import java.beans.PropertyChangeListener import java.beans.PropertyChangeSupport import java.util.function.Supplier import javax.swing.UIDefaults import javax.swing.UIManager import kotlin.math.abs import kotlin.math.roundToInt /** * @author tav */ object JBUIScale { @JvmField @Internal val SCALE_VERBOSE = java.lang.Boolean.getBoolean("ide.ui.scale.verbose") private const val USER_SCALE_FACTOR_PROPERTY = "JBUIScale.userScaleFactor" /** * The user scale factor, see [ScaleType.USR_SCALE]. */ private val userScaleFactor: SynchronizedClearableLazy<Float> = SynchronizedClearableLazy { DEBUG_USER_SCALE_FACTOR.value ?: computeUserScaleFactor(if (JreHiDpiUtil.isJreHiDPIEnabled()) 1f else systemScaleFactor.value) } @Internal fun preload(uiDefaults: Supplier<UIDefaults?>) { if (!systemScaleFactor.isInitialized()) { runActivity("system scale factor computation") { computeSystemScaleFactor(uiDefaults).let { systemScaleFactor.value = it } } } runActivity("user scale factor computation") { userScaleFactor.value } getSystemFontData(uiDefaults) } private val systemScaleFactor: SynchronizedClearableLazy<Float> = SynchronizedClearableLazy { computeSystemScaleFactor(uiDefaults = null) } private val PROPERTY_CHANGE_SUPPORT = PropertyChangeSupport(JBUIScale) private const val DISCRETE_SCALE_RESOLUTION = 0.25f @JvmField var DEF_SYSTEM_FONT_SIZE = 12f @JvmStatic fun addUserScaleChangeListener(listener: PropertyChangeListener) { PROPERTY_CHANGE_SUPPORT.addPropertyChangeListener(USER_SCALE_FACTOR_PROPERTY, listener) } @JvmStatic fun removeUserScaleChangeListener(listener: PropertyChangeListener) { PROPERTY_CHANGE_SUPPORT.removePropertyChangeListener(USER_SCALE_FACTOR_PROPERTY, listener) } private var systemFontData = SynchronizedClearableLazy<Pair<String?, Int>> { runActivity("system font data computation") { computeSystemFontData(null) } } private fun computeSystemFontData(uiDefaults: Supplier<UIDefaults?>?): Pair<String, Int> { if (GraphicsEnvironment.isHeadless()) { return Pair("Dialog", 12) } // with JB Linux JDK the label font comes properly scaled based on Xft.dpi settings. var font: Font if (SystemInfoRt.isMac) { // see AquaFonts.getControlTextFont() - lucida13Pt is hardcoded // text family should be used for relatively small sizes (<20pt), don't change to Display // see more about SF https://medium.com/@mach/the-secret-of-san-francisco-fonts-4b5295d9a745#.2ndr50z2v font = Font(".SF NS Text", Font.PLAIN, 13) DEF_SYSTEM_FONT_SIZE = font.size.toFloat() } else { font = if (uiDefaults == null) UIManager.getFont("Label.font") else uiDefaults.get()!!.getFont("Label.font") } val log = thisLogger() val isScaleVerbose = SCALE_VERBOSE if (isScaleVerbose) { log.info(String.format("Label font: %s, %d", font.fontName, font.size)) } if (SystemInfoRt.isLinux) { val value = Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/DPI") if (isScaleVerbose) { log.info(String.format("gnome.Xft/DPI: %s", value)) } if (value is Int) { // defined by JB JDK when the resource is available in the system // If the property is defined, then: // 1) it provides correct system scale // 2) the label font size is scaled var dpi = value / 1024 if (dpi < 50) dpi = 50 val scale = if (JreHiDpiUtil.isJreHiDPIEnabled()) 1f else discreteScale(dpi / 96f) // no scaling in JRE-HiDPI mode // derive actual system base font size DEF_SYSTEM_FONT_SIZE = font.size / scale if (isScaleVerbose) { log.info(String.format("DEF_SYSTEM_FONT_SIZE: %.2f", DEF_SYSTEM_FONT_SIZE)) } } else if (!SystemInfo.isJetBrainsJvm) { // With Oracle JDK: derive scale from X server DPI, do not change DEF_SYSTEM_FONT_SIZE val size = DEF_SYSTEM_FONT_SIZE * screenScale font = font.deriveFont(size) if (isScaleVerbose) { log.info(String.format("(Not-JB JRE) reset font size: %.2f", size)) } } } else if (SystemInfoRt.isWindows) { val winFont = Toolkit.getDefaultToolkit().getDesktopProperty("win.messagebox.font") as Font? if (winFont != null) { font = winFont // comes scaled if (isScaleVerbose) { log.info(String.format("Windows sys font: %s, %d", winFont.fontName, winFont.size)) } } } val result = Pair(font.name, font.size) if (isScaleVerbose) { log.info(String.format("systemFontData: %s, %d", result.first, result.second)) } return result } @Internal @JvmField val DEBUG_USER_SCALE_FACTOR: SynchronizedClearableLazy<Float?> = SynchronizedClearableLazy { val prop = System.getProperty("ide.ui.scale") when { prop != null -> { try { return@SynchronizedClearableLazy prop.toFloat() } catch (e: NumberFormatException) { thisLogger().error("ide.ui.scale system property is not a float value: $prop") null } } java.lang.Boolean.getBoolean("ide.ui.scale.override") -> 1f else -> null } } private fun computeSystemScaleFactor(uiDefaults: Supplier<UIDefaults?>?): Float { if (!java.lang.Boolean.parseBoolean(System.getProperty("hidpi", "true"))) { return 1f } if (JreHiDpiUtil.isJreHiDPIEnabled()) { val gd = try { GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice } catch (ignore: HeadlessException) { null } val gc = gd?.defaultConfiguration if (gc == null || gc.device.type == GraphicsDevice.TYPE_PRINTER) { return 1f } else { return gc.defaultTransform.scaleX.toFloat() } } val result = getFontScale(getSystemFontData(uiDefaults).second.toFloat()) thisLogger().info("System scale factor: $result (${if (JreHiDpiUtil.isJreHiDPIEnabled()) "JRE" else "IDE"}-managed HiDPI)") return result } @TestOnly @JvmStatic fun setSystemScaleFactor(sysScale: Float) { systemScaleFactor.value = sysScale } @TestOnly @JvmStatic fun setUserScaleFactorForTest(value: Float) { setUserScaleFactorProperty(value) } private fun setUserScaleFactorProperty(value: Float) { val oldValue = userScaleFactor.valueIfInitialized if (oldValue == value) { return } userScaleFactor.value = value thisLogger().info("User scale factor: $value") PROPERTY_CHANGE_SUPPORT.firePropertyChange(USER_SCALE_FACTOR_PROPERTY, oldValue, value) } /** * @return the scale factor of `fontSize` relative to the standard font size (currently 12pt) */ @JvmStatic fun getFontScale(fontSize: Float): Float { return fontSize / DEF_SYSTEM_FONT_SIZE } /** * Sets the user scale factor. * The method is used by the IDE, it's not recommended to call the method directly from the client code. * For debugging purposes, the following JVM system property can be used: * ide.ui.scale=float * or the IDE registry keys (for backward compatibility): * ide.ui.scale.override=boolean * ide.ui.scale=float * * @return the result */ @Internal @JvmStatic fun setUserScaleFactor(value: Float): Float { var scale = value val factor = DEBUG_USER_SCALE_FACTOR.value if (factor != null) { if (scale == factor) { // set the debug value as is, or otherwise ignore setUserScaleFactorProperty(factor) } return factor } scale = computeUserScaleFactor(scale) setUserScaleFactorProperty(scale) return scale } private fun computeUserScaleFactor(value: Float): Float { var scale = value if (!java.lang.Boolean.parseBoolean(System.getProperty("hidpi", "true"))) { return 1f } scale = discreteScale(scale) // downgrading user scale below 1.0 may be uncomfortable (tiny icons), // whereas some users prefer font size slightly below normal which is ok if (scale < 1 && systemScaleFactor.value >= 1) { scale = 1f } // ignore the correction when UIUtil.DEF_SYSTEM_FONT_SIZE is overridden, see UIUtil.initSystemFontData if (SystemInfoRt.isLinux && scale == 1.25f && DEF_SYSTEM_FONT_SIZE == 12f) { // Default UI font size for Unity and Gnome is 15. Scaling factor 1.25f works badly on Linux. return 1f } else { return scale } } private fun discreteScale(scale: Float): Float { return (scale / DISCRETE_SCALE_RESOLUTION).roundToInt() * DISCRETE_SCALE_RESOLUTION } /** * The system scale factor, corresponding to the default monitor device. */ @JvmStatic fun sysScale(): Float = systemScaleFactor.value /** * Returns the system scale factor, corresponding to the device the component is tied to. * In the IDE-managed HiDPI mode defaults to [.sysScale] */ @JvmStatic fun sysScale(component: Component?): Float { return if (component == null) sysScale() else sysScale(component.graphicsConfiguration) } /** * Returns the system scale factor, corresponding to the graphics configuration. * In the IDE-managed HiDPI mode defaults to [.sysScale] */ @JvmStatic fun sysScale(gc: GraphicsConfiguration?): Float { if (JreHiDpiUtil.isJreHiDPIEnabled() && gc != null && gc.device.type != GraphicsDevice.TYPE_PRINTER) { return gc.defaultTransform.scaleX.toFloat() } else { return systemScaleFactor.value } } /** * @return 'f' scaled by the user scale factor */ @JvmStatic fun scale(f: Float): Float { return f * userScaleFactor.value } /** * @return 'i' scaled by the user scale factor */ @JvmStatic fun scale(i: Int): Int { return (userScaleFactor.value * i).roundToInt() } /** * Scales the passed `icon` according to the user scale factor. * * @see ScaleType.USR_SCALE */ @JvmStatic fun <T : JBScalableIcon> scaleIcon(icon: T): T { @Suppress("UNCHECKED_CAST") return icon.withIconPreScaled(false) as T } @JvmStatic fun scaleFontSize(fontSize: Float): Int { return scaleFontSize(fontSize, userScaleFactor.value) } @Internal @JvmStatic fun scaleFontSize(fontSize: Float, userScaleFactor: Float): Int { return when (userScaleFactor) { 1.25f -> fontSize * 1.34f 1.75f -> fontSize * 1.67f else -> fontSize * userScaleFactor }.toInt() } private val screenScale: Float get() { val dpi = try { Toolkit.getDefaultToolkit().screenResolution } catch (ignored: HeadlessException) { 96 } return discreteScale(dpi / 96f) } @JvmStatic fun getSystemFontData(uiDefaults: Supplier<UIDefaults?>?): Pair<String?, Int> { if (uiDefaults == null) { return systemFontData.value } systemFontData.valueIfInitialized?.let { return it } return computeSystemFontData(uiDefaults).also { systemFontData.value = it } } /** * Returns the system scale factor, corresponding to the graphics. * This is a convenience method allowing to avoid casting to `Graphics2D` * on the calling side. */ @JvmStatic fun sysScale(g: Graphics?): Float = sysScale(g as? Graphics2D?) /** * Returns the system scale factor, corresponding to the graphics. * For BufferedImage's graphics, the scale is taken from the graphics itself. * In the IDE-managed HiDPI mode defaults to [.sysScale] */ @JvmStatic fun sysScale(g: Graphics2D?): Float { if (g == null || !JreHiDpiUtil.isJreHiDPIEnabled()) { return sysScale() } val gc = g.deviceConfiguration if (gc == null || gc.device.type == GraphicsDevice.TYPE_IMAGE_BUFFER || gc.device.type == GraphicsDevice.TYPE_PRINTER) { // in this case gc doesn't provide a valid scale return abs(g.transform.scaleX.toFloat()) } else { return sysScale(gc) } } @JvmStatic fun sysScale(context: ScaleContext?): Double { return context?.getScale(ScaleType.SYS_SCALE) ?: sysScale().toDouble() } /** * Returns whether the provided scale assumes HiDPI-awareness. */ @JvmStatic fun isHiDPI(scale: Double): Boolean { // Scale below 1.0 is impractical, it's rather accepted for debug purpose. // Treat it as "hidpi" to correctly manage images which have different user and real size // (for scale below 1.0 the real size will be smaller). return scale != 1.0 } /** * Returns whether the [ScaleType.USR_SCALE] scale factor assumes HiDPI-awareness. An equivalent of `isHiDPI(scale(1f))` */ @JvmStatic val isUsrHiDPI: Boolean get() = isHiDPI(scale(1f).toDouble()) }
platform/util/ui/src/com/intellij/ui/scale/JBUIScale.kt
749996206
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElementVisitor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.startOffset import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection class RedundantElvisReturnNullInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor { return returnExpressionVisitor(fun(returnExpression: KtReturnExpression) { if ((returnExpression.returnedExpression?.deparenthesize() as? KtConstantExpression)?.text != KtTokens.NULL_KEYWORD.value) return val binaryExpression = returnExpression.getStrictParentOfType<KtBinaryExpression>()?.takeIf { it == it.getStrictParentOfType<KtReturnExpression>()?.returnedExpression?.deparenthesize() } ?: return val right = binaryExpression.right?.deparenthesize()?.takeIf { it == returnExpression } ?: return if (binaryExpression.operationToken == KtTokens.ELSE_KEYWORD) return if (binaryExpression.left?.resolveToCall()?.resultingDescriptor?.returnType?.isMarkedNullable != true) return holder.registerProblem( binaryExpression, KotlinBundle.message("inspection.redundant.elvis.return.null.descriptor"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, TextRange(binaryExpression.operationReference.startOffset, right.endOffset).shiftLeft(binaryExpression.startOffset), RemoveRedundantElvisReturnNull() ) }) } private fun KtExpression.deparenthesize() = KtPsiUtil.deparenthesize(this) private class RemoveRedundantElvisReturnNull : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.redundant.elvis.return.null.text") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val binaryExpression = descriptor.psiElement as? KtBinaryExpression ?: return val left = binaryExpression.left ?: return binaryExpression.replace(left) } } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantElvisReturnNullInspection.kt
869270528
// 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.refactoring.changeSignature.ui import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.util.NlsSafe import com.intellij.psi.PsiClassOwner import com.intellij.psi.PsiElement import com.intellij.psi.PsiMethod import com.intellij.psi.PsiReference import com.intellij.psi.search.searches.MethodReferencesSearch import com.intellij.psi.search.searches.ReferencesSearch import com.intellij.refactoring.changeSignature.CallerChooserBase import com.intellij.refactoring.changeSignature.MemberNodeBase import com.intellij.ui.ColoredTreeCellRenderer import com.intellij.ui.JBColor import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.treeStructure.Tree import com.intellij.util.Consumer import com.intellij.util.ui.UIUtil import org.jetbrains.kotlin.asJava.getRepresentativeLightMethod import org.jetbrains.kotlin.asJava.namedUnwrappedElement import org.jetbrains.kotlin.asJava.toLightMethods import org.jetbrains.kotlin.descriptors.ClassDescriptor import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.KotlinFileType import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMethodDescriptor import org.jetbrains.kotlin.idea.hierarchy.calls.CalleeReferenceProcessor import org.jetbrains.kotlin.idea.hierarchy.calls.KotlinCallHierarchyNodeDescriptor import org.jetbrains.kotlin.idea.base.util.useScope import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtFunction import org.jetbrains.kotlin.psi.psiUtil.getElementTextWithContext class KotlinCallerChooser( declaration: PsiElement, project: Project, @NlsContexts.DialogTitle title: String, previousTree: Tree?, callback: Consumer<in Set<PsiElement>> ) : CallerChooserBase<PsiElement>(declaration, project, title, previousTree, "dummy." + KotlinFileType.EXTENSION, callback) { override fun createTreeNodeFor(method: PsiElement?, called: HashSet<PsiElement>?, cancelCallback: Runnable?) = KotlinMethodNode(method, called ?: HashSet(), myProject, cancelCallback ?: Runnable {}) override fun findDeepestSuperMethods(method: PsiElement) = method.toLightMethods().singleOrNull()?.findDeepestSuperMethods() override fun getEmptyCallerText() = KotlinBundle.message("text.caller.text.with.highlighted.callee.call.would.be.shown.here") override fun getEmptyCalleeText() = KotlinBundle.message("text.callee.text.would.be.shown.here") } class KotlinMethodNode( method: PsiElement?, called: HashSet<PsiElement>, project: Project, cancelCallback: Runnable ) : MemberNodeBase<PsiElement>(method?.namedUnwrappedElement ?: method, called, project, cancelCallback) { override fun createNode(caller: PsiElement, called: HashSet<PsiElement>) = KotlinMethodNode(caller, called, myProject, myCancelCallback) override fun customizeRendererText(renderer: ColoredTreeCellRenderer) { val method = myMethod val descriptor = when (method) { is KtFunction -> method.unsafeResolveToDescriptor() as FunctionDescriptor is KtClass -> (method.unsafeResolveToDescriptor() as ClassDescriptor).unsubstitutedPrimaryConstructor ?: return is PsiMethod -> method.getJavaMethodDescriptor() ?: return else -> throw AssertionError("Invalid declaration: ${method.getElementTextWithContext()}") } val containerName = generateSequence<DeclarationDescriptor>(descriptor) { it.containingDeclaration } .firstOrNull { it is ClassDescriptor } ?.name val renderedFunction = KotlinCallHierarchyNodeDescriptor.renderNamedFunction(descriptor) val renderedFunctionWithContainer = containerName?.let { @NlsSafe val name = "${if (it.isSpecial) KotlinBundle.message("text.anonymous") else it.asString()}.$renderedFunction" name } ?: renderedFunction val attributes = if (isEnabled) SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getTreeForeground()) else SimpleTextAttributes.EXCLUDED_ATTRIBUTES renderer.append(renderedFunctionWithContainer, attributes) val packageName = (method.containingFile as? PsiClassOwner)?.packageName ?: "" renderer.append(" ($packageName)", SimpleTextAttributes(SimpleTextAttributes.STYLE_ITALIC, JBColor.GRAY)) } override fun computeCallers(): List<PsiElement> { if (myMethod == null) return emptyList() val callers = LinkedHashSet<PsiElement>() val processor = object : CalleeReferenceProcessor(false) { override fun onAccept(ref: PsiReference, element: PsiElement) { if ((element is KtFunction || element is KtClass || element is PsiMethod) && element !in myCalled) { callers.add(element) } } } val query = myMethod.getRepresentativeLightMethod() ?.let { MethodReferencesSearch.search(it, it.useScope(), true) } ?: ReferencesSearch.search(myMethod, myMethod.useScope()) query.forEach { processor.process(it) } return callers.toList() } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/ui/KotlinCallerChooser.kt
810297924
package smartStepIntoInlinedFunctionalExpression fun main(args: Array<String>) { val array = arrayOf(1, 2) //Breakpoint! val myClass = MyClass() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 4 // smart step into f2.invoke(), one-line lambda myClass.f1(fun () { test() }) .f2(fun () { test() }) // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 2 // smart step into f1.invoke(), one-line lambda myClass.f1(fun () { test() }) .f2(fun () { test() }) // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 2 // smart step into map.invoke(), multiline lambda array.map(fun (it): Int { return it * 2 }) // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 4 // smart step into filter.invoke() array.map(fun (it): Int { return it * 2 }) .filter(fun (it): Boolean { return it > 2 }) // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 2 // smart step into map.invoke() array.map(fun (it): Int { return it * 2 }) .filter(fun (it): Boolean { return it > 2 }) // RESUME: 1 //Breakpoint! test() // STEP_OVER: 1 // SMART_STEP_INTO_BY_INDEX: 2 myClass.f3(fun () = myClass.f3 { val a = 1 }) } class MyClass { inline fun f1(f1Param: () -> Unit): MyClass { test() f1Param() return this } inline fun f2(f1Param: () -> Unit): MyClass { test() f1Param() return this } inline fun f3(f1Param: () -> Unit): Unit { test() f1Param() } } fun test() {} // IGNORE_K2
plugins/kotlin/jvm-debugger/test/testData/stepping/custom/smartStepIntoInlinedFunctionalExpression.kt
278642360
package com.strumenta.kolasu.emf import com.strumenta.kolasu.model.PropertyTypeDescription import com.strumenta.kolasu.model.processProperties import org.eclipse.emf.ecore.* import org.eclipse.emf.ecore.resource.Resource import java.util.* import kotlin.reflect.* import kotlin.reflect.full.isSubclassOf import kotlin.reflect.full.superclasses import kotlin.reflect.full.withNullability private val KClass<*>.packageName: String? get() { val qname = this.qualifiedName ?: throw IllegalStateException("The class has no qualified name: $this") return if (qname == this.simpleName) { null } else { require(qname.endsWith(".${this.simpleName}")) qname.removeSuffix(".${this.simpleName}") } } /** * When building multiple related EPackages use MetamodelsBuilder instead. */ class MetamodelBuilder(packageName: String, nsURI: String, nsPrefix: String, resource: Resource? = null) : ClassifiersProvider { private val ePackage: EPackage = EcoreFactory.eINSTANCE.createEPackage() private val eClasses = HashMap<KClass<*>, EClass>() private val dataTypes = HashMap<KType, EDataType>() private val eclassTypeHandlers = LinkedList<EClassTypeHandler>() private val dataTypeHandlers = LinkedList<EDataTypeHandler>() internal var container: MetamodelsBuilder? = null init { ePackage.name = packageName ePackage.nsURI = nsURI ePackage.nsPrefix = nsPrefix if (resource == null) { ePackage.setResourceURI(nsURI) } else { resource.contents.add(ePackage) eclassTypeHandlers.add(ResourceClassTypeHandler(resource, ePackage)) } dataTypeHandlers.add(StringHandler) dataTypeHandlers.add(CharHandler) dataTypeHandlers.add(BooleanHandler) dataTypeHandlers.add(IntHandler) dataTypeHandlers.add(IntegerHandler) dataTypeHandlers.add(FloatHandler) dataTypeHandlers.add(DoubleHandler) dataTypeHandlers.add(LongHandler) dataTypeHandlers.add(BigIntegerHandler) dataTypeHandlers.add(BigDecimalHandler) eclassTypeHandlers.add(LocalDateHandler) eclassTypeHandlers.add(LocalTimeHandler) eclassTypeHandlers.add(LocalDateTimeHandler) eclassTypeHandlers.add(NodeHandler) eclassTypeHandlers.add(NamedHandler) eclassTypeHandlers.add(PositionHandler) eclassTypeHandlers.add(PossiblyNamedHandler) eclassTypeHandlers.add(ReferenceByNameHandler) eclassTypeHandlers.add(ResultHandler) eclassTypeHandlers.add(StatementHandler) eclassTypeHandlers.add(ExpressionHandler) eclassTypeHandlers.add(EntityDeclarationHandler) } /** * Normally a class is not treated as a DataType, so we need specific DataTypeHandlers * to recognize it as such */ fun addDataTypeHandler(eDataTypeHandler: EDataTypeHandler) { dataTypeHandlers.add(eDataTypeHandler) } /** * This should be needed only to customize how we want to deal with a class when translating * it to an EClass */ fun addEClassTypeHandler(eClassTypeHandler: EClassTypeHandler) { eclassTypeHandlers.add(eClassTypeHandler) } private fun createEEnum(kClass: KClass<out Enum<*>>): EEnum { val eEnum = EcoreFactory.eINSTANCE.createEEnum() eEnum.name = kClass.eClassifierName kClass.java.enumConstants.forEach { val eLiteral = EcoreFactory.eINSTANCE.createEEnumLiteral() eLiteral.name = it.name eLiteral.value = it.ordinal eEnum.eLiterals.add(eLiteral) } return eEnum } override fun provideDataType(ktype: KType): EDataType? { if (!dataTypes.containsKey(ktype)) { val eDataType: EDataType var external = false when { (ktype.classifier as? KClass<*>)?.isSubclassOf(Enum::class) == true -> { eDataType = createEEnum(ktype.classifier as KClass<out Enum<*>>) } else -> { val handler = dataTypeHandlers.find { it.canHandle(ktype) } if (handler == null) { // throw RuntimeException("Unable to handle data type $ktype, with classifier ${ktype.classifier}")\ return null } else { external = handler.external() eDataType = handler.toDataType(ktype) } } } if (!external) { ensureClassifierNameIsNotUsed(eDataType) ePackage.eClassifiers.add(eDataType) } dataTypes[ktype] = eDataType } return dataTypes[ktype]!! } private fun classToEClass(kClass: KClass<*>): EClass { if (kClass == Any::class) { return EcoreFactory.eINSTANCE.ecorePackage.eObject } if (kClass.packageName != this.ePackage.name) { if (container != null) { for (sibling in container!!.singleMetamodelsBuilders) { if (sibling.canProvideClass(kClass)) { return sibling.provideClass(kClass) } } } throw Error( "This class does not belong to this EPackage: ${kClass.qualifiedName}. " + "This EPackage: ${this.ePackage.name}" ) } val eClass = EcoreFactory.eINSTANCE.createEClass() // This is necessary because some classes refer to themselves registerKClassForEClass(kClass, eClass) kClass.superclasses.forEach { if (it != Any::class) { eClass.eSuperTypes.add(provideClass(it)) } } eClass.name = kClass.eClassifierName eClass.isAbstract = kClass.isAbstract || kClass.isSealed eClass.isInterface = kClass.java.isInterface kClass.typeParameters.forEach { kTypeParameter: KTypeParameter -> eClass.eTypeParameters.add( EcoreFactory.eINSTANCE.createETypeParameter().apply { // TODO consider bounds, taking in account that in Kotlin we have variance (in/out) // which may not exactly correspond to how bounds work in EMF name = kTypeParameter.name } ) } kClass.processProperties { prop -> try { if (eClass.eAllStructuralFeatures.any { sf -> sf.name == prop.name }) { // skip } else { // do not process inherited properties val valueType = prop.valueType if (prop.provideNodes) { registerReference(prop, valueType, eClass) } else { val nullable = prop.valueType.isMarkedNullable val dataType = provideDataType(prop.valueType.withNullability(false)) if (dataType == null) { // We can treat it like a class registerReference(prop, valueType, eClass) } else { val ea = EcoreFactory.eINSTANCE.createEAttribute() ea.name = prop.name if (prop.multiple) { ea.lowerBound = 0 ea.upperBound = -1 } else { ea.lowerBound = if (nullable) 0 else 1 ea.upperBound = 1 } ea.eType = dataType eClass.eStructuralFeatures.add(ea) } } } } catch (e: Exception) { throw RuntimeException("Issue processing property $prop in class $kClass", e) } } return eClass } private fun registerReference( prop: PropertyTypeDescription, valueType: KType, eClass: EClass ) { val ec = EcoreFactory.eINSTANCE.createEReference() ec.name = prop.name if (prop.multiple) { ec.lowerBound = 0 ec.upperBound = -1 } else { ec.lowerBound = 0 ec.upperBound = 1 } ec.isContainment = true // No type parameters on methods should be allowed elsewhere and only the type parameters // on the class should be visible. We are not expecting containing classes to expose // type parameters val visibleTypeParameters = eClass.eTypeParameters.associateBy { it.name } setType(ec, valueType, visibleTypeParameters) eClass.eStructuralFeatures.add(ec) } private fun provideType(valueType: KTypeProjection): EGenericType { when (valueType.variance) { KVariance.INVARIANT -> { return provideType(valueType.type!!) } else -> TODO("Variance ${valueType.variance} not yet sypported") } } private fun provideType(valueType: KType): EGenericType { val dataType = provideDataType(valueType.withNullability(false)) if (dataType != null) { return EcoreFactory.eINSTANCE.createEGenericType().apply { eClassifier = dataType } } if (valueType.arguments.isNotEmpty()) { TODO("Not yet supported: type arguments in $valueType") } if (valueType.classifier is KClass<*>) { return EcoreFactory.eINSTANCE.createEGenericType().apply { eClassifier = provideClass(valueType.classifier as KClass<*>) } } else { TODO("Not yet supported: ${valueType.classifier}") } } private fun setType( element: ETypedElement, valueType: KType, visibleTypeParameters: Map<String, ETypeParameter> ) { when (val classifier = valueType.classifier) { is KClass<*> -> { if (classifier.typeParameters.isEmpty()) { element.eType = provideClass(classifier) } else { element.eGenericType = EcoreFactory.eINSTANCE.createEGenericType().apply { eClassifier = provideClass(classifier) require(classifier.typeParameters.size == valueType.arguments.size) eTypeArguments.addAll( valueType.arguments.map { provideType(it) } ) } } } is KTypeParameter -> { element.eGenericType = EcoreFactory.eINSTANCE.createEGenericType().apply { eTypeParameter = visibleTypeParameters[classifier.name] ?: throw IllegalStateException("Type parameter not found") } } else -> throw Error("Not a valid classifier: $classifier") } } private fun ensureClassifierNameIsNotUsed(classifier: EClassifier) { if (ePackage.hasClassifierNamed(classifier.name)) { throw IllegalStateException( "There is already a Classifier named ${classifier.name}: ${ePackage.classifierByName(classifier.name)}" ) } } private fun registerKClassForEClass(kClass: KClass<*>, eClass: EClass) { if (eClasses.containsKey(kClass)) { require(eClasses[kClass] == eClass) } else { eClasses[kClass] = eClass } } fun canProvideClass(kClass: KClass<*>): Boolean { if (eClasses.containsKey(kClass)) { return true } if (eclassTypeHandlers.any { it.canHandle(kClass) }) { return true } if (kClass == Any::class) { return true } return kClass.packageName == this.ePackage.name } override fun provideClass(kClass: KClass<*>): EClass { if (!eClasses.containsKey(kClass)) { val ch = eclassTypeHandlers.find { it.canHandle(kClass) } val eClass = ch?.toEClass(kClass, this) ?: classToEClass(kClass) if (kClass.packageName != this.ePackage.name) { return eClass } if (ch == null || !ch.external()) { ensureClassifierNameIsNotUsed(eClass) ePackage.eClassifiers.add(eClass) } registerKClassForEClass(kClass, eClass) if (kClass.isSealed) { kClass.sealedSubclasses.forEach { queue.add(it) } } } while (queue.isNotEmpty()) { provideClass(queue.removeFirst()) } return eClasses[kClass]!! } private val queue = LinkedList<KClass<*>>() fun generate(): EPackage { return ePackage } }
emf/src/main/kotlin/com/strumenta/kolasu/emf/MetamodelBuilder.kt
3890758667
package de.nicidienase.chaosflix.common import android.os.Build import android.os.Parcel import android.os.Parcelable import de.nicidienase.chaosflix.common.mediadata.entities.recording.RelatedEventDto import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Conference import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.ConferenceGroup import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Event import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.Recording import de.nicidienase.chaosflix.common.mediadata.entities.recording.persistence.RelatedEvent import de.nicidienase.chaosflix.common.mediadata.entities.streaming.Room import de.nicidienase.chaosflix.common.mediadata.entities.streaming.Stream import de.nicidienase.chaosflix.common.mediadata.entities.streaming.StreamEvent import de.nicidienase.chaosflix.common.mediadata.entities.streaming.StreamUrl import de.nicidienase.chaosflix.common.userdata.entities.download.OfflineEvent import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.P]) class ParcelableTest { @Test fun conferenceParcelableTest() { val conference = Conference(23, 42, "GPN42", "16:9", "Gulaschprogrammiernacht 42", "GPN42", "http://example/com", "http://example/com", "http://example/com", "http://example/com", "http://example/com", "http://example/com", "2042-04-05 23:42:50", false, "2042-04-05 23:42:50") assertTrue(conference.equals(Conference.createFromParcel(writeToParcel(conference)))) } @Test fun eventParcelableTest() { val event = Event(23, 42, "GPN42", "2314324-12323432-4326546", "Developing for Android 23", "finally in Swift ;)", "And23", "https://example.com/", "Lorem Ipsum", "klingon", "2042.4.5 23:42:59", "2042.4.5 23:42:59", "2042.4.5 23:42:59", 1337, "https://example.com/thumb.png", "https://example.com/poster.png", "https://example.com/talk.json", "https://example.com/talk.html", "https://example.com/GPN42", true, 230, null, null, null, null ) assertTrue(event.equals(Event.createFromParcel(writeToParcel(event)))) } @Test fun reletedEventDtoParcelableTest() { val relatedEventDto = RelatedEventDto("ß9834573240ß958", 42) assertTrue(relatedEventDto.equals(RelatedEventDto.createFromParcel(writeToParcel(relatedEventDto)))) } @Test fun conferenceGroupParcelableTest() { val conferenceGroup = ConferenceGroup("conferenceGroup") assertTrue(conferenceGroup.equals(ConferenceGroup.createFromParcel(writeToParcel(conferenceGroup)))) } @Test fun recordingParcelableTest() { val recording = Recording(23, 42, 2342, 1337, "video/mp5", "klingon", "foo.bar", "bar", "foo", true, 640, 480, "1970.1.1 00:00:00", "https://example.com/recording", "https://example.com/item", "https://example.com/event", "https://example.com/conference", 99) assertTrue(recording.equals(Recording.createFromParcel(writeToParcel(recording)))) } @Test fun relatedEventParcelableTest() { val relatedEvent = RelatedEvent(23, 42, "asdlkfjasdf", 99) val other = RelatedEvent.createFromParcel(writeToParcel(relatedEvent)) assertTrue(relatedEvent.equals(other)) } @Test fun roomParcelableTest() { val room = Room("foo", "schedulename", "thumb", "link", "display", null, emptyList()) val other = Room.createFromParcel(writeToParcel(room)) assertTrue(room.equals(other)) } @Test fun streamParcelableTest() { val stream = Stream("slug", "display", "type", true, intArrayOf(640, 480), HashMap<String, StreamUrl>()) val other = Stream.createFromParcel(writeToParcel(stream)) assertTrue(stream.equals(other)) } @Test fun streamEventParcelableTest() { val streamEvent = StreamEvent("title", "speaker", "fstart", "fend", 1, 23, 42, true) assertTrue(streamEvent.equals(StreamEvent.createFromParcel(writeToParcel(streamEvent)))) } @Test fun streamUrlParcelableTest() { val streamUrl = StreamUrl("display", "tech", "url") assertTrue(streamUrl.equals(StreamUrl.createFromParcel(writeToParcel(streamUrl)))) } @Test fun offlineEventParcelableTest() { val offlineEvent = OfflineEvent(12, "asdflkjasdf", 34, 56, "/path/to/file.mp4") assertTrue(offlineEvent.equals(OfflineEvent.createFromParcel(writeToParcel(offlineEvent)))) } private fun writeToParcel(parcelable: Parcelable): Parcel { val parcel = Parcel.obtain() parcelable.writeToParcel(parcel, 0) parcel.setDataPosition(0) return parcel } }
common/src/test/java/de/nicidienase/chaosflix/common/ParcelableTest.kt
3328347324
// ktlint-disable filename /* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.tls public actual class TLSConfig()
ktor-network/ktor-network-tls/nix/src/io/ktor/network/tls/TLSConfigNative.kt
3000004510
package com.gogoapps.androidcomponents.facebook import android.app.Activity import android.content.Intent import com.facebook.login.LoginResult import io.reactivex.Observable interface FacebookRepository { fun requestFacebookToken(activity: Activity): Observable<LoginResult> fun onActivityResult( requestCode: Int, resultCode: Int, data: Intent ) }
gogoapps-facebook/src/main/java/com/gogoapps/androidcomponents/facebook/FacebookRepository.kt
2491891593