content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package io.mockk.ait import androidx.test.ext.junit.runners.AndroidJUnit4 import io.mockk.mockk import io.mockk.verify import org.junit.runner.RunWith import kotlin.test.Test abstract class MyAbstractClass interface IOtherInterface {} interface IMockableInterface { fun doSomethingWithAbstractClass(a: MyAbstractClass?) fun doSomethingWithInterface(a: IOtherInterface?) fun doSomethingWithString(s: String) } @RunWith(AndroidJUnit4::class) class MockAbstractArgTest { @Test fun canVerifyStringArg() { val myMock = mockk<IMockableInterface>(relaxUnitFun = true) myMock.doSomethingWithString("hello") // works verify { myMock.doSomethingWithString(any()) } } @Test fun cannotVerifyAbstractArg() { val myMock = mockk<IMockableInterface>(relaxUnitFun = true) myMock.doSomethingWithAbstractClass(null) // JNI DETECTED ERROR IN APPLICATION: can't make objects of type com.test.MyAbstractClass verify { myMock.doSomethingWithAbstractClass(any()) } } @Test fun canVerifyInterfaceArg() { val myMock = mockk<IMockableInterface>(relaxUnitFun = true) myMock.doSomethingWithInterface(null) // works verify { myMock.doSomethingWithInterface(any()) } } }
modules/mockk-android/src/androidTest/java/io/mockk/ait/MockAbstractArgTest.kt
2647950172
package com.groupdocs.ui.usecase import com.groupdocs.ui.util.InternalServerException import io.micronaut.context.annotation.Bean import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import java.nio.file.Files import java.nio.file.Path @Bean class GetLocalFilesUseCase { suspend operator fun invoke(directory: Path): List<LocalStorageEntry> = withContext(Dispatchers.IO) { if (Files.notExists(directory)) { throw GetLocalFilesException("Directory does not exist: ${directory.fileName}") } try { val entries = mutableListOf<LocalStorageEntry>() Files.newDirectoryStream(directory).use { directoryStream -> directoryStream.forEach { path -> val entry: LocalStorageEntry = when (Files.isDirectory(path)) { true -> { LocalStorageEntry.Directory( name = path.fileName.toString(), parentPath = directory ) } else -> { LocalStorageEntry.File( name = path.fileName.toString(), parentPath = directory, size = Files.size(path) ) } } entries.add(entry) } } entries } catch (e: Exception) { throw GetLocalFilesException("can't get content of $directory", e) } } } sealed class LocalStorageEntry(val name: String, val parentPath: Path) { class File(name: String, val size: Long, parentPath: Path) : LocalStorageEntry(name, parentPath) class Directory(name: String, parentPath: Path) : LocalStorageEntry(name, parentPath) val fullPath get() = parentPath.resolve(name) } class GetLocalFilesException(message: String, e: Throwable? = null) : InternalServerException(message, e)
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/usecase/GetLocalFilesUseCase.kt
3509293862
package com.kesco.xposed.slideback.view.recycleview import android.R import android.content.Context import android.content.res.TypedArray import android.graphics.Canvas import android.graphics.Rect import android.graphics.drawable.Drawable import android.support.v7.widget.RecyclerView import android.view.View /** * [RecyclerView]的分隔线,注意只支持垂直方向 * @author Kesco Lin */ public class LineDividerItemDecoration(ctx: Context, resId: Int = 0) : RecyclerView.ItemDecoration() { private val DEFAULT_ATTRS = intArrayOf(R.attr.listDivider) protected var divider: Drawable init { if (resId != 0) { divider = ctx.getDrawable(resId) } else { val a = ctx.obtainStyledAttributes(DEFAULT_ATTRS) divider = a.getDrawable(0) a.recycle() } } override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) { val endLeft = parent.paddingLeft val endRight = parent.width val left = endLeft val right = endRight - parent.paddingRight val childCount = parent.childCount for (i in 0..childCount - 1) { val child = parent.getChildAt(i) if (child.visibility != View.VISIBLE) { continue } val params = child.layoutParams as RecyclerView.LayoutParams val top = child.bottom + params.bottomMargin val bottom = top + divider.intrinsicHeight if (i == childCount - 1) { divider.setBounds(endLeft, top, endRight, bottom) } else { divider.setBounds(left, top, right, bottom) } divider.draw(c) } } override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { if (parent.getChildLayoutPosition(view) < 1) { return } outRect.top = divider.intrinsicHeight } }
app/src/main/kotlin/com/kesco/xposed/slideback/view/recycleview/LineDividerItemDecoration.kt
1791064938
package yuku.alkitab.datatransfer.process import kotlinx.serialization.json.Json object Serializer { val exportJson = Json { classDiscriminator = "kind" encodeDefaults = false prettyPrint = true @Suppress("EXPERIMENTAL_API_USAGE") prettyPrintIndent = " " } val importJson = Json { classDiscriminator = "kind" ignoreUnknownKeys = true } }
Alkitab/src/main/java/yuku/alkitab/datatransfer/process/Serializer.kt
4206321245
/* * Copyright (C) 2017 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.marklogic.tests.server import junit.framework.TestCase import uk.co.reecedunn.intellij.plugin.marklogic.server.LogType import uk.co.reecedunn.intellij.plugin.marklogic.server.MarkLogicAppServer import uk.co.reecedunn.intellij.plugin.marklogic.server.* import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat class MarkLogicAppServerTest : TestCase() { fun testSystem() { val appserver = MarkLogicAppServer.SYSTEM assertThat(appserver.toString(), `is`("System (MarkLogic)")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 0, MARKLOGIC_8), `is`("AccessLog.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 1, MARKLOGIC_8), `is`("AccessLog_1.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 0, MARKLOGIC_9), `is`("AccessLog.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 1, MARKLOGIC_9), `is`("AccessLog_1.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 0, MARKLOGIC_8), `is`("AuditLog.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 1, MARKLOGIC_8), `is`("AuditLog_1.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 0, MARKLOGIC_9), `is`("AuditLog.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 1, MARKLOGIC_9), `is`("AuditLog_1.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 0, MARKLOGIC_8), `is`("CrashLog.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 1, MARKLOGIC_8), `is`("CrashLog_1.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 0, MARKLOGIC_9), `is`("CrashLog.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 1, MARKLOGIC_9), `is`("CrashLog_1.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 0, MARKLOGIC_8), `is`("ErrorLog.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 1, MARKLOGIC_8), `is`("ErrorLog_1.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 0, MARKLOGIC_9), `is`("ErrorLog.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 1, MARKLOGIC_9), `is`("ErrorLog_1.txt")) } fun testAppServer() { val appserver = MarkLogicAppServer("Default", "test", "HTTP", 8020) assertThat(appserver.toString(), `is`("Default :: test : 8020 [HTTP]")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 0, MARKLOGIC_8), `is`("8020_AccessLog.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 1, MARKLOGIC_8), `is`("8020_AccessLog_1.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 0, MARKLOGIC_9), `is`("8020_AccessLog.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 1, MARKLOGIC_9), `is`("8020_AccessLog_1.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 0, MARKLOGIC_8), `is`("8020_AuditLog.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 1, MARKLOGIC_8), `is`("8020_AuditLog_1.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 0, MARKLOGIC_9), `is`("8020_AuditLog.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 1, MARKLOGIC_9), `is`("8020_AuditLog_1.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 0, MARKLOGIC_8), `is`("8020_CrashLog.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 1, MARKLOGIC_8), `is`("8020_CrashLog_1.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 0, MARKLOGIC_9), `is`("8020_CrashLog.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 1, MARKLOGIC_9), `is`("8020_CrashLog_1.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 0, MARKLOGIC_8), `is`("ErrorLog.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 1, MARKLOGIC_8), `is`("ErrorLog_1.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 0, MARKLOGIC_9), `is`("8020_ErrorLog.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 1, MARKLOGIC_9), `is`("8020_ErrorLog_1.txt")) } fun testTaskServer() { val appserver = MarkLogicAppServer.TASKSERVER assertThat(appserver.toString(), `is`("TaskServer")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 0, MARKLOGIC_8), `is`("TaskServer_AccessLog.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 1, MARKLOGIC_8), `is`("TaskServer_AccessLog_1.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 0, MARKLOGIC_9), `is`("TaskServer_AccessLog.txt")) assertThat(appserver.logfile(LogType.ACCESS_LOG, 1, MARKLOGIC_9), `is`("TaskServer_AccessLog_1.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 0, MARKLOGIC_8), `is`("TaskServer_AuditLog.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 1, MARKLOGIC_8), `is`("TaskServer_AuditLog_1.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 0, MARKLOGIC_9), `is`("TaskServer_AuditLog.txt")) assertThat(appserver.logfile(LogType.AUDIT_LOG, 1, MARKLOGIC_9), `is`("TaskServer_AuditLog_1.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 0, MARKLOGIC_8), `is`("TaskServer_CrashLog.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 1, MARKLOGIC_8), `is`("TaskServer_CrashLog_1.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 0, MARKLOGIC_9), `is`("TaskServer_CrashLog.txt")) assertThat(appserver.logfile(LogType.CRASH_LOG, 1, MARKLOGIC_9), `is`("TaskServer_CrashLog_1.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 0, MARKLOGIC_8), `is`("ErrorLog.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 1, MARKLOGIC_8), `is`("ErrorLog_1.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 0, MARKLOGIC_9), `is`("TaskServer_ErrorLog.txt")) assertThat(appserver.logfile(LogType.ERROR_LOG, 1, MARKLOGIC_9), `is`("TaskServer_ErrorLog_1.txt")) } }
src/test/java/uk/co/reecedunn/intellij/plugin/marklogic/tests/server/MarkLogicAppServerTest.kt
2381152706
/* * 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.view.holder import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import android.view.View.OnClickListener import android.view.View.OnLongClickListener import android.widget.RelativeLayout import kotlinx.android.synthetic.main.list_item_user.view.* import org.mariotaku.ktextension.hideIfEmpty import org.mariotaku.ktextension.spannable import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.iface.IUsersAdapter import de.vanita5.twittnuker.adapter.iface.IUsersAdapter.* import de.vanita5.twittnuker.extension.loadProfileImage import de.vanita5.twittnuker.extension.model.hasSameHost import de.vanita5.twittnuker.model.ParcelableUser import de.vanita5.twittnuker.util.Utils import de.vanita5.twittnuker.util.Utils.getUserTypeIconRes import java.util.* class UserViewHolder( itemView: View, private val adapter: IUsersAdapter<*>, private val simple: Boolean = false, private val showFollow: Boolean = false ) : ViewHolder(itemView), OnClickListener, OnLongClickListener { private val itemContent = itemView.itemContent private val profileImageView = itemView.profileImage private val profileTypeView = itemView.profileType private val nameView = itemView.name private val externalIndicator = itemView.externalIndicator private val descriptionView = itemView.description private val locationView = itemView.location private val urlView = itemView.url private val statusesCountView = itemView.statusesCount private val followersCountView = itemView.followersCount private val friendsCountView = itemView.friendsCount private val acceptRequestButton = itemView.acceptRequest private val denyRequestButton = itemView.denyRequest private val unblockButton = itemView.unblock private val unmuteButton = itemView.unmute private val followButton = itemView.follow private val actionsProgressContainer = itemView.actionsProgressContainer private val actionsContainer = itemView.actionsContainer private val processingRequestProgress = itemView.processingRequest private val countsContainer = itemView.countsContainer private var userClickListener: UserClickListener? = null private var requestClickListener: RequestClickListener? = null private var friendshipClickListener: FriendshipClickListener? = null init { if (simple) { externalIndicator.visibility = View.GONE descriptionView.visibility = View.GONE locationView.visibility = View.GONE urlView.visibility = View.GONE countsContainer.visibility = View.GONE itemView.profileImageContainer.layoutParams.apply { (this as RelativeLayout.LayoutParams).clearVerticalRules() this.addRule(RelativeLayout.CENTER_VERTICAL) } nameView.layoutParams.apply { (this as RelativeLayout.LayoutParams).clearVerticalRules() this.addRule(RelativeLayout.CENTER_VERTICAL) } actionsProgressContainer.layoutParams.apply { (this as RelativeLayout.LayoutParams).clearVerticalRules() this.addRule(RelativeLayout.CENTER_VERTICAL) } } } fun display(user: ParcelableUser) { val context = itemView.context val manager = adapter.userColorNameManager val twitter = adapter.twitterWrapper itemContent.drawStart(manager.getUserColor(user.key)) val userTypeRes = getUserTypeIconRes(user.is_verified, user.is_protected) if (userTypeRes != 0) { profileTypeView.setImageResource(userTypeRes) } else { profileTypeView.setImageDrawable(null) } nameView.name = user.name nameView.screenName = "@${user.screen_name}" nameView.updateText(adapter.bidiFormatter) if (adapter.profileImageEnabled) { profileImageView.visibility = View.VISIBLE adapter.requestManager.loadProfileImage(context, user, adapter.profileImageStyle, profileImageView.cornerRadius, profileImageView.cornerRadiusRatio, adapter.profileImageSize).into(profileImageView) } else { profileImageView.visibility = View.GONE } val accountKey = user.account_key if (accountKey != null && twitter.isUpdatingRelationship(accountKey, user.key)) { processingRequestProgress.visibility = View.VISIBLE actionsContainer.visibility = View.GONE } else { processingRequestProgress.visibility = View.GONE actionsContainer.visibility = View.VISIBLE } if (accountKey != null && user.key.hasSameHost(accountKey)) { externalIndicator.visibility = View.GONE } else { externalIndicator.visibility = View.VISIBLE externalIndicator.text = context.getString(R.string.external_user_host_format, user.key.host) } followButton.setImageResource(if (user.is_following) R.drawable.ic_action_confirm else R.drawable.ic_action_add) followButton.isActivated = user.is_following val isMySelf = accountKey == user.key if (requestClickListener != null && !isMySelf) { acceptRequestButton.visibility = View.VISIBLE denyRequestButton.visibility = View.VISIBLE } else { acceptRequestButton.visibility = View.GONE denyRequestButton.visibility = View.GONE } if (friendshipClickListener != null && !isMySelf) { if (user.extras?.blocking ?: false) { followButton.visibility = View.GONE unblockButton.visibility = View.VISIBLE } else { if (showFollow) { followButton.visibility = View.VISIBLE } else { followButton.visibility = View.GONE } unblockButton.visibility = View.GONE } unmuteButton.visibility = if (user.extras?.muting ?: false) View.VISIBLE else View.GONE } else { followButton.visibility = View.GONE unblockButton.visibility = View.GONE unmuteButton.visibility = View.GONE } if (!simple) { descriptionView.spannable = user.description_unescaped descriptionView.hideIfEmpty() locationView.spannable = user.location locationView.hideIfEmpty() urlView.spannable = user.url_expanded urlView.hideIfEmpty() val locale = Locale.getDefault() statusesCountView.text = Utils.getLocalizedNumber(locale, user.statuses_count) followersCountView.text = Utils.getLocalizedNumber(locale, user.followers_count) friendsCountView.text = Utils.getLocalizedNumber(locale, user.friends_count) } } override fun onClick(v: View) { when (v.id) { R.id.itemContent -> { userClickListener?.onUserClick(this, layoutPosition) } R.id.acceptRequest -> { requestClickListener?.onAcceptClicked(this, layoutPosition) } R.id.denyRequest -> { requestClickListener?.onDenyClicked(this, layoutPosition) } R.id.follow -> { friendshipClickListener?.onFollowClicked(this, layoutPosition) } R.id.unblock -> { friendshipClickListener?.onUnblockClicked(this, layoutPosition) } R.id.unmute -> { friendshipClickListener?.onUnmuteClicked(this, layoutPosition) } } } override fun onLongClick(v: View): Boolean { when (v.id) { R.id.itemContent -> { return userClickListener?.onUserLongClick(this, layoutPosition) ?: false } } return false } fun setOnClickListeners() { setUserClickListener(adapter.userClickListener) setActionClickListeners(adapter.requestClickListener, adapter.friendshipClickListener) } private fun setActionClickListeners(requestClickListener: RequestClickListener?, friendshipClickListener: FriendshipClickListener?) { this.requestClickListener = requestClickListener this.friendshipClickListener = friendshipClickListener if (requestClickListener != null || friendshipClickListener != null) { nameView.twoLine = true actionsProgressContainer.visibility = View.VISIBLE } else { nameView.twoLine = false actionsProgressContainer.visibility = View.GONE } nameView.updateText() acceptRequestButton.setOnClickListener(this) denyRequestButton.setOnClickListener(this) followButton.setOnClickListener(this) unblockButton.setOnClickListener(this) unmuteButton.setOnClickListener(this) } fun setTextSize(textSize: Float) { descriptionView.textSize = textSize externalIndicator.textSize = textSize nameView.setPrimaryTextSize(textSize) nameView.setSecondaryTextSize(textSize * 0.75f) locationView.textSize = textSize urlView.textSize = textSize statusesCountView.textSize = textSize followersCountView.textSize = textSize friendsCountView.textSize = textSize } fun setUserClickListener(listener: UserClickListener?) { userClickListener = listener (itemContent as View).setOnClickListener(this) itemContent.setOnLongClickListener(this) } fun setupViewOptions() { profileImageView.style = adapter.profileImageStyle setTextSize(adapter.textSize) } private fun RelativeLayout.LayoutParams.clearVerticalRules() { intArrayOf(RelativeLayout.ABOVE, RelativeLayout.BELOW, RelativeLayout.ALIGN_BASELINE, RelativeLayout.ALIGN_TOP, RelativeLayout.ALIGN_BOTTOM).forEach { verb -> addRule(verb, 0) } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/view/holder/UserViewHolder.kt
57122757
/* * 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.fragment import android.content.SharedPreferences.OnSharedPreferenceChangeListener import android.os.Bundle import android.preference.PreferenceActivity.EXTRA_SHOW_FRAGMENT import android.text.TextUtils import android.view.Menu import android.view.MenuInflater import android.widget.CompoundButton import de.vanita5.twittnuker.R import de.vanita5.twittnuker.TwittnukerConstants.ACCOUNT_PREFERENCES_NAME_PREFIX import de.vanita5.twittnuker.constant.IntentConstants.EXTRA_ACCOUNT import de.vanita5.twittnuker.constant.SharedPreferenceConstants.KEY_NAME_FIRST import de.vanita5.twittnuker.model.AccountDetails abstract class BaseAccountPreferenceFragment : BasePreferenceFragment() { protected val account: AccountDetails? get() { return arguments?.getParcelable(EXTRA_ACCOUNT) } protected abstract val preferencesResource: Int protected abstract val switchPreferenceDefault: Boolean protected abstract val switchPreferenceKey: String? private val preferenceChangeListener = OnSharedPreferenceChangeListener { _, key -> if (key == switchPreferenceKey) { updatePreferenceScreen() } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { val pm = preferenceManager val account: AccountDetails = arguments.getParcelable(EXTRA_ACCOUNT) ?: return val preferenceName = "$ACCOUNT_PREFERENCES_NAME_PREFIX${account.key}" pm.sharedPreferencesName = preferenceName addPreferencesFromResource(preferencesResource) val prefs = pm.sharedPreferences prefs.registerOnSharedPreferenceChangeListener(preferenceChangeListener) val activity = activity val intent = activity.intent if (intent.hasExtra(EXTRA_SHOW_FRAGMENT)) { val nameFirst = prefs.getBoolean(KEY_NAME_FIRST, true) val name = userColorNameManager.getDisplayName(account.key, account.user.name, account.user.screen_name, nameFirst) activity.title = name } updatePreferenceScreen() } override fun onDestroy() { val pm = preferenceManager val prefs = pm.sharedPreferences prefs.unregisterOnSharedPreferenceChangeListener(preferenceChangeListener) super.onDestroy() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { val switchKey = switchPreferenceKey if (!TextUtils.isEmpty(switchKey)) { inflater.inflate(R.menu.menu_switch_preference, menu) val actionView = menu.findItem(R.id.toggle).actionView val toggle = actionView.findViewById<CompoundButton>(android.R.id.toggle) val prefs = preferenceManager.sharedPreferences toggle.setOnCheckedChangeListener { _, isChecked -> val editor = prefs.edit() if (prefs.getBoolean(switchPreferenceKey, switchPreferenceDefault) != isChecked) { editor.putBoolean(switchPreferenceKey, isChecked) editor.apply() onSwitchPreferenceChanged(isChecked) updatePreferenceScreen() } } toggle.isChecked = prefs.getBoolean(switchKey, switchPreferenceDefault) } super.onCreateOptionsMenu(menu, inflater) } protected open fun onSwitchPreferenceChanged(isChecked: Boolean) { } private fun updatePreferenceScreen() { val screen = preferenceScreen val sharedPreferences = preferenceManager.sharedPreferences if (screen == null || sharedPreferences == null) return screen.isEnabled = sharedPreferences.getBoolean(switchPreferenceKey, switchPreferenceDefault) } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/fragment/BaseAccountPreferenceFragment.kt
1353255382
package org.wikipedia.analytics import android.os.Build import androidx.core.app.NotificationManagerCompat import org.json.JSONObject import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.json.JsonUtil import org.wikipedia.notifications.NotificationCategory import org.wikipedia.notifications.NotificationFilterActivity import org.wikipedia.settings.Prefs class NotificationPreferencesFunnel(app: WikipediaApp) : Funnel(app, SCHEMA_NAME, REV_ID) { override fun preprocessSessionToken(eventData: JSONObject) {} fun done() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notificationManagerCompat = NotificationManagerCompat.from(app) val toggleMap = NotificationCategory.MAP.valueIterator().asSequence().associate { val importance = notificationManagerCompat.getNotificationChannel(it.id)?.importance // TODO: figure out the "Show notifications" status it.id to (importance != NotificationManagerCompat.IMPORTANCE_NONE && importance != null && notificationManagerCompat.areNotificationsEnabled()) } log( "type_toggles", JsonUtil.encodeToString(toggleMap), "background_fetch", app.resources.getInteger(R.integer.notification_poll_interval_minutes) ) } } fun logNotificationFilterPrefs() { val excludedWikiCodes = Prefs.notificationExcludedWikiCodes val excludedTypeCodes = Prefs.notificationExcludedTypeCodes val fullFiltersList = NotificationFilterActivity.allWikisList() + NotificationFilterActivity.allTypesIdList() val toggleMap = fullFiltersList.associateWith { !excludedWikiCodes.contains(it) && !excludedTypeCodes.contains(it) } log("type_toggles", JsonUtil.encodeToString(toggleMap)) } fun logSearchClick() { log("type_toggles", "search_clicked") } fun logFilterClick() { log("type_toggles", "filter_clicked") } companion object { private const val SCHEMA_NAME = "MobileWikiAppNotificationPreferences" private const val REV_ID = 22083261 } }
app/src/main/java/org/wikipedia/analytics/NotificationPreferencesFunnel.kt
3512429793
package com.stripe.example.activity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.stripe.android.model.PaymentMethod import com.stripe.android.model.PaymentMethodCreateParams import com.stripe.example.databinding.CreateCardPaymentMethodActivityBinding import com.stripe.example.databinding.PaymentMethodItemBinding class CreateCardPaymentMethodActivity : AppCompatActivity() { private val viewBinding: CreateCardPaymentMethodActivityBinding by lazy { CreateCardPaymentMethodActivityBinding.inflate(layoutInflater) } private val viewModel: PaymentMethodViewModel by viewModels() private val adapter: PaymentMethodsAdapter = PaymentMethodsAdapter() private val snackbarController: SnackbarController by lazy { SnackbarController(viewBinding.coordinator) } private val keyboardController: KeyboardController by lazy { KeyboardController(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(viewBinding.root) viewBinding.paymentMethods.setHasFixedSize(false) viewBinding.paymentMethods.layoutManager = LinearLayoutManager(this) viewBinding.paymentMethods.adapter = adapter viewBinding.cardFormView.setCardValidCallback { isValid, invalidFields -> viewBinding.createButton.isEnabled = isValid Log.d( CARD_VALID_CALLBACK_TAG, "Card information is " + (if (isValid) " valid" else " invalid") ) if (!isValid) { Log.d(CARD_VALID_CALLBACK_TAG, " Invalid fields are $invalidFields") } } viewBinding.createButton.setOnClickListener { keyboardController.hide() viewBinding.cardFormView.cardParams?.let { createPaymentMethod(PaymentMethodCreateParams.createCard(it)) } } viewBinding.toggleCardFormView.setOnClickListener { viewBinding.cardFormView.isEnabled = !viewBinding.cardFormView.isEnabled showSnackbar( if (viewBinding.cardFormView.isEnabled) { "CardFormView Enabled" } else { "CardFormView Disabled" } ) } } private fun createPaymentMethod(params: PaymentMethodCreateParams) { onCreatePaymentMethodStart() viewModel.createPaymentMethod(params).observe(this) { result -> onCreatePaymentMethodCompleted() result.fold( onSuccess = ::onCreatedPaymentMethod, onFailure = { showSnackbar(it.message.orEmpty()) } ) } } private fun showSnackbar(message: String) { snackbarController.show(message) } private fun onCreatePaymentMethodStart() { viewBinding.progressBar.visibility = View.VISIBLE viewBinding.createButton.isEnabled = false } private fun onCreatePaymentMethodCompleted() { viewBinding.progressBar.visibility = View.INVISIBLE viewBinding.createButton.isEnabled = true } private fun onCreatedPaymentMethod(paymentMethod: PaymentMethod?) { if (paymentMethod != null) { adapter.paymentMethods.add(0, paymentMethod) adapter.notifyItemInserted(0) } else { showSnackbar("Created null PaymentMethod") } } private class PaymentMethodsAdapter : RecyclerView.Adapter<PaymentMethodsAdapter.PaymentMethodViewHolder>() { val paymentMethods: MutableList<PaymentMethod> = mutableListOf() init { setHasStableIds(true) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PaymentMethodViewHolder { return PaymentMethodViewHolder( PaymentMethodItemBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int { return paymentMethods.size } override fun onBindViewHolder(holder: PaymentMethodViewHolder, position: Int) { holder.setPaymentMethod(paymentMethods[position]) } override fun getItemId(position: Int): Long { return requireNotNull(paymentMethods[position].id).hashCode().toLong() } class PaymentMethodViewHolder internal constructor( private val viewBinding: PaymentMethodItemBinding ) : RecyclerView.ViewHolder(viewBinding.root) { internal fun setPaymentMethod(paymentMethod: PaymentMethod) { val card = paymentMethod.card viewBinding.paymentMethodId.text = paymentMethod.id viewBinding.brand.text = card?.brand?.displayName.orEmpty() viewBinding.last4.text = card?.last4.orEmpty() } } } private companion object { private const val CARD_VALID_CALLBACK_TAG = "CardValidCallback" } }
example/src/main/java/com/stripe/example/activity/CreateCardPaymentMethodActivity.kt
3382696362
package com.stripe.android.view import android.webkit.ConsoleMessage import com.google.common.truth.Truth.assertThat import com.stripe.android.FakeLogger import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.robolectric.RobolectricTestRunner import kotlin.test.Test @RunWith(RobolectricTestRunner::class) class PaymentAuthWebChromeClientTest { private val logger = FakeLogger() private val webChromeClient = PaymentAuthWebChromeClient( mock(), logger ) @Test fun `onConsoleMessage should write to logger`() { webChromeClient.onConsoleMessage( ConsoleMessage("hello world", "", 0, ConsoleMessage.MessageLevel.DEBUG) ) assertThat(logger.debugLogs) .containsExactly("hello world") } }
payments-core/src/test/java/com/stripe/android/view/PaymentAuthWebChromeClientTest.kt
1974951193
package com.projectcitybuild import com.projectcitybuild.entities.PlayerConfig import java.time.LocalDateTime import java.util.UUID fun PlayerConfigMock(uuid: UUID? = null): PlayerConfig { return PlayerConfig( id = 1, uuid = uuid ?: UUID.randomUUID(), isMuted = false, isAllowingTPs = true, firstSeen = LocalDateTime.now(), ) }
src/test/com/projectcitybuild/stubs/PlayerConfigMock.kt
4040361725
package glmatrix import kotlin.js.Math open class GlMatrix { companion object { /** * Common utilities * @module GlMatrix */ // Configuration Constants val EPSILON = 0.000001 val RANDOM = Math.random() private val degree = Math.PI / 180 /** * Convert Degree To Radian * * @param {Double} angleInDegree Angle in Degrees */ fun toRadian(angleInDegree: Double): Double { return angleInDegree * degree } /** * Convert Degree To Radian * * @param {Float} angleInDegree Angle in Degrees */ fun toRadian(angleInDegree: Float): Double { return angleInDegree * degree } fun perspectiveProjectionMatrix(fieldOfViewInRadians: Float, aspectRatio: Float, near: Float, far: Float): Array<Float> { val f = (1.0 / Math.tan(fieldOfViewInRadians / 2.0)).toFloat() val rangeInv = 1 / (near - far) return arrayOf( f / aspectRatio, 0.0f, 0.0f, 0.0f, 0.0f, f, 0.0f, 0.0f, 0.0f, 0.0f, (near + far) * rangeInv, -1.0f, 0.0f, 0.0f, near * far * rangeInv * 2, 0.0f ) } fun orthographicProjectionMatrix(left: Float, right: Float, bottom: Float, top: Float, near: Float, far: Float): Array<Float> { return arrayOf( 2.0f / (right - left), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (top - bottom), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (near - far), 0.0f, (left + right) / (left - right), (bottom + top) / (bottom - top), (near + far) / (near - far), 1.0f ) } } }
src/main/kotlin/glmatrix/GlMatrix.kt
3041076805
/* * 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.camera.camera2.pipe.integration import androidx.annotation.RequiresApi import androidx.camera.camera2.pipe.integration.adapter.CameraFactoryAdapter import androidx.camera.camera2.pipe.integration.adapter.CameraSurfaceAdapter import androidx.camera.camera2.pipe.integration.adapter.CameraUseCaseAdapter import androidx.camera.core.CameraXConfig /** * Convenience class for generating a pre-populated CameraPipe based [CameraXConfig]. */ @RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java class CameraPipeConfig private constructor() { /** * @hide */ companion object { /** * Creates a [CameraXConfig] containing a default CameraPipe implementation for CameraX. */ @JvmStatic fun defaultConfig(): CameraXConfig { return CameraXConfig.Builder() .setCameraFactoryProvider(::CameraFactoryAdapter) .setDeviceSurfaceManagerProvider(::CameraSurfaceAdapter) .setUseCaseConfigFactoryProvider(::CameraUseCaseAdapter) .build() } } }
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/CameraPipeConfig.kt
234759307
/* * 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.ui.window import androidx.compose.runtime.Recomposer import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.Snapshot import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.takeWhile import kotlinx.coroutines.runBlocking import kotlinx.coroutines.swing.Swing import kotlinx.coroutines.withTimeout import kotlinx.coroutines.yield import org.junit.Assume.assumeFalse import java.awt.GraphicsEnvironment @OptIn(ExperimentalCoroutinesApi::class) internal fun runApplicationTest( /** * Use delay(500) additionally to `yield` in `await*` functions * * Set this property only if you sure that you can't easily make the test deterministic * (non-flaky). * * We have to use `useDelay` in some Linux Tests, because Linux can behave in * non-deterministic way when we change position/size very fast (see the snippet below) */ useDelay: Boolean = false, body: suspend WindowTestScope.() -> Unit ) { assumeFalse(GraphicsEnvironment.getLocalGraphicsEnvironment().isHeadlessInstance) runBlocking(Dispatchers.Swing) { withTimeout(30000) { val testScope = WindowTestScope(this, useDelay) if (testScope.isOpen) { testScope.body() } } } } /* Snippet that demonstrated the issue with window state listening on Linux import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.runBlocking import kotlinx.coroutines.swing.Swing import kotlinx.coroutines.yield import java.awt.Point import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.JFrame fun main() { runBlocking(Dispatchers.Swing) { repeat(10) { val actions = mutableListOf<String>() val frame = JFrame() frame.addComponentListener(object : ComponentAdapter() { override fun componentMoved(e: ComponentEvent?) { actions.add(frame.x.toString()) } }) frame.location = Point(200, 200) frame.isVisible = true yield() // delay(200) actions.add("set300") frame.location = Point(300, 300) delay(200) /** * output is [200, set300, 300, 200, 300] on Linux * (see 200, 300 at the end, they are unexpected events that make impossible to write * robust tests without delays) */ println(actions) frame.dispose() } } } */ internal class WindowTestScope( private val scope: CoroutineScope, private val useDelay: Boolean ) : CoroutineScope by CoroutineScope(scope.coroutineContext + Job()) { var isOpen by mutableStateOf(true) private val initialRecomposers = Recomposer.runningRecomposers.value fun exitApplication() { isOpen = false } suspend fun awaitIdle() { if (useDelay) { delay(500) } // TODO(demin): It seems this not-so-good synchronization // doesn't cause flakiness in our window tests. // But more robust solution will be to use something like // TestCoroutineDispatcher/FlushCoroutineDispatcher (but we can't use it in a pure form, // because there are Swing/system events that we don't control). // Most of the work usually is done after the first yield(), almost all of the work - // after fourth yield() repeat(100) { yield() } Snapshot.sendApplyNotifications() for (recomposerInfo in Recomposer.runningRecomposers.value - initialRecomposers) { recomposerInfo.state.takeWhile { it > Recomposer.State.Idle }.collect() } } }
compose/ui/ui/src/desktopTest/kotlin/androidx/compose/ui/window/TestUtils.kt
3332929499
package com.vimeo.networking2.properties class PrivatePropertyContainer { private val foo: String = "foo" }
model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/properties/PrivatePropertyContainer.kt
1038201341
package us.cornus.rotlin.path /** * Created by ejw on 5/30/17. */ import us.cornus.rotlin.shift import us.cornus.rotlin.push data class DJItem(val x : Int, val y : Int, val prev : DJItem?) /** * @class Simplified Dijkstra's algorithm: all edges have a value of 1 * @augments ROT.Path * @see ROT.Path */ class Dijkstra(toX : Int, toY : Int, options : PathOptions, passableCallback: PathCallback) : Path(toX, toY, options, passableCallback) { constructor(toX : Int, toY : Int, topology: Int = 8, passableCallback: PathCallback) : this(toX, toY, PathOptions(topology), passableCallback) constructor(toX: Int, toY : Int, passableCallback: PathCallback, options: PathOptions) : this(toX, toY, options, passableCallback) private val computed = HashMap<String, DJItem>() private val todo = ArrayList<DJItem>() init { add(toX, toY, null) } /** * Compute a path from a given point * @see Path#compute */ override fun compute(fromX : Int, fromY : Int, callback : PathCallback) { val key = "$fromX,$fromY" if (key !in computed) { _compute(fromX, fromY) } if (key !in computed) { return } var item = computed[key] while (item != null) { callback(item.x, item.y) item = item.prev } } /** * Compute a non-cached value */ private fun _compute(fromX : Int, fromY : Int) { while (todo.size != 0) { val item = todo.shift()!! if (item.x == fromX && item.y == fromY) { return } val neighbors = this._getNeighbors(item.x, item.y) for ((x, y) in neighbors) { val id = "$x,$y" if (id in computed) { continue } /* already done */ add(x, y, item) } } } private fun add(x : Int, y : Int, prev : DJItem?) { val obj = DJItem( x = x, y = y, prev = prev ) computed["$x,$y"] = obj todo.push(obj) } }
src/main/kotlin/us/cornus/rotlin/path/Dijkstra.kt
3690698665
package com.gh0u1l5.wechatmagician.frontend.wechat import android.view.View data class ListPopupWindowPosition( val anchor: View, val x: Int, val y: Int)
app/src/main/kotlin/com/gh0u1l5/wechatmagician/frontend/wechat/ListPopupWindowPosition.kt
3123951426
package org.jetbrains.fortran.lang.parsing import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.io.FileUtilRt import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.IFileElementType import com.intellij.testFramework.ParsingTestCase import com.intellij.util.PathUtil import org.jetbrains.fortran.FortranFixedFormLanguage import org.jetbrains.fortran.FortranLanguage import org.jetbrains.fortran.lang.parser.FortranFixedFormParserDefinition import org.jetbrains.fortran.lang.parser.FortranParserDefinition import org.jetbrains.fortran.lang.stubs.FortranFileStub abstract class FortranBaseParsingTestCase : ParsingTestCase( ".", "f", FortranParserDefinition(), FortranFixedFormParserDefinition() ) { override fun getTestDataPath() = "src/test/resources/psi" override fun includeRanges() = true fun doPreprocessorParsingTest(filePath: String) { doBaseTest(filePath, FortranFileStub.Type) } @Throws(Exception::class) fun doParsingTest(filePath: String) { if (filePath.endsWith(".f") || filePath.endsWith(".for")) { doBaseTest(filePath, IFileElementType(FortranFixedFormLanguage)) } else { doBaseTest(filePath, IFileElementType(FortranLanguage)) } } @Throws(Exception::class) private fun doBaseTest(filePath: String, fileType: IElementType) { myLanguage = fileType.language myFileExt = FileUtilRt.getExtension(PathUtil.getFileName(filePath)) myFile = createPsiFile(FileUtil.getNameWithoutExtension(PathUtil.getFileName(filePath)), loadFile(filePath)) doCheckResult(myFullDataPath, filePath.replace("\\.(for|f90|f95|f03|f08|f)".toRegex(), ".txt"), toParseTreeText(myFile, false, false).trim()) } }
src/test/kotlin/org/jetbrains/fortran/lang/parsing/FortranBaseParsingTestCase.kt
3929081837
package com.takwolf.android.demo.hfrecyclerview.ui.activity import android.os.Bundle import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.takwolf.android.demo.hfrecyclerview.R import com.takwolf.android.demo.hfrecyclerview.databinding.ActivityRecyclerViewBinding import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotoDeleteListener import com.takwolf.android.demo.hfrecyclerview.ui.adapter.OnPhotosSwapListener import com.takwolf.android.demo.hfrecyclerview.ui.adapter.StaggeredHorizontalAdapter import com.takwolf.android.demo.hfrecyclerview.vm.SingleListViewModel import com.takwolf.android.demo.hfrecyclerview.vm.holder.setupView class StaggeredHorizontalActivity : AppCompatActivity() { private val viewModel: SingleListViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityRecyclerViewBinding.inflate(layoutInflater) binding.toolbar.setTitle(R.string.staggered_horizontal) binding.toolbar.setNavigationOnClickListener { finish() } binding.recyclerView.layoutManager = StaggeredGridLayoutManager(3, RecyclerView.HORIZONTAL) viewModel.extraHolder.setupHorizontal(layoutInflater, binding.recyclerView, binding.hfDashboard) val adapter = StaggeredHorizontalAdapter(layoutInflater).apply { onPhotosSwapListener = OnPhotosSwapListener(viewModel.photosHolder) onPhotoDeleteListener = OnPhotoDeleteListener(viewModel.photosHolder) } binding.recyclerView.adapter = adapter viewModel.photosHolder.setupView(this, adapter) setContentView(binding.root) } }
app/src/main/java/com/takwolf/android/demo/hfrecyclerview/ui/activity/StaggeredHorizontalActivity.kt
2811986851
package com.habitrpg.android.habitica.models.inventory import io.realm.RealmObject import io.realm.annotations.PrimaryKey open class HatchingPotion : RealmObject(), Item { @PrimaryKey override var key: String = "" override var text: String = "" override var event: ItemEvent? = null var notes: String? = null override var value: Int = 0 var limited: Boolean? = null var premium: Boolean? = null override val type: String get() = "hatchingPotions" }
Habitica/src/main/java/com/habitrpg/android/habitica/models/inventory/HatchingPotion.kt
2374409654
package org.thoughtcrime.securesms.database.model import android.os.Parcelable import kotlinx.parcelize.Parcelize /** * Represents a pair of values that can be used to find a message. Because we have two tables, * that means this has both the primary key and a boolean indicating which table it's in. */ @Parcelize data class MessageId( val id: Long, @get:JvmName("isMms") val mms: Boolean ) : Parcelable { fun serialize(): String { return "$id|$mms" } companion object { /** * Returns null for invalid IDs. Useful when pulling a possibly-unset ID from a database, or something like that. */ @JvmStatic fun fromNullable(id: Long, mms: Boolean): MessageId? { return if (id > 0) { MessageId(id, mms) } else { null } } @JvmStatic fun deserialize(serialized: String): MessageId { val parts: List<String> = serialized.split("|") return MessageId(parts[0].toLong(), parts[1].toBoolean()) } } }
app/src/main/java/org/thoughtcrime/securesms/database/model/MessageId.kt
1504112830
/******************************************************************************* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *******************************************************************************/ package org.jetbrains.kotlin.ui.editors import org.eclipse.core.runtime.jobs.Job import org.eclipse.jdt.core.IJavaProject import org.eclipse.jdt.core.JavaCore import org.eclipse.jface.text.IDocument import org.eclipse.swt.widgets.Composite import org.eclipse.ui.PlatformUI import org.jetbrains.kotlin.core.builder.KotlinPsiManager import org.jetbrains.kotlin.core.model.KotlinScriptEnvironment import org.jetbrains.kotlin.core.model.getEnvironment import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.script.KotlinScriptExternalDependencies import org.jetbrains.kotlin.ui.editors.annotations.KotlinLineAnnotationsReconciler import org.jetbrains.kotlin.script.ScriptDependenciesProvider import kotlin.script.experimental.dependencies.ScriptDependencies class KotlinScriptEditor : KotlinCommonEditor() { override val parsedFile: KtFile? get() { val file = eclipseFile ?: return null return KotlinPsiManager.getKotlinFileIfExist(file, document.get()) } override val javaProject: IJavaProject? by lazy { eclipseFile?.let { JavaCore.create(it.getProject()) } } override val document: IDocument get() = getDocumentProvider().getDocument(getEditorInput()) override fun createPartControl(parent: Composite) { super.createPartControl(parent) val file = eclipseFile ?: return val environment = getEnvironment(file) as KotlinScriptEnvironment environment.initializeScriptDefinitions { scriptDefinitions, classpath -> if (file.isAccessible && isOpen()) { reconcile { KotlinScriptEnvironment.replaceEnvironment(file, scriptDefinitions, classpath, null) } } } } override val isScript: Boolean get() = true override fun dispose() { val file = eclipseFile if (file != null && file.exists()) { val family = KotlinScriptEnvironment.constructFamilyForInitialization(file); Job.getJobManager().cancel(family); } super.dispose() eclipseFile?.let { KotlinScriptEnvironment.removeKotlinEnvironment(it) KotlinPsiManager.removeFile(it) } } internal fun reconcile(runBeforeReconciliation: () -> Unit = {}) { kotlinReconcilingStrategy.reconcile(runBeforeReconciliation) } } fun getScriptDependencies(editor: KotlinScriptEditor): ScriptDependencies? { val eclipseFile = editor.eclipseFile ?: return null val project = getEnvironment(eclipseFile).project val definition = ScriptDependenciesProvider.getInstance(project) val ktFile = editor.parsedFile ?: return null return definition.getScriptDependencies(ktFile) } fun KotlinCommonEditor.isOpen(): Boolean { for (window in PlatformUI.getWorkbench().getWorkbenchWindows()) { for (page in window.getPages()) { for (editorReference in page.getEditorReferences()) { if (editorReference.getEditor(false) == this) { return true } } } } return false }
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/editors/KotlinScriptEditor.kt
701155679
package org.elm.lang.core.resolve.reference import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.elm.lang.core.psi.ElmNamedElement import org.elm.lang.core.psi.ElmPsiFactory import org.elm.lang.core.psi.ElmQID import org.elm.lang.core.psi.elements.ElmUpperCaseQID import org.elm.lang.core.psi.elements.ElmValueQID import org.elm.lang.core.psi.offsetIn import org.elm.lang.core.resolve.ElmReferenceElement import org.elm.lang.core.resolve.scope.GlobalScope import org.elm.lang.core.resolve.scope.ModuleScope import org.elm.lang.core.stubs.index.ElmModulesIndex /** * A module-name (or alias) reference which qualifies a name from the value or type namespaces. * * e.g. `Data.User` in the expression `Data.User.name defaultUser` * * e.g. the `DU` alias in the expression `DU.name` in the program: * ``` * import Data.User as DU * f x = DU.name x * ``` * * @param elem the Psi element which owns the reference * @param elementQID the QID (qualified ID) element within `elem` */ class ModuleNameQualifierReference<T : ElmReferenceElement>( elem: T, private val elementQID: ElmQID, // IMPORTANT: do not use in stub-based codepaths; denormalize instead! qualifierPrefix: String // denormalized from [elementQID] to support Stubs ) : ElmReferenceCached<T>(elem), ElmReference { private val refText: String = qualifierPrefix override fun resolveInner(): ElmNamedElement? { val clientFile = element.elmFile val importDecls = ModuleScope.getImportDecls(clientFile) // First, check to see if it resolves to an aliased import for (decl in importDecls) { val asClause = decl.asClause if (asClause?.name == refText) return asClause } // Otherwise, try to resolve the import directly val targetModuleName = GlobalScope.defaultAliases[refText] ?: refText val targetDecl = ElmModulesIndex.get(targetModuleName, clientFile) ?: return null // Ensure that it's in scope return when { targetModuleName in GlobalScope.defaultImports -> targetDecl importDecls.any { it.moduleQID.text == refText } -> targetDecl else -> null } } override fun getVariants(): Array<ElmNamedElement> { // Code-completion of Elm module names is not done via the PsiReference 'variant' system. // Instead, see `ElmCompletionProvider` return emptyArray() } override fun calculateDefaultRangeInElement(): TextRange { val startOffset = elementQID.offsetIn(element) return TextRange(startOffset, startOffset + refText.length) } override fun handleElementRename(newElementName: String): PsiElement { val factory = ElmPsiFactory(element.project) val nameParts = elementQID.text.split(".") val newName = newElementName + "." + nameParts.last() val newId = when (elementQID) { is ElmUpperCaseQID -> factory.createUpperCaseQID(newName) is ElmValueQID -> factory.createValueQID(newName) else -> error("unexpected QID type") } elementQID.replace(newId) return element } }
src/main/kotlin/org/elm/lang/core/resolve/reference/ModuleNameQualifierReference.kt
2661308034
<selection>fun <A, <caret>B> foo() { }</selection>
kotlin-eclipse-ui-test/testData/wordSelection/selectEnclosing/TypeParameters/2.kt
1563502422
package io.mockk.it import io.mockk.every import io.mockk.mockk import io.mockk.util.assertArrayEquals import io.mockk.verify import kotlin.test.Test class ArraysTest { val mock = mockk<MockCls>() @Test fun booleanArray() { every { mock.arrayOp(BooleanArray(3, { true })) } returns BooleanArray(3, { false }) assertArrayEquals(BooleanArray(3, { false }), mock.arrayOp(BooleanArray(3, { true }))) verify { mock.arrayOp(BooleanArray(3, { true })) } } @Test fun byteArray() { every { mock.arrayOp(ByteArray(3, { (it + 1).toByte() })) } returns ByteArray(3, { (3 - it).toByte() }) assertArrayEquals(ByteArray(3, { (3 - it).toByte() }), mock.arrayOp(ByteArray(3, { (it + 1).toByte() }))) verify { mock.arrayOp(ByteArray(3, { (it + 1).toByte() })) } } @Test fun shortArray() { every { mock.arrayOp(ShortArray(3, { (it + 1).toShort() })) } returns ShortArray(3, { (3 - it).toShort() }) assertArrayEquals(ShortArray(3, { (3 - it).toShort() }), mock.arrayOp(ShortArray(3, { (it + 1).toShort() }))) verify { mock.arrayOp(ShortArray(3, { (it + 1).toShort() })) } } @Test fun charArray() { every { mock.arrayOp(CharArray(3, { (it + 1).toChar() })) } returns CharArray(3, { (3 - it).toChar() }) assertArrayEquals(CharArray(3, { (3 - it).toChar() }), mock.arrayOp(CharArray(3, { (it + 1).toChar() }))) verify { mock.arrayOp(CharArray(3, { (it + 1).toChar() })) } } @Test fun intArray() { every { mock.arrayOp(IntArray(3, { it + 1 })) } returns IntArray(3, { 3 - it }) assertArrayEquals(IntArray(3, { 3 - it }), mock.arrayOp(IntArray(3, { it + 1 }))) verify { mock.arrayOp(IntArray(3, { it + 1 })) } } @Test fun longArray() { every { mock.arrayOp(LongArray(3, { (it + 1).toLong() })) } returns LongArray(3, { (3 - it).toLong() }) assertArrayEquals(LongArray(3, { (3 - it).toLong() }), mock.arrayOp(LongArray(3, { (it + 1).toLong() }))) verify { mock.arrayOp(LongArray(3, { (it + 1).toLong() })) } } @Test fun floatArray() { every { mock.arrayOp(FloatArray(3, { (it + 1).toFloat() })) } returns FloatArray(3, { (3 - it).toFloat() }) assertArrayEquals( FloatArray(3, { (3 - it).toFloat() }), mock.arrayOp(FloatArray(3, { (it + 1).toFloat() })), 1e-6f ) verify { mock.arrayOp(FloatArray(3, { (it + 1).toFloat() })) } } @Test fun doubleArray() { every { mock.arrayOp(DoubleArray(3, { (it + 1).toDouble() })) } returns DoubleArray(3, { (3 - it).toDouble() }) assertArrayEquals( DoubleArray(3, { (3 - it).toDouble() }), mock.arrayOp(DoubleArray(3, { (it + 1).toDouble() })), 1e-6 ) verify { mock.arrayOp(DoubleArray(3, { (it + 1).toDouble() })) } } @Test fun booleanObjectArray() { every { mock.arrayOp(Array(3, { true })) } returns Array(3, { false }) assertArrayEquals(Array(3, { false }), mock.arrayOp(Array(3, { true }))) verify { mock.arrayOp(Array(3, { true })) } } @Test fun byteObjectArray() { every { mock.arrayOp(Array(3, { (it + 1).toByte() })) } returns Array(3, { (3 - it).toByte() }) assertArrayEquals(Array(3, { (3 - it).toByte() }), mock.arrayOp(Array(3, { (it + 1).toByte() }))) verify { mock.arrayOp(Array(3, { (it + 1).toByte() })) } } @Test fun shortObjectArray() { every { mock.arrayOp(Array(3, { (it + 1).toShort() })) } returns Array(3, { (3 - it).toShort() }) assertArrayEquals( Array(3, { (3 - it).toShort() }), mock.arrayOp(Array(3, { (it + 1).toShort() })) ) verify { mock.arrayOp(Array(3, { (it + 1).toShort() })) } } @Test fun charObjectArray() { every { mock.arrayOp(Array(3, { (it + 1).toChar() })) } returns Array(3, { (3 - it).toChar() }) assertArrayEquals(Array(3, { (3 - it).toChar() }), mock.arrayOp(Array(3, { (it + 1).toChar() }))) verify { mock.arrayOp(Array(3, { (it + 1).toChar() })) } } @Test fun intObjectArray() { every { mock.arrayOp(Array(3, { it + 1 })) } returns Array(3, { 3 - it }) assertArrayEquals(Array(3, { 3 - it }), mock.arrayOp(Array(3, { it + 1 }))) verify { mock.arrayOp(Array(3, { it + 1 })) } } @Test fun longObjectArray() { every { mock.arrayOp(Array(3, { (it + 1).toLong() })) } returns Array(3, { (3 - it).toLong() }) assertArrayEquals(Array(3, { (3 - it).toLong() }), mock.arrayOp(Array(3, { (it + 1).toLong() }))) verify { mock.arrayOp(Array(3, { (it + 1).toLong() })) } } @Test fun floatObjectArray() { every { mock.arrayOp(Array(3, { (it + 1).toFloat() })) } returns Array(3, { (3 - it).toFloat() }) assertArrayEquals( Array(3, { (3 - it).toFloat() }), mock.arrayOp(Array(3, { (it + 1).toFloat() })) ) verify { mock.arrayOp(Array(3, { (it + 1).toFloat() })) } } @Test fun doubleObjectArray() { every { mock.arrayOp(Array(3, { (it + 1).toDouble() })) } returns Array(3, { (3 - it).toDouble() }) assertArrayEquals( Array(3, { (3 - it).toDouble() }), mock.arrayOp(Array(3, { (it + 1).toDouble() })) ) verify { mock.arrayOp(Array(3, { (it + 1).toDouble() })) } } @Test fun anyAnyObjectArray() { every { mock.arrayOp(Array<Array<Any>>(3, { i -> Array(3, { j -> i + j }) })) } returns Array(3, { i -> Array<Any>(3, { j -> j - i }) }) assertArrayEquals( Array(3, { i -> Array<Any>(3, { j -> j - i }) }), mock.arrayOp(Array(3, { i -> Array<Any>(3, { j -> i + j }) })) ) verify { mock.arrayOp(Array(3, { i -> Array<Any>(3, { j -> i + j }) })) } } @Test fun intWrapperObjectArray() { every { mock.arrayOp(any<Array<IntWrapper>>()) } answers { Array(3, { IntWrapper(it + 2) }) } assertArrayEquals( Array(3, { IntWrapper(it + 2) }), mock.arrayOp(Array(3, { IntWrapper(it + 5) })) ) verify { mock.arrayOp(Array(3, { IntWrapper(it + 5) })) } } data class IntWrapper(val data: Int) class MockCls { fun arrayOp(arr: BooleanArray) = arr.map { it }.toBooleanArray() fun arrayOp(arr: ByteArray) = arr.map { (it + 1).toByte() }.toByteArray() fun arrayOp(arr: ShortArray) = arr.map { (it + 1).toShort() }.toShortArray() fun arrayOp(arr: CharArray) = arr.map { (it + 1) }.toCharArray() fun arrayOp(arr: IntArray) = arr.map { it + 1 }.toIntArray() fun arrayOp(arr: LongArray) = arr.map { it + 1 }.toLongArray() fun arrayOp(arr: FloatArray) = arr.map { it + 1 }.toFloatArray() fun arrayOp(arr: DoubleArray) = arr.map { it + 1 }.toDoubleArray() fun arrayOp(arr: Array<Boolean>) = arr.map { it }.toTypedArray() fun arrayOp(arr: Array<Byte>) = arr.map { (it + 1).toByte() }.toTypedArray() fun arrayOp(arr: Array<Short>) = arr.map { (it + 1).toShort() }.toTypedArray() fun arrayOp(arr: Array<Char>) = arr.map { it + 1 }.toTypedArray() fun arrayOp(arr: Array<Int>) = arr.map { it + 1 }.toTypedArray() fun arrayOp(arr: Array<Long>) = arr.map { it + 1 }.toTypedArray() fun arrayOp(arr: Array<Float>) = arr.map { it + 1 }.toTypedArray() fun arrayOp(arr: Array<Double>) = arr.map { it + 1 }.toTypedArray() fun arrayOp(array: Array<Array<Any>>): Array<Array<Any>> = array.map { it.map { ((it as Int) + 1) as Any }.toTypedArray() }.toTypedArray() fun arrayOp(array: Array<IntWrapper>): Array<IntWrapper> = array.map { IntWrapper(it.data + 1) }.toTypedArray() } }
mockk/common/src/test/kotlin/io/mockk/it/ArraysTest.kt
4115397454
package br.com.vitorsalgado.example import br.com.vitorsalgado.example.api.HttpClientWithPinningProvider import com.facebook.imagepipeline.cache.ImageCacheStatsTracker import okhttp3.OkHttpClient internal class PerBuildComponentProvider { fun okHttpBuilder(): OkHttpClient.Builder { return HttpClientWithPinningProvider.client.newBuilder() } fun imageCacheStatsTracker(): ImageCacheStatsTracker? { return null } companion object { private var instance: PerBuildComponentProvider? = null fun getInstance(): PerBuildComponentProvider { if (instance == null) { instance = PerBuildComponentProvider() } return instance as PerBuildComponentProvider } } }
app/src/release/kotlin/br/com/vitorsalgado/example/PerBuildComponentProvider.kt
2328714795
package me.proxer.app.util.compat import android.app.Activity import android.app.ActivityManager import android.content.pm.PackageManager import android.graphics.BitmapFactory import android.os.Build import androidx.annotation.ColorInt import me.proxer.app.R /** * @author Ruben Gees */ object TaskDescriptionCompat { fun setTaskDescription(activity: Activity, @ColorInt primaryColor: Int) { val activityInfo = activity.packageManager.getActivityInfo( activity.componentName, PackageManager.GET_META_DATA ) val taskDescription = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { ActivityManager.TaskDescription( activity.getString(R.string.app_name), activityInfo.icon, primaryColor ) } else { @Suppress("DEPRECATION") ActivityManager.TaskDescription( activity.getString(R.string.app_name), BitmapFactory.decodeResource(activity.resources, activityInfo.icon), primaryColor ) } activity.setTaskDescription(taskDescription) } }
src/main/kotlin/me/proxer/app/util/compat/TaskDescriptionCompat.kt
3899789002
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.notifications import android.service.notification.StatusBarNotification import androidx.core.app.NotificationCompat import androidx.core.app.NotificationCompat.MessagingStyle import androidx.core.app.Person import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import java.time.Instant import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class NotificationUtilsTest { private val defaultKey = "key" @Test fun passesCarMsgRequirements_returnsTrueWhenValid() { val sbn = createSBN() val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isTrue() } @Test fun passesCarMsgRequirements_noReplyAction() { val sbn = createSBN(hasReplyAction = false) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun passesCarMsgRequirements_noMarkAsReadAction() { val sbn = createSBN(hasMarkAsRead = false) val passesStrictCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesStrictCarMsgRequirements).isFalse() val passesRelaxedCarMsgRequirements = sbn.notification.passesRelaxedCarMsgRequirements assertThat(passesRelaxedCarMsgRequirements).isTrue() } @Test fun passesCarMsgRequirements_usingInvisibleActions() { val sbn = createSBN(useInvisibleActions = true) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isTrue() } @Test fun passesCarMsgRequirements_showsUI() { val sbn = createSBN(showsUI = true) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun passesCarMsgRequirements_showsUI_InvisibleActions() { val sbn = createSBN(showsUI = true, useInvisibleActions = true) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun passesCarMsgRequirements_noMessagingStyle() { val sbn = createSBN(hasMessagingStyle = false) val passesCarMsgRequirements = sbn.notification.passesStrictCarMsgRequirements assertThat(passesCarMsgRequirements).isFalse() } @Test fun replyAction_returnsAppropriateAction() { val sbn = createSBN() val replyAction = sbn.notification.replyAction assertThat(replyAction).isNotNull() assertThat(replyAction?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) } @Test fun replyAction_returnsAppropriateActio_whenInvisible() { val sbn = createSBN(useInvisibleActions = true) val replyAction = sbn.notification.replyAction assertThat(replyAction).isNotNull() assertThat(replyAction?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_REPLY) } @Test fun replyAction_noActionFound() { val sbn = createSBN(hasReplyAction = false) val replyAction = sbn.notification.replyAction assertThat(replyAction).isNull() } @Test fun replyAction_wrongReplySemanticAction() { val sbn = createSBN(hasWrongReplySemanticAction = true) val replyAction = sbn.notification.replyAction assertThat(replyAction).isNull() } @Test fun markAsReadAction_returnsAppropriateAction() { val sbn = createSBN(hasMarkAsRead = true) val action = sbn.notification.markAsReadAction assertThat(action).isNotNull() assertThat(action?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) } @Test fun markAsReadAction_returnsAppropriateAction_whenInvisible() { val sbn = createSBN(hasMarkAsRead = true, useInvisibleActions = true) val action = sbn.notification.markAsReadAction assertThat(action).isNotNull() assertThat(action?.semanticAction) .isEqualTo(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ) } @Test fun markAsReadAction_noMarkAsReadFound() { val sbn = createSBN(hasMarkAsRead = false) val action = sbn.notification.markAsReadAction assertThat(action).isNull() } @Test fun showsUI_returnsTrueAsAppropriate() { val sbn = createSBN(showsUI = true) val showsUI = sbn.notification.showsUI assertThat(showsUI).isTrue() } @Test fun showsUI_returnsFalseAsAppropriate() { val sbn = createSBN(showsUI = false) val showsUI = sbn.notification.showsUI assertThat(showsUI).isFalse() } @Test fun messagingStyle_returnsStyleWhenFound() { val sbn = createSBN(hasMessagingStyle = true) val style = sbn.notification.messagingStyle assertThat(style).isNotNull() assertThat(sbn.notification.messagingStyle?.user?.name).isNotNull() } @Test fun lastMessage_getsAppropriateMessage() { val style = MessagingStyle(Person.Builder().setName("user").build()) val firstMessage = MessagingStyle.Message( "Text Message One", Instant.now().toEpochMilli() + 100, Person.Builder().setName("senderOne").build() ) val lastMessage = MessagingStyle.Message( "Text Message Two", Instant.now().toEpochMilli() + 200, Person.Builder().setName("senderTwo").build() ) style.addMessage(lastMessage) style.addMessage(firstMessage) assertThat(style.lastMessage).isEqualTo(lastMessage) } /** * Default functionality is a valid message [StatusBarNotification]. To make invalid, you may * customize the input. */ private fun createSBN( hasMessagingStyle: Boolean = true, isOldMessage: Boolean = false, hasReplyAction: Boolean = true, hasWrongReplySemanticAction: Boolean = false, hasMarkAsRead: Boolean = true, useInvisibleActions: Boolean = false, showsUI: Boolean = false, key: String = defaultKey, connectionTime: Instant = Instant.now(), postSpecificMessage: MessagingStyle.Message? = null ): StatusBarNotification { return MessageNotificationMocks.createSBN( hasMessagingStyle = hasMessagingStyle, isOldMessage = isOldMessage, hasReplyAction = hasReplyAction, hasWrongReplySemanticAction = hasWrongReplySemanticAction, hasMarkAsRead = hasMarkAsRead, useInvisibleActions = useInvisibleActions, key = key, showsUI = showsUI, connectionTime = connectionTime, postSpecificMessage = postSpecificMessage ) } }
communication/tests/unit/src/com/google/android/libraries/car/notifications/NotificationUtilsTest.kt
4244461807
/* * Copyright 2017 Peter Kenji Yamanaka * * 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.pyamsoft.powermanager.manage import com.pyamsoft.powermanager.base.preference.DozePreferences import com.pyamsoft.powermanager.model.PermissionObserver import io.reactivex.Completable import io.reactivex.Single import javax.inject.Inject internal class DozeExceptionInteractor @Inject internal constructor( private val permissionObserver: PermissionObserver, private val preferences: DozePreferences) : ExceptionInteractor() { override fun setIgnoreCharging(state: Boolean): Single<Boolean> { return Completable.fromAction { preferences.ignoreChargingDoze = state }.andThen( Single.just(state)) } override fun setIgnoreWear(state: Boolean): Single<Boolean> { return Completable.fromAction { preferences.ignoreWearDoze = state }.andThen(Single.just(state)) } override val isIgnoreCharging: Single<Pair<Boolean, Boolean>> get() = Single.fromCallable { Pair(preferences.dozeManaged && permissionObserver.hasPermission(), preferences.ignoreChargingDoze) } override val isIgnoreWear: Single<Pair<Boolean, Boolean>> get() = Single.fromCallable { Pair(preferences.dozeManaged && permissionObserver.hasPermission(), preferences.ignoreWearDoze) } }
powermanager-manage/src/main/java/com/pyamsoft/powermanager/manage/DozeExceptionInteractor.kt
4078784437
/* * Copyright (C) 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 com.example.woof import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material.icons.filled.ExpandMore import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.woof.data.Dog import com.example.woof.data.dogs import com.example.woof.ui.theme.WoofTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { WoofTheme { WoofApp() } } } } /** * Composable that displays an app bar and a list of dogs. */ @Composable fun WoofApp() { Scaffold( topBar = { WoofTopAppBar() } ) { LazyColumn(modifier = Modifier.background(MaterialTheme.colors.background)) { items(dogs) { DogItem(dog = it) } } } } /** * Composable that displays a list item containing a dog icon and their information. * * @param dog contains the data that populates the list item * @param modifier modifiers to set to this composable */ @Composable fun DogItem(dog: Dog, modifier: Modifier = Modifier) { var expanded by remember { mutableStateOf(false) } Card( elevation = 4.dp, modifier = modifier.padding(8.dp) ) { Column( modifier = Modifier .animateContentSize( animationSpec = spring( dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow ) ) ) { Row( modifier = Modifier .fillMaxWidth() .padding(8.dp) ) { DogIcon(dog.imageResourceId) DogInformation(dog.name, dog.age) Spacer(Modifier.weight(1f)) DogItemButton( expanded = expanded, onClick = { expanded = !expanded }, ) } if (expanded) { DogHobby(dog.hobbies) } } } } /** * Composable that displays a button that is clickable and displays an expand more or an expand less * icon. * * @param expanded represents whether the expand more or expand less icon is visible * @param onClick is the action that happens when the button is clicked * @param modifier modifiers to set to this composable */ @Composable private fun DogItemButton( expanded: Boolean, onClick: () -> Unit, modifier: Modifier = Modifier ) { IconButton(onClick = onClick) { Icon( imageVector = if (expanded) Icons.Filled.ExpandLess else Icons.Filled.ExpandMore, tint = MaterialTheme.colors.secondary, contentDescription = stringResource(R.string.expand_button_content_description), ) } } /** * Composable that displays a Top Bar with an icon and text. * * @param modifier modifiers to set to this composable */ @Composable fun WoofTopAppBar(modifier: Modifier = Modifier) { Row( modifier = modifier .fillMaxWidth() .background(color = MaterialTheme.colors.primary), verticalAlignment = Alignment.CenterVertically ) { Image( modifier = modifier .size(64.dp) .padding(8.dp), painter = painterResource(R.drawable.ic_woof_logo), /* * Content Description is not needed here - image is decorative, and setting a null * content description allows accessibility services to skip this element during * navigation. */ contentDescription = null ) Text( text = stringResource(R.string.app_name), style = MaterialTheme.typography.h1 ) } } /** * Composable that displays a photo of a dog. * * @param dogIcon is the resource ID for the image of the dog * @param modifier modifiers to set to this composable */ @Composable fun DogIcon(@DrawableRes dogIcon: Int, modifier: Modifier = Modifier) { Image( modifier = modifier .size(64.dp) .padding(8.dp) .clip(RoundedCornerShape(50)), contentScale = ContentScale.Crop, painter = painterResource(dogIcon), /* * Content Description is not needed here - image is decorative, and setting a null content * description allows accessibility services to skip this element during navigation. */ contentDescription = null ) } /** * Composable that displays a dog's name and age. * * @param dogName is the resource ID for the string of the dog's name * @param dogAge is the Int that represents the dog's age * @param modifier modifiers to set to this composable */ @Composable fun DogInformation(@StringRes dogName: Int, dogAge: Int, modifier: Modifier = Modifier) { Column { Text( text = stringResource(dogName), style = MaterialTheme.typography.h2, modifier = modifier.padding(top = 8.dp) ) Text( text = stringResource(R.string.years_old, dogAge), style = MaterialTheme.typography.body1 ) } } /** * Composable that displays a dog's hobbies. * * @param dogHobby is the resource ID for the text string of the hobby to display * @param modifier modifiers to set to this composable */ @Composable fun DogHobby(@StringRes dogHobby: Int, modifier: Modifier = Modifier) { Column( modifier = modifier.padding( start = 16.dp, top = 8.dp, bottom = 16.dp, end = 16.dp ) ) { Text( text = stringResource(R.string.about), style = MaterialTheme.typography.h3 ) Text( text = stringResource(dogHobby), style = MaterialTheme.typography.body1 ) } } /** * Composable that displays what the UI of the app looks like in light theme in the design tab. */ @Preview @Composable fun WoofPreview() { WoofTheme(darkTheme = false) { WoofApp() } } /** * Composable that displays what the UI of the app looks like in dark theme in the design tab. */ @Preview @Composable fun WoofDarkThemePreview() { WoofTheme(darkTheme = true) { WoofApp() } }
app/src/main/java/com/example/woof/MainActivity.kt
489368256
package at.ac.tuwien.caa.docscan.worker import android.content.Context import androidx.work.WorkInfo import androidx.work.WorkManager import androidx.work.WorkQuery import java.util.* /** * @return a list of some worker jobs. * * The params are set to return jobs for all tags, but only for work.info states that are != SUCCEEDED. */ fun getCurrentWorkerJobStates( context: Context, tags: List<String> = listOf( UploadWorker.UPLOAD_TAG, ExportWorker.EXPORT_TAG, DocumentSanitizeWorker.TAG ), states: List<WorkInfo.State> = WorkInfo.State.values() .filter { state -> state != WorkInfo.State.SUCCEEDED }, ): List<DocScanWorkInfo> { val docScanWorkInfos = mutableListOf<DocScanWorkInfo>() val workInfosFuture = WorkManager.getInstance(context) .getWorkInfos(WorkQuery.Builder.fromTags(tags).addStates(states).build()) // TODO: Call can throw val workInfos = workInfosFuture.get() workInfos.forEach { // we assume that a worker request was always associated with just one tag. val firstTag = it.tags.firstOrNull() if (firstTag != null) { docScanWorkInfos.add(DocScanWorkInfo(firstTag, it.id, it)) } } return docScanWorkInfos.sortedBy { docScanWorkInfo -> docScanWorkInfo.tag } } data class DocScanWorkInfo(val tag: String, val jobId: UUID, val workInfo: WorkInfo) { override fun toString(): String { return "DocScanWorkInfo{tag=${tag}, jobId=${jobId}, workInfo=$workInfo}}" } }
app/src/main/java/at/ac/tuwien/caa/docscan/worker/WorkerManagerHelper.kt
3276222863
@file:Suppress("DEPRECATION") package org.wordpress.aztec import android.test.AndroidTestCase import android.text.SpannableString import android.text.SpannableStringBuilder import androidx.test.core.app.ApplicationProvider import junit.framework.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.wordpress.aztec.source.Format @RunWith(RobolectricTestRunner::class) @Config(sdk = [23]) class CalypsoFormattingTest : AndroidTestCase() { private var parser = AztecParser(AlignmentRendering.SPAN_LEVEL) private val HTML_LINE_BREAKS = "HI<br><br><br><br><br><br>BYE" private val HTML_LINE_BREAKS_FORMATTED = "HI\n\n\n\n\n\nBYE" private val HTML_NESTED = "<span></span>" + "<div class=\"first\">" + "<div class=\"second\">" + "<div class=\"third\">" + "Div<br><span><b>b</b></span><br>Hidden" + "</div>" + "<div class=\"fourth\"></div>" + "<div class=\"fifth\"></div>" + "</div>" + "<span class=\"second last\"></span>" + "<div><span></span><div><div><span></span></div></div></div><div></div>" + "</div>" + "<br><br>" private val HTML_NESTED_CALYPSO = "<div class=\"first\">\n" + "<div class=\"second\">\n" + "<div class=\"third\">Div\n" + "<span><b>b</b></span>\n" + "Hidden</div>\n" + "<div class=\"fourth\"></div>\n" + "<div class=\"fifth\"></div>\n" + "</div>\n<div>\n<div>\n<div></div>\n" + "</div>\n</div>\n<div></div>\n</div>" private val HTML_MIXED_WITH_NEWLINES = "\n\n<span><i>Italic</i></span>\n\n<b>Bold</b><br>" + "\t<div class=\"first\">" + "<a href=\"https://github.com/wordpress-mobile/WordPress-Aztec-Android\">Link</a>" + " \t<div class=\"second\">" + " <div class=\"third\">" + " Div<br><span><b>Span</b></span><br>Hidden" + " </div>" + "<iframe class=\"classic\">Menu</iframe><br><br>" + " <div class=\"fourth\"><u>Under</u>line</div>\n\n" + " <div class=\"fifth\"></div>" + " \t\t</div>" + " <span class=\"second last\"></span>" + "</div>" + "<br>" private val HTML_MIXED_WITH_NEWLINES_CALYPSO = "<span><i>Italic</i></span> <b>Bold</b>\n" + "<div class=\"first\">" + "<a href=\"https://github.com/wordpress-mobile/WordPress-Aztec-Android\">Link</a>\n" + "<div class=\"second\">\n" + "<div class=\"third\">Div\n" + "<span><b>Span</b></span>\n" + "Hidden</div>\n" + "<iframe class=\"classic\">Menu</iframe>\n" + "<div class=\"fourth\"><u>Under</u>line</div>\n" + "<div class=\"fifth\"></div>\n</div>\n</div>" private val HTML_PARAGRAPHS_WITH_ATTRIBUTES = "a\n<p a=\"A\">b</p>\nc" private val HTML_PARAGRAPHS_MIXED = "a\n<p a=\"A\">b</p>\n<p a=\"A\">b</p>\nc\n\nd\n<p>e</p>" private val HTML_PARAGRAPHS_MIXED_CALPYSO = "a\n<p a=\"A\">b</p>\n<p a=\"A\">b</p>c\n\nd\n\ne" private val HTML_MIXED_REGEX = "\n\n<span><i>Italic</i></span>\n\n<b>Bold</b><br>" + "\t<div class=\"\$\$\$first\">" + "<a href=\"https://github.com/wordpress-mobile/Word\\Press-Aztec-Android\">Link</a>" + " \t<div class=\"sec $8 ond\"></div></div>" private val HTML_MIXED_REGEX_CALYPSO = "<span><i>Italic</i></span>\n\n<b>Bold</b>\n" + "<div class=\"\$\$\$first\">" + "<a href=\"https://github.com/wordpress-mobile/Word\\Press-Aztec-Android\">Link</a>\n" + "<div class=\"sec $8 ond\"></div>\n" + "</div>" /** * Initialize variables. */ @Before fun init() { context = ApplicationProvider.getApplicationContext() } /** * Test the conversion from HTML to visual mode with nested HTML (Calypso format) * * @throws Exception */ @Test @Throws(Exception::class) fun formatNestedHtmlCalypso() { val input = HTML_NESTED val span = SpannableString(parser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = Format.addSourceEditorFormatting(parser.toHtml(span), true) Assert.assertEquals(HTML_NESTED_CALYPSO, output) } /** * Test the conversion from HTML to visual mode with multiple line breaks (Calypso format) * * @throws Exception */ @Test @Throws(Exception::class) fun formatLineBreaksCalypso() { val input = HTML_LINE_BREAKS val span = SpannableString(parser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = Format.addSourceEditorFormatting(parser.toHtml(span), true) Assert.assertEquals(HTML_LINE_BREAKS_FORMATTED, output) } /** * Test the conversion from HTML to visual mode with mixed HTML (Calypso format) * * @throws Exception */ @Test @Throws(Exception::class) fun formatMixedHtmlCalypso() { val input = HTML_MIXED_WITH_NEWLINES val span = SpannableString(parser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = Format.addSourceEditorFormatting(parser.toHtml(span), true) Assert.assertEquals(HTML_MIXED_WITH_NEWLINES_CALYPSO, output) } /** * Test the conversion of HTML containing special regex characters * * @throws Exception */ @Test @Throws(Exception::class) fun formatRegexSpecialCharactersCalypso() { val input = Format.removeSourceEditorFormatting(HTML_MIXED_REGEX, true) val span = SpannableString(parser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = Format.addSourceEditorFormatting(parser.toHtml(span), true) Assert.assertEquals(HTML_MIXED_REGEX_CALYPSO, output) } /** * Test the preservation of paragraphs with attributes (Calypso format) * * @throws Exception */ @Test @Throws(Exception::class) fun paragraphsWithAttributes() { val input = HTML_PARAGRAPHS_WITH_ATTRIBUTES val span = SpannableString(parser.fromHtml(input, RuntimeEnvironment.application.applicationContext)) val output = Format.addSourceEditorFormatting(parser.toHtml(span), true) Assert.assertEquals(HTML_PARAGRAPHS_WITH_ATTRIBUTES, output) } /** * Test the preservation of paragraphs with attributes and removal of those without (Calypso format) * * @throws Exception */ @Test @Throws(Exception::class) fun mixedParagraphsWithAttributes() { val input = HTML_PARAGRAPHS_MIXED val span = SpannableStringBuilder(parser.fromHtml(Format.removeSourceEditorFormatting(input, true), RuntimeEnvironment.application.applicationContext)) val output = Format.addSourceEditorFormatting(parser.toHtml(span), true) Assert.assertEquals(HTML_PARAGRAPHS_MIXED_CALPYSO, output) } }
aztec/src/test/kotlin/org/wordpress/aztec/CalypsoFormattingTest.kt
3181665145
/** * 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.database.dto import com.google.gson.annotations.SerializedName import kotlin.Int import kotlin.String /** * @param id - Faculty ID * @param title - Faculty title */ data class DatabaseFaculty( @SerializedName("id") val id: Int? = null, @SerializedName("title") val title: String? = null )
api/src/main/java/com/vk/sdk/api/database/dto/DatabaseFaculty.kt
3599426082
// Author: Konrad Jamrozik, github.com/konrad-jamrozik package com.konradjamrozik import java.io.File import java.io.IOException import java.net.JarURLConnection import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption class Resource @JvmOverloads constructor(val name: String, val allowAmbiguity: Boolean = false) { val urls: List<URL> = { val urls = ClassLoader.getSystemResources(name).toList() if (urls.isEmpty()) throw IOException("No resource URLs found for path \"$name\"") if (!allowAmbiguity && urls.size > 1) throw IOException("More than one resource URL found for path $name. " + "The found URLs:\n${urls.joinToString(separator = "\n")}") urls }() val text: String by lazy { url.text } val url: URL by lazy { check(!allowAmbiguity, { "check failed: !allowAmbiguity" }) urls.single() } val path: Path by lazy { check(url.protocol == "file", { "cannot get path on a resource whose protocol is not 'file'. " + "The protocol is instead '${urls.single().protocol}'" }) Paths.get(urls.single().toURI()) } val file: File by lazy { check(!allowAmbiguity, { "check failed: !allowAmbiguity" }) File(url.toURI()) } private fun copyBesideContainer(url: URL): Path { val jarUrlConnection = url.openConnection() as JarURLConnection val jarFile = File(jarUrlConnection.jarFileURL.toURI()) // Example jarFile: C:\my\local\repos\github\utilities\build\resources\test\toplevel.jar val jarDir = jarFile.parent // Example jarDir: C:\my\local\repos\github\utilities\build\resources\test val jarEntry = jarUrlConnection.jarEntry.toString() // Example jarEntry: nested.jar val targetPath = Paths.get(jarDir, jarEntry) // Example targetPath: C:\my\local\repos\github\utilities\build\resources\test\nested.jar Files.copy(url.openStream(), targetPath) return targetPath } fun withExtractedPath(block: Path.() -> Unit) { if (url.protocol == "file") Paths.get(url.toURI()).block() else { val extractedPath = copyBesideContainer(url) extractedPath.block() check (extractedPath.isRegularFile, { ("Failure: extracted path $extractedPath has been deleted while being processed in the 'withExtractedPath' block.") }) Files.delete(extractedPath) } } fun extractTo(targetDir: Path): Path { val targetFile = if (url.protocol == "file") { targetDir.resolve(name) } else { val jarUrlConnection = url.openConnection() as JarURLConnection targetDir.resolve(jarUrlConnection.jarEntry.toString()) } targetFile.mkdirs() Files.copy(url.openStream(), targetFile, StandardCopyOption.REPLACE_EXISTING) return targetFile } }
src/main/kotlin/com/konradjamrozik/Resource.kt
3626265480
package de.pbauerochse.worklogviewer.view import de.pbauerochse.worklogviewer.timereport.Issue import de.pbauerochse.worklogviewer.timereport.IssueWithWorkItems import de.pbauerochse.worklogviewer.timereport.view.ReportRow import java.time.LocalDate /** * A row containing the work items for a certain [Issue] */ data class IssueReportRow(val issueWithWorkItems: IssueWithWorkItems) : ReportRow { override val isGrouping: Boolean = false override val isIssue: Boolean = true override val isSummary: Boolean = false override val label: String = issueWithWorkItems.issue.fullTitle override val children: List<ReportRow> = emptyList() override val totalDurationInMinutes: Long = issueWithWorkItems.totalTimeInMinutes override fun getDurationInMinutes(date: LocalDate): Long = issueWithWorkItems.getWorkItemsForDate(date).sumOf { it.durationInMinutes } }
application/src/main/java/de/pbauerochse/worklogviewer/view/IssueReportRow.kt
2544329613
package com.google.firebase.referencecode.database.kotlin import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.google.firebase.database.ChildEventListener import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.ServerValue import com.google.firebase.database.ValueEventListener import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase class OfflineActivity : AppCompatActivity() { private fun enablePersistence() { // [START rtdb_enable_persistence] Firebase.database.setPersistenceEnabled(true) // [END rtdb_enable_persistence] } private fun keepSynced() { // [START rtdb_keep_synced] val scoresRef = Firebase.database.getReference("scores") scoresRef.keepSynced(true) // [END rtdb_keep_synced] // [START rtdb_undo_keep_synced] scoresRef.keepSynced(false) // [END rtdb_undo_keep_synced] } private fun queryRecentScores() { // [START rtdb_query_recent_scores] val scoresRef = Firebase.database.getReference("scores") scoresRef.orderByValue().limitToLast(4).addChildEventListener(object : ChildEventListener { override fun onChildAdded(snapshot: DataSnapshot, previousChild: String?) { Log.d(TAG, "The ${snapshot.key} dinosaur's score is ${snapshot.value}") } // [START_EXCLUDE] override fun onChildRemoved(dataSnapshot: DataSnapshot) = Unit override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) = Unit override fun onCancelled(databaseError: DatabaseError) = Unit override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) = Unit // [END_EXCLUDE] }) // [END rtdb_query_recent_scores] // [START rtdb_query_recent_scores_overlap] scoresRef.orderByValue().limitToLast(2).addChildEventListener(object : ChildEventListener { override fun onChildAdded(snapshot: DataSnapshot, previousChild: String?) { Log.d(TAG, "The ${snapshot.key} dinosaur's score is ${snapshot.value}") } // [START_EXCLUDE] override fun onChildRemoved(dataSnapshot: DataSnapshot) = Unit override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) = Unit override fun onCancelled(databaseError: DatabaseError) = Unit override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) = Unit // [END_EXCLUDE] }) // [END rtdb_query_recent_scores_overlap] } private fun onDisconnect() { // [START rtdb_on_disconnect_set] val presenceRef = Firebase.database.getReference("disconnectmessage") // Write a string when this client loses connection presenceRef.onDisconnect().setValue("I disconnected!") // [END rtdb_on_disconnect_set] // [START rtdb_on_disconnect_remove] presenceRef.onDisconnect().removeValue { error, reference -> error?.let { Log.d(TAG, "could not establish onDisconnect event: ${error.message}") } } // [END rtdb_on_disconnect_remove] // [START rtdb_on_disconnect_cancel] val onDisconnectRef = presenceRef.onDisconnect() onDisconnectRef.setValue("I disconnected") // ... // some time later when we change our minds // ... onDisconnectRef.cancel() // [END rtdb_on_disconnect_cancel] } private fun getConnectionState() { // [START rtdb_listen_connected] val connectedRef = Firebase.database.getReference(".info/connected") connectedRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val connected = snapshot.getValue(Boolean::class.java) ?: false if (connected) { Log.d(TAG, "connected") } else { Log.d(TAG, "not connected") } } override fun onCancelled(error: DatabaseError) { Log.w(TAG, "Listener was cancelled") } }) // [END rtdb_listen_connected] } private fun disconnectionTimestamp() { // [START rtdb_on_disconnect_timestamp] val userLastOnlineRef = Firebase.database.getReference("users/joe/lastOnline") userLastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP) // [END rtdb_on_disconnect_timestamp] } private fun getServerTimeOffset() { // [START rtdb_server_time_offset] val offsetRef = Firebase.database.getReference(".info/serverTimeOffset") offsetRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val offset = snapshot.getValue(Double::class.java) ?: 0.0 val estimatedServerTimeMs = System.currentTimeMillis() + offset } override fun onCancelled(error: DatabaseError) { Log.w(TAG, "Listener was cancelled") } }) // [END rtdb_server_time_offset] } private fun fullConnectionExample() { // [START rtdb_full_connection_example] // Since I can connect from multiple devices, we store each connection instance separately // any time that connectionsRef's value is null (i.e. has no children) I am offline val database = Firebase.database val myConnectionsRef = database.getReference("users/joe/connections") // Stores the timestamp of my last disconnect (the last time I was seen online) val lastOnlineRef = database.getReference("/users/joe/lastOnline") val connectedRef = database.getReference(".info/connected") connectedRef.addValueEventListener(object : ValueEventListener { override fun onDataChange(snapshot: DataSnapshot) { val connected = snapshot.getValue<Boolean>() ?: false if (connected) { val con = myConnectionsRef.push() // When this device disconnects, remove it con.onDisconnect().removeValue() // When I disconnect, update the last time I was seen online lastOnlineRef.onDisconnect().setValue(ServerValue.TIMESTAMP) // Add this device to my connections list // this value could contain info about the device or a timestamp too con.setValue(java.lang.Boolean.TRUE) } } override fun onCancelled(error: DatabaseError) { Log.w(TAG, "Listener was cancelled at .info/connected") } }) // [END rtdb_full_connection_example] } companion object { private val TAG = "OfflineActivity" } }
database/app/src/main/java/com/google/firebase/referencecode/database/kotlin/OfflineActivity.kt
2532131054
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks import com.felipebz.flr.api.AstNode import org.sonar.plugins.plsqlopen.api.PlSqlGrammar import org.sonar.plugins.plsqlopen.api.annotations.* @Rule(priority = Priority.MINOR) @ConstantRemediation("2min") @RuleInfo(scope = RuleInfo.Scope.ALL) @ActivatedByDefault class EmptyStringAssignmentCheck : AbstractBaseCheck() { override fun init() { subscribeTo(PlSqlGrammar.ASSIGNMENT_STATEMENT) } override fun visitNode(node: AstNode) { val value = node.getLastChildOrNull(PlSqlGrammar.LITERAL) if (value != null && CheckUtils.isEmptyString(value)) { addIssue(node, getLocalizedMessage()) } } }
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/EmptyStringAssignmentCheck.kt
1947141831
package com.intfocus.template.dashboard.mine.bean /** * Created by liuruilin on 2017/6/15. */ class NoticeContentBean { var abstracts: String? = null var title: String? = null var content: String? = null var time: String? = null }
app/src/main/java/com/intfocus/template/dashboard/mine/bean/NoticeContentBean.kt
2897567687
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks import org.junit.jupiter.api.Test import org.sonar.plsqlopen.checks.verifier.PlSqlCheckVerifier class TooManyRowsHandlerCheckTest : BaseCheckTest() { @Test fun test() { PlSqlCheckVerifier.verify(getPath("too_many_rows_handler.sql"), TooManyRowsHandlerCheck()) } }
zpa-checks/src/test/kotlin/org/sonar/plsqlopen/checks/TooManyRowsHandlerCheckTest.kt
3552400655
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.biometricloginsample object SampleAppUser { var fakeToken: String? = null var username: String? = null }
codelab-02/app/src/main/java/com/example/biometricloginsample/SampleAppUser.kt
2564032079
/* * 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.xquery.ide.structureView import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.impl.common.PsiTreeElementBase import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xpm.optree.annotation.XpmAnnotated import uk.co.reecedunn.intellij.plugin.xpm.optree.function.XpmFunctionDeclaration import uk.co.reecedunn.intellij.plugin.xpm.optree.variable.XpmVariableDeclaration import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.* import uk.co.reecedunn.intellij.plugin.xquery.model.annotatedDeclarations import javax.swing.Icon class XQueryModuleStructureView(module: XQueryModule) : PsiTreeElementBase<XQueryModule>(module) { override fun getChildrenBase(): MutableCollection<out StructureViewTreeElement> { return element?.mainOrLibraryModule?.children()?.flatMap { child -> when (child) { is XQueryProlog -> child.annotatedDeclarations<XpmAnnotated>(reversed = false).map { decl -> when (decl) { is XQueryFunctionDecl -> { (decl as XpmFunctionDeclaration).functionName?.localName?.let { StructureViewLeafNode(decl) } } is XQueryVarDecl -> { (decl as XpmVariableDeclaration).variableName?.localName?.let { StructureViewLeafNode(decl) } } is XQueryItemTypeDecl -> StructureViewLeafNode(decl) else -> null } } is XQueryQueryBody -> sequenceOf(StructureViewLeafNode(child)) else -> emptySequence() } }?.filterNotNull()?.toMutableList<StructureViewTreeElement>() ?: mutableListOf() } override fun getPresentableText(): String? = element?.presentation?.presentableText override fun getIcon(open: Boolean): Icon? = element?.presentation?.getIcon(open) }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ide/structureView/XQueryModuleStructureView.kt
655598662
/* * Copyright (C) 2016; 2018-2019 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.xquery.psi.impl.xquery import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathComment import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQDocTokenType class XQueryCommentPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathComment { // region XPathComment override val isXQDoc: Boolean get() = firstChild.nextSibling?.node?.elementType === XQDocTokenType.XQDOC_COMMENT_MARKER // endregion }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/xquery/XQueryCommentPsiImpl.kt
3377895780
package com.habitrpg.android.habitica.models.user import com.habitrpg.android.habitica.models.BaseObject import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.RealmClass @RealmClass(embedded = true) open class UserTaskPreferences: RealmObject(), BaseObject { var confirmScoreNotes: Boolean = false var mirrorGroupTasks: RealmList<String> = RealmList() var groupByChallenge: Boolean = false }
Habitica/src/main/java/com/habitrpg/android/habitica/models/user/UserTaskPreferences.kt
3351818573
package com.fieldbook.tracker.utilities import android.location.Location import com.fieldbook.tracker.database.models.ObservationUnitModel import com.fieldbook.tracker.traits.GNSSTraitLayout import com.google.gson.Gson import java.io.FileWriter import java.io.IOException import java.lang.NumberFormatException import kotlin.math.* class GeodeticUtils { companion object { /** * GeoNav log is a user preference within Settings/Behavior/GeoNav * When enabled, a log file is created each time GeoNav begins. * The filename contains parameters for the GeoNav function: * "log_interval_address_theta_systemTime.csv" * Where interval is the update interval for the algorithm, 1, 5, or 10 * Address is the mac address of the external device (: replaced with _, also can be Internal_GPS) * Theta is the user preference angle threshold 22.5, 45, 67.5, or 90 * System time is the device's time in nano seconds. * * Whenever a line is added to the log file it is flushed to the file. * Newlines should be manually added using writeGeoNavLog(log, "\n") * * File headers are the following: * UTC, primary, secondary, start latitude, start longitude, end latitude, end longitude, * azimuth, teslas, bearing, distance, thetaCheck, closest * UTC: time given by the GPS, refers to the time the start location was received * primary/secondary: the primary/secondary ids of the current iteration * start: the lat/lng coordinates of the rover * end: the lat/lng coordinates of the target * azimuth: the direction the user is facing in degrees from 0-360 like a compass * teslas: the amount of noise calculated from the device's sensors * bearing: the angle between the start and end coordinates * distance: the distance between the start and end coordinates * thetaCheck: true if end lies within the theta threshold of the start's azimuth * closest: true if this is the closest point * e.g: In the below example 1,1 is the first closest, but is updated by 1,2 * therefore, 1,2 is the closest point. 1,5 is within the theta threshold, * but it is further away than 1,2. * 191438,1,1,...,true,true * 191438,1,2,...,true,true * 191438,1,5,...,true,false * * The file is populated by (1) device coordinate updates * and (2) for each iteration of the impact zone algorithm. * * (1) Device coordinate lines look like: * 191437.8,null,null,39.19216,-096.62184,null,null,null,null,null,null,null,null * ... where only the start coordinates and UTC are available * * (2) IZ lines look like: * 191438,1,1,39.19216,-96.62184,39.19222656,-96.62168695,326.4154145186235,56.7287763993025,null,15.124376606431571,false,false * note: the bearing can be null if the compass setting is disabled */ fun writeGeoNavLog(log: FileWriter?, line: String) { log?.let { geonav -> try { geonav.append(line) geonav.flush() } catch (io: IOException) { io.printStackTrace() } } } /** * Finds the closest location within a list of locations to the user. The location * must also be within the field of view of the user. Shown in the diagram below, * the user 'u' creates a cone (roughly) in front defined by their azimuth (from the compass). * The cone's angle from the user is defined in the preferences. * * * \ | * \ x | * \_______| * u * * @param start: the user's location * @param coordinates: the coordinate list to search from * @param theta: the field of view angle * @param isCompass: whether the compass setting is enabled and if theta threshold should be used in algorithm * @return a object representing the returned location and it's distance **/ fun impactZoneSearch(log: FileWriter?, start: Location, coordinates: Array<ObservationUnitModel>, azimuth: Double, theta: Double, teslas: Double, isCompass: Boolean = true): Pair<ObservationUnitModel?, Double> { //greedy algorithm to find closest point, first point is set to inf var closestDistance = Double.MAX_VALUE var closestPoint: ObservationUnitModel? = null coordinates.forEach { coordinate -> val location = parseGeoCoordinate(coordinate.geo_coordinates) if (location != null) { writeGeoNavLog(log, "${start.time},${coordinate.primary_id},${coordinate.secondary_id},${start.latitude},${start.longitude},${location.latitude},${location.longitude},$azimuth,$teslas") if (isCompass) { val bearing = checkThetaThreshold(start, location, azimuth, theta) val distance: Double = distanceHaversine(start, location) if (bearing.first) { if (closestDistance > distance) { writeGeoNavLog(log, ",${bearing.second},$distance,true,true") closestDistance = distance closestPoint = coordinate } else { writeGeoNavLog(log, ",${bearing.second},$distance,true,false") } } else { writeGeoNavLog(log, ",${bearing.second},$distance,false,false") } } else { val distance: Double = distanceHaversine(start, location) if (closestDistance > distance) { writeGeoNavLog(log, ",null,$distance,null,true") closestDistance = distance closestPoint = coordinate } else { writeGeoNavLog(log, ",null,$distance,null,false") } } //write newline to log file after each iteration writeGeoNavLog(log, "\n") } } return closestPoint to closestDistance } /** * Geocoordinates in FB can be stored as GeoJson or semi colon delimited strings. * This function parses the string and creates a Location object. * If the parsing fails then null is returned. */ fun parseGeoCoordinate(latLng: String?): Location? { val coords = (if (latLng == null || latLng.isBlank()) "" else latLng) val location = Location("search") //first try parsing as geojson, then try semi colon delimited var nonJson = false var failed = false try { val geoJson = Gson().fromJson(coords, GNSSTraitLayout.GeoJSON::class.java) location.latitude = geoJson.geometry.coordinates[0].toDouble() location.longitude = geoJson.geometry.coordinates[1].toDouble() } catch (e: Exception) { //could be a NPE, number format exception, index out of bounds or json syntax exception, failed = true nonJson = true } if (nonJson) { //check semi colon delimited values can be parsed to doubles val latLngTokens = coords.split(";") if (latLngTokens.size == 2) { try { location.latitude = latLngTokens[0].toDouble() location.longitude = latLngTokens[1].toDouble() failed = false } catch (e: NumberFormatException) { failed = true } } } return if (failed) null else location } /** * Checks whether an object lies within the user's field of view. * @param start: the user's location * @param end: the object's location * @param azimuth: defined by the compass, it's where the user is pointing * @param thetaThresh: a preference-defined double value that defines the field of view for the detection * @return a pair where first is if the bearing passes the threshold, second is the bearing */ private fun checkThetaThreshold(start: Location, end: Location, azimuth: Double, thetaThresh: Double): Pair<Boolean, Double> { //find the direction from user to target. val angle = angleFromCoordinate(start.latitude, start.longitude, end.latitude, end.longitude) //azimuth and angle are between 0-360 //if azimuth points towards end, then correctedAngle is close to 0 and should be between the theta thresh val correctedAngle = azimuth - angle //test if the direction found above is within a threshold from our user's azimuth return (correctedAngle in -thetaThresh..thetaThresh) to angle } /* uses the Haversine method to calculate distance between two GPS coordinates */ fun distanceHaversine(a: Location, b: Location): Double { val lata = a.latitude val lnga = a.longitude val latb = b.latitude val lngb = b.longitude val R = 6371.0 //radius of the Earth 6.371 million meters val latDst = Math.toRadians(latb - lata) val lngDst = Math.toRadians(lngb - lnga) val A = (sin(latDst / 2) * sin(latDst / 2) + (cos(Math.toRadians(lata)) * cos(Math.toRadians(latb)) * sin(lngDst / 2) * sin(lngDst / 2))) val c = 2 * atan2(sqrt(A), sqrt(1 - A)) //double height = el1 - el2; //dst = Math.pow(dst, 2); //return Math.sqrt(dst); return R * c * 1000.0 } fun geodesicDestination(start: Location, bearing: Double, distance: Double): Location { val latRads = Math.toRadians(start.latitude) val lngRads = Math.toRadians(start.longitude) //(Degrees * Math.PI) / 180.0; //final double bearing = azimuth;//location.getBearing(); //created weighted vector with bearing...? val R = 6371.0 //radius of the Earth val angDst = distance / R // d/R distance to point B over Earth's radius val lat2 = asin( sin(latRads) * cos(angDst) + cos(latRads) * sin(angDst) * cos(bearing) ) val lng2 = lngRads + atan2( sin(bearing) * sin(angDst) * cos(latRads), cos(angDst) - sin(latRads) * sin(lat2) ) val l = Location("end point") l.latitude = Math.toDegrees(lat2) l.longitude = Math.toDegrees(lng2) return l } //https://www.movable-type.co.uk/scripts/latlong.html private fun angleFromCoordinate( lat1: Double, long1: Double, lat2: Double, long2: Double ): Double { //get difference between longitudes val deltaLong = Math.toRadians(long2-long1) //convert latitudes to radians before trig functions val lat1Rads = Math.toRadians(lat1) val lat2Rads = Math.toRadians(lat2) //convert to x/y coordinates val y = sin(deltaLong)*cos(lat2Rads) val x = cos(lat1Rads)*sin(lat2Rads)-sin(lat1Rads)*cos(lat2Rads)*cos(deltaLong) //return degrees return (Math.toDegrees(atan2(y, x))+360) % 360 } /** * Truncates the coordinate string based on the fix value. * https://gis.stackexchange.com/questions/8650/measuring-accuracy-of-latitude-and-longitude * basically: normal gps ~4decimal places, differential 5, rtk 8 */ fun truncateFixQuality(x: String, fix: String): String = try { val tokens = x.split(".") val head = tokens[0] val tail = tokens[1] "$head." + when (fix) { "RTK", "manual input mode" -> if (tail.length > 8) tail.substring(0, 8) else tail "DGPS", "Float RTK" -> if (tail.length > 5) tail.substring(0, 5) else tail "internal" -> if (tail.length > 4) tail.substring(0, 4) else tail else -> if (tail.length > 3) tail.substring(0, 3) else tail } } catch (e: Exception) { e.printStackTrace() x } /** * Smooth two float arrays using a low pass filter. */ fun lowPassFilter(input: FloatArray, output: FloatArray?): FloatArray = output?.mapIndexed { index, fl -> fl + 0.5f * (input[index] - fl) }?.toFloatArray() ?: input } }
app/src/main/java/com/fieldbook/tracker/utilities/GeodeticUtils.kt
846105732
package de.westnordost.streetcomplete.data import android.database.sqlite.SQLiteOpenHelper import androidx.test.platform.app.InstrumentationRegistry import de.westnordost.streetcomplete.util.KryoSerializer import de.westnordost.streetcomplete.util.Serializer import org.junit.After import org.junit.Assert import org.junit.Before import org.junit.Test open class ApplicationDbTestCase { protected lateinit var dbHelper: SQLiteOpenHelper protected lateinit var serializer: Serializer @Before fun setUpHelper() { serializer = KryoSerializer() dbHelper = DbModule.sqLiteOpenHelper( InstrumentationRegistry.getInstrumentation().targetContext, DATABASE_NAME ) } @Test fun databaseAvailable() { Assert.assertNotNull(dbHelper.readableDatabase) } @After fun tearDownHelper() { dbHelper.close() InstrumentationRegistry.getInstrumentation().targetContext .deleteDatabase(DATABASE_NAME) } companion object { private const val DATABASE_NAME = "streetcomplete_test.db" } }
app/src/androidTest/java/de/westnordost/streetcomplete/data/ApplicationDbTestCase.kt
2284254921
/* * Copyright (C) 2016; 2018, 2021 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.xquery.lang.editor import com.intellij.lang.BracePair import com.intellij.lang.PairedBraceMatcher import com.intellij.psi.PsiFile import com.intellij.psi.tree.IElementType import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType import xqt.platform.intellij.ft.XPathFTTokenProvider import xqt.platform.intellij.saxon.SaxonXPathTokenProvider import xqt.platform.intellij.xpath.XPathTokenProvider class XQueryPairedBraceMatcher : PairedBraceMatcher { override fun getPairs(): Array<BracePair> = BRACE_PAIRS override fun isPairedBracesAllowedBeforeType(lbraceType: IElementType, contextType: IElementType?): Boolean = true override fun getCodeConstructStart(file: PsiFile, openingBraceOffset: Int): Int = openingBraceOffset companion object { private val BRACE_PAIRS = arrayOf( // { ... } BracePair(XPathTokenProvider.CurlyBracketOpen, XPathTokenProvider.CurlyBracketClose, true), // [ ... ] BracePair(XPathTokenProvider.SquareBracketOpen, XPathTokenProvider.SquareBracketClose, false), // ( ... ) BracePair(XPathTokenProvider.ParenthesisOpen, XPathTokenProvider.ParenthesisClose, false), // (: ... :) BracePair(XPathTokenProvider.CommentOpen, XPathTokenProvider.CommentClose, false), // < ... /> BracePair(XQueryTokenType.OPEN_XML_TAG, XQueryTokenType.SELF_CLOSING_XML_TAG, false), // < ... > BracePair(XQueryTokenType.OPEN_XML_TAG, XQueryTokenType.END_XML_TAG, false), // </ ... > BracePair(XQueryTokenType.CLOSE_XML_TAG, XQueryTokenType.END_XML_TAG, false), // <!-- ... --> BracePair(XQueryTokenType.XML_COMMENT_START_TAG, XQueryTokenType.XML_COMMENT_END_TAG, false), // <? ... ?> BracePair(XQueryTokenType.PROCESSING_INSTRUCTION_BEGIN, XQueryTokenType.PROCESSING_INSTRUCTION_END, false), // <![CDATA[ ... ]]> BracePair(XQueryTokenType.CDATA_SECTION_START_TAG, XQueryTokenType.CDATA_SECTION_END_TAG, false), // (# ... #) BracePair(XPathFTTokenProvider.PragmaOpen, XPathFTTokenProvider.PragmaClose, false), // `{ ... }` BracePair(XQueryTokenType.STRING_INTERPOLATION_OPEN, XQueryTokenType.STRING_INTERPOLATION_CLOSE, true), // .{ ... } BracePair(SaxonXPathTokenProvider.ContextFunctionOpen, XPathTokenProvider.CurlyBracketClose, true), // _{ ... } BracePair(SaxonXPathTokenProvider.LambdaFunctionOpen, XPathTokenProvider.CurlyBracketClose, true) ) } }
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/lang/editor/XQueryPairedBraceMatcher.kt
2679274561
package de.westnordost.streetcomplete.controls import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.fragment.app.Fragment import de.westnordost.osmfeatures.FeatureDictionary import de.westnordost.streetcomplete.Injector import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquest.OsmQuest import de.westnordost.streetcomplete.data.quest.QuestController import de.westnordost.streetcomplete.data.quest.UndoableOsmQuestsCountListener import de.westnordost.streetcomplete.data.quest.UndoableOsmQuestsSource import de.westnordost.streetcomplete.data.upload.UploadProgressListener import de.westnordost.streetcomplete.data.upload.UploadProgressSource import de.westnordost.streetcomplete.ktx.popIn import de.westnordost.streetcomplete.ktx.popOut import de.westnordost.streetcomplete.quests.getHtmlQuestTitle import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import java.util.concurrent.FutureTask import javax.inject.Inject /** Fragment that shows (and hides) the undo button, based on whether there is anything to undo */ class UndoButtonFragment : Fragment(R.layout.fragment_undo_button), CoroutineScope by CoroutineScope(Dispatchers.Main) { @Inject internal lateinit var undoableOsmQuestsSource: UndoableOsmQuestsSource @Inject internal lateinit var uploadProgressSource: UploadProgressSource @Inject internal lateinit var questController: QuestController @Inject internal lateinit var featureDictionaryFutureTask: FutureTask<FeatureDictionary> private val undoButton get() = view as ImageButton /* undo button is not shown when there is nothing to undo */ private val undoableOsmQuestsCountListener = object : UndoableOsmQuestsCountListener { override fun onUndoableOsmQuestsCountIncreased() { launch(Dispatchers.Main) { if (!undoButton.isVisible && undoableOsmQuestsSource.count > 0) { undoButton.popIn() } } } override fun onUndoableOsmQuestsCountDecreased() { launch(Dispatchers.Main) { if (undoButton.isVisible && undoableOsmQuestsSource.count == 0) { undoButton.popOut().withEndAction { undoButton.visibility = View.INVISIBLE } } } } } /* Don't allow undoing while uploading. Should prevent race conditions. (Undoing quest while * also uploading it at the same time) */ private val uploadProgressListener = object : UploadProgressListener { override fun onStarted() { launch(Dispatchers.Main) { updateUndoButtonEnablement(false) }} override fun onFinished() { launch(Dispatchers.Main) { updateUndoButtonEnablement(true) }} } /* --------------------------------------- Lifecycle ---------------------------------------- */ init { Injector.applicationComponent.inject(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) undoButton.setOnClickListener { undoButton.isEnabled = false val quest = undoableOsmQuestsSource.getLastUndoable() if (quest != null) confirmUndo(quest) } } override fun onStart() { super.onStart() updateUndoButtonVisibility() updateUndoButtonEnablement(true) undoableOsmQuestsSource.addListener(undoableOsmQuestsCountListener) uploadProgressSource.addUploadProgressListener(uploadProgressListener) } override fun onStop() { super.onStop() undoableOsmQuestsSource.removeListener(undoableOsmQuestsCountListener) uploadProgressSource.removeUploadProgressListener(uploadProgressListener) } override fun onDestroy() { super.onDestroy() coroutineContext.cancel() } /* ------------------------------------------------------------------------------------------ */ private fun confirmUndo(quest: OsmQuest) { val element = questController.getOsmElement(quest) ?: return val ctx = context ?: return val inner = LayoutInflater.from(ctx).inflate(R.layout.dialog_undo, null, false) val icon = inner.findViewById<ImageView>(R.id.icon) icon.setImageResource(quest.type.icon) val text = inner.findViewById<TextView>(R.id.text) text.text = resources.getHtmlQuestTitle(quest.type, element, featureDictionaryFutureTask) AlertDialog.Builder(ctx) .setTitle(R.string.undo_confirm_title) .setView(inner) .setPositiveButton(R.string.undo_confirm_positive) { _, _ -> questController.undo(quest) updateUndoButtonEnablement(true) } .setNegativeButton(R.string.undo_confirm_negative) { _, _ -> updateUndoButtonEnablement(true) } .setOnCancelListener { updateUndoButtonEnablement(true) } .show() } private fun updateUndoButtonVisibility() { view?.isGone = undoableOsmQuestsSource.count <= 0 } private fun updateUndoButtonEnablement(enable: Boolean) { undoButton.isEnabled = enable && !uploadProgressSource.isUploadInProgress } }
app/src/main/java/de/westnordost/streetcomplete/controls/UndoButtonFragment.kt
522709596
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.maddyhome.idea.vim.ex.handler import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.editor.Editor import com.maddyhome.idea.vim.VimPlugin import com.maddyhome.idea.vim.ex.CommandHandler import com.maddyhome.idea.vim.ex.CommandHandlerFlags import com.maddyhome.idea.vim.ex.CommandName import com.maddyhome.idea.vim.ex.ExCommand import com.maddyhome.idea.vim.ex.commands import com.maddyhome.idea.vim.ex.flags class AsciiHandler : CommandHandler.SingleExecution() { override val names: Array<CommandName> = commands("as[cii]") override val argFlags: CommandHandlerFlags = flags(RangeFlag.RANGE_FORBIDDEN, ArgumentFlag.ARGUMENT_FORBIDDEN) override fun execute(editor: Editor, context: DataContext, cmd: ExCommand): Boolean { VimPlugin.getFile().displayAsciiInfo(editor) return true } }
src/com/maddyhome/idea/vim/ex/handler/AsciiHandler.kt
1571768650
// FILE: 1.kt package test inline fun inlineFun(vararg constraints: String, init: String.() -> String): String { return "O".init() } // FILE: 2.kt import test.* fun box(): String { return inlineFun { this + "K" } }
backend.native/tests/external/codegen/boxInline/varargs/kt17653.kt
686684619
package com.mindera.skeletoid.logs.appenders import android.content.Context import android.content.Intent import android.os.Build import androidx.core.content.FileProvider import androidx.test.core.app.ApplicationProvider import com.mindera.skeletoid.generic.AndroidUtils import com.mindera.skeletoid.logs.LOG import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.Mockito.verifyNoMoreInteractions import org.powermock.api.mockito.PowerMockito import org.powermock.core.classloader.annotations.PowerMockIgnore import org.powermock.core.classloader.annotations.PrepareForTest import org.powermock.modules.junit4.rule.PowerMockRule import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import java.io.File import java.util.logging.FileHandler import java.util.logging.Level import java.util.logging.LogRecord import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @RunWith(RobolectricTestRunner::class) @Config(sdk = [Build.VERSION_CODES.O_MR1]) @PowerMockIgnore("org.mockito.*", "org.robolectric.*", "android.*") @PrepareForTest(FileProvider::class, Intent::class, AndroidUtils::class) class LogFileAppenderUnitTest { companion object { private const val PACKAGE_NAME = "my.package.name" private const val FILE_NAME = "FILENAME" } @Rule @JvmField var rule = PowerMockRule() @Test(expected = IllegalArgumentException::class) fun testConstructorFileNameInvalid() { LogFileAppender(PACKAGE_NAME, "*") } @Test fun testFileNameIsValidEmpty() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertFalse(appender.isFilenameValid("")) } @Test fun testFileNameIsValidInvalid() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertFalse(appender.isFilenameValid("//")) } @Test fun testFileNameIsValid() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertTrue(appender.isFilenameValid(FILE_NAME)) } @Test fun testConstructor() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertEquals("LogFileAppender", appender.loggerId) } @Test fun testEnableAppender() { val context = RuntimeEnvironment.application val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.enableAppender(context) Thread.sleep(2000) assertTrue(appender.canWriteToFile()) } @Test fun testDisableAppender() { val context = RuntimeEnvironment.application val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.enableAppender(context) Thread.sleep(2000) appender.disableAppender() assertFalse(appender.canWriteToFile()) } @Test fun testCanWriteToFile() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertFalse(appender.canWriteToFile()) } @Test fun testFormatLog() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertTrue( appender.formatLog( LOG.PRIORITY.DEBUG, "", "Hello", "My friend" ).matches(("\\d\\d\\d\\d-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d: D/" + PACKAGE_NAME + "\\(" + Thread.currentThread().id + "\\): Hello My friend").toRegex()) ) } @Test fun testSetMaxLineLength() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.logFileSize = 1000 assertEquals(1000, appender.logFileSize) } @Test fun testSetNumberOfLogFiles() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.numberOfLogFiles = 5 assertEquals(5, appender.numberOfLogFiles) } @Test fun testSetMinLogLevel() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.minLogLevel = LOG.PRIORITY.DEBUG assertEquals(LOG.PRIORITY.DEBUG, appender.minLogLevel) } @Test fun testGetFileLogPath() { val context = RuntimeEnvironment.application val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) PowerMockito.mockStatic(AndroidUtils::class.java) `when`( AndroidUtils.getFileDirPath( context, String.format( "%s%s.log", File.separator, FILE_NAME ) ) ).thenReturn("internal/com/mindera/skeletoid/FILENAME.log") assertEquals( "internal/com/mindera/skeletoid/FILENAME.log", appender.getFileLogPath(context) ) } @Test fun testGetExternalFileLogPath() { val context = RuntimeEnvironment.application val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME, true) PowerMockito.mockStatic(AndroidUtils::class.java) `when`( AndroidUtils.getExternalPublicDirectory( String.format( "%s%s.log", File.separator, FILE_NAME ) ) ).thenReturn("external/com/mindera/skeletoid/FILENAME.log") assertEquals( "external/com/mindera/skeletoid/FILENAME.log", appender.getFileLogPath(context) ) } @Test fun testFileHandlerLevelDebug() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertEquals(Level.SEVERE, appender.getFileHandlerLevel(LOG.PRIORITY.ERROR)) } @Test fun testFileHandlerLevelFatal() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertEquals(Level.SEVERE, appender.getFileHandlerLevel(LOG.PRIORITY.FATAL)) } @Test fun testFileHandlerLevelInfo() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertEquals(Level.INFO, appender.getFileHandlerLevel(LOG.PRIORITY.INFO)) } @Test fun testFileHandlerLevelVerbose() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertEquals(Level.ALL, appender.getFileHandlerLevel(LOG.PRIORITY.VERBOSE)) } @Test fun testFileHandlerLevelWarn() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertEquals(Level.WARNING, appender.getFileHandlerLevel(LOG.PRIORITY.WARN)) } @Test fun testIsThreadPoolRunningWhenAppenderEnabled() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) val context = RuntimeEnvironment.application appender.enableAppender(context) assertTrue(appender.isThreadPoolRunning) } @Test fun testIsThreadPoolNotRunningWhenAppenderInitialised() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) assertFalse(appender.isThreadPoolRunning) } @Test fun testIsThreadPoolNotRunningWhenAppenderDisabled() { val context = RuntimeEnvironment.application val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.enableAppender(context) appender.disableAppender() assertFalse(appender.isThreadPoolRunning) } @Test @Ignore fun testLog() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) val context = ApplicationProvider.getApplicationContext<Context>() val fileHandler = mock(FileHandler::class.java) appender.enableAppender(context) Thread.sleep(5000) appender.fileHandler = fileHandler appender.log(LOG.PRIORITY.DEBUG, Throwable("oops"), "hello") verify(fileHandler).publish(any(LogRecord::class.java)) } @Test fun testNoLogIfWritingNotEnabled() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) val fileHandler = mock(FileHandler::class.java) appender.fileHandler = fileHandler appender.log(LOG.PRIORITY.DEBUG, null, "hello") verifyNoMoreInteractions(fileHandler) } @Test fun testNoLogIfAppenderNotEnabled() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) val fileHandler = mock(FileHandler::class.java) appender.fileHandler = fileHandler appender.log(LOG.PRIORITY.DEBUG, null, "hello") verifyNoMoreInteractions(fileHandler) } @Test fun testNoLogIfAppenderDisabled() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) val fileHandler = mock(FileHandler::class.java) val context = RuntimeEnvironment.application appender.enableAppender(context) Thread.sleep(2000) appender.fileHandler = fileHandler appender.disableAppender() appender.log(LOG.PRIORITY.DEBUG, null, "hello") verify(fileHandler, times(0)).publish(any(LogRecord::class.java)) } @Test fun testNoLogIfLogLevelBelowMinLogLevel() { val appender = LogFileAppender(PACKAGE_NAME, FILE_NAME) appender.minLogLevel = LOG.PRIORITY.ERROR val fileHandler = mock(FileHandler::class.java) val context = RuntimeEnvironment.application appender.enableAppender(context) Thread.sleep(2000) appender.fileHandler = fileHandler appender.log(LOG.PRIORITY.DEBUG, null, "hello") verifyNoMoreInteractions(fileHandler) } }
base/src/test/java/com/mindera/skeletoid/logs/appenders/LogFileAppenderUnitTest.kt
775362972
package info.nightscout.androidaps.database.transactions import info.nightscout.androidaps.database.entities.TemporaryTarget import info.nightscout.androidaps.database.interfaces.end import kotlin.math.abs /** * Sync the TemporaryTarget from NS */ class SyncNsTemporaryTargetTransaction(private val temporaryTarget: TemporaryTarget) : Transaction<SyncNsTemporaryTargetTransaction.TransactionResult>() { override fun run(): TransactionResult { val result = TransactionResult() if (temporaryTarget.duration != 0L) { // not ending event val current: TemporaryTarget? = temporaryTarget.interfaceIDs.nightscoutId?.let { database.temporaryTargetDao.findByNSId(it) } if (current != null) { // nsId exists, allow only invalidation if (current.isValid && !temporaryTarget.isValid) { current.isValid = false database.temporaryTargetDao.updateExistingEntry(current) result.invalidated.add(current) } if (current.duration != temporaryTarget.duration) { current.duration = temporaryTarget.duration database.temporaryTargetDao.updateExistingEntry(current) result.updatedDuration.add(current) } return result } // not known nsId val running = database.temporaryTargetDao.getTemporaryTargetActiveAt(temporaryTarget.timestamp).blockingGet() if (running != null && abs(running.timestamp - temporaryTarget.timestamp) < 1000 && running.interfaceIDs.nightscoutId == null) { // allow missing milliseconds // the same record, update nsId only running.interfaceIDs.nightscoutId = temporaryTarget.interfaceIDs.nightscoutId database.temporaryTargetDao.updateExistingEntry(running) result.updatedNsId.add(running) } else if (running != null) { // another running record. end current and insert new running.end = temporaryTarget.timestamp database.temporaryTargetDao.updateExistingEntry(running) database.temporaryTargetDao.insertNewEntry(temporaryTarget) result.ended.add(running) result.inserted.add(temporaryTarget) } else { database.temporaryTargetDao.insertNewEntry(temporaryTarget) result.inserted.add(temporaryTarget) } return result } else { // ending event val running = database.temporaryTargetDao.getTemporaryTargetActiveAt(temporaryTarget.timestamp).blockingGet() if (running != null) { running.end = temporaryTarget.timestamp database.temporaryTargetDao.updateExistingEntry(running) result.ended.add(running) } } return result } class TransactionResult { val updatedNsId = mutableListOf<TemporaryTarget>() val updatedDuration = mutableListOf<TemporaryTarget>() val inserted = mutableListOf<TemporaryTarget>() val invalidated = mutableListOf<TemporaryTarget>() val ended = mutableListOf<TemporaryTarget>() } }
database/src/main/java/info/nightscout/androidaps/database/transactions/SyncNsTemporaryTargetTransaction.kt
3105172336
package info.nightscout.androidaps.dialogs import android.os.Bundle import android.os.SystemClock import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.core.R import info.nightscout.androidaps.core.databinding.DialogBolusprogressBinding import info.nightscout.androidaps.events.EventNtpStatus import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject class NtpProgressDialog : DaggerDialogFragment() { @Inject lateinit var rxBus: RxBus @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rh: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var aapsSchedulers: AapsSchedulers private val disposable = CompositeDisposable() private var state: String? = null private var percent = 0 private var _binding: DialogBolusprogressBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { isCancelable = false state = savedInstanceState?.getString("state", null) percent = savedInstanceState?.getInt("percent", 0) ?: 0 _binding = DialogBolusprogressBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val defaultMessage = rh.gs(R.string.timedetection) dialog?.setTitle(rh.gs(R.string.objectives)) binding.stop.setOnClickListener { dismiss() } binding.status.text = state ?: defaultMessage binding.progressbar.max = 100 binding.progressbar.progress = percent binding.stop.text = rh.gs(R.string.close) binding.title.text = rh.gs(R.string.please_wait) } override fun onResume() { super.onResume() aapsLogger.debug(LTag.UI, "onResume") if (percent == 100) { dismiss() return } else dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) disposable += rxBus .toObservable(EventNtpStatus::class.java) .observeOn(aapsSchedulers.main) .subscribe({ event: EventNtpStatus -> if (_binding != null) { aapsLogger.debug(LTag.UI, "Status: " + event.status + " Percent: " + event.percent) binding.status.text = event.status binding.progressbar.progress = event.percent if (event.percent == 100) { SystemClock.sleep(100) dismiss() } state = event.status percent = event.percent } }, fabricPrivacy::logException) } override fun onPause() { aapsLogger.debug(LTag.UI, "onPause") super.onPause() disposable.clear() } override fun onDestroyView() { super.onDestroyView() disposable.clear() _binding = null } override fun onSaveInstanceState(outState: Bundle) { outState.putString("state", state) outState.putInt("percent", percent) super.onSaveInstanceState(outState) } }
core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt
3942962354
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.virtualpeople.core.model import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.virtualpeople.common.labelerEvent import org.wfanet.virtualpeople.common.multiplicity private const val EVENT_COUNT = 10000 @RunWith(JUnit4::class) class MultiplicityImplTest { @Test fun `multiplicity ref not set should throw`() { val config = multiplicity { maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set multiplicity_ref")) } @Test fun `invalid multiplicity field name should throw`() { val config = multiplicity { expectedMultiplicityField = "bad field name" maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("The field name is invalid")) } @Test fun `invalid multiplicity field type should throw`() { val config = multiplicity { expectedMultiplicityField = "corrected_demo" maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Unsupported field type")) } @Test fun `person index field not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set person_index_field")) } @Test fun `invalid person index field name should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true personIndexField = "bad field name" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("The field name is invalid")) } @Test fun `invalid person index field type should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true personIndexField = "expected_multiplicity" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Invalid type for person_index_field")) } @Test fun `max value not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set max_value")) } @Test fun `cap at max not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set cap_at_max")) } @Test fun `random seed not set should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.2 capAtMax = true personIndexField = "multiplicity_person_index" } val error = assertFailsWith<IllegalStateException> { MultiplicityImpl.build(config) } assertTrue(error.message!!.contains("Multiplicity must set random_seed")) } @Test fun `explicit multiplicity and cap at max true`() { val config = multiplicity { expectedMultiplicity = 2.5 maxValue = 1.3 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.3 * EVENT_COUNT = 13000 */ assertEquals(12947, personTotal) } @Test fun `explicit multiplicity and cap at max false`() { val config = multiplicity { expectedMultiplicity = 2.5 maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("exceeds the specified max value")) } } @Test fun `explicit multiplicity is negative should throw`() { val config = multiplicity { expectedMultiplicity = -1.2 maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("multiplicity must >= 0")) } } @Test fun `multiplicity field and cap at max true`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.3 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) /** multiplicity field is not set, throws error. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("The multiplicity field is not set")) } /** multiplicity > max_value, cap at max_value. */ var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 2.0 } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.3 * EVENT_COUNT = 13000 */ assertEquals(12947, personTotal) /** multiplicity < max_value */ personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 1.2 } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.2 * EVENT_COUNT = 12000 */ assertEquals(11949, personTotal) } @Test fun `multiplicity field and cap at max false`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) /** multiplicity field is not set, throws error. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("The multiplicity field is not set")) } /** multiplicity > max_value, return error. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 2.0 } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("exceeds the specified max value")) } /** multiplicity < max_value */ var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = 1.2 } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(1, 2) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 1.2 * EVENT_COUNT = 12000 */ assertEquals(11949, personTotal) } @Test fun `multiplicity field is negative should throw`() { val config = multiplicity { expectedMultiplicityField = "expected_multiplicity" maxValue = 1.3 capAtMax = false personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) /** return error if multiplicity < 0. */ (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() expectedMultiplicity = -1.2 } val error = assertFailsWith<IllegalStateException> { multiplicity.computeEventMultiplicity(input) } assertTrue(error.message!!.contains("multiplicity must >= 0")) } } @Test fun `multiplicity less than one`() { val config = multiplicity { expectedMultiplicity = 0.3 maxValue = 1.3 capAtMax = true personIndexField = "multiplicity_person_index" randomSeed = "test multiplicity" } val multiplicity = MultiplicityImpl.build(config) var personTotal = 0 (0 until EVENT_COUNT).forEach { val input = labelerEvent { actingFingerprint = it.toLong() } val cloneCount = multiplicity.computeEventMultiplicity(input) assertTrue { cloneCount in listOf(0, 1) } personTotal += cloneCount } /** * Compare to the exact result to make sure C++ and Kotlin implementations behave the same. The * result should be around 0.3 * EVENT_COUNT = 3000 */ assertEquals(2947, personTotal) } }
src/test/kotlin/org/wfanet/virtualpeople/core/model/MultiplicityImplTest.kt
2957710491
package info.nightscout.androidaps.interaction.actions import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.util.Log import android.widget.Toast import dagger.android.DaggerActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventWearToMobile import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.shared.weardata.EventData import javax.inject.Inject /** * Send a snooze request to silence any alarm. Designed to be bound to a button for fast access */ class QuickSnoozeActivity : DaggerActivity() { @Inject lateinit var rxBus: RxBus override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Toast.makeText(this, R.string.sending_snooze, Toast.LENGTH_LONG).show() rxBus.send(EventWearToMobile(EventData.SnoozeAlert(System.currentTimeMillis()))) val xDripPackageName = "com.eveningoutpost.dexdrip" if (isPackageExisted(xDripPackageName)) { try { val i = Intent() i.setClassName(xDripPackageName, "$xDripPackageName.QuickSnooze") startActivity(i) } catch (e : Exception) { Log.e("WEAR", "failed to snooze xDrip: ", e) } } else { Log.d("WEAR", "Package $xDripPackageName not available for snooze") } finish() } private fun isPackageExisted(targetPackage: String): Boolean { try { packageManager.getPackageInfo(targetPackage, PackageManager.GET_META_DATA) } catch (e: PackageManager.NameNotFoundException) { return false } return true } }
wear/src/main/java/info/nightscout/androidaps/interaction/actions/QuickSnoozeActivity.kt
3759675524
// Copyright 2015-present 650 Industries. All rights reserved. package host.exp.exponent.kernel.services import host.exp.exponent.di.NativeModuleDepsProvider import host.exp.exponent.kernel.ExperienceKey import host.exp.exponent.storage.ExponentSharedPreferences import org.json.JSONException import org.json.JSONObject import java.util.* import javax.inject.Inject private const val FIVE_MINUTES_MS = (5 * 60 * 1000).toLong() private const val AUTO_RELOAD_BUFFER_BASE_MS = (5 * 1000).toLong() class ErrorRecoveryManager(private val experienceKey: ExperienceKey?) { private var timeLastLoaded = 0L private var didError = false @Inject lateinit var exponentSharedPreferences: ExponentSharedPreferences fun markExperienceLoaded() { timeLastLoaded = System.currentTimeMillis() timeAnyExperienceLoaded = timeLastLoaded markErrored(false) } @JvmOverloads fun markErrored(didError: Boolean = true) { this.didError = didError if (experienceKey != null) { val metadata = exponentSharedPreferences.getExperienceMetadata(experienceKey) ?: JSONObject() try { metadata.put(ExponentSharedPreferences.EXPERIENCE_METADATA_LOADING_ERROR, didError) exponentSharedPreferences.updateExperienceMetadata(experienceKey, metadata) } catch (e: JSONException) { e.printStackTrace() } } } fun shouldReloadOnError(): Boolean { val diff = System.currentTimeMillis() - timeLastLoaded val reloadBuffer = reloadBuffer() return diff >= reloadBuffer } private fun reloadBuffer(): Long { var interval = Math.min( FIVE_MINUTES_MS, ( AUTO_RELOAD_BUFFER_BASE_MS * Math.pow( 1.5, reloadBufferDepth.toDouble() ) ).toLong() ) val timeSinceLastExperienceLoaded = System.currentTimeMillis() - timeAnyExperienceLoaded if (timeSinceLastExperienceLoaded > interval * 2) { reloadBufferDepth = 0 interval = AUTO_RELOAD_BUFFER_BASE_MS } return interval } companion object { private val experienceScopeKeyToManager: MutableMap<String, ErrorRecoveryManager> = HashMap() private var timeAnyExperienceLoaded: Long = 0 // This goes up when there are a bunch of errors in succession private var reloadBufferDepth: Long = 0 @JvmStatic fun getInstance(experienceKey: ExperienceKey): ErrorRecoveryManager { if (!experienceScopeKeyToManager.containsKey(experienceKey.scopeKey)) { experienceScopeKeyToManager[experienceKey.scopeKey] = ErrorRecoveryManager(experienceKey) } return experienceScopeKeyToManager[experienceKey.scopeKey]!! } } init { NativeModuleDepsProvider.instance.inject(ErrorRecoveryManager::class.java, this) } }
android/expoview/src/main/java/host/exp/exponent/kernel/services/ErrorRecoveryManager.kt
1083533574
/* * Copyright 2019 Realm 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. */ // Most of com.sun.tools.javac content has been marked internal with JDK 9 @file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE") package io.realm.processor import com.sun.tools.javac.code.Attribute import com.sun.tools.javac.code.Scope import com.sun.tools.javac.code.Symbol import com.sun.tools.javac.code.Type import com.sun.tools.javac.util.Pair import io.realm.annotations.RealmNamingPolicy import io.realm.processor.nameconverter.* import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.* import javax.lang.model.type.DeclaredType import javax.lang.model.type.ReferenceType import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.util.Types import javax.tools.Diagnostic /** * Utility methods working with the Realm processor. */ object Utils { // API for retrieving symbols differs between JDK 8 and 9, so retrieve symbol information by // reflection private val classSymbolMembersMethod = Symbol.ClassSymbol::class.java.getMethod("members") private val scopeElementsMethod = try { // JDK 8 Scope::class.java.getMethod("getElements") } catch (e: NoSuchMethodException) { // JDK 9+ Scope::class.java.getMethod("getSymbols") } private lateinit var typeUtils: Types private lateinit var messager: Messager private lateinit var realmInteger: TypeMirror private lateinit var realmAny: TypeMirror private lateinit var realmList: DeclaredType private lateinit var realmResults: DeclaredType private lateinit var markerInterface: DeclaredType private lateinit var realmModel: TypeMirror private lateinit var realmDictionary: DeclaredType private lateinit var realmSet: DeclaredType fun initialize(env: ProcessingEnvironment) { val elementUtils = env.elementUtils typeUtils = env.typeUtils messager = env.messager realmInteger = elementUtils.getTypeElement("io.realm.MutableRealmInteger").asType() realmAny = elementUtils.getTypeElement("io.realm.RealmAny").asType() realmList = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmList"), typeUtils.getWildcardType(null, null)) realmResults = typeUtils.getDeclaredType(env.elementUtils.getTypeElement("io.realm.RealmResults"), typeUtils.getWildcardType(null, null)) realmModel = elementUtils.getTypeElement("io.realm.RealmModel").asType() markerInterface = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmModel")) realmDictionary = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmDictionary"), typeUtils.getWildcardType(null, null)) realmSet = typeUtils.getDeclaredType(elementUtils.getTypeElement("io.realm.RealmSet"), typeUtils.getWildcardType(null, null)) } /** * @return true if the given element is the default public no arg constructor for a class. */ fun isDefaultConstructor(constructor: Element): Boolean { return if (constructor.modifiers.contains(Modifier.PUBLIC)) { (constructor as ExecutableElement).parameters.isEmpty() } else false } fun getProxyClassSimpleName(field: VariableElement): SimpleClassName { return if (typeUtils.isAssignable(field.asType(), realmList)) { getProxyClassName(getGenericTypeQualifiedName(field)!!) } else { getProxyClassName(getFieldTypeQualifiedName(field)) } } fun getDictionaryGenericProxyClassSimpleName(field: VariableElement): SimpleClassName { return if (typeUtils.isAssignable(field.asType(), realmDictionary)) { getProxyClassName(getGenericTypeQualifiedName(field)!!) } else { getProxyClassName(getFieldTypeQualifiedName(field)) } } fun getSetGenericProxyClassSimpleName(field: VariableElement): SimpleClassName { return if (typeUtils.isAssignable(field.asType(), realmSet)) { getProxyClassName(getGenericTypeQualifiedName(field)!!) } else { getProxyClassName(getFieldTypeQualifiedName(field)) } } fun getModelClassQualifiedName(field: VariableElement): QualifiedClassName { return if (typeUtils.isAssignable(field.asType(), realmList)) { getGenericTypeQualifiedName(field)!! } else { getFieldTypeQualifiedName(field) } } fun getDictionaryGenericModelClassQualifiedName(field: VariableElement): QualifiedClassName { return if (typeUtils.isAssignable(field.asType(), realmDictionary)) { getGenericTypeQualifiedName(field)!! } else { getFieldTypeQualifiedName(field) } } fun getSetGenericModelClassQualifiedName(field: VariableElement): QualifiedClassName { return if (typeUtils.isAssignable(field.asType(), realmSet)) { getGenericTypeQualifiedName(field)!! } else { getFieldTypeQualifiedName(field) } } /** * @return the proxy class name for a given clazz */ fun getProxyClassName(className: QualifiedClassName): SimpleClassName { return SimpleClassName(className.toString().replace(".", "_") + Constants.PROXY_SUFFIX) } /** * @return `true` if a field is of type "java.lang.String", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isString(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "java.lang.String" } /** * @return `true` if a field is of type "org.bson.types.ObjectId", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isObjectId(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "org.bson.types.ObjectId" } /** * @return `true` if a field is of type "java.util.UUID", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isUUID(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "java.util.UUID" } /** * @return `true` if a field is a primitive type, `false` otherwise. * @throws IllegalArgumentException if the typeString is `null`. */ fun isPrimitiveType(typeString: String): Boolean { return typeString == "byte" || typeString == "short" || typeString == "int" || typeString == "long" || typeString == "float" || typeString == "double" || typeString == "boolean" || typeString == "char" } fun isPrimitiveType(type: QualifiedClassName): Boolean { return isPrimitiveType(type.toString()) } /** * @return `true` if a field is a boxed type, `false` otherwise. * @throws IllegalArgumentException if the typeString is `null`. */ fun isBoxedType(typeString: String?): Boolean { if (typeString == null) { throw IllegalArgumentException("Argument 'typeString' cannot be null.") } return typeString == Byte::class.javaObjectType.name || typeString == Short::class.javaObjectType.name || typeString == Int::class.javaObjectType.name || typeString == Long::class.javaObjectType.name || typeString == Float::class.javaObjectType.name || typeString == Double::class.javaObjectType.name || typeString == Boolean::class.javaObjectType.name } /** * @return `true` if a field is a type of primitive types, `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isPrimitiveType(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return field.asType().kind.isPrimitive } /** * @return `true` if a field is of type "byte[]", `false` otherwise. * @throws IllegalArgumentException if the field is `null`. */ fun isByteArray(field: VariableElement?): Boolean { if (field == null) { throw IllegalArgumentException("Argument 'field' cannot be null.") } return getFieldTypeQualifiedName(field).toString() == "byte[]" } /** * @return `true` if a given field type string is "java.lang.String", `false` otherwise. * @throws IllegalArgumentException if the fieldType is `null`. */ fun isString(fieldType: String?): Boolean { if (fieldType == null) { throw IllegalArgumentException("Argument 'fieldType' cannot be null.") } return String::class.java.name == fieldType } /** * @return `true` if a given type implement `RealmModel`, `false` otherwise. */ fun isImplementingMarkerInterface(classElement: Element): Boolean { return typeUtils.isAssignable(classElement.asType(), markerInterface) } /** * @return `true` if a given field type is `MutableRealmInteger`, `false` otherwise. */ fun isMutableRealmInteger(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmInteger) } /** * @return `true` if a given field type is `RealmAny`, `false` otherwise. */ fun isRealmAny(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmAny) } /** * @return `true` if a given field type is `RealmList`, `false` otherwise. */ fun isRealmList(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmList) } /** * @return `true` if a given field type is `RealmDictionary`, `false` otherwise. */ fun isRealmDictionary(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmDictionary) } /** * @return `true` if a given field type is `RealmDictionary` and its element type is value type, * `false` otherwise. */ fun isRealmValueDictionary(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) ?: return false return !isRealmModel(elementTypeMirror) && !isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmDictionary<RealmModel>`, `false` otherwise. */ fun isRealmModelDictionary(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) ?: return false return isRealmModel(elementTypeMirror) } /** * @return `true` if a given field type is `RealmDictionary` and its element type is `RealmAny`, * `false` otherwise. */ fun isRealmAnyDictionary(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) ?: return false return isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmSet`, `false` otherwise. */ fun isRealmSet(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmSet) } /** * @return `true` if a given field type is `RealmSet<RealmModel>`, `false` otherwise. */ fun isRealmModelSet(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) ?: return false return isRealmModel(elementTypeMirror) } /** * @return `true` if a given field type is `RealmSet` and its element type is value type, * `false` otherwise. */ fun isRealmValueSet(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) ?: return false return !isRealmModel(elementTypeMirror) && !isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmSet<RealmAny>`, `false` otherwise. */ fun isRealmAnySet(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) ?: return false return isRealmAny(elementTypeMirror) } /** * @param field [VariableElement] of a value list field. * @return element type of the list field. */ fun getValueListFieldType(field: VariableElement): Constants.RealmFieldType { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) return Constants.LIST_ELEMENT_TYPE_TO_REALM_TYPES[elementTypeMirror!!.toString()] ?: throw IllegalArgumentException("Invalid type mirror '$elementTypeMirror' for field '$field'") } /** * @param field [VariableElement] of a value dictionary field. * @return element type of the dictionary field. */ fun getValueDictionaryFieldType(field: VariableElement): Constants.RealmFieldType { val elementTypeMirror = TypeMirrors.getRealmDictionaryElementTypeMirror(field) return Constants.DICTIONARY_ELEMENT_TYPE_TO_REALM_TYPES[elementTypeMirror!!.toString()] ?: throw IllegalArgumentException("Invalid type mirror '$elementTypeMirror' for field '$field'") } /** * @param field [VariableElement] of a value set field. * @return element type of the set field. */ fun getValueSetFieldType(field: VariableElement): Constants.RealmFieldType { val elementTypeMirror = TypeMirrors.getRealmSetElementTypeMirror(field) return Constants.SET_ELEMENT_TYPE_TO_REALM_TYPES[elementTypeMirror!!.toString()] ?: throw IllegalArgumentException("Invalid type mirror '$elementTypeMirror' for field '$field'") } /** * @return `true` if a given field type is `RealmList` and its element type is `RealmObject`, * `false` otherwise. */ fun isRealmModelList(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) ?: return false return isRealmModel(elementTypeMirror) } /** * @return `true` if a given field type is `RealmList` and its element type is `RealmAny`, * `false` otherwise. */ fun isRealmAnyList(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) ?: return false return isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmList` and its element type is value type, * `false` otherwise. */ fun isRealmValueList(field: VariableElement): Boolean { val elementTypeMirror = TypeMirrors.getRealmListElementTypeMirror(field) ?: return false return !isRealmModel(elementTypeMirror) && !isRealmAny(elementTypeMirror) } /** * @return `true` if a given field type is `RealmModel`, `false` otherwise. */ fun isRealmModel(field: Element): Boolean { return isRealmModel(field.asType()) } /** * @return `true` if a given type is `RealmModel`, `false` otherwise. */ fun isRealmModel(type: TypeMirror?): Boolean { // This will return the wrong result if a model class doesn't exist at all, but // the compiler will catch that eventually. return typeUtils.isAssignable(type, realmModel) // // Not sure what is happening here, but typeUtils.isAssignable("Foo", realmModel) // // returns true even if Foo doesn't exist. No idea why this is happening. // // For now punt on the problem and check the direct supertype which should be either // // RealmObject or RealmModel. // // Original implementation: `` // // // // Theory: It looks like if `type` has the internal TypeTag.ERROR (internal API) it // // automatically translate to being assignable to everything. Possible some Java Specification // // rule taking effect. In our case, however we can do better since all Realm classes // // must be in the same compilation unit, so we should be able to look the type up. // for (TypeMirror typeMirror : typeUtils.directSupertypes(type)) { // String supertype = typeMirror.toString(); // if (supertype.equals("io.realm.RealmObject") || supertype.equals("io.realm.RealmModel")) { // return true; // } // } // return false; } /** * @return `true` if a given type is `RealmAny`, `false` otherwise. */ fun isRealmAny(type: TypeMirror?) = typeUtils.isAssignable(type, realmAny) fun isRealmResults(field: VariableElement): Boolean { return typeUtils.isAssignable(field.asType(), realmResults) } // get the fully-qualified type name for the generic type of a RealmResults fun getRealmResultsType(field: VariableElement): QualifiedClassName? { if (!isRealmResults(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } // get the fully-qualified type name for the generic type of a RealmList fun getRealmListType(field: VariableElement): QualifiedClassName? { if (!isRealmList(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } fun getDictionaryType(field: VariableElement): QualifiedClassName? { if (!isRealmDictionary(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } fun getSetType(field: VariableElement): QualifiedClassName? { if (!isRealmSet(field)) { return null } val type = getGenericTypeForContainer(field) ?: return null return QualifiedClassName(type.toString()) } // Note that, because subclassing subclasses of RealmObject is forbidden, // there is no need to deal with constructs like: <code>RealmResults&lt;? extends Foos&lt;</code>. fun getGenericTypeForContainer(field: VariableElement): ReferenceType? { var fieldType = field.asType() var kind = fieldType.kind if (kind != TypeKind.DECLARED) { return null } val args = (fieldType as DeclaredType).typeArguments if (args.size <= 0) { return null } fieldType = args[0] kind = fieldType.kind // We also support RealmList<byte[]> return if (kind != TypeKind.DECLARED && kind != TypeKind.ARRAY) { null } else fieldType as ReferenceType } /** * @return the qualified type name for a field. */ fun getFieldTypeQualifiedName(field: VariableElement): QualifiedClassName { return QualifiedClassName(field.asType().toString()) } /** * @return the generic type for Lists of the form `List<type>` */ fun getGenericTypeQualifiedName(field: VariableElement): QualifiedClassName? { val fieldType = field.asType() val typeArguments = (fieldType as DeclaredType).typeArguments return if (typeArguments.isEmpty()) null else QualifiedClassName(typeArguments[0].toString()) } /** * @return the generic type for Dictionaries of the form `RealmDictionary<type>` * Note: it applies to same types as RealmList. */ fun getDictionaryValueTypeQualifiedName(field: VariableElement): QualifiedClassName? { return getGenericTypeQualifiedName(field) } /** * @return the generic type for Sets of the form `RealmSet<type>` * Note: it applies to same types as RealmList. */ fun getSetValueTypeQualifiedName(field: VariableElement): QualifiedClassName? { return getGenericTypeQualifiedName(field) } /** * Return generic type mirror if any. */ fun getGenericType(field: VariableElement): TypeMirror? { val fieldType = field.asType() val typeArguments = (fieldType as DeclaredType).typeArguments return if (typeArguments.isEmpty()) null else typeArguments[0] } /** * Strips the package name from a fully qualified class name. */ fun stripPackage(fullyQualifiedClassName: String): String { val parts = fullyQualifiedClassName.split("\\.".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return if (parts.isNotEmpty()) { parts[parts.size - 1] } else { fullyQualifiedClassName } } fun error(message: String?, element: Element) { var e = element if (element is RealmFieldElement) { // Element is being cast to Symbol internally which breaks any implementors of the // Element interface. This is a hack to work around that. Bad bad Oracle e = element.fieldReference } messager.printMessage(Diagnostic.Kind.ERROR, message, e) } fun error(message: String?) { messager.printMessage(Diagnostic.Kind.ERROR, message) } fun note(message: String?, element: Element) { var e = element if (element is RealmFieldElement) { // Element is being cast to Symbol internally which breaks any implementors of the // Element interface. This is a hack to work around that. Bad bad Oracle e = element.fieldReference } messager.printMessage(Diagnostic.Kind.NOTE, message, e) } fun note(message: String?) { messager.printMessage(Diagnostic.Kind.NOTE, message) } fun getSuperClass(classType: TypeElement): Element { return typeUtils.asElement(classType.superclass) } /** * Returns the interface name for proxy class interfaces */ fun getProxyInterfaceName(qualifiedClassName: QualifiedClassName): SimpleClassName { return SimpleClassName(qualifiedClassName.toString().replace(".", "_") + Constants.INTERFACE_SUFFIX) } fun getNameFormatter(policy: RealmNamingPolicy?): NameConverter { if (policy == null) { return IdentityConverter() } when (policy) { RealmNamingPolicy.NO_POLICY -> return IdentityConverter() RealmNamingPolicy.IDENTITY -> return IdentityConverter() RealmNamingPolicy.LOWER_CASE_WITH_UNDERSCORES -> return LowerCaseWithSeparatorConverter('_') RealmNamingPolicy.CAMEL_CASE -> return CamelCaseConverter() RealmNamingPolicy.PASCAL_CASE -> return PascalCaseConverter() else -> throw IllegalArgumentException("Unknown policy: $policy") } } /** * Tries to find the internal class name for a referenced type. In model classes this can * happen with either direct object references or using `RealmList` or `RealmResults`. * * * This name is required by schema builders that operate on internal names and not the public ones. * * * Finding the internal name is easy if the referenced type is included in the current round * of annotation processing. In that case the internal name was also calculated in the same round * * * If the referenced type was already compiled, e.g being included from library, then we need * to get the name from the proxy class. Fortunately ProGuard should not have obfuscated any * class files at this point, meaning we can look it up dynamically. * * * If a name is looked up using the class loader, it also means that developers need to * combine a library and app module of model classes at runtime in the RealmConfiguration, but * this should be a valid use case. * * @param className type to lookup the internal name for. * @param classCollection collection of classes found in the current round of annotation processing. * @throws IllegalArgumentException If the internal name could not be looked up * @return the statement that evalutes to the internal class name. This will either be a string * constant or a reference to a static field in another class. In both cases, the return result * should not be put in quotes. */ fun getReferencedTypeInternalClassNameStatement(className: QualifiedClassName?, classCollection: ClassCollection): String { // Attempt to lookup internal name in current round if (classCollection.containsQualifiedClass(className)) { val metadata = classCollection.getClassFromQualifiedName(className!!) return "\"" + metadata.internalClassName + "\"" } // If we cannot find the name in the current processor round, we have to defer resolving the // name to runtime. The reason being that the annotation processor can only access the // compile type class path using Elements and Types which do not allow us to read // field values. // // Doing it this way unfortunately means that if the class is not on the apps classpath // a rather obscure class-not-found exception will be thrown when starting the app, but since // this is probably a very niche use case that is acceptable for now. // // TODO: We could probably create an internal annotation like `@InternalName("__Permission")` // which should make it possible for the annotation processor to read the value from the // proxy class, even for files in other jar files. return "io.realm.${getProxyClassName(className!!)}.ClassNameHelper.INTERNAL_CLASS_NAME" } /** * Returns a simple reference to the ColumnInfo class inside this model class, i.e. the package * name is not prefixed. */ fun getSimpleColumnInfoClassName(className: QualifiedClassName): String { val simpleModelClassName = className.getSimpleName() return "${getProxyClassName(className)}.${simpleModelClassName}ColumnInfo" } // Returns whether a type of a Realm field is embedded or not. // For types which are part of this processing round we can look it up immediately from // the metadata in the `classCollection`. For types defined in other modules we will // have to use the slower approach of inspecting the `embedded` property of the // RealmClass annotation using the compiler tool api. fun isFieldTypeEmbedded(type: TypeMirror, classCollection: ClassCollection) : Boolean { val fieldType = QualifiedClassName(type) val fieldTypeMetaData: ClassMetaData? = classCollection.getClassFromQualifiedNameOrNull(fieldType) return fieldTypeMetaData?.embedded ?: type.isEmbedded() } private fun TypeMirror.isEmbedded() : Boolean { var isEmbedded = false if (this is Type.ClassType) { val declarationAttributes: com.sun.tools.javac.util.List<Attribute.Compound>? = tsym.metadata?.declarationAttributes if (declarationAttributes != null) { loop@for (attribute: Attribute.Compound in declarationAttributes) { if (attribute.type.tsym.qualifiedName.toString() == "io.realm.annotations.RealmClass") { for (pair: Pair<Symbol.MethodSymbol, Attribute> in attribute.values) { if (pair.fst.name.toString() == "embedded") { isEmbedded = pair.snd.value as Boolean break@loop } } } } } } return isEmbedded } // Returns whether a type has primary key field // For types which are part of this processing round we can look it up immediately from // the metadata in the `classCollection`. For types defined in other modules we will // have to use the slower approach of inspecting the variable member `embedded` property of the // RealmClass annotation using the compiler tool api. fun fieldTypeHasPrimaryKey(type: TypeMirror, classCollection: ClassCollection): Boolean { val fieldType = QualifiedClassName(type) val fieldTypeMetaData: ClassMetaData? = classCollection.getClassFromQualifiedNameOrNull(fieldType) return fieldTypeMetaData?.hasPrimaryKey() ?: type.hasPrimaryKey() } private fun TypeMirror.hasPrimaryKey(): Boolean { if (this is Type.ClassType) { val scope = classSymbolMembersMethod.invoke(tsym) val elements: Iterable<Symbol> = scopeElementsMethod.invoke(scope) as Iterable<Symbol> val symbols = elements.filter { it is Symbol.VarSymbol } return symbols.any { it.declarationAttributes.any { attribute -> attribute.type.tsym.qualifiedName.toString() == "io.realm.annotations.PrimaryKey" } } } return false } }
realm/realm-annotations-processor/src/main/java/io/realm/processor/Utils.kt
4133607579
package com.cherryperry.amiami.model.mongodb import org.springframework.data.mongodb.repository.MongoRepository import org.springframework.data.mongodb.repository.Query interface ItemMongoRepository : MongoRepository<Item, String> { @Query(value = "{ url: { \$nin: ?0 } }", delete = true) fun deleteWhereIdNotInList(ids: Collection<String>): Long }
src/main/kotlin/com/cherryperry/amiami/model/mongodb/ItemMongoRepository.kt
2838152596
// Code generated by Wire protocol buffer compiler, do not edit. // Source: squareup.proto2.AllTypes in all_types_proto2.proto package com.squareup.wire.proto2.alltypes import com.squareup.wire.EnumAdapter import com.squareup.wire.FieldEncoding import com.squareup.wire.Message import com.squareup.wire.ProtoAdapter import com.squareup.wire.ProtoReader import com.squareup.wire.ProtoWriter import com.squareup.wire.ReverseProtoWriter import com.squareup.wire.Syntax import com.squareup.wire.Syntax.PROTO_2 import com.squareup.wire.WireEnum import com.squareup.wire.WireField import com.squareup.wire.`internal`.checkElementsNotNull import com.squareup.wire.`internal`.countNonNull import com.squareup.wire.`internal`.immutableCopyOf import com.squareup.wire.`internal`.missingRequiredFields import com.squareup.wire.`internal`.redactElements import com.squareup.wire.`internal`.sanitize import kotlin.Any import kotlin.Boolean import kotlin.Double import kotlin.Float import kotlin.Int import kotlin.Long import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.collections.Map import kotlin.jvm.JvmField import kotlin.jvm.JvmStatic import kotlin.lazy import okio.ByteString import okio.ByteString.Companion.decodeBase64 public class AllTypes( @field:WireField( tag = 1, adapter = "com.squareup.wire.ProtoAdapter#INT32", ) @JvmField public val opt_int32: Int? = null, @field:WireField( tag = 2, adapter = "com.squareup.wire.ProtoAdapter#UINT32", ) @JvmField public val opt_uint32: Int? = null, @field:WireField( tag = 3, adapter = "com.squareup.wire.ProtoAdapter#SINT32", ) @JvmField public val opt_sint32: Int? = null, @field:WireField( tag = 4, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", ) @JvmField public val opt_fixed32: Int? = null, @field:WireField( tag = 5, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", ) @JvmField public val opt_sfixed32: Int? = null, @field:WireField( tag = 6, adapter = "com.squareup.wire.ProtoAdapter#INT64", ) @JvmField public val opt_int64: Long? = null, @field:WireField( tag = 7, adapter = "com.squareup.wire.ProtoAdapter#UINT64", ) @JvmField public val opt_uint64: Long? = null, @field:WireField( tag = 8, adapter = "com.squareup.wire.ProtoAdapter#SINT64", ) @JvmField public val opt_sint64: Long? = null, @field:WireField( tag = 9, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", ) @JvmField public val opt_fixed64: Long? = null, @field:WireField( tag = 10, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", ) @JvmField public val opt_sfixed64: Long? = null, @field:WireField( tag = 11, adapter = "com.squareup.wire.ProtoAdapter#BOOL", ) @JvmField public val opt_bool: Boolean? = null, @field:WireField( tag = 12, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", ) @JvmField public val opt_float: Float? = null, @field:WireField( tag = 13, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", ) @JvmField public val opt_double: Double? = null, @field:WireField( tag = 14, adapter = "com.squareup.wire.ProtoAdapter#STRING", ) @JvmField public val opt_string: String? = null, @field:WireField( tag = 15, adapter = "com.squareup.wire.ProtoAdapter#BYTES", ) @JvmField public val opt_bytes: ByteString? = null, @field:WireField( tag = 16, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", ) @JvmField public val opt_nested_enum: NestedEnum? = null, @field:WireField( tag = 17, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", ) @JvmField public val opt_nested_message: NestedMessage? = null, @field:WireField( tag = 101, adapter = "com.squareup.wire.ProtoAdapter#INT32", label = WireField.Label.REQUIRED, ) @JvmField public val req_int32: Int, @field:WireField( tag = 102, adapter = "com.squareup.wire.ProtoAdapter#UINT32", label = WireField.Label.REQUIRED, ) @JvmField public val req_uint32: Int, @field:WireField( tag = 103, adapter = "com.squareup.wire.ProtoAdapter#SINT32", label = WireField.Label.REQUIRED, ) @JvmField public val req_sint32: Int, @field:WireField( tag = 104, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", label = WireField.Label.REQUIRED, ) @JvmField public val req_fixed32: Int, @field:WireField( tag = 105, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", label = WireField.Label.REQUIRED, ) @JvmField public val req_sfixed32: Int, @field:WireField( tag = 106, adapter = "com.squareup.wire.ProtoAdapter#INT64", label = WireField.Label.REQUIRED, ) @JvmField public val req_int64: Long, @field:WireField( tag = 107, adapter = "com.squareup.wire.ProtoAdapter#UINT64", label = WireField.Label.REQUIRED, ) @JvmField public val req_uint64: Long, @field:WireField( tag = 108, adapter = "com.squareup.wire.ProtoAdapter#SINT64", label = WireField.Label.REQUIRED, ) @JvmField public val req_sint64: Long, @field:WireField( tag = 109, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", label = WireField.Label.REQUIRED, ) @JvmField public val req_fixed64: Long, @field:WireField( tag = 110, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", label = WireField.Label.REQUIRED, ) @JvmField public val req_sfixed64: Long, @field:WireField( tag = 111, adapter = "com.squareup.wire.ProtoAdapter#BOOL", label = WireField.Label.REQUIRED, ) @JvmField public val req_bool: Boolean, @field:WireField( tag = 112, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", label = WireField.Label.REQUIRED, ) @JvmField public val req_float: Float, @field:WireField( tag = 113, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", label = WireField.Label.REQUIRED, ) @JvmField public val req_double: Double, @field:WireField( tag = 114, adapter = "com.squareup.wire.ProtoAdapter#STRING", label = WireField.Label.REQUIRED, ) @JvmField public val req_string: String, @field:WireField( tag = 115, adapter = "com.squareup.wire.ProtoAdapter#BYTES", label = WireField.Label.REQUIRED, ) @JvmField public val req_bytes: ByteString, @field:WireField( tag = 116, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", label = WireField.Label.REQUIRED, ) @JvmField public val req_nested_enum: NestedEnum, @field:WireField( tag = 117, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", label = WireField.Label.REQUIRED, ) @JvmField public val req_nested_message: NestedMessage, rep_int32: List<Int> = emptyList(), rep_uint32: List<Int> = emptyList(), rep_sint32: List<Int> = emptyList(), rep_fixed32: List<Int> = emptyList(), rep_sfixed32: List<Int> = emptyList(), rep_int64: List<Long> = emptyList(), rep_uint64: List<Long> = emptyList(), rep_sint64: List<Long> = emptyList(), rep_fixed64: List<Long> = emptyList(), rep_sfixed64: List<Long> = emptyList(), rep_bool: List<Boolean> = emptyList(), rep_float: List<Float> = emptyList(), rep_double: List<Double> = emptyList(), rep_string: List<String> = emptyList(), rep_bytes: List<ByteString> = emptyList(), rep_nested_enum: List<NestedEnum> = emptyList(), rep_nested_message: List<NestedMessage> = emptyList(), pack_int32: List<Int> = emptyList(), pack_uint32: List<Int> = emptyList(), pack_sint32: List<Int> = emptyList(), pack_fixed32: List<Int> = emptyList(), pack_sfixed32: List<Int> = emptyList(), pack_int64: List<Long> = emptyList(), pack_uint64: List<Long> = emptyList(), pack_sint64: List<Long> = emptyList(), pack_fixed64: List<Long> = emptyList(), pack_sfixed64: List<Long> = emptyList(), pack_bool: List<Boolean> = emptyList(), pack_float: List<Float> = emptyList(), pack_double: List<Double> = emptyList(), pack_nested_enum: List<NestedEnum> = emptyList(), @field:WireField( tag = 401, adapter = "com.squareup.wire.ProtoAdapter#INT32", ) @JvmField public val default_int32: Int? = null, @field:WireField( tag = 402, adapter = "com.squareup.wire.ProtoAdapter#UINT32", ) @JvmField public val default_uint32: Int? = null, @field:WireField( tag = 403, adapter = "com.squareup.wire.ProtoAdapter#SINT32", ) @JvmField public val default_sint32: Int? = null, @field:WireField( tag = 404, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", ) @JvmField public val default_fixed32: Int? = null, @field:WireField( tag = 405, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", ) @JvmField public val default_sfixed32: Int? = null, @field:WireField( tag = 406, adapter = "com.squareup.wire.ProtoAdapter#INT64", ) @JvmField public val default_int64: Long? = null, @field:WireField( tag = 407, adapter = "com.squareup.wire.ProtoAdapter#UINT64", ) @JvmField public val default_uint64: Long? = null, @field:WireField( tag = 408, adapter = "com.squareup.wire.ProtoAdapter#SINT64", ) @JvmField public val default_sint64: Long? = null, @field:WireField( tag = 409, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", ) @JvmField public val default_fixed64: Long? = null, @field:WireField( tag = 410, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", ) @JvmField public val default_sfixed64: Long? = null, @field:WireField( tag = 411, adapter = "com.squareup.wire.ProtoAdapter#BOOL", ) @JvmField public val default_bool: Boolean? = null, @field:WireField( tag = 412, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", ) @JvmField public val default_float: Float? = null, @field:WireField( tag = 413, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", ) @JvmField public val default_double: Double? = null, @field:WireField( tag = 414, adapter = "com.squareup.wire.ProtoAdapter#STRING", ) @JvmField public val default_string: String? = null, @field:WireField( tag = 415, adapter = "com.squareup.wire.ProtoAdapter#BYTES", ) @JvmField public val default_bytes: ByteString? = null, @field:WireField( tag = 416, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", ) @JvmField public val default_nested_enum: NestedEnum? = null, map_int32_int32: Map<Int, Int> = emptyMap(), map_string_string: Map<String, String> = emptyMap(), map_string_message: Map<String, NestedMessage> = emptyMap(), map_string_enum: Map<String, NestedEnum> = emptyMap(), @field:WireField( tag = 601, adapter = "com.squareup.wire.ProtoAdapter#STRING", oneofName = "choice", ) @JvmField public val oneof_string: String? = null, @field:WireField( tag = 602, adapter = "com.squareup.wire.ProtoAdapter#INT32", oneofName = "choice", ) @JvmField public val oneof_int32: Int? = null, @field:WireField( tag = 603, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", oneofName = "choice", ) @JvmField public val oneof_nested_message: NestedMessage? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1001, adapter = "com.squareup.wire.ProtoAdapter#INT32", ) @JvmField public val ext_opt_int32: Int? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1002, adapter = "com.squareup.wire.ProtoAdapter#UINT32", ) @JvmField public val ext_opt_uint32: Int? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1003, adapter = "com.squareup.wire.ProtoAdapter#SINT32", ) @JvmField public val ext_opt_sint32: Int? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1004, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", ) @JvmField public val ext_opt_fixed32: Int? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1005, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", ) @JvmField public val ext_opt_sfixed32: Int? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1006, adapter = "com.squareup.wire.ProtoAdapter#INT64", ) @JvmField public val ext_opt_int64: Long? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1007, adapter = "com.squareup.wire.ProtoAdapter#UINT64", ) @JvmField public val ext_opt_uint64: Long? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1008, adapter = "com.squareup.wire.ProtoAdapter#SINT64", ) @JvmField public val ext_opt_sint64: Long? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1009, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", ) @JvmField public val ext_opt_fixed64: Long? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1010, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", ) @JvmField public val ext_opt_sfixed64: Long? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1011, adapter = "com.squareup.wire.ProtoAdapter#BOOL", ) @JvmField public val ext_opt_bool: Boolean? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1012, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", ) @JvmField public val ext_opt_float: Float? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1013, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", ) @JvmField public val ext_opt_double: Double? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1014, adapter = "com.squareup.wire.ProtoAdapter#STRING", ) @JvmField public val ext_opt_string: String? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1015, adapter = "com.squareup.wire.ProtoAdapter#BYTES", ) @JvmField public val ext_opt_bytes: ByteString? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1016, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", ) @JvmField public val ext_opt_nested_enum: NestedEnum? = null, /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1017, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", ) @JvmField public val ext_opt_nested_message: NestedMessage? = null, ext_rep_int32: List<Int> = emptyList(), ext_rep_uint32: List<Int> = emptyList(), ext_rep_sint32: List<Int> = emptyList(), ext_rep_fixed32: List<Int> = emptyList(), ext_rep_sfixed32: List<Int> = emptyList(), ext_rep_int64: List<Long> = emptyList(), ext_rep_uint64: List<Long> = emptyList(), ext_rep_sint64: List<Long> = emptyList(), ext_rep_fixed64: List<Long> = emptyList(), ext_rep_sfixed64: List<Long> = emptyList(), ext_rep_bool: List<Boolean> = emptyList(), ext_rep_float: List<Float> = emptyList(), ext_rep_double: List<Double> = emptyList(), ext_rep_string: List<String> = emptyList(), ext_rep_bytes: List<ByteString> = emptyList(), ext_rep_nested_enum: List<NestedEnum> = emptyList(), ext_rep_nested_message: List<NestedMessage> = emptyList(), ext_pack_int32: List<Int> = emptyList(), ext_pack_uint32: List<Int> = emptyList(), ext_pack_sint32: List<Int> = emptyList(), ext_pack_fixed32: List<Int> = emptyList(), ext_pack_sfixed32: List<Int> = emptyList(), ext_pack_int64: List<Long> = emptyList(), ext_pack_uint64: List<Long> = emptyList(), ext_pack_sint64: List<Long> = emptyList(), ext_pack_fixed64: List<Long> = emptyList(), ext_pack_sfixed64: List<Long> = emptyList(), ext_pack_bool: List<Boolean> = emptyList(), ext_pack_float: List<Float> = emptyList(), ext_pack_double: List<Double> = emptyList(), ext_pack_nested_enum: List<NestedEnum> = emptyList(), unknownFields: ByteString = ByteString.EMPTY, ) : Message<AllTypes, AllTypes.Builder>(ADAPTER, unknownFields) { @field:WireField( tag = 201, adapter = "com.squareup.wire.ProtoAdapter#INT32", label = WireField.Label.REPEATED, ) @JvmField public val rep_int32: List<Int> = immutableCopyOf("rep_int32", rep_int32) @field:WireField( tag = 202, adapter = "com.squareup.wire.ProtoAdapter#UINT32", label = WireField.Label.REPEATED, ) @JvmField public val rep_uint32: List<Int> = immutableCopyOf("rep_uint32", rep_uint32) @field:WireField( tag = 203, adapter = "com.squareup.wire.ProtoAdapter#SINT32", label = WireField.Label.REPEATED, ) @JvmField public val rep_sint32: List<Int> = immutableCopyOf("rep_sint32", rep_sint32) @field:WireField( tag = 204, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", label = WireField.Label.REPEATED, ) @JvmField public val rep_fixed32: List<Int> = immutableCopyOf("rep_fixed32", rep_fixed32) @field:WireField( tag = 205, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", label = WireField.Label.REPEATED, ) @JvmField public val rep_sfixed32: List<Int> = immutableCopyOf("rep_sfixed32", rep_sfixed32) @field:WireField( tag = 206, adapter = "com.squareup.wire.ProtoAdapter#INT64", label = WireField.Label.REPEATED, ) @JvmField public val rep_int64: List<Long> = immutableCopyOf("rep_int64", rep_int64) @field:WireField( tag = 207, adapter = "com.squareup.wire.ProtoAdapter#UINT64", label = WireField.Label.REPEATED, ) @JvmField public val rep_uint64: List<Long> = immutableCopyOf("rep_uint64", rep_uint64) @field:WireField( tag = 208, adapter = "com.squareup.wire.ProtoAdapter#SINT64", label = WireField.Label.REPEATED, ) @JvmField public val rep_sint64: List<Long> = immutableCopyOf("rep_sint64", rep_sint64) @field:WireField( tag = 209, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", label = WireField.Label.REPEATED, ) @JvmField public val rep_fixed64: List<Long> = immutableCopyOf("rep_fixed64", rep_fixed64) @field:WireField( tag = 210, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", label = WireField.Label.REPEATED, ) @JvmField public val rep_sfixed64: List<Long> = immutableCopyOf("rep_sfixed64", rep_sfixed64) @field:WireField( tag = 211, adapter = "com.squareup.wire.ProtoAdapter#BOOL", label = WireField.Label.REPEATED, ) @JvmField public val rep_bool: List<Boolean> = immutableCopyOf("rep_bool", rep_bool) @field:WireField( tag = 212, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", label = WireField.Label.REPEATED, ) @JvmField public val rep_float: List<Float> = immutableCopyOf("rep_float", rep_float) @field:WireField( tag = 213, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", label = WireField.Label.REPEATED, ) @JvmField public val rep_double: List<Double> = immutableCopyOf("rep_double", rep_double) @field:WireField( tag = 214, adapter = "com.squareup.wire.ProtoAdapter#STRING", label = WireField.Label.REPEATED, ) @JvmField public val rep_string: List<String> = immutableCopyOf("rep_string", rep_string) @field:WireField( tag = 215, adapter = "com.squareup.wire.ProtoAdapter#BYTES", label = WireField.Label.REPEATED, ) @JvmField public val rep_bytes: List<ByteString> = immutableCopyOf("rep_bytes", rep_bytes) @field:WireField( tag = 216, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", label = WireField.Label.REPEATED, ) @JvmField public val rep_nested_enum: List<NestedEnum> = immutableCopyOf("rep_nested_enum", rep_nested_enum) @field:WireField( tag = 217, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", label = WireField.Label.REPEATED, ) @JvmField public val rep_nested_message: List<NestedMessage> = immutableCopyOf("rep_nested_message", rep_nested_message) @field:WireField( tag = 301, adapter = "com.squareup.wire.ProtoAdapter#INT32", label = WireField.Label.PACKED, ) @JvmField public val pack_int32: List<Int> = immutableCopyOf("pack_int32", pack_int32) @field:WireField( tag = 302, adapter = "com.squareup.wire.ProtoAdapter#UINT32", label = WireField.Label.PACKED, ) @JvmField public val pack_uint32: List<Int> = immutableCopyOf("pack_uint32", pack_uint32) @field:WireField( tag = 303, adapter = "com.squareup.wire.ProtoAdapter#SINT32", label = WireField.Label.PACKED, ) @JvmField public val pack_sint32: List<Int> = immutableCopyOf("pack_sint32", pack_sint32) @field:WireField( tag = 304, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", label = WireField.Label.PACKED, ) @JvmField public val pack_fixed32: List<Int> = immutableCopyOf("pack_fixed32", pack_fixed32) @field:WireField( tag = 305, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", label = WireField.Label.PACKED, ) @JvmField public val pack_sfixed32: List<Int> = immutableCopyOf("pack_sfixed32", pack_sfixed32) @field:WireField( tag = 306, adapter = "com.squareup.wire.ProtoAdapter#INT64", label = WireField.Label.PACKED, ) @JvmField public val pack_int64: List<Long> = immutableCopyOf("pack_int64", pack_int64) @field:WireField( tag = 307, adapter = "com.squareup.wire.ProtoAdapter#UINT64", label = WireField.Label.PACKED, ) @JvmField public val pack_uint64: List<Long> = immutableCopyOf("pack_uint64", pack_uint64) @field:WireField( tag = 308, adapter = "com.squareup.wire.ProtoAdapter#SINT64", label = WireField.Label.PACKED, ) @JvmField public val pack_sint64: List<Long> = immutableCopyOf("pack_sint64", pack_sint64) @field:WireField( tag = 309, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", label = WireField.Label.PACKED, ) @JvmField public val pack_fixed64: List<Long> = immutableCopyOf("pack_fixed64", pack_fixed64) @field:WireField( tag = 310, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", label = WireField.Label.PACKED, ) @JvmField public val pack_sfixed64: List<Long> = immutableCopyOf("pack_sfixed64", pack_sfixed64) @field:WireField( tag = 311, adapter = "com.squareup.wire.ProtoAdapter#BOOL", label = WireField.Label.PACKED, ) @JvmField public val pack_bool: List<Boolean> = immutableCopyOf("pack_bool", pack_bool) @field:WireField( tag = 312, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", label = WireField.Label.PACKED, ) @JvmField public val pack_float: List<Float> = immutableCopyOf("pack_float", pack_float) @field:WireField( tag = 313, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", label = WireField.Label.PACKED, ) @JvmField public val pack_double: List<Double> = immutableCopyOf("pack_double", pack_double) @field:WireField( tag = 316, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", label = WireField.Label.PACKED, ) @JvmField public val pack_nested_enum: List<NestedEnum> = immutableCopyOf("pack_nested_enum", pack_nested_enum) @field:WireField( tag = 501, keyAdapter = "com.squareup.wire.ProtoAdapter#INT32", adapter = "com.squareup.wire.ProtoAdapter#INT32", ) @JvmField public val map_int32_int32: Map<Int, Int> = immutableCopyOf("map_int32_int32", map_int32_int32) @field:WireField( tag = 502, keyAdapter = "com.squareup.wire.ProtoAdapter#STRING", adapter = "com.squareup.wire.ProtoAdapter#STRING", ) @JvmField public val map_string_string: Map<String, String> = immutableCopyOf("map_string_string", map_string_string) @field:WireField( tag = 503, keyAdapter = "com.squareup.wire.ProtoAdapter#STRING", adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", ) @JvmField public val map_string_message: Map<String, NestedMessage> = immutableCopyOf("map_string_message", map_string_message) @field:WireField( tag = 504, keyAdapter = "com.squareup.wire.ProtoAdapter#STRING", adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", ) @JvmField public val map_string_enum: Map<String, NestedEnum> = immutableCopyOf("map_string_enum", map_string_enum) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1101, adapter = "com.squareup.wire.ProtoAdapter#INT32", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_int32: List<Int> = immutableCopyOf("ext_rep_int32", ext_rep_int32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1102, adapter = "com.squareup.wire.ProtoAdapter#UINT32", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_uint32: List<Int> = immutableCopyOf("ext_rep_uint32", ext_rep_uint32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1103, adapter = "com.squareup.wire.ProtoAdapter#SINT32", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_sint32: List<Int> = immutableCopyOf("ext_rep_sint32", ext_rep_sint32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1104, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_fixed32: List<Int> = immutableCopyOf("ext_rep_fixed32", ext_rep_fixed32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1105, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_sfixed32: List<Int> = immutableCopyOf("ext_rep_sfixed32", ext_rep_sfixed32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1106, adapter = "com.squareup.wire.ProtoAdapter#INT64", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_int64: List<Long> = immutableCopyOf("ext_rep_int64", ext_rep_int64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1107, adapter = "com.squareup.wire.ProtoAdapter#UINT64", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_uint64: List<Long> = immutableCopyOf("ext_rep_uint64", ext_rep_uint64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1108, adapter = "com.squareup.wire.ProtoAdapter#SINT64", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_sint64: List<Long> = immutableCopyOf("ext_rep_sint64", ext_rep_sint64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1109, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_fixed64: List<Long> = immutableCopyOf("ext_rep_fixed64", ext_rep_fixed64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1110, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_sfixed64: List<Long> = immutableCopyOf("ext_rep_sfixed64", ext_rep_sfixed64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1111, adapter = "com.squareup.wire.ProtoAdapter#BOOL", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_bool: List<Boolean> = immutableCopyOf("ext_rep_bool", ext_rep_bool) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1112, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_float: List<Float> = immutableCopyOf("ext_rep_float", ext_rep_float) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1113, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_double: List<Double> = immutableCopyOf("ext_rep_double", ext_rep_double) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1114, adapter = "com.squareup.wire.ProtoAdapter#STRING", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_string: List<String> = immutableCopyOf("ext_rep_string", ext_rep_string) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1115, adapter = "com.squareup.wire.ProtoAdapter#BYTES", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_bytes: List<ByteString> = immutableCopyOf("ext_rep_bytes", ext_rep_bytes) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1116, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_nested_enum: List<NestedEnum> = immutableCopyOf("ext_rep_nested_enum", ext_rep_nested_enum) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1117, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedMessage#ADAPTER", label = WireField.Label.REPEATED, ) @JvmField public val ext_rep_nested_message: List<NestedMessage> = immutableCopyOf("ext_rep_nested_message", ext_rep_nested_message) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1201, adapter = "com.squareup.wire.ProtoAdapter#INT32", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_int32: List<Int> = immutableCopyOf("ext_pack_int32", ext_pack_int32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1202, adapter = "com.squareup.wire.ProtoAdapter#UINT32", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_uint32: List<Int> = immutableCopyOf("ext_pack_uint32", ext_pack_uint32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1203, adapter = "com.squareup.wire.ProtoAdapter#SINT32", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_sint32: List<Int> = immutableCopyOf("ext_pack_sint32", ext_pack_sint32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1204, adapter = "com.squareup.wire.ProtoAdapter#FIXED32", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_fixed32: List<Int> = immutableCopyOf("ext_pack_fixed32", ext_pack_fixed32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1205, adapter = "com.squareup.wire.ProtoAdapter#SFIXED32", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_sfixed32: List<Int> = immutableCopyOf("ext_pack_sfixed32", ext_pack_sfixed32) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1206, adapter = "com.squareup.wire.ProtoAdapter#INT64", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_int64: List<Long> = immutableCopyOf("ext_pack_int64", ext_pack_int64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1207, adapter = "com.squareup.wire.ProtoAdapter#UINT64", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_uint64: List<Long> = immutableCopyOf("ext_pack_uint64", ext_pack_uint64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1208, adapter = "com.squareup.wire.ProtoAdapter#SINT64", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_sint64: List<Long> = immutableCopyOf("ext_pack_sint64", ext_pack_sint64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1209, adapter = "com.squareup.wire.ProtoAdapter#FIXED64", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_fixed64: List<Long> = immutableCopyOf("ext_pack_fixed64", ext_pack_fixed64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1210, adapter = "com.squareup.wire.ProtoAdapter#SFIXED64", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_sfixed64: List<Long> = immutableCopyOf("ext_pack_sfixed64", ext_pack_sfixed64) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1211, adapter = "com.squareup.wire.ProtoAdapter#BOOL", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_bool: List<Boolean> = immutableCopyOf("ext_pack_bool", ext_pack_bool) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1212, adapter = "com.squareup.wire.ProtoAdapter#FLOAT", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_float: List<Float> = immutableCopyOf("ext_pack_float", ext_pack_float) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1213, adapter = "com.squareup.wire.ProtoAdapter#DOUBLE", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_double: List<Double> = immutableCopyOf("ext_pack_double", ext_pack_double) /** * Extension source: all_types_proto2.proto */ @field:WireField( tag = 1216, adapter = "com.squareup.wire.proto2.alltypes.AllTypes${'$'}NestedEnum#ADAPTER", label = WireField.Label.PACKED, ) @JvmField public val ext_pack_nested_enum: List<NestedEnum> = immutableCopyOf("ext_pack_nested_enum", ext_pack_nested_enum) init { require(countNonNull(oneof_string, oneof_int32, oneof_nested_message) <= 1) { "At most one of oneof_string, oneof_int32, oneof_nested_message may be non-null" } } public override fun newBuilder(): Builder { val builder = Builder() builder.opt_int32 = opt_int32 builder.opt_uint32 = opt_uint32 builder.opt_sint32 = opt_sint32 builder.opt_fixed32 = opt_fixed32 builder.opt_sfixed32 = opt_sfixed32 builder.opt_int64 = opt_int64 builder.opt_uint64 = opt_uint64 builder.opt_sint64 = opt_sint64 builder.opt_fixed64 = opt_fixed64 builder.opt_sfixed64 = opt_sfixed64 builder.opt_bool = opt_bool builder.opt_float = opt_float builder.opt_double = opt_double builder.opt_string = opt_string builder.opt_bytes = opt_bytes builder.opt_nested_enum = opt_nested_enum builder.opt_nested_message = opt_nested_message builder.req_int32 = req_int32 builder.req_uint32 = req_uint32 builder.req_sint32 = req_sint32 builder.req_fixed32 = req_fixed32 builder.req_sfixed32 = req_sfixed32 builder.req_int64 = req_int64 builder.req_uint64 = req_uint64 builder.req_sint64 = req_sint64 builder.req_fixed64 = req_fixed64 builder.req_sfixed64 = req_sfixed64 builder.req_bool = req_bool builder.req_float = req_float builder.req_double = req_double builder.req_string = req_string builder.req_bytes = req_bytes builder.req_nested_enum = req_nested_enum builder.req_nested_message = req_nested_message builder.rep_int32 = rep_int32 builder.rep_uint32 = rep_uint32 builder.rep_sint32 = rep_sint32 builder.rep_fixed32 = rep_fixed32 builder.rep_sfixed32 = rep_sfixed32 builder.rep_int64 = rep_int64 builder.rep_uint64 = rep_uint64 builder.rep_sint64 = rep_sint64 builder.rep_fixed64 = rep_fixed64 builder.rep_sfixed64 = rep_sfixed64 builder.rep_bool = rep_bool builder.rep_float = rep_float builder.rep_double = rep_double builder.rep_string = rep_string builder.rep_bytes = rep_bytes builder.rep_nested_enum = rep_nested_enum builder.rep_nested_message = rep_nested_message builder.pack_int32 = pack_int32 builder.pack_uint32 = pack_uint32 builder.pack_sint32 = pack_sint32 builder.pack_fixed32 = pack_fixed32 builder.pack_sfixed32 = pack_sfixed32 builder.pack_int64 = pack_int64 builder.pack_uint64 = pack_uint64 builder.pack_sint64 = pack_sint64 builder.pack_fixed64 = pack_fixed64 builder.pack_sfixed64 = pack_sfixed64 builder.pack_bool = pack_bool builder.pack_float = pack_float builder.pack_double = pack_double builder.pack_nested_enum = pack_nested_enum builder.default_int32 = default_int32 builder.default_uint32 = default_uint32 builder.default_sint32 = default_sint32 builder.default_fixed32 = default_fixed32 builder.default_sfixed32 = default_sfixed32 builder.default_int64 = default_int64 builder.default_uint64 = default_uint64 builder.default_sint64 = default_sint64 builder.default_fixed64 = default_fixed64 builder.default_sfixed64 = default_sfixed64 builder.default_bool = default_bool builder.default_float = default_float builder.default_double = default_double builder.default_string = default_string builder.default_bytes = default_bytes builder.default_nested_enum = default_nested_enum builder.map_int32_int32 = map_int32_int32 builder.map_string_string = map_string_string builder.map_string_message = map_string_message builder.map_string_enum = map_string_enum builder.oneof_string = oneof_string builder.oneof_int32 = oneof_int32 builder.oneof_nested_message = oneof_nested_message builder.ext_opt_int32 = ext_opt_int32 builder.ext_opt_uint32 = ext_opt_uint32 builder.ext_opt_sint32 = ext_opt_sint32 builder.ext_opt_fixed32 = ext_opt_fixed32 builder.ext_opt_sfixed32 = ext_opt_sfixed32 builder.ext_opt_int64 = ext_opt_int64 builder.ext_opt_uint64 = ext_opt_uint64 builder.ext_opt_sint64 = ext_opt_sint64 builder.ext_opt_fixed64 = ext_opt_fixed64 builder.ext_opt_sfixed64 = ext_opt_sfixed64 builder.ext_opt_bool = ext_opt_bool builder.ext_opt_float = ext_opt_float builder.ext_opt_double = ext_opt_double builder.ext_opt_string = ext_opt_string builder.ext_opt_bytes = ext_opt_bytes builder.ext_opt_nested_enum = ext_opt_nested_enum builder.ext_opt_nested_message = ext_opt_nested_message builder.ext_rep_int32 = ext_rep_int32 builder.ext_rep_uint32 = ext_rep_uint32 builder.ext_rep_sint32 = ext_rep_sint32 builder.ext_rep_fixed32 = ext_rep_fixed32 builder.ext_rep_sfixed32 = ext_rep_sfixed32 builder.ext_rep_int64 = ext_rep_int64 builder.ext_rep_uint64 = ext_rep_uint64 builder.ext_rep_sint64 = ext_rep_sint64 builder.ext_rep_fixed64 = ext_rep_fixed64 builder.ext_rep_sfixed64 = ext_rep_sfixed64 builder.ext_rep_bool = ext_rep_bool builder.ext_rep_float = ext_rep_float builder.ext_rep_double = ext_rep_double builder.ext_rep_string = ext_rep_string builder.ext_rep_bytes = ext_rep_bytes builder.ext_rep_nested_enum = ext_rep_nested_enum builder.ext_rep_nested_message = ext_rep_nested_message builder.ext_pack_int32 = ext_pack_int32 builder.ext_pack_uint32 = ext_pack_uint32 builder.ext_pack_sint32 = ext_pack_sint32 builder.ext_pack_fixed32 = ext_pack_fixed32 builder.ext_pack_sfixed32 = ext_pack_sfixed32 builder.ext_pack_int64 = ext_pack_int64 builder.ext_pack_uint64 = ext_pack_uint64 builder.ext_pack_sint64 = ext_pack_sint64 builder.ext_pack_fixed64 = ext_pack_fixed64 builder.ext_pack_sfixed64 = ext_pack_sfixed64 builder.ext_pack_bool = ext_pack_bool builder.ext_pack_float = ext_pack_float builder.ext_pack_double = ext_pack_double builder.ext_pack_nested_enum = ext_pack_nested_enum builder.addUnknownFields(unknownFields) return builder } public override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is AllTypes) return false if (unknownFields != other.unknownFields) return false if (opt_int32 != other.opt_int32) return false if (opt_uint32 != other.opt_uint32) return false if (opt_sint32 != other.opt_sint32) return false if (opt_fixed32 != other.opt_fixed32) return false if (opt_sfixed32 != other.opt_sfixed32) return false if (opt_int64 != other.opt_int64) return false if (opt_uint64 != other.opt_uint64) return false if (opt_sint64 != other.opt_sint64) return false if (opt_fixed64 != other.opt_fixed64) return false if (opt_sfixed64 != other.opt_sfixed64) return false if (opt_bool != other.opt_bool) return false if (opt_float != other.opt_float) return false if (opt_double != other.opt_double) return false if (opt_string != other.opt_string) return false if (opt_bytes != other.opt_bytes) return false if (opt_nested_enum != other.opt_nested_enum) return false if (opt_nested_message != other.opt_nested_message) return false if (req_int32 != other.req_int32) return false if (req_uint32 != other.req_uint32) return false if (req_sint32 != other.req_sint32) return false if (req_fixed32 != other.req_fixed32) return false if (req_sfixed32 != other.req_sfixed32) return false if (req_int64 != other.req_int64) return false if (req_uint64 != other.req_uint64) return false if (req_sint64 != other.req_sint64) return false if (req_fixed64 != other.req_fixed64) return false if (req_sfixed64 != other.req_sfixed64) return false if (req_bool != other.req_bool) return false if (req_float != other.req_float) return false if (req_double != other.req_double) return false if (req_string != other.req_string) return false if (req_bytes != other.req_bytes) return false if (req_nested_enum != other.req_nested_enum) return false if (req_nested_message != other.req_nested_message) return false if (rep_int32 != other.rep_int32) return false if (rep_uint32 != other.rep_uint32) return false if (rep_sint32 != other.rep_sint32) return false if (rep_fixed32 != other.rep_fixed32) return false if (rep_sfixed32 != other.rep_sfixed32) return false if (rep_int64 != other.rep_int64) return false if (rep_uint64 != other.rep_uint64) return false if (rep_sint64 != other.rep_sint64) return false if (rep_fixed64 != other.rep_fixed64) return false if (rep_sfixed64 != other.rep_sfixed64) return false if (rep_bool != other.rep_bool) return false if (rep_float != other.rep_float) return false if (rep_double != other.rep_double) return false if (rep_string != other.rep_string) return false if (rep_bytes != other.rep_bytes) return false if (rep_nested_enum != other.rep_nested_enum) return false if (rep_nested_message != other.rep_nested_message) return false if (pack_int32 != other.pack_int32) return false if (pack_uint32 != other.pack_uint32) return false if (pack_sint32 != other.pack_sint32) return false if (pack_fixed32 != other.pack_fixed32) return false if (pack_sfixed32 != other.pack_sfixed32) return false if (pack_int64 != other.pack_int64) return false if (pack_uint64 != other.pack_uint64) return false if (pack_sint64 != other.pack_sint64) return false if (pack_fixed64 != other.pack_fixed64) return false if (pack_sfixed64 != other.pack_sfixed64) return false if (pack_bool != other.pack_bool) return false if (pack_float != other.pack_float) return false if (pack_double != other.pack_double) return false if (pack_nested_enum != other.pack_nested_enum) return false if (default_int32 != other.default_int32) return false if (default_uint32 != other.default_uint32) return false if (default_sint32 != other.default_sint32) return false if (default_fixed32 != other.default_fixed32) return false if (default_sfixed32 != other.default_sfixed32) return false if (default_int64 != other.default_int64) return false if (default_uint64 != other.default_uint64) return false if (default_sint64 != other.default_sint64) return false if (default_fixed64 != other.default_fixed64) return false if (default_sfixed64 != other.default_sfixed64) return false if (default_bool != other.default_bool) return false if (default_float != other.default_float) return false if (default_double != other.default_double) return false if (default_string != other.default_string) return false if (default_bytes != other.default_bytes) return false if (default_nested_enum != other.default_nested_enum) return false if (map_int32_int32 != other.map_int32_int32) return false if (map_string_string != other.map_string_string) return false if (map_string_message != other.map_string_message) return false if (map_string_enum != other.map_string_enum) return false if (oneof_string != other.oneof_string) return false if (oneof_int32 != other.oneof_int32) return false if (oneof_nested_message != other.oneof_nested_message) return false if (ext_opt_int32 != other.ext_opt_int32) return false if (ext_opt_uint32 != other.ext_opt_uint32) return false if (ext_opt_sint32 != other.ext_opt_sint32) return false if (ext_opt_fixed32 != other.ext_opt_fixed32) return false if (ext_opt_sfixed32 != other.ext_opt_sfixed32) return false if (ext_opt_int64 != other.ext_opt_int64) return false if (ext_opt_uint64 != other.ext_opt_uint64) return false if (ext_opt_sint64 != other.ext_opt_sint64) return false if (ext_opt_fixed64 != other.ext_opt_fixed64) return false if (ext_opt_sfixed64 != other.ext_opt_sfixed64) return false if (ext_opt_bool != other.ext_opt_bool) return false if (ext_opt_float != other.ext_opt_float) return false if (ext_opt_double != other.ext_opt_double) return false if (ext_opt_string != other.ext_opt_string) return false if (ext_opt_bytes != other.ext_opt_bytes) return false if (ext_opt_nested_enum != other.ext_opt_nested_enum) return false if (ext_opt_nested_message != other.ext_opt_nested_message) return false if (ext_rep_int32 != other.ext_rep_int32) return false if (ext_rep_uint32 != other.ext_rep_uint32) return false if (ext_rep_sint32 != other.ext_rep_sint32) return false if (ext_rep_fixed32 != other.ext_rep_fixed32) return false if (ext_rep_sfixed32 != other.ext_rep_sfixed32) return false if (ext_rep_int64 != other.ext_rep_int64) return false if (ext_rep_uint64 != other.ext_rep_uint64) return false if (ext_rep_sint64 != other.ext_rep_sint64) return false if (ext_rep_fixed64 != other.ext_rep_fixed64) return false if (ext_rep_sfixed64 != other.ext_rep_sfixed64) return false if (ext_rep_bool != other.ext_rep_bool) return false if (ext_rep_float != other.ext_rep_float) return false if (ext_rep_double != other.ext_rep_double) return false if (ext_rep_string != other.ext_rep_string) return false if (ext_rep_bytes != other.ext_rep_bytes) return false if (ext_rep_nested_enum != other.ext_rep_nested_enum) return false if (ext_rep_nested_message != other.ext_rep_nested_message) return false if (ext_pack_int32 != other.ext_pack_int32) return false if (ext_pack_uint32 != other.ext_pack_uint32) return false if (ext_pack_sint32 != other.ext_pack_sint32) return false if (ext_pack_fixed32 != other.ext_pack_fixed32) return false if (ext_pack_sfixed32 != other.ext_pack_sfixed32) return false if (ext_pack_int64 != other.ext_pack_int64) return false if (ext_pack_uint64 != other.ext_pack_uint64) return false if (ext_pack_sint64 != other.ext_pack_sint64) return false if (ext_pack_fixed64 != other.ext_pack_fixed64) return false if (ext_pack_sfixed64 != other.ext_pack_sfixed64) return false if (ext_pack_bool != other.ext_pack_bool) return false if (ext_pack_float != other.ext_pack_float) return false if (ext_pack_double != other.ext_pack_double) return false if (ext_pack_nested_enum != other.ext_pack_nested_enum) return false return true } public override fun hashCode(): Int { var result = super.hashCode if (result == 0) { result = unknownFields.hashCode() result = result * 37 + (opt_int32?.hashCode() ?: 0) result = result * 37 + (opt_uint32?.hashCode() ?: 0) result = result * 37 + (opt_sint32?.hashCode() ?: 0) result = result * 37 + (opt_fixed32?.hashCode() ?: 0) result = result * 37 + (opt_sfixed32?.hashCode() ?: 0) result = result * 37 + (opt_int64?.hashCode() ?: 0) result = result * 37 + (opt_uint64?.hashCode() ?: 0) result = result * 37 + (opt_sint64?.hashCode() ?: 0) result = result * 37 + (opt_fixed64?.hashCode() ?: 0) result = result * 37 + (opt_sfixed64?.hashCode() ?: 0) result = result * 37 + (opt_bool?.hashCode() ?: 0) result = result * 37 + (opt_float?.hashCode() ?: 0) result = result * 37 + (opt_double?.hashCode() ?: 0) result = result * 37 + (opt_string?.hashCode() ?: 0) result = result * 37 + (opt_bytes?.hashCode() ?: 0) result = result * 37 + (opt_nested_enum?.hashCode() ?: 0) result = result * 37 + (opt_nested_message?.hashCode() ?: 0) result = result * 37 + req_int32.hashCode() result = result * 37 + req_uint32.hashCode() result = result * 37 + req_sint32.hashCode() result = result * 37 + req_fixed32.hashCode() result = result * 37 + req_sfixed32.hashCode() result = result * 37 + req_int64.hashCode() result = result * 37 + req_uint64.hashCode() result = result * 37 + req_sint64.hashCode() result = result * 37 + req_fixed64.hashCode() result = result * 37 + req_sfixed64.hashCode() result = result * 37 + req_bool.hashCode() result = result * 37 + req_float.hashCode() result = result * 37 + req_double.hashCode() result = result * 37 + req_string.hashCode() result = result * 37 + req_bytes.hashCode() result = result * 37 + req_nested_enum.hashCode() result = result * 37 + req_nested_message.hashCode() result = result * 37 + rep_int32.hashCode() result = result * 37 + rep_uint32.hashCode() result = result * 37 + rep_sint32.hashCode() result = result * 37 + rep_fixed32.hashCode() result = result * 37 + rep_sfixed32.hashCode() result = result * 37 + rep_int64.hashCode() result = result * 37 + rep_uint64.hashCode() result = result * 37 + rep_sint64.hashCode() result = result * 37 + rep_fixed64.hashCode() result = result * 37 + rep_sfixed64.hashCode() result = result * 37 + rep_bool.hashCode() result = result * 37 + rep_float.hashCode() result = result * 37 + rep_double.hashCode() result = result * 37 + rep_string.hashCode() result = result * 37 + rep_bytes.hashCode() result = result * 37 + rep_nested_enum.hashCode() result = result * 37 + rep_nested_message.hashCode() result = result * 37 + pack_int32.hashCode() result = result * 37 + pack_uint32.hashCode() result = result * 37 + pack_sint32.hashCode() result = result * 37 + pack_fixed32.hashCode() result = result * 37 + pack_sfixed32.hashCode() result = result * 37 + pack_int64.hashCode() result = result * 37 + pack_uint64.hashCode() result = result * 37 + pack_sint64.hashCode() result = result * 37 + pack_fixed64.hashCode() result = result * 37 + pack_sfixed64.hashCode() result = result * 37 + pack_bool.hashCode() result = result * 37 + pack_float.hashCode() result = result * 37 + pack_double.hashCode() result = result * 37 + pack_nested_enum.hashCode() result = result * 37 + (default_int32?.hashCode() ?: 0) result = result * 37 + (default_uint32?.hashCode() ?: 0) result = result * 37 + (default_sint32?.hashCode() ?: 0) result = result * 37 + (default_fixed32?.hashCode() ?: 0) result = result * 37 + (default_sfixed32?.hashCode() ?: 0) result = result * 37 + (default_int64?.hashCode() ?: 0) result = result * 37 + (default_uint64?.hashCode() ?: 0) result = result * 37 + (default_sint64?.hashCode() ?: 0) result = result * 37 + (default_fixed64?.hashCode() ?: 0) result = result * 37 + (default_sfixed64?.hashCode() ?: 0) result = result * 37 + (default_bool?.hashCode() ?: 0) result = result * 37 + (default_float?.hashCode() ?: 0) result = result * 37 + (default_double?.hashCode() ?: 0) result = result * 37 + (default_string?.hashCode() ?: 0) result = result * 37 + (default_bytes?.hashCode() ?: 0) result = result * 37 + (default_nested_enum?.hashCode() ?: 0) result = result * 37 + map_int32_int32.hashCode() result = result * 37 + map_string_string.hashCode() result = result * 37 + map_string_message.hashCode() result = result * 37 + map_string_enum.hashCode() result = result * 37 + (oneof_string?.hashCode() ?: 0) result = result * 37 + (oneof_int32?.hashCode() ?: 0) result = result * 37 + (oneof_nested_message?.hashCode() ?: 0) result = result * 37 + (ext_opt_int32?.hashCode() ?: 0) result = result * 37 + (ext_opt_uint32?.hashCode() ?: 0) result = result * 37 + (ext_opt_sint32?.hashCode() ?: 0) result = result * 37 + (ext_opt_fixed32?.hashCode() ?: 0) result = result * 37 + (ext_opt_sfixed32?.hashCode() ?: 0) result = result * 37 + (ext_opt_int64?.hashCode() ?: 0) result = result * 37 + (ext_opt_uint64?.hashCode() ?: 0) result = result * 37 + (ext_opt_sint64?.hashCode() ?: 0) result = result * 37 + (ext_opt_fixed64?.hashCode() ?: 0) result = result * 37 + (ext_opt_sfixed64?.hashCode() ?: 0) result = result * 37 + (ext_opt_bool?.hashCode() ?: 0) result = result * 37 + (ext_opt_float?.hashCode() ?: 0) result = result * 37 + (ext_opt_double?.hashCode() ?: 0) result = result * 37 + (ext_opt_string?.hashCode() ?: 0) result = result * 37 + (ext_opt_bytes?.hashCode() ?: 0) result = result * 37 + (ext_opt_nested_enum?.hashCode() ?: 0) result = result * 37 + (ext_opt_nested_message?.hashCode() ?: 0) result = result * 37 + ext_rep_int32.hashCode() result = result * 37 + ext_rep_uint32.hashCode() result = result * 37 + ext_rep_sint32.hashCode() result = result * 37 + ext_rep_fixed32.hashCode() result = result * 37 + ext_rep_sfixed32.hashCode() result = result * 37 + ext_rep_int64.hashCode() result = result * 37 + ext_rep_uint64.hashCode() result = result * 37 + ext_rep_sint64.hashCode() result = result * 37 + ext_rep_fixed64.hashCode() result = result * 37 + ext_rep_sfixed64.hashCode() result = result * 37 + ext_rep_bool.hashCode() result = result * 37 + ext_rep_float.hashCode() result = result * 37 + ext_rep_double.hashCode() result = result * 37 + ext_rep_string.hashCode() result = result * 37 + ext_rep_bytes.hashCode() result = result * 37 + ext_rep_nested_enum.hashCode() result = result * 37 + ext_rep_nested_message.hashCode() result = result * 37 + ext_pack_int32.hashCode() result = result * 37 + ext_pack_uint32.hashCode() result = result * 37 + ext_pack_sint32.hashCode() result = result * 37 + ext_pack_fixed32.hashCode() result = result * 37 + ext_pack_sfixed32.hashCode() result = result * 37 + ext_pack_int64.hashCode() result = result * 37 + ext_pack_uint64.hashCode() result = result * 37 + ext_pack_sint64.hashCode() result = result * 37 + ext_pack_fixed64.hashCode() result = result * 37 + ext_pack_sfixed64.hashCode() result = result * 37 + ext_pack_bool.hashCode() result = result * 37 + ext_pack_float.hashCode() result = result * 37 + ext_pack_double.hashCode() result = result * 37 + ext_pack_nested_enum.hashCode() super.hashCode = result } return result } public override fun toString(): String { val result = mutableListOf<String>() if (opt_int32 != null) result += """opt_int32=$opt_int32""" if (opt_uint32 != null) result += """opt_uint32=$opt_uint32""" if (opt_sint32 != null) result += """opt_sint32=$opt_sint32""" if (opt_fixed32 != null) result += """opt_fixed32=$opt_fixed32""" if (opt_sfixed32 != null) result += """opt_sfixed32=$opt_sfixed32""" if (opt_int64 != null) result += """opt_int64=$opt_int64""" if (opt_uint64 != null) result += """opt_uint64=$opt_uint64""" if (opt_sint64 != null) result += """opt_sint64=$opt_sint64""" if (opt_fixed64 != null) result += """opt_fixed64=$opt_fixed64""" if (opt_sfixed64 != null) result += """opt_sfixed64=$opt_sfixed64""" if (opt_bool != null) result += """opt_bool=$opt_bool""" if (opt_float != null) result += """opt_float=$opt_float""" if (opt_double != null) result += """opt_double=$opt_double""" if (opt_string != null) result += """opt_string=${sanitize(opt_string)}""" if (opt_bytes != null) result += """opt_bytes=$opt_bytes""" if (opt_nested_enum != null) result += """opt_nested_enum=$opt_nested_enum""" if (opt_nested_message != null) result += """opt_nested_message=$opt_nested_message""" result += """req_int32=$req_int32""" result += """req_uint32=$req_uint32""" result += """req_sint32=$req_sint32""" result += """req_fixed32=$req_fixed32""" result += """req_sfixed32=$req_sfixed32""" result += """req_int64=$req_int64""" result += """req_uint64=$req_uint64""" result += """req_sint64=$req_sint64""" result += """req_fixed64=$req_fixed64""" result += """req_sfixed64=$req_sfixed64""" result += """req_bool=$req_bool""" result += """req_float=$req_float""" result += """req_double=$req_double""" result += """req_string=${sanitize(req_string)}""" result += """req_bytes=$req_bytes""" result += """req_nested_enum=$req_nested_enum""" result += """req_nested_message=$req_nested_message""" if (rep_int32.isNotEmpty()) result += """rep_int32=$rep_int32""" if (rep_uint32.isNotEmpty()) result += """rep_uint32=$rep_uint32""" if (rep_sint32.isNotEmpty()) result += """rep_sint32=$rep_sint32""" if (rep_fixed32.isNotEmpty()) result += """rep_fixed32=$rep_fixed32""" if (rep_sfixed32.isNotEmpty()) result += """rep_sfixed32=$rep_sfixed32""" if (rep_int64.isNotEmpty()) result += """rep_int64=$rep_int64""" if (rep_uint64.isNotEmpty()) result += """rep_uint64=$rep_uint64""" if (rep_sint64.isNotEmpty()) result += """rep_sint64=$rep_sint64""" if (rep_fixed64.isNotEmpty()) result += """rep_fixed64=$rep_fixed64""" if (rep_sfixed64.isNotEmpty()) result += """rep_sfixed64=$rep_sfixed64""" if (rep_bool.isNotEmpty()) result += """rep_bool=$rep_bool""" if (rep_float.isNotEmpty()) result += """rep_float=$rep_float""" if (rep_double.isNotEmpty()) result += """rep_double=$rep_double""" if (rep_string.isNotEmpty()) result += """rep_string=${sanitize(rep_string)}""" if (rep_bytes.isNotEmpty()) result += """rep_bytes=$rep_bytes""" if (rep_nested_enum.isNotEmpty()) result += """rep_nested_enum=$rep_nested_enum""" if (rep_nested_message.isNotEmpty()) result += """rep_nested_message=$rep_nested_message""" if (pack_int32.isNotEmpty()) result += """pack_int32=$pack_int32""" if (pack_uint32.isNotEmpty()) result += """pack_uint32=$pack_uint32""" if (pack_sint32.isNotEmpty()) result += """pack_sint32=$pack_sint32""" if (pack_fixed32.isNotEmpty()) result += """pack_fixed32=$pack_fixed32""" if (pack_sfixed32.isNotEmpty()) result += """pack_sfixed32=$pack_sfixed32""" if (pack_int64.isNotEmpty()) result += """pack_int64=$pack_int64""" if (pack_uint64.isNotEmpty()) result += """pack_uint64=$pack_uint64""" if (pack_sint64.isNotEmpty()) result += """pack_sint64=$pack_sint64""" if (pack_fixed64.isNotEmpty()) result += """pack_fixed64=$pack_fixed64""" if (pack_sfixed64.isNotEmpty()) result += """pack_sfixed64=$pack_sfixed64""" if (pack_bool.isNotEmpty()) result += """pack_bool=$pack_bool""" if (pack_float.isNotEmpty()) result += """pack_float=$pack_float""" if (pack_double.isNotEmpty()) result += """pack_double=$pack_double""" if (pack_nested_enum.isNotEmpty()) result += """pack_nested_enum=$pack_nested_enum""" if (default_int32 != null) result += """default_int32=$default_int32""" if (default_uint32 != null) result += """default_uint32=$default_uint32""" if (default_sint32 != null) result += """default_sint32=$default_sint32""" if (default_fixed32 != null) result += """default_fixed32=$default_fixed32""" if (default_sfixed32 != null) result += """default_sfixed32=$default_sfixed32""" if (default_int64 != null) result += """default_int64=$default_int64""" if (default_uint64 != null) result += """default_uint64=$default_uint64""" if (default_sint64 != null) result += """default_sint64=$default_sint64""" if (default_fixed64 != null) result += """default_fixed64=$default_fixed64""" if (default_sfixed64 != null) result += """default_sfixed64=$default_sfixed64""" if (default_bool != null) result += """default_bool=$default_bool""" if (default_float != null) result += """default_float=$default_float""" if (default_double != null) result += """default_double=$default_double""" if (default_string != null) result += """default_string=${sanitize(default_string)}""" if (default_bytes != null) result += """default_bytes=$default_bytes""" if (default_nested_enum != null) result += """default_nested_enum=$default_nested_enum""" if (map_int32_int32.isNotEmpty()) result += """map_int32_int32=$map_int32_int32""" if (map_string_string.isNotEmpty()) result += """map_string_string=$map_string_string""" if (map_string_message.isNotEmpty()) result += """map_string_message=$map_string_message""" if (map_string_enum.isNotEmpty()) result += """map_string_enum=$map_string_enum""" if (oneof_string != null) result += """oneof_string=${sanitize(oneof_string)}""" if (oneof_int32 != null) result += """oneof_int32=$oneof_int32""" if (oneof_nested_message != null) result += """oneof_nested_message=$oneof_nested_message""" if (ext_opt_int32 != null) result += """ext_opt_int32=$ext_opt_int32""" if (ext_opt_uint32 != null) result += """ext_opt_uint32=$ext_opt_uint32""" if (ext_opt_sint32 != null) result += """ext_opt_sint32=$ext_opt_sint32""" if (ext_opt_fixed32 != null) result += """ext_opt_fixed32=$ext_opt_fixed32""" if (ext_opt_sfixed32 != null) result += """ext_opt_sfixed32=$ext_opt_sfixed32""" if (ext_opt_int64 != null) result += """ext_opt_int64=$ext_opt_int64""" if (ext_opt_uint64 != null) result += """ext_opt_uint64=$ext_opt_uint64""" if (ext_opt_sint64 != null) result += """ext_opt_sint64=$ext_opt_sint64""" if (ext_opt_fixed64 != null) result += """ext_opt_fixed64=$ext_opt_fixed64""" if (ext_opt_sfixed64 != null) result += """ext_opt_sfixed64=$ext_opt_sfixed64""" if (ext_opt_bool != null) result += """ext_opt_bool=$ext_opt_bool""" if (ext_opt_float != null) result += """ext_opt_float=$ext_opt_float""" if (ext_opt_double != null) result += """ext_opt_double=$ext_opt_double""" if (ext_opt_string != null) result += """ext_opt_string=${sanitize(ext_opt_string)}""" if (ext_opt_bytes != null) result += """ext_opt_bytes=$ext_opt_bytes""" if (ext_opt_nested_enum != null) result += """ext_opt_nested_enum=$ext_opt_nested_enum""" if (ext_opt_nested_message != null) result += """ext_opt_nested_message=$ext_opt_nested_message""" if (ext_rep_int32.isNotEmpty()) result += """ext_rep_int32=$ext_rep_int32""" if (ext_rep_uint32.isNotEmpty()) result += """ext_rep_uint32=$ext_rep_uint32""" if (ext_rep_sint32.isNotEmpty()) result += """ext_rep_sint32=$ext_rep_sint32""" if (ext_rep_fixed32.isNotEmpty()) result += """ext_rep_fixed32=$ext_rep_fixed32""" if (ext_rep_sfixed32.isNotEmpty()) result += """ext_rep_sfixed32=$ext_rep_sfixed32""" if (ext_rep_int64.isNotEmpty()) result += """ext_rep_int64=$ext_rep_int64""" if (ext_rep_uint64.isNotEmpty()) result += """ext_rep_uint64=$ext_rep_uint64""" if (ext_rep_sint64.isNotEmpty()) result += """ext_rep_sint64=$ext_rep_sint64""" if (ext_rep_fixed64.isNotEmpty()) result += """ext_rep_fixed64=$ext_rep_fixed64""" if (ext_rep_sfixed64.isNotEmpty()) result += """ext_rep_sfixed64=$ext_rep_sfixed64""" if (ext_rep_bool.isNotEmpty()) result += """ext_rep_bool=$ext_rep_bool""" if (ext_rep_float.isNotEmpty()) result += """ext_rep_float=$ext_rep_float""" if (ext_rep_double.isNotEmpty()) result += """ext_rep_double=$ext_rep_double""" if (ext_rep_string.isNotEmpty()) result += """ext_rep_string=${sanitize(ext_rep_string)}""" if (ext_rep_bytes.isNotEmpty()) result += """ext_rep_bytes=$ext_rep_bytes""" if (ext_rep_nested_enum.isNotEmpty()) result += """ext_rep_nested_enum=$ext_rep_nested_enum""" if (ext_rep_nested_message.isNotEmpty()) result += """ext_rep_nested_message=$ext_rep_nested_message""" if (ext_pack_int32.isNotEmpty()) result += """ext_pack_int32=$ext_pack_int32""" if (ext_pack_uint32.isNotEmpty()) result += """ext_pack_uint32=$ext_pack_uint32""" if (ext_pack_sint32.isNotEmpty()) result += """ext_pack_sint32=$ext_pack_sint32""" if (ext_pack_fixed32.isNotEmpty()) result += """ext_pack_fixed32=$ext_pack_fixed32""" if (ext_pack_sfixed32.isNotEmpty()) result += """ext_pack_sfixed32=$ext_pack_sfixed32""" if (ext_pack_int64.isNotEmpty()) result += """ext_pack_int64=$ext_pack_int64""" if (ext_pack_uint64.isNotEmpty()) result += """ext_pack_uint64=$ext_pack_uint64""" if (ext_pack_sint64.isNotEmpty()) result += """ext_pack_sint64=$ext_pack_sint64""" if (ext_pack_fixed64.isNotEmpty()) result += """ext_pack_fixed64=$ext_pack_fixed64""" if (ext_pack_sfixed64.isNotEmpty()) result += """ext_pack_sfixed64=$ext_pack_sfixed64""" if (ext_pack_bool.isNotEmpty()) result += """ext_pack_bool=$ext_pack_bool""" if (ext_pack_float.isNotEmpty()) result += """ext_pack_float=$ext_pack_float""" if (ext_pack_double.isNotEmpty()) result += """ext_pack_double=$ext_pack_double""" if (ext_pack_nested_enum.isNotEmpty()) result += """ext_pack_nested_enum=$ext_pack_nested_enum""" return result.joinToString(prefix = "AllTypes{", separator = ", ", postfix = "}") } public fun copy( opt_int32: Int? = this.opt_int32, opt_uint32: Int? = this.opt_uint32, opt_sint32: Int? = this.opt_sint32, opt_fixed32: Int? = this.opt_fixed32, opt_sfixed32: Int? = this.opt_sfixed32, opt_int64: Long? = this.opt_int64, opt_uint64: Long? = this.opt_uint64, opt_sint64: Long? = this.opt_sint64, opt_fixed64: Long? = this.opt_fixed64, opt_sfixed64: Long? = this.opt_sfixed64, opt_bool: Boolean? = this.opt_bool, opt_float: Float? = this.opt_float, opt_double: Double? = this.opt_double, opt_string: String? = this.opt_string, opt_bytes: ByteString? = this.opt_bytes, opt_nested_enum: NestedEnum? = this.opt_nested_enum, opt_nested_message: NestedMessage? = this.opt_nested_message, req_int32: Int = this.req_int32, req_uint32: Int = this.req_uint32, req_sint32: Int = this.req_sint32, req_fixed32: Int = this.req_fixed32, req_sfixed32: Int = this.req_sfixed32, req_int64: Long = this.req_int64, req_uint64: Long = this.req_uint64, req_sint64: Long = this.req_sint64, req_fixed64: Long = this.req_fixed64, req_sfixed64: Long = this.req_sfixed64, req_bool: Boolean = this.req_bool, req_float: Float = this.req_float, req_double: Double = this.req_double, req_string: String = this.req_string, req_bytes: ByteString = this.req_bytes, req_nested_enum: NestedEnum = this.req_nested_enum, req_nested_message: NestedMessage = this.req_nested_message, rep_int32: List<Int> = this.rep_int32, rep_uint32: List<Int> = this.rep_uint32, rep_sint32: List<Int> = this.rep_sint32, rep_fixed32: List<Int> = this.rep_fixed32, rep_sfixed32: List<Int> = this.rep_sfixed32, rep_int64: List<Long> = this.rep_int64, rep_uint64: List<Long> = this.rep_uint64, rep_sint64: List<Long> = this.rep_sint64, rep_fixed64: List<Long> = this.rep_fixed64, rep_sfixed64: List<Long> = this.rep_sfixed64, rep_bool: List<Boolean> = this.rep_bool, rep_float: List<Float> = this.rep_float, rep_double: List<Double> = this.rep_double, rep_string: List<String> = this.rep_string, rep_bytes: List<ByteString> = this.rep_bytes, rep_nested_enum: List<NestedEnum> = this.rep_nested_enum, rep_nested_message: List<NestedMessage> = this.rep_nested_message, pack_int32: List<Int> = this.pack_int32, pack_uint32: List<Int> = this.pack_uint32, pack_sint32: List<Int> = this.pack_sint32, pack_fixed32: List<Int> = this.pack_fixed32, pack_sfixed32: List<Int> = this.pack_sfixed32, pack_int64: List<Long> = this.pack_int64, pack_uint64: List<Long> = this.pack_uint64, pack_sint64: List<Long> = this.pack_sint64, pack_fixed64: List<Long> = this.pack_fixed64, pack_sfixed64: List<Long> = this.pack_sfixed64, pack_bool: List<Boolean> = this.pack_bool, pack_float: List<Float> = this.pack_float, pack_double: List<Double> = this.pack_double, pack_nested_enum: List<NestedEnum> = this.pack_nested_enum, default_int32: Int? = this.default_int32, default_uint32: Int? = this.default_uint32, default_sint32: Int? = this.default_sint32, default_fixed32: Int? = this.default_fixed32, default_sfixed32: Int? = this.default_sfixed32, default_int64: Long? = this.default_int64, default_uint64: Long? = this.default_uint64, default_sint64: Long? = this.default_sint64, default_fixed64: Long? = this.default_fixed64, default_sfixed64: Long? = this.default_sfixed64, default_bool: Boolean? = this.default_bool, default_float: Float? = this.default_float, default_double: Double? = this.default_double, default_string: String? = this.default_string, default_bytes: ByteString? = this.default_bytes, default_nested_enum: NestedEnum? = this.default_nested_enum, map_int32_int32: Map<Int, Int> = this.map_int32_int32, map_string_string: Map<String, String> = this.map_string_string, map_string_message: Map<String, NestedMessage> = this.map_string_message, map_string_enum: Map<String, NestedEnum> = this.map_string_enum, oneof_string: String? = this.oneof_string, oneof_int32: Int? = this.oneof_int32, oneof_nested_message: NestedMessage? = this.oneof_nested_message, ext_opt_int32: Int? = this.ext_opt_int32, ext_opt_uint32: Int? = this.ext_opt_uint32, ext_opt_sint32: Int? = this.ext_opt_sint32, ext_opt_fixed32: Int? = this.ext_opt_fixed32, ext_opt_sfixed32: Int? = this.ext_opt_sfixed32, ext_opt_int64: Long? = this.ext_opt_int64, ext_opt_uint64: Long? = this.ext_opt_uint64, ext_opt_sint64: Long? = this.ext_opt_sint64, ext_opt_fixed64: Long? = this.ext_opt_fixed64, ext_opt_sfixed64: Long? = this.ext_opt_sfixed64, ext_opt_bool: Boolean? = this.ext_opt_bool, ext_opt_float: Float? = this.ext_opt_float, ext_opt_double: Double? = this.ext_opt_double, ext_opt_string: String? = this.ext_opt_string, ext_opt_bytes: ByteString? = this.ext_opt_bytes, ext_opt_nested_enum: NestedEnum? = this.ext_opt_nested_enum, ext_opt_nested_message: NestedMessage? = this.ext_opt_nested_message, ext_rep_int32: List<Int> = this.ext_rep_int32, ext_rep_uint32: List<Int> = this.ext_rep_uint32, ext_rep_sint32: List<Int> = this.ext_rep_sint32, ext_rep_fixed32: List<Int> = this.ext_rep_fixed32, ext_rep_sfixed32: List<Int> = this.ext_rep_sfixed32, ext_rep_int64: List<Long> = this.ext_rep_int64, ext_rep_uint64: List<Long> = this.ext_rep_uint64, ext_rep_sint64: List<Long> = this.ext_rep_sint64, ext_rep_fixed64: List<Long> = this.ext_rep_fixed64, ext_rep_sfixed64: List<Long> = this.ext_rep_sfixed64, ext_rep_bool: List<Boolean> = this.ext_rep_bool, ext_rep_float: List<Float> = this.ext_rep_float, ext_rep_double: List<Double> = this.ext_rep_double, ext_rep_string: List<String> = this.ext_rep_string, ext_rep_bytes: List<ByteString> = this.ext_rep_bytes, ext_rep_nested_enum: List<NestedEnum> = this.ext_rep_nested_enum, ext_rep_nested_message: List<NestedMessage> = this.ext_rep_nested_message, ext_pack_int32: List<Int> = this.ext_pack_int32, ext_pack_uint32: List<Int> = this.ext_pack_uint32, ext_pack_sint32: List<Int> = this.ext_pack_sint32, ext_pack_fixed32: List<Int> = this.ext_pack_fixed32, ext_pack_sfixed32: List<Int> = this.ext_pack_sfixed32, ext_pack_int64: List<Long> = this.ext_pack_int64, ext_pack_uint64: List<Long> = this.ext_pack_uint64, ext_pack_sint64: List<Long> = this.ext_pack_sint64, ext_pack_fixed64: List<Long> = this.ext_pack_fixed64, ext_pack_sfixed64: List<Long> = this.ext_pack_sfixed64, ext_pack_bool: List<Boolean> = this.ext_pack_bool, ext_pack_float: List<Float> = this.ext_pack_float, ext_pack_double: List<Double> = this.ext_pack_double, ext_pack_nested_enum: List<NestedEnum> = this.ext_pack_nested_enum, unknownFields: ByteString = this.unknownFields, ): AllTypes = AllTypes(opt_int32, opt_uint32, opt_sint32, opt_fixed32, opt_sfixed32, opt_int64, opt_uint64, opt_sint64, opt_fixed64, opt_sfixed64, opt_bool, opt_float, opt_double, opt_string, opt_bytes, opt_nested_enum, opt_nested_message, req_int32, req_uint32, req_sint32, req_fixed32, req_sfixed32, req_int64, req_uint64, req_sint64, req_fixed64, req_sfixed64, req_bool, req_float, req_double, req_string, req_bytes, req_nested_enum, req_nested_message, rep_int32, rep_uint32, rep_sint32, rep_fixed32, rep_sfixed32, rep_int64, rep_uint64, rep_sint64, rep_fixed64, rep_sfixed64, rep_bool, rep_float, rep_double, rep_string, rep_bytes, rep_nested_enum, rep_nested_message, pack_int32, pack_uint32, pack_sint32, pack_fixed32, pack_sfixed32, pack_int64, pack_uint64, pack_sint64, pack_fixed64, pack_sfixed64, pack_bool, pack_float, pack_double, pack_nested_enum, default_int32, default_uint32, default_sint32, default_fixed32, default_sfixed32, default_int64, default_uint64, default_sint64, default_fixed64, default_sfixed64, default_bool, default_float, default_double, default_string, default_bytes, default_nested_enum, map_int32_int32, map_string_string, map_string_message, map_string_enum, oneof_string, oneof_int32, oneof_nested_message, ext_opt_int32, ext_opt_uint32, ext_opt_sint32, ext_opt_fixed32, ext_opt_sfixed32, ext_opt_int64, ext_opt_uint64, ext_opt_sint64, ext_opt_fixed64, ext_opt_sfixed64, ext_opt_bool, ext_opt_float, ext_opt_double, ext_opt_string, ext_opt_bytes, ext_opt_nested_enum, ext_opt_nested_message, ext_rep_int32, ext_rep_uint32, ext_rep_sint32, ext_rep_fixed32, ext_rep_sfixed32, ext_rep_int64, ext_rep_uint64, ext_rep_sint64, ext_rep_fixed64, ext_rep_sfixed64, ext_rep_bool, ext_rep_float, ext_rep_double, ext_rep_string, ext_rep_bytes, ext_rep_nested_enum, ext_rep_nested_message, ext_pack_int32, ext_pack_uint32, ext_pack_sint32, ext_pack_fixed32, ext_pack_sfixed32, ext_pack_int64, ext_pack_uint64, ext_pack_sint64, ext_pack_fixed64, ext_pack_sfixed64, ext_pack_bool, ext_pack_float, ext_pack_double, ext_pack_nested_enum, unknownFields) public class Builder : Message.Builder<AllTypes, Builder>() { @JvmField public var opt_int32: Int? = null @JvmField public var opt_uint32: Int? = null @JvmField public var opt_sint32: Int? = null @JvmField public var opt_fixed32: Int? = null @JvmField public var opt_sfixed32: Int? = null @JvmField public var opt_int64: Long? = null @JvmField public var opt_uint64: Long? = null @JvmField public var opt_sint64: Long? = null @JvmField public var opt_fixed64: Long? = null @JvmField public var opt_sfixed64: Long? = null @JvmField public var opt_bool: Boolean? = null @JvmField public var opt_float: Float? = null @JvmField public var opt_double: Double? = null @JvmField public var opt_string: String? = null @JvmField public var opt_bytes: ByteString? = null @JvmField public var opt_nested_enum: NestedEnum? = null @JvmField public var opt_nested_message: NestedMessage? = null @JvmField public var req_int32: Int? = null @JvmField public var req_uint32: Int? = null @JvmField public var req_sint32: Int? = null @JvmField public var req_fixed32: Int? = null @JvmField public var req_sfixed32: Int? = null @JvmField public var req_int64: Long? = null @JvmField public var req_uint64: Long? = null @JvmField public var req_sint64: Long? = null @JvmField public var req_fixed64: Long? = null @JvmField public var req_sfixed64: Long? = null @JvmField public var req_bool: Boolean? = null @JvmField public var req_float: Float? = null @JvmField public var req_double: Double? = null @JvmField public var req_string: String? = null @JvmField public var req_bytes: ByteString? = null @JvmField public var req_nested_enum: NestedEnum? = null @JvmField public var req_nested_message: NestedMessage? = null @JvmField public var rep_int32: List<Int> = emptyList() @JvmField public var rep_uint32: List<Int> = emptyList() @JvmField public var rep_sint32: List<Int> = emptyList() @JvmField public var rep_fixed32: List<Int> = emptyList() @JvmField public var rep_sfixed32: List<Int> = emptyList() @JvmField public var rep_int64: List<Long> = emptyList() @JvmField public var rep_uint64: List<Long> = emptyList() @JvmField public var rep_sint64: List<Long> = emptyList() @JvmField public var rep_fixed64: List<Long> = emptyList() @JvmField public var rep_sfixed64: List<Long> = emptyList() @JvmField public var rep_bool: List<Boolean> = emptyList() @JvmField public var rep_float: List<Float> = emptyList() @JvmField public var rep_double: List<Double> = emptyList() @JvmField public var rep_string: List<String> = emptyList() @JvmField public var rep_bytes: List<ByteString> = emptyList() @JvmField public var rep_nested_enum: List<NestedEnum> = emptyList() @JvmField public var rep_nested_message: List<NestedMessage> = emptyList() @JvmField public var pack_int32: List<Int> = emptyList() @JvmField public var pack_uint32: List<Int> = emptyList() @JvmField public var pack_sint32: List<Int> = emptyList() @JvmField public var pack_fixed32: List<Int> = emptyList() @JvmField public var pack_sfixed32: List<Int> = emptyList() @JvmField public var pack_int64: List<Long> = emptyList() @JvmField public var pack_uint64: List<Long> = emptyList() @JvmField public var pack_sint64: List<Long> = emptyList() @JvmField public var pack_fixed64: List<Long> = emptyList() @JvmField public var pack_sfixed64: List<Long> = emptyList() @JvmField public var pack_bool: List<Boolean> = emptyList() @JvmField public var pack_float: List<Float> = emptyList() @JvmField public var pack_double: List<Double> = emptyList() @JvmField public var pack_nested_enum: List<NestedEnum> = emptyList() @JvmField public var default_int32: Int? = null @JvmField public var default_uint32: Int? = null @JvmField public var default_sint32: Int? = null @JvmField public var default_fixed32: Int? = null @JvmField public var default_sfixed32: Int? = null @JvmField public var default_int64: Long? = null @JvmField public var default_uint64: Long? = null @JvmField public var default_sint64: Long? = null @JvmField public var default_fixed64: Long? = null @JvmField public var default_sfixed64: Long? = null @JvmField public var default_bool: Boolean? = null @JvmField public var default_float: Float? = null @JvmField public var default_double: Double? = null @JvmField public var default_string: String? = null @JvmField public var default_bytes: ByteString? = null @JvmField public var default_nested_enum: NestedEnum? = null @JvmField public var map_int32_int32: Map<Int, Int> = emptyMap() @JvmField public var map_string_string: Map<String, String> = emptyMap() @JvmField public var map_string_message: Map<String, NestedMessage> = emptyMap() @JvmField public var map_string_enum: Map<String, NestedEnum> = emptyMap() @JvmField public var oneof_string: String? = null @JvmField public var oneof_int32: Int? = null @JvmField public var oneof_nested_message: NestedMessage? = null @JvmField public var ext_opt_int32: Int? = null @JvmField public var ext_opt_uint32: Int? = null @JvmField public var ext_opt_sint32: Int? = null @JvmField public var ext_opt_fixed32: Int? = null @JvmField public var ext_opt_sfixed32: Int? = null @JvmField public var ext_opt_int64: Long? = null @JvmField public var ext_opt_uint64: Long? = null @JvmField public var ext_opt_sint64: Long? = null @JvmField public var ext_opt_fixed64: Long? = null @JvmField public var ext_opt_sfixed64: Long? = null @JvmField public var ext_opt_bool: Boolean? = null @JvmField public var ext_opt_float: Float? = null @JvmField public var ext_opt_double: Double? = null @JvmField public var ext_opt_string: String? = null @JvmField public var ext_opt_bytes: ByteString? = null @JvmField public var ext_opt_nested_enum: NestedEnum? = null @JvmField public var ext_opt_nested_message: NestedMessage? = null @JvmField public var ext_rep_int32: List<Int> = emptyList() @JvmField public var ext_rep_uint32: List<Int> = emptyList() @JvmField public var ext_rep_sint32: List<Int> = emptyList() @JvmField public var ext_rep_fixed32: List<Int> = emptyList() @JvmField public var ext_rep_sfixed32: List<Int> = emptyList() @JvmField public var ext_rep_int64: List<Long> = emptyList() @JvmField public var ext_rep_uint64: List<Long> = emptyList() @JvmField public var ext_rep_sint64: List<Long> = emptyList() @JvmField public var ext_rep_fixed64: List<Long> = emptyList() @JvmField public var ext_rep_sfixed64: List<Long> = emptyList() @JvmField public var ext_rep_bool: List<Boolean> = emptyList() @JvmField public var ext_rep_float: List<Float> = emptyList() @JvmField public var ext_rep_double: List<Double> = emptyList() @JvmField public var ext_rep_string: List<String> = emptyList() @JvmField public var ext_rep_bytes: List<ByteString> = emptyList() @JvmField public var ext_rep_nested_enum: List<NestedEnum> = emptyList() @JvmField public var ext_rep_nested_message: List<NestedMessage> = emptyList() @JvmField public var ext_pack_int32: List<Int> = emptyList() @JvmField public var ext_pack_uint32: List<Int> = emptyList() @JvmField public var ext_pack_sint32: List<Int> = emptyList() @JvmField public var ext_pack_fixed32: List<Int> = emptyList() @JvmField public var ext_pack_sfixed32: List<Int> = emptyList() @JvmField public var ext_pack_int64: List<Long> = emptyList() @JvmField public var ext_pack_uint64: List<Long> = emptyList() @JvmField public var ext_pack_sint64: List<Long> = emptyList() @JvmField public var ext_pack_fixed64: List<Long> = emptyList() @JvmField public var ext_pack_sfixed64: List<Long> = emptyList() @JvmField public var ext_pack_bool: List<Boolean> = emptyList() @JvmField public var ext_pack_float: List<Float> = emptyList() @JvmField public var ext_pack_double: List<Double> = emptyList() @JvmField public var ext_pack_nested_enum: List<NestedEnum> = emptyList() public fun opt_int32(opt_int32: Int?): Builder { this.opt_int32 = opt_int32 return this } public fun opt_uint32(opt_uint32: Int?): Builder { this.opt_uint32 = opt_uint32 return this } public fun opt_sint32(opt_sint32: Int?): Builder { this.opt_sint32 = opt_sint32 return this } public fun opt_fixed32(opt_fixed32: Int?): Builder { this.opt_fixed32 = opt_fixed32 return this } public fun opt_sfixed32(opt_sfixed32: Int?): Builder { this.opt_sfixed32 = opt_sfixed32 return this } public fun opt_int64(opt_int64: Long?): Builder { this.opt_int64 = opt_int64 return this } public fun opt_uint64(opt_uint64: Long?): Builder { this.opt_uint64 = opt_uint64 return this } public fun opt_sint64(opt_sint64: Long?): Builder { this.opt_sint64 = opt_sint64 return this } public fun opt_fixed64(opt_fixed64: Long?): Builder { this.opt_fixed64 = opt_fixed64 return this } public fun opt_sfixed64(opt_sfixed64: Long?): Builder { this.opt_sfixed64 = opt_sfixed64 return this } public fun opt_bool(opt_bool: Boolean?): Builder { this.opt_bool = opt_bool return this } public fun opt_float(opt_float: Float?): Builder { this.opt_float = opt_float return this } public fun opt_double(opt_double: Double?): Builder { this.opt_double = opt_double return this } public fun opt_string(opt_string: String?): Builder { this.opt_string = opt_string return this } public fun opt_bytes(opt_bytes: ByteString?): Builder { this.opt_bytes = opt_bytes return this } public fun opt_nested_enum(opt_nested_enum: NestedEnum?): Builder { this.opt_nested_enum = opt_nested_enum return this } public fun opt_nested_message(opt_nested_message: NestedMessage?): Builder { this.opt_nested_message = opt_nested_message return this } public fun req_int32(req_int32: Int): Builder { this.req_int32 = req_int32 return this } public fun req_uint32(req_uint32: Int): Builder { this.req_uint32 = req_uint32 return this } public fun req_sint32(req_sint32: Int): Builder { this.req_sint32 = req_sint32 return this } public fun req_fixed32(req_fixed32: Int): Builder { this.req_fixed32 = req_fixed32 return this } public fun req_sfixed32(req_sfixed32: Int): Builder { this.req_sfixed32 = req_sfixed32 return this } public fun req_int64(req_int64: Long): Builder { this.req_int64 = req_int64 return this } public fun req_uint64(req_uint64: Long): Builder { this.req_uint64 = req_uint64 return this } public fun req_sint64(req_sint64: Long): Builder { this.req_sint64 = req_sint64 return this } public fun req_fixed64(req_fixed64: Long): Builder { this.req_fixed64 = req_fixed64 return this } public fun req_sfixed64(req_sfixed64: Long): Builder { this.req_sfixed64 = req_sfixed64 return this } public fun req_bool(req_bool: Boolean): Builder { this.req_bool = req_bool return this } public fun req_float(req_float: Float): Builder { this.req_float = req_float return this } public fun req_double(req_double: Double): Builder { this.req_double = req_double return this } public fun req_string(req_string: String): Builder { this.req_string = req_string return this } public fun req_bytes(req_bytes: ByteString): Builder { this.req_bytes = req_bytes return this } public fun req_nested_enum(req_nested_enum: NestedEnum): Builder { this.req_nested_enum = req_nested_enum return this } public fun req_nested_message(req_nested_message: NestedMessage?): Builder { this.req_nested_message = req_nested_message return this } public fun rep_int32(rep_int32: List<Int>): Builder { checkElementsNotNull(rep_int32) this.rep_int32 = rep_int32 return this } public fun rep_uint32(rep_uint32: List<Int>): Builder { checkElementsNotNull(rep_uint32) this.rep_uint32 = rep_uint32 return this } public fun rep_sint32(rep_sint32: List<Int>): Builder { checkElementsNotNull(rep_sint32) this.rep_sint32 = rep_sint32 return this } public fun rep_fixed32(rep_fixed32: List<Int>): Builder { checkElementsNotNull(rep_fixed32) this.rep_fixed32 = rep_fixed32 return this } public fun rep_sfixed32(rep_sfixed32: List<Int>): Builder { checkElementsNotNull(rep_sfixed32) this.rep_sfixed32 = rep_sfixed32 return this } public fun rep_int64(rep_int64: List<Long>): Builder { checkElementsNotNull(rep_int64) this.rep_int64 = rep_int64 return this } public fun rep_uint64(rep_uint64: List<Long>): Builder { checkElementsNotNull(rep_uint64) this.rep_uint64 = rep_uint64 return this } public fun rep_sint64(rep_sint64: List<Long>): Builder { checkElementsNotNull(rep_sint64) this.rep_sint64 = rep_sint64 return this } public fun rep_fixed64(rep_fixed64: List<Long>): Builder { checkElementsNotNull(rep_fixed64) this.rep_fixed64 = rep_fixed64 return this } public fun rep_sfixed64(rep_sfixed64: List<Long>): Builder { checkElementsNotNull(rep_sfixed64) this.rep_sfixed64 = rep_sfixed64 return this } public fun rep_bool(rep_bool: List<Boolean>): Builder { checkElementsNotNull(rep_bool) this.rep_bool = rep_bool return this } public fun rep_float(rep_float: List<Float>): Builder { checkElementsNotNull(rep_float) this.rep_float = rep_float return this } public fun rep_double(rep_double: List<Double>): Builder { checkElementsNotNull(rep_double) this.rep_double = rep_double return this } public fun rep_string(rep_string: List<String>): Builder { checkElementsNotNull(rep_string) this.rep_string = rep_string return this } public fun rep_bytes(rep_bytes: List<ByteString>): Builder { checkElementsNotNull(rep_bytes) this.rep_bytes = rep_bytes return this } public fun rep_nested_enum(rep_nested_enum: List<NestedEnum>): Builder { checkElementsNotNull(rep_nested_enum) this.rep_nested_enum = rep_nested_enum return this } public fun rep_nested_message(rep_nested_message: List<NestedMessage>): Builder { checkElementsNotNull(rep_nested_message) this.rep_nested_message = rep_nested_message return this } public fun pack_int32(pack_int32: List<Int>): Builder { checkElementsNotNull(pack_int32) this.pack_int32 = pack_int32 return this } public fun pack_uint32(pack_uint32: List<Int>): Builder { checkElementsNotNull(pack_uint32) this.pack_uint32 = pack_uint32 return this } public fun pack_sint32(pack_sint32: List<Int>): Builder { checkElementsNotNull(pack_sint32) this.pack_sint32 = pack_sint32 return this } public fun pack_fixed32(pack_fixed32: List<Int>): Builder { checkElementsNotNull(pack_fixed32) this.pack_fixed32 = pack_fixed32 return this } public fun pack_sfixed32(pack_sfixed32: List<Int>): Builder { checkElementsNotNull(pack_sfixed32) this.pack_sfixed32 = pack_sfixed32 return this } public fun pack_int64(pack_int64: List<Long>): Builder { checkElementsNotNull(pack_int64) this.pack_int64 = pack_int64 return this } public fun pack_uint64(pack_uint64: List<Long>): Builder { checkElementsNotNull(pack_uint64) this.pack_uint64 = pack_uint64 return this } public fun pack_sint64(pack_sint64: List<Long>): Builder { checkElementsNotNull(pack_sint64) this.pack_sint64 = pack_sint64 return this } public fun pack_fixed64(pack_fixed64: List<Long>): Builder { checkElementsNotNull(pack_fixed64) this.pack_fixed64 = pack_fixed64 return this } public fun pack_sfixed64(pack_sfixed64: List<Long>): Builder { checkElementsNotNull(pack_sfixed64) this.pack_sfixed64 = pack_sfixed64 return this } public fun pack_bool(pack_bool: List<Boolean>): Builder { checkElementsNotNull(pack_bool) this.pack_bool = pack_bool return this } public fun pack_float(pack_float: List<Float>): Builder { checkElementsNotNull(pack_float) this.pack_float = pack_float return this } public fun pack_double(pack_double: List<Double>): Builder { checkElementsNotNull(pack_double) this.pack_double = pack_double return this } public fun pack_nested_enum(pack_nested_enum: List<NestedEnum>): Builder { checkElementsNotNull(pack_nested_enum) this.pack_nested_enum = pack_nested_enum return this } public fun default_int32(default_int32: Int?): Builder { this.default_int32 = default_int32 return this } public fun default_uint32(default_uint32: Int?): Builder { this.default_uint32 = default_uint32 return this } public fun default_sint32(default_sint32: Int?): Builder { this.default_sint32 = default_sint32 return this } public fun default_fixed32(default_fixed32: Int?): Builder { this.default_fixed32 = default_fixed32 return this } public fun default_sfixed32(default_sfixed32: Int?): Builder { this.default_sfixed32 = default_sfixed32 return this } public fun default_int64(default_int64: Long?): Builder { this.default_int64 = default_int64 return this } public fun default_uint64(default_uint64: Long?): Builder { this.default_uint64 = default_uint64 return this } public fun default_sint64(default_sint64: Long?): Builder { this.default_sint64 = default_sint64 return this } public fun default_fixed64(default_fixed64: Long?): Builder { this.default_fixed64 = default_fixed64 return this } public fun default_sfixed64(default_sfixed64: Long?): Builder { this.default_sfixed64 = default_sfixed64 return this } public fun default_bool(default_bool: Boolean?): Builder { this.default_bool = default_bool return this } public fun default_float(default_float: Float?): Builder { this.default_float = default_float return this } public fun default_double(default_double: Double?): Builder { this.default_double = default_double return this } public fun default_string(default_string: String?): Builder { this.default_string = default_string return this } public fun default_bytes(default_bytes: ByteString?): Builder { this.default_bytes = default_bytes return this } public fun default_nested_enum(default_nested_enum: NestedEnum?): Builder { this.default_nested_enum = default_nested_enum return this } public fun map_int32_int32(map_int32_int32: Map<Int, Int>): Builder { this.map_int32_int32 = map_int32_int32 return this } public fun map_string_string(map_string_string: Map<String, String>): Builder { this.map_string_string = map_string_string return this } public fun map_string_message(map_string_message: Map<String, NestedMessage>): Builder { this.map_string_message = map_string_message return this } public fun map_string_enum(map_string_enum: Map<String, NestedEnum>): Builder { this.map_string_enum = map_string_enum return this } public fun ext_opt_int32(ext_opt_int32: Int?): Builder { this.ext_opt_int32 = ext_opt_int32 return this } public fun ext_opt_uint32(ext_opt_uint32: Int?): Builder { this.ext_opt_uint32 = ext_opt_uint32 return this } public fun ext_opt_sint32(ext_opt_sint32: Int?): Builder { this.ext_opt_sint32 = ext_opt_sint32 return this } public fun ext_opt_fixed32(ext_opt_fixed32: Int?): Builder { this.ext_opt_fixed32 = ext_opt_fixed32 return this } public fun ext_opt_sfixed32(ext_opt_sfixed32: Int?): Builder { this.ext_opt_sfixed32 = ext_opt_sfixed32 return this } public fun ext_opt_int64(ext_opt_int64: Long?): Builder { this.ext_opt_int64 = ext_opt_int64 return this } public fun ext_opt_uint64(ext_opt_uint64: Long?): Builder { this.ext_opt_uint64 = ext_opt_uint64 return this } public fun ext_opt_sint64(ext_opt_sint64: Long?): Builder { this.ext_opt_sint64 = ext_opt_sint64 return this } public fun ext_opt_fixed64(ext_opt_fixed64: Long?): Builder { this.ext_opt_fixed64 = ext_opt_fixed64 return this } public fun ext_opt_sfixed64(ext_opt_sfixed64: Long?): Builder { this.ext_opt_sfixed64 = ext_opt_sfixed64 return this } public fun ext_opt_bool(ext_opt_bool: Boolean?): Builder { this.ext_opt_bool = ext_opt_bool return this } public fun ext_opt_float(ext_opt_float: Float?): Builder { this.ext_opt_float = ext_opt_float return this } public fun ext_opt_double(ext_opt_double: Double?): Builder { this.ext_opt_double = ext_opt_double return this } public fun ext_opt_string(ext_opt_string: String?): Builder { this.ext_opt_string = ext_opt_string return this } public fun ext_opt_bytes(ext_opt_bytes: ByteString?): Builder { this.ext_opt_bytes = ext_opt_bytes return this } public fun ext_opt_nested_enum(ext_opt_nested_enum: NestedEnum?): Builder { this.ext_opt_nested_enum = ext_opt_nested_enum return this } public fun ext_opt_nested_message(ext_opt_nested_message: NestedMessage?): Builder { this.ext_opt_nested_message = ext_opt_nested_message return this } public fun ext_rep_int32(ext_rep_int32: List<Int>): Builder { checkElementsNotNull(ext_rep_int32) this.ext_rep_int32 = ext_rep_int32 return this } public fun ext_rep_uint32(ext_rep_uint32: List<Int>): Builder { checkElementsNotNull(ext_rep_uint32) this.ext_rep_uint32 = ext_rep_uint32 return this } public fun ext_rep_sint32(ext_rep_sint32: List<Int>): Builder { checkElementsNotNull(ext_rep_sint32) this.ext_rep_sint32 = ext_rep_sint32 return this } public fun ext_rep_fixed32(ext_rep_fixed32: List<Int>): Builder { checkElementsNotNull(ext_rep_fixed32) this.ext_rep_fixed32 = ext_rep_fixed32 return this } public fun ext_rep_sfixed32(ext_rep_sfixed32: List<Int>): Builder { checkElementsNotNull(ext_rep_sfixed32) this.ext_rep_sfixed32 = ext_rep_sfixed32 return this } public fun ext_rep_int64(ext_rep_int64: List<Long>): Builder { checkElementsNotNull(ext_rep_int64) this.ext_rep_int64 = ext_rep_int64 return this } public fun ext_rep_uint64(ext_rep_uint64: List<Long>): Builder { checkElementsNotNull(ext_rep_uint64) this.ext_rep_uint64 = ext_rep_uint64 return this } public fun ext_rep_sint64(ext_rep_sint64: List<Long>): Builder { checkElementsNotNull(ext_rep_sint64) this.ext_rep_sint64 = ext_rep_sint64 return this } public fun ext_rep_fixed64(ext_rep_fixed64: List<Long>): Builder { checkElementsNotNull(ext_rep_fixed64) this.ext_rep_fixed64 = ext_rep_fixed64 return this } public fun ext_rep_sfixed64(ext_rep_sfixed64: List<Long>): Builder { checkElementsNotNull(ext_rep_sfixed64) this.ext_rep_sfixed64 = ext_rep_sfixed64 return this } public fun ext_rep_bool(ext_rep_bool: List<Boolean>): Builder { checkElementsNotNull(ext_rep_bool) this.ext_rep_bool = ext_rep_bool return this } public fun ext_rep_float(ext_rep_float: List<Float>): Builder { checkElementsNotNull(ext_rep_float) this.ext_rep_float = ext_rep_float return this } public fun ext_rep_double(ext_rep_double: List<Double>): Builder { checkElementsNotNull(ext_rep_double) this.ext_rep_double = ext_rep_double return this } public fun ext_rep_string(ext_rep_string: List<String>): Builder { checkElementsNotNull(ext_rep_string) this.ext_rep_string = ext_rep_string return this } public fun ext_rep_bytes(ext_rep_bytes: List<ByteString>): Builder { checkElementsNotNull(ext_rep_bytes) this.ext_rep_bytes = ext_rep_bytes return this } public fun ext_rep_nested_enum(ext_rep_nested_enum: List<NestedEnum>): Builder { checkElementsNotNull(ext_rep_nested_enum) this.ext_rep_nested_enum = ext_rep_nested_enum return this } public fun ext_rep_nested_message(ext_rep_nested_message: List<NestedMessage>): Builder { checkElementsNotNull(ext_rep_nested_message) this.ext_rep_nested_message = ext_rep_nested_message return this } public fun ext_pack_int32(ext_pack_int32: List<Int>): Builder { checkElementsNotNull(ext_pack_int32) this.ext_pack_int32 = ext_pack_int32 return this } public fun ext_pack_uint32(ext_pack_uint32: List<Int>): Builder { checkElementsNotNull(ext_pack_uint32) this.ext_pack_uint32 = ext_pack_uint32 return this } public fun ext_pack_sint32(ext_pack_sint32: List<Int>): Builder { checkElementsNotNull(ext_pack_sint32) this.ext_pack_sint32 = ext_pack_sint32 return this } public fun ext_pack_fixed32(ext_pack_fixed32: List<Int>): Builder { checkElementsNotNull(ext_pack_fixed32) this.ext_pack_fixed32 = ext_pack_fixed32 return this } public fun ext_pack_sfixed32(ext_pack_sfixed32: List<Int>): Builder { checkElementsNotNull(ext_pack_sfixed32) this.ext_pack_sfixed32 = ext_pack_sfixed32 return this } public fun ext_pack_int64(ext_pack_int64: List<Long>): Builder { checkElementsNotNull(ext_pack_int64) this.ext_pack_int64 = ext_pack_int64 return this } public fun ext_pack_uint64(ext_pack_uint64: List<Long>): Builder { checkElementsNotNull(ext_pack_uint64) this.ext_pack_uint64 = ext_pack_uint64 return this } public fun ext_pack_sint64(ext_pack_sint64: List<Long>): Builder { checkElementsNotNull(ext_pack_sint64) this.ext_pack_sint64 = ext_pack_sint64 return this } public fun ext_pack_fixed64(ext_pack_fixed64: List<Long>): Builder { checkElementsNotNull(ext_pack_fixed64) this.ext_pack_fixed64 = ext_pack_fixed64 return this } public fun ext_pack_sfixed64(ext_pack_sfixed64: List<Long>): Builder { checkElementsNotNull(ext_pack_sfixed64) this.ext_pack_sfixed64 = ext_pack_sfixed64 return this } public fun ext_pack_bool(ext_pack_bool: List<Boolean>): Builder { checkElementsNotNull(ext_pack_bool) this.ext_pack_bool = ext_pack_bool return this } public fun ext_pack_float(ext_pack_float: List<Float>): Builder { checkElementsNotNull(ext_pack_float) this.ext_pack_float = ext_pack_float return this } public fun ext_pack_double(ext_pack_double: List<Double>): Builder { checkElementsNotNull(ext_pack_double) this.ext_pack_double = ext_pack_double return this } public fun ext_pack_nested_enum(ext_pack_nested_enum: List<NestedEnum>): Builder { checkElementsNotNull(ext_pack_nested_enum) this.ext_pack_nested_enum = ext_pack_nested_enum return this } public fun oneof_string(oneof_string: String?): Builder { this.oneof_string = oneof_string this.oneof_int32 = null this.oneof_nested_message = null return this } public fun oneof_int32(oneof_int32: Int?): Builder { this.oneof_int32 = oneof_int32 this.oneof_string = null this.oneof_nested_message = null return this } public fun oneof_nested_message(oneof_nested_message: NestedMessage?): Builder { this.oneof_nested_message = oneof_nested_message this.oneof_string = null this.oneof_int32 = null return this } public override fun build(): AllTypes = AllTypes( opt_int32 = opt_int32, opt_uint32 = opt_uint32, opt_sint32 = opt_sint32, opt_fixed32 = opt_fixed32, opt_sfixed32 = opt_sfixed32, opt_int64 = opt_int64, opt_uint64 = opt_uint64, opt_sint64 = opt_sint64, opt_fixed64 = opt_fixed64, opt_sfixed64 = opt_sfixed64, opt_bool = opt_bool, opt_float = opt_float, opt_double = opt_double, opt_string = opt_string, opt_bytes = opt_bytes, opt_nested_enum = opt_nested_enum, opt_nested_message = opt_nested_message, req_int32 = req_int32 ?: throw missingRequiredFields(req_int32, "req_int32"), req_uint32 = req_uint32 ?: throw missingRequiredFields(req_uint32, "req_uint32"), req_sint32 = req_sint32 ?: throw missingRequiredFields(req_sint32, "req_sint32"), req_fixed32 = req_fixed32 ?: throw missingRequiredFields(req_fixed32, "req_fixed32"), req_sfixed32 = req_sfixed32 ?: throw missingRequiredFields(req_sfixed32, "req_sfixed32"), req_int64 = req_int64 ?: throw missingRequiredFields(req_int64, "req_int64"), req_uint64 = req_uint64 ?: throw missingRequiredFields(req_uint64, "req_uint64"), req_sint64 = req_sint64 ?: throw missingRequiredFields(req_sint64, "req_sint64"), req_fixed64 = req_fixed64 ?: throw missingRequiredFields(req_fixed64, "req_fixed64"), req_sfixed64 = req_sfixed64 ?: throw missingRequiredFields(req_sfixed64, "req_sfixed64"), req_bool = req_bool ?: throw missingRequiredFields(req_bool, "req_bool"), req_float = req_float ?: throw missingRequiredFields(req_float, "req_float"), req_double = req_double ?: throw missingRequiredFields(req_double, "req_double"), req_string = req_string ?: throw missingRequiredFields(req_string, "req_string"), req_bytes = req_bytes ?: throw missingRequiredFields(req_bytes, "req_bytes"), req_nested_enum = req_nested_enum ?: throw missingRequiredFields(req_nested_enum, "req_nested_enum"), req_nested_message = req_nested_message ?: throw missingRequiredFields(req_nested_message, "req_nested_message"), rep_int32 = rep_int32, rep_uint32 = rep_uint32, rep_sint32 = rep_sint32, rep_fixed32 = rep_fixed32, rep_sfixed32 = rep_sfixed32, rep_int64 = rep_int64, rep_uint64 = rep_uint64, rep_sint64 = rep_sint64, rep_fixed64 = rep_fixed64, rep_sfixed64 = rep_sfixed64, rep_bool = rep_bool, rep_float = rep_float, rep_double = rep_double, rep_string = rep_string, rep_bytes = rep_bytes, rep_nested_enum = rep_nested_enum, rep_nested_message = rep_nested_message, pack_int32 = pack_int32, pack_uint32 = pack_uint32, pack_sint32 = pack_sint32, pack_fixed32 = pack_fixed32, pack_sfixed32 = pack_sfixed32, pack_int64 = pack_int64, pack_uint64 = pack_uint64, pack_sint64 = pack_sint64, pack_fixed64 = pack_fixed64, pack_sfixed64 = pack_sfixed64, pack_bool = pack_bool, pack_float = pack_float, pack_double = pack_double, pack_nested_enum = pack_nested_enum, default_int32 = default_int32, default_uint32 = default_uint32, default_sint32 = default_sint32, default_fixed32 = default_fixed32, default_sfixed32 = default_sfixed32, default_int64 = default_int64, default_uint64 = default_uint64, default_sint64 = default_sint64, default_fixed64 = default_fixed64, default_sfixed64 = default_sfixed64, default_bool = default_bool, default_float = default_float, default_double = default_double, default_string = default_string, default_bytes = default_bytes, default_nested_enum = default_nested_enum, map_int32_int32 = map_int32_int32, map_string_string = map_string_string, map_string_message = map_string_message, map_string_enum = map_string_enum, oneof_string = oneof_string, oneof_int32 = oneof_int32, oneof_nested_message = oneof_nested_message, ext_opt_int32 = ext_opt_int32, ext_opt_uint32 = ext_opt_uint32, ext_opt_sint32 = ext_opt_sint32, ext_opt_fixed32 = ext_opt_fixed32, ext_opt_sfixed32 = ext_opt_sfixed32, ext_opt_int64 = ext_opt_int64, ext_opt_uint64 = ext_opt_uint64, ext_opt_sint64 = ext_opt_sint64, ext_opt_fixed64 = ext_opt_fixed64, ext_opt_sfixed64 = ext_opt_sfixed64, ext_opt_bool = ext_opt_bool, ext_opt_float = ext_opt_float, ext_opt_double = ext_opt_double, ext_opt_string = ext_opt_string, ext_opt_bytes = ext_opt_bytes, ext_opt_nested_enum = ext_opt_nested_enum, ext_opt_nested_message = ext_opt_nested_message, ext_rep_int32 = ext_rep_int32, ext_rep_uint32 = ext_rep_uint32, ext_rep_sint32 = ext_rep_sint32, ext_rep_fixed32 = ext_rep_fixed32, ext_rep_sfixed32 = ext_rep_sfixed32, ext_rep_int64 = ext_rep_int64, ext_rep_uint64 = ext_rep_uint64, ext_rep_sint64 = ext_rep_sint64, ext_rep_fixed64 = ext_rep_fixed64, ext_rep_sfixed64 = ext_rep_sfixed64, ext_rep_bool = ext_rep_bool, ext_rep_float = ext_rep_float, ext_rep_double = ext_rep_double, ext_rep_string = ext_rep_string, ext_rep_bytes = ext_rep_bytes, ext_rep_nested_enum = ext_rep_nested_enum, ext_rep_nested_message = ext_rep_nested_message, ext_pack_int32 = ext_pack_int32, ext_pack_uint32 = ext_pack_uint32, ext_pack_sint32 = ext_pack_sint32, ext_pack_fixed32 = ext_pack_fixed32, ext_pack_sfixed32 = ext_pack_sfixed32, ext_pack_int64 = ext_pack_int64, ext_pack_uint64 = ext_pack_uint64, ext_pack_sint64 = ext_pack_sint64, ext_pack_fixed64 = ext_pack_fixed64, ext_pack_sfixed64 = ext_pack_sfixed64, ext_pack_bool = ext_pack_bool, ext_pack_float = ext_pack_float, ext_pack_double = ext_pack_double, ext_pack_nested_enum = ext_pack_nested_enum, unknownFields = buildUnknownFields() ) } public companion object { public const val DEFAULT_DEFAULT_INT32: Int = Int.MAX_VALUE public const val DEFAULT_DEFAULT_UINT32: Int = -1 public const val DEFAULT_DEFAULT_SINT32: Int = Int.MIN_VALUE public const val DEFAULT_DEFAULT_FIXED32: Int = -1 public const val DEFAULT_DEFAULT_SFIXED32: Int = Int.MIN_VALUE public const val DEFAULT_DEFAULT_INT64: Long = Long.MAX_VALUE public const val DEFAULT_DEFAULT_UINT64: Long = -1L public const val DEFAULT_DEFAULT_SINT64: Long = Long.MIN_VALUE public const val DEFAULT_DEFAULT_FIXED64: Long = -1L public const val DEFAULT_DEFAULT_SFIXED64: Long = Long.MIN_VALUE public const val DEFAULT_DEFAULT_BOOL: Boolean = true public const val DEFAULT_DEFAULT_FLOAT: Float = 123.456e7f public const val DEFAULT_DEFAULT_DOUBLE: Double = 1.23456E80 public const val DEFAULT_DEFAULT_STRING: String = "çok\u0007\b\u000c\n\r\t\u000b\u0001\u0001\u0001\u000f\u000f~\u0001\u0001\u0011\u0001\u0001\u0011güzel" @JvmField public val DEFAULT_DEFAULT_BYTES: ByteString = "529rBwgMCg0JCwEBAQ8PfgEBEQEBEWf8emVs".decodeBase64()!! @JvmField public val DEFAULT_DEFAULT_NESTED_ENUM: NestedEnum = NestedEnum.A @JvmField public val ADAPTER: ProtoAdapter<AllTypes> = object : ProtoAdapter<AllTypes>( FieldEncoding.LENGTH_DELIMITED, AllTypes::class, "type.googleapis.com/squareup.proto2.AllTypes", PROTO_2, null, "all_types_proto2.proto" ) { private val map_int32_int32Adapter: ProtoAdapter<Map<Int, Int>> by lazy { ProtoAdapter.newMapAdapter(ProtoAdapter.INT32, ProtoAdapter.INT32) } private val map_string_stringAdapter: ProtoAdapter<Map<String, String>> by lazy { ProtoAdapter.newMapAdapter(ProtoAdapter.STRING, ProtoAdapter.STRING) } private val map_string_messageAdapter: ProtoAdapter<Map<String, NestedMessage>> by lazy { ProtoAdapter.newMapAdapter(ProtoAdapter.STRING, NestedMessage.ADAPTER) } private val map_string_enumAdapter: ProtoAdapter<Map<String, NestedEnum>> by lazy { ProtoAdapter.newMapAdapter(ProtoAdapter.STRING, NestedEnum.ADAPTER) } public override fun encodedSize(`value`: AllTypes): Int { var size = value.unknownFields.size size += ProtoAdapter.INT32.encodedSizeWithTag(1, value.opt_int32) size += ProtoAdapter.UINT32.encodedSizeWithTag(2, value.opt_uint32) size += ProtoAdapter.SINT32.encodedSizeWithTag(3, value.opt_sint32) size += ProtoAdapter.FIXED32.encodedSizeWithTag(4, value.opt_fixed32) size += ProtoAdapter.SFIXED32.encodedSizeWithTag(5, value.opt_sfixed32) size += ProtoAdapter.INT64.encodedSizeWithTag(6, value.opt_int64) size += ProtoAdapter.UINT64.encodedSizeWithTag(7, value.opt_uint64) size += ProtoAdapter.SINT64.encodedSizeWithTag(8, value.opt_sint64) size += ProtoAdapter.FIXED64.encodedSizeWithTag(9, value.opt_fixed64) size += ProtoAdapter.SFIXED64.encodedSizeWithTag(10, value.opt_sfixed64) size += ProtoAdapter.BOOL.encodedSizeWithTag(11, value.opt_bool) size += ProtoAdapter.FLOAT.encodedSizeWithTag(12, value.opt_float) size += ProtoAdapter.DOUBLE.encodedSizeWithTag(13, value.opt_double) size += ProtoAdapter.STRING.encodedSizeWithTag(14, value.opt_string) size += ProtoAdapter.BYTES.encodedSizeWithTag(15, value.opt_bytes) size += NestedEnum.ADAPTER.encodedSizeWithTag(16, value.opt_nested_enum) size += NestedMessage.ADAPTER.encodedSizeWithTag(17, value.opt_nested_message) size += ProtoAdapter.INT32.encodedSizeWithTag(101, value.req_int32) size += ProtoAdapter.UINT32.encodedSizeWithTag(102, value.req_uint32) size += ProtoAdapter.SINT32.encodedSizeWithTag(103, value.req_sint32) size += ProtoAdapter.FIXED32.encodedSizeWithTag(104, value.req_fixed32) size += ProtoAdapter.SFIXED32.encodedSizeWithTag(105, value.req_sfixed32) size += ProtoAdapter.INT64.encodedSizeWithTag(106, value.req_int64) size += ProtoAdapter.UINT64.encodedSizeWithTag(107, value.req_uint64) size += ProtoAdapter.SINT64.encodedSizeWithTag(108, value.req_sint64) size += ProtoAdapter.FIXED64.encodedSizeWithTag(109, value.req_fixed64) size += ProtoAdapter.SFIXED64.encodedSizeWithTag(110, value.req_sfixed64) size += ProtoAdapter.BOOL.encodedSizeWithTag(111, value.req_bool) size += ProtoAdapter.FLOAT.encodedSizeWithTag(112, value.req_float) size += ProtoAdapter.DOUBLE.encodedSizeWithTag(113, value.req_double) size += ProtoAdapter.STRING.encodedSizeWithTag(114, value.req_string) size += ProtoAdapter.BYTES.encodedSizeWithTag(115, value.req_bytes) size += NestedEnum.ADAPTER.encodedSizeWithTag(116, value.req_nested_enum) size += NestedMessage.ADAPTER.encodedSizeWithTag(117, value.req_nested_message) size += ProtoAdapter.INT32.asRepeated().encodedSizeWithTag(201, value.rep_int32) size += ProtoAdapter.UINT32.asRepeated().encodedSizeWithTag(202, value.rep_uint32) size += ProtoAdapter.SINT32.asRepeated().encodedSizeWithTag(203, value.rep_sint32) size += ProtoAdapter.FIXED32.asRepeated().encodedSizeWithTag(204, value.rep_fixed32) size += ProtoAdapter.SFIXED32.asRepeated().encodedSizeWithTag(205, value.rep_sfixed32) size += ProtoAdapter.INT64.asRepeated().encodedSizeWithTag(206, value.rep_int64) size += ProtoAdapter.UINT64.asRepeated().encodedSizeWithTag(207, value.rep_uint64) size += ProtoAdapter.SINT64.asRepeated().encodedSizeWithTag(208, value.rep_sint64) size += ProtoAdapter.FIXED64.asRepeated().encodedSizeWithTag(209, value.rep_fixed64) size += ProtoAdapter.SFIXED64.asRepeated().encodedSizeWithTag(210, value.rep_sfixed64) size += ProtoAdapter.BOOL.asRepeated().encodedSizeWithTag(211, value.rep_bool) size += ProtoAdapter.FLOAT.asRepeated().encodedSizeWithTag(212, value.rep_float) size += ProtoAdapter.DOUBLE.asRepeated().encodedSizeWithTag(213, value.rep_double) size += ProtoAdapter.STRING.asRepeated().encodedSizeWithTag(214, value.rep_string) size += ProtoAdapter.BYTES.asRepeated().encodedSizeWithTag(215, value.rep_bytes) size += NestedEnum.ADAPTER.asRepeated().encodedSizeWithTag(216, value.rep_nested_enum) size += NestedMessage.ADAPTER.asRepeated().encodedSizeWithTag(217, value.rep_nested_message) size += ProtoAdapter.INT32.asPacked().encodedSizeWithTag(301, value.pack_int32) size += ProtoAdapter.UINT32.asPacked().encodedSizeWithTag(302, value.pack_uint32) size += ProtoAdapter.SINT32.asPacked().encodedSizeWithTag(303, value.pack_sint32) size += ProtoAdapter.FIXED32.asPacked().encodedSizeWithTag(304, value.pack_fixed32) size += ProtoAdapter.SFIXED32.asPacked().encodedSizeWithTag(305, value.pack_sfixed32) size += ProtoAdapter.INT64.asPacked().encodedSizeWithTag(306, value.pack_int64) size += ProtoAdapter.UINT64.asPacked().encodedSizeWithTag(307, value.pack_uint64) size += ProtoAdapter.SINT64.asPacked().encodedSizeWithTag(308, value.pack_sint64) size += ProtoAdapter.FIXED64.asPacked().encodedSizeWithTag(309, value.pack_fixed64) size += ProtoAdapter.SFIXED64.asPacked().encodedSizeWithTag(310, value.pack_sfixed64) size += ProtoAdapter.BOOL.asPacked().encodedSizeWithTag(311, value.pack_bool) size += ProtoAdapter.FLOAT.asPacked().encodedSizeWithTag(312, value.pack_float) size += ProtoAdapter.DOUBLE.asPacked().encodedSizeWithTag(313, value.pack_double) size += NestedEnum.ADAPTER.asPacked().encodedSizeWithTag(316, value.pack_nested_enum) size += ProtoAdapter.INT32.encodedSizeWithTag(401, value.default_int32) size += ProtoAdapter.UINT32.encodedSizeWithTag(402, value.default_uint32) size += ProtoAdapter.SINT32.encodedSizeWithTag(403, value.default_sint32) size += ProtoAdapter.FIXED32.encodedSizeWithTag(404, value.default_fixed32) size += ProtoAdapter.SFIXED32.encodedSizeWithTag(405, value.default_sfixed32) size += ProtoAdapter.INT64.encodedSizeWithTag(406, value.default_int64) size += ProtoAdapter.UINT64.encodedSizeWithTag(407, value.default_uint64) size += ProtoAdapter.SINT64.encodedSizeWithTag(408, value.default_sint64) size += ProtoAdapter.FIXED64.encodedSizeWithTag(409, value.default_fixed64) size += ProtoAdapter.SFIXED64.encodedSizeWithTag(410, value.default_sfixed64) size += ProtoAdapter.BOOL.encodedSizeWithTag(411, value.default_bool) size += ProtoAdapter.FLOAT.encodedSizeWithTag(412, value.default_float) size += ProtoAdapter.DOUBLE.encodedSizeWithTag(413, value.default_double) size += ProtoAdapter.STRING.encodedSizeWithTag(414, value.default_string) size += ProtoAdapter.BYTES.encodedSizeWithTag(415, value.default_bytes) size += NestedEnum.ADAPTER.encodedSizeWithTag(416, value.default_nested_enum) size += map_int32_int32Adapter.encodedSizeWithTag(501, value.map_int32_int32) size += map_string_stringAdapter.encodedSizeWithTag(502, value.map_string_string) size += map_string_messageAdapter.encodedSizeWithTag(503, value.map_string_message) size += map_string_enumAdapter.encodedSizeWithTag(504, value.map_string_enum) size += ProtoAdapter.STRING.encodedSizeWithTag(601, value.oneof_string) size += ProtoAdapter.INT32.encodedSizeWithTag(602, value.oneof_int32) size += NestedMessage.ADAPTER.encodedSizeWithTag(603, value.oneof_nested_message) size += ProtoAdapter.INT32.encodedSizeWithTag(1001, value.ext_opt_int32) size += ProtoAdapter.UINT32.encodedSizeWithTag(1002, value.ext_opt_uint32) size += ProtoAdapter.SINT32.encodedSizeWithTag(1003, value.ext_opt_sint32) size += ProtoAdapter.FIXED32.encodedSizeWithTag(1004, value.ext_opt_fixed32) size += ProtoAdapter.SFIXED32.encodedSizeWithTag(1005, value.ext_opt_sfixed32) size += ProtoAdapter.INT64.encodedSizeWithTag(1006, value.ext_opt_int64) size += ProtoAdapter.UINT64.encodedSizeWithTag(1007, value.ext_opt_uint64) size += ProtoAdapter.SINT64.encodedSizeWithTag(1008, value.ext_opt_sint64) size += ProtoAdapter.FIXED64.encodedSizeWithTag(1009, value.ext_opt_fixed64) size += ProtoAdapter.SFIXED64.encodedSizeWithTag(1010, value.ext_opt_sfixed64) size += ProtoAdapter.BOOL.encodedSizeWithTag(1011, value.ext_opt_bool) size += ProtoAdapter.FLOAT.encodedSizeWithTag(1012, value.ext_opt_float) size += ProtoAdapter.DOUBLE.encodedSizeWithTag(1013, value.ext_opt_double) size += ProtoAdapter.STRING.encodedSizeWithTag(1014, value.ext_opt_string) size += ProtoAdapter.BYTES.encodedSizeWithTag(1015, value.ext_opt_bytes) size += NestedEnum.ADAPTER.encodedSizeWithTag(1016, value.ext_opt_nested_enum) size += NestedMessage.ADAPTER.encodedSizeWithTag(1017, value.ext_opt_nested_message) size += ProtoAdapter.INT32.asRepeated().encodedSizeWithTag(1101, value.ext_rep_int32) size += ProtoAdapter.UINT32.asRepeated().encodedSizeWithTag(1102, value.ext_rep_uint32) size += ProtoAdapter.SINT32.asRepeated().encodedSizeWithTag(1103, value.ext_rep_sint32) size += ProtoAdapter.FIXED32.asRepeated().encodedSizeWithTag(1104, value.ext_rep_fixed32) size += ProtoAdapter.SFIXED32.asRepeated().encodedSizeWithTag(1105, value.ext_rep_sfixed32) size += ProtoAdapter.INT64.asRepeated().encodedSizeWithTag(1106, value.ext_rep_int64) size += ProtoAdapter.UINT64.asRepeated().encodedSizeWithTag(1107, value.ext_rep_uint64) size += ProtoAdapter.SINT64.asRepeated().encodedSizeWithTag(1108, value.ext_rep_sint64) size += ProtoAdapter.FIXED64.asRepeated().encodedSizeWithTag(1109, value.ext_rep_fixed64) size += ProtoAdapter.SFIXED64.asRepeated().encodedSizeWithTag(1110, value.ext_rep_sfixed64) size += ProtoAdapter.BOOL.asRepeated().encodedSizeWithTag(1111, value.ext_rep_bool) size += ProtoAdapter.FLOAT.asRepeated().encodedSizeWithTag(1112, value.ext_rep_float) size += ProtoAdapter.DOUBLE.asRepeated().encodedSizeWithTag(1113, value.ext_rep_double) size += ProtoAdapter.STRING.asRepeated().encodedSizeWithTag(1114, value.ext_rep_string) size += ProtoAdapter.BYTES.asRepeated().encodedSizeWithTag(1115, value.ext_rep_bytes) size += NestedEnum.ADAPTER.asRepeated().encodedSizeWithTag(1116, value.ext_rep_nested_enum) size += NestedMessage.ADAPTER.asRepeated().encodedSizeWithTag(1117, value.ext_rep_nested_message) size += ProtoAdapter.INT32.asPacked().encodedSizeWithTag(1201, value.ext_pack_int32) size += ProtoAdapter.UINT32.asPacked().encodedSizeWithTag(1202, value.ext_pack_uint32) size += ProtoAdapter.SINT32.asPacked().encodedSizeWithTag(1203, value.ext_pack_sint32) size += ProtoAdapter.FIXED32.asPacked().encodedSizeWithTag(1204, value.ext_pack_fixed32) size += ProtoAdapter.SFIXED32.asPacked().encodedSizeWithTag(1205, value.ext_pack_sfixed32) size += ProtoAdapter.INT64.asPacked().encodedSizeWithTag(1206, value.ext_pack_int64) size += ProtoAdapter.UINT64.asPacked().encodedSizeWithTag(1207, value.ext_pack_uint64) size += ProtoAdapter.SINT64.asPacked().encodedSizeWithTag(1208, value.ext_pack_sint64) size += ProtoAdapter.FIXED64.asPacked().encodedSizeWithTag(1209, value.ext_pack_fixed64) size += ProtoAdapter.SFIXED64.asPacked().encodedSizeWithTag(1210, value.ext_pack_sfixed64) size += ProtoAdapter.BOOL.asPacked().encodedSizeWithTag(1211, value.ext_pack_bool) size += ProtoAdapter.FLOAT.asPacked().encodedSizeWithTag(1212, value.ext_pack_float) size += ProtoAdapter.DOUBLE.asPacked().encodedSizeWithTag(1213, value.ext_pack_double) size += NestedEnum.ADAPTER.asPacked().encodedSizeWithTag(1216, value.ext_pack_nested_enum) return size } public override fun encode(writer: ProtoWriter, `value`: AllTypes): Unit { ProtoAdapter.INT32.encodeWithTag(writer, 1, value.opt_int32) ProtoAdapter.UINT32.encodeWithTag(writer, 2, value.opt_uint32) ProtoAdapter.SINT32.encodeWithTag(writer, 3, value.opt_sint32) ProtoAdapter.FIXED32.encodeWithTag(writer, 4, value.opt_fixed32) ProtoAdapter.SFIXED32.encodeWithTag(writer, 5, value.opt_sfixed32) ProtoAdapter.INT64.encodeWithTag(writer, 6, value.opt_int64) ProtoAdapter.UINT64.encodeWithTag(writer, 7, value.opt_uint64) ProtoAdapter.SINT64.encodeWithTag(writer, 8, value.opt_sint64) ProtoAdapter.FIXED64.encodeWithTag(writer, 9, value.opt_fixed64) ProtoAdapter.SFIXED64.encodeWithTag(writer, 10, value.opt_sfixed64) ProtoAdapter.BOOL.encodeWithTag(writer, 11, value.opt_bool) ProtoAdapter.FLOAT.encodeWithTag(writer, 12, value.opt_float) ProtoAdapter.DOUBLE.encodeWithTag(writer, 13, value.opt_double) ProtoAdapter.STRING.encodeWithTag(writer, 14, value.opt_string) ProtoAdapter.BYTES.encodeWithTag(writer, 15, value.opt_bytes) NestedEnum.ADAPTER.encodeWithTag(writer, 16, value.opt_nested_enum) NestedMessage.ADAPTER.encodeWithTag(writer, 17, value.opt_nested_message) ProtoAdapter.INT32.encodeWithTag(writer, 101, value.req_int32) ProtoAdapter.UINT32.encodeWithTag(writer, 102, value.req_uint32) ProtoAdapter.SINT32.encodeWithTag(writer, 103, value.req_sint32) ProtoAdapter.FIXED32.encodeWithTag(writer, 104, value.req_fixed32) ProtoAdapter.SFIXED32.encodeWithTag(writer, 105, value.req_sfixed32) ProtoAdapter.INT64.encodeWithTag(writer, 106, value.req_int64) ProtoAdapter.UINT64.encodeWithTag(writer, 107, value.req_uint64) ProtoAdapter.SINT64.encodeWithTag(writer, 108, value.req_sint64) ProtoAdapter.FIXED64.encodeWithTag(writer, 109, value.req_fixed64) ProtoAdapter.SFIXED64.encodeWithTag(writer, 110, value.req_sfixed64) ProtoAdapter.BOOL.encodeWithTag(writer, 111, value.req_bool) ProtoAdapter.FLOAT.encodeWithTag(writer, 112, value.req_float) ProtoAdapter.DOUBLE.encodeWithTag(writer, 113, value.req_double) ProtoAdapter.STRING.encodeWithTag(writer, 114, value.req_string) ProtoAdapter.BYTES.encodeWithTag(writer, 115, value.req_bytes) NestedEnum.ADAPTER.encodeWithTag(writer, 116, value.req_nested_enum) NestedMessage.ADAPTER.encodeWithTag(writer, 117, value.req_nested_message) ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 201, value.rep_int32) ProtoAdapter.UINT32.asRepeated().encodeWithTag(writer, 202, value.rep_uint32) ProtoAdapter.SINT32.asRepeated().encodeWithTag(writer, 203, value.rep_sint32) ProtoAdapter.FIXED32.asRepeated().encodeWithTag(writer, 204, value.rep_fixed32) ProtoAdapter.SFIXED32.asRepeated().encodeWithTag(writer, 205, value.rep_sfixed32) ProtoAdapter.INT64.asRepeated().encodeWithTag(writer, 206, value.rep_int64) ProtoAdapter.UINT64.asRepeated().encodeWithTag(writer, 207, value.rep_uint64) ProtoAdapter.SINT64.asRepeated().encodeWithTag(writer, 208, value.rep_sint64) ProtoAdapter.FIXED64.asRepeated().encodeWithTag(writer, 209, value.rep_fixed64) ProtoAdapter.SFIXED64.asRepeated().encodeWithTag(writer, 210, value.rep_sfixed64) ProtoAdapter.BOOL.asRepeated().encodeWithTag(writer, 211, value.rep_bool) ProtoAdapter.FLOAT.asRepeated().encodeWithTag(writer, 212, value.rep_float) ProtoAdapter.DOUBLE.asRepeated().encodeWithTag(writer, 213, value.rep_double) ProtoAdapter.STRING.asRepeated().encodeWithTag(writer, 214, value.rep_string) ProtoAdapter.BYTES.asRepeated().encodeWithTag(writer, 215, value.rep_bytes) NestedEnum.ADAPTER.asRepeated().encodeWithTag(writer, 216, value.rep_nested_enum) NestedMessage.ADAPTER.asRepeated().encodeWithTag(writer, 217, value.rep_nested_message) ProtoAdapter.INT32.asPacked().encodeWithTag(writer, 301, value.pack_int32) ProtoAdapter.UINT32.asPacked().encodeWithTag(writer, 302, value.pack_uint32) ProtoAdapter.SINT32.asPacked().encodeWithTag(writer, 303, value.pack_sint32) ProtoAdapter.FIXED32.asPacked().encodeWithTag(writer, 304, value.pack_fixed32) ProtoAdapter.SFIXED32.asPacked().encodeWithTag(writer, 305, value.pack_sfixed32) ProtoAdapter.INT64.asPacked().encodeWithTag(writer, 306, value.pack_int64) ProtoAdapter.UINT64.asPacked().encodeWithTag(writer, 307, value.pack_uint64) ProtoAdapter.SINT64.asPacked().encodeWithTag(writer, 308, value.pack_sint64) ProtoAdapter.FIXED64.asPacked().encodeWithTag(writer, 309, value.pack_fixed64) ProtoAdapter.SFIXED64.asPacked().encodeWithTag(writer, 310, value.pack_sfixed64) ProtoAdapter.BOOL.asPacked().encodeWithTag(writer, 311, value.pack_bool) ProtoAdapter.FLOAT.asPacked().encodeWithTag(writer, 312, value.pack_float) ProtoAdapter.DOUBLE.asPacked().encodeWithTag(writer, 313, value.pack_double) NestedEnum.ADAPTER.asPacked().encodeWithTag(writer, 316, value.pack_nested_enum) ProtoAdapter.INT32.encodeWithTag(writer, 401, value.default_int32) ProtoAdapter.UINT32.encodeWithTag(writer, 402, value.default_uint32) ProtoAdapter.SINT32.encodeWithTag(writer, 403, value.default_sint32) ProtoAdapter.FIXED32.encodeWithTag(writer, 404, value.default_fixed32) ProtoAdapter.SFIXED32.encodeWithTag(writer, 405, value.default_sfixed32) ProtoAdapter.INT64.encodeWithTag(writer, 406, value.default_int64) ProtoAdapter.UINT64.encodeWithTag(writer, 407, value.default_uint64) ProtoAdapter.SINT64.encodeWithTag(writer, 408, value.default_sint64) ProtoAdapter.FIXED64.encodeWithTag(writer, 409, value.default_fixed64) ProtoAdapter.SFIXED64.encodeWithTag(writer, 410, value.default_sfixed64) ProtoAdapter.BOOL.encodeWithTag(writer, 411, value.default_bool) ProtoAdapter.FLOAT.encodeWithTag(writer, 412, value.default_float) ProtoAdapter.DOUBLE.encodeWithTag(writer, 413, value.default_double) ProtoAdapter.STRING.encodeWithTag(writer, 414, value.default_string) ProtoAdapter.BYTES.encodeWithTag(writer, 415, value.default_bytes) NestedEnum.ADAPTER.encodeWithTag(writer, 416, value.default_nested_enum) map_int32_int32Adapter.encodeWithTag(writer, 501, value.map_int32_int32) map_string_stringAdapter.encodeWithTag(writer, 502, value.map_string_string) map_string_messageAdapter.encodeWithTag(writer, 503, value.map_string_message) map_string_enumAdapter.encodeWithTag(writer, 504, value.map_string_enum) ProtoAdapter.INT32.encodeWithTag(writer, 1001, value.ext_opt_int32) ProtoAdapter.UINT32.encodeWithTag(writer, 1002, value.ext_opt_uint32) ProtoAdapter.SINT32.encodeWithTag(writer, 1003, value.ext_opt_sint32) ProtoAdapter.FIXED32.encodeWithTag(writer, 1004, value.ext_opt_fixed32) ProtoAdapter.SFIXED32.encodeWithTag(writer, 1005, value.ext_opt_sfixed32) ProtoAdapter.INT64.encodeWithTag(writer, 1006, value.ext_opt_int64) ProtoAdapter.UINT64.encodeWithTag(writer, 1007, value.ext_opt_uint64) ProtoAdapter.SINT64.encodeWithTag(writer, 1008, value.ext_opt_sint64) ProtoAdapter.FIXED64.encodeWithTag(writer, 1009, value.ext_opt_fixed64) ProtoAdapter.SFIXED64.encodeWithTag(writer, 1010, value.ext_opt_sfixed64) ProtoAdapter.BOOL.encodeWithTag(writer, 1011, value.ext_opt_bool) ProtoAdapter.FLOAT.encodeWithTag(writer, 1012, value.ext_opt_float) ProtoAdapter.DOUBLE.encodeWithTag(writer, 1013, value.ext_opt_double) ProtoAdapter.STRING.encodeWithTag(writer, 1014, value.ext_opt_string) ProtoAdapter.BYTES.encodeWithTag(writer, 1015, value.ext_opt_bytes) NestedEnum.ADAPTER.encodeWithTag(writer, 1016, value.ext_opt_nested_enum) NestedMessage.ADAPTER.encodeWithTag(writer, 1017, value.ext_opt_nested_message) ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 1101, value.ext_rep_int32) ProtoAdapter.UINT32.asRepeated().encodeWithTag(writer, 1102, value.ext_rep_uint32) ProtoAdapter.SINT32.asRepeated().encodeWithTag(writer, 1103, value.ext_rep_sint32) ProtoAdapter.FIXED32.asRepeated().encodeWithTag(writer, 1104, value.ext_rep_fixed32) ProtoAdapter.SFIXED32.asRepeated().encodeWithTag(writer, 1105, value.ext_rep_sfixed32) ProtoAdapter.INT64.asRepeated().encodeWithTag(writer, 1106, value.ext_rep_int64) ProtoAdapter.UINT64.asRepeated().encodeWithTag(writer, 1107, value.ext_rep_uint64) ProtoAdapter.SINT64.asRepeated().encodeWithTag(writer, 1108, value.ext_rep_sint64) ProtoAdapter.FIXED64.asRepeated().encodeWithTag(writer, 1109, value.ext_rep_fixed64) ProtoAdapter.SFIXED64.asRepeated().encodeWithTag(writer, 1110, value.ext_rep_sfixed64) ProtoAdapter.BOOL.asRepeated().encodeWithTag(writer, 1111, value.ext_rep_bool) ProtoAdapter.FLOAT.asRepeated().encodeWithTag(writer, 1112, value.ext_rep_float) ProtoAdapter.DOUBLE.asRepeated().encodeWithTag(writer, 1113, value.ext_rep_double) ProtoAdapter.STRING.asRepeated().encodeWithTag(writer, 1114, value.ext_rep_string) ProtoAdapter.BYTES.asRepeated().encodeWithTag(writer, 1115, value.ext_rep_bytes) NestedEnum.ADAPTER.asRepeated().encodeWithTag(writer, 1116, value.ext_rep_nested_enum) NestedMessage.ADAPTER.asRepeated().encodeWithTag(writer, 1117, value.ext_rep_nested_message) ProtoAdapter.INT32.asPacked().encodeWithTag(writer, 1201, value.ext_pack_int32) ProtoAdapter.UINT32.asPacked().encodeWithTag(writer, 1202, value.ext_pack_uint32) ProtoAdapter.SINT32.asPacked().encodeWithTag(writer, 1203, value.ext_pack_sint32) ProtoAdapter.FIXED32.asPacked().encodeWithTag(writer, 1204, value.ext_pack_fixed32) ProtoAdapter.SFIXED32.asPacked().encodeWithTag(writer, 1205, value.ext_pack_sfixed32) ProtoAdapter.INT64.asPacked().encodeWithTag(writer, 1206, value.ext_pack_int64) ProtoAdapter.UINT64.asPacked().encodeWithTag(writer, 1207, value.ext_pack_uint64) ProtoAdapter.SINT64.asPacked().encodeWithTag(writer, 1208, value.ext_pack_sint64) ProtoAdapter.FIXED64.asPacked().encodeWithTag(writer, 1209, value.ext_pack_fixed64) ProtoAdapter.SFIXED64.asPacked().encodeWithTag(writer, 1210, value.ext_pack_sfixed64) ProtoAdapter.BOOL.asPacked().encodeWithTag(writer, 1211, value.ext_pack_bool) ProtoAdapter.FLOAT.asPacked().encodeWithTag(writer, 1212, value.ext_pack_float) ProtoAdapter.DOUBLE.asPacked().encodeWithTag(writer, 1213, value.ext_pack_double) NestedEnum.ADAPTER.asPacked().encodeWithTag(writer, 1216, value.ext_pack_nested_enum) ProtoAdapter.STRING.encodeWithTag(writer, 601, value.oneof_string) ProtoAdapter.INT32.encodeWithTag(writer, 602, value.oneof_int32) NestedMessage.ADAPTER.encodeWithTag(writer, 603, value.oneof_nested_message) writer.writeBytes(value.unknownFields) } public override fun encode(writer: ReverseProtoWriter, `value`: AllTypes): Unit { writer.writeBytes(value.unknownFields) NestedMessage.ADAPTER.encodeWithTag(writer, 603, value.oneof_nested_message) ProtoAdapter.INT32.encodeWithTag(writer, 602, value.oneof_int32) ProtoAdapter.STRING.encodeWithTag(writer, 601, value.oneof_string) NestedEnum.ADAPTER.asPacked().encodeWithTag(writer, 1216, value.ext_pack_nested_enum) ProtoAdapter.DOUBLE.asPacked().encodeWithTag(writer, 1213, value.ext_pack_double) ProtoAdapter.FLOAT.asPacked().encodeWithTag(writer, 1212, value.ext_pack_float) ProtoAdapter.BOOL.asPacked().encodeWithTag(writer, 1211, value.ext_pack_bool) ProtoAdapter.SFIXED64.asPacked().encodeWithTag(writer, 1210, value.ext_pack_sfixed64) ProtoAdapter.FIXED64.asPacked().encodeWithTag(writer, 1209, value.ext_pack_fixed64) ProtoAdapter.SINT64.asPacked().encodeWithTag(writer, 1208, value.ext_pack_sint64) ProtoAdapter.UINT64.asPacked().encodeWithTag(writer, 1207, value.ext_pack_uint64) ProtoAdapter.INT64.asPacked().encodeWithTag(writer, 1206, value.ext_pack_int64) ProtoAdapter.SFIXED32.asPacked().encodeWithTag(writer, 1205, value.ext_pack_sfixed32) ProtoAdapter.FIXED32.asPacked().encodeWithTag(writer, 1204, value.ext_pack_fixed32) ProtoAdapter.SINT32.asPacked().encodeWithTag(writer, 1203, value.ext_pack_sint32) ProtoAdapter.UINT32.asPacked().encodeWithTag(writer, 1202, value.ext_pack_uint32) ProtoAdapter.INT32.asPacked().encodeWithTag(writer, 1201, value.ext_pack_int32) NestedMessage.ADAPTER.asRepeated().encodeWithTag(writer, 1117, value.ext_rep_nested_message) NestedEnum.ADAPTER.asRepeated().encodeWithTag(writer, 1116, value.ext_rep_nested_enum) ProtoAdapter.BYTES.asRepeated().encodeWithTag(writer, 1115, value.ext_rep_bytes) ProtoAdapter.STRING.asRepeated().encodeWithTag(writer, 1114, value.ext_rep_string) ProtoAdapter.DOUBLE.asRepeated().encodeWithTag(writer, 1113, value.ext_rep_double) ProtoAdapter.FLOAT.asRepeated().encodeWithTag(writer, 1112, value.ext_rep_float) ProtoAdapter.BOOL.asRepeated().encodeWithTag(writer, 1111, value.ext_rep_bool) ProtoAdapter.SFIXED64.asRepeated().encodeWithTag(writer, 1110, value.ext_rep_sfixed64) ProtoAdapter.FIXED64.asRepeated().encodeWithTag(writer, 1109, value.ext_rep_fixed64) ProtoAdapter.SINT64.asRepeated().encodeWithTag(writer, 1108, value.ext_rep_sint64) ProtoAdapter.UINT64.asRepeated().encodeWithTag(writer, 1107, value.ext_rep_uint64) ProtoAdapter.INT64.asRepeated().encodeWithTag(writer, 1106, value.ext_rep_int64) ProtoAdapter.SFIXED32.asRepeated().encodeWithTag(writer, 1105, value.ext_rep_sfixed32) ProtoAdapter.FIXED32.asRepeated().encodeWithTag(writer, 1104, value.ext_rep_fixed32) ProtoAdapter.SINT32.asRepeated().encodeWithTag(writer, 1103, value.ext_rep_sint32) ProtoAdapter.UINT32.asRepeated().encodeWithTag(writer, 1102, value.ext_rep_uint32) ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 1101, value.ext_rep_int32) NestedMessage.ADAPTER.encodeWithTag(writer, 1017, value.ext_opt_nested_message) NestedEnum.ADAPTER.encodeWithTag(writer, 1016, value.ext_opt_nested_enum) ProtoAdapter.BYTES.encodeWithTag(writer, 1015, value.ext_opt_bytes) ProtoAdapter.STRING.encodeWithTag(writer, 1014, value.ext_opt_string) ProtoAdapter.DOUBLE.encodeWithTag(writer, 1013, value.ext_opt_double) ProtoAdapter.FLOAT.encodeWithTag(writer, 1012, value.ext_opt_float) ProtoAdapter.BOOL.encodeWithTag(writer, 1011, value.ext_opt_bool) ProtoAdapter.SFIXED64.encodeWithTag(writer, 1010, value.ext_opt_sfixed64) ProtoAdapter.FIXED64.encodeWithTag(writer, 1009, value.ext_opt_fixed64) ProtoAdapter.SINT64.encodeWithTag(writer, 1008, value.ext_opt_sint64) ProtoAdapter.UINT64.encodeWithTag(writer, 1007, value.ext_opt_uint64) ProtoAdapter.INT64.encodeWithTag(writer, 1006, value.ext_opt_int64) ProtoAdapter.SFIXED32.encodeWithTag(writer, 1005, value.ext_opt_sfixed32) ProtoAdapter.FIXED32.encodeWithTag(writer, 1004, value.ext_opt_fixed32) ProtoAdapter.SINT32.encodeWithTag(writer, 1003, value.ext_opt_sint32) ProtoAdapter.UINT32.encodeWithTag(writer, 1002, value.ext_opt_uint32) ProtoAdapter.INT32.encodeWithTag(writer, 1001, value.ext_opt_int32) map_string_enumAdapter.encodeWithTag(writer, 504, value.map_string_enum) map_string_messageAdapter.encodeWithTag(writer, 503, value.map_string_message) map_string_stringAdapter.encodeWithTag(writer, 502, value.map_string_string) map_int32_int32Adapter.encodeWithTag(writer, 501, value.map_int32_int32) NestedEnum.ADAPTER.encodeWithTag(writer, 416, value.default_nested_enum) ProtoAdapter.BYTES.encodeWithTag(writer, 415, value.default_bytes) ProtoAdapter.STRING.encodeWithTag(writer, 414, value.default_string) ProtoAdapter.DOUBLE.encodeWithTag(writer, 413, value.default_double) ProtoAdapter.FLOAT.encodeWithTag(writer, 412, value.default_float) ProtoAdapter.BOOL.encodeWithTag(writer, 411, value.default_bool) ProtoAdapter.SFIXED64.encodeWithTag(writer, 410, value.default_sfixed64) ProtoAdapter.FIXED64.encodeWithTag(writer, 409, value.default_fixed64) ProtoAdapter.SINT64.encodeWithTag(writer, 408, value.default_sint64) ProtoAdapter.UINT64.encodeWithTag(writer, 407, value.default_uint64) ProtoAdapter.INT64.encodeWithTag(writer, 406, value.default_int64) ProtoAdapter.SFIXED32.encodeWithTag(writer, 405, value.default_sfixed32) ProtoAdapter.FIXED32.encodeWithTag(writer, 404, value.default_fixed32) ProtoAdapter.SINT32.encodeWithTag(writer, 403, value.default_sint32) ProtoAdapter.UINT32.encodeWithTag(writer, 402, value.default_uint32) ProtoAdapter.INT32.encodeWithTag(writer, 401, value.default_int32) NestedEnum.ADAPTER.asPacked().encodeWithTag(writer, 316, value.pack_nested_enum) ProtoAdapter.DOUBLE.asPacked().encodeWithTag(writer, 313, value.pack_double) ProtoAdapter.FLOAT.asPacked().encodeWithTag(writer, 312, value.pack_float) ProtoAdapter.BOOL.asPacked().encodeWithTag(writer, 311, value.pack_bool) ProtoAdapter.SFIXED64.asPacked().encodeWithTag(writer, 310, value.pack_sfixed64) ProtoAdapter.FIXED64.asPacked().encodeWithTag(writer, 309, value.pack_fixed64) ProtoAdapter.SINT64.asPacked().encodeWithTag(writer, 308, value.pack_sint64) ProtoAdapter.UINT64.asPacked().encodeWithTag(writer, 307, value.pack_uint64) ProtoAdapter.INT64.asPacked().encodeWithTag(writer, 306, value.pack_int64) ProtoAdapter.SFIXED32.asPacked().encodeWithTag(writer, 305, value.pack_sfixed32) ProtoAdapter.FIXED32.asPacked().encodeWithTag(writer, 304, value.pack_fixed32) ProtoAdapter.SINT32.asPacked().encodeWithTag(writer, 303, value.pack_sint32) ProtoAdapter.UINT32.asPacked().encodeWithTag(writer, 302, value.pack_uint32) ProtoAdapter.INT32.asPacked().encodeWithTag(writer, 301, value.pack_int32) NestedMessage.ADAPTER.asRepeated().encodeWithTag(writer, 217, value.rep_nested_message) NestedEnum.ADAPTER.asRepeated().encodeWithTag(writer, 216, value.rep_nested_enum) ProtoAdapter.BYTES.asRepeated().encodeWithTag(writer, 215, value.rep_bytes) ProtoAdapter.STRING.asRepeated().encodeWithTag(writer, 214, value.rep_string) ProtoAdapter.DOUBLE.asRepeated().encodeWithTag(writer, 213, value.rep_double) ProtoAdapter.FLOAT.asRepeated().encodeWithTag(writer, 212, value.rep_float) ProtoAdapter.BOOL.asRepeated().encodeWithTag(writer, 211, value.rep_bool) ProtoAdapter.SFIXED64.asRepeated().encodeWithTag(writer, 210, value.rep_sfixed64) ProtoAdapter.FIXED64.asRepeated().encodeWithTag(writer, 209, value.rep_fixed64) ProtoAdapter.SINT64.asRepeated().encodeWithTag(writer, 208, value.rep_sint64) ProtoAdapter.UINT64.asRepeated().encodeWithTag(writer, 207, value.rep_uint64) ProtoAdapter.INT64.asRepeated().encodeWithTag(writer, 206, value.rep_int64) ProtoAdapter.SFIXED32.asRepeated().encodeWithTag(writer, 205, value.rep_sfixed32) ProtoAdapter.FIXED32.asRepeated().encodeWithTag(writer, 204, value.rep_fixed32) ProtoAdapter.SINT32.asRepeated().encodeWithTag(writer, 203, value.rep_sint32) ProtoAdapter.UINT32.asRepeated().encodeWithTag(writer, 202, value.rep_uint32) ProtoAdapter.INT32.asRepeated().encodeWithTag(writer, 201, value.rep_int32) NestedMessage.ADAPTER.encodeWithTag(writer, 117, value.req_nested_message) NestedEnum.ADAPTER.encodeWithTag(writer, 116, value.req_nested_enum) ProtoAdapter.BYTES.encodeWithTag(writer, 115, value.req_bytes) ProtoAdapter.STRING.encodeWithTag(writer, 114, value.req_string) ProtoAdapter.DOUBLE.encodeWithTag(writer, 113, value.req_double) ProtoAdapter.FLOAT.encodeWithTag(writer, 112, value.req_float) ProtoAdapter.BOOL.encodeWithTag(writer, 111, value.req_bool) ProtoAdapter.SFIXED64.encodeWithTag(writer, 110, value.req_sfixed64) ProtoAdapter.FIXED64.encodeWithTag(writer, 109, value.req_fixed64) ProtoAdapter.SINT64.encodeWithTag(writer, 108, value.req_sint64) ProtoAdapter.UINT64.encodeWithTag(writer, 107, value.req_uint64) ProtoAdapter.INT64.encodeWithTag(writer, 106, value.req_int64) ProtoAdapter.SFIXED32.encodeWithTag(writer, 105, value.req_sfixed32) ProtoAdapter.FIXED32.encodeWithTag(writer, 104, value.req_fixed32) ProtoAdapter.SINT32.encodeWithTag(writer, 103, value.req_sint32) ProtoAdapter.UINT32.encodeWithTag(writer, 102, value.req_uint32) ProtoAdapter.INT32.encodeWithTag(writer, 101, value.req_int32) NestedMessage.ADAPTER.encodeWithTag(writer, 17, value.opt_nested_message) NestedEnum.ADAPTER.encodeWithTag(writer, 16, value.opt_nested_enum) ProtoAdapter.BYTES.encodeWithTag(writer, 15, value.opt_bytes) ProtoAdapter.STRING.encodeWithTag(writer, 14, value.opt_string) ProtoAdapter.DOUBLE.encodeWithTag(writer, 13, value.opt_double) ProtoAdapter.FLOAT.encodeWithTag(writer, 12, value.opt_float) ProtoAdapter.BOOL.encodeWithTag(writer, 11, value.opt_bool) ProtoAdapter.SFIXED64.encodeWithTag(writer, 10, value.opt_sfixed64) ProtoAdapter.FIXED64.encodeWithTag(writer, 9, value.opt_fixed64) ProtoAdapter.SINT64.encodeWithTag(writer, 8, value.opt_sint64) ProtoAdapter.UINT64.encodeWithTag(writer, 7, value.opt_uint64) ProtoAdapter.INT64.encodeWithTag(writer, 6, value.opt_int64) ProtoAdapter.SFIXED32.encodeWithTag(writer, 5, value.opt_sfixed32) ProtoAdapter.FIXED32.encodeWithTag(writer, 4, value.opt_fixed32) ProtoAdapter.SINT32.encodeWithTag(writer, 3, value.opt_sint32) ProtoAdapter.UINT32.encodeWithTag(writer, 2, value.opt_uint32) ProtoAdapter.INT32.encodeWithTag(writer, 1, value.opt_int32) } public override fun decode(reader: ProtoReader): AllTypes { var opt_int32: Int? = null var opt_uint32: Int? = null var opt_sint32: Int? = null var opt_fixed32: Int? = null var opt_sfixed32: Int? = null var opt_int64: Long? = null var opt_uint64: Long? = null var opt_sint64: Long? = null var opt_fixed64: Long? = null var opt_sfixed64: Long? = null var opt_bool: Boolean? = null var opt_float: Float? = null var opt_double: Double? = null var opt_string: String? = null var opt_bytes: ByteString? = null var opt_nested_enum: NestedEnum? = null var opt_nested_message: NestedMessage? = null var req_int32: Int? = null var req_uint32: Int? = null var req_sint32: Int? = null var req_fixed32: Int? = null var req_sfixed32: Int? = null var req_int64: Long? = null var req_uint64: Long? = null var req_sint64: Long? = null var req_fixed64: Long? = null var req_sfixed64: Long? = null var req_bool: Boolean? = null var req_float: Float? = null var req_double: Double? = null var req_string: String? = null var req_bytes: ByteString? = null var req_nested_enum: NestedEnum? = null var req_nested_message: NestedMessage? = null val rep_int32 = mutableListOf<Int>() val rep_uint32 = mutableListOf<Int>() val rep_sint32 = mutableListOf<Int>() val rep_fixed32 = mutableListOf<Int>() val rep_sfixed32 = mutableListOf<Int>() val rep_int64 = mutableListOf<Long>() val rep_uint64 = mutableListOf<Long>() val rep_sint64 = mutableListOf<Long>() val rep_fixed64 = mutableListOf<Long>() val rep_sfixed64 = mutableListOf<Long>() val rep_bool = mutableListOf<Boolean>() val rep_float = mutableListOf<Float>() val rep_double = mutableListOf<Double>() val rep_string = mutableListOf<String>() val rep_bytes = mutableListOf<ByteString>() val rep_nested_enum = mutableListOf<NestedEnum>() val rep_nested_message = mutableListOf<NestedMessage>() val pack_int32 = mutableListOf<Int>() val pack_uint32 = mutableListOf<Int>() val pack_sint32 = mutableListOf<Int>() val pack_fixed32 = mutableListOf<Int>() val pack_sfixed32 = mutableListOf<Int>() val pack_int64 = mutableListOf<Long>() val pack_uint64 = mutableListOf<Long>() val pack_sint64 = mutableListOf<Long>() val pack_fixed64 = mutableListOf<Long>() val pack_sfixed64 = mutableListOf<Long>() val pack_bool = mutableListOf<Boolean>() val pack_float = mutableListOf<Float>() val pack_double = mutableListOf<Double>() val pack_nested_enum = mutableListOf<NestedEnum>() var default_int32: Int? = null var default_uint32: Int? = null var default_sint32: Int? = null var default_fixed32: Int? = null var default_sfixed32: Int? = null var default_int64: Long? = null var default_uint64: Long? = null var default_sint64: Long? = null var default_fixed64: Long? = null var default_sfixed64: Long? = null var default_bool: Boolean? = null var default_float: Float? = null var default_double: Double? = null var default_string: String? = null var default_bytes: ByteString? = null var default_nested_enum: NestedEnum? = null val map_int32_int32 = mutableMapOf<Int, Int>() val map_string_string = mutableMapOf<String, String>() val map_string_message = mutableMapOf<String, NestedMessage>() val map_string_enum = mutableMapOf<String, NestedEnum>() var oneof_string: String? = null var oneof_int32: Int? = null var oneof_nested_message: NestedMessage? = null var ext_opt_int32: Int? = null var ext_opt_uint32: Int? = null var ext_opt_sint32: Int? = null var ext_opt_fixed32: Int? = null var ext_opt_sfixed32: Int? = null var ext_opt_int64: Long? = null var ext_opt_uint64: Long? = null var ext_opt_sint64: Long? = null var ext_opt_fixed64: Long? = null var ext_opt_sfixed64: Long? = null var ext_opt_bool: Boolean? = null var ext_opt_float: Float? = null var ext_opt_double: Double? = null var ext_opt_string: String? = null var ext_opt_bytes: ByteString? = null var ext_opt_nested_enum: NestedEnum? = null var ext_opt_nested_message: NestedMessage? = null val ext_rep_int32 = mutableListOf<Int>() val ext_rep_uint32 = mutableListOf<Int>() val ext_rep_sint32 = mutableListOf<Int>() val ext_rep_fixed32 = mutableListOf<Int>() val ext_rep_sfixed32 = mutableListOf<Int>() val ext_rep_int64 = mutableListOf<Long>() val ext_rep_uint64 = mutableListOf<Long>() val ext_rep_sint64 = mutableListOf<Long>() val ext_rep_fixed64 = mutableListOf<Long>() val ext_rep_sfixed64 = mutableListOf<Long>() val ext_rep_bool = mutableListOf<Boolean>() val ext_rep_float = mutableListOf<Float>() val ext_rep_double = mutableListOf<Double>() val ext_rep_string = mutableListOf<String>() val ext_rep_bytes = mutableListOf<ByteString>() val ext_rep_nested_enum = mutableListOf<NestedEnum>() val ext_rep_nested_message = mutableListOf<NestedMessage>() val ext_pack_int32 = mutableListOf<Int>() val ext_pack_uint32 = mutableListOf<Int>() val ext_pack_sint32 = mutableListOf<Int>() val ext_pack_fixed32 = mutableListOf<Int>() val ext_pack_sfixed32 = mutableListOf<Int>() val ext_pack_int64 = mutableListOf<Long>() val ext_pack_uint64 = mutableListOf<Long>() val ext_pack_sint64 = mutableListOf<Long>() val ext_pack_fixed64 = mutableListOf<Long>() val ext_pack_sfixed64 = mutableListOf<Long>() val ext_pack_bool = mutableListOf<Boolean>() val ext_pack_float = mutableListOf<Float>() val ext_pack_double = mutableListOf<Double>() val ext_pack_nested_enum = mutableListOf<NestedEnum>() val unknownFields = reader.forEachTag { tag -> when (tag) { 1 -> opt_int32 = ProtoAdapter.INT32.decode(reader) 2 -> opt_uint32 = ProtoAdapter.UINT32.decode(reader) 3 -> opt_sint32 = ProtoAdapter.SINT32.decode(reader) 4 -> opt_fixed32 = ProtoAdapter.FIXED32.decode(reader) 5 -> opt_sfixed32 = ProtoAdapter.SFIXED32.decode(reader) 6 -> opt_int64 = ProtoAdapter.INT64.decode(reader) 7 -> opt_uint64 = ProtoAdapter.UINT64.decode(reader) 8 -> opt_sint64 = ProtoAdapter.SINT64.decode(reader) 9 -> opt_fixed64 = ProtoAdapter.FIXED64.decode(reader) 10 -> opt_sfixed64 = ProtoAdapter.SFIXED64.decode(reader) 11 -> opt_bool = ProtoAdapter.BOOL.decode(reader) 12 -> opt_float = ProtoAdapter.FLOAT.decode(reader) 13 -> opt_double = ProtoAdapter.DOUBLE.decode(reader) 14 -> opt_string = ProtoAdapter.STRING.decode(reader) 15 -> opt_bytes = ProtoAdapter.BYTES.decode(reader) 16 -> try { opt_nested_enum = NestedEnum.ADAPTER.decode(reader) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 17 -> opt_nested_message = NestedMessage.ADAPTER.decode(reader) 101 -> req_int32 = ProtoAdapter.INT32.decode(reader) 102 -> req_uint32 = ProtoAdapter.UINT32.decode(reader) 103 -> req_sint32 = ProtoAdapter.SINT32.decode(reader) 104 -> req_fixed32 = ProtoAdapter.FIXED32.decode(reader) 105 -> req_sfixed32 = ProtoAdapter.SFIXED32.decode(reader) 106 -> req_int64 = ProtoAdapter.INT64.decode(reader) 107 -> req_uint64 = ProtoAdapter.UINT64.decode(reader) 108 -> req_sint64 = ProtoAdapter.SINT64.decode(reader) 109 -> req_fixed64 = ProtoAdapter.FIXED64.decode(reader) 110 -> req_sfixed64 = ProtoAdapter.SFIXED64.decode(reader) 111 -> req_bool = ProtoAdapter.BOOL.decode(reader) 112 -> req_float = ProtoAdapter.FLOAT.decode(reader) 113 -> req_double = ProtoAdapter.DOUBLE.decode(reader) 114 -> req_string = ProtoAdapter.STRING.decode(reader) 115 -> req_bytes = ProtoAdapter.BYTES.decode(reader) 116 -> try { req_nested_enum = NestedEnum.ADAPTER.decode(reader) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 117 -> req_nested_message = NestedMessage.ADAPTER.decode(reader) 201 -> rep_int32.add(ProtoAdapter.INT32.decode(reader)) 202 -> rep_uint32.add(ProtoAdapter.UINT32.decode(reader)) 203 -> rep_sint32.add(ProtoAdapter.SINT32.decode(reader)) 204 -> rep_fixed32.add(ProtoAdapter.FIXED32.decode(reader)) 205 -> rep_sfixed32.add(ProtoAdapter.SFIXED32.decode(reader)) 206 -> rep_int64.add(ProtoAdapter.INT64.decode(reader)) 207 -> rep_uint64.add(ProtoAdapter.UINT64.decode(reader)) 208 -> rep_sint64.add(ProtoAdapter.SINT64.decode(reader)) 209 -> rep_fixed64.add(ProtoAdapter.FIXED64.decode(reader)) 210 -> rep_sfixed64.add(ProtoAdapter.SFIXED64.decode(reader)) 211 -> rep_bool.add(ProtoAdapter.BOOL.decode(reader)) 212 -> rep_float.add(ProtoAdapter.FLOAT.decode(reader)) 213 -> rep_double.add(ProtoAdapter.DOUBLE.decode(reader)) 214 -> rep_string.add(ProtoAdapter.STRING.decode(reader)) 215 -> rep_bytes.add(ProtoAdapter.BYTES.decode(reader)) 216 -> try { rep_nested_enum.add(NestedEnum.ADAPTER.decode(reader)) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 217 -> rep_nested_message.add(NestedMessage.ADAPTER.decode(reader)) 301 -> pack_int32.add(ProtoAdapter.INT32.decode(reader)) 302 -> pack_uint32.add(ProtoAdapter.UINT32.decode(reader)) 303 -> pack_sint32.add(ProtoAdapter.SINT32.decode(reader)) 304 -> pack_fixed32.add(ProtoAdapter.FIXED32.decode(reader)) 305 -> pack_sfixed32.add(ProtoAdapter.SFIXED32.decode(reader)) 306 -> pack_int64.add(ProtoAdapter.INT64.decode(reader)) 307 -> pack_uint64.add(ProtoAdapter.UINT64.decode(reader)) 308 -> pack_sint64.add(ProtoAdapter.SINT64.decode(reader)) 309 -> pack_fixed64.add(ProtoAdapter.FIXED64.decode(reader)) 310 -> pack_sfixed64.add(ProtoAdapter.SFIXED64.decode(reader)) 311 -> pack_bool.add(ProtoAdapter.BOOL.decode(reader)) 312 -> pack_float.add(ProtoAdapter.FLOAT.decode(reader)) 313 -> pack_double.add(ProtoAdapter.DOUBLE.decode(reader)) 316 -> try { pack_nested_enum.add(NestedEnum.ADAPTER.decode(reader)) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 401 -> default_int32 = ProtoAdapter.INT32.decode(reader) 402 -> default_uint32 = ProtoAdapter.UINT32.decode(reader) 403 -> default_sint32 = ProtoAdapter.SINT32.decode(reader) 404 -> default_fixed32 = ProtoAdapter.FIXED32.decode(reader) 405 -> default_sfixed32 = ProtoAdapter.SFIXED32.decode(reader) 406 -> default_int64 = ProtoAdapter.INT64.decode(reader) 407 -> default_uint64 = ProtoAdapter.UINT64.decode(reader) 408 -> default_sint64 = ProtoAdapter.SINT64.decode(reader) 409 -> default_fixed64 = ProtoAdapter.FIXED64.decode(reader) 410 -> default_sfixed64 = ProtoAdapter.SFIXED64.decode(reader) 411 -> default_bool = ProtoAdapter.BOOL.decode(reader) 412 -> default_float = ProtoAdapter.FLOAT.decode(reader) 413 -> default_double = ProtoAdapter.DOUBLE.decode(reader) 414 -> default_string = ProtoAdapter.STRING.decode(reader) 415 -> default_bytes = ProtoAdapter.BYTES.decode(reader) 416 -> try { default_nested_enum = NestedEnum.ADAPTER.decode(reader) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 501 -> map_int32_int32.putAll(map_int32_int32Adapter.decode(reader)) 502 -> map_string_string.putAll(map_string_stringAdapter.decode(reader)) 503 -> map_string_message.putAll(map_string_messageAdapter.decode(reader)) 504 -> map_string_enum.putAll(map_string_enumAdapter.decode(reader)) 601 -> oneof_string = ProtoAdapter.STRING.decode(reader) 602 -> oneof_int32 = ProtoAdapter.INT32.decode(reader) 603 -> oneof_nested_message = NestedMessage.ADAPTER.decode(reader) 1001 -> ext_opt_int32 = ProtoAdapter.INT32.decode(reader) 1002 -> ext_opt_uint32 = ProtoAdapter.UINT32.decode(reader) 1003 -> ext_opt_sint32 = ProtoAdapter.SINT32.decode(reader) 1004 -> ext_opt_fixed32 = ProtoAdapter.FIXED32.decode(reader) 1005 -> ext_opt_sfixed32 = ProtoAdapter.SFIXED32.decode(reader) 1006 -> ext_opt_int64 = ProtoAdapter.INT64.decode(reader) 1007 -> ext_opt_uint64 = ProtoAdapter.UINT64.decode(reader) 1008 -> ext_opt_sint64 = ProtoAdapter.SINT64.decode(reader) 1009 -> ext_opt_fixed64 = ProtoAdapter.FIXED64.decode(reader) 1010 -> ext_opt_sfixed64 = ProtoAdapter.SFIXED64.decode(reader) 1011 -> ext_opt_bool = ProtoAdapter.BOOL.decode(reader) 1012 -> ext_opt_float = ProtoAdapter.FLOAT.decode(reader) 1013 -> ext_opt_double = ProtoAdapter.DOUBLE.decode(reader) 1014 -> ext_opt_string = ProtoAdapter.STRING.decode(reader) 1015 -> ext_opt_bytes = ProtoAdapter.BYTES.decode(reader) 1016 -> try { ext_opt_nested_enum = NestedEnum.ADAPTER.decode(reader) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 1017 -> ext_opt_nested_message = NestedMessage.ADAPTER.decode(reader) 1101 -> ext_rep_int32.add(ProtoAdapter.INT32.decode(reader)) 1102 -> ext_rep_uint32.add(ProtoAdapter.UINT32.decode(reader)) 1103 -> ext_rep_sint32.add(ProtoAdapter.SINT32.decode(reader)) 1104 -> ext_rep_fixed32.add(ProtoAdapter.FIXED32.decode(reader)) 1105 -> ext_rep_sfixed32.add(ProtoAdapter.SFIXED32.decode(reader)) 1106 -> ext_rep_int64.add(ProtoAdapter.INT64.decode(reader)) 1107 -> ext_rep_uint64.add(ProtoAdapter.UINT64.decode(reader)) 1108 -> ext_rep_sint64.add(ProtoAdapter.SINT64.decode(reader)) 1109 -> ext_rep_fixed64.add(ProtoAdapter.FIXED64.decode(reader)) 1110 -> ext_rep_sfixed64.add(ProtoAdapter.SFIXED64.decode(reader)) 1111 -> ext_rep_bool.add(ProtoAdapter.BOOL.decode(reader)) 1112 -> ext_rep_float.add(ProtoAdapter.FLOAT.decode(reader)) 1113 -> ext_rep_double.add(ProtoAdapter.DOUBLE.decode(reader)) 1114 -> ext_rep_string.add(ProtoAdapter.STRING.decode(reader)) 1115 -> ext_rep_bytes.add(ProtoAdapter.BYTES.decode(reader)) 1116 -> try { ext_rep_nested_enum.add(NestedEnum.ADAPTER.decode(reader)) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } 1117 -> ext_rep_nested_message.add(NestedMessage.ADAPTER.decode(reader)) 1201 -> ext_pack_int32.add(ProtoAdapter.INT32.decode(reader)) 1202 -> ext_pack_uint32.add(ProtoAdapter.UINT32.decode(reader)) 1203 -> ext_pack_sint32.add(ProtoAdapter.SINT32.decode(reader)) 1204 -> ext_pack_fixed32.add(ProtoAdapter.FIXED32.decode(reader)) 1205 -> ext_pack_sfixed32.add(ProtoAdapter.SFIXED32.decode(reader)) 1206 -> ext_pack_int64.add(ProtoAdapter.INT64.decode(reader)) 1207 -> ext_pack_uint64.add(ProtoAdapter.UINT64.decode(reader)) 1208 -> ext_pack_sint64.add(ProtoAdapter.SINT64.decode(reader)) 1209 -> ext_pack_fixed64.add(ProtoAdapter.FIXED64.decode(reader)) 1210 -> ext_pack_sfixed64.add(ProtoAdapter.SFIXED64.decode(reader)) 1211 -> ext_pack_bool.add(ProtoAdapter.BOOL.decode(reader)) 1212 -> ext_pack_float.add(ProtoAdapter.FLOAT.decode(reader)) 1213 -> ext_pack_double.add(ProtoAdapter.DOUBLE.decode(reader)) 1216 -> try { ext_pack_nested_enum.add(NestedEnum.ADAPTER.decode(reader)) } catch (e: ProtoAdapter.EnumConstantNotFoundException) { reader.addUnknownField(tag, FieldEncoding.VARINT, e.value.toLong()) } else -> reader.readUnknownField(tag) } } return AllTypes( opt_int32 = opt_int32, opt_uint32 = opt_uint32, opt_sint32 = opt_sint32, opt_fixed32 = opt_fixed32, opt_sfixed32 = opt_sfixed32, opt_int64 = opt_int64, opt_uint64 = opt_uint64, opt_sint64 = opt_sint64, opt_fixed64 = opt_fixed64, opt_sfixed64 = opt_sfixed64, opt_bool = opt_bool, opt_float = opt_float, opt_double = opt_double, opt_string = opt_string, opt_bytes = opt_bytes, opt_nested_enum = opt_nested_enum, opt_nested_message = opt_nested_message, req_int32 = req_int32 ?: throw missingRequiredFields(req_int32, "req_int32"), req_uint32 = req_uint32 ?: throw missingRequiredFields(req_uint32, "req_uint32"), req_sint32 = req_sint32 ?: throw missingRequiredFields(req_sint32, "req_sint32"), req_fixed32 = req_fixed32 ?: throw missingRequiredFields(req_fixed32, "req_fixed32"), req_sfixed32 = req_sfixed32 ?: throw missingRequiredFields(req_sfixed32, "req_sfixed32"), req_int64 = req_int64 ?: throw missingRequiredFields(req_int64, "req_int64"), req_uint64 = req_uint64 ?: throw missingRequiredFields(req_uint64, "req_uint64"), req_sint64 = req_sint64 ?: throw missingRequiredFields(req_sint64, "req_sint64"), req_fixed64 = req_fixed64 ?: throw missingRequiredFields(req_fixed64, "req_fixed64"), req_sfixed64 = req_sfixed64 ?: throw missingRequiredFields(req_sfixed64, "req_sfixed64"), req_bool = req_bool ?: throw missingRequiredFields(req_bool, "req_bool"), req_float = req_float ?: throw missingRequiredFields(req_float, "req_float"), req_double = req_double ?: throw missingRequiredFields(req_double, "req_double"), req_string = req_string ?: throw missingRequiredFields(req_string, "req_string"), req_bytes = req_bytes ?: throw missingRequiredFields(req_bytes, "req_bytes"), req_nested_enum = req_nested_enum ?: throw missingRequiredFields(req_nested_enum, "req_nested_enum"), req_nested_message = req_nested_message ?: throw missingRequiredFields(req_nested_message, "req_nested_message"), rep_int32 = rep_int32, rep_uint32 = rep_uint32, rep_sint32 = rep_sint32, rep_fixed32 = rep_fixed32, rep_sfixed32 = rep_sfixed32, rep_int64 = rep_int64, rep_uint64 = rep_uint64, rep_sint64 = rep_sint64, rep_fixed64 = rep_fixed64, rep_sfixed64 = rep_sfixed64, rep_bool = rep_bool, rep_float = rep_float, rep_double = rep_double, rep_string = rep_string, rep_bytes = rep_bytes, rep_nested_enum = rep_nested_enum, rep_nested_message = rep_nested_message, pack_int32 = pack_int32, pack_uint32 = pack_uint32, pack_sint32 = pack_sint32, pack_fixed32 = pack_fixed32, pack_sfixed32 = pack_sfixed32, pack_int64 = pack_int64, pack_uint64 = pack_uint64, pack_sint64 = pack_sint64, pack_fixed64 = pack_fixed64, pack_sfixed64 = pack_sfixed64, pack_bool = pack_bool, pack_float = pack_float, pack_double = pack_double, pack_nested_enum = pack_nested_enum, default_int32 = default_int32, default_uint32 = default_uint32, default_sint32 = default_sint32, default_fixed32 = default_fixed32, default_sfixed32 = default_sfixed32, default_int64 = default_int64, default_uint64 = default_uint64, default_sint64 = default_sint64, default_fixed64 = default_fixed64, default_sfixed64 = default_sfixed64, default_bool = default_bool, default_float = default_float, default_double = default_double, default_string = default_string, default_bytes = default_bytes, default_nested_enum = default_nested_enum, map_int32_int32 = map_int32_int32, map_string_string = map_string_string, map_string_message = map_string_message, map_string_enum = map_string_enum, oneof_string = oneof_string, oneof_int32 = oneof_int32, oneof_nested_message = oneof_nested_message, ext_opt_int32 = ext_opt_int32, ext_opt_uint32 = ext_opt_uint32, ext_opt_sint32 = ext_opt_sint32, ext_opt_fixed32 = ext_opt_fixed32, ext_opt_sfixed32 = ext_opt_sfixed32, ext_opt_int64 = ext_opt_int64, ext_opt_uint64 = ext_opt_uint64, ext_opt_sint64 = ext_opt_sint64, ext_opt_fixed64 = ext_opt_fixed64, ext_opt_sfixed64 = ext_opt_sfixed64, ext_opt_bool = ext_opt_bool, ext_opt_float = ext_opt_float, ext_opt_double = ext_opt_double, ext_opt_string = ext_opt_string, ext_opt_bytes = ext_opt_bytes, ext_opt_nested_enum = ext_opt_nested_enum, ext_opt_nested_message = ext_opt_nested_message, ext_rep_int32 = ext_rep_int32, ext_rep_uint32 = ext_rep_uint32, ext_rep_sint32 = ext_rep_sint32, ext_rep_fixed32 = ext_rep_fixed32, ext_rep_sfixed32 = ext_rep_sfixed32, ext_rep_int64 = ext_rep_int64, ext_rep_uint64 = ext_rep_uint64, ext_rep_sint64 = ext_rep_sint64, ext_rep_fixed64 = ext_rep_fixed64, ext_rep_sfixed64 = ext_rep_sfixed64, ext_rep_bool = ext_rep_bool, ext_rep_float = ext_rep_float, ext_rep_double = ext_rep_double, ext_rep_string = ext_rep_string, ext_rep_bytes = ext_rep_bytes, ext_rep_nested_enum = ext_rep_nested_enum, ext_rep_nested_message = ext_rep_nested_message, ext_pack_int32 = ext_pack_int32, ext_pack_uint32 = ext_pack_uint32, ext_pack_sint32 = ext_pack_sint32, ext_pack_fixed32 = ext_pack_fixed32, ext_pack_sfixed32 = ext_pack_sfixed32, ext_pack_int64 = ext_pack_int64, ext_pack_uint64 = ext_pack_uint64, ext_pack_sint64 = ext_pack_sint64, ext_pack_fixed64 = ext_pack_fixed64, ext_pack_sfixed64 = ext_pack_sfixed64, ext_pack_bool = ext_pack_bool, ext_pack_float = ext_pack_float, ext_pack_double = ext_pack_double, ext_pack_nested_enum = ext_pack_nested_enum, unknownFields = unknownFields ) } public override fun redact(`value`: AllTypes): AllTypes = value.copy( opt_nested_message = value.opt_nested_message?.let(NestedMessage.ADAPTER::redact), req_nested_message = NestedMessage.ADAPTER.redact(value.req_nested_message), rep_nested_message = value.rep_nested_message.redactElements(NestedMessage.ADAPTER), map_string_message = value.map_string_message.redactElements(NestedMessage.ADAPTER), oneof_nested_message = value.oneof_nested_message?.let(NestedMessage.ADAPTER::redact), ext_opt_nested_message = value.ext_opt_nested_message?.let(NestedMessage.ADAPTER::redact), ext_rep_nested_message = value.ext_rep_nested_message.redactElements(NestedMessage.ADAPTER), unknownFields = ByteString.EMPTY ) } private const val serialVersionUID: Long = 0L } public enum class NestedEnum( public override val `value`: Int, ) : WireEnum { UNKNOWN(0), A(1), ; public companion object { @JvmField public val ADAPTER: ProtoAdapter<NestedEnum> = object : EnumAdapter<NestedEnum>( NestedEnum::class, PROTO_2, NestedEnum.UNKNOWN ) { public override fun fromValue(`value`: Int): NestedEnum? = NestedEnum.fromValue(value) } @JvmStatic public fun fromValue(`value`: Int): NestedEnum? = when (value) { 0 -> UNKNOWN 1 -> A else -> null } } } public class NestedMessage( @field:WireField( tag = 1, adapter = "com.squareup.wire.ProtoAdapter#INT32", ) @JvmField public val a: Int? = null, unknownFields: ByteString = ByteString.EMPTY, ) : Message<NestedMessage, NestedMessage.Builder>(ADAPTER, unknownFields) { public override fun newBuilder(): Builder { val builder = Builder() builder.a = a builder.addUnknownFields(unknownFields) return builder } public override fun equals(other: Any?): Boolean { if (other === this) return true if (other !is NestedMessage) return false if (unknownFields != other.unknownFields) return false if (a != other.a) return false return true } public override fun hashCode(): Int { var result = super.hashCode if (result == 0) { result = unknownFields.hashCode() result = result * 37 + (a?.hashCode() ?: 0) super.hashCode = result } return result } public override fun toString(): String { val result = mutableListOf<String>() if (a != null) result += """a=$a""" return result.joinToString(prefix = "NestedMessage{", separator = ", ", postfix = "}") } public fun copy(a: Int? = this.a, unknownFields: ByteString = this.unknownFields): NestedMessage = NestedMessage(a, unknownFields) public class Builder : Message.Builder<NestedMessage, Builder>() { @JvmField public var a: Int? = null public fun a(a: Int?): Builder { this.a = a return this } public override fun build(): NestedMessage = NestedMessage( a = a, unknownFields = buildUnknownFields() ) } public companion object { @JvmField public val ADAPTER: ProtoAdapter<NestedMessage> = object : ProtoAdapter<NestedMessage>( FieldEncoding.LENGTH_DELIMITED, NestedMessage::class, "type.googleapis.com/squareup.proto2.AllTypes.NestedMessage", PROTO_2, null, "all_types_proto2.proto" ) { public override fun encodedSize(`value`: NestedMessage): Int { var size = value.unknownFields.size size += ProtoAdapter.INT32.encodedSizeWithTag(1, value.a) return size } public override fun encode(writer: ProtoWriter, `value`: NestedMessage): Unit { ProtoAdapter.INT32.encodeWithTag(writer, 1, value.a) writer.writeBytes(value.unknownFields) } public override fun encode(writer: ReverseProtoWriter, `value`: NestedMessage): Unit { writer.writeBytes(value.unknownFields) ProtoAdapter.INT32.encodeWithTag(writer, 1, value.a) } public override fun decode(reader: ProtoReader): NestedMessage { var a: Int? = null val unknownFields = reader.forEachTag { tag -> when (tag) { 1 -> a = ProtoAdapter.INT32.decode(reader) else -> reader.readUnknownField(tag) } } return NestedMessage( a = a, unknownFields = unknownFields ) } public override fun redact(`value`: NestedMessage): NestedMessage = value.copy( unknownFields = ByteString.EMPTY ) } private const val serialVersionUID: Long = 0L } } }
wire-library/wire-tests/src/jvmJsonKotlinTest/proto-kotlin/com/squareup/wire/proto2/alltypes/AllTypes.kt
810485065
package com.github.kurtyan.guitarchinahunter.fetcher import java.net.HttpURLConnection import java.net.URL import java.nio.charset.Charset /** * Created by yanke on 2016/4/19. */ class HttpGetter { val setGetMethodCallback: (HttpURLConnection) -> Unit = { it.setRequestMethod("GET") } val userAgentCallback: (HttpURLConnection) -> Unit = { it.setRequestProperty( "User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" ) } val connectionCallback = arrayListOf( setGetMethodCallback, userAgentCallback ) fun withConnectionCallback(callback: (HttpURLConnection) -> Unit):HttpGetter { connectionCallback.add(callback) return this } fun doGet(url: String): String { val conn = URL(url).openConnection() as HttpURLConnection connectionCallback.forEach { it.invoke(conn) } return conn.inputStream.bufferedReader(Charset.forName("utf-8")).readText() } }
src/main/java/com/github/kurtyan/guitarchinahunter/fetcher/HttpGetter.kt
3461918073
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.vimscript.model.expressions.operators.handlers.binary object GreaterOrEqualsHandler : BinaryOperatorWithIgnoreCaseOption(GreaterIgnoreCaseHandler, GreaterCaseSensitiveHandler)
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/expressions/operators/handlers/binary/GreaterOrEqualsHandler.kt
3736952475
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers.models.attention.attentionmechanism import com.kotlinnlp.simplednn.core.arrays.ParamsArray import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer import com.kotlinnlp.simplednn.core.layers.LayerParameters /** * The parameters of the layer of type AttentionLayer. * * @property inputSize the size of each element of the input sequence * @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot) * @param sparseInput whether the weights connected to the input are sparse or not */ class AttentionMechanismLayerParameters( inputSize: Int, weightsInitializer: Initializer? = GlorotInitializer(), private val sparseInput: Boolean = false ) : LayerParameters( inputSize = inputSize, outputSize = -1, // depends on the number of element in the input sequence weightsInitializer = weightsInitializer, biasesInitializer = null ) { companion object { /** * Private val used to serialize the class (needed by Serializable) */ @Suppress("unused") private const val serialVersionUID: Long = 1L } /** * The context vector trainable parameter. */ val contextVector = ParamsArray(inputSize) /** * The list of weights parameters. */ override val weightsList: List<ParamsArray> = listOf(this.contextVector) /** * The list of biases parameters. */ override val biasesList: List<ParamsArray> = listOf() /** * Initialize all parameters values. */ init { this.initialize() } }
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/models/attention/attentionmechanism/AttentionMechanismLayerParameters.kt
1095182990
package org.wordpress.android.imageeditor.crop import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import com.yalantis.ucrop.UCropFragment import com.yalantis.ucrop.UCropFragment.UCropResult import com.yalantis.ucrop.UCropFragmentCallback import org.wordpress.android.imageeditor.EditImageViewModel import org.wordpress.android.imageeditor.ImageEditor import org.wordpress.android.imageeditor.R import org.wordpress.android.imageeditor.crop.CropViewModel.CropResult import org.wordpress.android.imageeditor.crop.CropViewModel.ImageCropAndSaveState.ImageCropAndSaveFailedState import org.wordpress.android.imageeditor.crop.CropViewModel.ImageCropAndSaveState.ImageCropAndSaveStartState import org.wordpress.android.imageeditor.crop.CropViewModel.ImageCropAndSaveState.ImageCropAndSaveSuccessState import org.wordpress.android.imageeditor.crop.CropViewModel.UiState.UiLoadedState import org.wordpress.android.imageeditor.crop.CropViewModel.UiState.UiStartLoadingWithBundleState import org.wordpress.android.imageeditor.preview.PreviewImageFragment.Companion.ARG_EDIT_IMAGE_DATA import org.wordpress.android.imageeditor.utils.ToastUtils import org.wordpress.android.imageeditor.utils.ToastUtils.Duration /** * Container fragment for displaying third party crop fragment and done menu item. */ class CropFragment : Fragment(), UCropFragmentCallback { private lateinit var viewModel: CropViewModel private var doneMenu: MenuItem? = null private val navArgs: CropFragmentArgs by navArgs() companion object { private val TAG = CropFragment::class.java.simpleName const val CROP_RESULT = "crop_result" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = inflater.inflate(R.layout.crop_image_fragment, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initializeViewModels() } private fun initializeViewModels() { viewModel = ViewModelProvider(this).get(CropViewModel::class.java) setupObservers() viewModel.start( navArgs.inputFilePath, navArgs.outputFileExtension, navArgs.shouldReturnToPreviewScreen, requireContext().cacheDir, ImageEditor.instance ) } private fun setupObservers() { viewModel.uiState.observe(viewLifecycleOwner, Observer { uiState -> when (uiState) { is UiStartLoadingWithBundleState -> { showThirdPartyCropFragmentWithBundle(uiState.bundle) } is UiLoadedState -> { // Do nothing } } doneMenu?.isVisible = uiState.doneMenuVisible }) viewModel.cropAndSaveImageStateEvent.observe(viewLifecycleOwner, Observer { stateEvent -> stateEvent?.getContentIfNotHandled()?.let { state -> when (state) { is ImageCropAndSaveStartState -> { val thirdPartyCropFragment = childFragmentManager .findFragmentByTag(UCropFragment.TAG) as? UCropFragment if (thirdPartyCropFragment != null && thirdPartyCropFragment.isAdded) { thirdPartyCropFragment.cropAndSaveImage() } else { Log.e(TAG, "Cannot crop and save image as thirdPartyCropFragment is null or not added!") } } is ImageCropAndSaveFailedState -> { showCropError(state.errorResId) } is ImageCropAndSaveSuccessState -> { // Do nothing } } } }) viewModel.navigateBackWithCropResult.observe(viewLifecycleOwner, Observer { cropResult -> navigateBackWithCropResult(cropResult) }) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_crop_fragment, menu) doneMenu = menu.findItem(R.id.menu_done) } override fun onOptionsItemSelected(item: MenuItem): Boolean = if (item.itemId == R.id.menu_done) { viewModel.onDoneMenuClicked() true } else if (item.itemId == android.R.id.home) { if (navArgs.shouldReturnToPreviewScreen) { findNavController().popBackStack() true } else { super.onOptionsItemSelected(item) } } else { super.onOptionsItemSelected(item) } private fun showThirdPartyCropFragmentWithBundle(bundle: Bundle) { var thirdPartyCropFragment = childFragmentManager .findFragmentByTag(UCropFragment.TAG) as? UCropFragment if (thirdPartyCropFragment == null || !thirdPartyCropFragment.isAdded) { thirdPartyCropFragment = UCropFragment.newInstance(bundle) childFragmentManager.beginTransaction() .replace(R.id.fragment_container, thirdPartyCropFragment, UCropFragment.TAG) .disallowAddToBackStack() .commit() } } override fun loadingProgress(loading: Boolean) { viewModel.onLoadingProgress(loading) } override fun onCropFinish(result: UCropResult?) { result?.let { viewModel.onCropFinish(it.mResultCode, it.mResultData) } } private fun showCropError(errorResId: Int) { ToastUtils.showToast(context, getString(errorResId), Duration.LONG) } private fun navigateBackWithCropResult(cropResult: CropResult) { if (navArgs.shouldReturnToPreviewScreen) { val navController = findNavController() ViewModelProvider(requireActivity()).get(EditImageViewModel::class.java).setCropResult(cropResult) navController.popBackStack() } else { val resultData = viewModel.getOutputData(cropResult) activity?.let { it.setResult( cropResult.resultCode, Intent().apply { putParcelableArrayListExtra(ARG_EDIT_IMAGE_DATA, resultData) }) it.finish() } } } }
libs/image-editor/src/main/kotlin/org/wordpress/android/imageeditor/crop/CropFragment.kt
3342358625
package org.rust.ide.structure import com.intellij.ide.structureView.StructureViewModel import com.intellij.ide.structureView.StructureViewTreeElement import com.intellij.ide.structureView.TextEditorBasedStructureViewModel import com.intellij.openapi.editor.Editor import org.rust.lang.core.psi.RustFnItem import org.rust.lang.core.psi.RustImplMethod import org.rust.lang.core.psi.RustStructDeclField import org.rust.lang.core.psi.impl.RustFileImpl class RustStructureViewModel(editor: Editor?, file: RustFileImpl) : TextEditorBasedStructureViewModel(editor, file) , StructureViewModel.ElementInfoProvider { override fun getRoot() = RustFileTreeElement(psiFile) override fun getPsiFile(): RustFileImpl = super.getPsiFile() as RustFileImpl override fun isAlwaysShowsPlus(element: StructureViewTreeElement) = when(element.value) { is RustFileImpl -> true else -> false } override fun isAlwaysLeaf(element: StructureViewTreeElement) = when(element.value) { is RustFnItem -> true is RustImplMethod -> true is RustStructDeclField -> true else -> false } }
src/main/kotlin/org/rust/ide/structure/RustStructureViewModel.kt
3248735111
// "Import" "false" // ACTION: Create extension function 'A.bar' // ACTION: Create function 'bar' // ACTION: Create member function 'A.bar' // ACTION: Rename reference // ERROR: Unresolved reference: bar package p open class A open class B : A() fun A.foo() { <caret>bar() } open class C { fun <T : B> T.bar() {} } object CObject : C()
plugins/kotlin/idea/tests/testData/quickfix/autoImports/callablesDeclaredInClasses/noImportGenericExtensionFunctionTypeConstraintWrongReceiver2.kt
3533469826
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.java import java.io.File /** * This file contains drafts of elements a new Java project model. */ /** Represents a set of source files written in JVM-based languages which have the same dependencies */ interface JvmSourceSet { val mode: Mode val sourceRoots: List<JvmSourceRoot> val outputRoots: List<FilePointer> val dependencies: List<JvmDependency> enum class Mode { /** The actual code is available as sources, they are compiled to output roots during build (corresponds to Module in old model) */ SOURCE, /** The actual code is available in compiled form under [outputRoots], [sourceRoots] (corresponds to Library/SDK in the old model) */ COMPILED } } interface JvmSourceRoot { val type: Type val file: FilePointer val generated: Boolean /** Corresponds to package prefix for source roots */ val relativeOutputPath: String? enum class Type { SOURCE, RESOURCES } } interface FilePointer { val url: String val file: File } interface Reference<T> { /** Not whether we need to store unresolvable references in the model, maybe there is a better way to store incorrect elements */ val resolved: T? /** This name is used to show error message if the reference cannot be resolved */ val displayName: String } interface JvmDependency { val target: Reference<JvmSourceSet> /** Not sure about this part */ val includedAtRuntime: Boolean val includedForCompilation: Boolean val exported: Boolean } /** * Represents a source set which contains tests. May be contain reference to a source set which contains production code which is tested here. */ interface JvmTestSourceSet : JvmSourceSet { val productionSourceSet: Reference<JvmSourceSet>? } /** * Qualified name (including the project name) of a source set imported from Gradle. */ val JvmSourceSet.gradleQualifiedName: String get() = TODO() /** * Name of a manually created module provided by user. */ val JvmSourceSet.moduleName: String get() = TODO() /** * Returns maven coordinates if the source set is actually a library imported from a Maven repository */ val JvmSourceSet.mavenCoordinates: String get() = TODO() val JvmSourceSet.annotationRoot: List<FilePointer> get() = TODO() val JvmSourceSet.javadocRoot: List<FilePointer> get() = TODO()
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/java/javaModel.kt
3932393103
package net.nextpulse.jacumulus.requests.models /** * Enum representing the payment status of an invoice. */ enum class PaymentStatus constructor(private val value: Int) { Due(1), Paid(2); override fun toString(): String { return value.toString() } }
src/main/java/net/nextpulse/jacumulus/requests/models/PaymentStatus.kt
958768174
package org.thoughtcrime.securesms.keyboard.emoji import android.content.Context import org.signal.core.util.concurrent.SignalExecutors import org.thoughtcrime.securesms.components.emoji.EmojiPageModel import org.thoughtcrime.securesms.components.emoji.RecentEmojiPageModel import org.thoughtcrime.securesms.emoji.EmojiSource.Companion.latest import org.thoughtcrime.securesms.util.TextSecurePreferences import java.util.function.Consumer class EmojiKeyboardPageRepository(context: Context) { private val recentEmojiPageModel: RecentEmojiPageModel = RecentEmojiPageModel(context, TextSecurePreferences.RECENT_STORAGE_KEY) fun getEmoji(consumer: Consumer<List<EmojiPageModel>>) { SignalExecutors.BOUNDED.execute { val list = mutableListOf<EmojiPageModel>() list += recentEmojiPageModel list += latest.displayPages consumer.accept(list) } } }
app/src/main/java/org/thoughtcrime/securesms/keyboard/emoji/EmojiKeyboardPageRepository.kt
1961472932
package au.id.micolous.metrodroid.transit interface CardTransitFactory<T> { val allCards: List<CardInfo> get() = emptyList() fun parseTransitIdentity(card: T): TransitIdentity? fun parseTransitData(card: T): TransitData? fun check(card: T): Boolean val notice: String? get() = null }
src/commonMain/kotlin/au/id/micolous/metrodroid/transit/CardTransitFactory.kt
476095692
package instep.dao.sql import instep.dao.sql.dialect.AbstractDialect interface ResultSetColumnValueExtractor { fun extract(valueType: Class<*>, rs: AbstractDialect.ResultSet, colIndex: Int): Any? }
dao/src/main/kotlin/instep/dao/sql/ResultSetColumnValueExtractor.kt
2336614352
package dev.mfazio.abl.teams import dev.mfazio.abl.R data class UITeam( val team: Team, val logoId: Int, val primaryColorId: Int, val secondaryColorId: Int, val tertiaryColorId: Int ) { val teamId = team.id val location = team.city val nickname = team.nickname val teamName = "$location $nickname" val division = team.division companion object { val allTeams = listOf( UITeam(Team.Appleton, R.drawable.fi_ic_fox, R.color.appletonPrimary, R.color.appletonSecondary, R.color.appletonTertiary), UITeam(Team.Baraboo, R.drawable.fi_ic_circus, R.color.barabooPrimary, R.color.barabooSecondary, R.color.barabooTertiary), UITeam(Team.EauClaire, R.drawable.fi_ic_lake, R.color.eauClairePrimary, R.color.eauClaireSecondary, R.color.eauClaireTertiary), UITeam(Team.GreenBay, R.drawable.ic_skyline_logo, R.color.greenBayPrimary, R.color.greenBaySecondary, R.color.greenBayTertiary), UITeam(Team.LaCrosse, R.drawable.fi_ic_heart, R.color.laCrossePrimary, R.color.laCrosseSecondary, R.color.laCrosseTertiary), UITeam(Team.LakeDelton, R.drawable.fi_ic_sea, R.color.lakeDeltonPrimary, R.color.lakeDeltonSecondary, R.color.lakeDeltonTertiary), UITeam(Team.Madison, R.drawable.fi_ic_snow_sharp, R.color.madisonPrimary, R.color.madisonSecondary, R.color.madisonTertiary), UITeam(Team.Milwaukee, R.drawable.mke_flag, R.color.milwaukeePrimary, R.color.milwaukeeSecondary, R.color.milwaukeeTertiary), UITeam(Team.Pewaukee, R.drawable.fi_ic_crown, R.color.pewaukeePrimary, R.color.pewaukeeSecondary, R.color.pewaukeeTertiary), UITeam(Team.Shawano, R.drawable.fi_ic_swallow, R.color.shawanoPrimary, R.color.shawanoSecondary, R.color.shawanoTertiary), UITeam(Team.SpringGreen, R.drawable.fi_ic_theater, R.color.springGreenPrimary, R.color.springGreenSecondary, R.color.springGreenTertiary), UITeam(Team.SturgeonBay, R.drawable.fi_ic_walking_stick, R.color.sturgeonBayPrimary, R.color.sturgeonBaySecondary, R.color.sturgeonBayTertiary), UITeam(Team.Waukesha, R.drawable.fi_ic_electric_guitar, R.color.waukeshaPrimary, R.color.waukeshaSecondary, R.color.waukeshaTertiary), UITeam(Team.WisconsinRapids, R.drawable.fi_ic_cranberry, R.color.wiRapidsPrimary, R.color.wiRapidsSecondary, R.color.wiRapidsTertiary) ) @JvmStatic fun fromTeamId(teamId: String?) = allTeams.firstOrNull { uiTeam -> uiTeam.teamId == teamId } fun fromTeamIds(vararg teamIds: String) = teamIds.map { teamId -> fromTeamId(teamId) } } }
kotlin/kotlin-and-android-development-featuring-jetpack/chapter-11/app-code/app/src/main/java/dev/mfazio/abl/teams/UITeam.kt
3341652967
package net.squanchy.schedule.domain.view import org.threeten.bp.LocalDate data class Day(val id: String, val date: LocalDate)
app/src/main/java/net/squanchy/schedule/domain/view/Day.kt
2362302959
/* * 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. */ package io.sweers.catchup.ui.debug import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import io.sweers.catchup.ui.BindableAdapter internal class NetworkVarianceAdapter(context: Context) : BindableAdapter<Int>(context) { override fun getCount(): Int { return VALUES.size } override fun getItem(position: Int): Int { return VALUES[position] } override fun getItemId(position: Int): Long { return position.toLong() } override fun newView(inflater: LayoutInflater, position: Int, container: ViewGroup): View { return inflater.inflate(android.R.layout.simple_spinner_item, container, false) } override fun bindView(item: Int, position: Int, view: View) { val tv = view.findViewById<TextView>(android.R.id.text1) tv.text = "±$item%" } override fun newDropDownView( inflater: LayoutInflater, position: Int, container: ViewGroup ): View { return inflater.inflate(android.R.layout.simple_spinner_dropdown_item, container, false) } companion object { private val VALUES = intArrayOf(20, 40, 60) fun getPositionForValue(value: Int): Int { return VALUES.indices.firstOrNull { VALUES[it] == value } ?: 1 // Default to 40% if something changes. } } }
app/src/debug/kotlin/io/sweers/catchup/ui/debug/NetworkVarianceAdapter.kt
1534274401
package io.ipoli.android.quest.usecase import io.ipoli.android.common.UseCase import io.ipoli.android.quest.data.persistence.QuestRepository class RemoveAllCompletedFromBucketListUseCase(private val questRepository: QuestRepository) : UseCase<Unit, Unit> { override fun execute(parameters: Unit) { questRepository.removeAllUnscheduledCompleted() } }
app/src/main/java/io/ipoli/android/quest/usecase/RemoveAllCompletedFromBucketListUseCase.kt
203260761
package com.eden.orchid.swiftdoc.swift.members import com.eden.orchid.api.OrchidContext import com.eden.orchid.swiftdoc.swift.SwiftAttributes import com.eden.orchid.swiftdoc.swift.SwiftMember import com.eden.orchid.swiftdoc.swift.SwiftStatement import org.json.JSONObject class SwiftStaticMethod(context: OrchidContext, data: JSONObject, origin: SwiftStatement) : SwiftMember(context, data, "staticMethod", origin), SwiftAttributes { override lateinit var attributes: List<String> var name: String? = null override fun init() { super.init() initAttributes(data) name = data.optString("key.name") } }
plugins/OrchidSwiftdoc/src/main/kotlin/com/eden/orchid/swiftdoc/swift/members/SwiftStaticMethod.kt
2956540614
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.SymbolicEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractOneChild import com.intellij.workspaceModel.storage.impl.updateOneToAbstractOneChildOfParent import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class HeadAbstractionEntityImpl(val dataSource: HeadAbstractionEntityData) : HeadAbstractionEntity, WorkspaceEntityBase() { companion object { internal val CHILD_CONNECTION_ID: ConnectionId = ConnectionId.create(HeadAbstractionEntity::class.java, CompositeBaseEntity::class.java, ConnectionId.ConnectionType.ABSTRACT_ONE_TO_ONE, true) val connections = listOf<ConnectionId>( CHILD_CONNECTION_ID, ) } override val data: String get() = dataSource.data override val child: CompositeBaseEntity? get() = snapshot.extractOneToAbstractOneChild(CHILD_CONNECTION_ID, this) override val entitySource: EntitySource get() = dataSource.entitySource override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(result: HeadAbstractionEntityData?) : ModifiableWorkspaceEntityBase<HeadAbstractionEntity, HeadAbstractionEntityData>( result), HeadAbstractionEntity.Builder { constructor() : this(HeadAbstractionEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity HeadAbstractionEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // After adding entity data to the builder, we need to unbind it and move the control over entity data to builder // Builder may switch to snapshot at any moment and lock entity data to modification this.currentEntityData = null // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } if (!getEntityData().isDataInitialized()) { error("Field HeadAbstractionEntity#data should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as HeadAbstractionEntity if (this.entitySource != dataSource.entitySource) this.entitySource = dataSource.entitySource if (this.data != dataSource.data) this.data = dataSource.data if (parents != null) { } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData(true).entitySource = value changedProperty.add("entitySource") } override var data: String get() = getEntityData().data set(value) { checkModificationAllowed() getEntityData(true).data = value changedProperty.add("data") } override var child: CompositeBaseEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractOneChild(CHILD_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? CompositeBaseEntity } else { this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] as? CompositeBaseEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*, *> && value.diff == null) { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*, *> || value.diff != null)) { _diff.updateOneToAbstractOneChildOfParent(CHILD_CONNECTION_ID, this, value) } else { if (value is ModifiableWorkspaceEntityBase<*, *>) { value.entityLinks[EntityLink(false, CHILD_CONNECTION_ID)] = this } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(true, CHILD_CONNECTION_ID)] = value } changedProperty.add("child") } override fun getEntityClass(): Class<HeadAbstractionEntity> = HeadAbstractionEntity::class.java } } class HeadAbstractionEntityData : WorkspaceEntityData.WithCalculableSymbolicId<HeadAbstractionEntity>() { lateinit var data: String fun isDataInitialized(): Boolean = ::data.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): WorkspaceEntity.Builder<HeadAbstractionEntity> { val modifiable = HeadAbstractionEntityImpl.Builder(null) modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() return modifiable } override fun createEntity(snapshot: EntityStorage): HeadAbstractionEntity { return getCached(snapshot) { val entity = HeadAbstractionEntityImpl(this) entity.snapshot = snapshot entity.id = createEntityId() entity } } override fun symbolicId(): SymbolicEntityId<*> { return HeadAbstractionSymbolicId(data) } override fun getEntityInterface(): Class<out WorkspaceEntity> { return HeadAbstractionEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return HeadAbstractionEntity(data, entitySource) { } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as HeadAbstractionEntityData if (this.entitySource != other.entitySource) return false if (this.data != other.data) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this.javaClass != other.javaClass) return false other as HeadAbstractionEntityData if (this.data != other.data) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + data.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + data.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.sameForAllEntities = true } }
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/HeadAbstractionEntityImpl.kt
2183553728
// 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.core.script import com.intellij.openapi.application.Application import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.util.Key import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.kotlin.idea.core.script.configuration.cache.ScriptConfigurationSnapshot import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.NotNullableUserDataProperty import kotlin.script.experimental.api.ScriptDiagnostic @set: org.jetbrains.annotations.TestOnly var Application.isScriptChangesNotifierDisabled by NotNullableUserDataProperty( Key.create("SCRIPT_CHANGES_NOTIFIER_DISABLED"), true ) internal val logger = Logger.getInstance("#org.jetbrains.kotlin.idea.script") fun scriptingDebugLog(file: KtFile, message: () -> String) { scriptingDebugLog(file.originalFile.virtualFile, message) } fun scriptingDebugLog(file: VirtualFile? = null, message: () -> String) { if (logger.isDebugEnabled) { logger.debug("[KOTLIN_SCRIPTING] ${file?.let { file.path + " "} ?: ""}" + message()) } } fun scriptingInfoLog(message: String) { logger.info("[KOTLIN_SCRIPTING] $message") } fun scriptingWarnLog(message: String) { logger.warn("[KOTLIN_SCRIPTING] $message") } fun scriptingWarnLog(message: String, throwable: Throwable?) { logger.warn("[KOTLIN_SCRIPTING] $message", throwable) } fun scriptingErrorLog(message: String, throwable: Throwable?) { logger.error("[KOTLIN_SCRIPTING] $message", throwable) } fun logScriptingConfigurationErrors(file: VirtualFile, snapshot: ScriptConfigurationSnapshot) { if (snapshot.configuration == null) { scriptingWarnLog("Script configuration for file $file was not loaded") for (report in snapshot.reports) { if (report.severity >= ScriptDiagnostic.Severity.WARNING) { scriptingWarnLog(report.message, report.exception) } } } }
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/core/script/scriptUtils.kt
4145813994
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.bookmark.actions import com.intellij.icons.AllIcons.Actions.Checked import com.intellij.ide.bookmark.Bookmark import com.intellij.ide.bookmark.BookmarkBundle import com.intellij.ide.bookmark.BookmarkType import com.intellij.ide.bookmark.ui.GroupSelectDialog import com.intellij.openapi.actionSystem.* import com.intellij.openapi.editor.EditorGutter import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.util.SystemInfo import java.awt.event.MouseEvent import javax.swing.SwingUtilities fun checkMultipleSelectionAndDisableAction(event: AnActionEvent): Boolean { if (event.contextBookmarks != null) { event.presentation.isEnabledAndVisible = false return true } return false } internal class ToggleBookmarkAction : Toggleable, DumbAwareAction(BookmarkBundle.messagePointer("bookmark.toggle.action.text")) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(event: AnActionEvent) { if (event.contextBookmarks != null) { event.presentation.apply { isEnabledAndVisible = true text = BookmarkBundle.message("bookmark.add.multiple.action.text") } return } val manager = event.bookmarksManager val bookmark = event.contextBookmark val type = bookmark?.let { manager?.getType(it) } event.presentation.apply { isEnabledAndVisible = bookmark != null icon = when (event.place) { ActionPlaces.TOUCHBAR_GENERAL -> { Toggleable.setSelected(this, type != null) Checked } else -> null } text = when { !ActionPlaces.isPopupPlace(event.place) -> BookmarkBundle.message("bookmark.toggle.action.text") type != null -> BookmarkBundle.message("bookmark.delete.action.text") else -> BookmarkBundle.message("bookmark.add.action.text") } } } override fun actionPerformed(event: AnActionEvent) { val unexpectedGutterClick = (event.inputEvent as? MouseEvent)?.run { source is EditorGutter && isUnexpected } if (unexpectedGutterClick == true) return val bookmarks = event.contextBookmarks when { bookmarks != null -> addMultipleBookmarks(event, bookmarks) else -> addSingleBookmark(event) } } private fun addSingleBookmark(event: AnActionEvent) { val manager = event.bookmarksManager ?: return val bookmark = event.contextBookmark ?: return val type = manager.getType(bookmark) ?: BookmarkType.DEFAULT manager.toggle(bookmark, type) val selectedText = event.getData(CommonDataKeys.EDITOR)?.selectionModel?.selectedText if (!selectedText.isNullOrBlank()) { manager.getGroups(bookmark).forEach { group -> group.setDescription(bookmark, selectedText) } } } private fun addMultipleBookmarks(event: AnActionEvent, bookmarks: List<Bookmark>) { val manager = event.bookmarksManager ?: return val group = GroupSelectDialog(event.project, null, manager, manager.groups) .showAndGetGroup(false) ?: return bookmarks.forEach { group.add(it, BookmarkType.DEFAULT) } } private val MouseEvent.isUnexpected // see MouseEvent.isUnexpected in LineBookmarkProvider get() = !SwingUtilities.isLeftMouseButton(this) || isPopupTrigger || if (SystemInfo.isMac) !isMetaDown else !isControlDown init { isEnabledInModalContext = true } }
platform/lang-impl/src/com/intellij/ide/bookmark/actions/ToggleBookmarkAction.kt
1613653346
/* * Copyright (c) 2017 Lizhaotailang * * 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 io.github.tonnyl.mango.mvp /** * Created by lizhaotailang on 2017/6/24. * * Base presenter in MVP architecture. */ interface BasePresenter { fun subscribe() fun unsubscribe() }
app/src/main/java/io/github/tonnyl/mango/mvp/BasePresenter.kt
410079518
package org.roylance.yaclib.core.utilities import org.roylance.yaclib.YaclibModel object ArtifactoryUtilities { const val UploadScriptName = "upload.sh" const val UploadWheelScriptName = "uploadWheel.sh" fun buildUploadWheelScript(directory: String, dependency: YaclibModel.Dependency): String { val actualUrl = JavaUtilities.buildRepositoryUrl(dependency.pipRepository) val wheelName = PythonUtilities.buildWheelFileName(dependency) val initialTemplate = """#!/usr/bin/env bash if [ -z "$${JavaUtilities.ArtifactoryUserName}" ]; then ${InitUtilities.Curl} -u -X PUT "$actualUrl/${PythonUtilities.buildWheelUrl( dependency)}" -T $directory/$wheelName else ${InitUtilities.Curl} -u $${JavaUtilities.ArtifactoryUserName}:$${JavaUtilities.ArtifactoryPasswordName} -X PUT "$actualUrl/${PythonUtilities.buildWheelUrl( dependency)}" -T $directory/$wheelName fi """ return initialTemplate } fun buildUploadTarGzScript(directory: String, dependency: YaclibModel.Dependency): String { val actualUrl = JavaUtilities.buildRepositoryUrl(dependency.npmRepository) val tarFileName = buildTarFileName(dependency) val initialTemplate = """#!/usr/bin/env bash if [ -z "$${JavaUtilities.ArtifactoryUserName}" ]; then ${InitUtilities.Curl} -u -X PUT "$actualUrl/${buildTarUrl( dependency)}" -T $directory/$tarFileName else ${InitUtilities.Curl} -u $${JavaUtilities.ArtifactoryUserName}:$${JavaUtilities.ArtifactoryPasswordName} -X PUT "$actualUrl/${buildTarUrl( dependency)}" -T $directory/$tarFileName fi """ return initialTemplate } fun buildTarFileName(dependency: YaclibModel.Dependency): String { return "${dependency.group}.${dependency.name}.${dependency.majorVersion}.${dependency.minorVersion}.tar.gz" } fun buildTarUrl(dependency: YaclibModel.Dependency): String { return buildUrlName(dependency) + ".tar.gz" } fun replacePeriodWithForwardSlash(item: String): String { val newGroup = item.replace(".", "/") return newGroup } private fun buildUrlName(dependency: YaclibModel.Dependency): String { val newGroup = replacePeriodWithForwardSlash(dependency.group) return "$newGroup/${dependency.name}/${dependency.majorVersion}.${dependency.minorVersion}" } }
core/src/main/java/org/roylance/yaclib/core/utilities/ArtifactoryUtilities.kt
42178325
package com.darrenatherton.droidcommunity.features.main import com.darrenatherton.droidcommunity.base.presentation.BasePresenter import com.darrenatherton.droidcommunity.base.presentation.BaseView import com.darrenatherton.droidcommunity.common.injection.scope.PerScreen import javax.inject.Inject @PerScreen class MainPresenter @Inject constructor() : BasePresenter<MainPresenter.View>() { val FEED_TAB = 0 val CHAT_TAB = 1 val EVENTS_TAB = 2 override fun onViewAttached() { } override fun onViewDetached() { } fun onTabSelected(tab: Int) { when (tab) { FEED_TAB -> { performViewAction { setTitleForFeed() } performViewAction { enableSubscriptionsMenuSwipe() } } CHAT_TAB -> { performViewAction { setTitleForChat() } performViewAction { disableSubscriptionsMenuSwipe() } } EVENTS_TAB -> { performViewAction { setTitleForEvents() } performViewAction { disableSubscriptionsMenuSwipe() } } } } interface View : BaseView { fun setTitleForFeed() fun setTitleForChat() fun setTitleForEvents() fun enableSubscriptionsMenuSwipe() fun disableSubscriptionsMenuSwipe() } }
app/src/main/kotlin/com/darrenatherton/droidcommunity/features/main/MainPresenter.kt
3340107329
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openal.templates import org.lwjgl.generator.* import openal.* val AL_SOFT_gain_clamp_ex = "SOFTGainClampEx".nativeClassAL("SOFT_gain_clamp_ex") { documentation = """ Native bindings to the $specLinkOpenALSoft extension. This extension extends the gain clamping mechanism in standard AL. By default, OpenAL allows the source's and listener's #GAIN property to be set to any value that's greater-than or equal-to 0. The calculated source gain is clamped between its #MIN_GAIN and #MAX_GAIN properties after distance attenuation and the directional cone is applied, and before the listener gain is applied, however these two clamping properties are themselves restricted to being between 0 and 1 (inclusive). That behavior effectively nullifies any purpose of setting a source's gain being above 1, as the source's distance- and cone-related properties can be modified for the same effect. Oddly, the listener gain is applied to the source gain *after* the clamping, so it is still possible for the final calculated gain to exceed 1. On top of this, the spec allows an implementation the option to implicitly clamp the final calculated gain for the source as needed, but provides no means for applications to detect such behavior. This extension aims to fix those problems by removing the maximum limit for #MIN_GAIN and #MAX_GAIN, allowing applications to increase the effective source gain above 1. Additionally, it provides a query for the application to retrieve the implicit clamp level an implementation may put on the final calculated gain. """ IntConstant( "An implementation-defined maximum per-source gain limit (guaranteed to be at least 1).", "GAIN_LIMIT_SOFT"..0x200E ) }
modules/lwjgl/openal/src/templates/kotlin/openal/templates/AL_SOFT_gain_clamp_ex.kt
3247129334
package imgui.classes import glm_.i import glm_.max import imgui.ImGui import imgui.api.g /** Helper: Manually clip large list of items. * If you are submitting lots of evenly spaced items and you have a random access to the list, you can perform coarse * clipping based on visibility to save yourself from processing those items at all. * The clipper calculates the range of visible items and advance the cursor to compensate for the non-visible items we * have skipped. * (Dear ImGui already clip items based on their bounds but it needs to measure text size to do so, whereas manual * coarse clipping before submission makes this cost and your own data fetching/submission cost almost null) * ImGuiListClipper clipper; * clipper.Begin(1000); // We have 1000 elements, evenly spaced. * while (clipper.Step()) * for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++) * ImGui::Text("line number %d", i); * Generally what happens is: * - Clipper lets you process the first element (DisplayStart = 0, DisplayEnd = 1) regardless of it being visible or not. * - User code submit one element. * - Clipper can measure the height of the first element * - Clipper calculate the actual range of elements to display based on the current clipping rectangle, position the cursor before the first visible element. * - User code submit visible elements. */ class ListClipper { var displayStart = 0 var displayEnd = 0 val display get() = displayStart until displayEnd // [Internal] var itemsCount = -1 var stepNo = 0 var itemsFrozen = 0 var itemsHeight = 0f var startPosY = 0f fun dispose() = assert(itemsCount == -1) { "Forgot to call End(), or to Step() until false?" } /** Automatically called by constructor if you passed 'items_count' or by Step() in Step 1. * Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1 * Use case B: Begin() called from constructor with items_height>0 * FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still * support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style. */ fun begin(itemsCount: Int = -1, itemsHeight: Float = -1f) { val window = g.currentWindow!! g.currentTable?.let { table -> if (table.isInsideRow) table.endRow() } startPosY = window.dc.cursorPos.y this.itemsHeight = itemsHeight this.itemsCount = itemsCount itemsFrozen = 0 stepNo = 0 displayStart = -1 displayEnd = 0 } /** Automatically called on the last call of Step() that returns false. */ fun end() { if (itemsCount < 0) // Already ended return // In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user. if (itemsCount < Int.MAX_VALUE && displayStart >= 0) setCursorPosYAndSetupForPrevLine(startPosY + (itemsCount - itemsFrozen) * itemsHeight, itemsHeight) itemsCount = -1 stepNo = 3 } /** Call until it returns false. The DisplayStart/DisplayEnd fields will be set and you can process/draw those * items. */ fun step(): Boolean { val window = g.currentWindow!! val table = g.currentTable if (table != null && table.isInsideRow) table.endRow() // Reached end of list if (itemsCount == 0 || skipItemForListClipping) { end() return false } // Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height) if (stepNo == 0) { // While we are in frozen row state, keep displaying items one by one, unclipped // FIXME: Could be stored as a table-agnostic state. if (table != null && !table.isUnfrozenRows) { displayStart = itemsFrozen displayEnd = itemsFrozen + 1 itemsFrozen++ return true } startPosY = window.dc.cursorPos.y if (itemsHeight <= 0f) { // Submit the first item so we can measure its height (generally it is 0..1) displayStart = itemsFrozen displayEnd = itemsFrozen + 1 stepNo = 1 return true } // Already has item height (given by user in Begin): skip to calculating step displayStart = displayEnd stepNo = 2 } // Step 1: the clipper infer height from first element if (stepNo == 1) { assert(itemsHeight <= 0f) if (table != null) { val posY1 = table.rowPosY1 // Using this instead of StartPosY to handle clipper straddling the frozen row val posY2 = table.rowPosY2 // Using this instead of CursorPos.y to take account of tallest cell. itemsHeight = posY2 - posY1 window.dc.cursorPos.y = posY2 } else itemsHeight = window.dc.cursorPos.y - startPosY assert(itemsHeight > 0f) { "Unable to calculate item height! First item hasn't moved the cursor vertically!" } stepNo = 2 } // Reached end of list if (displayEnd >= itemsCount) { end() return false } // Step 2: calculate the actual range of elements to display, and position the cursor before the first element if (stepNo == 2) { assert(itemsHeight > 0f) val alreadySubmitted = displayEnd ImGui.calcListClipping(itemsCount - alreadySubmitted, itemsHeight) displayStart += alreadySubmitted displayEnd += alreadySubmitted // Seek cursor if (displayStart > alreadySubmitted) setCursorPosYAndSetupForPrevLine(startPosY + (displayStart - itemsFrozen) * itemsHeight, itemsHeight) stepNo = 3 return true } // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), // Advance the cursor to the end of the list and then returns 'false' to end the loop. if (stepNo == 3) { // Seek cursor if (itemsCount < Int.MAX_VALUE) setCursorPosYAndSetupForPrevLine(startPosY + (itemsCount - itemsFrozen) * itemsHeight, itemsHeight) // advance cursor itemsCount = -1 return false } error("game over") } companion object { fun setCursorPosYAndSetupForPrevLine(posY: Float, lineHeight: Float) { // Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor. // FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue. // The clipper should probably have a 4th step to display the last item in a regular manner. val window = g.currentWindow!! val offY = posY - window.dc.cursorPos.y window.dc.cursorPos.y = posY window.dc.cursorMaxPos.y = window.dc.cursorMaxPos.y max posY window.dc.cursorPosPrevLine.y = window.dc.cursorPos.y - lineHeight // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage. window.dc.prevLineSize.y = lineHeight - g.style.itemSpacing.y // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list. window.dc.currentColumns?.let { columns -> columns.lineMinY = window.dc.cursorPos.y // Setting this so that cell Y position are set properly } g.currentTable?.let { table -> if (table.isInsideRow) table.endRow() table.rowPosY2 = window.dc.cursorPos.y val rowIncrease = ((offY / lineHeight) + 0.5f).i //table->CurrentRow += row_increase; // Can't do without fixing TableEndRow() table.rowBgColorCounter += rowIncrease } } } } // FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell. // The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous. val skipItemForListClipping: Boolean get() = g.currentTable?.hostSkipItems ?: g.currentWindow!!.skipItems
core/src/main/kotlin/imgui/classes/ListClipper.kt
3376851538
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package openxr.templates import org.lwjgl.generator.* import openxr.* val KHR_composition_layer_cylinder = "KHRCompositionLayerCylinder".nativeClassXR("KHR_composition_layer_cylinder", type = "instance", postfix = "KHR") { documentation = """ The <a href="https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html\#XR_KHR_composition_layer_cylinder">XR_KHR_composition_layer_cylinder</a> extension. This extension adds an additional layer type where the XR runtime <b>must</b> map a texture stemming from a swapchain onto the inside of a cylinder section. It can be imagined much the same way a curved television display looks to a viewer. This is not a projection type of layer but rather an object-in-world type of layer, similar to ##XrCompositionLayerQuad. Only the interior of the cylinder surface <b>must</b> be visible; the exterior of the cylinder is not visible and <b>must</b> not be drawn by the runtime. The cylinder characteristics are specified by the following parameters: <pre><code> ￿ XrPosef pose; ￿ float radius; ￿ float centralAngle; ￿ float aspectRatio;</code></pre> These can be understood via the following diagram, which is a top-down view of a horizontally oriented cylinder. The aspect ratio drives how tall the cylinder will appear based on the other parameters. Typically the aspectRatio would be set to be the aspect ratio of the texture being used, so that it looks the same within the cylinder as it does in 2D. <ul> <li><em>r</em> — Radius</li> <li><em>a</em> — Central angle in <code>(0, 2π)</code></li> <li><em>p</em> — Origin of pose transform</li> <li><em>U</em>/<em>V</em> — UV coordinates</li> </ul> """ IntConstant( "The extension specification version.", "KHR_composition_layer_cylinder_SPEC_VERSION".."4" ) StringConstant( "The extension name.", "KHR_COMPOSITION_LAYER_CYLINDER_EXTENSION_NAME".."XR_KHR_composition_layer_cylinder" ) EnumConstant( "Extends {@code XrStructureType}.", "TYPE_COMPOSITION_LAYER_CYLINDER_KHR".."1000017000" ) }
modules/lwjgl/openxr/src/templates/kotlin/openxr/templates/KHR_composition_layer_cylinder.kt
3902691872
package org.thoughtcrime.securesms.components.settings.app.internal import org.thoughtcrime.securesms.emoji.EmojiFiles data class InternalSettingsState( val seeMoreUserDetails: Boolean, val gv2doNotCreateGv2Groups: Boolean, val gv2forceInvites: Boolean, val gv2ignoreServerChanges: Boolean, val gv2ignoreP2PChanges: Boolean, val disableAutoMigrationInitiation: Boolean, val disableAutoMigrationNotification: Boolean, val forceCensorship: Boolean, val callingServer: String, val useBuiltInEmojiSet: Boolean, val emojiVersion: EmojiFiles.Version?, val removeSenderKeyMinimium: Boolean, )
app/src/main/java/org/thoughtcrime/securesms/components/settings/app/internal/InternalSettingsState.kt
1285685015
package com.scavi.brainsqueeze.adventofcode class Day3TobogganTrajectory { private val TREE = '#' fun solve(map: List<String>, slopes: Array<Pair<Int, Int>>): Long { val results = mutableListOf<Long>() for (slope in slopes) { var x = 0 var treeCount = 0L for (i in map.indices step slope.second) { var row = map[i] // treeCount = if (row[x] == TREE) treeCount + 1 else treeCount if (row[x] == TREE) { treeCount += 1 } x = (x + slope.first) % row.length } results.add(treeCount) } // [57, 252, 64, 66, 43] // [252, 75, ...] return results.reduce { acc, i -> acc * i } } }
src/main/kotlin/com/scavi/brainsqueeze/adventofcode/Day3TobogganTrajectory.kt
2661115264
/* * Copyright (C) 2016-Present The MoonLake ([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 com.mcmoonlake.api.anvil import org.bukkit.entity.Player /** * ## AnvilWindowEvent (铁砧窗口事件) * * @see [AnvilWindowClickEvent] * @see [AnvilWindowCloseEvent] * @see [AnvilWindowInputEvent] * @see [AnvilWindowOpenEvent] * @author lgou2w * @since 2.0 * @constructor AnvilWindowEvent * @param anvilWindow Anvil window object for event. * @param anvilWindow 事件的铁砧窗口对象. * @param player Player object for event. * @param player 事件的玩家对象. */ abstract class AnvilWindowEvent( /** * * Anvil window object for current event. * * 当前事件的铁砧窗口对象. */ val anvilWindow: AnvilWindow, /** * * Player object for current event. * * 当前事件的玩家对象. */ val player: Player) { }
API/src/main/kotlin/com/mcmoonlake/api/anvil/AnvilWindowEvent.kt
1495409980
package dao.yuan.sen.gluttony.sqlite_module.operator import dao.yuan.sen.gluttony.Gluttony import dao.yuan.sen.gluttony.sqlite_module.annotation.PrimaryKey import dao.yuan.sen.gluttony.sqlite_module.condition import dao.yuan.sen.gluttony.sqlite_module.parser.classParser import org.jetbrains.anko.db.SelectQueryBuilder import org.jetbrains.anko.db.select import kotlin.reflect.declaredMemberProperties /** * Created by Administrator on 2016/11/28. */ /** * 根据 主键 查询数据 * */ inline fun <reified T : Any> T.findOneByKey(primaryKey: Any): T? { val mClass = this.javaClass.kotlin val name = "${mClass.simpleName}" var propertyName: String? = null mClass.declaredMemberProperties.forEach { if (it.annotations.map { it.annotationClass }.contains(PrimaryKey::class)) propertyName = it.name } if (propertyName == null) throw Exception("$name 类型没有设置PrimaryKey") return Gluttony.database.use { tryDo { select(name).apply { limit(1) condition { propertyName!! equalsData primaryKey } }.parseOpt(dao.yuan.sen.gluttony.sqlite_module.parser.classParser<T>()) }.let { when (it) { null, "no such table" -> null is T -> it else -> null } } } } inline fun <reified T : Any> T.findOne(crossinline functor: SelectQueryBuilder.() -> Unit): T? { val name = "${this.javaClass.kotlin.simpleName}" return Gluttony.database.use { tryDo { select(name).apply { limit(1) functor() }.parseOpt(classParser<T>()) }.let { when (it) { null, "no such table" -> null is T -> it else -> null } } } } inline fun <reified T : Any> T.findAll(crossinline functor: SelectQueryBuilder.() -> Unit): List<T> { val name = "${this.javaClass.kotlin.simpleName}" return Gluttony.database.use { tryDo { select(name).apply { functor() }.parseList(classParser<T>()) }.let { when (it) { null, "no such table" -> emptyList() is List<*> -> it as List<T> else -> emptyList() } } } }
gluttony/src/main/java/dao/yuan/sen/gluttony/sqlite_module/operator/sqlite_find.kt
2670289652
/* * Copyright 2016 Jasmine Villadarez * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jv.practice.notes.presentation.presenters import com.jv.practice.notes.presentation.views.BaseView abstract class Presenter<V : BaseView> { private lateinit var _view: V var view: V get() = _view set(value) { _view = value initializeView() } abstract fun onViewCreated() abstract fun onViewHidden() abstract fun onViewDestroyed() protected abstract fun initializeView() }
Notes/app/src/main/kotlin/com/jv/practice/notes/presentation/presenters/Presenter.kt
3862262504
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.codeinsight.actions import com.intellij.icons.AllIcons import com.intellij.ide.actions.CreateInDirectoryActionBase import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.LangDataKeys import com.intellij.openapi.application.runWriteAction import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiFile import org.editorconfig.language.filetype.EditorConfigFileConstants import org.editorconfig.language.messages.EditorConfigBundle class CreateEditorConfigFileAction : CreateInDirectoryActionBase( EditorConfigBundle.get("create.file.title"), EditorConfigBundle.get("create.file.description"), AllIcons.Nodes.Editorconfig ) { @Suppress("UsePropertyAccessSyntax") override fun actionPerformed(event: AnActionEvent) { val view = event.getData(LangDataKeys.IDE_VIEW) ?: return val directory = view.getOrChooseDirectory() ?: return val file = createOrFindEditorConfig(directory) view.selectElement(file) } private fun createOrFindEditorConfig(directory: PsiDirectory): PsiFile { val name = EditorConfigFileConstants.FILE_NAME val existing = directory.findFile(name) if (existing != null) return existing return runWriteAction { directory.createFile(".editorconfig") } } }
plugins/editorconfig/src/org/editorconfig/language/codeinsight/actions/CreateEditorConfigFileAction.kt
3382906954
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.psi.impl.search import com.intellij.model.search.SearchParameters import com.intellij.model.search.Searcher import com.intellij.model.search.impl.* import com.intellij.openapi.progress.* import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.Project import com.intellij.openapi.util.ClassExtension import com.intellij.openapi.util.Computable import com.intellij.psi.PsiElement import com.intellij.psi.search.LocalSearchScope import com.intellij.psi.search.PsiSearchHelper import com.intellij.psi.search.SearchSession import com.intellij.util.Processor import com.intellij.util.Query import com.intellij.util.SmartList import com.intellij.util.text.StringSearcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.produce import org.jetbrains.annotations.ApiStatus.Internal import java.util.* import kotlin.collections.component1 import kotlin.collections.component2 import kotlin.collections.set private val searchersExtension = ClassExtension<Searcher<*, *>>("com.intellij.searcher") @Suppress("UNCHECKED_CAST") internal fun <R : Any> searchers(parameters: SearchParameters<R>): List<Searcher<SearchParameters<R>, R>> { return searchersExtension.forKey(parameters.javaClass) as List<Searcher<SearchParameters<R>, R>> } internal val indicatorOrEmpty: ProgressIndicator get() = EmptyProgressIndicator.notNullize(ProgressIndicatorProvider.getGlobalProgressIndicator()) fun <R> runSearch(cs: CoroutineScope, project: Project, query: Query<R>): ReceiveChannel<R> { @Suppress("EXPERIMENTAL_API_USAGE") return cs.produce(capacity = Channel.UNLIMITED) { runUnderIndicator { runSearch(project, query, Processor { require(channel.trySend(it).isSuccess) true }) } } } @Internal fun <R> runSearch(project: Project, query: Query<out R>, processor: Processor<in R>): Boolean { val progress = indicatorOrEmpty var currentQueries: Collection<Query<out R>> = listOf(query) while (currentQueries.isNotEmpty()) { progress.checkCanceled() val layer = buildLayer(progress, project, currentQueries) when (val layerResult = layer.runLayer(processor)) { is LayerResult.Ok -> currentQueries = layerResult.subqueries is LayerResult.Stop -> return false } } return true } private fun <R> buildLayer(progress: ProgressIndicator, project: Project, queries: Collection<Query<out R>>): Layer<out R> { val queue: Queue<Query<out R>> = ArrayDeque() queue.addAll(queries) val queryRequests = SmartList<QueryRequest<*, R>>() val wordRequests = SmartList<WordRequest<R>>() while (queue.isNotEmpty()) { progress.checkCanceled() val query: Query<out R> = queue.remove() val primitives: Requests<R> = decompose(query) queryRequests.addAll(primitives.queryRequests) wordRequests.addAll(primitives.wordRequests) for (parametersRequest in primitives.parametersRequests) { progress.checkCanceled() handleParamRequest(progress, parametersRequest) { queue.offer(it) } } } return Layer(project, progress, queryRequests, wordRequests) } private fun <B, R> handleParamRequest(progress: ProgressIndicator, request: ParametersRequest<B, R>, queue: (Query<out R>) -> Unit) { val searchRequests: Collection<Query<out B>> = collectSearchRequests(request.params) for (query: Query<out B> in searchRequests) { progress.checkCanceled() queue(XQuery(query, request.transformation)) } } private fun <R : Any> collectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> { return DumbService.getInstance(parameters.project).runReadActionInSmartMode(Computable { if (parameters.areValid()) { doCollectSearchRequests(parameters) } else { emptyList() } }) } private fun <R : Any> doCollectSearchRequests(parameters: SearchParameters<R>): Collection<Query<out R>> { val queries = ArrayList<Query<out R>>() queries.add(SearchersQuery(parameters)) val searchers = searchers(parameters) for (searcher: Searcher<SearchParameters<R>, R> in searchers) { ProgressManager.checkCanceled() queries += searcher.collectSearchRequests(parameters) } return queries } private sealed class LayerResult<out T> { object Stop : LayerResult<Nothing>() class Ok<T>(val subqueries: Collection<Query<out T>>) : LayerResult<T>() } private class Layer<T>( private val project: Project, private val progress: ProgressIndicator, private val queryRequests: Collection<QueryRequest<*, T>>, private val wordRequests: Collection<WordRequest<T>> ) { private val myHelper = PsiSearchHelper.getInstance(project) as PsiSearchHelperImpl fun runLayer(processor: Processor<in T>): LayerResult<T> { val subQueries = Collections.synchronizedList(ArrayList<Query<out T>>()) val xProcessor = Processor<XResult<T>> { result -> when (result) { is ValueResult -> processor.process(result.value) is QueryResult -> { subQueries.add(result.query) true } } } if (!processQueryRequests(progress, queryRequests, xProcessor)) { return LayerResult.Stop } if (!processWordRequests(xProcessor)) { return LayerResult.Stop } return LayerResult.Ok(subQueries) } private fun processWordRequests(processor: Processor<in XResult<T>>): Boolean { if (wordRequests.isEmpty()) { return true } val allRequests: Collection<RequestAndProcessors> = distributeWordRequests(processor) val globals = SmartList<RequestAndProcessors>() val locals = SmartList<RequestAndProcessors>() for (requestAndProcessor: RequestAndProcessors in allRequests) { if (requestAndProcessor.request.searchScope is LocalSearchScope) { locals += requestAndProcessor } else { globals += requestAndProcessor } } return processGlobalRequests(globals) && processLocalRequests(locals) } private fun distributeWordRequests(processor: Processor<in XResult<T>>): Collection<RequestAndProcessors> { val theMap = LinkedHashMap< WordRequestInfo, Pair< MutableCollection<OccurrenceProcessor>, MutableMap<LanguageInfo, MutableCollection<OccurrenceProcessor>> > >() for (wordRequest: WordRequest<T> in wordRequests) { progress.checkCanceled() val occurrenceProcessor: OccurrenceProcessor = wordRequest.occurrenceProcessor(processor) val byRequest = theMap.getOrPut(wordRequest.searchWordRequest) { Pair(SmartList(), LinkedHashMap()) } val injectionInfo = wordRequest.injectionInfo if (injectionInfo == InjectionInfo.NoInjection || injectionInfo == InjectionInfo.IncludeInjections) { byRequest.first.add(occurrenceProcessor) } if (injectionInfo is InjectionInfo.InInjection || injectionInfo == InjectionInfo.IncludeInjections) { val languageInfo: LanguageInfo = if (injectionInfo is InjectionInfo.InInjection) { injectionInfo.languageInfo } else { LanguageInfo.NoLanguage } byRequest.second.getOrPut(languageInfo) { SmartList() }.add(occurrenceProcessor) } } return theMap.map { (wordRequest: WordRequestInfo, byRequest) -> progress.checkCanceled() val (hostProcessors, injectionProcessors) = byRequest RequestAndProcessors(wordRequest, RequestProcessors(hostProcessors, injectionProcessors)) } } private fun processGlobalRequests(globals: Collection<RequestAndProcessors>): Boolean { if (globals.isEmpty()) { return true } else if (globals.size == 1) { return processSingleRequest(globals.first()) } val globalsIds: Map<PsiSearchHelperImpl.TextIndexQuery, List<WordRequestInfo>> = globals.groupBy( { (request: WordRequestInfo, _) -> PsiSearchHelperImpl.TextIndexQuery.fromWord(request.word, request.isCaseSensitive, null) }, { (request: WordRequestInfo, _) -> progress.checkCanceled(); request } ) return myHelper.processGlobalRequests(globalsIds, progress, scopeProcessors(globals)) } private fun scopeProcessors(globals: Collection<RequestAndProcessors>): Map<WordRequestInfo, Processor<in PsiElement>> { val result = HashMap<WordRequestInfo, Processor<in PsiElement>>() for (requestAndProcessors: RequestAndProcessors in globals) { progress.checkCanceled() result[requestAndProcessors.request] = scopeProcessor(requestAndProcessors) } return result } private fun scopeProcessor(requestAndProcessors: RequestAndProcessors): Processor<in PsiElement> { val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors val searcher = StringSearcher(request.word, request.isCaseSensitive, true, false) val adapted = MyBulkOccurrenceProcessor(project, processors) return PsiSearchHelperImpl.localProcessor(searcher, adapted) } private fun processLocalRequests(locals: Collection<RequestAndProcessors>): Boolean { if (locals.isEmpty()) { return true } for (requestAndProcessors: RequestAndProcessors in locals) { progress.checkCanceled() if (!processSingleRequest(requestAndProcessors)) return false } return true } private fun processSingleRequest(requestAndProcessors: RequestAndProcessors): Boolean { val (request: WordRequestInfo, processors: RequestProcessors) = requestAndProcessors val options = EnumSet.of(PsiSearchHelperImpl.Options.PROCESS_ONLY_JAVA_IDENTIFIERS_IF_POSSIBLE) if (request.isCaseSensitive) options.add(PsiSearchHelperImpl.Options.CASE_SENSITIVE_SEARCH) return myHelper.bulkProcessElementsWithWord( request.searchScope, request.word, request.searchContext, options, request.containerName, SearchSession(), MyBulkOccurrenceProcessor(project, processors) ) } } private fun <R> processQueryRequests(progress: ProgressIndicator, requests: Collection<QueryRequest<*, R>>, processor: Processor<in XResult<R>>): Boolean { if (requests.isEmpty()) { return true } val map: Map<Query<*>, List<XTransformation<*, R>>> = requests.groupBy({ it.query }, { it.transformation }) for ((query: Query<*>, transforms: List<XTransformation<*, R>>) in map.iterator()) { progress.checkCanceled() @Suppress("UNCHECKED_CAST") if (!runQueryRequest(query as Query<Any>, transforms as Collection<XTransformation<Any, R>>, processor)) { return false } } return true } private fun <B, R> runQueryRequest(query: Query<out B>, transformations: Collection<Transformation<B, R>>, processor: Processor<in R>): Boolean { return query.forEach(fun(baseValue: B): Boolean { for (transformation: Transformation<B, R> in transformations) { for (resultValue: R in transformation(baseValue)) { if (!processor.process(resultValue)) { return false } } } return true }) } private data class RequestAndProcessors( val request: WordRequestInfo, val processors: RequestProcessors ) internal class RequestProcessors( val hostProcessors: Collection<OccurrenceProcessor>, val injectionProcessors: Map<LanguageInfo, Collection<OccurrenceProcessor>> )
platform/indexing-impl/src/com/intellij/psi/impl/search/helper.kt
2002027258
fun foo(x: Any): Unit { <caret> }
plugins/kotlin/live-templates/tests/testData/fun1.exp.kt
852737325
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license * MACHINE GENERATED FILE, DO NOT EDIT */ package vulkan.templates import org.lwjgl.generator.* import vulkan.* val EXT_external_memory_dma_buf = "EXTExternalMemoryDmaBuf".nativeClassVK("EXT_external_memory_dma_buf", type = "device", postfix = "EXT") { documentation = """ A {@code dma_buf} is a type of file descriptor, defined by the Linux kernel, that allows sharing memory across kernel device drivers and across processes. This extension enables applications to import a {@code dma_buf} as {@code VkDeviceMemory}, to export {@code VkDeviceMemory} as a {@code dma_buf}, and to create {@code VkBuffer} objects that <b>can</b> be bound to that memory. <h5>VK_EXT_external_memory_dma_buf</h5> <dl> <dt><b>Name String</b></dt> <dd>{@code VK_EXT_external_memory_dma_buf}</dd> <dt><b>Extension Type</b></dt> <dd>Device extension</dd> <dt><b>Registered Extension Number</b></dt> <dd>126</dd> <dt><b>Revision</b></dt> <dd>1</dd> <dt><b>Extension and Version Dependencies</b></dt> <dd><ul> <li>Requires support for Vulkan 1.0</li> <li>Requires {@link KHRExternalMemoryFd VK_KHR_external_memory_fd} to be enabled for any device-level functionality</li> </ul></dd> <dt><b>Contact</b></dt> <dd><ul> <li>Chad Versace <a target="_blank" href="https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_external_memory_dma_buf]%20@chadversary%250A%3C%3CHere%20describe%20the%20issue%20or%20question%20you%20have%20about%20the%20VK_EXT_external_memory_dma_buf%20extension%3E%3E">chadversary</a></li> </ul></dd> </dl> <h5>Other Extension Metadata</h5> <dl> <dt><b>Last Modified Date</b></dt> <dd>2017-10-10</dd> <dt><b>IP Status</b></dt> <dd>No known IP claims.</dd> <dt><b>Contributors</b></dt> <dd><ul> <li>Chad Versace, Google</li> <li>James Jones, NVIDIA</li> <li>Jason Ekstrand, Intel</li> </ul></dd> </dl> """ IntConstant( "The extension specification version.", "EXT_EXTERNAL_MEMORY_DMA_BUF_SPEC_VERSION".."1" ) StringConstant( "The extension name.", "EXT_EXTERNAL_MEMORY_DMA_BUF_EXTENSION_NAME".."VK_EXT_external_memory_dma_buf" ) EnumConstant( "Extends {@code VkExternalMemoryHandleTypeFlagBits}.", "EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT".enum(0x00000200) ) }
modules/lwjgl/vulkan/src/templates/kotlin/vulkan/templates/EXT_external_memory_dma_buf.kt
722382577
object Dependencies { const val androidPlugin = "com.android.tools.build:gradle:${Versions.androidPlugin}" const val appCompat = "com.android.support:appcompat-v7:${Versions.supportLibrary}" const val assertJAndroid = "com.squareup.assertj:assertj-android:${Versions.assertJAndroid}" const val cardView = "com.android.support:cardview-v7:${Versions.supportLibrary}" const val constraintLayout = "com.android.support.constraint:constraint-layout:${Versions.constraintLayout}" const val crashlytics = "com.crashlytics.sdk.android:crashlytics:${Versions.crashlytics}" const val customTabs = "com.android.support:customtabs:${Versions.supportLibrary}" const val design = "com.android.support:design:${Versions.supportLibrary}" const val fabricPlugin = "io.fabric.tools:gradle:${Versions.fabricPlugin}" const val fastscroll = "com.futuremind.recyclerfastscroll:fastscroll:${Versions.fastscroll}" const val firebaseAnalytics = "com.google.firebase:firebase-analytics:${Versions.firebase}" const val firebaseCore = "com.google.firebase:firebase-core:${Versions.firebase}" const val firebaseJobDispatcher = "com.firebase:firebase-jobdispatcher:${Versions.firebaseJobDispatcher}" const val glide = "com.github.bumptech.glide:glide:${Versions.glide}" const val glideOkHttp = "com.github.bumptech.glide:okhttp-integration:${Versions.glide}" const val googleServicesPlugin = "com.google.gms:google-services:${Versions.googleServicesPlugin}" const val jacocoPlugin = "com.vanniktech:gradle-android-junit-jacoco-plugin:${Versions.jacocoPlugin}" const val jUnit = "junit:junit:${Versions.jUnit}" const val kotlin = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlinPlugin}" const val kotlinPlugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlinPlugin}" const val mediaRouter = "com.android.support:mediarouter-v7:${Versions.supportLibrary}" const val mockito = "org.mockito:mockito-core:${Versions.mockito}" const val okHttp = "com.squareup.okhttp:okhttp:${Versions.okHttp}" const val okHttpUrlConnection = "com.squareup.okhttp:okhttp-urlconnection:${Versions.okHttp}" const val palette = "com.android.support:palette-v7:${Versions.supportLibrary}" const val playServicesCast = "com.google.android.gms:play-services-cast:${Versions.playServicesCast}" const val preferences = "com.takisoft.fix:preference-v7:${Versions.preferences}" const val realmAdapters = "io.realm:android-adapters:${Versions.realmAdapters}" const val realmPlugin = "io.realm:realm-gradle-plugin:${Versions.realmPlugin}" const val recyclerView = "com.android.support:recyclerview-v7:${Versions.supportLibrary}" const val retrofit = "com.squareup.retrofit:retrofit:${Versions.retrofit}" const val sonarQubePlugin = "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:${Versions.sonarQubePlugin}" const val supportAnnotations = "com.android.support:support-annotations:${Versions.supportLibrary}" const val supportTestLibraryRules = "com.android.support.test:rules:${Versions.supportTestLibrary}" const val supportTestLibraryRunner = "com.android.support.test:runner:${Versions.supportTestLibrary}" const val supportV4 = "com.android.support:support-v4:${Versions.supportLibrary}" const val supportVectorDrawable = "com.android.support:support-vector-drawable:${Versions.supportLibrary}" }
buildSrc/src/main/kotlin/Dependencies.kt
2260977522
package co.smartreceipts.android.tooltip.receipt.paymentmethods import android.content.Context import androidx.annotation.AnyThread import androidx.annotation.UiThread import co.smartreceipts.analytics.Analytics import co.smartreceipts.analytics.events.Events import co.smartreceipts.analytics.log.Logger import co.smartreceipts.android.R import co.smartreceipts.android.columns.ordering.CsvColumnsOrderer import co.smartreceipts.android.columns.ordering.PdfColumnsOrderer import co.smartreceipts.android.model.impl.columns.receipts.ReceiptColumnDefinitions import co.smartreceipts.android.settings.UserPreferenceManager import co.smartreceipts.android.settings.catalog.UserPreference import co.smartreceipts.android.tooltip.TooltipController import co.smartreceipts.android.tooltip.TooltipView import co.smartreceipts.android.tooltip.model.TooltipInteraction import co.smartreceipts.android.tooltip.model.TooltipMetadata import co.smartreceipts.android.tooltip.model.TooltipType import co.smartreceipts.android.tooltip.receipt.FirstReceiptQuestionsUserInteractionStore import co.smartreceipts.android.utils.rx.RxSchedulers import co.smartreceipts.core.di.scopes.FragmentScope import com.hadisatrio.optional.Optional import io.reactivex.Completable import io.reactivex.Scheduler import io.reactivex.Single import io.reactivex.functions.Consumer import javax.inject.Inject import javax.inject.Named /** * An implementation of the [TooltipController] contract, which presents a question to our users * about if they wish to enable the payment method tracking field (as this is not otherwise obvious * to new users, since it is hidden in the settings menu). */ @FragmentScope class FirstReceiptUsePaymentMethodsQuestionTooltipController @Inject constructor(private val context: Context, private val tooltipView: TooltipView, private val store: FirstReceiptQuestionsUserInteractionStore, private val userPreferenceManager: UserPreferenceManager, private val pdfColumnsOrderer: PdfColumnsOrderer, private val csvColumnsOrderer: CsvColumnsOrderer, private val analytics: Analytics, @Named(RxSchedulers.IO) private val scheduler: Scheduler) : TooltipController { @UiThread override fun shouldDisplayTooltip(): Single<Optional<TooltipMetadata>> { return store.hasUserInteractionWithPaymentMethodsQuestionOccurred() .subscribeOn(scheduler) .map { hasUserInteractionOccurred -> if (hasUserInteractionOccurred) { Logger.debug(this, "This user has interacted with the payment methods tracking question tooltip before. Ignoring.") return@map Optional.absent<TooltipMetadata>() } else { Logger.debug(this, "The user has not seen the payment methods tracking question before. Displaying...") return@map Optional.of(newTooltipMetadata()) } } } @AnyThread override fun handleTooltipInteraction(interaction: TooltipInteraction): Completable { return Single.just(interaction) .subscribeOn(scheduler) .doOnSuccess { Logger.info(this, "User interacted with the payment methods question: {}", interaction) } .flatMapCompletable { when (interaction) { TooltipInteraction.YesButtonClick -> { Completable.fromAction { userPreferenceManager[UserPreference.Receipts.UsePaymentMethods] = true store.setInteractionWithPaymentMethodsQuestionHasOccurred(true) analytics.record(Events.Informational.ClickedPaymentMethodsQuestionTipYes) } .andThen(pdfColumnsOrderer.insertColumnAfter(ReceiptColumnDefinitions.ActualDefinition.PAYMENT_METHOD, ReceiptColumnDefinitions.ActualDefinition.CATEGORY_CODE)) .andThen(csvColumnsOrderer.insertColumnAfter(ReceiptColumnDefinitions.ActualDefinition.PAYMENT_METHOD, ReceiptColumnDefinitions.ActualDefinition.CATEGORY_CODE)) } TooltipInteraction.NoButtonClick -> Completable.fromAction { userPreferenceManager[UserPreference.Receipts.UsePaymentMethods] = false store.setInteractionWithPaymentMethodsQuestionHasOccurred(true) analytics.record(Events.Informational.ClickedPaymentMethodsQuestionTipNo) } TooltipInteraction.CloseCancelButtonClick -> Completable.fromAction { store.setInteractionWithPaymentMethodsQuestionHasOccurred(true) } else -> Completable.complete() } } .doOnError { Logger.warn(this, "Failed to handle tooltip interaction for the payment methods question. Failing silently") } .onErrorComplete() } @UiThread override fun consumeTooltipInteraction(): Consumer<TooltipInteraction> { return Consumer { if (it == TooltipInteraction.CloseCancelButtonClick || it == TooltipInteraction.YesButtonClick || it == TooltipInteraction.NoButtonClick) { tooltipView.hideTooltip() } } } private fun newTooltipMetadata() : TooltipMetadata { return TooltipMetadata(TooltipType.FirstReceiptUsePaymentMethodsQuestion, context.getString(R.string.pref_receipt_use_payment_methods_title)) } }
app/src/main/java/co/smartreceipts/android/tooltip/receipt/paymentmethods/FirstReceiptUsePaymentMethodsQuestionTooltipController.kt
1381993858
package co.smartreceipts.android.tooltip.backup import android.preference.PreferenceManager import androidx.test.core.app.ApplicationProvider import co.smartreceipts.android.utils.TestLazy import io.reactivex.schedulers.Schedulers import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class AutomaticBackupRecoveryHintUserInteractionStoreTest { private lateinit var automaticBackupRecoveryHintUserInteractionStore: AutomaticBackupRecoveryHintUserInteractionStore private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(ApplicationProvider.getApplicationContext()) private val scheduler = Schedulers.trampoline() @Before fun setUp() { automaticBackupRecoveryHintUserInteractionStore = AutomaticBackupRecoveryHintUserInteractionStore(TestLazy.create(sharedPreferences), scheduler) } @After fun tearDown() { sharedPreferences.edit().clear().apply() } @Test fun hasUserInteractionOccurredDefaultsToFalse() { automaticBackupRecoveryHintUserInteractionStore.hasUserInteractionOccurred() .test() .await() .assertValue(false) .assertComplete() .assertNoErrors() } @Test fun setUserHasInteractedWithPrivacyPolicy() { automaticBackupRecoveryHintUserInteractionStore.setUserHasInteractedWithAutomaticBackupRecoveryHint(true) automaticBackupRecoveryHintUserInteractionStore.hasUserInteractionOccurred() .test() .await() .assertValue(true) .assertComplete() .assertNoErrors() val newInstance = AutomaticBackupRecoveryHintUserInteractionStore(TestLazy.create(sharedPreferences), scheduler) newInstance.hasUserInteractionOccurred() .test() .await() .assertValue(true) .assertComplete() .assertNoErrors() } }
app/src/test/java/co/smartreceipts/android/tooltip/backup/AutomaticBackupRecoveryHintUserInteractionStoreTest.kt
3522334657
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package git4idea.rebase import com.intellij.dvcs.DvcsUtil import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.Messages import com.intellij.openapi.vcs.ui.CommitMessage import com.intellij.util.LineSeparator import git4idea.branch.GitBranchUiHandler import git4idea.branch.GitBranchWorker import git4idea.branch.GitRebaseParams import git4idea.config.GitVersionSpecialty import git4idea.repo.GitRepository import git4idea.test.* import org.junit.Assume import org.mockito.Mockito import org.mockito.Mockito.`when` class GitSingleRepoRebaseTest : GitRebaseBaseTest() { private lateinit var repo: GitRepository override fun setUp() { super.setUp() repo = createRepository(projectPath) } fun `test simple case`() { repo.`diverge feature and master`() rebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test up-to-date`() { repo.`place feature above master`() rebaseOnMaster() assertSuccessfulRebaseNotification("feature is up-to-date with master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun test_ff() { repo.`place feature below master`() rebaseOnMaster() assertSuccessfulRebaseNotification("Fast-forwarded feature to master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test conflict resolver is shown`() { repo.`prepare simple conflict`() `do nothing on merge`() rebaseOnMaster() `assert merge dialog was shown`() } fun `test fail on 2nd commit should show notification with proposal to abort`() { repo.`make rebase fail on 2nd commit`() rebaseOnMaster() `assert unknown error notification with link to abort`() } fun `test multiple conflicts`() { build { master { 0("c.txt") 1("c.txt") } feature(0) { 2("c.txt") 3("c.txt") } } var conflicts = 0 vcsHelper.onMerge { conflicts++ repo.assertConflict("c.txt") repo.resolveConflicts() } rebaseOnMaster() assertEquals("Incorrect number of conflicting patches", 2, conflicts) repo.`assert feature rebased on master`() assertSuccessfulRebaseNotification("Rebased feature on master") } fun `test continue rebase after resolving all conflicts`() { repo.`prepare simple conflict`() vcsHelper.onMerge { repo.resolveConflicts() } rebaseOnMaster() assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test warning notification if conflicts were not resolved`() { repo.`prepare simple conflict`() `do nothing on merge`() rebaseOnMaster() `assert conflict not resolved notification`() repo.assertRebaseInProgress() } fun `test skip if user decides to skip`() { repo.`prepare simple conflict`() `do nothing on merge`() rebaseOnMaster() GitRebaseUtils.skipRebase(project) assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test rebase failed for unknown reason`() { repo.`diverge feature and master`() git.setShouldRebaseFail { true } rebaseOnMaster() `assert unknown error notification`() } fun `test propose to abort when rebase failed after continue`() { repo.`prepare simple conflict`() `do nothing on merge`() rebaseOnMaster() repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() repo.resolveConflicts() git.setShouldRebaseFail { true } GitRebaseUtils.continueRebase(project) `assert unknown error notification with link to abort`(true) repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() } fun `test local changes auto-saved initially`() { repo.`diverge feature and master`() val localChange = LocalChange(repo, "new.txt").generate() object : GitTestingRebaseProcess(project, simpleParams("master"), repo) { override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> { return listOf(repo) } }.rebase() assertSuccessfulRebaseNotification("Rebased feature on master") assertRebased(repo, "feature", "master") assertNoRebaseInProgress(repo) localChange.verify() } fun `test local changes are saved even if not detected initially`() { repo.`diverge feature and master`() val localChange = LocalChange(repo, "new.txt").generate() object : GitTestingRebaseProcess(project, simpleParams("master"), repo) { override fun getDirtyRoots(repositories: Collection<GitRepository>): Collection<GitRepository> { return emptyList() } }.rebase() assertSuccessfulRebaseNotification("Rebased feature on master") assertRebased(repo, "feature", "master") assertNoRebaseInProgress(repo) localChange.verify() } fun `test local changes are not restored in case of error even if nothing was rebased`() { repo.`diverge feature and master`() LocalChange(repo, "new.txt", "content").generate() git.setShouldRebaseFail { true } rebaseOnMaster() assertErrorNotification("Rebase Failed", """ $UNKNOWN_ERROR_TEXT<br/> Local changes were stashed before rebase. """) assertNoRebaseInProgress(repo) repo.assertNoLocalChanges() assertFalse(file("new.txt").exists()) } fun `test critical error should show notification and not restore local changes`() { repo.`diverge feature and master`() LocalChange(repo, "new.txt", "content").generate() git.setShouldRebaseFail { true } rebaseOnMaster() `assert unknown error notification with link to stash`() repo.assertNoLocalChanges() } fun `test successful retry from notification on critical error restores local changes`() { repo.`diverge feature and master`() val localChange = LocalChange(repo, "new.txt", "content").generate() var attempt = 0 git.setShouldRebaseFail { attempt == 0 } rebaseOnMaster() attempt++ vcsNotifier.lastNotification GitRebaseUtils.continueRebase(project) assertNoRebaseInProgress(repo) repo.`assert feature rebased on master`() localChange.verify() } fun `test local changes are restored after successful abort`() { repo.`prepare simple conflict`() val localChange = LocalChange(repo, "new.txt", "content").generate() `do nothing on merge`() dialogManager.onMessage { Messages.YES } rebaseOnMaster() `assert conflict not resolved notification with link to stash`() GitRebaseUtils.abort(project, EmptyProgressIndicator()) assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() localChange.verify() } fun `test local changes are not restored after failed abort`() { repo.`prepare simple conflict`() LocalChange(repo, "new.txt", "content").generate() `do nothing on merge`() dialogManager.onMessage { Messages.YES } rebaseOnMaster() `assert conflict not resolved notification with link to stash`() git.setShouldRebaseFail { true } GitRebaseUtils.abort(project, EmptyProgressIndicator()) repo.assertRebaseInProgress() repo.`assert feature not rebased on master`() repo.assertConflict("c.txt") assertErrorNotification("Rebase Abort Failed", """ unknown error<br/> $LOCAL_CHANGES_WARNING """) } // git rebase --continue should be either called from a commit dialog, either from the GitRebaseProcess. // both should prepare the working tree themselves by adding all necessary changes to the index. fun `test local changes in the conflicting file should lead to error on continue rebase`() { repo.`prepare simple conflict`() `do nothing on merge`() rebaseOnMaster() repo.assertConflict("c.txt") //manually resolve conflicts repo.resolveConflicts() file("c.txt").append("more changes after resolving") // forget to git add afterwards GitRebaseUtils.continueRebase(project) `assert error about unstaged file before continue rebase`("c.txt") repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() } fun `test local changes in some other file should lead to error on continue rebase`() { build { master { 0("d.txt") 1("c.txt") 2("c.txt") } feature(1) { 3("c.txt") } } `do nothing on merge`() rebaseOnMaster() repo.assertConflict("c.txt") //manually resolve conflicts repo.resolveConflicts() // add more changes to some other file file("d.txt").append("more changes after resolving") GitRebaseUtils.continueRebase(project) `assert error about unstaged file before continue rebase`("d.txt") repo.`assert feature not rebased on master`() repo.assertRebaseInProgress() } fun `test unresolved conflict should lead to conflict resolver with continue rebase`() { repo.`prepare simple conflict`() `do nothing on merge`() rebaseOnMaster() repo.assertConflict("c.txt") vcsHelper.onMerge { repo.resolveConflicts() } GitRebaseUtils.continueRebase(project) assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } fun `test skipped commit`() { build { master { 0("c.txt", "base") 1("c.txt", "\nmaster") } feature(0) { 2("c.txt", "feature", "commit to be skipped") 3() } } val hash2skip = DvcsUtil.getShortHash(git("log -2 --pretty=%H").lines()[1]) vcsHelper.onMerge { file("c.txt").write("base\nmaster") repo.resolveConflicts() } rebaseOnMaster() assertRebased(repo, "feature", "master") assertNoRebaseInProgress(repo) assertSuccessfulRebaseNotification( """ Rebased feature on master<br/> The following commit was skipped during rebase:<br/> <a>$hash2skip</a> commit to be skipped """) } fun `test interactive rebase stopped for editing`() { build { master { 0() 1() } feature(1) { 2() 3() } } git.setInteractiveRebaseEditor (TestGitImpl.InteractiveRebaseEditor({ it.lines().mapIndexed { i, s -> if (i != 0) s else s.replace("pick", "edit") }.joinToString(LineSeparator.getSystemLineSeparator().separatorString) }, null)) rebaseInteractively() assertSuccessfulNotification("Rebase Stopped for Editing", "") assertEquals("The repository must be in the 'SUSPENDED' state", repo, repositoryManager.ongoingRebaseSpec!!.ongoingRebase) GitRebaseUtils.continueRebase(project) assertSuccessfulRebaseNotification("Rebased feature on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } // IDEA-140568 fun `test git help comments are ignored when parsing interactive rebase`() { makeCommit("initial.txt") repo.update() val initialMessage = "Wrong message" val commit = file("a").create("initial").addCommit(initialMessage).details() git("config core.commentChar $") var receivedEntries: List<GitRebaseEntry>? = null val rebaseEditor = GitAutomaticRebaseEditor(project, commit.root, entriesEditor = { list -> receivedEntries = list list }, plainTextEditor = { it }) GitTestingRebaseProcess(project, GitRebaseParams.editCommits("HEAD^", rebaseEditor, false), repo).rebase() assertNotNull("Didn't get any rebase entries", receivedEntries) assertEquals("Rebase entries parsed incorrectly", listOf(GitRebaseEntry.Action.PICK), receivedEntries!!.map { it.action }) } // IDEA-176455 fun `test reword during interactive rebase writes commit message correctly`() { Assume.assumeTrue("Not testing: not possible to fix in Git prior to 1.8.2: ${vcs.version}", GitVersionSpecialty.KNOWS_CORE_COMMENT_CHAR.existsIn(vcs.version)) // IDEA-182044 makeCommit("initial.txt") repo.update() val initialMessage = "Wrong message" file("a").create("initial").addCommit(initialMessage).details() val newMessage = """ Subject #body starting with a hash """.trimIndent() git.setInteractiveRebaseEditor (TestGitImpl.InteractiveRebaseEditor({ it.lines().mapIndexed { i, s -> if (i != 0) s else s.replace("pick", "reword") }.joinToString(LineSeparator.getSystemLineSeparator().separatorString) }, null)) var receivedMessage : String? = null dialogManager.onDialog(GitRebaseUnstructuredEditor::class.java, { it -> receivedMessage = it.text val field = GitRebaseUnstructuredEditor::class.java.getDeclaredField("myTextEditor") field.isAccessible = true val commitMessage = field.get (it) as CommitMessage commitMessage.setText(newMessage) 0 }) rebaseInteractively("HEAD^") assertEquals("Initial message is incorrect", initialMessage, receivedMessage) assertLastMessage(newMessage) } fun `test cancel in interactive rebase should show no error notification`() { repo.`diverge feature and master`() dialogManager.onDialog(GitRebaseEditor::class.java) { DialogWrapper.CANCEL_EXIT_CODE } assertNoNotification() assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() } fun `test cancel in noop case should show no error notification`() { build { master { 0() 1() } feature(0) {} } dialogManager.onMessage { Messages.CANCEL } assertNoNotification() assertNoRebaseInProgress(repo) repo.`assert feature not rebased on master`() } private fun rebaseInteractively(revision: String = "master") { GitTestingRebaseProcess(project, GitRebaseParams(null, null, revision, true, false), repo).rebase() } fun `test checkout with rebase`() { repo.`diverge feature and master`() repo.git("checkout master") val uiHandler = Mockito.mock(GitBranchUiHandler::class.java) `when`(uiHandler.progressIndicator).thenReturn(EmptyProgressIndicator()) GitBranchWorker(project, git, uiHandler).rebaseOnCurrent(listOf(repo), "feature") assertSuccessfulRebaseNotification("Checked out feature and rebased it on master") repo.`assert feature rebased on master`() assertNoRebaseInProgress(repo) } private fun build(f: RepoBuilder.() -> Unit) { build(repo, f) } private fun rebaseOnMaster() { GitTestingRebaseProcess(project, simpleParams("master"), repo).rebase() } private fun simpleParams(newBase: String): GitRebaseParams { return GitRebaseParams(newBase) } internal fun file(path: String) = repo.file(path) }
plugins/git4idea/tests/git4idea/rebase/GitSingleRepoRebaseTest.kt
2970223196
package rst.pdftools.compare import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.isA import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File import java.io.InputStream class PdfCompareTest { val expectedFileNameBase = "blubber" val expectedFileName = "$expectedFileNameBase.jpg" lateinit var original: InputStream lateinit var original2: InputStream lateinit var changed: InputStream lateinit var lessPages: InputStream lateinit var small: InputStream @Rule @JvmField val folder = TemporaryFolder() lateinit var diffImageDir: File @Before fun setUp() { original = PdfCompareTest::class.java.getResource("original.pdf").openStream() original2 = PdfCompareTest::class.java.getResource("original.pdf").openStream() changed = PdfCompareTest::class.java.getResource("changed.pdf").openStream() lessPages = PdfCompareTest::class.java.getResource("lessPages.pdf").openStream() small = PdfCompareTest::class.java.getResource("small.pdf").openStream() diffImageDir = folder.newFolder() } @Test fun pdfWithIdenticalContent() { val comparator = PdfComparator(diffImageDir) val result = comparator.comparePdfs(original, original2, expectedFileName) assertNotNull(result) assertTrue(result is PdfCompareResult.Identical) } @Test fun pdfWithDifferentContent() { val comparator = PdfComparator(diffImageDir) val result = comparator.comparePdfs(original, changed, expectedFileName) assertNotNull(result) assertTrue(result is PdfCompareResult.ContentDiffers) val contentDiffers = result as PdfCompareResult.ContentDiffers assertEquals(5, contentDiffers.differentPages.size) assertPageContentDiffers(contentDiffers.differentPages[0], 0) assertPageContentDiffers(contentDiffers.differentPages[1], 1) assertPageContentDiffers(contentDiffers.differentPages[2], 2) assertPageContentDiffers(contentDiffers.differentPages[3], 3) assertPageContentDiffers(contentDiffers.differentPages[4], 4) } @Test fun pdfWithDifferentPageSize() { val comparator = PdfComparator(diffImageDir) val result = comparator.comparePdfs(original, small, expectedFileName) assertNotNull(result) assertThat(result, isA<PdfCompareResult.ContentDiffers>()) val contentDiffers = result as PdfCompareResult.ContentDiffers assertEquals(5, contentDiffers.differentPages.size) assertThat(contentDiffers.differentPages[0], isA<PdfPageCompareResult.SizeDiffers>()) assertThat(contentDiffers.differentPages[1], isA<PdfPageCompareResult.SizeDiffers>()) assertThat(contentDiffers.differentPages[2], isA<PdfPageCompareResult.SizeDiffers>()) assertThat(contentDiffers.differentPages[3], isA<PdfPageCompareResult.SizeDiffers>()) assertThat(contentDiffers.differentPages[4], isA<PdfPageCompareResult.SizeDiffers>()) } @Test fun pdfWithDifferentPageCount() { val comparator = PdfComparator(diffImageDir) val result = comparator.comparePdfs(original, lessPages, expectedFileName) assertNotNull(result) assertThat(result, isA<PdfCompareResult.PageCountDiffers>()) val pageCountDiffers = result as PdfCompareResult.PageCountDiffers assertEquals(5, pageCountDiffers.expectedPageCount) assertEquals(2, pageCountDiffers.actualPageCount) } private fun assertPageContentDiffers(differentPage: PdfPageCompareResult, pageIndex: Int) { assertThat(differentPage, isA<PdfPageCompareResult.ContentDiffers>()) val contentDiffers = differentPage as PdfPageCompareResult.ContentDiffers assertEquals("page index", pageIndex, contentDiffers.pageIndex) assertEquals( "${diffImageDir.invariantSeparatorsPath}/$expectedFileNameBase.page-$pageIndex-diff.png", contentDiffers.diffImageFile.invariantSeparatorsPath ) } }
src/test/kotlin/rst/pdftools/compare/PdfCompareTest.kt
1671231211
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.cloneDialog import com.intellij.collaboration.auth.AccountsListener import com.intellij.collaboration.auth.ui.CompactAccountsPanelFactory import com.intellij.collaboration.ui.CollaborationToolsUIUtil import com.intellij.collaboration.ui.util.JListHoveredRowMaterialiser import com.intellij.collaboration.util.ProgressIndicatorsProvider import com.intellij.dvcs.repo.ClonePathProvider import com.intellij.dvcs.ui.CloneDvcsValidationUtils import com.intellij.dvcs.ui.DvcsBundle.message import com.intellij.dvcs.ui.FilePathDocumentChildPathHandle import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vcs.CheckoutProvider import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.wm.IdeFocusManager import com.intellij.ui.* import com.intellij.ui.SingleSelectionModel import com.intellij.ui.components.JBList import com.intellij.ui.components.panels.Wrapper import com.intellij.ui.dsl.builder.panel import com.intellij.ui.dsl.gridLayout.HorizontalAlign import com.intellij.ui.dsl.gridLayout.VerticalAlign import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.UIUtil import com.intellij.util.ui.cloneDialog.AccountMenuItem import com.intellij.util.ui.cloneDialog.VcsCloneDialogUiSpec import git4idea.GitUtil import git4idea.checkout.GitCheckoutProvider import git4idea.commands.Git import git4idea.remote.GitRememberedInputs import org.jetbrains.annotations.Nls import org.jetbrains.plugins.github.GithubIcons import org.jetbrains.plugins.github.api.GHRepositoryCoordinates import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.ui.GHAccountsDetailsLoader import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException import org.jetbrains.plugins.github.exceptions.GithubMissingTokenException import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.util.* import java.awt.event.ActionEvent import java.nio.file.Paths import javax.swing.* import javax.swing.event.DocumentEvent import javax.swing.event.ListDataEvent import javax.swing.event.ListDataListener import kotlin.properties.Delegates internal abstract class GHCloneDialogExtensionComponentBase( private val project: Project, private val authenticationManager: GithubAuthenticationManager, private val executorManager: GithubApiRequestExecutorManager ) : VcsCloneDialogExtensionComponent() { private val LOG = GithubUtil.LOG private val githubGitHelper: GithubGitHelper = GithubGitHelper.getInstance() // UI private val wrapper: Wrapper = Wrapper() private val repositoriesPanel: DialogPanel private val repositoryList: JBList<GHRepositoryListItem> private val searchField: SearchTextField private val directoryField = TextFieldWithBrowseButton().apply { val fcd = FileChooserDescriptorFactory.createSingleFolderDescriptor() fcd.isShowFileSystemRoots = true fcd.isHideIgnored = false addBrowseFolderListener(message("clone.destination.directory.browser.title"), message("clone.destination.directory.browser.description"), project, fcd) } private val cloneDirectoryChildHandle = FilePathDocumentChildPathHandle .install(directoryField.textField.document, ClonePathProvider.defaultParentDirectoryPath(project, GitRememberedInputs.getInstance())) // state private val loader = GHCloneDialogRepositoryListLoaderImpl(executorManager) private var inLoginState = false private var selectedUrl by Delegates.observable<String?>(null) { _, _, _ -> onSelectedUrlChanged() } protected val content: JComponent get() = wrapper.targetComponent private val accountListModel: ListModel<GithubAccount> = createAccountsModel() init { repositoryList = JBList(loader.listModel).apply { cellRenderer = GHRepositoryListCellRenderer(ErrorHandler()) { accountListModel.itemsSet } isFocusable = false selectionModel = loader.listSelectionModel }.also { val mouseAdapter = GHRepositoryMouseAdapter(it) it.addMouseListener(mouseAdapter) it.addMouseMotionListener(mouseAdapter) it.addListSelectionListener { evt -> if (evt.valueIsAdjusting) return@addListSelectionListener updateSelectedUrl() } } //TODO: fix jumping selection in the presence of filter loader.addLoadingStateListener { repositoryList.setPaintBusy(loader.loading) } searchField = SearchTextField(false).also { it.addDocumentListener(object : DocumentAdapter() { override fun textChanged(e: DocumentEvent) = updateSelectedUrl() }) createFocusFilterFieldAction(it) } CollaborationToolsUIUtil.attachSearch(repositoryList, searchField) { when (it) { is GHRepositoryListItem.Repo -> it.repo.fullName is GHRepositoryListItem.Error -> "" } } val indicatorsProvider = ProgressIndicatorsProvider() @Suppress("LeakingThis") val parentDisposable: Disposable = this Disposer.register(parentDisposable, loader) Disposer.register(parentDisposable, indicatorsProvider) val accountDetailsLoader = GHAccountsDetailsLoader(indicatorsProvider) { try { executorManager.getExecutor(it) } catch (e: Exception) { null } } val accountsPanel = CompactAccountsPanelFactory(accountListModel, accountDetailsLoader) .create(GithubIcons.DefaultAvatar, VcsCloneDialogUiSpec.Components.avatarSize, AccountsPopupConfig()) repositoriesPanel = panel { row { cell(searchField.textEditor) .resizableColumn() .verticalAlign(VerticalAlign.FILL) .horizontalAlign(HorizontalAlign.FILL) cell(JSeparator(JSeparator.VERTICAL)) .verticalAlign(VerticalAlign.FILL) cell(accountsPanel) .verticalAlign(VerticalAlign.FILL) } row { scrollCell(repositoryList) .resizableColumn() .verticalAlign(VerticalAlign.FILL) .horizontalAlign(HorizontalAlign.FILL) }.resizableRow() row(GithubBundle.message("clone.dialog.directory.field")) { cell(directoryField) .horizontalAlign(HorizontalAlign.FILL) .validationOnApply { CloneDvcsValidationUtils.checkDirectory(it.text, it.textField) } } } repositoriesPanel.border = JBEmptyBorder(UIUtil.getRegularPanelInsets()) setupAccountsListeners() } private inner class ErrorHandler : GHRepositoryListCellRenderer.ErrorHandler { override fun getPresentableText(error: Throwable): @Nls String = when (error) { is GithubMissingTokenException -> GithubBundle.message("account.token.missing") is GithubAuthenticationException -> GithubBundle.message("credentials.invalid.auth.data", "") else -> GithubBundle.message("clone.error.load.repositories") } override fun getAction(account: GithubAccount, error: Throwable) = when (error) { is GithubAuthenticationException -> object : AbstractAction(GithubBundle.message("accounts.relogin")) { override fun actionPerformed(e: ActionEvent?) { switchToLogin(account) } } else -> object : AbstractAction(GithubBundle.message("retry.link")) { override fun actionPerformed(e: ActionEvent?) { loader.clear(account) loader.loadRepositories(account) } } } } protected abstract fun isAccountHandled(account: GithubAccount): Boolean protected fun getAccounts(): Set<GithubAccount> = accountListModel.itemsSet protected abstract fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent private fun setupAccountsListeners() { accountListModel.addListDataListener(object : ListDataListener { private var currentList by Delegates.observable(emptySet<GithubAccount>()) { _, oldValue, newValue -> val delta = CollectionDelta(oldValue, newValue) for (account in delta.removedItems) { loader.clear(account) } for (account in delta.newItems) { loader.loadRepositories(account) } if (newValue.isEmpty()) { switchToLogin(null) } else { switchToRepositories() } dialogStateListener.onListItemChanged() } init { currentList = accountListModel.itemsSet } override fun intervalAdded(e: ListDataEvent) { currentList = accountListModel.itemsSet } override fun intervalRemoved(e: ListDataEvent) { currentList = accountListModel.itemsSet } override fun contentsChanged(e: ListDataEvent) { for (i in e.index0..e.index1) { val account = accountListModel.getElementAt(i) loader.clear(account) loader.loadRepositories(account) } switchToRepositories() dialogStateListener.onListItemChanged() } }) } protected fun switchToLogin(account: GithubAccount?) { wrapper.setContent(createLoginPanel(account) { switchToRepositories() }) wrapper.repaint() inLoginState = true updateSelectedUrl() } private fun switchToRepositories() { wrapper.setContent(repositoriesPanel) wrapper.repaint() inLoginState = false updateSelectedUrl() } override fun getView() = wrapper override fun doValidateAll(): List<ValidationInfo> = (wrapper.targetComponent as? DialogPanel)?.validationsOnApply?.values?.flatten()?.mapNotNull { it.validate() } ?: emptyList() override fun doClone(checkoutListener: CheckoutProvider.Listener) { val parent = Paths.get(directoryField.text).toAbsolutePath().parent val destinationValidation = CloneDvcsValidationUtils.createDestination(parent.toString()) if (destinationValidation != null) { LOG.error("Unable to create destination directory", destinationValidation.message) GithubNotifications.showError(project, GithubNotificationIdsHolder.CLONE_UNABLE_TO_CREATE_DESTINATION_DIR, GithubBundle.message("clone.dialog.clone.failed"), GithubBundle.message("clone.error.unable.to.create.dest.dir")) return } val lfs = LocalFileSystem.getInstance() var destinationParent = lfs.findFileByIoFile(parent.toFile()) if (destinationParent == null) { destinationParent = lfs.refreshAndFindFileByIoFile(parent.toFile()) } if (destinationParent == null) { LOG.error("Clone Failed. Destination doesn't exist") GithubNotifications.showError(project, GithubNotificationIdsHolder.CLONE_UNABLE_TO_FIND_DESTINATION, GithubBundle.message("clone.dialog.clone.failed"), GithubBundle.message("clone.error.unable.to.find.dest")) return } val directoryName = Paths.get(directoryField.text).fileName.toString() val parentDirectory = parent.toAbsolutePath().toString() GitCheckoutProvider.clone(project, Git.getInstance(), checkoutListener, destinationParent, selectedUrl, directoryName, parentDirectory) } override fun onComponentSelected() { dialogStateListener.onOkActionNameChanged(GithubBundle.message("clone.button")) updateSelectedUrl() val focusManager = IdeFocusManager.getInstance(project) getPreferredFocusedComponent()?.let { focusManager.requestFocus(it, true) } } override fun getPreferredFocusedComponent(): JComponent? { return searchField } private fun updateSelectedUrl() { repositoryList.emptyText.clear() if (inLoginState) { selectedUrl = null return } val githubRepoPath = getGithubRepoPath(searchField.text) if (githubRepoPath != null) { selectedUrl = githubGitHelper.getRemoteUrl(githubRepoPath.serverPath, githubRepoPath.repositoryPath.owner, githubRepoPath.repositoryPath.repository) repositoryList.emptyText.appendText(GithubBundle.message("clone.dialog.text", selectedUrl!!)) return } val selectedValue = repositoryList.selectedValue if (selectedValue is GHRepositoryListItem.Repo) { selectedUrl = githubGitHelper.getRemoteUrl(selectedValue.account.server, selectedValue.repo.userName, selectedValue.repo.name) return } selectedUrl = null } private fun getGithubRepoPath(searchText: String): GHRepositoryCoordinates? { val url = searchText .trim() .removePrefix("git clone") .removeSuffix(".git") .trim() try { var serverPath = GithubServerPath.from(url) serverPath = GithubServerPath.from(serverPath.toUrl().removeSuffix(serverPath.suffix ?: "")) val githubFullPath = GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(url) ?: return null return GHRepositoryCoordinates(serverPath, githubFullPath) } catch (e: Throwable) { return null } } private fun onSelectedUrlChanged() { val urlSelected = selectedUrl != null dialogStateListener.onOkActionEnabled(urlSelected) if (urlSelected) { val path = StringUtil.trimEnd(ClonePathProvider.relativeDirectoryPathForVcsUrl(project, selectedUrl!!), GitUtil.DOT_GIT) cloneDirectoryChildHandle.trySetChildPath(path) } } private fun createAccountsModel(): ListModel<GithubAccount> { val model = CollectionListModel(authenticationManager.getAccounts().filter(::isAccountHandled)) authenticationManager.addListener(this, object : AccountsListener<GithubAccount> { override fun onAccountListChanged(old: Collection<GithubAccount>, new: Collection<GithubAccount>) { val oldList = old.filter(::isAccountHandled) val newList = new.filter(::isAccountHandled) val delta = CollectionDelta(oldList, newList) model.add(delta.newItems.toList()) for (account in delta.removedItems) { model.remove(account) } } override fun onAccountCredentialsChanged(account: GithubAccount) { if (!isAccountHandled(account)) return model.contentsChanged(account) } }) return model } private inner class AccountsPopupConfig : CompactAccountsPanelFactory.PopupConfig<GithubAccount> { override val avatarSize: Int = VcsCloneDialogUiSpec.Components.popupMenuAvatarSize override fun createActions(): Collection<AccountMenuItem.Action> = createAccountMenuLoginActions(null) } protected abstract fun createAccountMenuLoginActions(account: GithubAccount?): Collection<AccountMenuItem.Action> private fun createFocusFilterFieldAction(searchField: SearchTextField) { val action = DumbAwareAction.create { val focusManager = IdeFocusManager.getInstance(project) if (focusManager.getFocusedDescendantFor(repositoriesPanel) != null) { focusManager.requestFocus(searchField, true) } } val shortcuts = KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_FIND) action.registerCustomShortcutSet(shortcuts, repositoriesPanel, this) } companion object { internal val <E> ListModel<E>.items get() = Iterable { object : Iterator<E> { private var idx = -1 override fun hasNext(): Boolean = idx < size - 1 override fun next(): E { idx++ return getElementAt(idx) } } } internal val <E> ListModel<E>.itemsSet get() = items.toSet() } }
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogExtensionComponentBase.kt
656826404
/* * Copyright 2012-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 org.springframework.boot.docs.messaging.kafka.sending import org.springframework.kafka.core.KafkaTemplate import org.springframework.stereotype.Component @Component class MyBean(private val kafkaTemplate: KafkaTemplate<String, String>) { // @fold:on // ... fun someMethod() { kafkaTemplate.send("someTopic", "Hello") } // @fold:off }
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/messaging/kafka/sending/MyBean.kt
907247581
/** * This file is part of QuickBeer. * Copyright (C) 2017 Antti Poikela <[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 quickbeer.android.feature.styledetails import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import dagger.hilt.android.AndroidEntryPoint import quickbeer.android.R import quickbeer.android.data.state.State import quickbeer.android.databinding.StyleDetailsInfoFragmentBinding import quickbeer.android.domain.style.Style import quickbeer.android.navigation.NavParams import quickbeer.android.ui.base.BaseFragment import quickbeer.android.util.ktx.observe import quickbeer.android.util.ktx.viewBinding @AndroidEntryPoint class StyleDetailsInfoFragment : BaseFragment(R.layout.style_details_info_fragment) { private val binding by viewBinding(StyleDetailsInfoFragmentBinding::bind) private val viewModel by viewModels<StyleDetailsViewModel>() override fun observeViewState() { observe(viewModel.styleState) { state -> when (state) { is State.Initial -> Unit is State.Loading -> Unit is State.Empty -> Unit is State.Success -> setStyle(state.value) is State.Error -> Unit } } observe(viewModel.parentStyleState) { state -> when (state) { is State.Initial -> Unit is State.Loading -> Unit is State.Empty -> Unit is State.Success -> setParentStyle(state.value) is State.Error -> Unit } } } private fun setStyle(style: Style) { binding.description.value = style.description } private fun setParentStyle(style: Style) { binding.parent.value = style.name } companion object { fun create(styleId: Int): Fragment { return StyleDetailsInfoFragment().apply { arguments = bundleOf(NavParams.ID to styleId) } } } }
app/src/main/java/quickbeer/android/feature/styledetails/StyleDetailsInfoFragment.kt
2896118350