content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package net.perfectdreams.loritta.morenitta import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.debug.DebugProbes import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import mu.KotlinLogging import net.perfectdreams.loritta.cinnamon.discord.utils.RedisKeys import net.perfectdreams.loritta.cinnamon.discord.utils.metrics.InteractionsMetrics import net.perfectdreams.loritta.cinnamon.pudding.Pudding import net.perfectdreams.loritta.common.locale.LocaleManager import net.perfectdreams.loritta.common.locale.LorittaLanguageManager import net.perfectdreams.loritta.common.utils.HostnameUtils import net.perfectdreams.loritta.morenitta.utils.config.BaseConfig import net.perfectdreams.loritta.morenitta.utils.devious.GatewaySessionData import net.perfectdreams.loritta.morenitta.utils.readConfigurationFromFile import java.io.File import java.util.* import javax.imageio.ImageIO /** * Loritta's Launcher * * @author MrPowerGamerBR */ object LorittaLauncher { private val logger = KotlinLogging.logger {} @JvmStatic fun main(args: Array<String>) { // https://github.com/JetBrains/Exposed/issues/1356 TimeZone.setDefault(TimeZone.getTimeZone("UTC")) installCoroutinesDebugProbes() // Speeds up image loading/writing/etc // https://stackoverflow.com/a/44170254/7271796 ImageIO.setUseCache(false) val configurationFile = File(System.getProperty("conf") ?: "./loritta.conf") if (!configurationFile.exists()) { println("Welcome to Loritta Morenitta! :3") println("") println("I want to make the world a better place... helping people, making them laugh... I hope I succeed!") println("") println("Before we start, you need to configure me!") println("I created a file named \"loritta.conf\", there you can configure a lot of things and stuff related to me, open it on your favorite text editor and change it!") println("") println("After configuring the file, run me again!") copyFromJar("/loritta.conf", "./loritta.conf") copyFromJar("/emotes.conf", "./emotes.conf") System.exit(1) return } val config = readConfigurationFromFile<BaseConfig>(configurationFile) logger.info { "Loaded Loritta's configuration file" } val clusterId = if (config.loritta.clusters.getClusterIdFromHostname) { val hostname = HostnameUtils.getHostname() hostname.substringAfterLast("-").toIntOrNull() ?: error("Clusters are enabled, but I couldn't get the Cluster ID from the hostname!") } else { config.loritta.clusters.clusterIdOverride ?: 1 } val lorittaCluster = config.loritta.clusters.instances.first { it.id == clusterId } logger.info { "Loritta's Cluster ID: $clusterId (${lorittaCluster.name})" } InteractionsMetrics.registerJFRExports() InteractionsMetrics.registerInteractions() logger.info { "Registered Prometheus Metrics" } logger.info { "Loading languages..." } val languageManager = LorittaLanguageManager(LorittaBot::class) val localeManager = LocaleManager(LorittaBot::class).also { it.loadLocales() } val services = Pudding.createPostgreSQLPudding( config.loritta.pudding.address, config.loritta.pudding.database, config.loritta.pudding.username, config.loritta.pudding.password ) services.setupShutdownHook() logger.info { "Started Pudding client!" } // Used for Logback System.setProperty("cluster.name", config.loritta.clusters.instances.first { it.id == clusterId }.getUserAgent(config.loritta.environment)) val cacheFolder = File("cache") cacheFolder.mkdirs() val initialSessions = mutableMapOf<Int, GatewaySessionData>() val previousVersionKeyFile = File(cacheFolder, "version") if (previousVersionKeyFile.exists()) { val previousVersion = UUID.fromString(previousVersionKeyFile.readText()) for (shard in lorittaCluster.minShard..lorittaCluster.maxShard) { try { val shardCacheFolder = File(cacheFolder, shard.toString()) val sessionFile = File(shardCacheFolder, "session.json") val cacheVersionKeyFile = File(shardCacheFolder, "version") // Does not exist, so bail out if (!cacheVersionKeyFile.exists()) { logger.warn("Couldn't load shard $shard cached data because the version file does not exist!") continue } val cacheVersion = UUID.fromString(cacheVersionKeyFile.readText()) // Only load the data if the version matches if (cacheVersion == previousVersion) { if (sessionFile.exists()) { val sessionData = if (sessionFile.exists()) Json.decodeFromString<GatewaySessionData>(sessionFile.readText()) else null if (sessionData != null) initialSessions[shard] = sessionData } } else { logger.warn { "Couldn't load shard $shard cached data because the cache version does not match!" } } } catch (e: Exception) { logger.warn { "Failed to load shard $shard cached data!" } } } } // Iniciar instância da Loritta val loritta = LorittaBot(clusterId, config, languageManager, localeManager, services, cacheFolder, initialSessions) loritta.start() } private fun copyFromJar(inputPath: String, outputPath: String) { val inputStream = LorittaLauncher::class.java.getResourceAsStream(inputPath) File(outputPath).writeBytes(inputStream.readAllBytes()) } @OptIn(ExperimentalCoroutinesApi::class) private fun installCoroutinesDebugProbes() { // It is recommended to set this to false to avoid performance hits with the DebugProbes option! DebugProbes.enableCreationStackTraces = false DebugProbes.install() } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/LorittaLauncher.kt
3114884906
package com.blankj.utilcode.pkg.feature.bar.status.fragment import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.viewpager.widget.ViewPager import com.blankj.common.activity.CommonActivity import com.blankj.utilcode.pkg.R import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.android.synthetic.main.bar_status_fragment_activity.* import java.util.* /** * ``` * author: Blankj * blog : http://blankj.com * time : 2017/05/27 * desc : demo about BarUtils * ``` */ class BarStatusFragmentActivity : CommonActivity() { companion object { fun start(context: Context) { val starter = Intent(context, BarStatusFragmentActivity::class.java) context.startActivity(starter) } } private val itemIds = intArrayOf( R.id.barStatusFragmentNavigationColor, R.id.barStatusFragmentNavigationAlpha, R.id.barStatusFragmentNavigationImageView, R.id.barStatusFragmentNavigationCustom ) private val mFragmentList = ArrayList<androidx.fragment.app.Fragment>() private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener l@{ item -> when (item.itemId) { R.id.barStatusFragmentNavigationColor -> { barStatusFragmentVp.currentItem = 0 return@l true } R.id.barStatusFragmentNavigationAlpha -> { barStatusFragmentVp.currentItem = 1 return@l true } R.id.barStatusFragmentNavigationImageView -> { barStatusFragmentVp.currentItem = 2 return@l true } R.id.barStatusFragmentNavigationCustom -> { barStatusFragmentVp.currentItem = 3 return@l true } else -> false } } override fun isSwipeBack(): Boolean { return false } override fun bindLayout(): Int { return R.layout.bar_status_fragment_activity } override fun initView(savedInstanceState: Bundle?, contentView: View?) { super.initView(savedInstanceState, contentView) mFragmentList.add(BarStatusFragmentColor.newInstance()) mFragmentList.add(BarStatusFragmentAlpha.newInstance()) mFragmentList.add(BarStatusFragmentImageView.newInstance()) mFragmentList.add(BarStatusFragmentCustom.newInstance()) barStatusFragmentVp.offscreenPageLimit = mFragmentList.size - 1 barStatusFragmentVp.adapter = object : FragmentPagerAdapter(supportFragmentManager) { override fun getItem(position: Int): Fragment { return mFragmentList[position] } override fun getCount(): Int { return mFragmentList.size } } barStatusFragmentVp.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {} override fun onPageSelected(position: Int) { barStatusFragmentNav.selectedItemId = itemIds[position] } override fun onPageScrollStateChanged(state: Int) {} }) barStatusFragmentNav.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) } }
feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/bar/status/fragment/BarStatusFragmentActivity.kt
646527532
package net.perfectdreams.loritta.cinnamon.pudding.data import kotlinx.serialization.Serializable @Serializable sealed class BackgroundVariation { abstract val file: String abstract val preferredMediaType: String abstract val crop: Rectangle? } @Serializable class DefaultBackgroundVariation( override val file: String, override val preferredMediaType: String, override val crop: Rectangle? ) : BackgroundVariation() { } @Serializable class ProfileDesignGroupBackgroundVariation( // TODO: This is actually a UUID, should be handled as a UUID (However there isn't mpp UUID yet) val profileDesignGroupId: String, override val file: String, override val preferredMediaType: String, override val crop: Rectangle? ) : BackgroundVariation()
pudding/data/src/commonMain/kotlin/net/perfectdreams/loritta/cinnamon/pudding/data/BackgroundVariation.kt
1289192641
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.packtracker import dev.kord.common.entity.ButtonStyle import net.perfectdreams.discordinteraktions.common.builder.message.actionRow import dev.kord.core.entity.User import net.perfectdreams.loritta.cinnamon.emotes.Emotes import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentExecutorIds import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.utils.declarations.PackageCommand import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ButtonExecutorDeclaration import net.perfectdreams.loritta.cinnamon.discord.interactions.components.CinnamonButtonExecutor import net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext import net.perfectdreams.loritta.cinnamon.discord.interactions.components.interactiveButton import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentDataUtils import net.perfectdreams.loritta.cinnamon.discord.utils.correios.CorreiosClient import net.perfectdreams.loritta.cinnamon.pudding.data.UserId class UnfollowPackageButtonClickExecutor( loritta: LorittaBot, val correios: CorreiosClient ) : CinnamonButtonExecutor(loritta) { companion object : ButtonExecutorDeclaration(ComponentExecutorIds.UNFOLLOW_PACKAGE_BUTTON_EXECUTOR) override suspend fun onClick(user: User, context: ComponentContext) { context.deferUpdateMessage() val decoded = context.decodeDataFromComponentAndRequireUserToMatch<UnfollowPackageData>() loritta.pudding.packagesTracking.untrackCorreiosPackage( UserId(user.id.value), decoded.trackingId ) context.updateMessage { actionRow { interactiveButton( ButtonStyle.Primary, context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.FollowPackageUpdates), FollowPackageButtonClickExecutor, ComponentDataUtils.encode( FollowPackageData( context.user.id, decoded.trackingId ) ) ) } } context.sendEphemeralReply( context.i18nContext.get(PackageCommand.I18N_PREFIX.Track.UnfollowPackage.YouUnfollowedThePackage(decoded.trackingId)), Emotes.LoriSunglasses ) } }
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/utils/packtracker/UnfollowPackageButtonClickExecutor.kt
4218677283
package com.directdev.portal.features.finance import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.directdev.portal.R import com.directdev.portal.models.FinanceModel import com.directdev.portal.utils.formatToRupiah import io.realm.OrderedRealmCollection import io.realm.Realm import io.realm.RealmRecyclerViewAdapter import kotlinx.android.synthetic.main.item_finances.view.* import kotlinx.android.synthetic.main.item_finances_header.view.* import org.joda.time.DateTime import org.joda.time.DateTimeComparator import org.joda.time.Days import org.joda.time.format.DateTimeFormat /**------------------------------------------------------------------------------------------------- * * Adapter for list of bills in finance fragment. It includes a header that shows the total number * of incoming bills. * *------------------------------------------------------------------------------------------------*/ // TODO: REFACTOR | This list is reversed, and i forgot why, further investigation needed // This recyclerView is in reversed order, so we put the header (The one that shows unpaid bill) at // the end of the list to make it show on top class FinancesRecyclerAdapter( val realm: Realm, data: OrderedRealmCollection<FinanceModel>?, autoUpdate: Boolean) : RealmRecyclerViewAdapter<FinanceModel, FinancesRecyclerAdapter.ViewHolder>(data, autoUpdate) { private val HEADER = 1 override fun getItemCount() = super.getItemCount() + 1 // Normally for header, position==0 will be used (So that it shows on top), since this is // reversed, we will want to put the header on the bottom. override fun getItemViewType(position: Int) = if (position == data?.size) HEADER else super.getItemViewType(position) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = if (viewType == HEADER) HeaderViewHolder(realm, LayoutInflater.from(parent.context).inflate(R.layout.item_finances_header, parent, false)) else NormalViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_finances, parent, false)) override fun onBindViewHolder(holder: ViewHolder, position: Int) { if (position == data?.size) holder.bindData(getItem(position - 1) as FinanceModel) else holder.bindData(getItem(position) as FinanceModel) } abstract class ViewHolder(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) { abstract fun bindData(item: FinanceModel) } private class NormalViewHolder(view: View) : ViewHolder(view) { override fun bindData(item: FinanceModel) { val date = DateTime .parse(item.dueDate.substring(0, 10)) .toString(DateTimeFormat.forPattern("dd MMM ''yy")) val amount = item.chargeAmount.formatToRupiah() itemView.finance_description.text = item.description itemView.finance_date.text = date itemView.finance_amount.text = amount if (DateTime.parse(item.dueDate.substring(0, 10)).isAfterNow) { itemView.finance_passed.visibility = View.GONE itemView.finance_upcoming.visibility = View.VISIBLE } else { itemView.finance_passed.visibility = View.VISIBLE itemView.finance_upcoming.visibility = View.GONE } } } private class HeaderViewHolder(val realm: Realm, view: View) : ViewHolder(view) { override fun bindData(item: FinanceModel) { val totalBillText: String val nextChargeText: String val data = realm.where(FinanceModel::class.java).findAll() val closestDate = data .map { DateTime.parse(it.dueDate.substring(0, 10)) } .filter { it.isAfterNow } .sortedWith(DateTimeComparator.getInstance()) if (closestDate.isNotEmpty()) { val nextChargeDate = closestDate[0].toString("dd MMMM") val daysCount = Days .daysBetween(closestDate[0], DateTime.now()) .days .toString() .substring(1) val totalBill = data .filter { DateTime.parse(it.dueDate.substring(0, 10)).isAfterNow } .sumBy { it.chargeAmount.toDouble().toInt() } totalBillText = "Rp. $totalBill" nextChargeText = "$nextChargeDate ($daysCount days)" } else { totalBillText = "Rp. 0,-" nextChargeText = "-" } itemView.total_amount.text = totalBillText itemView.next_charge.text = nextChargeText } } }
app/src/main/java/com/directdev/portal/features/finance/FinancesRecyclerAdapter.kt
3030378180
package com.angcyo.uiview.widget import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.graphics.drawable.Drawable import android.support.v4.view.MotionEventCompat import android.util.AttributeSet import android.view.MotionEvent import android.view.View import com.angcyo.uiview.R import com.angcyo.uiview.kotlin.density import com.angcyo.uiview.kotlin.getDrawable /** * Created by angcyo on 2017-09-13. */ class BlockSeekBar(context: Context, attributeSet: AttributeSet? = null) : View(context, attributeSet) { /**不规则高度列表*/ private val heightList = listOf(0.5f, 0.7f, 0.9f, 1.0f, 0.8f, 0.6f, 0.3f, 0.7f, 0.8f) private val tempRectF = RectF() private val clipRectF = RectF() private val paint by lazy { Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL } } /**每一个的宽度*/ private var blockWidth = 4 * density /**圆角大小*/ private var roundSize = 4 * density /**空隙大小*/ private var spaceSize = 2 * density /**滑块*/ private var sliderDrawable: Drawable? = null var blockProgressColor: Int = Color.YELLOW var blockProgressBgColor: Int = Color.WHITE /**当前的进度, 非百分比*/ var blockProgress: Int = 0 set(value) { field = when { value < 0 -> 0 value > blockMaxProgress -> blockMaxProgress else -> value } postInvalidate() } /**最大刻度, 百分比计算的分母*/ var blockMaxProgress: Int = 100 set(value) { field = value postInvalidate() } /**滑块的最小宽度, 非百分比*/ var blockMinWidth: Int = 20 set(value) { field = when { value < 10 -> 10 value > blockMaxProgress -> blockMaxProgress - 10 else -> value } postInvalidate() } init { sliderDrawable = getDrawable(R.drawable.base_slider)?.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.BlockSeekBar) blockProgress = typedArray.getInt(R.styleable.BlockSeekBar_r_block_progress, blockProgress) blockMaxProgress = typedArray.getInt(R.styleable.BlockSeekBar_r_block_max_progress, blockMaxProgress) blockMinWidth = typedArray.getInt(R.styleable.BlockSeekBar_r_block_min_width, blockMinWidth) blockProgressColor = typedArray.getColor(R.styleable.BlockSeekBar_r_block_progress_color, blockProgressColor) blockProgressBgColor = typedArray.getColor(R.styleable.BlockSeekBar_r_block_progress_bg_color, blockProgressBgColor) val drawable = typedArray.getDrawable(R.styleable.BlockSeekBar_r_slider_drawable) if (drawable != null) { sliderDrawable = drawable.apply { setBounds(0, 0, intrinsicWidth, intrinsicHeight) } } typedArray.recycle() } //滑块的高度 private val sliderHeight: Int get() { if (sliderDrawable == null) { return 0 } return sliderDrawable!!.intrinsicHeight } private val sliderWidth: Int get() { if (sliderDrawable == null) { return 0 } return sliderDrawable!!.intrinsicWidth } //滑块允许绘制的高度 private val blockDrawHeight: Int get() { return measuredHeight - sliderHeight - paddingTop - paddingBottom } //滑块允许绘制的宽度 private val blockDrawWidth: Int get() { return sliderDrawWidth - sliderWidth } private val sliderDrawWidth: Int get() { return measuredWidth - paddingLeft - paddingRight } private val sliderDrawLeft: Float get() { return drawProgress * blockDrawWidth } private val blockDrawLeft: Float get() { return paddingLeft.toFloat() + sliderWidth / 2 } /**按照百分比, 转换的进度*/ private val drawProgress: Float get() { return Math.min(blockProgress * 1f / blockMaxProgress, 1f) } //最小绘制宽度的进度比 private val drawMinBlockProgress: Float get() { return Math.min(blockMinWidth * 1f / blockMaxProgress, 1f) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) if (isInEditMode) { canvas.drawColor(Color.DKGRAY) } //绘制标准柱子 drawBlock(canvas, blockProgressBgColor) //绘制进度柱子 canvas.save() val left = blockDrawLeft + blockDrawWidth * drawProgress clipRectF.set(left, 0f, left + drawMinBlockProgress * blockDrawWidth, blockDrawHeight.toFloat() + paddingTop) canvas.clipRect(clipRectF) drawBlock(canvas, blockProgressColor) canvas.restore() //绘制滑块 canvas.save() canvas.translate(paddingLeft.toFloat() + sliderDrawLeft, blockDrawHeight.toFloat() + paddingTop) sliderDrawable?.draw(canvas) canvas.restore() } private fun drawBlock(canvas: Canvas, color: Int) { var left = blockDrawLeft var index = 0 while (left + blockWidth < measuredWidth - sliderWidth / 2 - paddingRight) { paint.color = color val blockHeight = blockDrawHeight * heightList[index.rem(heightList.size)] val top = (blockDrawHeight - blockHeight) / 2 + paddingTop tempRectF.set(left, top, left + blockWidth, top + blockHeight) canvas.drawRoundRect(tempRectF, roundSize, roundSize, paint) left += blockWidth + spaceSize index++ } } //touch处理 override fun onTouchEvent(event: MotionEvent): Boolean { val action = MotionEventCompat.getActionMasked(event) val eventX = event.x //L.e("call: onTouchEvent([event])-> " + action + " x:" + eventX); when (action) { MotionEvent.ACTION_DOWN -> { //L.e("call: onTouchEvent([event])-> DOWN:" + " x:" + eventX); // isTouchDown = true // notifyListenerStartTouch() blockSeekListener?.onTouchStart(this) calcProgress(eventX) parent.requestDisallowInterceptTouchEvent(true) } MotionEvent.ACTION_MOVE -> calcProgress(eventX) MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { // isTouchDown = false // notifyListenerStopTouch() blockSeekListener?.onTouchEnd(this) parent.requestDisallowInterceptTouchEvent(false) } } return true } /** * 根据touch坐标, 计算进度 */ private fun calcProgress(touchX: Float) { //事件发生在柱子中的比率 val scale = (touchX - blockDrawLeft) / blockDrawWidth val progress = (scale * blockMaxProgress).toInt() if (progress <= blockMaxProgress - blockMinWidth) { //将比率转换成进度 blockProgress = progress //L.e("call: onSeekChange -> $blockProgress ${blockProgress + blockMinWidth}") blockSeekListener?.onSeekChange(this, blockProgress, blockProgress + blockMinWidth) postInvalidate() } // val x = touchX - paddingLeft.toFloat() - (mThumbWidth / 2).toFloat() // val old = this.curProgress // this.curProgress = ensureProgress((x / getMaxLength() * maxProgress).toInt()) // if (old != curProgress) { // notifyListenerProgress(true) // } } fun setBlockProgressAndNotify(progress: Int) { blockProgress = progress blockSeekListener?.onSeekChange(this, blockProgress, blockProgress + blockMinWidth) } /**事件监听*/ var blockSeekListener: OnBlockSeekListener? = null public abstract class OnBlockSeekListener { public open fun onTouchStart(view: BlockSeekBar) { } public open fun onSeekChange(view: BlockSeekBar, startX: Int /*非百分比*/, endX: Int) { } public open fun onTouchEnd(view: BlockSeekBar) { } } }
uiview/src/main/java/com/angcyo/uiview/widget/BlockSeekBar.kt
3745039933
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.intellij.plugins.hcl.codeinsight import com.intellij.lang.BracePair import com.intellij.lang.PairedBraceMatcher import com.intellij.psi.PsiFile import com.intellij.psi.tree.IElementType import org.intellij.plugins.hcl.HCLElementTypes.* class HCLBraceMatcher : PairedBraceMatcher { override fun getCodeConstructStart(file: PsiFile?, openingBraceOffset: Int): Int { return openingBraceOffset } override fun isPairedBracesAllowedBeforeType(lbraceType: IElementType, contextType: IElementType?): Boolean { return true } companion object { private val BRACE_PAIRS = arrayOf(BracePair(L_CURLY, R_CURLY, true), BracePair(L_BRACKET, R_BRACKET, true)) } override fun getPairs(): Array<out BracePair> { return BRACE_PAIRS } }
src/kotlin/org/intellij/plugins/hcl/codeinsight/HCLBraceMatcher.kt
4060892282
/* * Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vanniktech.emoji.sample import android.app.Dialog import android.graphics.PorterDuff import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.ImageButton import android.widget.ImageView import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.RecyclerView import com.vanniktech.emoji.Emoji import com.vanniktech.emoji.EmojiPopup import com.vanniktech.emoji.material.MaterialEmojiLayoutFactory import timber.log.Timber // We don't care about duplicated code in the sample. class MainDialog : DialogFragment() { override fun onCreate(savedInstanceState: Bundle?) { layoutInflater.factory2 = MaterialEmojiLayoutFactory(null) super.onCreate(savedInstanceState) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { return AlertDialog.Builder(requireContext()) .setView(buildView()) .create() } private fun buildView(): View? { val context = requireContext() val result = View.inflate(context, R.layout.dialog_main, null) val editText = result.findViewById<EditText>(R.id.main_dialog_chat_bottom_message_edittext) val rootView = result.findViewById<View>(R.id.main_dialog_root_view) val emojiButton = result.findViewById<ImageButton>(R.id.main_dialog_emoji) val sendButton = result.findViewById<ImageView>(R.id.main_dialog_send) val emojiPopup = EmojiPopup( rootView = rootView, editText = editText, onEmojiBackspaceClickListener = { Timber.d(TAG, "Clicked on Backspace") }, onEmojiClickListener = { emoji: Emoji -> Timber.d(TAG, "Clicked on Emoji " + emoji.unicode) }, onEmojiPopupShownListener = { emojiButton.setImageResource(R.drawable.ic_keyboard) }, onSoftKeyboardOpenListener = { px -> Timber.d(TAG, "Opened soft keyboard with height $px") }, onEmojiPopupDismissListener = { emojiButton.setImageResource(R.drawable.ic_emojis) }, onSoftKeyboardCloseListener = { Timber.d(TAG, "Closed soft keyboard") }, keyboardAnimationStyle = R.style.emoji_fade_animation_style, ) emojiButton.setColorFilter(ContextCompat.getColor(context, R.color.colorPrimary), PorterDuff.Mode.SRC_IN) sendButton.setColorFilter(ContextCompat.getColor(context, R.color.colorPrimary), PorterDuff.Mode.SRC_IN) val chatAdapter = ChatAdapter() emojiButton.setOnClickListener { emojiPopup.toggle() } sendButton.setOnClickListener { val text = editText.text.toString().trim { it <= ' ' } if (text.isNotEmpty()) { chatAdapter.add(text) editText.setText("") } } val recyclerView: RecyclerView = result.findViewById(R.id.main_dialog_recycler_view) recyclerView.adapter = chatAdapter return rootView } internal companion object { const val TAG = "MainDialog" fun show(activity: AppCompatActivity) { MainDialog().show(activity.supportFragmentManager, TAG) } } }
app/src/main/kotlin/com/vanniktech/emoji/sample/MainDialog.kt
669294091
package ee.task.shared import ee.lang.CompilationUnit import java.nio.file.Path import java.nio.file.Paths import java.util.concurrent.TimeUnit open class ExecConfig { val home: Path val cmd: List<String> val env: Map<String, String> val filterPattern: Unit val failOnError: Boolean val filter: Boolean val noConsole: Boolean val wait: Boolean val timeout: Long val timeoutUnit: TimeUnit constructor(home: Path = Paths.get(""), cmd: List<String> = arrayListOf(), env: Map<String, String> = emptyMap(), filterPattern: Unit =, failOnError: Boolean = false, filter: Boolean = false, noConsole: Boolean = false, wait: Boolean = true, timeout: Long = ee.lang.Attribute@6ebc05a6, timeoutUnit: TimeUnit = TimeUnit.SECONDS) { this.home = home this.cmd = cmd this.env = env this.filterPattern = filterPattern this.failOnError = failOnError this.filter = filter this.noConsole = noConsole this.wait = wait this.timeout = timeout this.timeoutUnit = timeoutUnit } companion object { val EMPTY = ExecConfig() } } open class PathResolver { val home: Path val itemToHome: Map<String, String> constructor(home: Path = Paths.get(""), itemToHome: Map<String, String> = emptyMap()) { this.home = home this.itemToHome = itemToHome } open fun <T : CompilationUnit> resolve()Path { throw IllegalAccessException("Not implemented yet.") } companion object { val EMPTY = PathResolver() } } open class Result { val action: Unit val ok: Boolean val failure: Unit val info: Unit val error: Throwable? val results: List<Result> constructor(action: Unit =, ok: Boolean = true, failure: Unit =, info: Unit =, error: Throwable? = null, results: List<Result> = arrayListOf()) { this.action = action this.ok = ok this.failure = failure this.info = info this.error = error this.results = results } companion object { val EMPTY = Result() } } open class Task { val name: Unit val group: Unit constructor(name: Unit =, group: Unit =) { this.name = name this.group = group } open fun execute()Result { throw IllegalAccessException("Not implemented yet.") } companion object { val EMPTY = Task() } } open class TaskFactory { val name: Unit val group: Unit constructor(name: Unit =, group: Unit =) { this.name = name this.group = group } open fun supports()Boolean { throw IllegalAccessException("Not implemented yet.") } open fun create()List<Task> { throw IllegalAccessException("Not implemented yet.") } companion object { val EMPTY = TaskFactory() } } open class TaskGroup { val taskFactories: List<TaskFactory<Task>> val tasks: List<Task> constructor(taskFactories: List<TaskFactory<Task>> = arrayListOf(), tasks: List<Task> = arrayListOf()) { this.taskFactories = taskFactories this.tasks = tasks } companion object { val EMPTY = TaskGroup() } } open class TaskRegistry { val pathResolver: PathResolver constructor(pathResolver: PathResolver = PathResolver()) { this.pathResolver = pathResolver } open fun register()Unit { throw IllegalAccessException("Not implemented yet.") } companion object { val EMPTY = TaskRegistry() } } open class TaskRepository { val typeFactories: List<TaskFactory<Task>> constructor(typeFactories: List<TaskFactory<Task>> = arrayListOf()) { this.typeFactories = typeFactories } open fun <V : TaskFactory<Task>> register()Unit { throw IllegalAccessException("Not implemented yet.") } open fun <T : CompilationUnit> find()List<TaskFactory<Task>> { throw IllegalAccessException("Not implemented yet.") } companion object { val EMPTY = TaskRepository() } } open class TaskResult { val task: Task val result: Result constructor(task: Task = Task(), result: Result = Result()) { this.task = task this.result = result } companion object { val EMPTY = TaskResult() } }
task/task/src-gen/main/kotlin/ee/task/shared/SharedApiBase.kt
638676834
@file:JvmName("K") package ir.iais.utilities.javautils import com.fasterxml.jackson.annotation.JsonIgnore import com.fasterxml.jackson.databind.ObjectMapper import ir.iais.utilities.javautils.utils.InjectorService import ir.iais.utilities.javautils.utils.Jackson import ir.iais.utilities.javautils.utils.ShortUUID import org.apache.commons.lang3.exception.ExceptionUtils import org.slf4j.Logger import org.slf4j.LoggerFactory //import org.apache.logging.log4j.LogManager //import org.apache.logging.log4j.Logger import java.util.* import kotlin.reflect.KClass /** static helper methods Created by yoones on 8/21/2016 AD. */ fun ObjectMapper.config(): ObjectMapper = Jackson.objectMapperConfigurer(this) /** * logging with Log4j2 without hassles */ inline val KClass<*>.logger: Logger inline get() = LoggerFactory.getLogger(this.java) inline val Class<*>.logger: Logger inline get() = LoggerFactory.getLogger(this) interface IQ { @get:JsonIgnore val logger: Logger get() = LoggerFactory.getLogger(this.javaClass) // fun Any.toJson(): String = Jackson.toJson(this) } inline fun <reified T : Any> fromJson(json: String): T = Jackson.fromJson(json, T::class.java) fun <T : Enum<*>> T.isOneOf(vararg enums: T): Boolean = listOf(*enums).contains(this) fun <T : Throwable> Throwable.contains(exClass: KClass<T>): Boolean = ExceptionUtils.indexOfType(this, exClass.java) >= 0 operator inline fun <reified T : Throwable> Throwable.get(exClass: KClass<T>): T { val i = ExceptionUtils.indexOfType(this, exClass.java) return if (i >= 0) ExceptionUtils.getThrowables(this)[i] as T else throw Error("'${this.localizedMessage}' doesn't have error cause of type ${T::class.qualifiedName}") } inline fun <reified T : Throwable> Throwable.rootCause(): T { var throwable = this while (throwable.cause != null) throwable = throwable.cause as Throwable return throwable as T } /** Get instance with [InjectorService] */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Use constructor injection") fun <OBJ : Any> Class<OBJ>.inject(): OBJ = InjectorService.instance(this) /** Get instance with [InjectorService] */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Use constructor injection") fun <OBJ : Any> KClass<OBJ>.inject(): OBJ = InjectorService.instance(this.java) inline fun <reified T : Any> Array<T>.randomItem(): T { if (this.isEmpty()) throw Error("Array<${T::class.simpleName}> is empty") val rnd = Random().nextInt(this.size) return this[rnd] } inline fun <reified T : Any> Collection<T>.randomItem(): T = this.toTypedArray().randomItem() fun <T> T.println(toString: (T) -> Any? = { it }): T { println(toString(this)) return this } fun shortUUID(): String = ShortUUID.next() fun uuid(): String = UUID.randomUUID().toString() fun <T> T?.toOptional(): Optional<T> = Optional.ofNullable(this)
src/main/java/ir/iais/utilities/javautils/_K.kt
2186269848
package team.morale.core.domain.event interface EventPublisher { fun publish(event: Event) }
src/main/kotlin/team/morale/core/domain/event/EventPublisher.kt
151321296
package io.kotest.matchers.maps import io.kotest.matchers.Matcher import io.kotest.matchers.MatcherResult import io.kotest.matchers.should import io.kotest.matchers.shouldNot fun <K, V> mapcontain(key: K, v: V) = object : Matcher<Map<K, V>> { override fun test(value: Map<K, V>) = MatcherResult( value[key] == v, "Map should contain mapping $key=$v but was $value", "Map should not contain mapping $key=$v but was $value" ) } fun <K, V> Map<K, V>.shouldContain(key: K, value: V) = this should mapcontain(key, value) fun <K, V> Map<K, V>.shouldNotContain(key: K, value: V) = this shouldNot mapcontain(key, value) infix fun <K, V> Map<K, V>.shouldContain(entry: Pair<K, V>) = this should mapcontain(entry.first, entry.second) infix fun <K, V> Map<K, V>.shouldNotContain(entry: Pair<K, V>) = this shouldNot mapcontain(entry.first, entry.second) infix fun <K, V> Map<K, V>.shouldContainExactly(expected: Map<K, V>) = this should containExactly(expected) infix fun <K, V> Map<K, V>.shouldNotContainExactly(expected: Map<K, V>) = this shouldNot containExactly(expected) infix fun <K, V> Map<K, V>.shouldContainAll(expected: Map<K, V>) = this should containAll(expected) infix fun <K, V> Map<K, V>.shouldNotContainAll(expected: Map<K, V>) = this shouldNot containAll(expected) infix fun <K, V : Any> Map<K, V>.shouldHaveKey(key: K) = this should haveKey(key) infix fun <K, V : Any> Map<K, V>.shouldContainKey(key: K) = this should haveKey(key) infix fun <K, V : Any> Map<K, V>.shouldNotHaveKey(key: K) = this shouldNot haveKey(key) infix fun <K, V : Any> Map<K, V>.shouldNotContainKey(key: K) = this shouldNot haveKey(key) infix fun <K, V> Map<K, V>.shouldContainValue(value: V) = this should haveValue<V>(value) infix fun <K, V> Map<K, V>.shouldNotContainValue(value: V) = this shouldNot haveValue<V>(value) infix fun <K, V> Map<K, V>.shouldHaveSize(size: Int) = this should haveSize(size) fun <K, V> Map<K, V>.shouldHaveKeys(vararg keys: K) = this should haveKeys(*keys) fun <K, V> Map<K, V>.shouldContainKeys(vararg keys: K) = this should haveKeys(*keys) fun <K, V> Map<K, V>.shouldNotHaveKeys(vararg keys: K) = this shouldNot haveKeys(*keys) fun <K, V> Map<K, V>.shouldNotContainKeys(vararg keys: K) = this shouldNot haveKeys(*keys) fun <K, V> Map<K, V>.shouldHaveValues(vararg values: V) = this should haveValues(*values) fun <K, V> Map<K, V>.shouldContainValues(vararg values: V) = this should haveValues(*values) fun <K, V> Map<K, V>.shouldNotHaveValues(vararg values: V) = this shouldNot haveValues(*values) fun <K, V> Map<K, V>.shouldNotContainValues(vararg values: V) = this shouldNot haveValues(*values) fun <K, V> Map<K, V>.shouldBeEmpty() = this should beEmpty() fun <K, V> Map<K, V>.shouldNotBeEmpty() = this shouldNot beEmpty() fun beEmpty() = object : Matcher<Map<*, *>> { override fun test(value: Map<*, *>): MatcherResult { return MatcherResult( value.isEmpty(), { "Map should be empty, but was $value." }, { "Map should not be empty, but was." } ) } }
kotest-assertions/src/commonMain/kotlin/io/kotest/matchers/maps/matchers.kt
615346755
package io.kotest.core.filters import io.kotest.core.extensions.TestCaseExtension import io.kotest.core.test.Description import io.kotest.core.test.TestCase import io.kotest.core.test.TestResult /** * A [TestCaseFilter] can be used to filter tests before they are executed. * * In this way it is similar to a [TestCaseExtension] but with a specialized purpose * and therefore simpler to use. */ interface TestCaseFilter : Filter { /** * This method is invoked with the test [Description] and the result * used to determine if the test should be included or not. */ fun filter(description: Description): TestFilterResult } /** * Creates an extension from this test case filter so it can be used as an extension. */ fun TestCaseFilter.toExtension(): TestCaseExtension = object : TestCaseExtension { override suspend fun intercept(testCase: TestCase, execute: suspend (TestCase) -> TestResult): TestResult { return when (filter(testCase.description)) { TestFilterResult.Include -> execute(testCase) TestFilterResult.Exclude -> TestResult.Ignored } } } enum class TestFilterResult { Include, Exclude }
kotest-core/src/commonMain/kotlin/io/kotest/core/filters/TestCaseFilter.kt
3844178160
/* * Sone - FreenetTemplatePage.kt - Copyright © 2010–2020 David Roden * * 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 net.pterodactylus.sone.web.page import freenet.clients.http.* import net.pterodactylus.sone.main.* import net.pterodactylus.util.template.* import net.pterodactylus.util.web.* import java.lang.String.* import java.net.* import java.util.logging.* import java.util.logging.Logger.* /** * Base class for all [Page]s that are rendered with [Template]s and * fit into Freenet’s web interface. */ open class FreenetTemplatePage( private val templateRenderer: TemplateRenderer, loaders: Loaders, private val invalidFormPasswordRedirectTarget: String ) : FreenetPage, LinkEnabledCallback { private val pageMakerInteractionFactory: PageMakerInteractionFactory = DefaultPageMakerInteractionFactory() open val styleSheets: Collection<String> = emptySet() open val shortcutIcon: String? get() = null open val isFullAccessOnly get() = false override fun getPath() = toadletPath open fun getPageTitle(request: FreenetRequest) = "" override fun isPrefixPage() = false open fun getRedirectTarget(request: FreenetRequest): String? = null open fun getAdditionalLinkNodes(request: FreenetRequest): List<Map<String, String>> = emptyList() override fun isLinkExcepted(link: URI) = false override fun isEnabled(toadletContext: ToadletContext) = !isFullAccessOnly private val template = templatePath?.let(loaders::loadTemplate) ?: Template() override fun handleRequest(request: FreenetRequest, response: Response): Response { getRedirectTarget(request)?.let { redirectTarget -> return RedirectResponse(redirectTarget) } if (isFullAccessOnly && !request.toadletContext.isAllowedFullAccess) { return response.setStatusCode(401).setStatusText("Not authorized").setContentType("text/html") } val toadletContext = request.toadletContext if (request.method == Method.POST) { /* require form password. */ val formPassword = request.httpRequest.getPartAsStringFailsafe("formPassword", 32) if (formPassword != toadletContext.container.formPassword) { return RedirectResponse(invalidFormPasswordRedirectTarget) } } val pageMakerInteraction = pageMakerInteractionFactory.createPageMaker(toadletContext, getPageTitle(request)) styleSheets.forEach(pageMakerInteraction::addStyleSheet) getAdditionalLinkNodes(request).forEach(pageMakerInteraction::addLinkNode) shortcutIcon?.let(pageMakerInteraction::addShortcutIcon) val output = try { val start = System.nanoTime() templateRenderer.render(template) { templateContext -> processTemplate(request, templateContext) }.also { val finish = System.nanoTime() logger.log(Level.FINEST, format("Template was rendered in %.2fms.", (finish - start) / 1000000.0)) } } catch (re1: RedirectException) { return RedirectResponse(re1.target ?: "") } pageMakerInteraction.setContent(output) return response.setStatusCode(200).setStatusText("OK").setContentType("text/html").write(pageMakerInteraction.renderPage()) } open fun processTemplate(request: FreenetRequest, templateContext: TemplateContext) { /* do nothing. */ } fun redirectTo(target: String?): Nothing = throw RedirectException(target) class RedirectException(val target: String?) : Exception() { override fun toString(): String = format("RedirectException{target='%s'}", target) } } private val logger: Logger = getLogger(FreenetTemplatePage::class.java.name)
src/main/kotlin/net/pterodactylus/sone/web/page/FreenetTemplatePage.kt
3746818468
package mil.nga.giat.mage.map.preference import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Transformations import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import mil.nga.giat.mage.data.feed.Feed import mil.nga.giat.mage.data.feed.FeedDao import javax.inject.Inject @HiltViewModel class MapPreferencesViewModel @Inject constructor( @ApplicationContext val context: Context, private val feedDao: FeedDao ): ViewModel() { private val eventId = MutableLiveData<String>() val feeds: LiveData<List<Feed>> = Transformations.switchMap(eventId) { feedDao.mappableFeeds(it) } fun setEvent(eventId: String) { this.eventId.value = eventId } }
mage/src/main/java/mil/nga/giat/mage/map/preference/MapPreferencesViewModel.kt
1978468758
package net.pterodactylus.sone.template import net.pterodactylus.sone.data.Profile import net.pterodactylus.sone.data.Sone import net.pterodactylus.sone.test.* import net.pterodactylus.sone.text.FreenetLinkPart import net.pterodactylus.sone.text.Part import net.pterodactylus.sone.text.PlainTextPart import net.pterodactylus.sone.text.SonePart import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.contains import org.junit.Test /** * Unit test for [ShortenFilter]. */ class ShortenFilterTest { private val filter = ShortenFilter() @Suppress("UNCHECKED_CAST") private fun shortenParts(length: Int, cutOffLength: Int, vararg parts: Part) = filter.format(null, listOf(*parts), mapOf("cut-off-length" to cutOffLength, "length" to length)) as Iterable<Part> @Test fun `plain text part is shortened if length exceeds maxl ength`() { assertThat(shortenParts(15, 10, PlainTextPart("This is a long text.")), contains<Part>( PlainTextPart("This is a …") )) } @Test fun `plain text part is not shortened if length does not exceed max length`() { assertThat(shortenParts(20, 10, PlainTextPart("This is a long text.")), contains<Part>( PlainTextPart("This is a long text.") )) } @Test fun `short parts are not shortened`() { assertThat(shortenParts(15, 10, PlainTextPart("This.")), contains<Part>( PlainTextPart("This.") )) } @Test fun `multiple plain text parts are shortened`() { assertThat(shortenParts(15, 10, PlainTextPart("This "), PlainTextPart("is a long text.")), contains<Part>( PlainTextPart("This "), PlainTextPart("is a …") )) } @Test fun `parts after length has been reached are ignored`() { assertThat(shortenParts(15, 10, PlainTextPart("This is a long text."), PlainTextPart(" And even more.")), contains<Part>( PlainTextPart("This is a …") )) } @Test fun `link parts are not shortened`() { assertThat(shortenParts(15, 10, FreenetLinkPart("[email protected]", "This is a long text.", false)), contains<Part>( FreenetLinkPart("[email protected]", "This is a long text.", false) )) } @Test fun `additional link parts are ignored`() { assertThat(shortenParts(15, 10, PlainTextPart("This is a long text."), FreenetLinkPart("[email protected]", "This is a long text.", false)), contains<Part>( PlainTextPart("This is a …") )) } @Test fun `sone parts are added but their length is ignored`() { val sone = mock<Sone>() whenever(sone.profile).thenReturn(Profile(sone)) assertThat(shortenParts(15, 10, SonePart(sone), PlainTextPart("This is a long text.")), contains<Part>( SonePart(sone), PlainTextPart("This is a …") )) } @Test fun `additional sone parts are ignored`() { val sone = mock<Sone>() whenever(sone.profile).thenReturn(Profile(sone)) assertThat(shortenParts(15, 10, PlainTextPart("This is a long text."), SonePart(sone)), contains<Part>( PlainTextPart("This is a …") )) } }
src/test/kotlin/net/pterodactylus/sone/template/ShortenFilterTest.kt
453022541
package cz.letalvoj.gpgpu.fft import org.junit.Assert import org.junit.Test /** * Run it with: -Djava.library.path=./native -Dcom.amd.aparapi.executionMode=%1 */ class FFTTest { @Test fun testCalculateOddPower() { val len = 16 val expected = FrequencySpectrum( doubleArrayOf(120.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0, -8.0 ), doubleArrayOf(0.0, 40.2187, 19.3137, 11.9728, 8.0, 5.3454, 3.3137, 1.5913, 0.0, -1.5913, -3.3137, -5.3454, -8.0, -11.9728, -19.3137, -40.2187 ) ); testCalculateTwice(len, expected) } @Test fun testCalculateEvenPower() { val len = 32 val expected = FrequencySpectrum( doubleArrayOf( 496.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0, -16.0 ), doubleArrayOf( 0.0, 162.4507, 80.4374, 52.7449, 38.6274, 29.9339, 23.9457, 19.4961, 16.0, 13.1309, 10.6909, 8.5522, 6.6274, 4.8535, 3.1826, 1.5759, 0.0, -1.5759, -3.1826, -4.8535, -6.6274, -8.5522, -10.6909, -13.1309, -16.0, -19.4961, -23.9457, -29.9339, -38.6274, -52.7449, -80.4374, -162.4507 ) ); testCalculateTwice(len, expected) } private fun testCalculateTwice(len: Int, expected: FrequencySpectrum) { val fft = OpenCLFFTCalculator(len) testCalculate(fft, len, expected) fft.close() } fun testCalculate(fft: FFTCalculator, len: Int, expected: FrequencySpectrum) { val signal = DoubleArray(len) for (i in 0..len - 1) signal[i] = i.toDouble() val actual = fft.calculate(signal) Assert.assertArrayEquals("Real parts equal", expected.real, actual.real, 10E-5) Assert.assertArrayEquals("Imaginary parts equal", expected.imag, actual.imag, 10E-5) } }
src/test/java/cz/letalvoj/gpgpu/fft/FFTTest.kt
2119574467
package com.github.shynixn.petblocks.sponge.logic.business.service import com.github.shynixn.petblocks.api.business.service.EventService import com.github.shynixn.petblocks.api.persistence.entity.PetBlocksPostSave import com.github.shynixn.petblocks.api.persistence.entity.PetBlocksPreSave import com.github.shynixn.petblocks.api.persistence.entity.PetPostSpawn import com.github.shynixn.petblocks.api.persistence.entity.PetPreSpawn import com.github.shynixn.petblocks.api.sponge.event.* import org.spongepowered.api.Sponge import org.spongepowered.api.entity.living.player.Player /** * Created by Shynixn 2019. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2019 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class EventServiceImpl : EventService { /** * Calls a framework event and returns if it was cancelled. */ override fun callEvent(event: Any): Boolean { val cEvent: PetBlocksEvent = when (event) { is PetPreSpawn -> PetPreSpawnEvent(event.player as Player, event.petMeta) is PetPostSpawn -> PetPostSpawnEvent(event.player as Player, event.pet) is PetBlocksPreSave -> PetBlocksPreSaveEvent(event.petMeta) is PetBlocksPostSave -> PetBlocksPostSaveEvent(event.petMeta) else -> throw IllegalArgumentException("Event is not mapped to PetBlocks!") } Sponge.getEventManager().post(cEvent) if (cEvent is PetBlocksCancelableEvent) { return cEvent.isCancelled } return false } }
petblocks-sponge-plugin/src/main/java/com/github/shynixn/petblocks/sponge/logic/business/service/EventServiceImpl.kt
4059843762
package com.cout970.magneticraft.registry import com.cout970.magneticraft.api.internal.registries.generation.OreGenerationRegistry import com.cout970.magneticraft.api.registries.generation.OreGeneration import com.cout970.magneticraft.features.items.CraftingItems import com.cout970.magneticraft.features.items.EnumMetal import com.cout970.magneticraft.features.items.ToolItems import com.cout970.magneticraft.misc.inventory.stack import com.cout970.magneticraft.systems.config.Config import com.cout970.magneticraft.systems.config.OreConfig import net.minecraftforge.oredict.OreDictionary import com.cout970.magneticraft.features.decoration.Blocks as DecorationBlocks import com.cout970.magneticraft.features.ores.Blocks as OreBlocks /** * Created by cout970 on 24/06/2016. */ /** * This register all the ore dictionary names */ fun registerOreDictionaryEntries() { EnumMetal.values().forEach { if (!it.vanilla && !it.isComposite) { OreDictionary.registerOre("ingot${it.name.toLowerCase().capitalize()}", it.getIngot()) OreDictionary.registerOre("nugget${it.name.toLowerCase().capitalize()}", it.getNugget()) } if (it.useful && !it.isComposite) { OreDictionary.registerOre("lightPlate${it.name.toLowerCase().capitalize()}", it.getLightPlate()) OreDictionary.registerOre("heavyPlate${it.name.toLowerCase().capitalize()}", it.getHeavyPlate()) } if (!it.isComposite) { OreDictionary.registerOre("chunk${it.name.toLowerCase().capitalize()}", it.getChunk()) } OreDictionary.registerOre("rockyChunk${it.name.toLowerCase().capitalize()}", it.getRockyChunk()) if (it.subComponents.isEmpty()) { OreDictionary.registerOre("dust${it.name.toLowerCase().capitalize()}", it.getDust()) } } //oreAluminium has two names! EnumMetal.ALUMINIUM.let { OreDictionary.registerOre("ingotAluminum", it.getIngot()) OreDictionary.registerOre("nuggetAluminum", it.getNugget()) OreDictionary.registerOre("dustAluminum", it.getDust()) OreDictionary.registerOre("chunkAluminum", it.getChunk()) OreDictionary.registerOre("rockyChunkAluminum", it.getRockyChunk()) } OreDictionary.registerOre("dustSulfur", CraftingItems.crafting.stack(1, CraftingItems.Type.SULFUR.meta)) OreDictionary.registerOre("oreCopper", OreBlocks.ores.stack(1, 0)) OreDictionary.registerOre("oreGalena", OreBlocks.ores.stack(1, 1)) OreDictionary.registerOre("oreLead", OreBlocks.ores.stack(1, 1)) OreDictionary.registerOre("oreSilver", OreBlocks.ores.stack(1, 1)) OreDictionary.registerOre("oreCobalt", OreBlocks.ores.stack(1, 2)) OreDictionary.registerOre("oreTungsten", OreBlocks.ores.stack(1, 3)) OreDictionary.registerOre("orePyrite", OreBlocks.ores.stack(1, 4)) OreDictionary.registerOre("oreSulfur", OreBlocks.ores.stack(1, 4)) OreDictionary.registerOre("blockCopper", OreBlocks.storageBlocks.stack(1, 0)) OreDictionary.registerOre("blockLead", OreBlocks.storageBlocks.stack(1, 1)) OreDictionary.registerOre("blockCobalt", OreBlocks.storageBlocks.stack(1, 2)) OreDictionary.registerOre("blockTungsten", OreBlocks.storageBlocks.stack(1, 3)) OreDictionary.registerOre("blockSulfur", OreBlocks.storageBlocks.stack(1, 4)) OreDictionary.registerOre("stoneLimestonePolished", DecorationBlocks.limestone.stack(1, 0)) OreDictionary.registerOre("brickLimestone", DecorationBlocks.limestone.stack(1, 1)) OreDictionary.registerOre("stoneLimestone", DecorationBlocks.limestone.stack(1, 2)) OreDictionary.registerOre("stoneBurnLimestonePolished", DecorationBlocks.burnLimestone.stack(1, 0)) OreDictionary.registerOre("brickBurnLimestone", DecorationBlocks.burnLimestone.stack(1, 1)) OreDictionary.registerOre("stoneBurnLimestone", DecorationBlocks.burnLimestone.stack(1, 2)) OreDictionary.registerOre("stoneTileLimestone", DecorationBlocks.tileLimestone.stack(1, 0)) OreDictionary.registerOre("stoneTileLimestone", DecorationBlocks.tileLimestone.stack(1, 1)) OreDictionary.registerOre("magneticraftHammer", ToolItems.stoneHammer) OreDictionary.registerOre("magneticraftHammer", ToolItems.ironHammer) OreDictionary.registerOre("magneticraftHammer", ToolItems.steelHammer) } fun registerOreGenerations() { OreGenerationRegistry.registerOreGeneration(Config.copperOre.toOG("oreCopper")) OreGenerationRegistry.registerOreGeneration(Config.leadOre.toOG("oreGalena")) OreGenerationRegistry.registerOreGeneration(Config.pyriteOre.toOG("orePyrite")) OreGenerationRegistry.registerOreGeneration(Config.tungstenOre.toOG("oreTungsten")) } fun OreConfig.toOG(name: String): OreGeneration { return OreGeneration(name, active, chunkAmount, veinAmount, maxLevel, minLevel) }
src/main/kotlin/com/cout970/magneticraft/registry/OreDictionary.kt
2052827242
/* 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 org.mozilla.focus.activity.robots import androidx.test.espresso.Espresso import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.typeText import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import androidx.test.uiautomator.UiObject import androidx.test.uiautomator.UiScrollable import androidx.test.uiautomator.UiSelector import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.mozilla.focus.R import org.mozilla.focus.helpers.TestHelper.getStringResource import org.mozilla.focus.helpers.TestHelper.getTargetContext import org.mozilla.focus.helpers.TestHelper.mDevice import org.mozilla.focus.helpers.TestHelper.packageName import org.mozilla.focus.helpers.TestHelper.waitingTime class SearchSettingsRobot { fun verifySearchSettingsItems() { assertTrue(searchEngineSubMenu.exists()) assertTrue(searchEngineDefaultOption.exists()) assertTrue(searchSuggestionsHeading.exists()) assertTrue(searchSuggestionDescription.exists()) verifySearchSuggestionsSwitchState() assertTrue(searchSuggestionLearnMoreLink.exists()) assertTrue(urlAutocompleteSubMenu.exists()) assertTrue(urlAutocompleteDefaultOption.exists()) } fun openSearchEngineSubMenu() { searchEngineSubMenu.waitForExists(waitingTime) searchEngineSubMenu.click() } fun selectSearchEngine(engineName: String) { searchEngineList.waitForExists(waitingTime) searchEngineList .getChild(UiSelector().text(engineName)) .click() } fun clickSearchSuggestionsSwitch() { searchSuggestionsSwitch.waitForExists(waitingTime) searchSuggestionsSwitch.click() } fun verifySearchSuggestionsSwitchState(enabled: Boolean = false) { if (enabled) { assertTrue(searchSuggestionsSwitch.isChecked) } else { assertFalse(searchSuggestionsSwitch.isChecked) } } fun openUrlAutocompleteSubMenu() { urlAutocompleteSubMenu.waitForExists(waitingTime) urlAutocompleteSubMenu.click() } fun openManageSitesSubMenu() { manageSitesSubMenu.check(matches(isDisplayed())) manageSitesSubMenu.perform(click()) } fun openAddCustomUrlDialog() { addCustomUrlButton.check(matches(isDisplayed())) addCustomUrlButton.perform(click()) } fun enterCustomUrl(url: String) { customUrlText.check(matches(isDisplayed())) customUrlText.perform(typeText(url)) } fun saveCustomUrl() = saveButton.perform(click()) fun verifySavedCustomURL(url: String) { customUrlText.check(matches(withText(url))) } fun removeCustomUrl() { Espresso.openActionBarOverflowOrOptionsMenu(getTargetContext) onView(withText(R.string.preference_autocomplete_menu_remove)).perform(click()) customUrlText.perform(click()) onView(withId(R.id.remove)).perform(click()) } fun verifyCustomUrlDialogNotClosed() { saveButton.check(matches(isDisplayed())) } fun toggleCustomAutocomplete() { onView(withText(R.string.preference_switch_autocomplete_user_list)).perform(click()) } fun toggleTopSitesAutocomplete() { onView(withText(R.string.preference_switch_autocomplete_topsites)).perform(click()) } class Transition } private val searchEngineSubMenu = UiScrollable(UiSelector().resourceId("$packageName:id/recycler_view")) .getChild(UiSelector().text(getStringResource(R.string.preference_search_engine_label))) private val searchEngineDefaultOption = mDevice.findObject(UiSelector().textContains("Google")) private val searchEngineList = UiScrollable( UiSelector() .resourceId("$packageName:id/search_engine_group").enabled(true), ) private val searchSuggestionsHeading: UiObject = mDevice.findObject( UiSelector() .textContains(getStringResource(R.string.preference_show_search_suggestions)), ) private val searchSuggestionDescription: UiObject = mDevice.findObject( UiSelector() .textContains(getStringResource(R.string.preference_show_search_suggestions_summary)), ) private val searchSuggestionLearnMoreLink: UiObject = mDevice.findObject( UiSelector() .resourceId("$packageName:id/link"), ) private val searchSuggestionsSwitch: UiObject = mDevice.findObject( UiSelector() .resourceId("$packageName:id/switchWidget"), ) private val urlAutocompleteSubMenu = UiScrollable(UiSelector().resourceId("$packageName:id/recycler_view")) .getChildByText( UiSelector().text(getStringResource(R.string.preference_subitem_autocomplete)), getStringResource(R.string.preference_subitem_autocomplete), true, ) private val urlAutocompleteDefaultOption = mDevice.findObject( UiSelector() .textContains(getStringResource(R.string.preference_state_on)), ) private val manageSitesSubMenu = onView(withText(R.string.preference_autocomplete_subitem_manage_sites)) private val addCustomUrlButton = onView(withText(R.string.preference_autocomplete_action_add)) private val customUrlText = onView(withId(R.id.domainView)) private val saveButton = onView(withId(R.id.save))
app/src/androidTest/java/org/mozilla/focus/activity/robots/SettingsSearchMenuRobot.kt
435405051
/* * The MIT License (MIT) * * Copyright (c) 2015-2022 Elior "Mallowigi" Boukhobza * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.mallowigi.utils import com.intellij.cloudConfig.CloudConfigAppender import com.mallowigi.config.AtomConfigurable import com.mallowigi.config.AtomFileIconsConfig import com.mallowigi.config.AtomSettingsBundle.message import com.mallowigi.config.select.AtomSelectConfig import com.mallowigi.config.select.AtomSelectConfigurable /** Atom cloud provider. */ class AtomCloudProvider : CloudConfigAppender { /** Classes to sync. */ override fun appendClassesToStream(): List<Class<*>> = listOf( AtomSelectConfig::class.java, AtomFileIconsConfig::class.java ) /** Sync Settings description. */ override fun getConfigDescription(clazz: Class<*>): String { return when (clazz.simpleName) { AtomConfigurable.ID -> message("settings.titles.prefix", message("settings.titles.main")) AtomSelectConfigurable.ID -> message("settings.titles.prefix", message("settings.titles.customAssociations")) else -> clazz.simpleName } } }
common/src/main/java/com/mallowigi/utils/AtomCloudProvider.kt
1807295094
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.command import com.intellij.openapi.actionSystem.AnActionEvent import org.rust.cargo.icons.CargoIcons import org.rust.cargo.runconfig.ui.RunCargoCommandDialog class RunCargoCommandAction : RunCargoCommandActionBase(CargoIcons.ICON) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val cargoProject = getAppropriateCargoProject(e) ?: return val dialog = RunCargoCommandDialog(project, cargoProject) if (!dialog.showAndGet()) return runCommand(project, dialog.getCargoCommandLine()) } }
src/main/kotlin/org/rust/cargo/runconfig/command/RunCargoCommandAction.kt
124578478
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.navsample.snackbar import com.google.android.horologist.compose.navscaffold.ExperimentalHorologistComposeLayoutApi import java.util.UUID @ExperimentalHorologistComposeLayoutApi public data class UiMessage( val message: String, val id: String = UUID.randomUUID().toString() )
sample/src/main/java/com/google/android/horologist/navsample/snackbar/UiMessage.kt
3589304952
package com.example.jingbin.cloudreader.ui.wan.child import android.app.Activity import android.content.Context import android.os.Bundle import androidx.lifecycle.Observer import com.example.jingbin.cloudreader.R import com.example.jingbin.cloudreader.adapter.WanAndroidAdapter import com.example.jingbin.cloudreader.databinding.FragmentAndroidBinding import com.example.jingbin.cloudreader.utils.RefreshHelper import com.example.jingbin.cloudreader.viewmodel.wan.WanCenterViewModel import me.jingbin.bymvvm.base.BaseFragment /** * 问答 */ class WendaFragment : BaseFragment<WanCenterViewModel, FragmentAndroidBinding>() { private var isFirst = true private lateinit var activity: Activity private lateinit var mAdapter: WanAndroidAdapter override fun setContent(): Int = R.layout.fragment_android companion object { fun newInstance(): WendaFragment { return WendaFragment() } } override fun onAttach(context: Context) { super.onAttach(context) activity = context as Activity } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) } override fun onResume() { super.onResume() if (isFirst) { showLoading() initRv() getWendaData() isFirst = false } } private fun initRv() { RefreshHelper.initLinear(bindingView.xrvAndroid, true, 1) mAdapter = WanAndroidAdapter(activity) mAdapter.isNoShowChapterName = true mAdapter.isNoImage = false mAdapter.isShowDesc = true bindingView.xrvAndroid.adapter = mAdapter bindingView.xrvAndroid.setOnRefreshListener { viewModel.mPage = 1 getWendaData() } bindingView.xrvAndroid.setOnLoadMoreListener(true) { ++viewModel.mPage getWendaData() } } private fun getWendaData() { viewModel.getWendaList().observe(this, Observer { bindingView.xrvAndroid.isRefreshing = false if (it != null && it.isNotEmpty()) { showContentView() if (viewModel.mPage == 1) { mAdapter.setNewData(it) } else { mAdapter.addData(it) bindingView.xrvAndroid.loadMoreComplete() } } else { if (viewModel.mPage == 1) { if (it != null) { showEmptyView("没找到问答的内容~") } else { showError() if (viewModel.mPage > 1) viewModel.mPage-- } } else { bindingView.xrvAndroid.loadMoreEnd() } } }) } override fun onRefresh() { getWendaData() } }
app/src/main/java/com/example/jingbin/cloudreader/ui/wan/child/WendaFragment.kt
1844836847
package net.dinkla.raytracer.objects.acceleration.kdtree import net.dinkla.raytracer.math.Axis import net.dinkla.raytracer.math.BBox import net.dinkla.raytracer.math.Point3D import net.dinkla.raytracer.objects.GeometricObject import net.dinkla.raytracer.utilities.Counter import org.slf4j.LoggerFactory import java.util.* class Simple2Builder : IKDTreeBuilder { override var maxDepth = 10 var minChildren = 4 override fun build(tree: KDTree, voxel: BBox): AbstractNode { return build(tree.objects, tree.boundingBox, 0) } /** * * @param objects * @param voxel * @param depth * @return */ fun build(objects: List<GeometricObject>, voxel: BBox, depth: Int): AbstractNode { Counter.count("KDtree.build") var node: AbstractNode? var voxelL: BBox? var voxelR: BBox? if (objects.size < minChildren || depth >= maxDepth) { Counter.count("KDtree.build.leaf") node = Leaf(objects) return node } Counter.count("KDtree.build.node") val half = voxel.q!!.minus(voxel.p!!).times(0.5) val mid = voxel.p.plus(half) var split: Double? = null var objectsL: List<GeometricObject> var objectsR: List<GeometricObject> var voxelLx: BBox? var voxelRx: BBox? var voxelLy: BBox? var voxelRy: BBox? var voxelLz: BBox? var voxelRz: BBox? val objectsLx = ArrayList<GeometricObject>() val objectsRx = ArrayList<GeometricObject>() val objectsLy = ArrayList<GeometricObject>() val objectsRy = ArrayList<GeometricObject>() val objectsLz = ArrayList<GeometricObject>() val objectsRz = ArrayList<GeometricObject>() split = mid.x val q1 = Point3D(mid.x, voxel.q.y, voxel.q.z) voxelLx = BBox(voxel.p, q1) val p2 = Point3D(mid.x, voxel.p.y, voxel.p.z) voxelRx = BBox(p2, voxel.q) var bothX = 0 var bothY = 0 var bothZ = 0 for (`object` in objects) { val bbox = `object`.boundingBox var isBoth = false if (bbox.p.x <= split) { objectsLx.add(`object`) isBoth = true } if (bbox.q.x >= split) { objectsRx.add(`object`) if (isBoth) { bothX++ } } } split = mid.y val q1y = Point3D(voxel.q.x, mid.y, voxel.q.z) voxelLy = BBox(voxel.p, q1y) val p2y = Point3D(voxel.p.x, mid.y, voxel.p.z) voxelRy = BBox(p2y, voxel.q) for (`object` in objects) { val bbox = `object`.boundingBox var isBoth = false if (bbox.p.y <= split) { objectsLy.add(`object`) isBoth = true } if (bbox.q.y >= split) { objectsRy.add(`object`) if (isBoth) { bothY++ } } } split = mid.z val q1z = Point3D(voxel.q.x, voxel.q.y, mid.z) voxelLz = BBox(voxel.p, q1z) val p2z = Point3D(voxel.p.x, voxel.p.y, mid.z) voxelRz = BBox(p2z, voxel.q) for (`object` in objects) { val bbox = `object`.boundingBox var isBoth = false if (bbox.p.z <= split) { objectsLz.add(`object`) isBoth = true } if (bbox.q.z >= split) { objectsRz.add(`object`) if (isBoth) { bothZ++ } } } val n = objects.size val diffX = Math.abs(objectsLx.size - objectsRx.size) + bothX * 3 + (objectsLx.size + objectsRx.size - n) * 5 val diffY = Math.abs(objectsLy.size - objectsRy.size) + bothY * 3 + (objectsLy.size + objectsRy.size - n) * 5 val diffZ = Math.abs(objectsLz.size - objectsRz.size) + bothZ * 3 + (objectsLz.size + objectsRz.size - n) * 5 if (diffX < diffY) { if (diffX < diffZ) { objectsL = objectsLx objectsR = objectsRx voxelL = voxelLx voxelR = voxelRx } else { objectsL = objectsLz objectsR = objectsRz voxelL = voxelLz voxelR = voxelRz } } else { if (diffY < diffZ) { objectsL = objectsLy objectsR = objectsRy voxelL = voxelLy voxelR = voxelRy } else { objectsL = objectsLz objectsR = objectsRz voxelL = voxelLz voxelR = voxelRz } } if (objectsL.size + objectsR.size > n * 1.5) { node = Leaf(objects) } else { LOGGER.info("Splitting " + objects.size + " objects into " + objectsL.size + " and " + objectsR.size + " objects at " + split + " with depth " + depth) val left = build(objectsL, voxelL, depth + 1) val right = build(objectsR, voxelR, depth + 1) node = InnerNode(left, right, voxel, split, Axis.fromInt(depth % 3)) } return node } companion object { internal val LOGGER = LoggerFactory.getLogger(this::class.java) } }
src/main/kotlin/net/dinkla/raytracer/objects/acceleration/kdtree/Simple2Builder.kt
2081876125
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.datalayer import com.google.android.horologist.components.SampleApplication import com.google.android.horologist.data.ExperimentalHorologistDataLayerApi import com.google.android.horologist.data.WearDataLayerRegistry import com.google.android.horologist.data.WearDataService @OptIn(ExperimentalHorologistDataLayerApi::class) class SampleDataService : WearDataService() { override lateinit var registry: WearDataLayerRegistry override fun onCreate() { super.onCreate() registry = (application as SampleApplication).registry } }
sample/src/main/java/com/google/android/horologist/datalayer/SampleDataService.kt
1327313718
package com.mrebollob.loteria.data import com.mrebollob.loteria.data.mapper.TicketMapper import com.mrebollob.loteria.di.LotteryDatabaseWrapper import com.mrebollob.loteria.domain.entity.Ticket import com.mrebollob.loteria.domain.repository.TicketsRepository class TicketsRepositoryImp( lotteryDatabaseWrapper: LotteryDatabaseWrapper, private val ticketMapper: TicketMapper ) : TicketsRepository { private val lotteryQueries = lotteryDatabaseWrapper.instance?.lotteryQueries override suspend fun getTickets(): Result<List<Ticket>> { val dbTickets = lotteryQueries?.selectAll()?.executeAsList() ?: emptyList() return Result.success(dbTickets.map { ticketMapper.toDomain(it) }) } override suspend fun createTicket( name: String, number: Int, bet: Float ): Result<Unit> { lotteryQueries?.insertItem( id = null, name = name, number = number.toLong(), bet = bet.toDouble() ) return Result.success(Unit) } override suspend fun deleteTicket(ticket: Ticket): Result<Unit> { lotteryQueries?.deleteById(id = ticket.id) return Result.success(Unit) } }
shared/src/commonMain/kotlin/com/mrebollob/loteria/data/TicketsRepositoryImp.kt
3625934942
package net.yslibrary.monotweety.data.user data class User( val id: String, val name: String, val screenName: String, val profileImageUrl: String, val updatedAt: Long, )
data/src/main/java/net/yslibrary/monotweety/data/user/User.kt
1424313594
package fr.corenting.edcompanion.models import fr.corenting.edcompanion.models.apis.EDAPIV4.SystemResponse import org.threeten.bp.DateTimeUtils import org.threeten.bp.Instant data class System(val name: String, val isPermitRequired: Boolean, val allegiance: String?, val controllingFaction: String?, val government: String?, val population:Long?, val power:String?, val powerState:String?, val primaryEconomy:String?, val security: String?, val state:String?, val x:Float, val y:Float, val z:Float, val factions: List<Faction>) { companion object { fun fromSystemResponse(res: SystemResponse): System { val factions = ArrayList<Faction>() res.Factions.mapTo(factions) { Faction.fromFactionResponse(it) } return System(res.Name, res.PermitRequired, res.Allegiance, res.ControllingFaction, res.Government, res.Population, res.Power, res.PowerState, res.PrimaryEconomy, res.Security, res.State, res.X, res.Y, res.Z, factions) } } }
app/src/main/java/fr/corenting/edcompanion/models/System.kt
665035426
package com.supercilex.robotscouter.core.ui import android.os.Bundle import android.os.Parcelable import androidx.core.view.postOnAnimationDelayed import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.SimpleItemAnimator import com.firebase.ui.firestore.FirestoreRecyclerAdapter import com.firebase.ui.firestore.FirestoreRecyclerOptions import kotlin.math.max private val defaultMaxAnimationDuration: Long by lazy { DefaultItemAnimator().maxAnimationDuration() } fun RecyclerView.isItemInRange(position: Int): Boolean { val manager = layoutManager as LinearLayoutManager val adapter = checkNotNull(adapter) val first = manager.findFirstCompletelyVisibleItemPosition() // Only compute findLastCompletelyVisibleItemPosition if necessary return position in first until adapter.itemCount && position in first..manager.findLastCompletelyVisibleItemPosition() } inline fun RecyclerView.notifyItemsNoChangeAnimation( payload: Any? = null, update: RecyclerView.Adapter<*>.() -> Unit = { notifyItemRangeChanged(0, itemCount, payload) } ) { val animator = itemAnimator as? SimpleItemAnimator animator?.supportsChangeAnimations = false checkNotNull(adapter).update() postOnAnimationDelayed(animator.maxAnimationDuration()) { animator?.supportsChangeAnimations = true } } fun RecyclerView.ItemAnimator?.maxAnimationDuration() = this?.let { max(max(addDuration, removeDuration), changeDuration) } ?: defaultMaxAnimationDuration inline fun RecyclerView.Adapter<*>.swap( viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder, swap: (Int, Int) -> Unit ) { val fromPos = viewHolder.adapterPosition val toPos = target.adapterPosition if (fromPos < toPos) { for (i in fromPos until toPos) swap(i, i + 1) // Swap down } else { for (i in fromPos downTo toPos + 1) swap(i, i - 1) // Swap up } notifyItemMoved(fromPos, toPos) } /** * A [FirestoreRecyclerAdapter] whose state can be saved regardless of database connection * instability. * * This adapter will save its state across basic stop/start listening lifecycles, config changes, * and even full blown process death. Extenders _must_ call [SavedStateAdapter.onSaveInstanceState] * in the Activity/Fragment holding the adapter. */ abstract class SavedStateAdapter<T, VH : RecyclerView.ViewHolder>( options: FirestoreRecyclerOptions<T>, savedInstanceState: Bundle?, protected val recyclerView: RecyclerView ) : FirestoreRecyclerAdapter<T, VH>(options) { private var state: Parcelable? private val RecyclerView.state get() = layoutManager?.onSaveInstanceState() init { state = savedInstanceState?.getParcelable(SAVED_STATE_KEY) } fun onSaveInstanceState(outState: Bundle) { outState.putParcelable(SAVED_STATE_KEY, recyclerView.state) } override fun stopListening() { state = recyclerView.state super.stopListening() } override fun onDataChanged() { recyclerView.layoutManager?.onRestoreInstanceState(state) state = null } private companion object { const val SAVED_STATE_KEY = "layout_manager_saved_state" } }
library/core-ui/src/main/java/com/supercilex/robotscouter/core/ui/RecyclerView.kt
2031166861
package com.supercilex.robotscouter.feature.trash import android.os.Bundle import android.view.KeyEvent import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.view.View import androidx.activity.addCallback import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.content.res.AppCompatResources import androidx.core.view.isVisible import androidx.fragment.app.viewModels import androidx.lifecycle.MutableLiveData import androidx.recyclerview.selection.SelectionTracker import androidx.recyclerview.selection.StorageStrategy import androidx.recyclerview.widget.DividerItemDecoration import com.google.android.gms.tasks.Task import com.supercilex.robotscouter.common.DeletionType import com.supercilex.robotscouter.common.FIRESTORE_DELETION_QUEUE import com.supercilex.robotscouter.core.data.model.untrashTeam import com.supercilex.robotscouter.core.data.model.untrashTemplate import com.supercilex.robotscouter.core.longToast import com.supercilex.robotscouter.core.ui.AllChangesSelectionObserver import com.supercilex.robotscouter.core.ui.FragmentBase import com.supercilex.robotscouter.core.ui.KeyboardShortcutListener import com.supercilex.robotscouter.core.ui.animatePopReveal import com.supercilex.robotscouter.core.ui.longSnackbar import kotlinx.android.synthetic.main.fragment_trash.* import com.supercilex.robotscouter.R as RC internal class TrashFragment : FragmentBase(R.layout.fragment_trash), View.OnClickListener, KeyboardShortcutListener { private val holder by viewModels<TrashHolder>() private val allItems get() = holder.trashListener.value.orEmpty() private lateinit var selectionTracker: SelectionTracker<String> private lateinit var menuHelper: TrashMenuHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) holder.init() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { actionEmptyTrash.setOnClickListener(this) (activity as AppCompatActivity).apply { setSupportActionBar(findViewById(RC.id.toolbar)) checkNotNull(supportActionBar).setDisplayHomeAsUpEnabled(true) } val divider = DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL) divider.setDrawable(checkNotNull(AppCompatResources.getDrawable( requireContext(), R.drawable.trash_item_divider))) trashList.addItemDecoration(divider) val adapter = TrashListAdapter() trashList.adapter = adapter selectionTracker = SelectionTracker.Builder( FIRESTORE_DELETION_QUEUE, trashList, TrashKeyProvider(holder.trashListener), TrashDetailsLookup(trashList), StorageStrategy.createStringStorage() ).build().apply { adapter.selectionTracker = this addObserver(TrashMenuHelper(this@TrashFragment, this).also { menuHelper = it }) val backPressedCallback = requireActivity().onBackPressedDispatcher .addCallback(viewLifecycleOwner, false) { clearSelection() } addObserver(object : AllChangesSelectionObserver<String>() { override fun onSelectionChanged() { backPressedCallback.isEnabled = hasSelection() } }) onRestoreInstanceState(savedInstanceState) } holder.trashListener.observe(viewLifecycleOwner) { val hasTrash = it.orEmpty().isNotEmpty() noTrashHint.animatePopReveal(!hasTrash) notice.isVisible = hasTrash menuHelper.onTrashCountUpdate(hasTrash) if (it != null) for (i in 0 until adapter.itemCount) { // Unselect deleted items val item = adapter.getItem(i) if (!it.contains(item)) selectionTracker.deselect(item.id) } adapter.submitList(it) } } override fun onSaveInstanceState(outState: Bundle) { selectionTracker.onSaveInstanceState(outState) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { menuHelper.onCreateOptionsMenu(menu, inflater) menuHelper.onTrashCountUpdate(holder.trashListener.value.orEmpty().isNotEmpty()) } override fun onOptionsItemSelected(item: MenuItem) = menuHelper.onOptionsItemSelected(item) override fun onShortcut(keyCode: Int, event: KeyEvent): Boolean { when (keyCode) { KeyEvent.KEYCODE_DEL, KeyEvent.KEYCODE_FORWARD_DEL -> if (selectionTracker.hasSelection()) emptySelected() else emptyAll() else -> return false } return true } override fun onClick(v: View) { emptyAll() } fun restoreItems() { val all = allItems val restored = selectionTracker.selection.toList().map { key -> all.single { it.id == key } }.ifEmpty { all }.onEach { (id, _, type) -> when (type) { DeletionType.TEAM -> untrashTeam(id) DeletionType.TEMPLATE -> untrashTemplate(id) else -> error("Unsupported type: $type") } } if (restored.isNotEmpty()) { requireView().longSnackbar(resources.getQuantityString( R.plurals.trash_restored_message, restored.size, restored.size)) } } fun emptySelected() { showEmptyTrashDialog(selectionTracker.selection.toList()) } fun onEmptyTrashConfirmed(deleted: List<String>, emptyTrashResult: Task<*>) { requireView().longSnackbar(resources.getQuantityString( R.plurals.trash_emptied_message, deleted.size, deleted.size)) // Visual hack to pretend items were deleted really fast (usually takes a few seconds) val data = holder.trashListener as MutableLiveData val prev = data.value data.value = prev.orEmpty().filter { !deleted.contains(it.id) } emptyTrashResult.addOnFailureListener(requireActivity()) { longToast(R.string.trash_empty_failed_message) data.value = prev } } private fun emptyAll() { showEmptyTrashDialog(allItems.map { it.id }, true) } private fun showEmptyTrashDialog(ids: List<String>, emptyAll: Boolean = false) { EmptyTrashDialog.show(childFragmentManager, ids, emptyAll) } companion object { const val TAG = "TrashFragment" fun newInstance() = TrashFragment() } }
feature/trash/src/main/java/com/supercilex/robotscouter/feature/trash/TrashFragment.kt
2228532659
package it.sephiroth.android.library.bottomnavigation import android.view.View /** * Created by alessandro on 4/4/16 at 11:14 PM. * Project: Material-BottomNavigation */ interface OnItemClickListener { fun onItemClick(parent: ItemsLayoutContainer, view: View, index: Int, animate: Boolean) fun onItemDown(parent: ItemsLayoutContainer, view: View, pressed: Boolean, x: Float, y: Float) }
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/OnItemClickListener.kt
3655238328
package com.bachhuberdesign.deckbuildergwent.database import android.content.ContentValues import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteDatabase.CONFLICT_REPLACE import android.database.sqlite.SQLiteOpenHelper import android.util.Log import com.bachhuberdesign.deckbuildergwent.features.deckbuild.Deck import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction import com.bachhuberdesign.deckbuildergwent.features.stattrack.Match import com.google.gson.Gson /** * @author Eric Bachhuber * @version 1.0.0 * @since 1.0.0 */ class DatabaseHelper(var context: Context) : SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) { companion object { @JvmStatic val TAG: String = DatabaseHelper::class.java.name const val DB_NAME = "deck_builder.db" const val DB_VERSION: Int = 1 const val CREATE_TABLE_CARDS: String = "CREATE TABLE ${Card.TABLE} (" + "${Card.ID} INTEGER NOT NULL PRIMARY KEY, " + "${Card.NAME} TEXT NOT NULL, " + "${Card.DESCRIPTION} TEXT NOT NULL, " + "${Card.FLAVOR_TEXT} TEXT NOT NULL, " + "${Card.ICON_URL} TEXT NOT NULL, " + "${Card.MILL} INTEGER NOT NULL DEFAULT 0, " + "${Card.MILL_PREMIUM} INTEGER NOT NULL DEFAULT 0, " + "${Card.SCRAP} INTEGER NOT NULL DEFAULT 0, " + "${Card.SCRAP_PREMIUM} INTEGER NOT NULL DEFAULT 0, " + "${Card.POWER} INTEGER NOT NULL DEFAULT 0, " + "${Card.FACTION} INTEGER NOT NULL, " + "${Card.LANE} INTEGER NOT NULL, " + "${Card.LOYALTY} INTEGER NOT NULL DEFAULT 0, " + "${Card.RARITY} INTEGER NOT NULL, " + "${Card.TYPE} INTEGER NOT NULL" + ")" const val CREATE_TABLE_USER_DECKS: String = "CREATE TABLE ${Deck.TABLE} (" + "${Deck.ID} INTEGER NOT NULL PRIMARY KEY, " + "${Deck.NAME} TEXT NOT NULL, " + "${Deck.FACTION} INTEGER NOT NULL, " + "${Deck.LEADER_ID} INTEGER NOT NULL, " + "${Deck.FAVORITED} INTEGER NOT NULL DEFAULT 0, " + "${Deck.CREATED_DATE} INTEGER NOT NULL, " + "${Deck.LAST_UPDATE} INTEGER NOT NULL" + ")" const val CREATE_TABLE_USER_DECKS_CARDS: String = "CREATE TABLE ${Deck.JOIN_CARD_TABLE} (" + "join_id INTEGER NOT NULL PRIMARY KEY," + "deck_id INTEGER NOT NULL, " + "card_id INTEGER NOT NULL, " + "${Card.SELECTED_LANE} INTEGER NOT NULL" + ")" const val CREATE_TABLE_FACTIONS: String = "CREATE TABLE ${Faction.TABLE} (" + "${Faction.ID} INTEGER NOT NULL PRIMARY KEY, " + "${Faction.NAME} TEXT NOT NULL, " + "${Faction.EFFECT} TEXT NOT NULL," + "${Faction.ICON_URL} TEXT NOT NULL" + ")" const val CREATE_TABLE_MATCHES: String = "CREATE TABLE ${Match.TABLE} (" + "${Match.ID} INTEGER NOT NULL PRIMARY KEY, " + "${Match.DECK_ID} INTEGER NOT NULL, " + "${Match.OUTCOME} INTEGER NOT NULL, " + "${Match.OPPONENT_FACTION} INTEGER NOT NULL, " + "${Match.OPPONENT_LEADER} INTEGER DEFAULT 0, " + "${Match.NOTES} TEXT, " + "${Match.PLAYED_DATE} INTEGER, " + "${Match.CREATED_DATE} INTEGER, " + "${Match.LAST_UPDATE} INTEGER" + ")" } override fun onCreate(database: SQLiteDatabase) { database.execSQL(CREATE_TABLE_CARDS) database.execSQL(CREATE_TABLE_USER_DECKS) database.execSQL(CREATE_TABLE_USER_DECKS_CARDS) database.execSQL(CREATE_TABLE_FACTIONS) database.execSQL(CREATE_TABLE_MATCHES) val cards = Gson().fromJson(loadJsonFromAssets("card_list.json"), Array<Card>::class.java) val factions = Gson().fromJson(loadJsonFromAssets("faction_list.json"), Array<Faction>::class.java) cards.forEach { (id, name, description, flavorText, iconUrl, mill, millPremium, scrap, scrapPremium, power, faction, lane, loyalty, rarity, cardType) -> val cv = ContentValues() cv.put(Card.NAME, name) cv.put(Card.DESCRIPTION, description) cv.put(Card.FLAVOR_TEXT, flavorText) cv.put(Card.ICON_URL, iconUrl) cv.put(Card.MILL, mill) cv.put(Card.MILL_PREMIUM, millPremium) cv.put(Card.SCRAP, scrap) cv.put(Card.SCRAP_PREMIUM, scrapPremium) cv.put(Card.POWER, power) cv.put(Card.FACTION, faction) cv.put(Card.LANE, lane) cv.put(Card.LOYALTY, loyalty) cv.put(Card.RARITY, rarity) cv.put(Card.TYPE, cardType) database.insertWithOnConflict(Card.TABLE, null, cv, CONFLICT_REPLACE) } factions.forEach { (id, name, effect, iconUrl) -> val cv = ContentValues() cv.put(Faction.ID, id) cv.put(Faction.NAME, name) cv.put(Faction.EFFECT, effect) cv.put(Faction.ICON_URL, iconUrl) database.insertWithOnConflict(Faction.TABLE, null, cv, CONFLICT_REPLACE) } } override fun onUpgrade(database: SQLiteDatabase, oldVersion: Int, newVersion: Int) { Log.d(TAG, "onUpgrade()") } private fun loadJsonFromAssets(fileName: String): String { val stream = context.assets.open(fileName) val buffer = ByteArray(stream.available()) stream.use { stream.read(buffer) } return String(buffer).format("UTF-8") } }
app/src/main/java/com/bachhuberdesign/deckbuildergwent/database/DatabaseHelper.kt
1881640952
package domain.record import common.stream import okio.BufferedSource import okio.Okio import org.assertj.core.api.Assertions.assertThat import org.junit.Test import rx.Observable import rx.observers.TestSubscriber import java.io.InputStream class RecordTest { @Test fun testRecording() { val ts = TestSubscriber<RecordBuffer>() val tar = TestAudioRecorder(stream("mgs5.m4a"), true, true) val cnt = 300 Observable.create(startRecording { tar }) .take(cnt) .subscribe(ts) ts.assertCompleted() ts.assertValueCount(cnt) assertThat(tar.triedToStart).isTrue() assertThat(tar.released).isTrue() } @Test fun testInitError() { val ts = TestSubscriber<RecordBuffer>() val tar = TestAudioRecorder(stream("robolectric.properties"), false, true) Observable.create(startRecording { tar }).subscribe(ts) ts.assertError(FailedToInitialize::class.java) assertThat(tar.triedToStart).isFalse() assertThat(tar.released).isTrue() } @Test fun testStartError() { val ts = TestSubscriber<RecordBuffer>() val tar = TestAudioRecorder(stream("robolectric.properties"), true, false) Observable.create(startRecording { tar }).subscribe(ts) assertThat(tar.triedToStart).isTrue() ts.assertError(FailedToStart::class.java) assertThat(tar.released).isTrue() } } fun bufferedSource(stream: InputStream): BufferedSource = Okio.buffer(Okio.source(stream)) fun TestAudioRecorder(stream: InputStream, initialized: Boolean, recording: Boolean): TestAudioRecorder = TestAudioRecorder(bufferedSource(stream), initialized, recording) class TestAudioRecorder(val bs: BufferedSource, val initialized: Boolean, val recording: Boolean) : AudioRecorder { var triedToStart = false var released = false override fun isInitialized(): Boolean = initialized override fun isRecording(): Boolean = recording override fun read(sa: ShortArray, offset: Int, size: Int): Int = readLoop(sa, size, 0) override fun release() { bs.close() released = true } override fun startRecording() { triedToStart = true } private tailrec fun readLoop(sa: ShortArray, size: Int, i: Int): Int = if (i < size) { sa[i] = bs.readShort() readLoop(sa, size, i + 1) } else i }
app/src/test/kotlin/domain/record/RecordTest.kt
2587468470
package com.github.shynixn.blockball.core.logic.persistence.entity import com.github.shynixn.blockball.api.business.annotation.YamlSerialize import com.github.shynixn.blockball.api.business.enumeration.EffectTargetType import com.github.shynixn.blockball.api.persistence.entity.Sound /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class SoundEntity( /** * Name of the sound. */ @YamlSerialize(value = "name", orderNumber = 1) override var name: String = "none", /** * Pitch of the sound. */ @YamlSerialize(value = "pitch", orderNumber = 2) override var pitch: Double = 1.0, /** * Volume of the sound. */ @YamlSerialize(value = "volume", orderNumber = 3) override var volume: Double = 1.0) : Sound { /** * Which players are effected. */ @YamlSerialize(value = "effecting", orderNumber = 4) override var effectingType: EffectTargetType = EffectTargetType.NOBODY }
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/persistence/entity/SoundEntity.kt
200678991
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.ksp.symbol.impl.binary import com.google.devtools.ksp.memoized import com.google.devtools.ksp.symbol.* import com.google.devtools.ksp.symbol.impl.toKSPropertyDeclaration import com.google.devtools.ksp.toFunctionKSModifiers import com.google.devtools.ksp.toKSModifiers import org.jetbrains.kotlin.descriptors.PropertyAccessorDescriptor abstract class KSPropertyAccessorDescriptorImpl(val descriptor: PropertyAccessorDescriptor) : KSPropertyAccessor { override val origin: Origin by lazy { when (receiver.origin) { // if receiver is kotlin source, that means we are a synthetic where developer // didn't declare an explicit accessor so we used the descriptor instead Origin.KOTLIN -> Origin.SYNTHETIC else -> descriptor.origin } } override val receiver: KSPropertyDeclaration by lazy { descriptor.correspondingProperty.toKSPropertyDeclaration() } override val parent: KSNode? by lazy { receiver } override val location: Location get() { // if receiver is kotlin source, that means `this` is synthetic hence we want the property's location // Otherwise, receiver is also from a .class file where the location will be NoLocation return receiver.location } override val annotations: Sequence<KSAnnotation> by lazy { descriptor.annotations.asSequence().map { KSAnnotationDescriptorImpl.getCached(it, this) }.memoized() } override val modifiers: Set<Modifier> by lazy { val modifiers = mutableSetOf<Modifier>() modifiers.addAll(descriptor.toKSModifiers()) modifiers.addAll(descriptor.toFunctionKSModifiers()) modifiers } }
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/binary/KSPropertyAccessorDescriptorImpl.kt
4108056980
@file:JvmMultifileClass @file:JvmName("DialogsV7Kt") @file:Suppress("NOTHING_TO_INLINE", "UNUSED") package kota import android.content.DialogInterface import android.content.DialogInterface.* import android.support.annotation.StringRes import android.support.v7.app.AlertDialog @JvmOverloads inline fun AlertDialog.setPositiveButton( text: CharSequence, noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setButton(BUTTON_POSITIVE, text) { dialog, _ -> action?.invoke(dialog) } @JvmOverloads inline fun AlertDialog.setPositiveButton( @StringRes textId: Int, noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setPositiveButton(getText(textId), action) @JvmOverloads inline fun AlertDialog.setNegativeButton( text: CharSequence, noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setButton(BUTTON_NEGATIVE, text) { dialog, _ -> action?.invoke(dialog) } @JvmOverloads inline fun AlertDialog.setNegativeButton( @StringRes textId: Int, noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setNegativeButton(getText(textId), action) @JvmOverloads inline fun AlertDialog.setNeutralButton( text: CharSequence, noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setButton(BUTTON_NEUTRAL, text) { dialog, _ -> action?.invoke(dialog) } @JvmOverloads inline fun AlertDialog.setNeutralButton( @StringRes textId: Int, noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setNeutralButton(getText(textId), action) @JvmOverloads inline fun AlertDialog.setOKButton( noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setPositiveButton(android.R.string.ok, action) @JvmOverloads inline fun AlertDialog.setCancelButton( noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setNegativeButton(android.R.string.cancel, action) @JvmOverloads inline fun AlertDialog.setYesButton( noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setPositiveButton(android.R.string.yes, action) @JvmOverloads inline fun AlertDialog.setNoButton( noinline action: ((dialog: DialogInterface) -> Unit)? = null ) = setNegativeButton(android.R.string.no, action)
kota-appcompat-v7/src/dialogs/DialogsV7.kt
561323826
/* * 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 * * 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 app.tivi.common.compose.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes /** * We intentionally use the defaults for now. */ val TiviShapes = Shapes( small = RoundedCornerShape(50) )
common/ui/compose/src/main/java/app/tivi/common/compose/theme/Shape.kt
2004050825
package io.noties.markwon.app.samples import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import io.noties.markwon.Markwon import io.noties.markwon.app.BuildConfig import io.noties.markwon.app.sample.ui.MarkwonTextViewSample import io.noties.markwon.image.ImagesPlugin import io.noties.markwon.sample.annotations.MarkwonArtifact import io.noties.markwon.sample.annotations.MarkwonSampleInfo import io.noties.markwon.sample.annotations.Tag @MarkwonSampleInfo( id = "20200627074017", title = "Markdown in Toast (with dynamic content)", description = "Display markdown in a `android.widget.Toast` with dynamic content (image)", artifacts = [MarkwonArtifact.CORE, MarkwonArtifact.IMAGE], tags = [Tag.toast, Tag.hack] ) class ToastDynamicContentSample : MarkwonTextViewSample() { override fun render() { val md = """ # Head! ![alt](${BuildConfig.GIT_REPOSITORY}/raw/master/art/markwon_logo.png) Do you see an image? ☝️ """.trimIndent() val markwon = Markwon.builder(context) .usePlugin(ImagesPlugin.create()) .build() val markdown = markwon.toMarkdown(md) val toast = Toast.makeText(context, markdown, Toast.LENGTH_LONG) // try to obtain textView val textView = toast.textView if (textView != null) { markwon.setParsedMarkdown(textView, markdown) } // finally show toast (at this point, if we didn't find TextView it will still // present markdown, just without dynamic content (image)) toast.show() } } private val Toast.textView: TextView? get() { fun find(view: View?): TextView? { if (view is TextView) { return view } if (view is ViewGroup) { for (i in 0 until view.childCount) { val textView = find(view.getChildAt(i)) if (textView != null) { return textView } } } return null } return find(view) }
app-sample/src/main/java/io/noties/markwon/app/samples/ToastDynamicContentSample.kt
11998159
package ru.dyatel.tsuschedule.model import hirondelle.date4j.DateTime data class Exam( val discipline: String, val consultationDatetime: DateTime?, val examDatetime: DateTime, val consultationAuditory: String?, val examAuditory: String, val teacher: String ) : Comparable<Exam> { override fun compareTo(other: Exam) = examDatetime.compareTo(other.examDatetime) }
src/main/kotlin/ru/dyatel/tsuschedule/model/Exam.kt
1007610028
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.entity import com.badlogic.ashley.core.ComponentMapper import com.jupiter.europa.entity.component.* /** * @author Nathan Templon */ public object Mappers { // Constants public val abilities: ComponentMapper<AbilityComponent> = ComponentMapper.getFor(javaClass<AbilityComponent>()) public val attributes: ComponentMapper<AttributesComponent> = ComponentMapper.getFor(javaClass<AttributesComponent>()) public val characterClass: ComponentMapper<CharacterClassComponent> = ComponentMapper.getFor(javaClass<CharacterClassComponent>()) public val collision: ComponentMapper<CollisionComponent> = ComponentMapper.getFor(javaClass<CollisionComponent>()) public val effects: ComponentMapper<EffectsComponent> = ComponentMapper.getFor(javaClass<EffectsComponent>()) public val moveTexture: ComponentMapper<MovementResourceComponent> = ComponentMapper.getFor(javaClass<MovementResourceComponent>()) public val name: ComponentMapper<NameComponent> = ComponentMapper.getFor(javaClass<NameComponent>()) public val position: ComponentMapper<PositionComponent> = ComponentMapper.getFor(javaClass<PositionComponent>()) public val race: ComponentMapper<RaceComponent> = ComponentMapper.getFor(javaClass<RaceComponent>()) public val render: ComponentMapper<RenderComponent> = ComponentMapper.getFor(javaClass<RenderComponent>()) public val resources: ComponentMapper<ResourceComponent> = ComponentMapper.getFor(javaClass<ResourceComponent>()) public val size: ComponentMapper<SizeComponent> = ComponentMapper.getFor(javaClass<SizeComponent>()) public val skills: ComponentMapper<SkillsComponent> = ComponentMapper.getFor(javaClass<SkillsComponent>()) public val walk: ComponentMapper<WalkComponent> = ComponentMapper.getFor(javaClass<WalkComponent>()) }
core/src/com/jupiter/europa/entity/Mappers.kt
1280079613
/* * Copyright 2020 Thomas Nappo (Jire) * * 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.jire.strukt.benchmarks.heap import org.jire.strukt.IntField import org.jire.strukt.ThreadSafeType import org.jire.strukt.internal.AbstractField class HeapIntField( override val default: Int, val heapPoint: HeapPoint, ) : AbstractField(HeapPoint::class, HeapPoints, ThreadSafeType.NONE), IntField { override val size = 4L override fun get(address: Long) = heapPoint.x override fun set(address: Long, value: Int) { heapPoint.x = value } }
src/jmh/kotlin/org/jire/strukt/benchmarks/heap/HeapIntField.kt
906661087
package com.airbnb.android.airmapview import androidx.core.view.doOnLayout fun AirMapView.doWhenMapIsLaidOut(runnable: Runnable) = doOnLayout { runnable.run() }
library/src/main/java/com/airbnb/android/airmapview/MapLaidOutCheck.kt
7186285
package com.tokbox.sample.multipartyconstraintlayout import android.os.Build import android.transition.TransitionManager import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet class ConstraintSetHelper(containerViewId: Int) { private val set = ConstraintSet() private val container = containerViewId fun layoutViewAboveView(aboveViewId: Int, belowViewId: Int) { // above // below set.constrainHeight(aboveViewId, 0) set.constrainHeight(belowViewId, 0) set.connect(aboveViewId, ConstraintSet.BOTTOM, belowViewId, ConstraintSet.TOP) set.connect(belowViewId, ConstraintSet.TOP, aboveViewId, ConstraintSet.BOTTOM) } fun layoutViewWithTopBound(viewId: Int, topBound: Int) { set.connect(viewId, ConstraintSet.TOP, topBound, ConstraintSet.TOP) } fun layoutViewWithBottomBound(viewId: Int, bottomBound: Int) { set.connect(viewId, ConstraintSet.BOTTOM, bottomBound, ConstraintSet.BOTTOM) } private fun layoutViewNextToView(leftViewId: Int, rightViewId: Int, leftBoundViewId: Int, rightBoundViewId: Int) { // leftBound | leftView | rightView | rightBound set.constrainWidth(leftViewId, 0) set.constrainWidth(rightViewId, 0) set.connect(leftViewId, ConstraintSet.LEFT, leftBoundViewId, ConstraintSet.LEFT) set.connect(leftViewId, ConstraintSet.RIGHT, rightViewId, ConstraintSet.LEFT) set.connect(rightViewId, ConstraintSet.RIGHT, rightBoundViewId, ConstraintSet.RIGHT) set.connect(rightViewId, ConstraintSet.LEFT, leftViewId, ConstraintSet.RIGHT) } private fun layoutViewOccupyingAllRow(viewId: Int, leftBoundViewId: Int, rightBoundViewId: Int) { // leftBound | view | rightBound set.constrainWidth(viewId, 0) set.connect(viewId, ConstraintSet.LEFT, leftBoundViewId, ConstraintSet.LEFT) set.connect(viewId, ConstraintSet.RIGHT, rightBoundViewId, ConstraintSet.RIGHT) } fun layoutTwoViewsOccupyingAllRow(leftViewId: Int, rightViewId: Int) { layoutViewNextToView(leftViewId, rightViewId, container, container) } fun layoutViewAllContainerWide(viewId: Int, containerId: Int) { layoutViewOccupyingAllRow(viewId, containerId, containerId) } fun applyToLayout(layout: ConstraintLayout?, animated: Boolean) { if (animated) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { TransitionManager.beginDelayedTransition(layout) } } set.applyTo(layout) } fun layoutViewFullScreen(viewId: Int) { layoutViewAllContainerWide(viewId, container) layoutViewWithTopBound(viewId, container) layoutViewWithBottomBound(viewId, container) } fun layoutViewHeightPercent(viewId: Int, value: Float) { set.constrainPercentHeight(viewId, value) } fun layoutViewWidthPercent(viewId: Int, value: Float) { set.constrainPercentWidth(viewId, value) } }
Multiparty-Constraint-Layout-Kotlin/app/src/main/java/com/tokbox/sample/multipartyconstraintlayout/ConstraintSetHelper.kt
117129223
package com.jtransc.plugin.enum import com.jtransc.ast.* import com.jtransc.ast.treeshaking.TreeShakingApi import com.jtransc.plugin.JTranscPlugin /** * Plugin that include values() method from enums */ class EnumJTranscPlugin : JTranscPlugin() { override fun onTreeShakingAddBasicClass(treeShaking: TreeShakingApi, fqname: FqName, oldclass: AstClass, newclass: AstClass) { if (oldclass.isEnum && oldclass.extending == java.lang.Enum::class.java.fqname) { treeShaking.addMethod(AstMethodRef(fqname, "values", AstType.METHOD(ARRAY(oldclass.astType), listOf())), EnumJTranscPlugin::class.simpleName!!) } } }
jtransc-core/src/com/jtransc/plugin/enum/EnumJTranscPlugin.kt
1019848236
/* * Copyright (C) 2019. OpenLattice, Inc. * * 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/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.hazelcast.serializers import com.kryptnostic.rhizome.hazelcast.serializers.AbstractStreamSerializerTest import com.openlattice.mapstores.TestDataFactory import com.openlattice.organizations.SecurablePrincipalList import com.openlattice.organizations.events.MembersRemovedFromOrganizationEvent import java.util.UUID class MembersRemovedFromOrganizationEventStreamSerializerTest : AbstractStreamSerializerTest<MembersRemovedFromOrganizationEventStreamSerializer, MembersRemovedFromOrganizationEvent>() { override fun createSerializer(): MembersRemovedFromOrganizationEventStreamSerializer { return MembersRemovedFromOrganizationEventStreamSerializer() } override fun createInput(): MembersRemovedFromOrganizationEvent { return MembersRemovedFromOrganizationEvent( UUID.randomUUID(), SecurablePrincipalList( mutableListOf( TestDataFactory.securableUserPrincipal(), TestDataFactory.securableUserPrincipal() ) ) ) } }
src/test/kotlin/com/openlattice/hazelcast/serializers/MembersRemovedFromOrganizationEventStreamSerializerTest.kt
3279865659
/* * 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.features.testing.utilities.testresttemplate import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.context.SpringBootTest.WebEnvironment import org.springframework.boot.test.context.TestConfiguration import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.boot.web.client.RestTemplateBuilder import org.springframework.context.annotation.Bean import java.time.Duration @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) class MySpringBootTests(@Autowired val template: TestRestTemplate) { @Test fun testRequest() { val headers = template.getForEntity("/example", String::class.java).headers assertThat(headers.location).hasHost("other.example.com") } @TestConfiguration(proxyBeanMethods = false) internal class RestTemplateBuilderConfiguration { @Bean fun restTemplateBuilder(): RestTemplateBuilder { return RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(1)) .setReadTimeout(Duration.ofSeconds(1)) } } }
spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/testing/utilities/testresttemplate/MySpringBootTests.kt
2995223241
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.ui.components import androidx.annotation.FloatRange import androidx.compose.animation.core.InfiniteRepeatableSpec import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import com.google.accompanist.placeholder.PlaceholderDefaults import com.google.accompanist.placeholder.PlaceholderHighlight import com.google.accompanist.placeholder.shimmer @Composable fun shimmer( highlightColor: Color = MaterialTheme.colors.secondary.copy(alpha = .15f), animationSpec: InfiniteRepeatableSpec<Float> = PlaceholderDefaults.shimmerAnimationSpec, @FloatRange(from = 0.0, to = 1.0) progressForMaxAlpha: Float = 0.6f, ): PlaceholderHighlight = PlaceholderHighlight.shimmer( highlightColor = highlightColor, animationSpec = animationSpec, progressForMaxAlpha = progressForMaxAlpha, )
modules/common-ui-components/src/main/java/tm/alashow/ui/components/Placeholder.kt
3724159066
package com.balanza.android.harrypotter.app.di.module import com.balanza.android.harrypotter.domain.interactor.character.* import com.balanza.android.harrypotter.domain.repository.character.CharacterRepository import dagger.Module import dagger.Provides /** * Created by balanza on 15/02/17. */ @Module class InteractorModule { @Provides fun provideGetAllCharacters( characterRepository: CharacterRepository): GetAllCharacters = GetAllCharactersImp( characterRepository) @Provides fun provideFetchCharacter( characterRepository: CharacterRepository): FetchCharacter = FetchCharacterImp( characterRepository) @Provides fun provideGetCharacter(characterRepository: CharacterRepository): GetCharacter = GetCharacterImp( characterRepository) @Provides fun provideGetPointsWin(characterRepository: CharacterRepository): GetPointsWin = GetPointsWinImp( characterRepository) }
app/src/main/java/com/balanza/android/harrypotter/app/di/module/InteractorModule.kt
4110754333
package org.intellij.markdown.flavours.commonmark import org.intellij.markdown.MarkdownTokenTypes import org.intellij.markdown.parser.LookaheadText import org.intellij.markdown.parser.MarkerProcessor import org.intellij.markdown.parser.MarkerProcessorFactory import org.intellij.markdown.parser.ProductionHolder import org.intellij.markdown.parser.constraints.CommonMarkdownConstraints import org.intellij.markdown.parser.constraints.MarkdownConstraints import org.intellij.markdown.parser.constraints.getCharsEaten import org.intellij.markdown.parser.markerblocks.MarkerBlock import org.intellij.markdown.parser.markerblocks.MarkerBlockProvider import org.intellij.markdown.parser.markerblocks.providers.* import org.intellij.markdown.parser.sequentialparsers.SequentialParser import kotlin.math.min open class CommonMarkMarkerProcessor(productionHolder: ProductionHolder, constraintsBase: MarkdownConstraints) : MarkerProcessor<MarkerProcessor.StateInfo>(productionHolder, constraintsBase) { override var stateInfo: MarkerProcessor.StateInfo = MarkerProcessor.StateInfo(startConstraints, startConstraints, markersStack) private val markerBlockProviders = listOf( CodeBlockProvider(), HorizontalRuleProvider(), CodeFenceProvider(), SetextHeaderProvider(), BlockQuoteProvider(), ListMarkerProvider(), AtxHeaderProvider(), HtmlBlockProvider(), LinkReferenceDefinitionProvider() ) override fun getMarkerBlockProviders(): List<MarkerBlockProvider<MarkerProcessor.StateInfo>> { return markerBlockProviders } override fun updateStateInfo(pos: LookaheadText.Position) { if (pos.offsetInCurrentLine == -1) { stateInfo = MarkerProcessor.StateInfo(startConstraints, topBlockConstraints.applyToNextLine(pos), markersStack) } else if (MarkerBlockProvider.isStartOfLineWithConstraints(pos, stateInfo.nextConstraints)) { stateInfo = MarkerProcessor.StateInfo(stateInfo.nextConstraints, stateInfo.nextConstraints.addModifierIfNeeded(pos) ?: stateInfo.nextConstraints, markersStack) } } override fun populateConstraintsTokens(pos: LookaheadText.Position, constraints: MarkdownConstraints, productionHolder: ProductionHolder) { if (constraints.indent == 0) { return } val startOffset = pos.offset val endOffset = min(pos.offset - pos.offsetInCurrentLine + constraints.getCharsEaten(pos.currentLine), pos.nextLineOrEofOffset) val type = when (constraints.types.lastOrNull()) { '>' -> MarkdownTokenTypes.BLOCK_QUOTE '.', ')' -> MarkdownTokenTypes.LIST_NUMBER else -> MarkdownTokenTypes.LIST_BULLET } productionHolder.addProduction(listOf(SequentialParser.Node(startOffset..endOffset, type))) } override fun createNewMarkerBlocks(pos: LookaheadText.Position, productionHolder: ProductionHolder): List<MarkerBlock> { if (pos.offsetInCurrentLine == -1) { return NO_BLOCKS } return super.createNewMarkerBlocks(pos, productionHolder) } object Factory : MarkerProcessorFactory { override fun createMarkerProcessor(productionHolder: ProductionHolder): MarkerProcessor<*> { return CommonMarkMarkerProcessor(productionHolder, CommonMarkdownConstraints.BASE) } } }
src/commonMain/kotlin/org/intellij/markdown/flavours/commonmark/CommonMarkMarkerProcessor.kt
3834165337
package de.westnordost.streetcomplete.view import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint.Align import android.graphics.Rect import android.text.TextPaint import android.util.AttributeSet import android.view.View import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.ktx.toPx import kotlin.math.min /** A very basic text view whose text is displayed vertically. No line break is possible */ class VerticalLabelView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { private val textPaint = TextPaint() private var text: String? = null private val textBounds = Rect() private val orientationRight: Boolean init { textPaint.isAntiAlias = true textPaint.textAlign = Align.CENTER val a = context.obtainStyledAttributes(attrs, R.styleable.VerticalLabelView) setText(a.getString(R.styleable.VerticalLabelView_android_text)) setTextSize(a.getDimensionPixelSize(R.styleable.VerticalLabelView_android_textSize, 16f.toPx(context).toInt())) setTextColor(a.getColor(R.styleable.VerticalLabelView_android_textColor, Color.BLACK)) orientationRight = a.getBoolean(R.styleable.VerticalLabelView_orientationRight, false) a.recycle() } fun setText(text: String?) { if (this.text == text) return this.text = text requestLayout() invalidate() } fun setTextSize(size: Int) { if (textPaint.textSize == size.toFloat()) return textPaint.textSize = size.toFloat() requestLayout() invalidate() } fun setTextColor(color: Int) { if (textPaint.color == color) return textPaint.color = color invalidate() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { text.let { textPaint.getTextBounds(it.orEmpty(), 0, text?.length ?: 0, textBounds) } val desiredWidth = textBounds.height() + paddingLeft + paddingRight val desiredHeight = textBounds.width() + paddingTop + paddingBottom val width = reconcileSize(desiredWidth, widthMeasureSpec) val height = reconcileSize(desiredHeight, heightMeasureSpec) setMeasuredDimension(width, height) } private fun reconcileSize(contentSize: Int, measureSpec: Int): Int { val mode = MeasureSpec.getMode(measureSpec) val size = MeasureSpec.getSize(measureSpec) return when (mode) { MeasureSpec.EXACTLY -> size MeasureSpec.AT_MOST -> min(contentSize, size) else -> contentSize } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) text?.let { val originY = paddingTop + textBounds.width() / 2f if (orientationRight) { val originX = paddingLeft - textBounds.height() - textPaint.ascent() canvas.translate(originX, originY) canvas.rotate(90f) } else { val originX = paddingLeft - textPaint.ascent() canvas.translate(originX, originY) canvas.rotate(-90f) } canvas.drawText(it, 0f, 0f, textPaint) } } }
app/src/main/java/de/westnordost/streetcomplete/view/VerticalLabelView.kt
3274770401
package info.adavis.qualitychecks.tasks import info.adavis.qualitychecks.QualityChecksPlugin import org.gradle.api.Project import org.gradle.testfixtures.ProjectBuilder 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 class WriteConfigFileTaskTest { @Rule @JvmField val temporaryFolder = TemporaryFolder() lateinit var projectDir: File lateinit var project: Project lateinit var task: WriteConfigFileTask @Before fun setUp() { projectDir = temporaryFolder.root projectDir.mkdirs() project = ProjectBuilder.builder().withProjectDir(projectDir).build() task = project.tasks.create("writeConfigFile", WriteConfigFileTask::class.java) } @Test fun `should be able to create task`() { assertTrue(task is WriteConfigFileTask) } @Test fun `should not write file when already provided`() { with(task) { configFile = File.createTempFile("temp", ".xml") fileName = "pmd-ruleset.xml" writeConfigFile() configFile?.name?.startsWith("temp")?.let(::assertTrue) } } @Test fun `should not write file if null`() { with(task) { writeConfigFile() assertNull(configFile) } } @Test fun `should write default file contents if file exists`() { with(task) { configFile = temporaryFolder.newFile("pmd-ruleset.xml") fileName = QualityChecksPlugin.PMD_FILE_NAME writeConfigFile() val file = File(projectDir, "pmd-ruleset.xml") assertTrue(file.exists()) assertEquals(QualityChecksPlugin.PMD_FILE_NAME, task.configFile?.name) assertTrue(file.readText().contains("<description>Custom ruleset for Android application</description>")) } } }
qualityChecks/src/test/kotlin/info/adavis/qualitychecks/tasks/WriteConfigFileTaskTest.kt
215778697
package com.tschuchort.compiletesting import com.nhaarman.mockitokotlin2.* import com.tschuchort.compiletesting.KotlinCompilation.ExitCode import com.tschuchort.compiletesting.MockitoAdditionalMatchersKotlin.Companion.not import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.compiler.plugin.AbstractCliOption import org.jetbrains.kotlin.compiler.plugin.CliOption import org.jetbrains.kotlin.compiler.plugin.CommandLineProcessor import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.ByteArrayOutputStream import java.io.File import java.nio.file.Files import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.TypeElement @Suppress("MemberVisibilityCanBePrivate") class KotlinCompilationTests { @Rule @JvmField val temporaryFolder = TemporaryFolder() val kotlinTestProc = KotlinTestProcessor() val javaTestProc = JavaTestProcessor() @Test fun `runs with only kotlin sources`() { val result = defaultCompilerConfig().apply { sources = listOf(SourceFile.kotlin("kSource.kt", "class KSource")) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "KSource") } @Test fun `runs with only java sources`() { val result = defaultCompilerConfig().apply { sources = listOf(SourceFile.java("JSource.java", "class JSource {}")) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "JSource") } @Test fun `runs with no sources`() { val result = defaultCompilerConfig().apply { sources = emptyList() }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) } @Test fun `runs with SourceFile from path`() { val sourceFile = temporaryFolder.newFile("KSource.kt").apply { writeText("class KSource") } val result = defaultCompilerConfig().apply { sources = listOf(SourceFile.fromPath(sourceFile)) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "KSource") } @Test fun `runs with SourceFile from paths with filename conflicts`() { temporaryFolder.newFolder("a") val sourceFileA = temporaryFolder.newFile("a/KSource.kt").apply { writeText("package a\n\nclass KSource") } temporaryFolder.newFolder("b") val sourceFileB = temporaryFolder.newFile("b/KSource.kt").apply { writeText("package b\n\nclass KSource") } val result = defaultCompilerConfig().apply { sources = listOf( SourceFile.fromPath(sourceFileA), SourceFile.fromPath(sourceFileB)) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "a.KSource") assertClassLoadable(result, "b.KSource") } @Test fun `Kotlin can access JDK`() { val source = SourceFile.kotlin("kSource.kt", """ import javax.lang.model.SourceVersion import java.io.File fun main(addKotlincArgs: Array<String>) { File("") } """) val result = defaultCompilerConfig().apply { sources = listOf(source) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "KSourceKt") } @Test fun `Kotlin can not access JDK`() { val source = SourceFile.kotlin("kSource.kt", """ import javax.lang.model.SourceVersion import java.io.File fun main(addKotlincArgs: Array<String>) { File("") } """) val result = defaultCompilerConfig().apply { sources = listOf(source) jdkHome = null }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.COMPILATION_ERROR) assertThat(result.messages).containsIgnoringCase("unresolved reference: java") } @Test fun `can compile Kotlin without JDK`() { val source = SourceFile.kotlin("kSource.kt", "class KClass") val result = defaultCompilerConfig().apply { sources = listOf(source) jdkHome = null }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "KClass") } @Test fun `Java can access JDK`() { val source = SourceFile.java("JSource.java", """ import javax.lang.model.SourceVersion; import java.io.File; class JSource { File foo() { return new File(""); } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "JSource") } @Test fun `Java can not access JDK`() { val source = SourceFile.java("JSource.java", """ import javax.lang.model.SourceVersion; import java.io.File; class JSource { File foo() { return new File(""); } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) jdkHome = null }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("Unable to find package java.lang") assertThat(result.messages).contains( "jdkHome is set to null, removing boot classpath from java compilation" ) } @Test fun `Java inherits classpath`() { val source = SourceFile.java("JSource.java", """ package com.tschuchort.compiletesting; class JSource { void foo() { String s = KotlinCompilationTests.InheritedClass.class.getName(); } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.JSource") } @Test fun `Java doesn't inherit classpath`() { val source = SourceFile.java("JSource.java", """ package com.tschuchort.compiletesting; class JSource { void foo() { String s = KotlinCompilationTests.InheritedClass.class.getName(); } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) inheritClassPath = false }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.COMPILATION_ERROR) assertThat(result.messages).contains("package KotlinCompilationTests does not exist") } @Test fun `Kotlin inherits classpath`() { val source = SourceFile.kotlin("KSource.kt", """ package com.tschuchort.compiletesting class KSource { fun foo() { val s = KotlinCompilationTests.InheritedClass::class.java.name } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.KSource") } @Test fun `Kotlin doesn't inherit classpath`() { val source = SourceFile.kotlin("KSource.kt", """ package com.tschuchort.compiletesting class KSource { fun foo() { val s = KotlinCompilationTests.InheritedClass::class.java.name } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) inheritClassPath = false }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.COMPILATION_ERROR) assertThat(result.messages).containsIgnoringCase("unresolved reference: KotlinCompilationTests") } @Test fun `Compiled Kotlin class can be loaded`() { val source = SourceFile.kotlin("Source.kt", """ package com.tschuchort.compiletesting class Source { fun helloWorld(): String { return "Hello World" } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) annotationProcessors = listOf(object : AbstractProcessor() { override fun process(annotations: MutableSet<out TypeElement>?, roundEnv: RoundEnvironment?): Boolean { return false } }) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) val clazz = result.classLoader.loadClass("com.tschuchort.compiletesting.Source") assertThat(clazz).isNotNull val instance = clazz.newInstance() assertThat(instance).isNotNull assertThat(clazz).hasDeclaredMethods("helloWorld") assertThat(clazz.getDeclaredMethod("helloWorld").invoke(instance)).isEqualTo("Hello World") } @Test fun `Compiled Java class can be loaded`() { val source = SourceFile.java("Source.java", """ package com.tschuchort.compiletesting; public class Source { public String helloWorld() { return "Hello World"; } } """) val result = defaultCompilerConfig().apply { sources = listOf(source) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) val clazz = result.classLoader.loadClass("com.tschuchort.compiletesting.Source") assertThat(clazz).isNotNull val instance = clazz.newInstance() assertThat(instance).isNotNull assertThat(clazz).hasDeclaredMethods("helloWorld") assertThat(clazz.getDeclaredMethod("helloWorld").invoke(instance)).isEqualTo("Hello World") } @Test fun `Kotlin can access Java class`() { val jSource = SourceFile.java("JSource.java", """ package com.tschuchort.compiletesting; class JSource { void foo() {} } """) val kSource = SourceFile.kotlin("KSource.kt", """ package com.tschuchort.compiletesting class KSource { fun bar() { JSource().foo() } } """) val result = defaultCompilerConfig().apply { sources = listOf(kSource, jSource) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.KSource") assertClassLoadable(result, "com.tschuchort.compiletesting.JSource") } @Test fun `Java can access Kotlin class`() { val jSource = SourceFile.java("JSource.java", """ package com.tschuchort.compiletesting; class JSource { void foo() { String s = (new KSource()).bar(); } } """) val kSource = SourceFile.kotlin("KSource.kt", """ package com.tschuchort.compiletesting class KSource { fun bar(): String = "bar" } """) val result = defaultCompilerConfig().apply { sources = listOf(kSource, jSource) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.KSource") assertClassLoadable(result, "com.tschuchort.compiletesting.JSource") } @Test fun `Java AP sees Kotlin class`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting @ProcessElem class KSource { } """) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(javaTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains(JavaTestProcessor.ON_INIT_MSG) assertThat(ProcessedElemMessage.parseAllIn(result.messages)).anyMatch { it.elementSimpleName == "KSource" } } @Test fun `Java AP sees Java class`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; @ProcessElem class JSource { } """) val result = defaultCompilerConfig().apply { sources = listOf(jSource) annotationProcessors = listOf(javaTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains(JavaTestProcessor.ON_INIT_MSG) assertThat(ProcessedElemMessage.parseAllIn(result.messages)).anyMatch { it.elementSimpleName == "JSource" } } @Test fun `Kotlin AP sees Kotlin class`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting @ProcessElem class KSource { } """ ) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains(KotlinTestProcessor.ON_INIT_MSG) assertThat(ProcessedElemMessage.parseAllIn(result.messages)).anyMatch { it.elementSimpleName == "KSource" } } @Test fun `Kotlin AP sees Java class`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; @ProcessElem class JSource { } """ ) val result = defaultCompilerConfig().apply { sources = listOf(jSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains(KotlinTestProcessor.ON_INIT_MSG) assertThat(ProcessedElemMessage.parseAllIn(result.messages)).anyMatch { it.elementSimpleName == "JSource" } } @Test fun `Given only Java sources, Kotlin sources are generated and compiled`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; @ProcessElem class JSource { } """ ) val result = defaultCompilerConfig().apply { sources = listOf(jSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains(KotlinTestProcessor.ON_INIT_MSG) val clazz = result.classLoader.loadClass(KotlinTestProcessor.GENERATED_PACKAGE + "." + KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME) assertThat(clazz).isNotNull } @Test fun `Java can access generated Kotlin class`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; import ${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME}; @ProcessElem class JSource { void foo() { Class<?> c = ${KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME}.class; } } """ ) val result = defaultCompilerConfig().apply { sources = listOf(jSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.JSource") assertClassLoadable(result, "${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME}") } @Test fun `Java can access generated Java class`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; import ${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME}; @ProcessElem class JSource { void foo() { Class<?> c = ${KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME}.class; } } """ ) val result = defaultCompilerConfig().apply { sources = listOf(jSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.JSource") assertClassLoadable(result, "${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME}") } @Test fun `Kotlin can access generated Kotlin class`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting import ${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME} @ProcessElem class KSource { fun foo() { val c = ${KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME}::class.java } } """ ) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.KSource") assertClassLoadable(result, "${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME}") } @Test fun `Kotlin can access generated Java class`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting import ${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME} @ProcessElem class KSource { fun foo() { val c = ${KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME}::class.java } } """ ) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "com.tschuchort.compiletesting.KSource") assertClassLoadable(result, "${KotlinTestProcessor.GENERATED_PACKAGE}.${KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME}") } @Test fun `detects the plugin provided for compilation via pluginClasspaths property`() { val result = defaultCompilerConfig().apply { sources = listOf(SourceFile.kotlin("kSource.kt", "class KSource")) pluginClasspaths = listOf(classpathOf("kotlin-scripting-compiler-${BuildConfig.KOTLIN_VERSION}")) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains( "provided plugin org.jetbrains.kotlin.scripting.compiler.plugin.ScriptingCompilerConfigurationComponentRegistrar" ) } @Test fun `returns an internal error when adding a non existing plugin for compilation`() { val result = defaultCompilerConfig().apply { sources = listOf(SourceFile.kotlin("kSource.kt", "class KSource")) pluginClasspaths = listOf(File("./non-existing-plugin.jar")) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.INTERNAL_ERROR) assertThat(result.messages).contains("non-existing-plugin.jar not found") } @Test fun `Generated Java source is among generated files list`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting @ProcessElem class KSource { fun foo() {} } """ ) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.generatedFiles.map { it.name }).contains(KotlinTestProcessor.GENERATED_JAVA_CLASS_NAME + ".java") } @Test fun `Generated Kotlin source is among generated files list`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting @ProcessElem class KSource { fun foo() {} } """ ) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.generatedFiles.map { it.name }).contains(KotlinTestProcessor.GENERATED_KOTLIN_CLASS_NAME + ".kt") } @Test fun `Compiled Kotlin class file is among generated files list`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting @ProcessElem class KSource { fun foo() {} } """ ) val result = defaultCompilerConfig().apply { sources = listOf(kSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.generatedFiles.map { it.name }).contains("KSource.class") } @Test fun `Compiled Java class file is among generated files list`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; @ProcessElem class JSource { void foo() { } } """ ) val result = defaultCompilerConfig().apply { sources = listOf(jSource) annotationProcessors = listOf(kotlinTestProc) inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.generatedFiles.map { it.name }).contains("JSource.class") } @Test fun `Custom plugin receives CLI argument`() { val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting; class KSource() """.trimIndent() ) val cliProcessor = spy(object : CommandLineProcessor { override val pluginId = "myPluginId" override val pluginOptions = listOf(CliOption("test_option_name", "", "")) }) val result = defaultCompilerConfig().apply { sources = listOf(kSource) inheritClassPath = false pluginOptions = listOf(PluginOption("myPluginId", "test_option_name", "test_value")) commandLineProcessors = listOf(cliProcessor) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) verify(cliProcessor, atLeastOnce()).processOption(argWhere<AbstractCliOption> { it.optionName == "test_option_name" }, eq("test_value"), any()) verify(cliProcessor, never()).processOption(argWhere<AbstractCliOption> { it.optionName == "test_option_name" }, not(eq("test_value")), any()) verify(cliProcessor, never()).processOption(argWhere<AbstractCliOption> { it.optionName != "test_option_name" }, any(), any()) } @Test fun `Output directory contains compiled class files`() { val jSource = SourceFile.java( "JSource.java", """ package com.tschuchort.compiletesting; @ProcessElem class JSource { void foo() { } } """ ) val kSource = SourceFile.kotlin( "KSource.kt", """ package com.tschuchort.compiletesting @ProcessElem class KSource { fun foo() {} } """ ) val result = defaultCompilerConfig().apply { sources = listOf(jSource, kSource) annotationProcessors = emptyList() inheritClassPath = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.outputDirectory.listFilesRecursively().map { it.name }) .contains("JSource.class", "KSource.class") } @Test fun `java compilation runs in process when no jdk is specified`() { val source = SourceFile.java("JSource.java", """ class JSource {} """.trimIndent()) val result = defaultCompilerConfig().apply { sources = listOf(source) }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertThat(result.messages).contains( "jdkHome is not specified. Using system java compiler of the host process." ) assertThat(result.messages).doesNotContain( "jdkHome is set to null, removing boot classpath from java compilation" ) } @Ignore // Ignored because symlinks can't be created on Windows 7 without admin rights @Test fun `java compilation runs in a sub-process when jdk is specified`() { val source = SourceFile.java("JSource.java", """ class JSource {} """.trimIndent()) val fakeJdkHome = temporaryFolder.newFolder("jdk-copy") fakeJdkHome.mkdirs() Files.createLink(fakeJdkHome.resolve("bin").toPath(), processJdkHome.toPath()) val logsStream = ByteArrayOutputStream() val compiler = defaultCompilerConfig().apply { sources = listOf(source) jdkHome = fakeJdkHome messageOutputStream = logsStream } val result = compiler.compile() assertThat(result.exitCode).isEqualTo(ExitCode.COMPILATION_ERROR) val logs = logsStream.toString("utf-8")// use string charset for jdk 8 compatibility assertThat(logs).contains( "compiling java in a sub-process because a jdkHome is specified" ) assertThat(logs).doesNotContain( "jdkHome is set to null, removing boot classpath from java compilation" ) fakeJdkHome.delete() } @Test fun `the classLoader from a 2nd compilation can load classes from the first compilation`() { val kSource1 = SourceFile.kotlin( "KSource1.kt", """ package com.tschuchort.compiletesting interface KSource1 """ ) val result = defaultCompilerConfig() .apply { sources = listOf(kSource1) inheritClassPath = true } .compile() .apply { assertThat(exitCode).isEqualTo(ExitCode.OK) assertThat(outputDirectory.listFilesRecursively().map { it.name }).contains("KSource1.class") } val kSource2 = SourceFile.kotlin( "KSource2.kt", """ package com.tschuchort.compiletesting interface KSource2 : KSource1 """ ) defaultCompilerConfig() .apply { sources = listOf(kSource2) inheritClassPath = true } .addPreviousResultToClasspath(result) .compile() .apply { assertThat(exitCode).isEqualTo(ExitCode.OK) assertThat(outputDirectory.listFilesRecursively().map { it.name }).contains("KSource2.class") assertThat(classLoader.loadClass("com.tschuchort.compiletesting.KSource2")).isNotNull } } @Test fun `runs the K2 compiler without compiler plugins`() { val result = defaultCompilerConfig().apply { sources = listOf(SourceFile.kotlin("kSource.kt", "class KSource")) compilerPlugins = emptyList() pluginClasspaths = emptyList() useK2 = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) assertClassLoadable(result, "KSource") } @Test fun `can compile code with multi-platform expect modifier`() { val result = defaultCompilerConfig().apply { sources = listOf( SourceFile.kotlin("kSource1.kt", "expect interface MppInterface"), SourceFile.kotlin("kSource2.kt", "actual interface MppInterface") ) multiplatform = true }.compile() assertThat(result.exitCode).isEqualTo(ExitCode.OK) } class InheritedClass {} }
core/src/test/kotlin/com/tschuchort/compiletesting/KotlinCompilationTests.kt
3717478433
package ninenine.com.duplicateuser.view import ninenine.com.duplicateuser.domain.User interface UserContractView: IView { fun showUsers(users: Collection<User>) }
app/src/main/java/ninenine/com/duplicateuser/view/UserContractView.kt
2951858278
package com.sergey.spacegame.common.game /** * Represents the dimensional limits of a level * * @author sergeys * * @constructor Creates a new LevelLimits object * * @property minX - the minimum x coordinate * @property maxX - the maximum x coordinate * @property minY - the minimum y coordinate * @property maxY - the maximum y coordinate */ data class LevelLimits(val minX: Float, val maxX: Float, val minY: Float, val maxY: Float) { /** * The width of the level */ val width: Float get() = maxX - minX /** * The height of the level */ val height: Float get() = maxY - minY /** * The center x coordinate of the level */ val centerX: Float get() = (maxX + minX) / 2f /** * The center y coordinate of the level */ val centerY: Float get() = (maxY + minY) / 2f } /** * Represents the background of a level * * @author sergeys * * @constructor Creates a new Background object * * @property image - the name of the image to use for the background */ data class Background(val image: String)
core/src/com/sergey/spacegame/common/game/LevelData.kt
2631260610
package com.naosim.someapp.infra.api.task.complete import com.naosim.rtm.domain.model.auth.Token import com.naosim.someapp.domain.タスクEntity import com.naosim.someapp.domain.タスクID import com.naosim.someapp.domain.タスク名 import com.naosim.someapp.domain.タスク消化予定日Optional import com.naosim.someapp.infra.MapConverter import com.naosim.someapp.infra.RepositoryFactory import com.naosim.someapp.infra.api.lib.Api import com.naosim.someapp.infra.api.lib.ApiRequestParams import com.naosim.someapp.infra.api.lib.RequiredParam import com.naosim.someapp.infra.api.task.add.TaskAddRequest import java.util.function.Function class TaskCompleteApi(val repositoryFactory: RepositoryFactory): Api<TaskCompleteRequest> { val mapConvertor = MapConverter() override val description = "タスク完了" override val path = "/task/complete" override val requestParams = TaskCompleteRequest() override val ok: (TaskCompleteRequest) -> Any = { val タスクEntity: タスクEntity = completeTask(it.token.get(), it.taskId.get()) mapConvertor.apiOkResult(listOf(mapConvertor.toMap(タスクEntity))) } fun completeTask(token: Token, タスクID: タスクID): タスクEntity { return repositoryFactory.createタスクRepository(token).完了(タスクID) } } class TaskCompleteRequest : ApiRequestParams<TaskCompleteRequest>() { @JvmField val taskId = RequiredParam<タスクID>("task_id", Function { タスクID(it) }) @JvmField val token = RequiredParam<Token>("token", Function { Token(it) }) }
src/main/java/com/naosim/someapp/infra/api/task/complete/TaskCompleteApi.kt
3979855887
package com.iamsalih.openweatherapplication.ui import android.os.Parcel import android.os.Parcelable /** * Created by muhammedsalihguler on 30.07.17. */ data class ForecastItemViewModel(val degreeDay : String?, val icon : String = "01d", val date : Long = System.currentTimeMillis(), val description: String = "No description", val minimumDegree : String?, val maximumDegree : String?, val pressure : String?, val humidity : String?, val cityName : String?) : Parcelable { constructor(parcel: Parcel) : this( parcel.readString(), parcel.readString(), parcel.readLong(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString(), parcel.readString()) { } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(degreeDay) parcel.writeString(icon) parcel.writeLong(date) parcel.writeString(description) parcel.writeString(minimumDegree) parcel.writeString(maximumDegree) parcel.writeString(pressure) parcel.writeString(humidity) parcel.writeString(cityName) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<ForecastItemViewModel> { override fun createFromParcel(parcel: Parcel): ForecastItemViewModel { return ForecastItemViewModel(parcel) } override fun newArray(size: Int): Array<ForecastItemViewModel?> { return arrayOfNulls(size) } } }
app/src/main/java/com/iamsalih/openweatherapplication/ui/ForecastItemViewModel.kt
3284057964
package org.wordpress.android.fluxc.example.di import android.app.Application import dagger.BindsInstance import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import org.wordpress.android.fluxc.di.WCDatabaseModule import org.wordpress.android.fluxc.example.ExampleApp import org.wordpress.android.fluxc.module.DatabaseModule import org.wordpress.android.fluxc.module.OkHttpClientModule import org.wordpress.android.fluxc.module.ReleaseNetworkModule import javax.inject.Singleton @Singleton @Component(modules = [ AndroidInjectionModule::class, ApplicationModule::class, AppConfigModule::class, OkHttpClientModule::class, ReleaseNetworkModule::class, MainActivityModule::class, WCOrderListActivityModule::class, WCDatabaseModule::class, DatabaseModule::class]) interface AppComponent : AndroidInjector<ExampleApp> { override fun inject(app: ExampleApp) // Allows us to inject the application without having to instantiate any modules, and provides the Application // in the app graph @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): AppComponent } }
example/src/main/java/org/wordpress/android/fluxc/example/di/AppComponent.kt
2177786833
package com.boardgamegeek.provider import android.content.Context import android.content.SharedPreferences import android.database.SQLException import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.os.Environment import android.provider.BaseColumns import com.boardgamegeek.pref.SyncPrefs import com.boardgamegeek.pref.clearCollection import com.boardgamegeek.pref.clearPlaysTimestamps import com.boardgamegeek.provider.BggContract.* import com.boardgamegeek.provider.BggContract.Collection import com.boardgamegeek.service.SyncService import com.boardgamegeek.util.FileUtils.deleteContents import com.boardgamegeek.util.TableBuilder import com.boardgamegeek.util.TableBuilder.ColumnType import com.boardgamegeek.util.TableBuilder.ConflictResolution import timber.log.Timber import java.io.File import java.io.IOException import java.util.* class BggDatabase(private val context: Context?) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) { var syncPrefs: SharedPreferences = SyncPrefs.getPrefs(context!!) object GamesDesigners { const val GAME_ID = Games.Columns.GAME_ID const val DESIGNER_ID = Designers.Columns.DESIGNER_ID } object GamesArtists { const val GAME_ID = Games.Columns.GAME_ID const val ARTIST_ID = Artists.Columns.ARTIST_ID } object GamesPublishers { const val GAME_ID = Games.Columns.GAME_ID const val PUBLISHER_ID = Publishers.Columns.PUBLISHER_ID } object GamesMechanics { const val GAME_ID = Games.Columns.GAME_ID const val MECHANIC_ID = Mechanics.Columns.MECHANIC_ID } object GamesCategories { const val GAME_ID = Games.Columns.GAME_ID const val CATEGORY_ID = Categories.Columns.CATEGORY_ID } object Tables { const val DESIGNERS = "designers" const val ARTISTS = "artists" const val PUBLISHERS = "publishers" const val MECHANICS = "mechanics" const val CATEGORIES = "categories" const val GAMES = "games" const val GAME_RANKS = "game_ranks" const val GAMES_DESIGNERS = "games_designers" const val GAMES_ARTISTS = "games_artists" const val GAMES_PUBLISHERS = "games_publishers" const val GAMES_MECHANICS = "games_mechanics" const val GAMES_CATEGORIES = "games_categories" const val GAMES_EXPANSIONS = "games_expansions" const val COLLECTION = "collection" const val BUDDIES = "buddies" const val GAME_POLLS = "game_polls" const val GAME_POLL_RESULTS = "game_poll_results" const val GAME_POLL_RESULTS_RESULT = "game_poll_results_result" const val GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS = "game_suggested_player_count_poll_results" const val GAME_COLORS = "game_colors" const val PLAYS = "plays" const val PLAY_PLAYERS = "play_players" const val COLLECTION_VIEWS = "collection_filters" const val COLLECTION_VIEW_FILTERS = "collection_filters_details" const val PLAYER_COLORS = "player_colors" val GAMES_JOIN_COLLECTION = createJoin(GAMES, COLLECTION, Games.Columns.GAME_ID) val GAMES_DESIGNERS_JOIN_DESIGNERS = createJoin(GAMES_DESIGNERS, DESIGNERS, Designers.Columns.DESIGNER_ID) val GAMES_ARTISTS_JOIN_ARTISTS = createJoin(GAMES_ARTISTS, ARTISTS, Artists.Columns.ARTIST_ID) val GAMES_PUBLISHERS_JOIN_PUBLISHERS = createJoin(GAMES_PUBLISHERS, PUBLISHERS, Publishers.Columns.PUBLISHER_ID) val GAMES_MECHANICS_JOIN_MECHANICS = createJoin(GAMES_MECHANICS, MECHANICS, Mechanics.Columns.MECHANIC_ID) val GAMES_CATEGORIES_JOIN_CATEGORIES = createJoin(GAMES_CATEGORIES, CATEGORIES, Categories.Columns.CATEGORY_ID) val GAMES_EXPANSIONS_JOIN_EXPANSIONS = createJoin(GAMES_EXPANSIONS, GAMES, GamesExpansions.Columns.EXPANSION_ID, Games.Columns.GAME_ID) val GAMES_RANKS_JOIN_GAMES = createJoin(GAME_RANKS, GAMES, GameRanks.Columns.GAME_ID, Games.Columns.GAME_ID) val POLLS_JOIN_POLL_RESULTS = createJoin(GAME_POLLS, GAME_POLL_RESULTS, BaseColumns._ID, GamePollResults.Columns.POLL_ID) val POLLS_JOIN_GAMES = createJoin(GAMES, GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS, Games.Columns.GAME_ID, GameSuggestedPlayerCountPollPollResults.Columns.GAME_ID) val POLL_RESULTS_JOIN_POLL_RESULTS_RESULT = createJoin(GAME_POLL_RESULTS, GAME_POLL_RESULTS_RESULT, BaseColumns._ID, GamePollResultsResult.Columns.POLL_RESULTS_ID) val COLLECTION_JOIN_GAMES = createJoin(COLLECTION, GAMES, Games.Columns.GAME_ID) val GAMES_JOIN_PLAYS = GAMES + createJoinSuffix(GAMES, PLAYS, Games.Columns.GAME_ID, Plays.Columns.OBJECT_ID) val PLAYS_JOIN_GAMES = PLAYS + createJoinSuffix(PLAYS, GAMES, Plays.Columns.OBJECT_ID, Games.Columns.GAME_ID) val PLAY_PLAYERS_JOIN_PLAYS = createJoin(PLAY_PLAYERS, PLAYS, PlayPlayers.Columns._PLAY_ID, BaseColumns._ID) val PLAY_PLAYERS_JOIN_PLAYS_JOIN_USERS = PLAY_PLAYERS + createJoinSuffix(PLAY_PLAYERS, PLAYS, PlayPlayers.Columns._PLAY_ID, BaseColumns._ID) + createJoinSuffix(PLAY_PLAYERS, BUDDIES, PlayPlayers.Columns.USER_NAME, Buddies.Columns.BUDDY_NAME) val PLAY_PLAYERS_JOIN_PLAYS_JOIN_GAMES = PLAY_PLAYERS + createJoinSuffix(PLAY_PLAYERS, PLAYS, PlayPlayers.Columns._PLAY_ID, BaseColumns._ID) + createJoinSuffix(PLAYS, GAMES, Plays.Columns.OBJECT_ID, Games.Columns.GAME_ID) val COLLECTION_VIEW_FILTERS_JOIN_COLLECTION_VIEWS = createJoin(COLLECTION_VIEWS, COLLECTION_VIEW_FILTERS, BaseColumns._ID, CollectionViewFilters.Columns.VIEW_ID) val POLLS_RESULTS_RESULT_JOIN_POLLS_RESULTS_JOIN_POLLS = createJoin(GAME_POLL_RESULTS_RESULT, GAME_POLL_RESULTS, GamePollResultsResult.Columns.POLL_RESULTS_ID, BaseColumns._ID) + createJoinSuffix(GAME_POLL_RESULTS, GAME_POLLS, GamePollResults.Columns.POLL_ID, BaseColumns._ID) val ARTIST_JOIN_GAMES_JOIN_COLLECTION = createJoin(GAMES_ARTISTS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID) val DESIGNER_JOIN_GAMES_JOIN_COLLECTION = createJoin(GAMES_DESIGNERS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID) val PUBLISHER_JOIN_GAMES_JOIN_COLLECTION = createJoin(GAMES_PUBLISHERS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID) val MECHANIC_JOIN_GAMES_JOIN_COLLECTION = createJoin(GAMES_MECHANICS, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID) val CATEGORY_JOIN_GAMES_JOIN_COLLECTION = createJoin(GAMES_CATEGORIES, GAMES, Games.Columns.GAME_ID) + createJoinSuffix(GAMES, COLLECTION, Games.Columns.GAME_ID, Collection.Columns.GAME_ID) val ARTISTS_JOIN_COLLECTION = createJoin(ARTISTS, GAMES_ARTISTS, Artists.Columns.ARTIST_ID) + createInnerJoinSuffix(GAMES_ARTISTS, COLLECTION, GamesArtists.GAME_ID, Collection.Columns.GAME_ID) val DESIGNERS_JOIN_COLLECTION = createJoin(DESIGNERS, GAMES_DESIGNERS, Designers.Columns.DESIGNER_ID) + createInnerJoinSuffix(GAMES_DESIGNERS, COLLECTION, GamesDesigners.GAME_ID, Collection.Columns.GAME_ID) val PUBLISHERS_JOIN_COLLECTION = createJoin(PUBLISHERS, GAMES_PUBLISHERS, Publishers.Columns.PUBLISHER_ID) + createInnerJoinSuffix(GAMES_PUBLISHERS, COLLECTION, GamesPublishers.GAME_ID, Collection.Columns.GAME_ID) val MECHANICS_JOIN_COLLECTION = createJoin(MECHANICS, GAMES_MECHANICS, Mechanics.Columns.MECHANIC_ID) + createInnerJoinSuffix(GAMES_MECHANICS, COLLECTION, GamesMechanics.GAME_ID, Collection.Columns.GAME_ID) val CATEGORIES_JOIN_COLLECTION = createJoin(CATEGORIES, GAMES_CATEGORIES, Categories.Columns.CATEGORY_ID) + createInnerJoinSuffix(GAMES_CATEGORIES, COLLECTION, GamesCategories.GAME_ID, Collection.Columns.GAME_ID) private fun createJoin(table1: String, table2: String, column: String) = table1 + createJoinSuffix(table1, table2, column, column) private fun createJoin(table1: String, table2: String, column1: String, column2: String) = table1 + createJoinSuffix(table1, table2, column1, column2) private fun createJoinSuffix(table1: String, table2: String, column1: String, column2: String) = " LEFT OUTER JOIN $table2 ON $table1.$column1=$table2.$column2" private fun createInnerJoinSuffix(table1: String, table2: String, column1: String, column2: String) = " INNER JOIN $table2 ON $table1.$column1=$table2.$column2" } override fun onCreate(db: SQLiteDatabase?) { db?.let { buildDesignersTable().create(it) buildArtistsTable().create(it) buildPublishersTable().create(it) buildMechanicsTable().create(it) buildCategoriesTable().create(it) buildGamesTable().create(it) buildGameRanksTable().create(it) buildGamesDesignersTable().create(it) buildGamesArtistsTable().create(it) buildGamesPublishersTable().create(it) buildGamesMechanicsTable().create(it) buildGamesCategoriesTable().create(it) buildGameExpansionsTable().create(it) buildGamePollsTable().create(it) buildGamePollResultsTable().create(it) buildGamePollResultsResultTable().create(it) buildGameSuggestedPlayerCountPollResultsTable().create(it) buildGameColorsTable().create(it) buildPlaysTable().create(it) buildPlayPlayersTable().create(it) buildCollectionTable().create(it) buildBuddiesTable().create(it) buildPlayerColorsTable().create(it) buildCollectionViewsTable().create(it) buildCollectionViewFiltersTable().create(it) } } override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) { Timber.d("Upgrading database from $oldVersion to $newVersion") try { for (version in oldVersion..newVersion) { db?.let { when (version + 1) { VER_INITIAL -> {} VER_WISHLIST_PRIORITY -> addColumn(it, Tables.COLLECTION, Collection.Columns.STATUS_WISHLIST_PRIORITY, ColumnType.INTEGER) VER_GAME_COLORS -> buildGameColorsTable().create(it) VER_EXPANSIONS -> buildGameExpansionsTable().create(it) VER_VARIOUS -> { addColumn(it, Tables.COLLECTION, Collection.Columns.LAST_MODIFIED, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.LAST_VIEWED, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.STARRED, ColumnType.INTEGER) } VER_PLAYS -> { buildPlaysTable().create(it) buildPlayPlayersTable().create(it) } VER_PLAY_NICKNAME -> addColumn(it, Tables.BUDDIES, Buddies.Columns.PLAY_NICKNAME, ColumnType.TEXT) VER_PLAY_SYNC_STATUS -> { addColumn(it, Tables.PLAYS, "sync_status", ColumnType.INTEGER) addColumn(it, Tables.PLAYS, "updated", ColumnType.INTEGER) } VER_COLLECTION_VIEWS -> { buildCollectionViewsTable().create(it) buildCollectionViewFiltersTable().create(it) } VER_COLLECTION_VIEWS_SORT -> addColumn(it, Tables.COLLECTION_VIEWS, CollectionViews.Columns.SORT_TYPE, ColumnType.INTEGER) VER_CASCADING_DELETE -> { buildGameRanksTable().replace(it) buildGamesDesignersTable().replace(it) buildGamesArtistsTable().replace(it) buildGamesPublishersTable().replace(it) buildGamesMechanicsTable().replace(it) buildGamesCategoriesTable().replace(it) buildGameExpansionsTable().replace(it) buildGamePollsTable().replace(it) buildGamePollResultsTable().replace(it) buildGamePollResultsResultTable().replace(it) buildGameColorsTable().replace(it) buildPlayPlayersTable().replace(it) buildCollectionViewFiltersTable().replace(it) } VER_IMAGE_CACHE -> { try { @Suppress("DEPRECATION") val oldCacheDirectory = File(Environment.getExternalStorageDirectory(), BggContract.CONTENT_AUTHORITY) deleteContents(oldCacheDirectory) if (!oldCacheDirectory.delete()) Timber.i("Unable to delete old cache directory") } catch (e: IOException) { Timber.e(e, "Error clearing the cache") } } VER_GAMES_UPDATED_PLAYS -> addColumn(it, Tables.GAMES, Games.Columns.UPDATED_PLAYS, ColumnType.INTEGER) VER_COLLECTION -> { addColumn(it, Tables.COLLECTION, Collection.Columns.CONDITION, ColumnType.TEXT) addColumn(it, Tables.COLLECTION, Collection.Columns.HASPARTS_LIST, ColumnType.TEXT) addColumn(it, Tables.COLLECTION, Collection.Columns.WANTPARTS_LIST, ColumnType.TEXT) addColumn(it, Tables.COLLECTION, Collection.Columns.WISHLIST_COMMENT, ColumnType.TEXT) addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_YEAR_PUBLISHED, ColumnType.INTEGER) addColumn(it, Tables.COLLECTION, Collection.Columns.RATING, ColumnType.REAL) addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_THUMBNAIL_URL, ColumnType.TEXT) addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_IMAGE_URL, ColumnType.TEXT) buildCollectionTable().replace(it) } VER_GAME_COLLECTION_CONFLICT -> { addColumn(it, Tables.GAMES, Games.Columns.SUBTYPE, ColumnType.TEXT) addColumn(it, Tables.GAMES, Games.Columns.CUSTOM_PLAYER_SORT, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.GAME_RANK, ColumnType.INTEGER) buildGamesTable().replace(it) it.dropTable(Tables.COLLECTION) buildCollectionTable().create(it) syncPrefs.clearCollection() SyncService.sync(context, SyncService.FLAG_SYNC_COLLECTION) } VER_PLAYS_START_TIME -> addColumn(it, Tables.PLAYS, Plays.Columns.START_TIME, ColumnType.INTEGER) VER_PLAYS_PLAYER_COUNT -> { addColumn(it, Tables.PLAYS, Plays.Columns.PLAYER_COUNT, ColumnType.INTEGER) it.execSQL( "UPDATE ${Tables.PLAYS} SET ${Plays.Columns.PLAYER_COUNT}=(SELECT COUNT(${PlayPlayers.Columns.USER_ID}) FROM ${Tables.PLAY_PLAYERS} WHERE ${Tables.PLAYS}.${Plays.Columns.PLAY_ID}=${Tables.PLAY_PLAYERS}.${Plays.Columns.PLAY_ID})" ) } VER_GAMES_SUBTYPE -> addColumn(it, Tables.GAMES, Games.Columns.SUBTYPE, ColumnType.TEXT) VER_COLLECTION_ID_NULLABLE -> buildCollectionTable().replace(it) VER_GAME_CUSTOM_PLAYER_SORT -> addColumn(it, Tables.GAMES, Games.Columns.CUSTOM_PLAYER_SORT, ColumnType.INTEGER) VER_BUDDY_FLAG -> addColumn(it, Tables.BUDDIES, Buddies.Columns.BUDDY_FLAG, ColumnType.INTEGER) VER_GAME_RANK -> addColumn(it, Tables.GAMES, Games.Columns.GAME_RANK, ColumnType.INTEGER) VER_BUDDY_SYNC_HASH_CODE -> addColumn(it, Tables.BUDDIES, Buddies.Columns.SYNC_HASH_CODE, ColumnType.INTEGER) VER_PLAY_SYNC_HASH_CODE -> addColumn(it, Tables.PLAYS, Plays.Columns.SYNC_HASH_CODE, ColumnType.INTEGER) VER_PLAYER_COLORS -> buildPlayerColorsTable().create(it) VER_RATING_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.RATING_DIRTY_TIMESTAMP, ColumnType.INTEGER) VER_COMMENT_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER) VER_PRIVATE_INFO_DIRTY_TIMESTAMP -> addColumn(db, Tables.COLLECTION, Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP, ColumnType.INTEGER) VER_STATUS_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.STATUS_DIRTY_TIMESTAMP, ColumnType.INTEGER) VER_COLLECTION_DIRTY_TIMESTAMP -> addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_DIRTY_TIMESTAMP, ColumnType.INTEGER) VER_COLLECTION_DELETE_TIMESTAMP -> addColumn(db, Tables.COLLECTION, Collection.Columns.COLLECTION_DELETE_TIMESTAMP, ColumnType.INTEGER) VER_COLLECTION_TIMESTAMPS -> { addColumn(it, Tables.COLLECTION, Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER) addColumn(it, Tables.COLLECTION, Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP, ColumnType.INTEGER) addColumn(it, Tables.COLLECTION, Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER) addColumn(it, Tables.COLLECTION, Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER) } VER_PLAY_ITEMS_COLLAPSE -> { addColumn(it, Tables.PLAYS, Plays.Columns.ITEM_NAME, ColumnType.TEXT) addColumn(it, Tables.PLAYS, Plays.Columns.OBJECT_ID, ColumnType.INTEGER) it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.OBJECT_ID} = (SELECT play_items.object_id FROM play_items WHERE play_items.${Plays.Columns.PLAY_ID} = ${Tables.PLAYS}.${Plays.Columns.PLAY_ID}), ${Plays.Columns.ITEM_NAME} = (SELECT play_items.name FROM play_items WHERE play_items.${Plays.Columns.PLAY_ID} = ${Tables.PLAYS}.${Plays.Columns.PLAY_ID})") it.dropTable("play_items") } VER_PLAY_PLAYERS_KEY -> { val columnMap: MutableMap<String, String> = HashMap() columnMap[PlayPlayers.Columns._PLAY_ID] = "${Tables.PLAYS}.${BaseColumns._ID}" buildPlayPlayersTable().replace(it, columnMap, Tables.PLAYS, Plays.Columns.PLAY_ID) } VER_PLAY_DELETE_TIMESTAMP -> { addColumn(it, Tables.PLAYS, Plays.Columns.DELETE_TIMESTAMP, ColumnType.INTEGER) it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.DELETE_TIMESTAMP}=${System.currentTimeMillis()}, sync_status=0 WHERE sync_status=3") // 3 = deleted sync status } VER_PLAY_UPDATE_TIMESTAMP -> { addColumn(it, Tables.PLAYS, Plays.Columns.UPDATE_TIMESTAMP, ColumnType.INTEGER) it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.UPDATE_TIMESTAMP}=${System.currentTimeMillis()}, sync_status=0 WHERE sync_status=1") // 1 = update sync status } VER_PLAY_DIRTY_TIMESTAMP -> { addColumn(it, Tables.PLAYS, Plays.Columns.DIRTY_TIMESTAMP, ColumnType.INTEGER) it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.DIRTY_TIMESTAMP}=${System.currentTimeMillis()}, sync_status=0 WHERE sync_status=2") // 2 = in progress } VER_PLAY_PLAY_ID_NOT_REQUIRED -> { buildPlaysTable().replace(it) it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.PLAY_ID}=null WHERE ${Plays.Columns.PLAY_ID}>=100000000 AND (${Plays.Columns.DIRTY_TIMESTAMP}>0 OR ${Plays.Columns.UPDATE_TIMESTAMP}>0 OR ${Plays.Columns.DELETE_TIMESTAMP}>0)") it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.DIRTY_TIMESTAMP}=${System.currentTimeMillis()}, ${Plays.Columns.PLAY_ID}=null WHERE ${Plays.Columns.PLAY_ID}>=100000000") } VER_PLAYS_RESET -> { syncPrefs.clearPlaysTimestamps() it.execSQL("UPDATE ${Tables.PLAYS} SET ${Plays.Columns.SYNC_HASH_CODE}=0") SyncService.sync(context!!, SyncService.FLAG_SYNC_PLAYS) } VER_PLAYS_HARD_RESET -> { it.dropTable(Tables.PLAYS) it.dropTable(Tables.PLAY_PLAYERS) buildPlaysTable().create(it) buildPlayPlayersTable().create(it) syncPrefs.clearPlaysTimestamps() SyncService.sync(context, SyncService.FLAG_SYNC_PLAYS) } VER_COLLECTION_VIEWS_SELECTED_COUNT -> { addColumn(it, Tables.COLLECTION_VIEWS, CollectionViews.Columns.SELECTED_COUNT, ColumnType.INTEGER) addColumn(it, Tables.COLLECTION_VIEWS, CollectionViews.Columns.SELECTED_TIMESTAMP, ColumnType.INTEGER) } VER_SUGGESTED_PLAYER_COUNT_POLL -> { addColumn(it, Tables.GAMES, Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL, ColumnType.INTEGER) buildGameSuggestedPlayerCountPollResultsTable().create(it) } VER_SUGGESTED_PLAYER_COUNT_RECOMMENDATION -> addColumn( db, Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS, GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION, ColumnType.INTEGER ) VER_MIN_MAX_PLAYING_TIME -> { addColumn(it, Tables.GAMES, Games.Columns.MIN_PLAYING_TIME, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.MAX_PLAYING_TIME, ColumnType.INTEGER) } VER_SUGGESTED_PLAYER_COUNT_RE_SYNC -> { it.execSQL("UPDATE ${Tables.GAMES} SET ${Games.Columns.UPDATED_LIST}=0, ${Games.Columns.UPDATED}=0, ${Games.Columns.UPDATED_PLAYS}=0") SyncService.sync(context, SyncService.FLAG_SYNC_GAMES) } VER_GAME_HERO_IMAGE_URL -> addColumn(it, Tables.GAMES, Games.Columns.HERO_IMAGE_URL, ColumnType.TEXT) VER_COLLECTION_HERO_IMAGE_URL -> addColumn(it, Tables.COLLECTION, Collection.Columns.COLLECTION_HERO_IMAGE_URL, ColumnType.TEXT) VER_GAME_PALETTE_COLORS -> { addColumn(it, Tables.GAMES, Games.Columns.ICON_COLOR, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.DARK_COLOR, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.WINS_COLOR, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.WINNABLE_PLAYS_COLOR, ColumnType.INTEGER) addColumn(it, Tables.GAMES, Games.Columns.ALL_PLAYS_COLOR, ColumnType.INTEGER) } VER_PRIVATE_INFO_INVENTORY_LOCATION -> addColumn(db, Tables.COLLECTION, Collection.Columns.PRIVATE_INFO_INVENTORY_LOCATION, ColumnType.TEXT) VER_ARTIST_IMAGES -> { addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_IMAGE_URL, ColumnType.TEXT) addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_THUMBNAIL_URL, ColumnType.TEXT) addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_HERO_IMAGE_URL, ColumnType.TEXT) addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER) } VER_DESIGNER_IMAGES -> { addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_IMAGE_URL, ColumnType.TEXT) addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_THUMBNAIL_URL, ColumnType.TEXT) addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_HERO_IMAGE_URL, ColumnType.TEXT) addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER) } VER_PUBLISHER_IMAGES -> { addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_IMAGE_URL, ColumnType.TEXT) addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_THUMBNAIL_URL, ColumnType.TEXT) addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_HERO_IMAGE_URL, ColumnType.TEXT) addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_SORT_NAME, ColumnType.INTEGER) } VER_WHITMORE_SCORE -> { addColumn(it, Tables.DESIGNERS, Designers.Columns.WHITMORE_SCORE, ColumnType.INTEGER) addColumn(it, Tables.ARTISTS, Artists.Columns.WHITMORE_SCORE, ColumnType.INTEGER) addColumn(it, Tables.PUBLISHERS, Publishers.Columns.WHITMORE_SCORE, ColumnType.INTEGER) } VER_DAP_STATS_UPDATED_TIMESTAMP -> { addColumn(it, Tables.DESIGNERS, Designers.Columns.DESIGNER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER) addColumn(it, Tables.ARTISTS, Artists.Columns.ARTIST_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER) addColumn(it, Tables.PUBLISHERS, Publishers.Columns.PUBLISHER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER) } VER_RECOMMENDED_PLAYER_COUNTS -> { addColumn(it, Tables.GAMES, Games.Columns.PLAYER_COUNTS_BEST, ColumnType.TEXT) addColumn(it, Tables.GAMES, Games.Columns.PLAYER_COUNTS_RECOMMENDED, ColumnType.TEXT) addColumn(it, Tables.GAMES, Games.Columns.PLAYER_COUNTS_NOT_RECOMMENDED, ColumnType.TEXT) it.execSQL("UPDATE ${Tables.GAMES} SET ${Games.Columns.UPDATED_LIST}=0, ${Games.Columns.UPDATED}=0, ${Games.Columns.UPDATED_PLAYS}=0") SyncService.sync(context, SyncService.FLAG_SYNC_GAMES) } } } } } catch (e: Exception) { Timber.e(e) recreateDatabase(db) } } override fun onOpen(db: SQLiteDatabase?) { super.onOpen(db) if (db?.isReadOnly == false) { db.execSQL("PRAGMA foreign_keys=ON;") } } private fun buildDesignersTable() = TableBuilder() .setTable(Tables.DESIGNERS) .useDefaultPrimaryKey() .addColumn(Designers.Columns.UPDATED, ColumnType.INTEGER) .addColumn(Designers.Columns.DESIGNER_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(Designers.Columns.DESIGNER_NAME, ColumnType.TEXT, true) .addColumn(Designers.Columns.DESIGNER_DESCRIPTION, ColumnType.TEXT) .addColumn(Designers.Columns.DESIGNER_IMAGE_URL, ColumnType.TEXT) .addColumn(Designers.Columns.DESIGNER_THUMBNAIL_URL, ColumnType.TEXT) .addColumn(Designers.Columns.DESIGNER_HERO_IMAGE_URL, ColumnType.TEXT) .addColumn(Designers.Columns.DESIGNER_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER) .addColumn(Designers.Columns.WHITMORE_SCORE, ColumnType.INTEGER) .addColumn(Designers.Columns.DESIGNER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER) private fun buildArtistsTable() = TableBuilder() .setTable(Tables.ARTISTS) .useDefaultPrimaryKey() .addColumn(Artists.Columns.UPDATED, ColumnType.INTEGER) .addColumn(Artists.Columns.ARTIST_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(Artists.Columns.ARTIST_NAME, ColumnType.TEXT, true) .addColumn(Artists.Columns.ARTIST_DESCRIPTION, ColumnType.TEXT) .addColumn(Artists.Columns.ARTIST_IMAGE_URL, ColumnType.TEXT) .addColumn(Artists.Columns.ARTIST_THUMBNAIL_URL, ColumnType.TEXT) .addColumn(Artists.Columns.ARTIST_HERO_IMAGE_URL, ColumnType.TEXT) .addColumn(Artists.Columns.ARTIST_IMAGES_UPDATED_TIMESTAMP, ColumnType.INTEGER) .addColumn(Artists.Columns.WHITMORE_SCORE, ColumnType.INTEGER) .addColumn(Artists.Columns.ARTIST_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER) private fun buildPublishersTable() = TableBuilder() .setTable(Tables.PUBLISHERS) .useDefaultPrimaryKey() .addColumn(Publishers.Columns.UPDATED, ColumnType.INTEGER) .addColumn(Publishers.Columns.PUBLISHER_ID, ColumnType.INTEGER, true, unique = true) .addColumn(Publishers.Columns.PUBLISHER_NAME, ColumnType.TEXT, true) .addColumn(Publishers.Columns.PUBLISHER_DESCRIPTION, ColumnType.TEXT) .addColumn(Publishers.Columns.PUBLISHER_IMAGE_URL, ColumnType.TEXT) .addColumn(Publishers.Columns.PUBLISHER_THUMBNAIL_URL, ColumnType.TEXT) .addColumn(Publishers.Columns.PUBLISHER_HERO_IMAGE_URL, ColumnType.TEXT) .addColumn(Publishers.Columns.PUBLISHER_SORT_NAME, ColumnType.TEXT) .addColumn(Publishers.Columns.WHITMORE_SCORE, ColumnType.INTEGER) .addColumn(Publishers.Columns.PUBLISHER_STATS_UPDATED_TIMESTAMP, ColumnType.INTEGER) private fun buildMechanicsTable() = TableBuilder() .setTable(Tables.MECHANICS) .useDefaultPrimaryKey() .addColumn(Mechanics.Columns.MECHANIC_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(Mechanics.Columns.MECHANIC_NAME, ColumnType.TEXT, true) private fun buildCategoriesTable() = TableBuilder() .setTable(Tables.CATEGORIES) .useDefaultPrimaryKey() .addColumn(Categories.Columns.CATEGORY_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(Categories.Columns.CATEGORY_NAME, ColumnType.TEXT, true) private fun buildGamesTable() = TableBuilder() .setTable(Tables.GAMES) .useDefaultPrimaryKey() .addColumn(Games.Columns.UPDATED, ColumnType.INTEGER) .addColumn(Games.Columns.UPDATED_LIST, ColumnType.INTEGER, true) .addColumn(Games.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(Games.Columns.GAME_NAME, ColumnType.TEXT, true) .addColumn(Games.Columns.GAME_SORT_NAME, ColumnType.TEXT, true) .addColumn(Games.Columns.YEAR_PUBLISHED, ColumnType.INTEGER) .addColumn(Games.Columns.IMAGE_URL, ColumnType.TEXT) .addColumn(Games.Columns.THUMBNAIL_URL, ColumnType.TEXT) .addColumn(Games.Columns.MIN_PLAYERS, ColumnType.INTEGER) .addColumn(Games.Columns.MAX_PLAYERS, ColumnType.INTEGER) .addColumn(Games.Columns.PLAYING_TIME, ColumnType.INTEGER) .addColumn(Games.Columns.MIN_PLAYING_TIME, ColumnType.INTEGER) .addColumn(Games.Columns.MAX_PLAYING_TIME, ColumnType.INTEGER) .addColumn(Games.Columns.NUM_PLAYS, ColumnType.INTEGER, true, 0) .addColumn(Games.Columns.MINIMUM_AGE, ColumnType.INTEGER) .addColumn(Games.Columns.DESCRIPTION, ColumnType.TEXT) .addColumn(Games.Columns.SUBTYPE, ColumnType.TEXT) .addColumn(Games.Columns.STATS_USERS_RATED, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_AVERAGE, ColumnType.REAL) .addColumn(Games.Columns.STATS_BAYES_AVERAGE, ColumnType.REAL) .addColumn(Games.Columns.STATS_STANDARD_DEVIATION, ColumnType.REAL) .addColumn(Games.Columns.STATS_MEDIAN, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_NUMBER_OWNED, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_NUMBER_TRADING, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_NUMBER_WANTING, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_NUMBER_WISHING, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_NUMBER_COMMENTS, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_NUMBER_WEIGHTS, ColumnType.INTEGER) .addColumn(Games.Columns.STATS_AVERAGE_WEIGHT, ColumnType.REAL) .addColumn(Games.Columns.LAST_VIEWED, ColumnType.INTEGER) .addColumn(Games.Columns.STARRED, ColumnType.INTEGER) .addColumn(Games.Columns.UPDATED_PLAYS, ColumnType.INTEGER) .addColumn(Games.Columns.CUSTOM_PLAYER_SORT, ColumnType.INTEGER) .addColumn(Games.Columns.GAME_RANK, ColumnType.INTEGER) .addColumn(Games.Columns.SUGGESTED_PLAYER_COUNT_POLL_VOTE_TOTAL, ColumnType.INTEGER) .addColumn(Games.Columns.HERO_IMAGE_URL, ColumnType.TEXT) .addColumn(Games.Columns.ICON_COLOR, ColumnType.INTEGER) .addColumn(Games.Columns.DARK_COLOR, ColumnType.INTEGER) .addColumn(Games.Columns.WINS_COLOR, ColumnType.INTEGER) .addColumn(Games.Columns.WINNABLE_PLAYS_COLOR, ColumnType.INTEGER) .addColumn(Games.Columns.ALL_PLAYS_COLOR, ColumnType.INTEGER) .addColumn(Games.Columns.PLAYER_COUNTS_BEST, ColumnType.TEXT) .addColumn(Games.Columns.PLAYER_COUNTS_RECOMMENDED, ColumnType.TEXT) .addColumn(Games.Columns.PLAYER_COUNTS_NOT_RECOMMENDED, ColumnType.TEXT) .setConflictResolution(ConflictResolution.ABORT) private fun buildGameRanksTable() = TableBuilder() .setTable(Tables.GAME_RANKS) .useDefaultPrimaryKey() .addColumn( GameRanks.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn(GameRanks.Columns.GAME_RANK_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(GameRanks.Columns.GAME_RANK_TYPE, ColumnType.TEXT, true) .addColumn(GameRanks.Columns.GAME_RANK_NAME, ColumnType.TEXT, true) .addColumn(GameRanks.Columns.GAME_RANK_FRIENDLY_NAME, ColumnType.TEXT, true) .addColumn(GameRanks.Columns.GAME_RANK_VALUE, ColumnType.INTEGER, true) .addColumn(GameRanks.Columns.GAME_RANK_BAYES_AVERAGE, ColumnType.REAL, true) .setConflictResolution(ConflictResolution.REPLACE) private fun buildGamesDesignersTable() = TableBuilder() .setTable(Tables.GAMES_DESIGNERS) .useDefaultPrimaryKey() .addColumn( GamesDesigners.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn( GamesDesigners.DESIGNER_ID, ColumnType.INTEGER, true, unique = true, referenceTable = Tables.DESIGNERS, referenceColumn = Designers.Columns.DESIGNER_ID ) private fun buildGamesArtistsTable() = TableBuilder().setTable(Tables.GAMES_ARTISTS).useDefaultPrimaryKey() .addColumn( GamesArtists.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn( GamesArtists.ARTIST_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.ARTISTS, referenceColumn = Artists.Columns.ARTIST_ID ) private fun buildGamesPublishersTable() = TableBuilder() .setTable(Tables.GAMES_PUBLISHERS) .useDefaultPrimaryKey() .addColumn( GamesPublishers.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn( GamesPublishers.PUBLISHER_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.PUBLISHERS, referenceColumn = Publishers.Columns.PUBLISHER_ID ) private fun buildGamesMechanicsTable() = TableBuilder() .setTable(Tables.GAMES_MECHANICS) .useDefaultPrimaryKey() .addColumn( GamesMechanics.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn( GamesMechanics.MECHANIC_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.MECHANICS, referenceColumn = Mechanics.Columns.MECHANIC_ID ) private fun buildGamesCategoriesTable() = TableBuilder() .setTable(Tables.GAMES_CATEGORIES) .useDefaultPrimaryKey() .addColumn( GamesCategories.GAME_ID, ColumnType.INTEGER, true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn( GamesCategories.CATEGORY_ID, ColumnType.INTEGER, true, unique = true, referenceTable = Tables.CATEGORIES, referenceColumn = Categories.Columns.CATEGORY_ID ) private fun buildGameExpansionsTable() = TableBuilder() .setTable(Tables.GAMES_EXPANSIONS) .useDefaultPrimaryKey() .addColumn( GamesExpansions.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn(GamesExpansions.Columns.EXPANSION_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(GamesExpansions.Columns.EXPANSION_NAME, ColumnType.TEXT, true) .addColumn(GamesExpansions.Columns.INBOUND, ColumnType.INTEGER) private fun buildGamePollsTable() = TableBuilder() .setTable(Tables.GAME_POLLS) .useDefaultPrimaryKey() .addColumn( GamePolls.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn(GamePolls.Columns.POLL_NAME, ColumnType.TEXT, notNull = true, unique = true) .addColumn(GamePolls.Columns.POLL_TITLE, ColumnType.TEXT, true) .addColumn(GamePolls.Columns.POLL_TOTAL_VOTES, ColumnType.INTEGER, true) private fun buildGamePollResultsTable() = TableBuilder() .setTable(Tables.GAME_POLL_RESULTS) .useDefaultPrimaryKey() .addColumn( GamePollResults.Columns.POLL_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAME_POLLS, referenceColumn = BaseColumns._ID, onCascadeDelete = true ) .addColumn(GamePollResults.Columns.POLL_RESULTS_KEY, ColumnType.TEXT, notNull = true, unique = true) .addColumn(GamePollResults.Columns.POLL_RESULTS_PLAYERS, ColumnType.TEXT) .addColumn(GamePollResults.Columns.POLL_RESULTS_SORT_INDEX, ColumnType.INTEGER, true) private fun buildGamePollResultsResultTable() = TableBuilder() .setTable(Tables.GAME_POLL_RESULTS_RESULT) .useDefaultPrimaryKey() .addColumn( GamePollResultsResult.Columns.POLL_RESULTS_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAME_POLL_RESULTS, referenceColumn = BaseColumns._ID, onCascadeDelete = true ) .addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_KEY, ColumnType.TEXT, notNull = true, unique = true) .addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_LEVEL, ColumnType.INTEGER) .addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VALUE, ColumnType.TEXT, true) .addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_VOTES, ColumnType.INTEGER, true) .addColumn(GamePollResultsResult.Columns.POLL_RESULTS_RESULT_SORT_INDEX, ColumnType.INTEGER, true) private fun buildGameSuggestedPlayerCountPollResultsTable() = TableBuilder() .setTable(Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS) .useDefaultPrimaryKey() .addColumn( GameSuggestedPlayerCountPollPollResults.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn(GameSuggestedPlayerCountPollPollResults.Columns.PLAYER_COUNT, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(GameSuggestedPlayerCountPollPollResults.Columns.SORT_INDEX, ColumnType.INTEGER) .addColumn(GameSuggestedPlayerCountPollPollResults.Columns.BEST_VOTE_COUNT, ColumnType.INTEGER) .addColumn(GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDED_VOTE_COUNT, ColumnType.INTEGER) .addColumn(GameSuggestedPlayerCountPollPollResults.Columns.NOT_RECOMMENDED_VOTE_COUNT, ColumnType.INTEGER) .addColumn(GameSuggestedPlayerCountPollPollResults.Columns.RECOMMENDATION, ColumnType.INTEGER) private fun buildGameColorsTable() = TableBuilder() .setTable(Tables.GAME_COLORS) .useDefaultPrimaryKey() .addColumn( GameColors.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = true, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn(GameColors.Columns.COLOR, ColumnType.TEXT, notNull = true, unique = true) private fun buildPlaysTable() = TableBuilder() .setTable(Tables.PLAYS) .useDefaultPrimaryKey() .addColumn(Plays.Columns.SYNC_TIMESTAMP, ColumnType.INTEGER, true) .addColumn(Plays.Columns.PLAY_ID, ColumnType.INTEGER) .addColumn(Plays.Columns.DATE, ColumnType.TEXT, true) .addColumn(Plays.Columns.QUANTITY, ColumnType.INTEGER, true) .addColumn(Plays.Columns.LENGTH, ColumnType.INTEGER, true) .addColumn(Plays.Columns.INCOMPLETE, ColumnType.INTEGER, true) .addColumn(Plays.Columns.NO_WIN_STATS, ColumnType.INTEGER, true) .addColumn(Plays.Columns.LOCATION, ColumnType.TEXT) .addColumn(Plays.Columns.COMMENTS, ColumnType.TEXT) .addColumn(Plays.Columns.START_TIME, ColumnType.INTEGER) .addColumn(Plays.Columns.PLAYER_COUNT, ColumnType.INTEGER) .addColumn(Plays.Columns.SYNC_HASH_CODE, ColumnType.INTEGER) .addColumn(Plays.Columns.ITEM_NAME, ColumnType.TEXT, true) .addColumn(Plays.Columns.OBJECT_ID, ColumnType.INTEGER, true) .addColumn(Plays.Columns.DELETE_TIMESTAMP, ColumnType.INTEGER) .addColumn(Plays.Columns.UPDATE_TIMESTAMP, ColumnType.INTEGER) .addColumn(Plays.Columns.DIRTY_TIMESTAMP, ColumnType.INTEGER) private fun buildPlayPlayersTable() = TableBuilder() .setTable(Tables.PLAY_PLAYERS) .useDefaultPrimaryKey() .addColumn( PlayPlayers.Columns._PLAY_ID, ColumnType.INTEGER, notNull = true, unique = false, referenceTable = Tables.PLAYS, referenceColumn = BaseColumns._ID, onCascadeDelete = true ) .addColumn(PlayPlayers.Columns.USER_NAME, ColumnType.TEXT) .addColumn(PlayPlayers.Columns.USER_ID, ColumnType.INTEGER) .addColumn(PlayPlayers.Columns.NAME, ColumnType.TEXT) .addColumn(PlayPlayers.Columns.START_POSITION, ColumnType.TEXT) .addColumn(PlayPlayers.Columns.COLOR, ColumnType.TEXT) .addColumn(PlayPlayers.Columns.SCORE, ColumnType.TEXT) .addColumn(PlayPlayers.Columns.NEW, ColumnType.INTEGER) .addColumn(PlayPlayers.Columns.RATING, ColumnType.REAL) .addColumn(PlayPlayers.Columns.WIN, ColumnType.INTEGER) private fun buildCollectionTable(): TableBuilder = TableBuilder() .setTable(Tables.COLLECTION) .useDefaultPrimaryKey() .addColumn(Collection.Columns.UPDATED, ColumnType.INTEGER) .addColumn(Collection.Columns.UPDATED_LIST, ColumnType.INTEGER) .addColumn( Collection.Columns.GAME_ID, ColumnType.INTEGER, notNull = true, unique = false, referenceTable = Tables.GAMES, referenceColumn = Games.Columns.GAME_ID, onCascadeDelete = true ) .addColumn(Collection.Columns.COLLECTION_ID, ColumnType.INTEGER) .addColumn(Collection.Columns.COLLECTION_NAME, ColumnType.TEXT, true) .addColumn(Collection.Columns.COLLECTION_SORT_NAME, ColumnType.TEXT, true) .addColumn(Collection.Columns.STATUS_OWN, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_PREVIOUSLY_OWNED, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_FOR_TRADE, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_WANT, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_WANT_TO_PLAY, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_WANT_TO_BUY, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_WISHLIST_PRIORITY, ColumnType.INTEGER) .addColumn(Collection.Columns.STATUS_WISHLIST, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.STATUS_PREORDERED, ColumnType.INTEGER, true, 0) .addColumn(Collection.Columns.COMMENT, ColumnType.TEXT) .addColumn(Collection.Columns.LAST_MODIFIED, ColumnType.INTEGER) .addColumn(Collection.Columns.PRIVATE_INFO_PRICE_PAID_CURRENCY, ColumnType.TEXT) .addColumn(Collection.Columns.PRIVATE_INFO_PRICE_PAID, ColumnType.REAL) .addColumn(Collection.Columns.PRIVATE_INFO_CURRENT_VALUE_CURRENCY, ColumnType.TEXT) .addColumn(Collection.Columns.PRIVATE_INFO_CURRENT_VALUE, ColumnType.REAL) .addColumn(Collection.Columns.PRIVATE_INFO_QUANTITY, ColumnType.INTEGER) .addColumn(Collection.Columns.PRIVATE_INFO_ACQUISITION_DATE, ColumnType.TEXT) .addColumn(Collection.Columns.PRIVATE_INFO_ACQUIRED_FROM, ColumnType.TEXT) .addColumn(Collection.Columns.PRIVATE_INFO_COMMENT, ColumnType.TEXT) .addColumn(Collection.Columns.CONDITION, ColumnType.TEXT) .addColumn(Collection.Columns.HASPARTS_LIST, ColumnType.TEXT) .addColumn(Collection.Columns.WANTPARTS_LIST, ColumnType.TEXT) .addColumn(Collection.Columns.WISHLIST_COMMENT, ColumnType.TEXT) .addColumn(Collection.Columns.COLLECTION_YEAR_PUBLISHED, ColumnType.INTEGER) .addColumn(Collection.Columns.RATING, ColumnType.REAL) .addColumn(Collection.Columns.COLLECTION_THUMBNAIL_URL, ColumnType.TEXT) .addColumn(Collection.Columns.COLLECTION_IMAGE_URL, ColumnType.TEXT) .addColumn(Collection.Columns.STATUS_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.RATING_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.PRIVATE_INFO_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.COLLECTION_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.COLLECTION_DELETE_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.WISHLIST_COMMENT_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.TRADE_CONDITION_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.WANT_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.HAS_PARTS_DIRTY_TIMESTAMP, ColumnType.INTEGER) .addColumn(Collection.Columns.COLLECTION_HERO_IMAGE_URL, ColumnType.TEXT) .addColumn(Collection.Columns.PRIVATE_INFO_INVENTORY_LOCATION, ColumnType.TEXT) .setConflictResolution(ConflictResolution.ABORT) private fun buildBuddiesTable() = TableBuilder().setTable(Tables.BUDDIES).useDefaultPrimaryKey() .addColumn(Buddies.Columns.UPDATED, ColumnType.INTEGER) .addColumn(Buddies.Columns.UPDATED_LIST, ColumnType.INTEGER, true) .addColumn(Buddies.Columns.BUDDY_ID, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(Buddies.Columns.BUDDY_NAME, ColumnType.TEXT, true) .addColumn(Buddies.Columns.BUDDY_FIRSTNAME, ColumnType.TEXT) .addColumn(Buddies.Columns.BUDDY_LASTNAME, ColumnType.TEXT) .addColumn(Buddies.Columns.AVATAR_URL, ColumnType.TEXT) .addColumn(Buddies.Columns.PLAY_NICKNAME, ColumnType.TEXT) .addColumn(Buddies.Columns.BUDDY_FLAG, ColumnType.INTEGER) .addColumn(Buddies.Columns.SYNC_HASH_CODE, ColumnType.INTEGER) private fun buildPlayerColorsTable() = TableBuilder().setTable(Tables.PLAYER_COLORS) .setConflictResolution(ConflictResolution.REPLACE) .useDefaultPrimaryKey() .addColumn(PlayerColors.Columns.PLAYER_TYPE, ColumnType.INTEGER, notNull = true, unique = true) .addColumn(PlayerColors.Columns.PLAYER_NAME, ColumnType.TEXT, notNull = true, unique = true) .addColumn(PlayerColors.Columns.PLAYER_COLOR, ColumnType.TEXT, notNull = true, unique = true) .addColumn(PlayerColors.Columns.PLAYER_COLOR_SORT_ORDER, ColumnType.INTEGER, true) private fun buildCollectionViewsTable() = TableBuilder() .setTable(Tables.COLLECTION_VIEWS) .useDefaultPrimaryKey() .addColumn(CollectionViews.Columns.NAME, ColumnType.TEXT) .addColumn(CollectionViews.Columns.STARRED, ColumnType.INTEGER) .addColumn(CollectionViews.Columns.SORT_TYPE, ColumnType.INTEGER) .addColumn(CollectionViews.Columns.SELECTED_COUNT, ColumnType.INTEGER) .addColumn(CollectionViews.Columns.SELECTED_TIMESTAMP, ColumnType.INTEGER) private fun buildCollectionViewFiltersTable() = TableBuilder() .setTable(Tables.COLLECTION_VIEW_FILTERS) .useDefaultPrimaryKey() .addColumn( CollectionViewFilters.Columns.VIEW_ID, ColumnType.INTEGER, notNull = true, unique = false, referenceTable = Tables.COLLECTION_VIEWS, referenceColumn = BaseColumns._ID, onCascadeDelete = true ) .addColumn(CollectionViewFilters.Columns.TYPE, ColumnType.INTEGER) .addColumn(CollectionViewFilters.Columns.DATA, ColumnType.TEXT) private fun recreateDatabase(db: SQLiteDatabase?) { if (db == null) return db.dropTable(Tables.DESIGNERS) db.dropTable(Tables.ARTISTS) db.dropTable(Tables.PUBLISHERS) db.dropTable(Tables.MECHANICS) db.dropTable(Tables.CATEGORIES) db.dropTable(Tables.GAMES) db.dropTable(Tables.GAME_RANKS) db.dropTable(Tables.GAMES_DESIGNERS) db.dropTable(Tables.GAMES_ARTISTS) db.dropTable(Tables.GAMES_PUBLISHERS) db.dropTable(Tables.GAMES_MECHANICS) db.dropTable(Tables.GAMES_CATEGORIES) db.dropTable(Tables.GAMES_EXPANSIONS) db.dropTable(Tables.COLLECTION) db.dropTable(Tables.BUDDIES) db.dropTable(Tables.GAME_POLLS) db.dropTable(Tables.GAME_POLL_RESULTS) db.dropTable(Tables.GAME_POLL_RESULTS_RESULT) db.dropTable(Tables.GAME_SUGGESTED_PLAYER_COUNT_POLL_RESULTS) db.dropTable(Tables.GAME_COLORS) db.dropTable(Tables.PLAYS) db.dropTable(Tables.PLAY_PLAYERS) db.dropTable(Tables.COLLECTION_VIEWS) db.dropTable(Tables.COLLECTION_VIEW_FILTERS) db.dropTable(Tables.PLAYER_COLORS) onCreate(db) } private fun SQLiteDatabase.dropTable(tableName: String) = this.execSQL("DROP TABLE IF EXISTS $tableName") private fun addColumn(db: SQLiteDatabase, table: String, column: String, type: ColumnType) { try { db.execSQL("ALTER TABLE $table ADD COLUMN $column $type") } catch (e: SQLException) { Timber.w(e, "Probably just trying to add an existing column.") } } companion object { private const val DATABASE_NAME = "bgg.db" private const val VER_INITIAL = 1 private const val VER_WISHLIST_PRIORITY = 2 private const val VER_GAME_COLORS = 3 private const val VER_EXPANSIONS = 4 private const val VER_VARIOUS = 5 private const val VER_PLAYS = 6 private const val VER_PLAY_NICKNAME = 7 private const val VER_PLAY_SYNC_STATUS = 8 private const val VER_COLLECTION_VIEWS = 9 private const val VER_COLLECTION_VIEWS_SORT = 10 private const val VER_CASCADING_DELETE = 11 private const val VER_IMAGE_CACHE = 12 private const val VER_GAMES_UPDATED_PLAYS = 13 private const val VER_COLLECTION = 14 private const val VER_GAME_COLLECTION_CONFLICT = 15 private const val VER_PLAYS_START_TIME = 16 private const val VER_PLAYS_PLAYER_COUNT = 17 private const val VER_GAMES_SUBTYPE = 18 private const val VER_COLLECTION_ID_NULLABLE = 19 private const val VER_GAME_CUSTOM_PLAYER_SORT = 20 private const val VER_BUDDY_FLAG = 21 private const val VER_GAME_RANK = 22 private const val VER_BUDDY_SYNC_HASH_CODE = 23 private const val VER_PLAY_SYNC_HASH_CODE = 24 private const val VER_PLAYER_COLORS = 25 private const val VER_RATING_DIRTY_TIMESTAMP = 27 private const val VER_COMMENT_DIRTY_TIMESTAMP = 28 private const val VER_PRIVATE_INFO_DIRTY_TIMESTAMP = 29 private const val VER_STATUS_DIRTY_TIMESTAMP = 30 private const val VER_COLLECTION_DIRTY_TIMESTAMP = 31 private const val VER_COLLECTION_DELETE_TIMESTAMP = 32 private const val VER_COLLECTION_TIMESTAMPS = 33 private const val VER_PLAY_ITEMS_COLLAPSE = 34 private const val VER_PLAY_PLAYERS_KEY = 36 private const val VER_PLAY_DELETE_TIMESTAMP = 37 private const val VER_PLAY_UPDATE_TIMESTAMP = 38 private const val VER_PLAY_DIRTY_TIMESTAMP = 39 private const val VER_PLAY_PLAY_ID_NOT_REQUIRED = 40 private const val VER_PLAYS_RESET = 41 private const val VER_PLAYS_HARD_RESET = 42 private const val VER_COLLECTION_VIEWS_SELECTED_COUNT = 43 private const val VER_SUGGESTED_PLAYER_COUNT_POLL = 44 private const val VER_SUGGESTED_PLAYER_COUNT_RECOMMENDATION = 45 private const val VER_MIN_MAX_PLAYING_TIME = 46 private const val VER_SUGGESTED_PLAYER_COUNT_RE_SYNC = 47 private const val VER_GAME_HERO_IMAGE_URL = 48 private const val VER_COLLECTION_HERO_IMAGE_URL = 49 private const val VER_GAME_PALETTE_COLORS = 50 private const val VER_PRIVATE_INFO_INVENTORY_LOCATION = 51 private const val VER_ARTIST_IMAGES = 52 private const val VER_DESIGNER_IMAGES = 53 private const val VER_PUBLISHER_IMAGES = 54 private const val VER_WHITMORE_SCORE = 55 private const val VER_DAP_STATS_UPDATED_TIMESTAMP = 56 private const val VER_RECOMMENDED_PLAYER_COUNTS = 57 private const val DATABASE_VERSION = VER_RECOMMENDED_PLAYER_COUNTS } }
app/src/main/java/com/boardgamegeek/provider/BggDatabase.kt
853293509
package com.vocalabs.egtest.codegenerator /** Builds a function used within a SourceFileBuilder. */ interface FunctionBuilder { /** Add one or more lines to the function. This may be called multiple times. */ fun addLines(lineToBeAdded: String) fun addAnnotation(annotationName: String, annotationBody: String? = null) }
kotlin-generator/src/main/kotlin/com/vocalabs/egtest/codegenerator/FunctionBuilder.kt
283527235
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.encoding import kotlinx.serialization.* import kotlinx.serialization.descriptors.* /** * A skeleton implementation of both [Decoder] and [CompositeDecoder] that can be used * for simple formats and for testability purpose. * Most of the `decode*` methods have default implementation that delegates `decodeValue(value: Any) as TargetType`. * See [Decoder] documentation for information about each particular `decode*` method. */ @ExperimentalSerializationApi public abstract class AbstractDecoder : Decoder, CompositeDecoder { /** * Invoked to decode a value when specialized `decode*` method was not overridden. */ public open fun decodeValue(): Any = throw SerializationException("${this::class} can't retrieve untyped values") override fun decodeNotNullMark(): Boolean = true override fun decodeNull(): Nothing? = null override fun decodeBoolean(): Boolean = decodeValue() as Boolean override fun decodeByte(): Byte = decodeValue() as Byte override fun decodeShort(): Short = decodeValue() as Short override fun decodeInt(): Int = decodeValue() as Int override fun decodeLong(): Long = decodeValue() as Long override fun decodeFloat(): Float = decodeValue() as Float override fun decodeDouble(): Double = decodeValue() as Double override fun decodeChar(): Char = decodeValue() as Char override fun decodeString(): String = decodeValue() as String override fun decodeEnum(enumDescriptor: SerialDescriptor): Int = decodeValue() as Int override fun decodeInline(descriptor: SerialDescriptor): Decoder = this // overwrite by default public open fun <T : Any?> decodeSerializableValue( deserializer: DeserializationStrategy<T>, previousValue: T? = null ): T = decodeSerializableValue(deserializer) override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder = this override fun endStructure(descriptor: SerialDescriptor) { } final override fun decodeBooleanElement(descriptor: SerialDescriptor, index: Int): Boolean = decodeBoolean() final override fun decodeByteElement(descriptor: SerialDescriptor, index: Int): Byte = decodeByte() final override fun decodeShortElement(descriptor: SerialDescriptor, index: Int): Short = decodeShort() final override fun decodeIntElement(descriptor: SerialDescriptor, index: Int): Int = decodeInt() final override fun decodeLongElement(descriptor: SerialDescriptor, index: Int): Long = decodeLong() final override fun decodeFloatElement(descriptor: SerialDescriptor, index: Int): Float = decodeFloat() final override fun decodeDoubleElement(descriptor: SerialDescriptor, index: Int): Double = decodeDouble() final override fun decodeCharElement(descriptor: SerialDescriptor, index: Int): Char = decodeChar() final override fun decodeStringElement(descriptor: SerialDescriptor, index: Int): String = decodeString() override fun decodeInlineElement( descriptor: SerialDescriptor, index: Int ): Decoder = decodeInline(descriptor.getElementDescriptor(index)) override fun <T> decodeSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T>, previousValue: T? ): T = decodeSerializableValue(deserializer, previousValue) final override fun <T : Any> decodeNullableSerializableElement( descriptor: SerialDescriptor, index: Int, deserializer: DeserializationStrategy<T?>, previousValue: T? ): T? { val isNullabilitySupported = deserializer.descriptor.isNullable return if (isNullabilitySupported || decodeNotNullMark()) decodeSerializableValue(deserializer, previousValue) else decodeNull() } }
core/commonMain/src/kotlinx/serialization/encoding/AbstractDecoder.kt
2965025239
package kotlinx.serialization.features import kotlinx.serialization.* import kotlinx.serialization.json.* import kotlin.test.* class MetaSerializableJsonTest : JsonTestBase() { @MetaSerializable @Target(AnnotationTarget.PROPERTY, AnnotationTarget.CLASS) annotation class JsonComment(val comment: String) @JsonComment("class_comment") data class IntDataCommented(val i: Int) @Serializable data class Carrier( val plain: String, @JsonComment("string_comment") val commented: StringData, val intData: IntDataCommented ) class CarrierSerializer : JsonTransformingSerializer<Carrier>(serializer()) { private val desc = Carrier.serializer().descriptor private fun List<Annotation>.comment(): String? = filterIsInstance<JsonComment>().firstOrNull()?.comment private val commentMap = (0 until desc.elementsCount).associateBy({ desc.getElementName(it) }, { desc.getElementAnnotations(it).comment() ?: desc.getElementDescriptor(it).annotations.comment() }) // NB: we may want to add this to public API private fun JsonElement.editObject(action: (MutableMap<String, JsonElement>) -> Unit): JsonElement { val mutable = this.jsonObject.toMutableMap() action(mutable) return JsonObject(mutable) } override fun transformDeserialize(element: JsonElement): JsonElement { return element.editObject { result -> for ((key, value) in result) { commentMap[key]?.let { result[key] = value.editObject { it.remove("comment") } } } } } override fun transformSerialize(element: JsonElement): JsonElement { return element.editObject { result -> for ((key, value) in result) { commentMap[key]?.let { comment -> result[key] = value.editObject { it["comment"] = JsonPrimitive(comment) } } } } } } @Test fun testMyJsonComment() { assertJsonFormAndRestored( CarrierSerializer(), Carrier("plain", StringData("string1"), IntDataCommented(42)), """{"plain":"plain","commented":{"data":"string1","comment":"string_comment"},"intData":{"i":42,"comment":"class_comment"}}""" ) } }
formats/json-tests/commonTest/src/kotlinx/serialization/features/MetaSerializableJsonTest.kt
3709871767
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.network.vanilla.packet.handler.play import org.lanternpowered.server.network.NetworkContext import org.lanternpowered.server.network.packet.PacketHandler import org.lanternpowered.server.network.vanilla.packet.type.play.ClientSprintStatePacket import org.lanternpowered.api.data.Keys object ClientSprintStateHandler : PacketHandler<ClientSprintStatePacket> { override fun handle(ctx: NetworkContext, packet: ClientSprintStatePacket) { ctx.session.player.offer(Keys.IS_SPRINTING, packet.isSprinting) } }
src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/play/ClientSprintStateHandler.kt
1461348538
package com.robyn.bitty.utils import org.junit.Test class ViewUtilsKtTest { @Test fun trimText() { val input = "RT @kengarex: Before/after photographs reveal how the world has changed… (32 photos) https://t.co/vmpmTRlLjC https://t.co/C13q9K5AfX" val expectedOutput = "RT @kengarex: Before/after photographs reveal how the world has changed… (32 photos) " val output = trimLinks(input) check(output == expectedOutput) } }
app/src/test/java/com/robyn/bitty/utils/ViewUtilsKtTest.kt
4255528496
package datastructs.fundamental.queue /** FIFO Queue */ public trait Queue<T> : Iterable<T> { override fun iterator(): Iterator<T> fun push(item: T) fun pop(): T fun clear() fun isEmpty(): Boolean fun size(): Int fun details() fun toList() : List<out T> }
src/datastructs/fundamental/queue/Queue.kt
3190285732
/* * Copyright (c) 2017. * Distributed under the GNU GPLv3 by David Whitman. * https://www.gnu.org/licenses/gpl-3.0.en.html * * This source code is made available to help others learn. Please don't clone my app. */ package com.thunderclouddev.playstoreapi import org.mockito.Mockito fun <T> anyKt(): T { return Mockito.any<T>() }
playstoreapi/src/test/java/com/thunderclouddev/playstoreapi/TestUtils.kt
1876335955
package ch.difty.scipamato.publ.web.paper.browse import ch.difty.scipamato.common.entity.CodeClassId import ch.difty.scipamato.common.web.LABEL_RESOURCE_TAG import ch.difty.scipamato.common.web.LABEL_TAG import ch.difty.scipamato.common.web.TITLE_RESOURCE_TAG import ch.difty.scipamato.common.web.component.SerializableConsumer import ch.difty.scipamato.common.web.component.table.column.ClickablePropertyColumn import ch.difty.scipamato.publ.entity.Code import ch.difty.scipamato.publ.entity.CodeClass import ch.difty.scipamato.publ.entity.PublicPaper import ch.difty.scipamato.publ.entity.filter.PublicPaperFilter import ch.difty.scipamato.publ.web.common.BasePage import ch.difty.scipamato.publ.web.model.CodeClassModel import ch.difty.scipamato.publ.web.model.CodeModel import com.giffing.wicket.spring.boot.context.scan.WicketHomePage import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapButton import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapExternalLink import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons import de.agilecoders.wicket.core.markup.html.bootstrap.table.TableBehavior import de.agilecoders.wicket.core.markup.html.bootstrap.tabs.BootstrapTabbedPanel import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapMultiSelect import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.select.BootstrapSelectConfig import de.agilecoders.wicket.extensions.markup.html.bootstrap.table.BootstrapDefaultDataTable import org.apache.wicket.AttributeModifier import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn import org.apache.wicket.extensions.markup.html.repeater.data.table.filter.FilterForm import org.apache.wicket.extensions.markup.html.tabs.AbstractTab import org.apache.wicket.extensions.markup.html.tabs.ITab import org.apache.wicket.markup.html.basic.Label import org.apache.wicket.markup.html.form.ChoiceRenderer import org.apache.wicket.markup.html.form.Form import org.apache.wicket.markup.html.panel.Panel import org.apache.wicket.model.IModel import org.apache.wicket.model.Model import org.apache.wicket.model.PropertyModel import org.apache.wicket.model.StringResourceModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.wicketstuff.annotation.mount.MountPath @WicketHomePage @MountPath("/") @Suppress("SameParameterValue", "UnnecessaryAbstractClass", "TooManyFunctions") class PublicPage(parameters: PageParameters) : BasePage<Void>(parameters) { private val filter: PublicPaperFilter = PublicPaperFilter() private val dataProvider = PublicPaperProvider(filter, RESULT_PAGE_SIZE) private var isQueryingInitialized = false override fun onInitialize() { super.onInitialize() makeAndQueueFilterForm("searchForm") makeAndQueueResultTable("results") } private fun makeAndQueueFilterForm(id: String) { object : FilterForm<PublicPaperFilter>(id, dataProvider) { override fun onSubmit() { super.onSubmit() updateNavigateable() } }.also { queue(it) addTabPanel(it, "tabs") queueQueryButton("query", it) } queueClearSearchButton("clear") queueHelpLink("help") } private fun addTabPanel( filterForm: FilterForm<PublicPaperFilter>, tabId: String, ) { mutableListOf<ITab>().apply { add(object : AbstractTab(StringResourceModel("tab1$LABEL_RESOURCE_TAG", this@PublicPage, null)) { override fun getPanel(panelId: String): Panel = TabPanel1(panelId, Model.of(filter)) }) add(object : AbstractTab(StringResourceModel("tab2$LABEL_RESOURCE_TAG", this@PublicPage, null)) { override fun getPanel(panelId: String): Panel = TabPanel2(panelId, Model.of(filter)) }) }.also { filterForm.add(BootstrapTabbedPanel(tabId, it)) } } private inner class TabPanel1( id: String, model: IModel<PublicPaperFilter>, ) : AbstractTabPanel(id, model) { override fun onInitialize() { super.onInitialize() queue(Form<Any>("tab1Form")) queue(SimpleFilterPanel("simpleFilterPanel", Model.of(filter), languageCode)) } } private inner class TabPanel2( id: String, model: IModel<PublicPaperFilter>, ) : AbstractTabPanel(id, model) { override fun onInitialize() { super.onInitialize() val form = Form<Any>("tab2Form") queue(form) queue(SimpleFilterPanel("simpleFilterPanel", Model.of(filter), languageCode)) CodeClassModel(languageCode).getObject().apply { makeCodeClassComplex(form, CodeClassId.CC1, this) makeCodeClassComplex(form, CodeClassId.CC2, this) makeCodeClassComplex(form, CodeClassId.CC3, this) makeCodeClassComplex(form, CodeClassId.CC4, this) makeCodeClassComplex(form, CodeClassId.CC5, this) makeCodeClassComplex(form, CodeClassId.CC6, this) makeCodeClassComplex(form, CodeClassId.CC7, this) makeCodeClassComplex(form, CodeClassId.CC8, this) } } private fun makeCodeClassComplex( form: Form<Any>, codeClassId: CodeClassId, codeClasses: List<CodeClass>, ) { val id = codeClassId.id val componentId = "$CODES_CLASS_BASE_NAME$id" val className = codeClasses .filter { it.codeClassId == id } .map { it.name } .firstOrNull() ?: codeClassId.name val model = PropertyModel.of<List<Code>>(filter, componentId) val choices = CodeModel(codeClassId, languageCode) val choiceRenderer = ChoiceRenderer<Code>("displayValue", "code") val config = BootstrapSelectConfig() .withMultiple(true) .withActionsBox(choices.getObject().size > properties.multiSelectBoxActionBoxWithMoreEntriesThan) .withSelectAllText(StringResourceModel(SELECT_ALL_RESOURCE_TAG, this, null).string) .withDeselectAllText(StringResourceModel(DESELECT_ALL_RESOURCE_TAG, this, null).string) .withNoneSelectedText(StringResourceModel(CODES_NONE_SELECT_RESOURCE_TAG, this, null).string) .withLiveSearch(true) .withLiveSearchStyle("startsWith") form.add(Label("$componentId$LABEL_TAG", Model.of(className))) form.add(BootstrapMultiSelect(componentId, model, choices, choiceRenderer).with(config)) } } private abstract class AbstractTabPanel(id: String, model: IModel<*>?) : Panel(id, model) { companion object { private const val serialVersionUID = 1L } } private fun queueQueryButton( id: String, filterForm: FilterForm<PublicPaperFilter>, ) { val labelModel = StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$LABEL_RESOURCE_TAG", this, null) object : BootstrapButton(id, labelModel, Buttons.Type.Primary) { override fun onSubmit() { super.onSubmit() isQueryingInitialized = true } }.also { queue(it) filterForm.defaultButton = it } } private fun queueClearSearchButton(id: String) { val labelModel = StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$LABEL_RESOURCE_TAG", this, null) val titleModel = StringResourceModel("$BUTTON_RESOURCE_PREFIX$id$TITLE_RESOURCE_TAG", this, null) object : BootstrapButton(id, labelModel, Buttons.Type.Default) { override fun onSubmit() { super.onSubmit() setResponsePage(PublicPage(pageParameters)) } }.apply { add(AttributeModifier("title", titleModel)) } .also { queue(it) } } private fun queueHelpLink(id: String) { object : BootstrapExternalLink(id, StringResourceModel("$id.url", this, null)) { }.apply { setTarget(BootstrapExternalLink.Target.blank) setLabel(StringResourceModel(id + LABEL_RESOURCE_TAG, this, null)) }.also { queue(it) } } private fun makeAndQueueResultTable(id: String) { object : BootstrapDefaultDataTable<PublicPaper, String>(id, makeTableColumns(), dataProvider, dataProvider.rowsPerPage.toLong()) { override fun onConfigure() { super.onConfigure() isVisible = isQueryingInitialized } override fun onAfterRender() { super.onAfterRender() paperIdManager.initialize([email protected]()) } }.apply { outputMarkupId = true add(TableBehavior().striped().hover()) }.also { queue(it) } } private fun makeTableColumns() = mutableListOf<IColumn<PublicPaper, String>>().apply { add(makePropertyColumn("authorsAbbreviated", "authors")) add(makeClickableColumn("title", this@PublicPage::onTitleClick)) add(makePropertyColumn("journal", "location")) add(makePropertyColumn("publicationYear", "publicationYear")) } private fun makePropertyColumn(fieldType: String, sortField: String) = PropertyColumn<PublicPaper, String>( StringResourceModel("$COLUMN_HEADER${fieldType}", this, null), sortField, fieldType, ) private fun makeClickableColumn( fieldType: String, consumer: SerializableConsumer<IModel<PublicPaper>>, ) = ClickablePropertyColumn( displayModel = StringResourceModel("$COLUMN_HEADER$fieldType", this, null), property = fieldType, action = consumer, sort = fieldType, inNewTab = true, ) /* * Note: The PaperIdManger manages the number in scipamato-public, not the id */ private fun onTitleClick(m: IModel<PublicPaper>) { m.getObject().number?.let { paperIdManager.setFocusToItem(it) } setResponsePage(PublicPaperDetailPage(m, page.pageReference, showBackButton = false)) } /** * Have the provider provide a list of all paper numbers (business key) matching the current filter. * Construct a navigateable with this list and set it into the session */ private fun updateNavigateable() { paperIdManager.initialize(dataProvider.findAllPaperNumbersByFilter()) } companion object { private const val serialVersionUID = 1L private const val RESULT_PAGE_SIZE = 20 private const val COLUMN_HEADER = "column.header." private const val CODES_CLASS_BASE_NAME = "codesOfClass" private const val CODES_NONE_SELECT_RESOURCE_TAG = "codes.noneSelected" private const val BUTTON_RESOURCE_PREFIX = "button." } }
public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/paper/browse/PublicPage.kt
54400405
package me.echeung.moemoekyun.client import me.echeung.moemoekyun.client.api.Library import me.echeung.moemoekyun.client.api.socket.Socket import me.echeung.moemoekyun.client.stream.Stream import me.echeung.moemoekyun.util.PreferenceUtil class RadioClient( private val preferenceUtil: PreferenceUtil, private val stream: Stream, private val socket: Socket, ) { init { setLibrary(preferenceUtil.libraryMode().get()) } fun changeLibrary(newLibrary: Library) { // Avoid unnecessary changes if (preferenceUtil.libraryMode().get() == newLibrary) { return } setLibrary(newLibrary) socket.reconnect() // Force it to play with new stream if (stream.isPlaying) { stream.play() } } private fun setLibrary(newLibrary: Library) { preferenceUtil.libraryMode().set(newLibrary) library = newLibrary } companion object { var library: Library = Library.JPOP private set fun isKpop() = library == Library.KPOP } }
app/src/main/kotlin/me/echeung/moemoekyun/client/RadioClient.kt
2283963499
package nl.hannahsten.texifyidea.lang.commands import nl.hannahsten.texifyidea.lang.LatexPackage import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.NATBIB /** * @author Hannah Schellekens */ enum class LatexNatbibCommand( override val command: String, override vararg val arguments: Argument = emptyArray(), override val dependency: LatexPackage = LatexPackage.DEFAULT, override val display: String? = null, override val isMathMode: Boolean = false, val collapse: Boolean = false ) : LatexCommand { CITEP("citep", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEP_STAR("citep*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITET("citet", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITET_STAR("citet*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEP_CAPITALIZED("Citep", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEP_STAR_CAPITALIZED("Citep*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITET_CAPITALIZED("Citet", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITET_STAR_CAPITALIZED("Citet*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALP("citealp", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALP_STAR("citealp*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALT("citealt", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALT_STAR("citealt*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALP_CAPITALIZED("Citealp", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALP_STAR_CAPITALIZED("Citealp*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALT_CAPITALIZED("Citealt", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEALT_STAR_CAPITALIZED("Citealt*", "before".asOptional(), "after".asOptional(), "keys".asRequired(), dependency = NATBIB), CITEAUTHOR("citeauthor", "keys".asRequired(), dependency = NATBIB), CITEAUTHOR_STAR("citeauthor*", "keys".asRequired(), dependency = NATBIB), CITEAUTHOR_CAPITALIZED("Citeauthor", "keys".asRequired(), dependency = NATBIB), CITEAUTHOR_STAR_CAPITALIZED("Citeauthor*", "keys".asRequired(), dependency = NATBIB), CITEYEAR("citeyear", "keys".asRequired(), dependency = NATBIB), CITEYEAR_STAR("citeyear*", "keys".asRequired(), dependency = NATBIB), CITEYEARPAR("citeyearpar", "keys".asRequired(), dependency = NATBIB), CITETITLE("citetitle", "keys".asRequired(), dependency = NATBIB), CITETITLE_STAR("citetitle*", "keys".asRequired(), dependency = NATBIB), CITENUM("citenum", "key".asRequired(), dependency = NATBIB), CITETEXT("citetext", "text".asRequired(), dependency = NATBIB), ; override val identifier: String get() = name }
src/nl/hannahsten/texifyidea/lang/commands/LatexNatbibCommand.kt
594602042
/* * Copyright 2015, 2017 Thomas Harning Jr. <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package us.eharning.atomun.keygen.internal.spi.bip0032 import us.eharning.atomun.keygen.KeyGeneratorAlgorithm import us.eharning.atomun.keygen.StandardKeyGeneratorAlgorithm import us.eharning.atomun.keygen.spi.KeyGeneratorBuilderSpi import us.eharning.atomun.keygen.spi.KeyGeneratorServiceProvider import javax.annotation.CheckForNull import javax.annotation.concurrent.Immutable /** * Registration class to perform the necessary default service provider registrations. * * @since 0.0.1 */ @Immutable class BIP0032KeyGeneratorServiceProvider : KeyGeneratorServiceProvider() { /** * Obtain a key generator builder SPI for the given algorithm. * * @param algorithm * mnemonic algorithm to try to retrieve. * * @return SPI instance for the given algorithm, else null. * * @since 0.0.1 */ @CheckForNull override fun getKeyGeneratorBuilder(algorithm: KeyGeneratorAlgorithm): KeyGeneratorBuilderSpi? { if (algorithm !== StandardKeyGeneratorAlgorithm.BIP0032) { return null } return BUILDER_SPI } companion object { private val BUILDER_SPI = BIP0032KeyGeneratorBuilderSpi() } }
src/main/java/us/eharning/atomun/keygen/internal/spi/bip0032/BIP0032KeyGeneratorServiceProvider.kt
1620511569
package net.ndrei.teslapoweredthingies.common.gui import net.minecraft.block.Block import net.minecraft.client.renderer.GlStateManager import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer import net.ndrei.teslacorelib.gui.SideDrawerPiece import net.ndrei.teslacorelib.inventory.BoundingRectangle import net.ndrei.teslapoweredthingies.client.ThingiesTexture import net.ndrei.teslapoweredthingies.integrations.GUI_BUTTONS import net.ndrei.teslapoweredthingies.integrations.jei.TheJeiThing import net.ndrei.teslapoweredthingies.integrations.localize /** * Created by CF on 2017-07-06. */ class OpenJEICategoryPiece(private val block: Block, topIndex: Int = 1) : SideDrawerPiece(topIndex) { override val isVisible: Boolean get() = TheJeiThing.isJeiAvailable && TheJeiThing.isBlockRegistered(this.block) override fun renderState(container: BasicTeslaGuiContainer<*>, state: Int, box: BoundingRectangle) { ThingiesTexture.MACHINES_TEXTURES.bind(container) GlStateManager.enableBlend() GlStateManager.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA) GlStateManager.color(1.0f, 1.0f, 1.0f, 1.0f) container.drawTexturedModalRect( box.left, box.top + 1, 81, 7, 14, 14) GlStateManager.disableBlend() } override fun getStateToolTip(state: Int) = listOf(localize(GUI_BUTTONS, "open jei")) override fun clicked() { TheJeiThing.showCategory(this.block) } }
src/main/kotlin/net/ndrei/teslapoweredthingies/common/gui/OpenJEICategoryPiece.kt
756976355
package com.pr0gramm.app.ui import android.content.Context import com.google.android.gms.ads.* import com.google.android.gms.ads.initialization.OnInitializationCompleteListener import com.google.android.gms.ads.interstitial.InterstitialAd import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback import com.pr0gramm.app.BuildConfig import com.pr0gramm.app.Duration import com.pr0gramm.app.Instant import com.pr0gramm.app.Settings import com.pr0gramm.app.model.config.Config import com.pr0gramm.app.services.Track import com.pr0gramm.app.services.UserService import com.pr0gramm.app.services.config.ConfigService import com.pr0gramm.app.util.AndroidUtility import com.pr0gramm.app.util.Holder import com.pr0gramm.app.util.ignoreAllExceptions import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.* import java.util.concurrent.TimeUnit /** * Utility methods for ads. */ class AdService(private val configService: ConfigService, private val userService: UserService) { private var lastInterstitialAdShown: Instant? = null /** * Loads an ad into this view. This method also registers a listener to track the view. * The resulting completable completes once the ad finishes loading. */ fun load(view: AdView?, type: Config.AdType): Flow<AdLoadState> { if (view == null) { return emptyFlow() } return channelFlow { view.adListener = object : TrackingAdListener("b") { override fun onAdLoaded() { super.onAdLoaded() if (!isClosedForSend) { [email protected](AdLoadState.SUCCESS).isSuccess } } override fun onAdFailedToLoad(p0: LoadAdError) { super.onAdFailedToLoad(p0) if (!isClosedForSend) { [email protected](AdLoadState.FAILURE).isSuccess } } override fun onAdClosed() { super.onAdClosed() if (!isClosedForSend) { [email protected](AdLoadState.CLOSED).isSuccess } } } view.loadAd(AdRequest.Builder().build()) awaitClose() } } fun enabledForTypeNow(type: Config.AdType): Boolean { if (Settings.alwaysShowAds) { // If the user opted in to ads, we always show the feed ad. return type == Config.AdType.FEED } if (userService.userIsPremium) { return false } if (userService.isAuthorized) { return type in configService.config().adTypesLoggedIn } else { return type in configService.config().adTypesLoggedOut } } fun enabledForType(type: Config.AdType): Flow<Boolean> { return userService.loginStates .map { enabledForTypeNow(type) } .distinctUntilChanged() } fun shouldShowInterstitialAd(): Boolean { if (!enabledForTypeNow(Config.AdType.FEED_TO_POST_INTERSTITIAL)) { return false } val lastAdShown = lastInterstitialAdShown ?: return true val interval = configService.config().interstitialAdIntervalInSeconds return Duration.since(lastAdShown).convertTo(TimeUnit.SECONDS) > interval } fun interstitialAdWasShown() { this.lastInterstitialAdShown = Instant.now() } fun newAdView(context: Context): AdView { val view = AdView(context) view.adUnitId = bannerUnitId val backgroundColor = AndroidUtility.resolveColorAttribute(context, android.R.attr.windowBackground) view.setBackgroundColor(backgroundColor) return view } fun buildInterstitialAd(context: Context): Holder<InterstitialAd?> { return if (enabledForTypeNow(Config.AdType.FEED_TO_POST_INTERSTITIAL)) { val value = CompletableDeferred<InterstitialAd?>() InterstitialAd.load(context, interstitialUnitId, AdRequest.Builder().build(), object : InterstitialAdLoadCallback() { override fun onAdLoaded(p0: InterstitialAd) { value.complete(p0) } override fun onAdFailedToLoad(p0: LoadAdError) { value.complete(null) } }) Holder { value.await() } } else { return Holder { null } } } companion object { private val interstitialUnitId: String = if (BuildConfig.DEBUG) { "ca-app-pub-3940256099942544/1033173712" } else { "ca-app-pub-2308657767126505/4231980510" } private val bannerUnitId: String = if (BuildConfig.DEBUG) { "ca-app-pub-3940256099942544/6300978111" } else { "ca-app-pub-2308657767126505/5614778874" } fun initializeMobileAds(context: Context) { // for some reason an internal getVersionString returns null, // and the result is not checked. We ignore the error in that case ignoreAllExceptions { val listener = OnInitializationCompleteListener { } MobileAds.initialize(context, listener) MobileAds.setAppVolume(0f) MobileAds.setAppMuted(true) } } } enum class AdLoadState { SUCCESS, FAILURE, CLOSED } open class TrackingAdListener(private val prefix: String) : AdListener() { override fun onAdImpression() { Track.adEvent("${prefix}_impression") } override fun onAdOpened() { Track.adEvent("${prefix}_opened") } } }
app/src/main/java/com/pr0gramm/app/ui/AdService.kt
2519516202
package com.jamieadkins.gwent.database import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import androidx.room.Transaction import com.jamieadkins.gwent.database.entity.CardEntity import com.jamieadkins.gwent.database.entity.CardWithArtEntity import com.jamieadkins.gwent.domain.GwentFaction import io.reactivex.Flowable import io.reactivex.Single @Dao interface CardDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertCards(items: Collection<CardEntity>) @Transaction @Query("SELECT * FROM " + GwentDatabase.CARD_TABLE) fun getCardsOnce(): Single<List<CardWithArtEntity>> @Transaction @Query("SELECT * FROM " + GwentDatabase.CARD_TABLE) fun getCards(): Flowable<List<CardWithArtEntity>> @Transaction @Query("SELECT * FROM " + GwentDatabase.CARD_TABLE + " WHERE id=:cardId") fun getCard(cardId: String): Flowable<CardWithArtEntity> @Transaction @Query("SELECT * FROM " + GwentDatabase.CARD_TABLE + " WHERE id IN(:ids)") fun getCards(ids: List<String>): Flowable<List<CardWithArtEntity>> @Transaction @Query("SELECT * FROM " + GwentDatabase.CARD_TABLE + " WHERE faction=:faction AND type='Leader'") fun getLeaders(faction: String): Flowable<List<CardWithArtEntity>> @Transaction @Query("SELECT * FROM " + GwentDatabase.CARD_TABLE + " WHERE faction IN(:factions) OR secondaryFaction IN(:factions)") fun getCardsInFactions(factions: List<String>): Flowable<List<CardWithArtEntity>> @Query("SELECT COUNT(*) FROM " + GwentDatabase.CARD_TABLE) fun count(): Flowable<Int> }
database/src/main/java/com/jamieadkins/gwent/database/CardDao.kt
459348031
package com.osacky.flank.gradle.integration /* * Copyright (C) 2016 Square, 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. */ import java.io.File import java.util.Properties internal fun androidHome(): String { val env = System.getenv("ANDROID_HOME") if (env != null) { return env.withInvariantPathSeparators() } val localProp = File(File(System.getProperty("user.dir")).parentFile, "local.properties") if (localProp.exists()) { val prop = Properties() localProp.inputStream().use { prop.load(it) } val sdkHome = prop.getProperty("sdk.dir") if (sdkHome != null) { return sdkHome.withInvariantPathSeparators() } } throw IllegalStateException( "Missing 'ANDROID_HOME' environment variable or local.properties with 'sdk.dir'" ) } internal fun String.withInvariantPathSeparators() = replace("\\", "/")
buildSrc/src/test/java/com/osacky/flank/gradle/integration/AndroidTestUtil.kt
1099591240
package org.rliz.mbs.release.boundary import org.rliz.mbs.common.boundary.limited import org.rliz.mbs.common.error.NotFoundException import org.rliz.mbs.release.data.ReleaseGroupRepo import org.rliz.mbs.release.data.ReleaseGroupWithArtists import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import java.util.UUID @Service class ReleaseGroupBoundary { @Autowired private lateinit var releaseGroupRepo: ReleaseGroupRepo fun getReleaseGroup(id: UUID): ReleaseGroupWithArtists = releaseGroupRepo.getReleaseGroup(id) ?: throw NotFoundException("id=$id") fun getReleaseGroups(ids: List<UUID>): List<ReleaseGroupWithArtists> = releaseGroupRepo.getReleaseGroups(limited(ids)) }
server/mbservice/src/main/kotlin/org/rliz/mbs/release/boundary/ReleaseGroupBoundary.kt
3119665963
/* Copyright (c) 2017 Lancaster Software & Service * * 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 lss.bef.core import java.io.PrintStream; class LogDefines { companion object { // LOG LEVELS const val ALL : Int = Int.MIN_VALUE; //Level.ALL.intValue(); const val EXCEPTION : Int = 1100; //Level.SEVERE.intValue() + 100; const val ERROR : Int = 1000; //Level.SEVERE.intValue(); const val WARNING : Int = 900; //Level.WARNING.intValue(); const val INFO : Int = 800; //Level.INFO.intValue(); const val CONFIG : Int = 700; //Level.CONFIG.intValue(); const val DEBUG : Int = 500; //Level.FINE.intValue(); const val PERFORMANCE : Int = 400; //Level.FINER.intValue(); const val VERBOSE : Int = 300; //Level.FINEST.intValue(); const val OFF : Int = Integer.MAX_VALUE; //Level.OFF.intValue(); } } interface Log { fun attachFileHandler( filenamePattern : String, maxFileSize : Int, numberOfRotatingFiles : Int, append : Boolean ) : Boolean fun attachFileHandlerFor( loggerName : String, filename : String ) : Boolean fun detachFileHandlerFor( loggerName : String ) : Boolean fun getCurrentGlobalLogLevel() : Int fun setCurrentGlobalLogLevel( level : Int ) : Unit fun getOriginalStderr() : PrintStream fun getOriginalStdout() : PrintStream fun logEnableLevel( level : Int ) : Unit fun logEnableTargetDisplay( flag : Boolean ) : Unit fun logIsLevelEnabled( level : Int ) : Boolean; fun log( level : Int, msg : String ) : Unit fun log( level : Int, format : String, vararg vars : Object ) : Unit fun log( level : Int, resourceId : Long, vararg vars : Object ) : Unit fun redirectStderrToLog() : Unit fun redirectStdoutToLog() : Unit fun resetStderrToOriginal() : Unit fun resetStdoutToOriginal() : Unit // CONVENIENCE METHODS fun logException( msg : String ) : Unit; fun logException( format : String, vararg vars : Object ) : Unit fun logException( resourceId : Long, vararg vars : Object ) : Unit fun logError( msg : String ) : Unit fun logError( format : String, vararg vars : Object ) : Unit fun logError( resourceId : Long, vararg vars : Object ) : Unit fun logWarning( msg : String ) : Unit fun logWarning( format : String, vararg vars : Object ) : Unit fun logWarning( resourceId : Long, vararg vars : Object ) : Unit fun logInfo( msg : String ) : Unit fun logInfo( format : String, vararg vars : Object ) : Unit fun logInfo( resourceId : Long, vararg vars : Object ) : Unit fun logDebug( msg : String ) : Unit fun logDebug( format : String, vararg vars : Object ) : Unit fun logDebug( resourceId : Long, vararg vars : Object ) : Unit fun logPerformance( msg : String ) : Long fun logPerformance( format : String, vararg vars : Object ) : Long fun logPerformance( resourceId : Long, vararg vars : Object ) : Long fun logPerformance( startTime : Long, msg : String ) : Unit fun logPerformance( startTime : Long, format : String, vararg vars : Object ) : Unit fun logPerformance( startTime : Long, resourceId : Long, vararg vars : Object ) : Unit }
src/interface/main/kotlin/lss/bef/core/Log.kt
3837951328
/* * Copyright (C) 2012 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 okhttp3.internal import java.net.IDN import java.net.InetAddress import java.util.Arrays import java.util.Locale import okio.Buffer /** * If this is an IP address, this returns the IP address in canonical form. * * Otherwise this performs IDN ToASCII encoding and canonicalize the result to lowercase. For * example this converts `☃.net` to `xn--n3h.net`, and `WwW.GoOgLe.cOm` to `www.google.com`. * `null` will be returned if the host cannot be ToASCII encoded or if the result contains * unsupported ASCII characters. */ fun String.toCanonicalHost(): String? { val host: String = this // If the input contains a :, it’s an IPv6 address. if (":" in host) { // If the input is encased in square braces "[...]", drop 'em. val inetAddress = (if (host.startsWith("[") && host.endsWith("]")) { decodeIpv6(host, 1, host.length - 1) } else { decodeIpv6(host, 0, host.length) }) ?: return null val address = inetAddress.address if (address.size == 16) return inet6AddressToAscii(address) if (address.size == 4) return inetAddress.hostAddress // An IPv4-mapped IPv6 address. throw AssertionError("Invalid IPv6 address: '$host'") } try { val result = IDN.toASCII(host).toLowerCase(Locale.US) if (result.isEmpty()) return null // Confirm that the IDN ToASCII result doesn't contain any illegal characters. return if (result.containsInvalidHostnameAsciiCodes()) { null } else { result // TODO: implement all label limits. } } catch (_: IllegalArgumentException) { return null } } private fun String.containsInvalidHostnameAsciiCodes(): Boolean { for (i in 0 until length) { val c = this[i] // The WHATWG Host parsing rules accepts some character codes which are invalid by // definition for OkHttp's host header checks (and the WHATWG Host syntax definition). Here // we rule out characters that would cause problems in host headers. if (c <= '\u001f' || c >= '\u007f') { return true } // Check for the characters mentioned in the WHATWG Host parsing spec: // U+0000, U+0009, U+000A, U+000D, U+0020, "#", "%", "/", ":", "?", "@", "[", "\", and "]" // (excluding the characters covered above). if (" #%/:?@[\\]".indexOf(c) != -1) { return true } } return false } /** Decodes an IPv6 address like 1111:2222:3333:4444:5555:6666:7777:8888 or ::1. */ private fun decodeIpv6(input: String, pos: Int, limit: Int): InetAddress? { val address = ByteArray(16) var b = 0 var compress = -1 var groupOffset = -1 var i = pos while (i < limit) { if (b == address.size) return null // Too many groups. // Read a delimiter. if (i + 2 <= limit && input.startsWith("::", startIndex = i)) { // Compression "::" delimiter, which is anywhere in the input, including its prefix. if (compress != -1) return null // Multiple "::" delimiters. i += 2 b += 2 compress = b if (i == limit) break } else if (b != 0) { // Group separator ":" delimiter. if (input.startsWith(":", startIndex = i)) { i++ } else if (input.startsWith(".", startIndex = i)) { // If we see a '.', rewind to the beginning of the previous group and parse as IPv4. if (!decodeIpv4Suffix(input, groupOffset, limit, address, b - 2)) return null b += 2 // We rewound two bytes and then added four. break } else { return null // Wrong delimiter. } } // Read a group, one to four hex digits. var value = 0 groupOffset = i while (i < limit) { val hexDigit = input[i].parseHexDigit() if (hexDigit == -1) break value = (value shl 4) + hexDigit i++ } val groupLength = i - groupOffset if (groupLength == 0 || groupLength > 4) return null // Group is the wrong size. // We've successfully read a group. Assign its value to our byte array. address[b++] = (value.ushr(8) and 0xff).toByte() address[b++] = (value and 0xff).toByte() } // All done. If compression happened, we need to move bytes to the right place in the // address. Here's a sample: // // input: "1111:2222:3333::7777:8888" // before: { 11, 11, 22, 22, 33, 33, 00, 00, 77, 77, 88, 88, 00, 00, 00, 00 } // compress: 6 // b: 10 // after: { 11, 11, 22, 22, 33, 33, 00, 00, 00, 00, 00, 00, 77, 77, 88, 88 } // if (b != address.size) { if (compress == -1) return null // Address didn't have compression or enough groups. System.arraycopy(address, compress, address, address.size - (b - compress), b - compress) Arrays.fill(address, compress, compress + (address.size - b), 0.toByte()) } return InetAddress.getByAddress(address) } /** Decodes an IPv4 address suffix of an IPv6 address, like 1111::5555:6666:192.168.0.1. */ private fun decodeIpv4Suffix( input: String, pos: Int, limit: Int, address: ByteArray, addressOffset: Int ): Boolean { var b = addressOffset var i = pos while (i < limit) { if (b == address.size) return false // Too many groups. // Read a delimiter. if (b != addressOffset) { if (input[i] != '.') return false // Wrong delimiter. i++ } // Read 1 or more decimal digits for a value in 0..255. var value = 0 val groupOffset = i while (i < limit) { val c = input[i] if (c < '0' || c > '9') break if (value == 0 && groupOffset != i) return false // Reject unnecessary leading '0's. value = value * 10 + c.toInt() - '0'.toInt() if (value > 255) return false // Value out of range. i++ } val groupLength = i - groupOffset if (groupLength == 0) return false // No digits. // We've successfully read a byte. address[b++] = value.toByte() } // Check for too few groups. We wanted exactly four. return b == addressOffset + 4 } /** Encodes an IPv6 address in canonical form according to RFC 5952. */ private fun inet6AddressToAscii(address: ByteArray): String { // Go through the address looking for the longest run of 0s. Each group is 2-bytes. // A run must be longer than one group (section 4.2.2). // If there are multiple equal runs, the first one must be used (section 4.2.3). var longestRunOffset = -1 var longestRunLength = 0 run { var i = 0 while (i < address.size) { val currentRunOffset = i while (i < 16 && address[i].toInt() == 0 && address[i + 1].toInt() == 0) { i += 2 } val currentRunLength = i - currentRunOffset if (currentRunLength > longestRunLength && currentRunLength >= 4) { longestRunOffset = currentRunOffset longestRunLength = currentRunLength } i += 2 } } // Emit each 2-byte group in hex, separated by ':'. The longest run of zeroes is "::". val result = Buffer() var i = 0 while (i < address.size) { if (i == longestRunOffset) { result.writeByte(':'.toInt()) i += longestRunLength if (i == 16) result.writeByte(':'.toInt()) } else { if (i > 0) result.writeByte(':'.toInt()) val group = address[i] and 0xff shl 8 or (address[i + 1] and 0xff) result.writeHexadecimalUnsignedLong(group.toLong()) i += 2 } } return result.readUtf8() }
okhttp/src/main/kotlin/okhttp3/internal/hostnames.kt
2475878055
package org.musicbrainz.picard.barcodescanner.data class ArtistCredit( var name: String, var joinphrase: String?, )
app/src/main/java/org/musicbrainz/picard/barcodescanner/data/ArtistCredit.kt
306500399
/* Copyright 2016 Dániel Sólyom 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 ds.violin.v1.app import android.os.Bundle import android.os.Parcelable import android.view.View import ds.violin.v1.app.violin.* import ds.violin.v1.model.entity.SelfLoadable import ds.violin.v1.widget.IRecyclerView import java.util.* abstract class ViolinRecyclerViewFragment : ViolinFragment(), RecyclerViewViolin { override lateinit var recyclerView: IRecyclerView override val emptyViewID: Int? = null override var emptyView: View? = null override var layoutManagerState: Parcelable? = null override var adapter: AbsRecyclerViewAdapter? = null override var adapterViewBinder: RecyclerViewAdapterBinder? = null override val parentCanHoldHeader: Boolean = true override val parentCanHoldFooter: Boolean = true override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super<RecyclerViewViolin>.onViewCreated(view, savedInstanceState) super<ViolinFragment>.onViewCreated(view, savedInstanceState) } override fun play() { /** create your [adapter] and [adapterViewBinder] before calling super */ super<RecyclerViewViolin>.play() super<ViolinFragment>.play() } override fun saveInstanceState(outState: Bundle) { super<ViolinFragment>.saveInstanceState(outState) super<RecyclerViewViolin>.saveInstanceState(outState) } override fun restoreInstanceState(savedInstanceState: Bundle) { super<ViolinFragment>.restoreInstanceState(savedInstanceState) super<RecyclerViewViolin>.restoreInstanceState(savedInstanceState) } }
ViolinDS/app/src/main/java/ds/violin/v1/app/ViolinRecyclerViewFragment.kt
3156647660
package tv.superawesome.sdk.publisher.common.network enum class Environment { Production, Staging; val baseUrl: String get() = when (this) { Production -> "https://ads.superawesome.tv/v2/" Staging -> "https://ads.staging.superawesome.tv/v2/" } }
superawesome-common/src/main/java/tv/superawesome/sdk/publisher/common/network/Environment.kt
4276669775
package cc.aoeiuv020.panovel.download import cc.aoeiuv020.panovel.Presenter import org.jetbrains.anko.AnkoLogger /** * Created by AoEiuV020 on 2018.10.06-19:06:57. */ class DownloadPresenter : Presenter<DownloadActivity>(), AnkoLogger { fun start() { } }
app/src/main/java/cc/aoeiuv020/panovel/download/DownloadPresenter.kt
2333996133
package ademar.study.template.view.home import ademar.study.template.R import ademar.study.template.ext.inflate import ademar.study.template.model.HelloWorldViewModel import ademar.study.template.view.base.BaseAdapter import android.view.ViewGroup import javax.inject.Inject class HomeAdapter @Inject constructor() : BaseAdapter<HelloWorldViewModel, HomeViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = HomeViewHolder(parent.inflate(R.layout.hello_item)) }
Template/app/src/main/java/ademar/study/template/view/home/HomeAdapter.kt
4294340918
/* * Copyright 2021 Brackeys IDE contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.brackeys.ui.language.html.provider import com.brackeys.ui.language.base.model.Suggestion import com.brackeys.ui.language.base.provider.SuggestionProvider import com.brackeys.ui.language.base.utils.WordsManager class HtmlProvider private constructor() : SuggestionProvider { companion object { private var htmlProvider: HtmlProvider? = null fun getInstance(): HtmlProvider { return htmlProvider ?: HtmlProvider().also { htmlProvider = it } } } private val wordsManager = WordsManager() override fun getAll(): Set<Suggestion> { return wordsManager.getWords() } override fun processLine(lineNumber: Int, text: String) { wordsManager.processLine(lineNumber, text) } override fun deleteLine(lineNumber: Int) { wordsManager.deleteLine(lineNumber) } override fun clearLines() { wordsManager.clearLines() } }
languages/language-html/src/main/kotlin/com/brackeys/ui/language/html/provider/HtmlProvider.kt
4161502500
/* * ProGuard -- shrinking, optimization, obfuscation, and preverification * of Java bytecode. * * Copyright (c) 2002-2021 Guardsquare NV * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package proguard.gradle import io.kotest.core.spec.style.FreeSpec import io.kotest.core.spec.style.funSpec import io.kotest.engine.spec.tempdir import io.kotest.matchers.shouldBe import io.kotest.matchers.string.shouldContain import java.io.File import java.lang.management.ManagementFactory import org.apache.commons.io.FileUtils import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import testutils.TestPluginClasspath class GradlePluginIntegrationTest : FreeSpec({ "Gradle plugin can be applied to spring-boot sample" - { val projectRoot = tempdir() val fixture = File(GradlePluginIntegrationTest::class.java.classLoader.getResource("spring-boot").path) FileUtils.copyDirectory(fixture, projectRoot) TestPluginClasspath.applyToRootGradle(projectRoot) "When the build is executed" - { val result = GradleRunner.create() .forwardOutput() .withArguments("proguard") .withPluginClasspath() .withProjectDir(projectRoot) .build() "Then the build was successful" { result.output shouldContain "SUCCESSFUL" } } } // ProguardTask is still incompatible, but will not fail the build. Once the issue is resolved, this test will fail // and should be updated to demonstrate compatibility. "ProguardTask will not fail when configuration cache is used" - { val projectRoot = tempdir() val fixture = File(GradlePluginIntegrationTest::class.java.classLoader.getResource("application").path) FileUtils.copyDirectory(fixture, projectRoot) TestPluginClasspath.applyToRootGradle(projectRoot) "When the build is executed" - { val result = GradleRunner.create() .forwardOutput() .withArguments("proguard", "--configuration-cache") .withPluginClasspath() .withGradleVersion("7.4") .withProjectDir(projectRoot) // Ensure this value is true when `--debug-jvm` is passed to Gradle, and false otherwise .withDebug(ManagementFactory.getRuntimeMXBean().inputArguments.toString().indexOf("-agentlib:jdwp") > 0) .build() "Then the build was successful with configuration cache" { result.output shouldContain "SUCCESSFUL" // E.g., "Configuration cache entry discarded with 4 problems." result.output shouldContain "Configuration cache entry discarded with" } } } "gradle plugin can be configured via #configOption" - { include(testConfigOption("proguard")) include(testConfigOption("proguardWithConfigFile")) include(testConfigOption("proguardWithGeneratedConfigFile")) } }) fun testConfigOption(task: String) = funSpec { fun runBuild(projectRoot: File, vararg tasks: String): BuildResult? = GradleRunner.create() .forwardOutput() .withArguments(tasks.asList()) .withPluginClasspath() .withProjectDir(projectRoot) .build() fun succeeds(buildResult: BuildResult?, projectRoot: File, task: String, outcome: TaskOutcome = TaskOutcome.SUCCESS) { buildResult?.output shouldContain "SUCCESSFUL" buildResult?.task(":$task")?.outcome shouldBe outcome File(projectRoot, "build/$task-obfuscated.jar").isFile shouldBe true File(projectRoot, "build/$task-mapping.txt").isFile shouldBe true } val projectRoot = tempdir() val fixture = File(GradlePluginIntegrationTest::class.java.classLoader.getResource("gradle-kotlin-dsl").path) FileUtils.copyDirectory(fixture, projectRoot) TestPluginClasspath.applyToRootGradleKts(projectRoot) addConfigFileTasks(projectRoot) succeeds(runBuild(projectRoot, task), projectRoot, task) // When no inputs or outputs are modified, task should be UP-TO-DATE succeeds(runBuild(projectRoot, task), projectRoot, task, TaskOutcome.UP_TO_DATE) // When proguard outputs are subsequently deleted, task should re-execute runBuild(projectRoot, "clean") succeeds(runBuild(projectRoot, task), projectRoot, task) // When proguard input sources are modified, task should re-execute val srcFile = File(projectRoot, "src/main/java/gradlekotlindsl/App.java") srcFile.writeText(srcFile.readText().replace("Hello world.", "Howdy Earth.")) succeeds(runBuild(projectRoot, task), projectRoot, task) } /** * Add extra tasks that load from a separate configuration file, including one that is generated by another task. * This allows us to validate that up-to-date checks work regardless of the configuration mechanism. */ fun addConfigFileTasks(projectRoot: File) { val buildFile = File(projectRoot, "build.gradle.kts") buildFile.writeText(buildFile.readText() + """ tasks.register<proguard.gradle.ProGuardTask>("proguardWithConfigFile") { dependsOn("jar") // Inputs and outputs declared in external config file are not automatically tracked inputs.file("build/libs/gradle-kotlin-dsl.jar") outputs.file("build/proguardWithConfigFile-obfuscated.jar") outputs.file("build/proguardWithConfigFile-mapping.txt") configuration("config.pro") } tasks.register("generateConfigFile") { val outputFile = file("build/proguard/config.pro") outputs.file(outputFile) doLast { file("build/proguard").mkdirs() outputFile.writeText("-basedirectory ../.. \n") outputFile.appendText(file("config.pro").readText().replace("proguardWithConfigFile", "proguardWithGeneratedConfigFile")) } } tasks.register<proguard.gradle.ProGuardTask>("proguardWithGeneratedConfigFile") { dependsOn("jar") // Inputs and outputs declared in external config file are not automatically tracked inputs.file("build/libs/gradle-kotlin-dsl.jar") outputs.file("build/proguardWithGeneratedConfigFile-obfuscated.jar") outputs.file("build/proguardWithGeneratedConfigFile-mapping.txt") // Consume the "generateConfigFile" output. This will automatically add the task dependency. configuration(tasks.named("generateConfigFile")) } """.trimIndent()) val libraryJars = if (System.getProperty("java.version").startsWith("1.")) "<java.home>/lib/rt.jar" else "<java.home>/jmods/java.base.jmod(!**.jar;!module-info.class)" val configFile = File(projectRoot, "config.pro") configFile.createNewFile() configFile.writeText(""" -injars build/libs/gradle-kotlin-dsl.jar -outjars build/proguardWithConfigFile-obfuscated.jar -libraryjars $libraryJars -allowaccessmodification -repackageclasses -printmapping build/proguardWithConfigFile-mapping.txt -keep class gradlekotlindsl.App { public static void main(java.lang.String[]); } """.trimIndent()) }
gradle-plugin/src/test/kotlin/proguard/gradle/GradlePluginIntegrationTest.kt
4033576759
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.configurationStore import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.components.StateSplitter import com.intellij.openapi.components.StateSplitterEx import com.intellij.openapi.components.StateStorage import com.intellij.openapi.components.TrackingPathMacroSubstitutor import com.intellij.openapi.components.impl.stores.DirectoryStorageUtil import com.intellij.openapi.components.impl.stores.FileStorageCoreUtil import com.intellij.openapi.util.Pair import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.LineSeparator import com.intellij.util.SmartList import com.intellij.util.SystemProperties import com.intellij.util.containers.SmartHashSet import com.intellij.util.io.systemIndependentPath import com.intellij.util.isEmpty import gnu.trove.THashMap import org.jdom.Element import java.io.IOException import java.nio.ByteBuffer import java.nio.file.Path abstract class DirectoryBasedStorageBase(@Suppress("DEPRECATION") protected val splitter: StateSplitter, protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : StateStorageBase<StateMap>() { protected var componentName: String? = null protected abstract val virtualFile: VirtualFile? override fun loadData() = StateMap.fromMap(DirectoryStorageUtil.loadFrom(virtualFile, pathMacroSubstitutor)) override fun startExternalization(): StateStorage.ExternalizationSession? = null override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) { // todo reload only changed file, compute diff val newData = loadData() storageDataRef.set(newData) if (componentName != null) { componentNames.add(componentName!!) } } override fun getSerializedState(storageData: StateMap, component: Any?, componentName: String, archive: Boolean): Element? { this.componentName = componentName if (storageData.isEmpty()) { return null } val state = Element(FileStorageCoreUtil.COMPONENT) if (splitter is StateSplitterEx) { for (fileName in storageData.keys()) { val subState = storageData.getState(fileName, archive) ?: return null splitter.mergeStateInto(state, subState) } } else { val subElements = SmartList<Element>() for (fileName in storageData.keys()) { val subState = storageData.getState(fileName, archive) ?: return null subElements.add(subState) } if (!subElements.isEmpty()) { splitter.mergeStatesInto(state, subElements.toTypedArray()) } } return state } override fun hasState(storageData: StateMap, componentName: String) = storageData.hasStates() } open class DirectoryBasedStorage(private val dir: Path, @Suppress("DEPRECATION") splitter: StateSplitter, pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : DirectoryBasedStorageBase(splitter, pathMacroSubstitutor) { private @Volatile var cachedVirtualFile: VirtualFile? = null override val virtualFile: VirtualFile? get() { var result = cachedVirtualFile if (result == null) { result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath) cachedVirtualFile = result } return result } internal fun setVirtualDir(dir: VirtualFile?) { cachedVirtualFile = dir } override fun startExternalization(): StateStorage.ExternalizationSession? = if (checkIsSavingDisabled()) null else MySaveSession(this, getStorageData()) private class MySaveSession(private val storage: DirectoryBasedStorage, private val originalStates: StateMap) : SaveSessionBase() { private var copiedStorageData: MutableMap<String, Any>? = null private val dirtyFileNames = SmartHashSet<String>() private var someFileRemoved = false override fun setSerializedState(componentName: String, element: Element?) { storage.componentName = componentName if (element.isEmpty()) { if (copiedStorageData != null) { copiedStorageData!!.clear() } else if (!originalStates.isEmpty()) { copiedStorageData = THashMap<String, Any>() } } else { val stateAndFileNameList = storage.splitter.splitState(element!!) for (pair in stateAndFileNameList) { doSetState(pair.second, pair.first) } outerLoop@ for (key in originalStates.keys()) { for (pair in stateAndFileNameList) { if (pair.second == key) { continue@outerLoop } } if (copiedStorageData == null) { copiedStorageData = originalStates.toMutableMap() } someFileRemoved = true copiedStorageData!!.remove(key) } } } private fun doSetState(fileName: String, subState: Element) { if (copiedStorageData == null) { copiedStorageData = setStateAndCloneIfNeed(fileName, subState, originalStates) if (copiedStorageData != null) { dirtyFileNames.add(fileName) } } else if (updateState(copiedStorageData!!, fileName, subState)) { dirtyFileNames.add(fileName) } } override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStorageData == null) null else this override fun save() { val stateMap = StateMap.fromMap(copiedStorageData!!) var dir = storage.virtualFile if (copiedStorageData!!.isEmpty()) { if (dir != null && dir.exists()) { deleteFile(this, dir) } storage.setStorageData(stateMap) return } if (dir == null || !dir.isValid) { dir = createDir(storage.dir, this) storage.cachedVirtualFile = dir } if (!dirtyFileNames.isEmpty) { saveStates(dir, stateMap) } if (someFileRemoved && dir.exists()) { deleteFiles(dir) } storage.setStorageData(stateMap) } private fun saveStates(dir: VirtualFile, states: StateMap) { val storeElement = Element(FileStorageCoreUtil.COMPONENT) for (fileName in states.keys()) { if (!dirtyFileNames.contains(fileName)) { continue } var element: Element? = null try { element = states.getElement(fileName) ?: continue storage.pathMacroSubstitutor?.collapsePaths(element) storeElement.setAttribute(FileStorageCoreUtil.NAME, storage.componentName!!) storeElement.addContent(element) val file = getFile(fileName, dir, this) // we don't write xml prolog due to historical reasons (and should not in any case) writeFile(null, this, file, storeElement, LineSeparator.fromString(if (file.exists()) loadFile(file).second else SystemProperties.getLineSeparator()), false) } catch (e: IOException) { LOG.error(e) } finally { if (element != null) { element.detach() } } } } private fun deleteFiles(dir: VirtualFile) { runWriteAction { for (file in dir.children) { val fileName = file.name if (fileName.endsWith(FileStorageCoreUtil.DEFAULT_EXT) && !copiedStorageData!!.containsKey(fileName)) { if (file.isWritable) { file.delete(this) } else { throw ReadOnlyModificationException(file, null) } } } } } } private fun setStorageData(newStates: StateMap) { storageDataRef.set(newStates) } } private val NON_EXISTENT_FILE_DATA = Pair.create<ByteArray, String>(null, SystemProperties.getLineSeparator()) /** * @return pair.first - file contents (null if file does not exist), pair.second - file line separators */ private fun loadFile(file: VirtualFile?): Pair<ByteArray, String> { if (file == null || !file.exists()) { return NON_EXISTENT_FILE_DATA } val bytes = file.contentsToByteArray() val lineSeparator = file.detectedLineSeparator ?: detectLineSeparators(Charsets.UTF_8.decode(ByteBuffer.wrap(bytes)), null).separatorString return Pair.create<ByteArray, String>(bytes, lineSeparator) }
platform/configuration-store-impl/src/DirectoryBasedStorage.kt
1596006936
package nl.sogeti.android.gpstracker.ng.features.util import android.content.ContentResolver import android.net.Uri import nl.sogeti.android.gpstracker.ng.base.BaseConfiguration import nl.sogeti.android.gpstracker.ng.base.dagger.AppComponent import nl.sogeti.android.gpstracker.ng.features.FeatureConfiguration import nl.sogeti.android.gpstracker.ng.features.dagger.FeatureComponent import nl.sogeti.android.gpstracker.service.dagger.ServiceComponent import nl.sogeti.android.gpstracker.service.dagger.ServiceConfiguration import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement import org.mockito.ArgumentMatchers import org.mockito.Mockito import org.mockito.Mockito.`when` import org.mockito.Mockito.mock class MockAppComponentTestRule : TestRule { lateinit var mockAppComponent: AppComponent lateinit var mockServiceComponent: ServiceComponent lateinit var mockFeatureComponent: FeatureComponent override fun apply(base: Statement, description: Description?): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { val mockUriBuilder = createMockBuilder() mockAppComponent = Mockito.mock(AppComponent::class.java) BaseConfiguration.appComponent = mockAppComponent `when`(mockAppComponent.uriBuilder()).thenReturn(mockUriBuilder) val mockResolver = mock(ContentResolver::class.java) `when`(mockAppComponent.contentResolver()).thenReturn(mockResolver) `when`(mockAppComponent.computationExecutor()).thenReturn(ImmediateExecutor()) mockServiceComponent = Mockito.mock(ServiceComponent::class.java) ServiceConfiguration.serviceComponent = mockServiceComponent `when`(mockServiceComponent.providerAuthority()).thenReturn("mock-authority") mockFeatureComponent = Mockito.mock(FeatureComponent::class.java) FeatureConfiguration.featureComponent = mockFeatureComponent base.evaluate() } } } private fun createMockBuilder(): Uri.Builder { val builder = Mockito.mock(Uri.Builder::class.java) val uri = Mockito.mock(Uri::class.java) `when`(builder.scheme(ArgumentMatchers.any())).thenReturn(builder) `when`(builder.authority(ArgumentMatchers.any())).thenReturn(builder) `when`(builder.appendPath(ArgumentMatchers.any())).thenReturn(builder) `when`(builder.appendEncodedPath(ArgumentMatchers.any())).thenReturn(builder) `when`(builder.build()).thenReturn(uri) return builder } }
studio/features/src/test/java/nl/sogeti/android/gpstracker/ng/features/util/MockAppComponentTestRule.kt
163688084
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.ds3autogen.go.generators.parser import com.google.common.collect.ImmutableList import com.google.common.collect.ImmutableMap import com.spectralogic.ds3autogen.api.models.apispec.Ds3Element import com.spectralogic.ds3autogen.api.models.apispec.Ds3Type import com.spectralogic.ds3autogen.go.models.parser.* import com.spectralogic.ds3autogen.go.utils.toGoResponseType import com.spectralogic.ds3autogen.go.utils.toGoType import com.spectralogic.ds3autogen.utils.ConverterUtil import com.spectralogic.ds3autogen.utils.Ds3ElementUtil import com.spectralogic.ds3autogen.utils.NormalizingContractNamesUtil import com.spectralogic.ds3autogen.utils.collections.GuavaCollectors open class BaseTypeParserGenerator : TypeParserModelGenerator<TypeParser>, TypeParserGeneratorUtil { override fun generate(ds3Type: Ds3Type, typeMap: ImmutableMap<String, Ds3Type>): TypeParser { val modelName = NormalizingContractNamesUtil.removePath(ds3Type.name) val name = modelName + "Parser" val attributes = toAttributeList(ds3Type.elements, modelName) val childNodes = toChildNodeList(ds3Type.elements, modelName, typeMap) return TypeParser(name, modelName, attributes, childNodes) } /** * Converts all non-attribute elements within a Ds3Element list into ParsingElements, which * contain the Go code for parsing the Ds3Elements as child nodes. */ override fun toChildNodeList( ds3Elements: ImmutableList<Ds3Element>?, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ImmutableList<ParseElement> { if (ConverterUtil.isEmpty(ds3Elements)) { return ImmutableList.of() } return ds3Elements!!.stream() .filter { ds3Element -> !Ds3ElementUtil.isAttribute(ds3Element.ds3Annotations) } .map { ds3Element -> toChildNode(ds3Element, typeName, typeMap) } .collect(GuavaCollectors.immutableList()) } /** * Converts a Ds3Element into a ParsingElements.There are no special-cased Ds3Elements within * the BaseTypeParserGenerator. */ override fun toChildNode(ds3Element: Ds3Element, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ParseElement { return toStandardChildNode(ds3Element, typeName, typeMap) } /** * Converts a Ds3Element into a ParsingElement, which contains the Go code for parsing the * specified Ds3Element as a child node. This assumes that the specified Ds3Element is not an attribute. */ fun toStandardChildNode(ds3Element: Ds3Element, typeName: String, typeMap: ImmutableMap<String, Ds3Type>): ParseElement { val xmlTag = getXmlTagName(ds3Element) val modelName = typeName.decapitalize() val paramName = ds3Element.name.capitalize() // Handle case if there is an encapsulating tag around a list of elements if (Ds3ElementUtil.hasWrapperAnnotations(ds3Element.ds3Annotations)) { val encapsulatingTag = Ds3ElementUtil.getEncapsulatingTagAnnotations(ds3Element.ds3Annotations).capitalize() val childType = NormalizingContractNamesUtil.removePath(ds3Element.componentType) // Handle if the slice is common prefixes if (encapsulatingTag == "CommonPrefixes") { return ParseChildNodeAsCommonPrefix(modelName, paramName) } return ParseChildNodeAsSlice(encapsulatingTag, xmlTag, modelName, paramName, childType) } // Handle case if there is a slice to be parsed (no encapsulating tag) if (ds3Element.type.equals("array")) { val childType = toGoType(ds3Element.componentType!!) // Handle if the slice is a string if (childType == "string") { return ParseChildNodeAddStringToSlice(xmlTag, modelName, paramName) } // Handle if the slice is a Ds3Type defined enum if (isElementEnum(ds3Element.componentType!!, typeMap)) { return ParseChildNodeAddEnumToSlice(xmlTag, modelName, paramName, childType) } return ParseChildNodeAddToSlice(xmlTag, modelName, paramName, childType) } // Handle case if the element is an enum if (isElementEnum(ds3Element.type!!, typeMap)) { if (ds3Element.nullable) { return ParseChildNodeAsNullableEnum(xmlTag, modelName, paramName, toGoType(ds3Element.type!!)) } return ParseChildNodeAsEnum(xmlTag, modelName, paramName) } val goType = toGoResponseType(ds3Element.type, ds3Element.componentType, ds3Element.nullable) val parserNamespace = getPrimitiveTypeParserNamespace(ds3Element.type!!, ds3Element.nullable) when (goType) { "bool", "*bool", "int", "*int", "int64", "*int64", "float64", "*float64" -> return ParseChildNodeAsPrimitiveType(xmlTag, modelName, paramName, parserNamespace) "string", "*string" -> return ParseChildNodeAsString(xmlTag, modelName, paramName, parserNamespace) else -> { // All remaining elements represent Ds3Types if (goType.first() == '*') { return ParseChildNodeAsNullableDs3Type(xmlTag, modelName, paramName, goType.drop(1)) } return ParseChildNodeAsDs3Type(xmlTag, modelName, paramName) } } } /** * Determines if the specified type is an enum. */ fun isElementEnum(elementType: String, typeMap: ImmutableMap<String, Ds3Type>): Boolean { if (ConverterUtil.isEmpty(typeMap)) { return false } val ds3Type = typeMap[elementType] ?: return false return ConverterUtil.isEnum(ds3Type) } /** * Converts all attributes within a Ds3Element list into ParsingElements which contain the * Go code for parsing the attributes. */ fun toAttributeList(ds3Elements: ImmutableList<Ds3Element>?, typeName: String): ImmutableList<ParseElement> { if (ConverterUtil.isEmpty(ds3Elements)) { return ImmutableList.of() } return ds3Elements!!.stream() .filter { ds3Element -> Ds3ElementUtil.isAttribute(ds3Element.ds3Annotations) } .map { ds3Element -> toAttribute(ds3Element, typeName) } .collect(GuavaCollectors.immutableList()) } /** * Converts a Ds3Element into a ParsingElement, which contains the Go code for parsing the * specified Ds3Element attribute. This assumes that the specified Ds3Element is an attribute. */ fun toAttribute(ds3Element: Ds3Element, typeName: String): ParseElement { val xmlName = getXmlTagName(ds3Element) val goType = toGoResponseType(ds3Element.type, ds3Element.componentType, ds3Element.nullable) val modelName = typeName.decapitalize() val paramName = ds3Element.name.capitalize() when (goType) { "bool", "*bool", "int", "*int", "int64", "*int64", "float64", "*float64" -> { val parserNamespace = getPrimitiveTypeParserNamespace(ds3Element.type!!, ds3Element.nullable) return ParseSimpleAttr(xmlName, modelName, paramName, parserNamespace) } "string" -> return ParseStringAttr(xmlName, modelName, paramName) "*string" -> return ParseNullableStringAttr(xmlName, modelName, paramName) else -> { if (ds3Element.nullable) { return ParseNullableEnumAttr(xmlName, modelName, paramName) } return ParseEnumAttr(xmlName, modelName, paramName) } } } /** * Retrieves the xml tag name for the specified Ds3Element. The result is capitalized. */ fun getXmlTagName(ds3Element: Ds3Element): String { return Ds3ElementUtil.getXmlTagName(ds3Element).capitalize() } /** * Gets the namespace of the required primitive type parser used to parse * the specified type. Assumes that the provided type is a Go primitive, or * a pointer to a Go primitive type. */ fun getPrimitiveTypeParserNamespace(type: String, nullable: Boolean): String { val parserPrefix = toGoType(type).capitalize() if (nullable) { return "Nullable$parserPrefix" } return parserPrefix } }
ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/parser/BaseTypeParserGenerator.kt
3254955224
package net.nemerosa.ontrack.graphql.schema import graphql.schema.* import graphql.schema.GraphQLObjectType.newObject import net.nemerosa.ontrack.common.UserException import net.nemerosa.ontrack.graphql.support.MutationInputValidationException import org.springframework.stereotype.Service @Service class GraphqlSchemaServiceImpl( private val types: List<GQLType>, private val inputTypes: List<GQLInputType<*>>, private val interfaces: List<GQLInterface>, private val enums: List<GQLEnum>, private val rootQueries: List<GQLRootQuery>, private val mutationProviders: List<MutationProvider> ) : GraphqlSchemaService { override val schema: GraphQLSchema by lazy { createSchema() } private fun createSchema(): GraphQLSchema { // All types val cache = GQLTypeCache() val dictionary = mutableSetOf<GraphQLType>() dictionary.addAll(types.map { it.createType(cache) }) dictionary.addAll(interfaces.map { it.createInterface() }) dictionary.addAll(enums.map { it.createEnum() }) dictionary.addAll(inputTypes.map { it.createInputType(dictionary) }) val mutationType = createMutationType(dictionary) return GraphQLSchema.newSchema() .additionalTypes(dictionary) .query(createQueryType()) .mutation(mutationType) .build() } private fun createQueryType(): GraphQLObjectType { return newObject() .name(QUERY) // Root queries .fields( rootQueries.map { it.fieldDefinition } ) // OK .build() } private fun createMutationType(dictionary: MutableSet<GraphQLType>): GraphQLObjectType { return newObject() .name(MUTATION) // Root mutations .fields( mutationProviders.flatMap { provider -> provider.mutations.map { mutation -> createMutation(mutation, dictionary) } } ) // OK .build() } private fun createMutation(mutation: Mutation, dictionary: MutableSet<GraphQLType>): GraphQLFieldDefinition { // Create the mutation input type val inputType = createMutationInputType(mutation, dictionary) // Create the mutation output type val outputType = createMutationOutputType(mutation, dictionary) // Create the mutation field return GraphQLFieldDefinition.newFieldDefinition() .name(mutation.name) .description(mutation.description) .argument { it.name("input") .description("Input for the mutation") .type(inputType) } .type(outputType) .dataFetcher { env -> mutationFetcher(mutation, env) } .build() } private fun mutationFetcher(mutation: Mutation, env: DataFetchingEnvironment): Any { return try { mutation.fetch(env) } catch (ex: Exception) { when (ex) { is MutationInputValidationException -> { mapOf("errors" to ex.violations.map { cv -> MutationInputValidationException.asUserError(cv) }) } is UserException -> { val exception = ex::class.java.name val error = UserError( message = ex.message ?: exception, exception = exception ) mapOf("errors" to listOf(error)) } else -> { throw ex } } } } private fun createMutationOutputType(mutation: Mutation, dictionary: MutableSet<GraphQLType>): GraphQLObjectType = newObject() .name("${mutation.typePrefix}Payload") .description("Output type for the ${mutation.name} mutation.") .fields(mutation.outputFields) // All mutation payloads inherit from the Payload type .withInterface(GraphQLTypeReference(GQLInterfacePayload.PAYLOAD)) // Errors field .field(GQLInterfacePayload.payloadErrorsField()) // OK .build() .apply { dictionary.add(this) } private fun createMutationInputType(mutation: Mutation, dictionary: MutableSet<GraphQLType>): GraphQLInputType = GraphQLInputObjectType.newInputObject() .name("${mutation.typePrefix}Input") .description("Input type for the ${mutation.name} mutation.") .fields(mutation.inputFields(dictionary)) .build() .apply { dictionary.add(this) } private val Mutation.typePrefix: String get() = name.capitalize() companion object { const val QUERY = "Query" const val MUTATION = "Mutation" } }
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/schema/GraphqlSchemaServiceImpl.kt
1711853202
package net.nemerosa.ontrack.extension.github.ingestion.ui import graphql.schema.GraphQLObjectType import net.nemerosa.ontrack.extension.github.ingestion.payload.IngestionHookPayload import net.nemerosa.ontrack.graphql.schema.GQLType import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.* import net.nemerosa.ontrack.model.annotations.getPropertyDescription import org.springframework.stereotype.Component @Component class GQLGitHubIngestionHookPayload( private val gqlEnumIngestionHookPayloadStatus: GQLEnumIngestionHookPayloadStatus, private val gqlEnumIngestionEventProcessingResult: GQLEnumIngestionEventProcessingResult, private val gqlGitHubRepository: GQLGitHubRepository, ) : GQLType { override fun getTypeName(): String = "GitHubIngestionHookPayload" override fun createType(cache: GQLTypeCache): GraphQLObjectType = GraphQLObjectType.newObject() .name(typeName) .description("Payload received by the GitHub Ingestion Hook") .stringField( IngestionHookPayload::uuid.name, getPropertyDescription(IngestionHookPayload::uuid), ) .dateField( IngestionHookPayload::timestamp.name, getPropertyDescription(IngestionHookPayload::timestamp), ) .stringField(IngestionHookPayload::gitHubDelivery) .stringField(IngestionHookPayload::gitHubEvent) .intField(IngestionHookPayload::gitHubHookID) .intField(IngestionHookPayload::gitHubHookInstallationTargetID) .stringField(IngestionHookPayload::gitHubHookInstallationTargetType) .field { it.name(IngestionHookPayload::payload.name) .description(getPropertyDescription(IngestionHookPayload::payload)) .type(GQLScalarJSON.INSTANCE.toNotNull()) } .field { it.name(IngestionHookPayload::status.name) .description(getPropertyDescription(IngestionHookPayload::status)) .type(gqlEnumIngestionHookPayloadStatus.getTypeRef().toNotNull()) } .field { it.name(IngestionHookPayload::outcome.name) .description(getPropertyDescription(IngestionHookPayload::outcome)) .type(gqlEnumIngestionEventProcessingResult.getTypeRef()) } .stringField(IngestionHookPayload::outcomeDetails) .dateField( IngestionHookPayload::started.name, getPropertyDescription(IngestionHookPayload::started), ) .stringField(IngestionHookPayload::message) .dateField( IngestionHookPayload::completion.name, getPropertyDescription(IngestionHookPayload::completion), ) .field { it.name(IngestionHookPayload::repository.name) .description(getPropertyDescription(IngestionHookPayload::repository)) .type(gqlGitHubRepository.typeRef) } .stringField(IngestionHookPayload::source) .stringField(IngestionHookPayload::routing) .stringField(IngestionHookPayload::queue) .build() }
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/ui/GQLGitHubIngestionHookPayload.kt
4141125086
package net.nemerosa.ontrack.extension.github.ingestion.ui import net.nemerosa.ontrack.extension.github.ingestion.config.model.IngestionConfig import net.nemerosa.ontrack.graphql.schema.GQLTypeCache import net.nemerosa.ontrack.graphql.support.GraphQLBeanConverter import org.junit.Test import kotlin.test.assertEquals class GQLTypeGitHubIngestionConfigTest { @Test fun `Programmatic type creation`() { val type = GraphQLBeanConverter.asObjectType(IngestionConfig::class, GQLTypeCache()) assertEquals("GitHubIngestionConfig", type.name) } }
ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/ingestion/ui/GQLTypeGitHubIngestionConfigTest.kt
1908481319
package de.axelrindle.broadcaster.model import net.md_5.bungee.api.chat.BaseComponent import net.md_5.bungee.chat.ComponentSerializer /** * A `Message` describes a piece of information that will be broadcasted around the server. */ abstract class Message /** * @param input The input text used for configuration. */ (protected val input: String) /** * A `SimpleMessage` is just a container for holding a plain text message. */ class SimpleMessage(input: String) : Message(input) { /** * Returns just the input string to use as the message text. * * @return The [input]. */ fun getText(): String = input } /** * A `JsonMessage` is created from a json string and converted into an [Array] of [BaseComponent]s. * * @see ComponentSerializer.parse * @see BaseComponent */ class JsonMessage(input: String) : Message(input) { // test for class dependency init { Class.forName("net.md_5.bungee.chat.ComponentSerializer") } val components: Array<BaseComponent> = ComponentSerializer.parse(input) }
src/main/kotlin/de/axelrindle/broadcaster/model/Message.kt
1726638544
package de.xikolo.controllers.section import android.content.res.Configuration import android.graphics.Point import android.os.Bundle import android.text.TextUtils import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import butterknife.BindView import com.yatatsu.autobundle.AutoBundleField import de.xikolo.R import de.xikolo.config.GlideApp import de.xikolo.controllers.base.ViewModelFragment import de.xikolo.controllers.helper.DownloadViewHelper import de.xikolo.controllers.video.VideoItemPlayerActivityAutoBundle import de.xikolo.extensions.observe import de.xikolo.models.DownloadAsset import de.xikolo.models.Item import de.xikolo.models.Video import de.xikolo.utils.LanalyticsUtil import de.xikolo.utils.LanguageUtil import de.xikolo.utils.extensions.cast import de.xikolo.utils.extensions.isCastConnected import de.xikolo.utils.extensions.setMarkdownText import de.xikolo.utils.extensions.videoThumbnailSize import de.xikolo.viewmodels.section.VideoPreviewViewModel import de.xikolo.views.CustomSizeImageView import java.util.concurrent.TimeUnit const val MAX_DESCRIPTION_LINES = 4 class VideoPreviewFragment : ViewModelFragment<VideoPreviewViewModel>() { companion object { val TAG: String = VideoPreviewFragment::class.java.simpleName } @AutoBundleField lateinit var courseId: String @AutoBundleField lateinit var sectionId: String @AutoBundleField lateinit var itemId: String @BindView(R.id.textTitle) lateinit var textTitle: TextView @BindView(R.id.textSubtitles) lateinit var textSubtitles: TextView @BindView(R.id.textPreviewDescription) lateinit var textDescription: TextView @BindView(R.id.showDescriptionButton) lateinit var showDescriptionButton: Button @BindView(R.id.videoDescriptionContainer) lateinit var videoDescriptionContainer: FrameLayout @BindView(R.id.durationText) lateinit var textDuration: TextView @BindView(R.id.videoThumbnail) lateinit var imageVideoThumbnail: CustomSizeImageView @BindView(R.id.containerDownloads) lateinit var linearLayoutDownloads: LinearLayout @BindView(R.id.refresh_layout) lateinit var viewContainer: View @BindView(R.id.playButton) lateinit var viewPlay: View @BindView(R.id.videoMetadata) lateinit var videoMetadata: ViewGroup private var downloadViewHelpers: MutableList<DownloadViewHelper> = ArrayList() private var video: Video? = null override val layoutResource = R.layout.fragment_video_preview override fun createViewModel(): VideoPreviewViewModel { return VideoPreviewViewModel(itemId) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) this.viewContainer.visibility = View.GONE activity?.let { val thumbnailSize: Point = it.videoThumbnailSize imageVideoThumbnail.setDimensions(thumbnailSize.x, thumbnailSize.y) if (it.resources?.configuration?.orientation != Configuration.ORIENTATION_PORTRAIT) { val paramsMeta = videoMetadata.layoutParams paramsMeta.width = thumbnailSize.x videoMetadata.layoutParams = paramsMeta } } viewModel.item .observe(viewLifecycleOwner) { item -> this.video = viewModel.video video?.let { video -> updateView(item, video) showContent() } } } private fun updateView(item: Item, video: Video) { viewContainer.visibility = View.VISIBLE GlideApp.with(this) .load(video.thumbnailUrl) .override(imageVideoThumbnail.forcedWidth, imageVideoThumbnail.forcedHeight) .into(imageVideoThumbnail) textTitle.text = item.title if (video.isSummaryAvailable) { textDescription.setMarkdownText(video.summary?.trim()) displayCollapsedDescription() showDescriptionButton.setOnClickListener { if (textDescription.maxLines == MAX_DESCRIPTION_LINES) { displayFullDescription() } else { displayCollapsedDescription() } } } else { hideDescription() } displayAvailableSubtitles() linearLayoutDownloads.removeAllViews() downloadViewHelpers.clear() activity?.let { activity -> if (video.streamToPlay?.hdUrl != null) { val dvh = DownloadViewHelper( activity, DownloadAsset.Course.Item.VideoHD(item, video), activity.getText(R.string.video_hd_as_mp4) ) dvh.onOpenFileClick(R.string.play) { play() } linearLayoutDownloads.addView(dvh.view) downloadViewHelpers.add(dvh) } if (video.streamToPlay?.sdUrl != null) { val dvh = DownloadViewHelper( activity, DownloadAsset.Course.Item.VideoSD(item, video), activity.getText(R.string.video_sd_as_mp4) ) dvh.onOpenFileClick(R.string.play) { play() } linearLayoutDownloads.addView(dvh.view) downloadViewHelpers.add(dvh) } if (video.slidesUrl != null) { val dvh = DownloadViewHelper( activity, DownloadAsset.Course.Item.Slides(item, video), activity.getText(R.string.slides_as_pdf) ) linearLayoutDownloads.addView(dvh.view) downloadViewHelpers.add(dvh) } if (video.transcriptUrl != null) { val dvh = DownloadViewHelper( activity, DownloadAsset.Course.Item.Transcript(item, video), activity.getText(R.string.transcript_as_pdf) ) linearLayoutDownloads.addView(dvh.view) downloadViewHelpers.add(dvh) } } val minutes = TimeUnit.SECONDS.toMinutes(video.duration.toLong()) val seconds = video.duration - TimeUnit.MINUTES.toSeconds( TimeUnit.SECONDS.toMinutes(video.duration.toLong()) ) textDuration.text = getString(R.string.duration, minutes, seconds) viewPlay.setOnClickListener { play() } } private fun play() { video?.let { video -> if (activity?.isCastConnected == true) { LanalyticsUtil.trackVideoPlay( itemId, courseId, sectionId, video.progress, 1.0f, Configuration.ORIENTATION_LANDSCAPE, "hd", "cast" ) activity?.let { video.cast(it, true) } } else { activity?.let { val intent = video.id?.let { videoId -> VideoItemPlayerActivityAutoBundle .builder(courseId, sectionId, itemId, videoId) .parentIntent(it.intent) .build(it) } startActivity(intent) } } } } private fun displayAvailableSubtitles() { video?.subtitles?.let { subtitles -> if (subtitles.isNotEmpty()) { textSubtitles.text = subtitles.map { LanguageUtil.toLocaleName(it.language) }.joinToString(", ", getString(R.string.video_settings_subtitles) + ": ") textSubtitles.visibility = View.VISIBLE } else { textSubtitles.visibility = View.GONE } } } private fun displayCollapsedDescription() { videoDescriptionContainer.visibility = View.VISIBLE videoDescriptionContainer.foreground = null showDescriptionButton.visibility = View.GONE textDescription.ellipsize = TextUtils.TruncateAt.END textDescription.maxLines = MAX_DESCRIPTION_LINES showDescriptionButton.text = getString(R.string.show_more) textDescription.post { if (textDescription.lineCount > MAX_DESCRIPTION_LINES) { showDescriptionButton.visibility = View.VISIBLE videoDescriptionContainer.foreground = ContextCompat.getDrawable( requireContext(), R.drawable.gradient_light_to_transparent_from_bottom ) } } } private fun displayFullDescription() { textDescription.ellipsize = null textDescription.maxLines = Integer.MAX_VALUE videoDescriptionContainer.foreground = null showDescriptionButton.text = getString(R.string.show_less) } private fun hideDescription() { videoDescriptionContainer.visibility = View.GONE showDescriptionButton.visibility = View.GONE } }
app/src/main/java/de/xikolo/controllers/section/VideoPreviewFragment.kt
1679529010
/* * Copyright 2013 Maurício Linhares * * Maurício Linhares licenses this file to you under the Apache License, * version 2.0 (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.github.mauricio.async.db.column object ShortEncoderDecoder : ColumnEncoderDecoder { override fun decode(value: String): Any = value.toShort() }
db-async-common/src/main/kotlin/com/github/mauricio/async/db/column/ShortEncoderDecoder.kt
681287913
package com.gigigo.orchextrasdk.demo.test.util import android.app.Activity import android.os.Handler import android.os.Looper import androidx.test.runner.lifecycle.ActivityLifecycleMonitor import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry import androidx.test.runner.lifecycle.Stage import java.util.ArrayList import java.util.EnumSet class ActivityFinisher private constructor() : Runnable { private val activityLifecycleMonitor: ActivityLifecycleMonitor = ActivityLifecycleMonitorRegistry.getInstance() override fun run() { val activities = ArrayList<Activity>() for (stage in EnumSet.range(Stage.CREATED, Stage.STOPPED)) { activities.addAll(activityLifecycleMonitor.getActivitiesInStage(stage)) } activities.filterNot { it.isFinishing } .forEach { it.finish() } } companion object { fun finishOpenActivities() { Handler(Looper.getMainLooper()).post(ActivityFinisher()) } } }
app/src/androidTest/java/com/gigigo/orchextrasdk/demo/test/util/ActivityFinisher.kt
603144784
/* * Copyright (C) 2017 Artem Hluhovskyi * * 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.dewarder.akommons.binding.support.view import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.dewarder.akommons.binding.common.NO_VIEW1 import com.dewarder.akommons.binding.common.NO_VIEW2 import com.dewarder.akommons.binding.common.R import com.dewarder.akommons.binding.common.view.TestableView import com.dewarder.akommons.binding.support.view import com.dewarder.akommons.binding.support.viewOptional import com.dewarder.akommons.binding.support.views import com.dewarder.akommons.binding.support.viewsOptional class TestViewSupportFragment : Fragment(), TestableView { override val viewRequiredExist: View by view(R.id.test_view1) override val viewRequiredAbsent: View by view(NO_VIEW1) override val viewOptionalExist: View? by viewOptional(R.id.test_view1) override val viewOptionalAbsent: View? by viewOptional(NO_VIEW1) override val textViewRequiredCorrect: TextView by view(R.id.test_text_view1) override val textViewRequiredIncorrect: LinearLayout by view(R.id.test_text_view1) override val textViewOptionalCorrect: TextView? by viewOptional(R.id.test_text_view1) override val textViewOptionalIncorrect: LinearLayout? by viewOptional(R.id.test_text_view1) override val viewsRequiredExist: List<View> by views(R.id.test_view1, R.id.test_view2) override val viewsRequiredAbsent: List<View> by views(NO_VIEW1, NO_VIEW2) override val viewsOptionalExist: List<View?> by viewsOptional(R.id.test_view1, R.id.test_view2) override val viewsOptionalAbsent: List<View?> by viewsOptional(NO_VIEW1, NO_VIEW2) override val viewsRequiredFirstExistSecondAbsent: List<View> by views(R.id.test_view1, NO_VIEW1) override val viewsOptionalFirstExistSecondAbsent: List<View?> by viewsOptional(R.id.test_view1, NO_VIEW1) override val viewsRequiredExistCorrect: List<TextView> by views(R.id.test_text_view1, R.id.test_text_view2) override val viewsRequiredExistIncorrect: List<TextView> by views(R.id.test_text_view1, R.id.test_view1) override val viewsRequiredExistFirstViewSecondTextViewCorrect: List<View> by views(R.id.test_view1, R.id.test_text_view1) override val viewsOptionalExistCorrect: List<TextView?> by viewsOptional(R.id.test_text_view1, R.id.test_text_view2) override val viewsOptionalExistIncorrect: List<TextView?> by viewsOptional(R.id.test_text_view1, R.id.test_view1) override val viewsOptionalExistFirstViewSecondTextViewCorrect: List<View?> by viewsOptional(R.id.test_view1, R.id.test_text_view1) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return inflater.inflate(R.layout.activity_test_view, container, false) } }
akommons-bindings-support/src/androidTest/java/com/dewarder/akommons/binding/support/view/TestViewSupportFragment.kt
1708771071
package app.cash.sqldelight.core import app.cash.sqldelight.VERSION object GradleCompatibility { fun validate(propertiesFile: SqlDelightPropertiesFile): CompatibilityReport { val (minimumIdeVersion, currentGradleVersion) = try { SemVer(propertiesFile.minimumSupportedVersion) to SemVer(propertiesFile.currentVersion) } catch (e: Throwable) { // If we can't even read the properties file version, it is not compatibile return CompatibilityReport.Incompatible( reason = "Plugin 'SQLDelight' is incompatible with the current version of the SQLDelight Gradle plugin. Upgrade the version of app.cash.sqldelight:gradle-plugin.", ) } val currentVersion = SemVer(VERSION) if (currentVersion < minimumIdeVersion) { return CompatibilityReport.Incompatible( reason = "Plugin 'SQLDelight' is no longer compatible with the current version of the SQLDelight Gradle plugin. Use version $minimumIdeVersion or later.", ) } val minimumGradleVersion = SemVer(MINIMUM_SUPPORTED_VERSION) if (currentGradleVersion < minimumGradleVersion) { return CompatibilityReport.Incompatible( reason = "Gradle plugin 'app.cash.sqldelight:gradle-plugin' is incompatible with the current SQLDelight IntelliJ Plugin version. Use version $minimumGradleVersion or later.", ) } return CompatibilityReport.Compatible } private data class SemVer( val major: Int, val minor: Int, val patch: Int, val snapshot: Boolean, ) { constructor(semVerText: String) : this( major = semVerText.split('.')[0].toInt(), minor = semVerText.split('.')[1].toInt(), patch = semVerText.split('.')[2].filter { it.isDigit() }.toInt(), snapshot = semVerText.endsWith("-SNAPSHOT"), ) operator fun compareTo(other: SemVer): Int { val majorCompare = major.compareTo(other.major) if (majorCompare != 0) return majorCompare val minorCompare = minor.compareTo(other.minor) if (minorCompare != 0) return minorCompare return patch.compareTo(other.patch) } override fun toString() = "$major.$minor.$patch" } sealed class CompatibilityReport { object Compatible : CompatibilityReport() data class Incompatible( val reason: String, ) : CompatibilityReport() } }
sqldelight-compiler/src/main/kotlin/app/cash/sqldelight/core/GradleCompatibility.kt
3006902753
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package jvm.katydid.vdom.builders.forms import jvm.katydid.vdom.api.checkBuild import o.katydid.vdom.application.katydid import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows @Suppress("RemoveRedundantBackticks") class FieldSetTests { @Test fun `A fieldset element produces correct HTML`() { val vdomNode = katydid<Unit> { fieldset(disabled=true,form="SomeForm",name="bunch o'fields") { legend { text("This is the field set") } } } val html = """<fieldset disabled="" form="SomeForm" name="bunch o'fields"> | <legend> | This is the field set | </legend> |</fieldset>""".trimMargin() checkBuild(html, vdomNode) } @Test fun `A fieldset may not have two legends`() { assertThrows<IllegalStateException> { katydid<Unit> { fieldset { legend {} legend {} } } } } @Test fun `A legend must be nested inside a fieldset`() { assertThrows<IllegalStateException> { katydid<Unit> { legend {} } } } }
Katydid-VDOM-JVM/src/test/kotlin/jvm/katydid/vdom/builders/forms/FieldSetTests.kt
1175795153
package com.example import app.cash.sqldelight.TransacterImpl import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.jdbc.JdbcPreparedStatement import kotlin.Unit public class DataQueries( driver: SqlDriver, private val testAdapter: Test.Adapter, ) : TransacterImpl(driver) { public fun insertWhole(test: Test): Unit { driver.execute(-2118611703, """ |INSERT INTO test |VALUES (?, ?) """.trimMargin(), 2) { check(this is JdbcPreparedStatement) bindString(0, test.third) bindString(1, test.second?.let { testAdapter.secondAdapter.encode(it) }) } notifyQueries(-2118611703) { emit -> emit("test") } } }
sqldelight-compiler/src/test/migration-interface-fixtures/alter-table-rename-column/output/com/example/DataQueries.kt
755137021
package mixit.repository import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import mixit.model.Role import mixit.model.User import mixit.util.Cryptographer import mixit.util.encodeToMd5 import org.slf4j.LoggerFactory import org.springframework.core.io.ClassPathResource import org.springframework.data.mongodb.core.ReactiveMongoTemplate import org.springframework.data.mongodb.core.count import org.springframework.data.mongodb.core.find import org.springframework.data.mongodb.core.findAll import org.springframework.data.mongodb.core.findById import org.springframework.data.mongodb.core.findOne import org.springframework.data.mongodb.core.query.Criteria.where import org.springframework.data.mongodb.core.query.Query import org.springframework.data.mongodb.core.query.TextCriteria import org.springframework.data.mongodb.core.query.TextQuery import org.springframework.data.mongodb.core.query.inValues import org.springframework.data.mongodb.core.query.isEqualTo import org.springframework.data.mongodb.core.remove import org.springframework.stereotype.Repository import reactor.core.publisher.Flux import reactor.core.publisher.Mono @Repository class UserRepository( private val template: ReactiveMongoTemplate, private val objectMapper: ObjectMapper, private val cryptographer: Cryptographer ) { private val logger = LoggerFactory.getLogger(this.javaClass) fun initData() { // We delete all users to recreate them since next MEP deleteAll() if (count().block() == 0L) { val usersResource = ClassPathResource("data/users.json") val users: List<User> = objectMapper.readValue(usersResource.inputStream) users.forEach { save(it).block() } logger.info("Users data initialization complete") } } fun findFullText(criteria: List<String>): Flux<User> { val textCriteria = TextCriteria() criteria.forEach { textCriteria.matching(it) } val query = TextQuery(textCriteria).sortByScore() return template.find(query) } fun count() = template.count<User>() fun findByYear(year: Int) = template.find<User>(Query(where("year").isEqualTo(year))) fun findByNonEncryptedEmail(email: String) = template.findOne<User>( Query( where("role").inValues(Role.STAFF, Role.STAFF_IN_PAUSE, Role.USER, Role.VOLUNTEER) .orOperator(where("email").isEqualTo(cryptographer.encrypt(email)), where("emailHash").isEqualTo(email.encodeToMd5())) ) ) fun findByName(firstname: String, lastname: String) = template.find<User>(Query(where("firstname").isEqualTo(firstname).and("lastname").isEqualTo(lastname))) fun findByRoles(roles: List<Role>) = template.find<User>(Query(where("role").inValues(roles))) fun findByRoleAndEvent(role: Role, event: String) = template.find<User>(Query(where("role").isEqualTo(role).and("events").inValues(event))) fun findOneByRoles(login: String, roles: List<Role>) = template.findOne<User>(Query(where("role").inValues(roles).and("_id").isEqualTo(login))) fun findAll() = template.findAll<User>() fun findOne(login: String) = template.findById<User>(login) fun findMany(logins: List<String>) = template.find<User>(Query(where("_id").inValues(logins))) fun findByLegacyId(id: Long) = template.findOne<User>(Query(where("legacyId").isEqualTo(id))) fun deleteAll() = template.remove<User>(Query()) fun deleteOne(login: String) = template.remove<User>(Query(where("_id").isEqualTo(login))) fun save(user: User) = template.save(user) fun save(user: Mono<User>) = template.save(user) }
src/main/kotlin/mixit/repository/UserRepository.kt
2356269487
package com.isupatches.wisefy.internal.mock import android.net.ConnectivityManager import android.net.NetworkInfo import android.net.wifi.ScanResult import android.net.wifi.WifiConfiguration import android.net.wifi.WifiInfo import android.net.wifi.WifiManager import com.isupatches.wisefy.TEST_IP_ADDRESS_INT import com.isupatches.wisefy.TEST_RSSI_LEVEL import com.isupatches.wisefy.TEST_RSSI_LEVEL_HIGH import com.isupatches.wisefy.TEST_RSSI_LEVEL_LOW import com.isupatches.wisefy.TEST_SSID import com.isupatches.wisefy.TEST_SSID2 import com.isupatches.wisefy.TEST_SSID3 import com.isupatches.wisefy.WiseFy.Companion.WIFI_MANAGER_FAILURE import com.isupatches.wisefy.internal.createMockAccessPointWithSSID import com.isupatches.wisefy.internal.createMockAccessPointWithSSIDAndRSSI import com.isupatches.wisefy.internal.createSavedNetwork import org.mockito.ArgumentMatchers.any import org.mockito.ArgumentMatchers.anyInt import org.mockito.Mockito.`when` import org.mockito.Mockito.mock /** * A class that mocks lower level returns from ConnectivityManager and WifiManager. * * @see ConnectivityManager * @see WifiManager * * @author Patches * @since 3.0 */ @Suppress("LargeClass") internal class MockNetworkUtil internal constructor( private val mockConnectivityManager: ConnectivityManager, private val mockWifiManager: WifiManager ) { private var expectedNearbyAccessPoint: ScanResult? = null private var expectedNearbyAccessPoints: MutableList<ScanResult>? = null private var expectedSavedNetwork: WifiConfiguration? = null private var expectedSavedNetworks: MutableList<WifiConfiguration>? = null private var expectedSSIDs: MutableList<String>? = null /** * To mock a device having active network info. * * @see ConnectivityManager.getActiveNetworkInfo * * @author Patches * @since 3.0 */ internal fun activeNetwork() { `when`(mockConnectivityManager.activeNetworkInfo).thenReturn(mock(NetworkInfo::class.java)) } /** * To mock a failure adding a network. * * @see WifiManager.addNetwork * * @author Patches * @since 3.0 */ internal fun addNetwork_failure() { `when`(mockWifiManager.addNetwork(any(WifiConfiguration::class.java))).thenReturn(WIFI_MANAGER_FAILURE) } /** * To mock a success adding a network. * * @see WifiManager.addNetwork * * @author Patches * @since 3.0 */ internal fun addNetwork_success() { `when`(mockWifiManager.addNetwork(any(WifiConfiguration::class.java))).thenReturn(0) } /** * To mock a device having an active network. * * @param ssid The SSID for the mocked network * * @return WifiInfo - The mock active network * * @see WifiInfo * @see WifiManager.getConnectionInfo * * @author Patches * @since 3.0 */ internal fun currentNetwork(ssid: String?): WifiInfo { val mockCurrentNetwork = mock(WifiInfo::class.java) `when`(mockCurrentNetwork.ssid).thenReturn(ssid) `when`(mockWifiManager.connectionInfo).thenReturn(mockCurrentNetwork) return mockCurrentNetwork } /** * To mock a current connection status. * * @param isAvailable Whether the network is available or not * @param isConnected Whether the network is connected or not * @param type The network type * * @see NetworkInfo.isAvailable * @see NetworkInfo.isConnected * @see NetworkInfo.getTypeName * @see ConnectivityManager.getActiveNetworkInfo * * @author Patches * @since 3.0 */ @Suppress("deprecation") internal fun currentNetworkConnectionStatus(isAvailable: Boolean, isConnected: Boolean, type: String?) { val networkInfo = mock(NetworkInfo::class.java) `when`(networkInfo.isAvailable).thenReturn(isAvailable) `when`(networkInfo.isConnected).thenReturn(isConnected) if (type != null) { `when`(networkInfo.typeName).thenReturn(type) } `when`(mockConnectivityManager.activeNetworkInfo).thenReturn(networkInfo) } /** * To mock no current network. * * @see WifiManager.getConnectionInfo * * @author Patches * @since 4.0 */ internal fun currentNetwork_null() { `when`(mockWifiManager.connectionInfo).thenReturn(null) } /** * To mock a failure disabling Wifi. * * @see WifiManager.setWifiEnabled * * @author Patches * @since 3.0 */ internal fun disableWifi_failure() { `when`(mockWifiManager.setWifiEnabled(false)).thenReturn(false) } /** * To mock a success disabling Wifi. * * @see WifiManager.setWifiEnabled * * @author Patches * @since 3.0 */ internal fun disableWifi_success() { `when`(mockWifiManager.setWifiEnabled(false)).thenReturn(true) } /** * To mock a failure disconnecting from current network. * * @see WifiManager.disconnect * * @author Patches * @since 3.0 */ internal fun disconnectFromCurrentNetwork_failure() { `when`(mockWifiManager.disconnect()).thenReturn(false) } /** * To mock a success disconnecting from current network. * * @see WifiManager.disconnect * * @author Patches * @since 3.0 */ internal fun disconnectFromCurrentNetwork_success() { `when`(mockWifiManager.disconnect()).thenReturn(true) } /** * To mock a failure enabling Wifi. * * @see WifiManager.setWifiEnabled * * @author Patches * @since 3.0 */ internal fun enableWifi_failure() { `when`(mockWifiManager.setWifiEnabled(true)).thenReturn(false) } /** * To mock a success enabling Wifi. * * @see WifiManager.setWifiEnabled * * @author Patches * @since 3.0 */ internal fun enableWifi_success() { `when`(mockWifiManager.setWifiEnabled(true)).thenReturn(true) } /** * To return the expected access point for testing. * * @return List of ScanResult - The expected access point for test * * @see ScanResult * * @author Patches * @since 3.0 */ internal fun getExpectedNearbyAccessPoint(): ScanResult? = expectedNearbyAccessPoint /** * To return the list of expected access points for testing. * * @return List of ScanResult - The expected access points for test * * @see ScanResult * * @author Patches * @since 3.0 */ internal fun getExpectedNearbyAccessPoints(): List<ScanResult>? = expectedNearbyAccessPoints /** * To return the expected saved network for testing. * * @return List of Strings - The expected saved network for test * * @see WifiConfiguration * * @author Patches * @since 3.0 */ internal fun getExpectedSavedNetwork(): WifiConfiguration? = expectedSavedNetwork /** * To return the expected list of saved networks for testing. * * @return List of WifiConfiguration - The expected saved networks for test * * @see WifiConfiguration * * @author Patches * @since 3.0 */ internal fun getExpectedSavedNetworks(): List<WifiConfiguration>? = expectedSavedNetworks /** * To return the expected list of SSIDs for testing. * * @return List of Strings - The expected SSIDS for test * * @author Patches * @since 3.0 */ internal fun getExpectedSSIDs(): List<String>? = expectedSSIDs /** * To mock if a device is roaming. * * @param roaming Whether the device is roaming or not * * @see NetworkInfo.isRoaming * @see ConnectivityManager.getActiveNetworkInfo * * @author Patches * @since 3.0 */ @Suppress("deprecation") internal fun isDeviceRoaming(roaming: Boolean) { val networkInfo = mock(NetworkInfo::class.java) `when`(networkInfo.isRoaming).thenReturn(roaming) `when`(mockConnectivityManager.activeNetworkInfo).thenReturn(networkInfo) } /** * To mock if Wifi is enabled or not. * * @param wifiEnabled Whether the device has Wifi enabled or not * * @see WifiManager.isWifiEnabled * * @author Patches * @since 3.0 */ internal fun isWifiEnabled(wifiEnabled: Boolean) { `when`(mockWifiManager.isWifiEnabled).thenReturn(wifiEnabled) } /** * To mock a network with a given frequency. * * @param frequency The frequency for the network * * @see WifiInfo.getFrequency * @see WifiManager.getConnectionInfo * * @author Patches * @since 3.0 */ internal fun networkWithFrequency(frequency: Int): WifiInfo { val mockWifiInfo = mock(WifiInfo::class.java) `when`(mockWifiInfo.frequency).thenReturn(frequency) `when`(mockWifiManager.connectionInfo).thenReturn(mockWifiInfo) return mockWifiInfo } /** * To mock a failure getting the IP of a device. * * @see WifiInfo.getIpAddress * @see WifiManager.getConnectionInfo * * @author Patches * @since 3.0 */ internal fun ip_failure() { val wifiInfo = mock(WifiInfo::class.java) `when`(wifiInfo.ipAddress).thenReturn(0) `when`(mockWifiManager.connectionInfo).thenReturn(wifiInfo) } /** * To mock a success getting the IP of a device. * * @see WifiInfo.getIpAddress * @see WifiManager.getConnectionInfo * * @author Patches * @since 3.0 */ internal fun ip_success() { val wifiInfo = mock(WifiInfo::class.java) `when`(wifiInfo.ipAddress).thenReturn(TEST_IP_ADDRESS_INT) `when`(mockWifiManager.connectionInfo).thenReturn(wifiInfo) } /** * To mock an empty list of access points. * * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_emptyList() { `when`(mockWifiManager.scanResults).thenReturn(ArrayList()) } /** * To mock a list of access points with one that has a matching SSID. * * @see addToExpectedNearbyAccessPoints * @see addToExpectedSSIDs * @see ScanResult * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_matchingSSID() { val accessPoint = createMockAccessPointWithSSID(TEST_SSID) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint) addToExpectedNearbyAccessPoints(accessPoint) addToExpectedSSIDs(accessPoint) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with multiple access points that have the same SSID. * Access point 1 will have the higher RSSI level. * * @param takeHighest If the search is going to take the access point with the highest RSSI * * @see createMockAccessPointWithSSIDAndRSSI * @see ScanResult * @see addToExpectedNearbyAccessPoints * @see addToExpectedSSIDs * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint1HasHigherRSSI(takeHighest: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_HIGH) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_LOW) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint1) accessPoints.add(accessPoint2) if (takeHighest) { addToExpectedNearbyAccessPoints(accessPoint1) } else { addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2) } addToExpectedSSIDs(accessPoint1) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with multiple access points that have the same SSID. * Access point 2 will have the higher RSSI level. * * @param takeHighest If the search is going to take the access point with the highest RSSI * * @see createMockAccessPointWithSSIDAndRSSI * @see ScanResult * @see addToExpectedNearbyAccessPoints * @see addToExpectedSSIDs * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_multipleMatchingSSIDs_accessPoint2HasHigherRSSI(takeHighest: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_LOW) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL_HIGH) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint1) accessPoints.add(accessPoint2) if (takeHighest) { addToExpectedNearbyAccessPoints(accessPoint2) } else { addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2) } addToExpectedSSIDs(accessPoint1) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with one access point that has a matching SSID and * another one that does not a matching SSID. Both will that have the same RSSI. * * @param addSecondNetwork If the second network should be added to the expected network * list for testing * * @see createMockAccessPointWithSSIDAndRSSI * @see ScanResult * @see addToExpectedNearbyAccessPoints * @see addToExpectedSSIDs * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_multipleSSIDs_sameRSSI(addSecondNetwork: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID2, TEST_RSSI_LEVEL) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint1) accessPoints.add(accessPoint2) if (addSecondNetwork) { addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2) } else { addToExpectedNearbyAccessPoints(accessPoint1) } if (addSecondNetwork) { addToExpectedSSIDs(accessPoint1, accessPoint2) } else { addToExpectedSSIDs(accessPoint1) } `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with multiple access points that have the same SSID and * the same RSSI level. * * @param addSecondNetwork If the second network should be added to the expected network * list for testing * * @see createMockAccessPointWithSSIDAndRSSI * @see ScanResult * @see addToExpectedNearbyAccessPoints * @see addToExpectedSSIDs * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_multipleMatchingSSIDs_sameRSSI(addSecondNetwork: Boolean) { val accessPoint1 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL) val accessPoint2 = createMockAccessPointWithSSIDAndRSSI(TEST_SSID, TEST_RSSI_LEVEL) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint1) accessPoints.add(accessPoint2) if (addSecondNetwork) { addToExpectedNearbyAccessPoints(accessPoint1, accessPoint2) } else { addToExpectedNearbyAccessPoints(accessPoint1) } addToExpectedSSIDs(accessPoint1) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with multiple non-matching SSIDs. * * @see createMockAccessPointWithSSID * @see ScanResult * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_multipleNonMatchingSSIDs() { val accessPoint1 = createMockAccessPointWithSSID(TEST_SSID2) val accessPoint2 = createMockAccessPointWithSSID(TEST_SSID3) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint1) accessPoints.add(accessPoint2) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with a non-matching SSID. * * @see createMockAccessPointWithSSID * @see ScanResult * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_nonMatchingSSID() { val accessPoint = createMockAccessPointWithSSID(TEST_SSID2) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a list of access points with a null configuration. * * @see ScanResult * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_nullAccessPoint() { val accessPoints = arrayListOf<ScanResult?>(null) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock a null list of access points. * * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_nullList() { `when`(mockWifiManager.scanResults).thenReturn(null) } /** * To mock a list of access points with a configuration that has a null SSID. * * @see createMockAccessPointWithSSID * @see ScanResult * @see WifiManager.getScanResults * * @author Patches * @since 3.0 */ internal fun nearbyAccessPoints_nullSSID() { val accessPoint = createMockAccessPointWithSSID(null) val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint) `when`(mockWifiManager.scanResults).thenReturn(accessPoints) } /** * To mock if removing a network is successful or not. * * @param removed Whether or not the network was successfully removed * * @see WifiManager.removeNetwork * * @author Patches * @since 3.0 */ internal fun removeNetwork(removed: Boolean) { `when`(mockWifiManager.removeNetwork(anyInt())).thenReturn(removed) } /** * To mock a list of saved networks. * * @return The list of saved networks for testing * * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks(): List<WifiConfiguration> { val savedNetworks = ArrayList<WifiConfiguration>() val wiFiConfiguration = createSavedNetwork(TEST_SSID) savedNetworks.add(wiFiConfiguration) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) return savedNetworks } /** * To mock an empty list of saved networks. * * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_emptyList() { `when`(mockWifiManager.configuredNetworks).thenReturn(ArrayList()) } /** * To mock a list of saved networks with a null configuration. * * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_listWithNull() { val savedNetworks = arrayListOf<WifiConfiguration?>(null) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /** * To mock a list of saved networks with a configuration that has a matching SSID. * * @see addToExpectedSavedNetworks * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_matchingSSID() { val savedNetwork = createSavedNetwork(TEST_SSID) val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork) addToExpectedSavedNetworks(savedNetwork) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /** * To mock a list of saved networks with multiple configurations that have a matching SSID. * * @see addToExpectedSavedNetworks * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_multipleMatchingSSIDs() { val savedNetwork1 = createSavedNetwork(TEST_SSID) val savedNetwork2 = createSavedNetwork(TEST_SSID) val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork1) savedNetworks.add(savedNetwork2) addToExpectedSavedNetworks(savedNetwork1, savedNetwork2) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /** * To mock a list of saved networks with multiple configurations that have non-matching SSIDs. * * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_multipleNonMatchingSSIDs() { val savedNetwork1 = createSavedNetwork(TEST_SSID2) val savedNetwork2 = createSavedNetwork(TEST_SSID3) val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork1) savedNetworks.add(savedNetwork2) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /** * To mock a list of saved networks with one matching and one non-matching SSID. * * @param addSecondNetwork If the second network should be added to the expected network * list for testing * * @see addToExpectedSavedNetworks * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_multipleSSIDs(addSecondNetwork: Boolean) { val savedNetwork1 = createSavedNetwork(TEST_SSID) val savedNetwork2 = createSavedNetwork(TEST_SSID2) val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork1) savedNetworks.add(savedNetwork2) if (addSecondNetwork) { addToExpectedSavedNetworks(savedNetwork1, savedNetwork2) } else { addToExpectedSavedNetworks(savedNetwork1) } `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /** * To mock a list of saved networks with a configuration that has a non-matching SSID. * * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_nonMatchingSSID() { val savedNetwork = createSavedNetwork(TEST_SSID2) val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /** * To mock a null list of saved networks. * * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_nullList() { `when`(mockWifiManager.configuredNetworks).thenReturn(null) } /** * To mock a list of saved networks with a configuration that has a null SSID. * * @see createSavedNetwork * @see WifiConfiguration * @see WifiManager.getConfiguredNetworks * * @author Patches * @since 3.0 */ internal fun savedNetworks_nullSSID() { val savedNetwork = createSavedNetwork(null) val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork) `when`(mockWifiManager.configuredNetworks).thenReturn(savedNetworks) } /* * HELPERS */ private fun addToExpectedNearbyAccessPoints(accessPoint: ScanResult) { expectedNearbyAccessPoint = accessPoint val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint) expectedNearbyAccessPoints = accessPoints } private fun addToExpectedNearbyAccessPoints(accessPoint1: ScanResult, accessPoint2: ScanResult) { expectedNearbyAccessPoint = accessPoint1 val accessPoints = ArrayList<ScanResult>() accessPoints.add(accessPoint1) accessPoints.add(accessPoint2) expectedNearbyAccessPoints = accessPoints } private fun addToExpectedSavedNetworks(savedNetwork: WifiConfiguration) { expectedSavedNetwork = savedNetwork val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork) expectedSavedNetworks = savedNetworks } private fun addToExpectedSavedNetworks(savedNetwork1: WifiConfiguration, savedNetwork2: WifiConfiguration) { expectedSavedNetwork = savedNetwork1 expectedSavedNetworks = ArrayList() val savedNetworks = ArrayList<WifiConfiguration>() savedNetworks.add(savedNetwork1) savedNetworks.add(savedNetwork2) expectedSavedNetworks = savedNetworks } private fun addToExpectedSSIDs(accessPoint: ScanResult) { val ssids = ArrayList<String>() ssids.add(accessPoint.SSID) expectedSSIDs = ssids } private fun addToExpectedSSIDs(accessPoint1: ScanResult, accessPoint2: ScanResult) { val ssids = ArrayList<String>() ssids.add(accessPoint1.SSID) ssids.add(accessPoint2.SSID) expectedSSIDs = ssids } }
wisefy/src/androidTest/java/com/isupatches/wisefy/internal/mock/MockNetworkUtil.kt
644437672