path
stringlengths
4
297
contentHash
stringlengths
1
10
content
stringlengths
0
13M
src/main/kotlin/com/freundtech/minecraft/oneslotserver/handler/event/ServerListPingListener.kt
1369565764
package com.freundtech.minecraft.oneslotserver.handler.event import com.freundtech.minecraft.oneslotserver.OneSlotServer import com.freundtech.minecraft.oneslotserver.extension.format import com.freundtech.minecraft.oneslotserver.extension.oneSlotServer import org.bukkit.Bukkit import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.server.ServerListPingEvent class ServerListPingListener(private val plugin: OneSlotServer) : Listener{ private var iconEmpty = Bukkit.loadServerIcon(plugin.iconEmpty) private var iconFull = Bukkit.loadServerIcon(plugin.iconFull) @EventHandler fun onServerListPing(event: ServerListPingEvent) { event.maxPlayers = 1 event.removeAll { player -> Boolean player.uniqueId != plugin.activePlayer?.uniqueId } plugin.activePlayer?.let { val waitLeft = it.oneSlotServer.timeLeft event.motd = "A player is currently playing. Please wait ${waitLeft.format()}." event.setServerIcon(iconFull) } ?: run { event.motd = "Nobody is playing. You can join the server." event.setServerIcon(iconEmpty) } } }
sketch-extensions/src/main/java/com/github/panpf/sketch/viewability/MimeTypeLogoAbility.kt
2567562547
/* * Copyright (C) 2022 panpf <[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 com.github.panpf.sketch.viewability import android.content.Context import android.graphics.Canvas import android.graphics.drawable.Animatable import android.graphics.drawable.Drawable import androidx.appcompat.content.res.AppCompatResources import com.github.panpf.sketch.util.findLastSketchDrawable /** * Display the MimeType logo in the lower right corner of the View */ fun ViewAbilityContainer.showMimeTypeLogoWithDrawable( mimeTypeIconMap: Map<String, Drawable>, margin: Int = 0 ) { removeMimeTypeLogo() addViewAbility( MimeTypeLogoAbility( mimeTypeIconMap.mapValues { MimeTypeLogo(it.value) }, margin ) ) } /** * Display the MimeType logo in the lower right corner of the View */ fun ViewAbilityContainer.showMimeTypeLogoWithRes( mimeTypeIconMap: Map<String, Int>, margin: Int = 0 ) { removeMimeTypeLogo() addViewAbility( MimeTypeLogoAbility( mimeTypeIconMap.mapValues { MimeTypeLogo(it.value) }, margin ) ) } /** * Remove MimeType logo */ fun ViewAbilityContainer.removeMimeTypeLogo() { viewAbilityList .find { it is MimeTypeLogoAbility } ?.let { removeViewAbility(it) } } /** * Returns true if MimeType logo feature is enabled */ val ViewAbilityContainer.isShowMimeTypeLogo: Boolean get() = viewAbilityList.find { it is MimeTypeLogoAbility } != null class MimeTypeLogoAbility( private val mimeTypeIconMap: Map<String, MimeTypeLogo>, private val margin: Int = 0 ) : ViewAbility, AttachObserver, DrawObserver, LayoutObserver, DrawableObserver { override var host: Host? = null private var logoDrawable: Drawable? = null override fun onAttachedToWindow() { reset() host?.view?.invalidate() } override fun onDetachedFromWindow() { } override fun onDrawableChanged(oldDrawable: Drawable?, newDrawable: Drawable?) { reset() host?.view?.invalidate() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { reset() host?.view?.invalidate() } override fun onDrawBefore(canvas: Canvas) { } override fun onDraw(canvas: Canvas) { logoDrawable?.draw(canvas) } private fun reset() { logoDrawable = null val host = host ?: return val view = host.view val lastDrawable = host.container.getDrawable()?.findLastSketchDrawable() ?: return val mimeType = lastDrawable.imageInfo.mimeType val mimeTypeLogo = mimeTypeIconMap[mimeType] ?: return if (mimeTypeLogo.hiddenWhenAnimatable && lastDrawable is Animatable) return val logoDrawable = mimeTypeLogo.getDrawable(host.context) logoDrawable.setBounds( view.right - view.paddingRight - margin - logoDrawable.intrinsicWidth, view.bottom - view.paddingBottom - margin - logoDrawable.intrinsicHeight, view.right - view.paddingRight - margin, view.bottom - view.paddingBottom - margin ) this.logoDrawable = logoDrawable } } class MimeTypeLogo { private val data: Any private var _drawable: Drawable? = null val hiddenWhenAnimatable: Boolean constructor(drawable: Drawable, hiddenWhenAnimatable: Boolean = false) { this.data = drawable this.hiddenWhenAnimatable = hiddenWhenAnimatable } constructor(drawableResId: Int, hiddenWhenAnimatable: Boolean = false) { this.data = drawableResId this.hiddenWhenAnimatable = hiddenWhenAnimatable } fun getDrawable(context: Context): Drawable { return _drawable ?: if (data is Drawable) { data } else { AppCompatResources.getDrawable(context, data as Int)!! }.apply { _drawable = this } } }
app/src/test/java/org/wikipedia/feed/topread/TopReadItemCardTest.kt
807271574
package org.wikipedia.feed.topread import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.wikipedia.dataclient.WikiSite import org.wikipedia.json.JsonUtil import org.wikipedia.test.TestFileUtil @RunWith(RobolectricTestRunner::class) class TopReadItemCardTest { private lateinit var content: TopRead @Before @Throws(Throwable::class) fun setUp() { val json = TestFileUtil.readRawFile("mostread_2016_11_07.json") content = JsonUtil.decodeFromString(json)!! } @Test fun testTitleNormalization() { val topReadItemCards = TopReadListCard.toItems(content.articles, TEST) for (topReadItemCard in topReadItemCards) { MatcherAssert.assertThat(topReadItemCard.title(), Matchers.not(Matchers.containsString("_"))) } } companion object { private val TEST = WikiSite.forLanguageCode("test") } }
app/src/main/java/org/wikipedia/analytics/eventplatform/EventPlatformClient.kt
3229852486
package org.wikipedia.analytics.eventplatform import androidx.core.os.postDelayed import io.reactivex.rxjava3.schedulers.Schedulers import org.wikipedia.BuildConfig import org.wikipedia.WikipediaApp import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.okhttp.HttpStatusException import org.wikipedia.settings.Prefs import org.wikipedia.util.ReleaseUtil import org.wikipedia.util.log.L import java.net.HttpURLConnection import java.util.* object EventPlatformClient { /** * Stream configs to be fetched on startup and stored for the duration of the app lifecycle. */ private val STREAM_CONFIGS = mutableMapOf<String, StreamConfig>() /* * When ENABLED is false, items can be enqueued but not dequeued. * Timers will not be set for enqueued items. * QUEUE will not grow beyond MAX_QUEUE_SIZE. * * Inputs: network connection state on/off, connection state bad y/n? * Taken out of iOS client, but flag can be set on the request object to wait until connected to send */ private var ENABLED = WikipediaApp.instance.isOnline fun setStreamConfig(streamConfig: StreamConfig) { STREAM_CONFIGS[streamConfig.streamName] = streamConfig } fun getStreamConfig(name: String): StreamConfig? { return STREAM_CONFIGS[name] } /** * Set whether the client is enabled. This can react to device online/offline state as well * as other considerations. */ @Synchronized fun setEnabled(enabled: Boolean) { ENABLED = enabled if (ENABLED) { /* * Try immediately to send any enqueued items. Otherwise another * item must be enqueued before sending is triggered. */ OutputBuffer.sendAllScheduled() } } /** * Submit an event to be enqueued and sent to the Event Platform * * @param event event */ @Synchronized fun submit(event: Event) { if (!SamplingController.isInSample(event)) { return } OutputBuffer.schedule(event) } fun flushCachedEvents() { OutputBuffer.sendAllScheduled() } private fun refreshStreamConfigs() { ServiceFactory.get(WikiSite(BuildConfig.META_WIKI_BASE_URI)).streamConfigs .subscribeOn(Schedulers.io()) .subscribe({ updateStreamConfigs(it.streamConfigs) }) { L.e(it) } } @Synchronized private fun updateStreamConfigs(streamConfigs: Map<String, StreamConfig>) { STREAM_CONFIGS.clear() STREAM_CONFIGS.putAll(streamConfigs) Prefs.streamConfigs = STREAM_CONFIGS } fun setUpStreamConfigs() { STREAM_CONFIGS.clear() STREAM_CONFIGS.putAll(Prefs.streamConfigs) refreshStreamConfigs() } /** * OutputBuffer: buffers events in a queue prior to transmission * * Transmissions are not sent at a uniform offset but are shaped into * 'bursts' using a combination of queue size and debounce time. * * These concentrate requests (and hence, theoretically, radio awake state) * so as not to contribute to battery drain. */ internal object OutputBuffer { private val QUEUE = mutableListOf<Event>() /* * When an item is added to QUEUE, wait this many ms before sending. * If another item is added to QUEUE during this time, reset the countdown. */ private const val WAIT_MS = 30000L private const val MAX_QUEUE_SIZE = 128 private const val TOKEN = "sendScheduled" @Synchronized fun sendAllScheduled() { WikipediaApp.instance.mainThreadHandler.removeCallbacksAndMessages(TOKEN) if (ENABLED) { send() QUEUE.clear() } } /** * Schedule a request to be sent. * * @param event event data */ @Synchronized fun schedule(event: Event) { if (ENABLED || QUEUE.size <= MAX_QUEUE_SIZE) { QUEUE.add(event) } if (ENABLED) { if (QUEUE.size >= MAX_QUEUE_SIZE) { sendAllScheduled() } else { // The arrival of a new item interrupts the timer and resets the countdown. WikipediaApp.instance.mainThreadHandler.removeCallbacksAndMessages(TOKEN) WikipediaApp.instance.mainThreadHandler.postDelayed(WAIT_MS, TOKEN) { sendAllScheduled() } } } } /** * If sending is enabled, attempt to send the provided events. * Also batch the events ordered by their streams, as the QUEUE * can contain events of different streams */ private fun send() { if (!Prefs.isEventLoggingEnabled) { return } QUEUE.groupBy { it.stream }.forEach { (stream, events) -> sendEventsForStream(STREAM_CONFIGS[stream]!!, events) } } fun sendEventsForStream(streamConfig: StreamConfig, events: List<Event>) { (if (ReleaseUtil.isDevRelease) ServiceFactory.getAnalyticsRest(streamConfig).postEvents(events) else ServiceFactory.getAnalyticsRest(streamConfig).postEventsHasty(events)) .subscribeOn(Schedulers.io()) .subscribe({ when (it.code()) { HttpURLConnection.HTTP_CREATED, HttpURLConnection.HTTP_ACCEPTED -> {} else -> { // Received successful response, but unexpected HTTP code. // TODO: queue up to retry? } } }) { if (it is HttpStatusException) { when (it.code) { HttpURLConnection.HTTP_BAD_REQUEST, HttpURLConnection.HTTP_INTERNAL_ERROR, HttpURLConnection.HTTP_UNAVAILABLE, HttpURLConnection.HTTP_GATEWAY_TIMEOUT -> { L.e(it) // TODO: queue up to retry? } else -> { // Something unexpected happened. Crash if this is a pre-production build. L.logRemoteErrorIfProd(it) } } } else { L.w(it) } } } } /** * AssociationController: provides associative identifiers and manage their * persistence * * Identifiers correspond to various scopes e.g. 'pageview', 'session', and 'device'. * * TODO: Possibly get rid of the pageview type? Does it make sense on apps? It is not in the iOS library currently. * On apps, a "session" starts when the app is loaded, and ends when completely closed, or after 15 minutes of inactivity * Save a ts when going into bg, then when returning to foreground, & if it's been more than 15 mins, start a new session, else continue session from before * Possible to query/track time since last interaction? (For future) */ internal object AssociationController { private var PAGEVIEW_ID: String? = null private var SESSION_ID: String? = null /** * Generate a pageview identifier. * * @return pageview ID * * The identifier is a string of 20 zero-padded hexadecimal digits * representing a uniformly random 80-bit integer. */ val pageViewId: String get() { if (PAGEVIEW_ID == null) { PAGEVIEW_ID = generateRandomId() } return PAGEVIEW_ID!! } /** * Generate a session identifier. * * @return session ID * * The identifier is a string of 20 zero-padded hexadecimal digits * representing a uniformly random 80-bit integer. */ val sessionId: String get() { if (SESSION_ID == null) { // If there is no runtime value for SESSION_ID, try to load a // value from persistent store. SESSION_ID = Prefs.eventPlatformSessionId if (SESSION_ID == null) { // If there is no value in the persistent store, generate a new value for // SESSION_ID, and write the update to the persistent store. SESSION_ID = generateRandomId() Prefs.eventPlatformSessionId = SESSION_ID } } return SESSION_ID!! } fun beginNewSession() { // Clear runtime and persisted value for SESSION_ID. SESSION_ID = null Prefs.eventPlatformSessionId = null // A session refresh implies a pageview refresh, so clear runtime value of PAGEVIEW_ID. PAGEVIEW_ID = null } /** * @return a string of 20 zero-padded hexadecimal digits representing a uniformly random * 80-bit integer */ private fun generateRandomId(): String { val random = Random() return String.format("%08x", random.nextInt()) + String.format("%08x", random.nextInt()) + String.format("%04x", random.nextInt() and 0xFFFF) } } /** * SamplingController: computes various sampling functions on the client * * Sampling is based on associative identifiers, each of which have a * well-defined scope, and sampling config, which each stream provides as * part of its configuration. */ internal object SamplingController { private var SAMPLING_CACHE = mutableMapOf<String, Boolean>() /** * @param event event * @return true if in sample or false otherwise */ fun isInSample(event: Event): Boolean { val stream = event.stream if (SAMPLING_CACHE.containsKey(stream)) { return SAMPLING_CACHE[stream]!! } val streamConfig = STREAM_CONFIGS[stream] ?: return false val samplingConfig = streamConfig.samplingConfig if (samplingConfig == null || samplingConfig.rate == 1.0) { return true } if (samplingConfig.rate == 0.0) { return false } val inSample = getSamplingValue(samplingConfig.unit) < samplingConfig.rate SAMPLING_CACHE[stream] = inSample return inSample } /** * @param unit Unit type from sampling config * @return a floating point value between 0.0 and 1.0 (inclusive) */ fun getSamplingValue(unit: String): Double { val token = getSamplingId(unit).substring(0, 8) return token.toLong(16).toDouble() / 0xFFFFFFFFL.toDouble() } fun getSamplingId(unit: String): String { if (unit == SamplingConfig.UNIT_SESSION) { return AssociationController.sessionId } if (unit == SamplingConfig.UNIT_PAGEVIEW) { return AssociationController.pageViewId } if (unit == SamplingConfig.UNIT_DEVICE) { return Prefs.appInstallId.orEmpty() } L.e("Bad identifier type") return UUID.randomUUID().toString() } } }
src/main/kotlin/com/projectcitybuild/core/infrastructure/database/migrations/20220115_player_configs_warps.kt
2759702297
package com.projectcitybuild.core.infrastructure.database.migrations import co.aikar.idb.HikariPooledDatabase import com.projectcitybuild.core.infrastructure.database.DatabaseMigration class `20220115_player_configs_warps` : DatabaseMigration { override val description = "Add player configs and warps" override fun execute(database: HikariPooledDatabase) { database.executeUpdate( """ |CREATE TABLE players ( | `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, | `uuid` VARCHAR(50) NOT NULL, | `is_muted` TINYINT(1) NOT NULL DEFAULT '0', | `is_allowing_tp` TINYINT(1) NOT NULL DEFAULT '1', | `first_seen` DATETIME NOT NULL, | PRIMARY KEY `id` (`id`), | INDEX (`uuid`) |); """ .trimMargin("|") .replace("\n", "") ) database.executeUpdate( """ |CREATE TABLE warps ( | `name` VARCHAR(50) NOT NULL, | `server_name` VARCHAR(50) NOT NULL, | `world_name` VARCHAR(50) NOT NULL, | `x` DOUBLE NOT NULL DEFAULT 0, | `y` DOUBLE NOT NULL DEFAULT 0, | `z` DOUBLE NOT NULL DEFAULT 0, | `pitch` FLOAT NOT NULL DEFAULT 0, | `yaw` FLOAT NOT NULL DEFAULT 0, | `created_at` DATETIME NOT NULL, | PRIMARY KEY (`name`) USING BTREE |); """ .trimMargin("|") .replace("\n", "") ) database.executeUpdate( """ |CREATE TABLE chat_ignores ( | `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, | `player_id` BIGINT UNSIGNED NOT NULL, | `ignored_player_id` BIGINT UNSIGNED NOT NULL, | `created_at` DATETIME NOT NULL, | PRIMARY KEY (`id`), | CONSTRAINT `chat_ignores_player_id` FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION, | CONSTRAINT `chat_ignores_ignored_player_id` FOREIGN KEY (`ignored_player_id`) REFERENCES `players` (`id`) ON UPDATE NO ACTION ON DELETE NO ACTION |); """ .trimMargin("|") .replace("\n", "") ) database.executeUpdate( """ |CREATE TABLE queued_warps ( | `player_uuid` VARCHAR(50) NOT NULL, | `warp_name` VARCHAR(50) NOT NULL, | `server_name` VARCHAR(50) NOT NULL, | `world_name` VARCHAR(50) NOT NULL, | `x` DOUBLE NOT NULL DEFAULT 0, | `y` DOUBLE NOT NULL DEFAULT 0, | `z` DOUBLE NOT NULL DEFAULT 0, | `pitch` FLOAT NOT NULL DEFAULT 0, | `yaw` FLOAT NOT NULL DEFAULT 0, | `created_at` DATETIME NOT NULL, | PRIMARY KEY (`player_uuid`) |); """ .trimMargin("|") .replace("\n", "") ) database.executeUpdate( """ |CREATE TABLE queued_teleports ( | `player_uuid` VARCHAR(50) NOT NULL, | `target_player_uuid` VARCHAR(50) NOT NULL, | `target_server_name` VARCHAR(50) NOT NULL, | `teleport_type` VARCHAR(10) NOT NULL, | `created_at` DATETIME NOT NULL, | PRIMARY KEY (`player_uuid`) |); """ .trimMargin("|") .replace("\n", "") ) } }
sudoq-app/sudoqapp/src/test/kotlin/de/sudoq/persistence/XmlHelperTests.kt
841922289
package de.sudoq.persistence import org.amshove.kluent.* import org.junit.jupiter.api.Test import java.io.File import java.io.FileNotFoundException import java.io.IOException class XmlHelperTests { private var helper = XmlHelper() @Test @Throws(FileNotFoundException::class, IllegalArgumentException::class, IOException::class) fun testLoadXml() { val sudokuTree: XmlTree = helper.loadXml(File("res/sudoku_example.xml"))!! // helper.buildXmlStructure(sudokuTree); sudokuTree.numberOfChildren `should be equal to` 2 sudokuTree.name `should be equal to` "sudoku" val gameTree: XmlTree = helper.loadXml(File("res/game_example.xml"))!! // helper.buildXmlStructure(gameTree); gameTree.numberOfChildren `should be equal to` 4 val gamesTree: XmlTree = helper.loadXml(File("res/games_example.xml"))!! // helper.buildXmlStructure(gamesTree); gamesTree.numberOfChildren `should be equal to` 1 } @Test @Throws(IllegalArgumentException::class, IOException::class) fun testLoadXmlFileNotFoundException() { invoking { helper.loadXml(File("res/not_existing_imaginary_file.xml")) }.`should throw`(FileNotFoundException::class) } @Test @Throws(IOException::class) fun testLoadXmlIOException() { invoking { helper.loadXml(File("res/compromised.xml")) }.`should throw`(IOException::class) } //TODO test content. it does not seem to bee working @Test @Throws(FileNotFoundException::class, IllegalArgumentException::class, IOException::class) fun testSaveXml() { val testFile = File("res/tmp.xml") testFile.setWritable(true) val testFile2 = File("res/tmp2.xml") val sudoku = XmlTree("sudoku") sudoku.addAttribute(XmlAttribute("id", "7845")) sudoku.addAttribute(XmlAttribute("type", "6")) sudoku.addAttribute(XmlAttribute("complexity", "3")) val fieldmap1 = XmlTree("fieldmap") fieldmap1.addAttribute(XmlAttribute("editable", "true")) fieldmap1.addAttribute(XmlAttribute("solution", "9")) val position1 = XmlTree("position") position1.addAttribute(XmlAttribute("x", "1")) position1.addAttribute(XmlAttribute("y", "8")) fieldmap1.addChild(position1) sudoku.addChild(fieldmap1) val fieldmap2 = XmlTree("fieldmap") fieldmap2.addAttribute(XmlAttribute("editable", "true")) fieldmap2.addAttribute(XmlAttribute("solution", "4")) val position2 = XmlTree("position") position2.addAttribute(XmlAttribute("x", "2")) position2.addAttribute(XmlAttribute("y", "6")) fieldmap2.addChild(position2) sudoku.addChild(fieldmap2) println(helper.buildXmlStructure(sudoku)) helper.saveXml(sudoku, testFile) val sudokuTest: XmlTree = helper.loadXml(testFile)!! println("------------------------------------------") println(helper.buildXmlStructure(sudokuTest)) sudokuTest.name `should be equal to` sudoku.name sudokuTest.numberOfChildren `should be equal to` sudoku.numberOfChildren var i = 0 val iterator: Iterator<XmlTree> = sudokuTest.getChildren() while (iterator.hasNext()) { val sub: XmlTree = iterator.next() if (i == 0) { sub.getAttributeValue("solution") `should be equal to` "9" } else if (i == 1) { sub.getAttributeValue("solution") `should be equal to` "4" } sub.getAttributeValue("editable") `should be equal to` "true" sub.name `should be equal to` "fieldmap" sub.numberOfChildren `should be equal to` 1 i++ } i `should be equal to` 2 val atomicTest = XmlTree("sudoku", "xyz") helper.saveXml(atomicTest, testFile2) } @Test @Throws(IllegalArgumentException::class, IOException::class) fun testSaveXmlIOException() { val file = File("res/tmp.xml") file.setWritable(false) // this test will fail if you use linux and the file gets created on a // ntfs partition. // seems that the java file implementation uses linux tools like chmod - // chmod doesnt work on ntfs... file.canWrite().`should be false`() invoking { helper.saveXml(XmlTree("sudoku", ""), file) }.`should throw`(IOException::class) } @Test @Throws(IOException::class) fun testSaveXmlIllegalArgumentException4() { invoking { helper.saveXml(XmlTree("name", ""), File("res/tmp.xml")) }.`should throw`(IllegalArgumentException::class) } }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/host/exp/exponent/VersionedUtils.kt
2573654702
// Copyright 2015-present 650 Industries. All rights reserved. package abi43_0_0.host.exp.exponent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import android.provider.Settings import android.util.Log import com.facebook.common.logging.FLog import abi43_0_0.com.facebook.hermes.reactexecutor.HermesExecutorFactory import abi43_0_0.com.facebook.react.ReactInstanceManager import abi43_0_0.com.facebook.react.ReactInstanceManagerBuilder import abi43_0_0.com.facebook.react.bridge.JavaScriptContextHolder import abi43_0_0.com.facebook.react.bridge.JavaScriptExecutorFactory import abi43_0_0.com.facebook.react.bridge.ReactApplicationContext import abi43_0_0.com.facebook.react.common.LifecycleState import abi43_0_0.com.facebook.react.common.ReactConstants import abi43_0_0.com.facebook.react.jscexecutor.JSCExecutorFactory import abi43_0_0.com.facebook.react.modules.systeminfo.AndroidInfoHelpers import abi43_0_0.com.facebook.react.packagerconnection.NotificationOnlyHandler import abi43_0_0.com.facebook.react.packagerconnection.RequestHandler import abi43_0_0.com.facebook.react.shell.MainReactPackage import expo.modules.jsonutils.getNullable import host.exp.exponent.Constants import host.exp.exponent.RNObject import host.exp.exponent.experience.ExperienceActivity import host.exp.exponent.experience.ReactNativeActivity import host.exp.exponent.kernel.KernelProvider import host.exp.expoview.Exponent import host.exp.expoview.Exponent.InstanceManagerBuilderProperties import org.json.JSONObject import abi43_0_0.host.exp.exponent.modules.api.reanimated.ReanimatedJSIModulePackage import java.io.File import java.io.FileInputStream import java.io.FileNotFoundException import java.io.IOException import java.util.* object VersionedUtils { // Update this value when hermes-engine getting updated. // Currently there is no way to retrieve Hermes bytecode version from Java, // as an alternative, we maintain the version by hand. private const val HERMES_BYTECODE_VERSION = 76 private fun toggleExpoDevMenu() { val currentActivity = Exponent.instance.currentActivity if (currentActivity is ExperienceActivity) { currentActivity.toggleDevMenu() } else { FLog.e( ReactConstants.TAG, "Unable to toggle the Expo dev menu because the current activity could not be found." ) } } private fun reloadExpoApp() { val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run { FLog.e( ReactConstants.TAG, "Unable to reload the app because the current activity could not be found." ) } val devSupportManager = currentActivity.devSupportManager ?: return run { FLog.e( ReactConstants.TAG, "Unable to get the DevSupportManager from current activity." ) } devSupportManager.callRecursive("reloadExpoApp") } private fun toggleElementInspector() { val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run { FLog.e( ReactConstants.TAG, "Unable to toggle the element inspector because the current activity could not be found." ) } val devSupportManager = currentActivity.devSupportManager ?: return run { FLog.e( ReactConstants.TAG, "Unable to get the DevSupportManager from current activity." ) } devSupportManager.callRecursive("toggleElementInspector") } private fun requestOverlayPermission(context: Context) { // From the unexposed DebugOverlayController static helper if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // Get permission to show debug overlay in dev builds. if (!Settings.canDrawOverlays(context)) { val intent = Intent( Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + context.packageName) ).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK } FLog.w( ReactConstants.TAG, "Overlay permissions needs to be granted in order for React Native apps to run in development mode" ) if (intent.resolveActivity(context.packageManager) != null) { context.startActivity(intent) } } } } private fun togglePerformanceMonitor() { val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run { FLog.e( ReactConstants.TAG, "Unable to toggle the performance monitor because the current activity could not be found." ) } val devSupportManager = currentActivity.devSupportManager ?: return run { FLog.e( ReactConstants.TAG, "Unable to get the DevSupportManager from current activity." ) } val devSettings = devSupportManager.callRecursive("getDevSettings") if (devSettings != null) { val isFpsDebugEnabled = devSettings.call("isFpsDebugEnabled") as Boolean if (!isFpsDebugEnabled) { // Request overlay permission if needed when "Show Perf Monitor" option is selected requestOverlayPermission(currentActivity) } devSettings.call("setFpsDebugEnabled", !isFpsDebugEnabled) } } private fun toggleRemoteJSDebugging() { val currentActivity = Exponent.instance.currentActivity as? ReactNativeActivity ?: return run { FLog.e( ReactConstants.TAG, "Unable to toggle remote JS debugging because the current activity could not be found." ) } val devSupportManager = currentActivity.devSupportManager ?: return run { FLog.e( ReactConstants.TAG, "Unable to get the DevSupportManager from current activity." ) } val devSettings = devSupportManager.callRecursive("getDevSettings") if (devSettings != null) { val isRemoteJSDebugEnabled = devSettings.call("isRemoteJSDebugEnabled") as Boolean devSettings.call("setRemoteJSDebugEnabled", !isRemoteJSDebugEnabled) } } private fun createPackagerCommandHelpers(): Map<String, RequestHandler> { // Attach listeners to the bundler's dev server web socket connection. // This enables tools to automatically reload the client remotely (i.e. in expo-cli). val packagerCommandHandlers = mutableMapOf<String, RequestHandler>() // Enable a lot of tools under the same command namespace packagerCommandHandlers["sendDevCommand"] = object : NotificationOnlyHandler() { override fun onNotification(params: Any?) { if (params != null && params is JSONObject) { when (params.getNullable<String>("name")) { "reload" -> reloadExpoApp() "toggleDevMenu" -> toggleExpoDevMenu() "toggleRemoteDebugging" -> { toggleRemoteJSDebugging() // Reload the app after toggling debugging, this is based on what we do in DevSupportManagerBase. reloadExpoApp() } "toggleElementInspector" -> toggleElementInspector() "togglePerformanceMonitor" -> togglePerformanceMonitor() } } } } // These commands (reload and devMenu) are here to match RN dev tooling. // Reload the app on "reload" packagerCommandHandlers["reload"] = object : NotificationOnlyHandler() { override fun onNotification(params: Any?) { reloadExpoApp() } } // Open the dev menu on "devMenu" packagerCommandHandlers["devMenu"] = object : NotificationOnlyHandler() { override fun onNotification(params: Any?) { toggleExpoDevMenu() } } return packagerCommandHandlers } @JvmStatic fun getReactInstanceManagerBuilder(instanceManagerBuilderProperties: InstanceManagerBuilderProperties): ReactInstanceManagerBuilder { // Build the instance manager var builder = ReactInstanceManager.builder() .setApplication(instanceManagerBuilderProperties.application) .setJSIModulesPackage { reactApplicationContext: ReactApplicationContext, jsContext: JavaScriptContextHolder? -> val devSupportManager = getDevSupportManager(reactApplicationContext) if (devSupportManager == null) { Log.e( "Exponent", "Couldn't get the `DevSupportManager`. JSI modules won't be initialized." ) return@setJSIModulesPackage emptyList() } val devSettings = devSupportManager.callRecursive("getDevSettings") val isRemoteJSDebugEnabled = devSettings != null && devSettings.call("isRemoteJSDebugEnabled") as Boolean if (!isRemoteJSDebugEnabled) { return@setJSIModulesPackage ReanimatedJSIModulePackage().getJSIModules( reactApplicationContext, jsContext ) } emptyList() } .addPackage(MainReactPackage()) .addPackage( ExponentPackage( instanceManagerBuilderProperties.experienceProperties, instanceManagerBuilderProperties.manifest, null, null, instanceManagerBuilderProperties.singletonModules ) ) .addPackage( ExpoTurboPackage( instanceManagerBuilderProperties.experienceProperties, instanceManagerBuilderProperties.manifest ) ) .setInitialLifecycleState(LifecycleState.BEFORE_CREATE) .setCustomPackagerCommandHandlers(createPackagerCommandHelpers()) .setJavaScriptExecutorFactory(createJSExecutorFactory(instanceManagerBuilderProperties)) if (instanceManagerBuilderProperties.jsBundlePath != null && instanceManagerBuilderProperties.jsBundlePath!!.isNotEmpty()) { builder = builder.setJSBundleFile(instanceManagerBuilderProperties.jsBundlePath) } return builder } private fun getDevSupportManager(reactApplicationContext: ReactApplicationContext): RNObject? { val currentActivity = Exponent.instance.currentActivity return if (currentActivity != null) { if (currentActivity is ReactNativeActivity) { currentActivity.devSupportManager } else { null } } else try { val devSettingsModule = reactApplicationContext.catalystInstance.getNativeModule("DevSettings") val devSupportManagerField = devSettingsModule!!.javaClass.getDeclaredField("mDevSupportManager") devSupportManagerField.isAccessible = true RNObject.wrap(devSupportManagerField[devSettingsModule]!!) } catch (e: Throwable) { e.printStackTrace() null } } private fun createJSExecutorFactory( instanceManagerBuilderProperties: InstanceManagerBuilderProperties ): JavaScriptExecutorFactory? { val appName = instanceManagerBuilderProperties.manifest.getName() ?: "" val deviceName = AndroidInfoHelpers.getFriendlyDeviceName() if (Constants.isStandaloneApp()) { return JSCExecutorFactory(appName, deviceName) } val hermesBundlePair = parseHermesBundleHeader(instanceManagerBuilderProperties.jsBundlePath) if (hermesBundlePair.first && hermesBundlePair.second != HERMES_BYTECODE_VERSION) { val message = String.format( Locale.US, "Unable to load unsupported Hermes bundle.\n\tsupportedBytecodeVersion: %d\n\ttargetBytecodeVersion: %d", HERMES_BYTECODE_VERSION, hermesBundlePair.second ) KernelProvider.instance.handleError(RuntimeException(message)) return null } val jsEngineFromManifest = instanceManagerBuilderProperties.manifest.getAndroidJsEngine() return if (jsEngineFromManifest == "hermes") HermesExecutorFactory() else JSCExecutorFactory( appName, deviceName ) } private fun parseHermesBundleHeader(jsBundlePath: String?): Pair<Boolean, Int> { if (jsBundlePath == null || jsBundlePath.isEmpty()) { return Pair(false, 0) } // https://github.com/facebook/hermes/blob/release-v0.5/include/hermes/BCGen/HBC/BytecodeFileFormat.h#L24-L25 val HERMES_MAGIC_HEADER = byteArrayOf( 0xc6.toByte(), 0x1f.toByte(), 0xbc.toByte(), 0x03.toByte(), 0xc1.toByte(), 0x03.toByte(), 0x19.toByte(), 0x1f.toByte() ) val file = File(jsBundlePath) try { FileInputStream(file).use { inputStream -> val bytes = ByteArray(12) inputStream.read(bytes, 0, bytes.size) // Magic header for (i in HERMES_MAGIC_HEADER.indices) { if (bytes[i] != HERMES_MAGIC_HEADER[i]) { return Pair(false, 0) } } // Bytecode version val bundleBytecodeVersion: Int = (bytes[11].toInt() shl 24) or (bytes[10].toInt() shl 16) or (bytes[9].toInt() shl 8) or bytes[8].toInt() return Pair(true, bundleBytecodeVersion) } } catch (e: FileNotFoundException) { } catch (e: IOException) { } return Pair(false, 0) } internal fun isHermesBundle(jsBundlePath: String?): Boolean { return parseHermesBundleHeader(jsBundlePath).first } internal fun getHermesBundleBytecodeVersion(jsBundlePath: String?): Int { return parseHermesBundleHeader(jsBundlePath).second } }
compose/material3/material3/samples/src/main/java/androidx/compose/material3/samples/MenuSamples.kt
3411954386
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material3.samples import androidx.annotation.Sampled import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.icons.outlined.Edit import androidx.compose.material.icons.outlined.Email import androidx.compose.material.icons.outlined.Settings import androidx.compose.material3.Divider import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview @Preview @Sampled @Composable fun MenuSample() { var expanded by remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) { IconButton(onClick = { expanded = true }) { Icon(Icons.Default.MoreVert, contentDescription = "Localized description") } DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false } ) { DropdownMenuItem( text = { Text("Edit") }, onClick = { /* Handle edit! */ }, leadingIcon = { Icon( Icons.Outlined.Edit, contentDescription = null ) }) DropdownMenuItem( text = { Text("Settings") }, onClick = { /* Handle settings! */ }, leadingIcon = { Icon( Icons.Outlined.Settings, contentDescription = null ) }) Divider() DropdownMenuItem( text = { Text("Send Feedback") }, onClick = { /* Handle send feedback! */ }, leadingIcon = { Icon( Icons.Outlined.Email, contentDescription = null ) }, trailingIcon = { Text("F11", textAlign = TextAlign.Center) }) } } }
src/main/kotlin/br/com/bumblebee/api/congressman/service/navigator/OpenDataLinkNavigator.kt
3162062670
package br.com.bumblebee.api.congressman.service.navigator import br.com.bumblebee.api.congressman.client.model.OpenDataResponse import java.net.URI interface OpenDataLinkNavigator<T> { fun navigate(uri: URI): OpenDataResponse<T> }
src/test/kotlin/com/aquivalabs/force/ant/BatchTestTestCase.kt
1867801233
package com.aquivalabs.force.ant import org.apache.tools.ant.Project import org.apache.tools.ant.types.ZipFileSet import org.hamcrest.MatcherAssert.* import org.hamcrest.Matchers.* import org.testng.Assert.assertEquals import org.testng.Assert.assertTrue import org.testng.annotations.DataProvider import org.testng.annotations.Test class BatchTestTestCase { @Test fun addFileSet_always_shouldFollowAntNamingConventions() { assertThat( nestedElementConvention("add"), BatchTest::addFileSet.name, startsWith("add")) } @Test fun addZipFileSet_always_shouldFollowAntNamingConventions() { assertThat( nestedElementConvention("add"), BatchTest::addZipFileSet.name, startsWith("add")) } @Test fun addFileSet_always_shouldFillProjectPropertyOfPassedValue() = withTestDirectory { val sut = createSystemUnderTest() val input = fileSet(it) sut.addFileSet(input) assertEquals(input.project, sut.project) } @Test fun addFileSet_always_shouldAddFileSetToResources() = withTestDirectory { val sut = createSystemUnderTest() val input = fileSet(it, "foo", "bar") sut.addFileSet(input) input.forEach { file -> assertTrue(sut.resources.contains(file)) } } @Test fun addZipFileSet_always_shouldFillProjectPropertyOfPassedValue() = withZipFile { zipFile -> val sut = createSystemUnderTest() val input = ZipFileSet().apply { src = zipFile } sut.addZipFileSet(input) assertEquals(input.project, sut.project) } @Test fun addZipFileSet_always_shouldAddFileSetToResources() { withZipFile(classes = setOf("foo", "bar")) { zipFile -> val sut = createSystemUnderTest() val input = ZipFileSet().apply { src = zipFile } sut.addZipFileSet(input) input.forEach { assertTrue(sut.resources.contains(it)) } } } @Test(dataProvider = "getFileNamesFileSetTestData") fun getFileNames_withFileSet_shouldReturnCorrectResult( namespace: String, inputFileNames: Set<String>, expected: Set<String>, message: String) = withTestDirectory { val sut = createSystemUnderTest() sut.namespace = namespace val fileSet = fileSet(it, inputFileNames) sut.addFileSet(fileSet) assertEquals(sut.getFileNames(), expected, message) } @DataProvider fun getFileNamesFileSetTestData(): Array<Array<Any>> { return arrayOf( arrayOf( "", setOf<String>(), setOf<String>(), "Should return empty list for empty fileSet"), arrayOf( "", setOf("foo.pdf", "bar.trigger", "baz$APEX_CLASS_FILE_EXTENSION"), setOf("baz"), "Should return only names (without extensions) of files that have $APEX_CLASS_FILE_EXTENSION extension"), arrayOf( "namespace", setOf("foo$APEX_CLASS_FILE_EXTENSION"), setOf("namespace${NAMESPACE_SEPARATOR}foo"), "Should add namespace to file names")) } @Test(dataProvider = "getFileNamesZipFileSetTestData") fun getFileNames_withZipFileSet_shouldReturnCorrectResult( namespace: String, classNames: Set<String>, triggerNames: Set<String>, expected: Set<String>, message: String) = withZipFile(classes = classNames, triggers = triggerNames) { zipFile -> val sut = createSystemUnderTest() sut.namespace = namespace val input = ZipFileSet().apply { src = zipFile } sut.addZipFileSet(input) assertEquals(sut.getFileNames(), expected, message) } @DataProvider fun getFileNamesZipFileSetTestData(): Array<Array<Any>> { return arrayOf( arrayOf( "", setOf<String>(), setOf<String>(), setOf<String>(), "Should return empty list for empty zipFileSet"), arrayOf( "", setOf<String>(), setOf("foo"), setOf<String>(), "Should ignore triggers from zipFileSet"), arrayOf( "", setOf("foo"), setOf("foo"), setOf("foo"), "Should ignore triggers from zipFileSet (same class and trigger name)"), arrayOf( "", setOf("foo", "bar", "baz"), setOf<String>(), setOf("foo", "bar", "baz"), "Should return only names (without extensions) of files that have $APEX_CLASS_FILE_EXTENSION extension"), arrayOf( "namespace", setOf("foo"), setOf<String>(), setOf("namespace${NAMESPACE_SEPARATOR}foo"), "Should add namespace to file names")) } private fun createSystemUnderTest(): BatchTest = BatchTest(Project().apply { name = "TestProject" }) }
android/app/src/main/java/nl/brouwerijdemolen/borefts2013/api/Poi.kt
471315196
package nl.brouwerijdemolen.borefts2013.api import com.google.android.gms.maps.model.LatLng class Poi( val id: String, val name_nl: String, val name_en: String, val marker: String, val point: Point) { val pointLatLng get() = LatLng(point.latitude.toDouble(), point.longitude.toDouble()) }
advanced/microservice/gateway/gateway-scg/src/main/kotlin/org/tsdes/advanced/microservice/gateway/scg/GatewayApplication.kt
927084644
package org.tsdes.advanced.microservice.gateway.scg import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication @SpringBootApplication class GatewayApplication { } fun main(args: Array<String>) { SpringApplication.run(GatewayApplication::class.java, *args) }
anko/library/static/commons/src/dialogs/Selectors.kt
3992643413
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("NOTHING_TO_INLINE", "unused") package org.jetbrains.anko import android.app.Fragment import android.content.Context import android.content.DialogInterface inline fun <D : DialogInterface> AnkoContext<*>.selector( noinline factory: AlertBuilderFactory<D>, title: CharSequence? = null, items: List<CharSequence>, noinline onClick: (DialogInterface, CharSequence, Int) -> Unit ): Unit = ctx.selector(factory, title, items, onClick) inline fun <D : DialogInterface> Fragment.selector( noinline factory: AlertBuilderFactory<D>, title: CharSequence? = null, items: List<CharSequence>, noinline onClick: (DialogInterface, CharSequence, Int) -> Unit ): Unit = activity.selector(factory, title, items, onClick) fun <D : DialogInterface> Context.selector( factory: AlertBuilderFactory<D>, title: CharSequence? = null, items: List<CharSequence>, onClick: (DialogInterface, CharSequence, Int) -> Unit ) { with(factory(this)) { if (title != null) { this.title = title } items(items, onClick) show() } }
core/testdata/format/inheritedLink.1.kt
3318993818
package p1 import java.util.LinkedList interface Foo { /** Says hello - [LinkedList]. */ fun sayHello() : String }
library/src/main/java/me/toptas/rssconverter/RssConverterFactory.kt
3472314620
package me.toptas.rssconverter import java.lang.reflect.Type import okhttp3.ResponseBody import retrofit2.Converter import retrofit2.Retrofit /** * A [converter][Converter.Factory] which uses [XMLParser] to parse RSS feeds. */ class RssConverterFactory /** * Constructor */ private constructor() : Converter.Factory() { override fun responseBodyConverter(type: Type?, annotations: Array<Annotation>?, retrofit: Retrofit?): Converter<ResponseBody, *> = RssResponseBodyConverter() companion object { /** * Creates an instance * * @return instance */ fun create(): RssConverterFactory { return RssConverterFactory() } } }
app/src/main/kotlin/taiwan/no1/app/ssfm/internal/di/modules/fragment/dependency/UseCaseModule.kt
3536035153
package taiwan.no1.app.ssfm.internal.di.modules.fragment.dependency import dagger.Module import dagger.Provides import taiwan.no1.app.ssfm.internal.di.annotations.scopes.PerFragment import taiwan.no1.app.ssfm.models.data.repositories.DataRepository import taiwan.no1.app.ssfm.models.usecases.AddPlaylistCase import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemUsecase import taiwan.no1.app.ssfm.models.usecases.AddPlaylistUsecase import taiwan.no1.app.ssfm.models.usecases.DeleteSearchHistoryCase import taiwan.no1.app.ssfm.models.usecases.EditPlaylistCase import taiwan.no1.app.ssfm.models.usecases.EditPlaylistUsecase import taiwan.no1.app.ssfm.models.usecases.EditRankChartCase import taiwan.no1.app.ssfm.models.usecases.EditRankChartUsecase import taiwan.no1.app.ssfm.models.usecases.FetchAlbumInfoCase import taiwan.no1.app.ssfm.models.usecases.FetchArtistInfoCase import taiwan.no1.app.ssfm.models.usecases.FetchHotPlaylistCase import taiwan.no1.app.ssfm.models.usecases.FetchMusicDetailCase import taiwan.no1.app.ssfm.models.usecases.FetchMusicRankCase import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistCase import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistDetailCase import taiwan.no1.app.ssfm.models.usecases.FetchPlaylistItemCase import taiwan.no1.app.ssfm.models.usecases.FetchRankChartCase import taiwan.no1.app.ssfm.models.usecases.FetchSearchHistoryCase import taiwan.no1.app.ssfm.models.usecases.FetchTagInfoCase import taiwan.no1.app.ssfm.models.usecases.FetchTopAlbumOfArtistCase import taiwan.no1.app.ssfm.models.usecases.FetchTopAlbumOfTagCase import taiwan.no1.app.ssfm.models.usecases.FetchTopArtistCase import taiwan.no1.app.ssfm.models.usecases.FetchTopArtistOfTagCase import taiwan.no1.app.ssfm.models.usecases.FetchTopTagCase import taiwan.no1.app.ssfm.models.usecases.FetchTopTrackCase import taiwan.no1.app.ssfm.models.usecases.FetchTopTrackOfArtistCase import taiwan.no1.app.ssfm.models.usecases.FetchTopTrackOfTagCase import taiwan.no1.app.ssfm.models.usecases.GetAlbumInfoUsecase import taiwan.no1.app.ssfm.models.usecases.GetArtistInfoUsecase import taiwan.no1.app.ssfm.models.usecases.GetArtistTopAlbumsUsecase import taiwan.no1.app.ssfm.models.usecases.GetArtistTopTracksUsecase import taiwan.no1.app.ssfm.models.usecases.GetDetailMusicUsecase import taiwan.no1.app.ssfm.models.usecases.GetKeywordHistoriesUsecase import taiwan.no1.app.ssfm.models.usecases.GetPlaylistItemsUsecase import taiwan.no1.app.ssfm.models.usecases.GetPlaylistsUsecase import taiwan.no1.app.ssfm.models.usecases.GetTagInfoUsecase import taiwan.no1.app.ssfm.models.usecases.GetTagTopAlbumsUsecase import taiwan.no1.app.ssfm.models.usecases.GetTagTopArtistsUsecase import taiwan.no1.app.ssfm.models.usecases.GetTagTopTracksUsecase import taiwan.no1.app.ssfm.models.usecases.GetTopArtistsUsecase import taiwan.no1.app.ssfm.models.usecases.GetTopChartsUsecase import taiwan.no1.app.ssfm.models.usecases.GetTopTagsUsecase import taiwan.no1.app.ssfm.models.usecases.GetTopTracksUsecase import taiwan.no1.app.ssfm.models.usecases.RemoveKeywordHistoriesUsecase import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistCase import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistItemCase import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistItemUsecase import taiwan.no1.app.ssfm.models.usecases.RemovePlaylistUsecase import taiwan.no1.app.ssfm.models.usecases.SearchMusicUsecase import taiwan.no1.app.ssfm.models.usecases.SearchMusicV1Case import taiwan.no1.app.ssfm.models.usecases.SearchMusicV2Case import taiwan.no1.app.ssfm.models.usecases.v2.GetHotPlaylistUsecase import taiwan.no1.app.ssfm.models.usecases.v2.GetMusicRankUsecase import taiwan.no1.app.ssfm.models.usecases.v2.GetSongListUsecase import javax.inject.Named /** * @author jieyi * @since 10/21/17 */ @Module class UseCaseModule { //region Chart top @Provides @PerFragment fun provideTopArtistsUsecase(dataRepository: DataRepository): FetchTopArtistCase = GetTopArtistsUsecase(dataRepository) @Provides @PerFragment fun provideTopTracksUsecase(dataRepository: DataRepository): FetchTopTrackCase = GetTopTracksUsecase(dataRepository) @Provides @PerFragment fun provideTopTagsUsecase(dataRepository: DataRepository): FetchTopTagCase = GetTopTagsUsecase(dataRepository) @Provides @PerFragment fun provideRankChartUsecase(dataRepository: DataRepository): FetchRankChartCase = GetTopChartsUsecase(dataRepository) @Provides @PerFragment fun provideEditRankChartUsecase(dataRepository: DataRepository): EditRankChartCase = EditRankChartUsecase( dataRepository) //endregion //region Artist @Provides @PerFragment fun provideArtistInfoUsecase(dataRepository: DataRepository): FetchArtistInfoCase = GetArtistInfoUsecase(dataRepository) @Provides @PerFragment fun provideArtistTopAlbumUsecase(dataRepository: DataRepository): FetchTopAlbumOfArtistCase = GetArtistTopAlbumsUsecase(dataRepository) @Provides @PerFragment fun provideArtistTopTrackUsecase(dataRepository: DataRepository): FetchTopTrackOfArtistCase = GetArtistTopTracksUsecase(dataRepository) //endregion //region Album @Provides @PerFragment fun provideAlbumInfoUsecase(dataRepository: DataRepository): FetchAlbumInfoCase = GetAlbumInfoUsecase(dataRepository) //endregion //region Tag @Provides @PerFragment fun provideTagInfoUsecase(dataRepository: DataRepository): FetchTagInfoCase = GetTagInfoUsecase(dataRepository) @Provides @PerFragment fun provideTagTopAlbumUsecase(dataRepository: DataRepository): FetchTopAlbumOfTagCase = GetTagTopAlbumsUsecase(dataRepository) @Provides @PerFragment fun provideTagTopArtistUsecase(dataRepository: DataRepository): FetchTopArtistOfTagCase = GetTagTopArtistsUsecase(dataRepository) @Provides @PerFragment fun provideTagTopTrackUsecase(dataRepository: DataRepository): FetchTopTrackOfTagCase = GetTagTopTracksUsecase(dataRepository) //endregion //region Search music V1 @Provides @PerFragment fun provideGetKeywordHistoryUsecase(dataRepository: DataRepository): FetchSearchHistoryCase = GetKeywordHistoriesUsecase(dataRepository) @Provides @PerFragment fun provideSearchMusicUsecase(dataRepository: DataRepository): SearchMusicV1Case = SearchMusicUsecase(dataRepository) @Provides @PerFragment fun provideGetDetailMusicUsecase(dataRepository: DataRepository): FetchMusicDetailCase = GetDetailMusicUsecase(dataRepository) // endregion //region Search music V2 @Provides @PerFragment fun provideSearchMusicV2Usecase(dataRepository: DataRepository): SearchMusicV2Case = taiwan.no1.app.ssfm.models.usecases.v2.SearchMusicUsecase(dataRepository) @Provides @PerFragment fun provideMusicRankUsecase(dataRepository: DataRepository): FetchMusicRankCase = GetMusicRankUsecase(dataRepository) @Provides @PerFragment fun provideHotPlaylistUsecase(dataRepository: DataRepository): FetchHotPlaylistCase = GetHotPlaylistUsecase(dataRepository) @Provides @PerFragment fun provideHotPlaylistDetailUsecase(dataRepository: DataRepository): FetchPlaylistDetailCase = GetSongListUsecase(dataRepository) //endregion //region For Database @Provides @PerFragment fun provideDeleteUsecase(dataRepository: DataRepository): DeleteSearchHistoryCase = RemoveKeywordHistoriesUsecase(dataRepository) @Provides @PerFragment @Named("add_playlist_item") fun provideAddPlaylistItemUsecase(dataRepository: DataRepository): AddPlaylistItemCase = AddPlaylistItemUsecase(dataRepository) @Provides @PerFragment fun provideAddPlaylistUsecase(dataRepository: DataRepository): AddPlaylistCase = AddPlaylistUsecase(dataRepository) @Provides @PerFragment fun provideGetPlaylistsUsecase(dataRepository: DataRepository): FetchPlaylistCase = GetPlaylistsUsecase(dataRepository) @Provides @PerFragment fun provideGetPlaylistItemsUsecase(dataRepository: DataRepository): FetchPlaylistItemCase = GetPlaylistItemsUsecase(dataRepository) @Provides @PerFragment @Named("remove_playlist") fun provideRemovePlaylistUsecase(dataRepository: DataRepository): RemovePlaylistCase = RemovePlaylistUsecase(dataRepository) @Provides @PerFragment @Named("remove_playlist_item") fun provideRemovePlaylistItemUsecase(dataRepository: DataRepository): RemovePlaylistItemCase = RemovePlaylistItemUsecase(dataRepository) @Provides @PerFragment @Named("edit_playlist") fun provideEditPlaylistUsecase(dataRepository: DataRepository): EditPlaylistCase = EditPlaylistUsecase(dataRepository) //endregion }
credentials/credentials/src/androidTest/java/androidx/credentials/exceptions/ClearCredentialExceptionTest.kt
2887897044
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.credentials.exceptions import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SmallTest import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) @SmallTest class ClearCredentialExceptionTest { @Test(expected = ClearCredentialException::class) fun construct_inputsNonEmpty_success() { throw ClearCredentialException("type", "msg") } @Test(expected = ClearCredentialException::class) fun construct_errorMessageNull_success() { throw ClearCredentialException("type", null) } @Test(expected = IllegalArgumentException::class) fun construct_typeEmpty_throws() { throw ClearCredentialException("", "msg") } }
room/room-compiler/src/test/kotlin/androidx/room/writer/DatabaseKotlinCodeGenTest.kt
1122938780
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.DatabaseProcessingStep import androidx.room.compiler.processing.util.Source import androidx.room.compiler.processing.util.XTestInvocation import androidx.room.compiler.processing.util.runKspTest import androidx.room.processor.Context import loadTestSource import org.junit.Test class DatabaseKotlinCodeGenTest { @Test fun database_simple() { val testName = object {}.javaClass.enclosingMethod!!.name val src = Source.kotlin( "MyDatabase.kt", """ import androidx.room.* @Database(entities = [MyEntity::class], version = 1, exportSchema = false) abstract class MyDatabase : RoomDatabase() { abstract fun getDao(): MyDao } @Dao interface MyDao { @Query("SELECT * FROM MyEntity") fun getEntity(): MyEntity } @Entity data class MyEntity( @PrimaryKey var pk: Int ) """.trimIndent() ) runTest( sources = listOf(src), expectedFilePath = getTestGoldenPath(testName) ) } @Test fun database_propertyDao() { val testName = object {}.javaClass.enclosingMethod!!.name val src = Source.kotlin( "MyDatabase.kt", """ import androidx.room.* @Database(entities = [MyEntity::class], version = 1, exportSchema = false) abstract class MyDatabase : RoomDatabase() { abstract val dao: MyDao } @Dao interface MyDao { @Query("SELECT * FROM MyEntity") fun getEntity(): MyEntity } @Entity data class MyEntity( @PrimaryKey var pk: Int ) """.trimIndent() ) runTest( sources = listOf(src), expectedFilePath = getTestGoldenPath(testName) ) } @Test fun database_withFtsAndView() { val testName = object {}.javaClass.enclosingMethod!!.name val src = Source.kotlin( "MyDatabase.kt", """ import androidx.room.* @Database( entities = [ MyParentEntity::class, MyEntity::class, MyFtsEntity::class, ], views = [ MyView::class ], version = 1, exportSchema = false ) abstract class MyDatabase : RoomDatabase() { abstract val dao: MyDao } @Dao interface MyDao { @Query("SELECT * FROM MyEntity") fun getEntity(): MyEntity } @Entity data class MyParentEntity(@PrimaryKey val parentKey: Long) @Entity( foreignKeys = [ ForeignKey( entity = MyParentEntity::class, parentColumns = ["parentKey"], childColumns = ["indexedCol"], onDelete = ForeignKey.CASCADE ) ], indices = [Index("indexedCol")] ) data class MyEntity( @PrimaryKey val pk: Int, val indexedCol: String ) @Fts4 @Entity data class MyFtsEntity( @PrimaryKey @ColumnInfo(name = "rowid") val pk: Int, val text: String ) @DatabaseView("SELECT text FROM MyFtsEntity") data class MyView(val text: String) """.trimIndent() ) runTest( sources = listOf(src), expectedFilePath = getTestGoldenPath(testName) ) } private fun getTestGoldenPath(testName: String): String { return "kotlinCodeGen/$testName.kt" } private fun runTest( sources: List<Source>, expectedFilePath: String, handler: (XTestInvocation) -> Unit = { } ) { runKspTest( sources = sources, options = mapOf(Context.BooleanProcessorOptions.GENERATE_KOTLIN.argName to "true"), ) { val databaseFqn = "androidx.room.Database" DatabaseProcessingStep().process( it.processingEnv, mapOf(databaseFqn to it.roundEnv.getElementsAnnotatedWith(databaseFqn)), it.roundEnv.isProcessingOver ) it.assertCompilationResult { this.generatedSource( loadTestSource( expectedFilePath, "MyDatabase_Impl" ) ) this.hasNoWarnings() } handler.invoke(it) } } }
obevo-core/src/main/java/com/gs/obevo/impl/DeployStrategy.kt
2681924785
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.impl import com.gs.obevo.api.platform.CommandExecutionContext /** * Strategy interface for controlling how change deployments should get done, notably around whether certain differences * are allowed or whether to execute them. */ interface DeployStrategy { val deployVerbMessage: String fun deploy(changeTypeBehaviorRegistry: ChangeTypeBehaviorRegistry, changeCommand: ExecuteChangeCommand, cec: CommandExecutionContext) val isInitAllowedOnHashExceptions: Boolean }
kotlin-eclipse-ui-test/testData/completion/basic/common/InParametersTypesForce.kt
1749664917
class SomeClass { class SomeInternal fun some(a : S<caret>) } // INVOCATION_COUNT: 2 // EXIST: SomeClass // EXIST: SomeInternal // EXIST: String // EXIST: StringBuilder // EXIST_JAVA_ONLY: StringBuffer // EXIST_JS_ONLY: HTMLStyleElement // EXIST_JAVA_ONLY: { lookupString:"Statement", tailText:" (java.sql)" } // TODO: json { lookupString:"String", tailText:" (jet)" }
lib/src/main/java/uk/co/glass_software/android/shared_preferences/persistence/preferences/StoreModule.kt
3268192925
/* * Copyright (C) 2017 Glass Software Ltd * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF 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 uk.co.glass_software.android.shared_preferences.persistence.preferences import android.content.Context import dagger.Module import dagger.Provides import io.reactivex.subjects.PublishSubject import uk.co.glass_software.android.boilerplate.core.utils.delegates.Prefs import uk.co.glass_software.android.boilerplate.core.utils.log.Logger import uk.co.glass_software.android.shared_preferences.persistence.base.KeyValueStore import uk.co.glass_software.android.shared_preferences.persistence.serialisation.SerialisationModule import uk.co.glass_software.android.shared_preferences.persistence.serialisation.SerialisationModule.Companion.BASE_64 import uk.co.glass_software.android.shared_preferences.persistence.serialisation.SerialisationModule.Companion.CUSTOM import uk.co.glass_software.android.shared_preferences.persistence.serialisation.Serialiser import javax.inject.Named import javax.inject.Singleton @Module(includes = [SerialisationModule::class]) internal class StoreModule(private val context: Context, private val prefs: Prefs, private val logger: Logger, private val isMemoryCacheEnabled: Boolean) { @Provides @Singleton fun provideContext() = context @Provides @Singleton fun provideSharedPreferenceStore(@Named(BASE_64) base64Serialiser: Serialiser, @Named(CUSTOM) customSerialiser: Serialiser?, logger: Logger): SharedPreferenceStore = SharedPreferenceStore( prefs, base64Serialiser, customSerialiser, PublishSubject.create(), logger, isMemoryCacheEnabled ) @Provides @Singleton fun provideStore(store: SharedPreferenceStore): KeyValueStore = store @Provides @Singleton fun provideLogger() = logger companion object { internal const val MAX_FILE_NAME_LENGTH = 127 } }
trustagent/src/com/google/android/libraries/car/trustagent/util/TimeProvider.kt
3643151611
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.trustagent.util import java.time.OffsetDateTime import java.time.format.DateTimeFormatter /** A time provider that will provide current time stamp in the ISO 8601 format. */ object TimeProvider { fun createCurrentTimeStamp() = DateTimeFormatter.ISO_DATE_TIME.format(OffsetDateTime.now()) }
core/src/main/kotlin/cyberpunk/core/state/State.kt
159518155
package cyberpunk.core.state import com.badlogic.gdx.InputProcessor import com.badlogic.gdx.graphics.g2d.Batch import com.badlogic.gdx.math.Vector2 interface State : InputProcessor { /** * Updates the state. * This is called every frame. * @param delta time elapsed since the last call to this method. */ fun update(delta: Float) /** * Renders the state. * This is also called every frame, always after [State.update]. * @param batch [Batch] used to render the state. */ fun render(batch: Batch) /** * Pauses the state. */ fun pause() /** * Resumes the state, after it being paused. */ fun resume() /** * Hides the state. */ fun hide() /** * Disposes the state and all of the state's [com.badlogic.gdx.utils.Disposable] components. */ fun dispose() /** * Resizes the state and any of its components. * @param width new width. * @param height new height. */ fun resize(width: Int, height: Int) /** * Unprojects screen coordinates into world coordinates. * @param screenX X in screen coordinates. * @param screenY Y in screen coordinates. * @return world coordinates. */ fun unproject(screenX: Float, screenY: Float): Vector2 /** * Unprojects screen coordinates into world coordinates. * @param screenCoordinates (X, Y) screen coordinates. * @return world coordinates. */ fun unproject(screenCoordinates: Vector2): Vector2 }
gto-support-material-components/src/main/kotlin/org/ccci/gto/android/common/material/bottomsheet/BindingBottomSheetDialogFragment.kt
979633934
package org.ccci.gto.android.common.material.bottomsheet import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.annotation.LayoutRes import androidx.databinding.DataBindingUtil import androidx.databinding.ViewDataBinding import androidx.viewbinding.ViewBinding import com.google.android.material.bottomsheet.BottomSheetDialogFragment import org.ccci.gto.android.common.base.Constants.INVALID_LAYOUT_RES abstract class BindingBottomSheetDialogFragment<B : ViewBinding>( @LayoutRes private val contentLayoutId: Int ) : BottomSheetDialogFragment() { constructor() : this(INVALID_LAYOUT_RES) private var binding: B? = null // region Lifecycle final override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = onCreateBinding(inflater, container, savedInstanceState)?.also { if (it is ViewDataBinding && it.lifecycleOwner == null) it.lifecycleOwner = viewLifecycleOwner } return binding?.root ?: super.onCreateView(inflater, container, savedInstanceState) } @Suppress("UNCHECKED_CAST") protected open fun onCreateBinding( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): B? { if (contentLayoutId != INVALID_LAYOUT_RES) return DataBindingUtil.inflate<ViewDataBinding>(inflater, contentLayoutId, container, false) as? B return null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding?.let { onBindingCreated(it, savedInstanceState) } } open fun onBindingCreated(binding: B, savedInstanceState: Bundle?) = Unit override fun onDestroyView() { binding?.let { onDestroyBinding(it) } binding = null super.onDestroyView() } open fun onDestroyBinding(binding: B) = Unit // endregion Lifecycle }
mycollab-web/src/main/java/com/mycollab/vaadin/ui/formatter/CurrencyHistoryFieldFormat.kt
1187070013
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.vaadin.ui.formatter import com.hp.gagawa.java.elements.Span import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.core.utils.CurrencyUtils import com.mycollab.core.utils.StringUtils import com.mycollab.module.user.domain.SimpleUser import com.mycollab.vaadin.UserUIContext /** * @author MyCollab Ltd * @since 5.3.4 */ class CurrencyHistoryFieldFormat : HistoryFieldFormat { override fun toString(value: String): String = toString(UserUIContext.getUser(), value, true, UserUIContext.getMessage(GenericI18Enum.FORM_EMPTY)) override fun toString(currentViewUser: SimpleUser, value: String, displayAsHtml: Boolean, msgIfBlank: String): String = when { StringUtils.isNotBlank(value) -> { val currency = CurrencyUtils.getInstance(value) if (displayAsHtml) { Span().appendText(value).setTitle(currency.getDisplayName(currentViewUser.locale)).write() } else { value } } else -> msgIfBlank } }
mycollab-dao/src/main/java/com/mycollab/db/arguments/SetSearchField.kt
832296066
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.mycollab.db.arguments import com.mycollab.core.IgnoreException import com.mycollab.core.utils.ArrayUtils import org.apache.commons.collections.CollectionUtils /** * @param <T> * @author MyCollab Ltd. * @since 1.0 </T> */ class SetSearchField<T> : SearchField { private var values: MutableSet<T> = mutableSetOf() constructor() constructor(vararg vals: T) { if (ArrayUtils.isNotEmpty(vals)) { CollectionUtils.addAll(values, vals) } this.operation = SearchField.AND } constructor(oper: String, vals: Collection<T>) : super(oper) { values.addAll(vals) } constructor(items: Collection<T>) { if (CollectionUtils.isNotEmpty(items)) { values.addAll(items) } this.operation = SearchField.AND } fun getValues(): Set<T> { if (values.isEmpty()) { throw IgnoreException("You must select one option") } return values } fun setValues(values: MutableSet<T>) { this.values = values } fun addValue(value: T) { values.add(value) } fun removeValue(value: T) { values.remove(value) } }
app/src/main/kotlin/ru/fantlab/android/ui/adapter/EditionsAdapter.kt
1142024172
package ru.fantlab.android.ui.adapter import android.view.ViewGroup import ru.fantlab.android.data.dao.model.EditionsBlocks import ru.fantlab.android.ui.adapter.viewholder.EditionsViewHolder import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder import java.util.* class EditionsAdapter constructor(edition: ArrayList<EditionsBlocks.Edition>) : BaseRecyclerAdapter<EditionsBlocks.Edition, EditionsViewHolder>(edition) { override fun viewHolder(parent: ViewGroup, viewType: Int): EditionsViewHolder = EditionsViewHolder.newInstance(parent, this) override fun onBindView(holder: EditionsViewHolder, position: Int) { holder.bind(getItem(position)) } }
reagent/jdk/src/main/kotlin/reagent/source/TaskCreator.kt
3329789172
package reagent.source import reagent.Task interface TaskCreator<out I> { fun subscribe(downstream: Downstream<I>) interface Downstream<in I> : Task.Observer<I> { val isDisposed: Boolean } }
app/src/main/java/com/stfalcon/new_uaroads_android/common/analytics/AnalyticsManager.kt
2557732901
/* * Copyright (c) 2017 stfalcon.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under 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.stfalcon.new_uaroads_android.common.analytics /* * Created by Anton Bevza on 5/13/17. */ interface AnalyticsManager { fun sendScreen(screenName: String) fun sendSearchAction(from: String, to: String) fun sendNavigationAction() fun sendStartManualRecord() fun sendStopManualRecord() fun sendPauseManualRecord() fun sendStartAutoRecord() fun sendStopAutoRecord() fun sendSettingPitSound(checked: Boolean) fun sendSettingAutoStartSound(checked: Boolean) fun sendSettingSendingOnlyWIfi(checked: Boolean) fun sendSettingAutoSending(checked: Boolean) fun sendSettingAutoRecord(checked: Boolean) fun sendTrackManualSent() fun sendTrackAutoSent() }
app/src/main/kotlin/com/hpedrorodrigues/gzmd/activity/view/BaseView.kt
2160165550
/* * Copyright 2016 Pedro Rodrigues * * 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.hpedrorodrigues.gzmd.activity.view import rx.Subscription interface BaseView { fun bindSubscription(subscription: Subscription) }
api/src/main/java/com/vk/sdk/api/groups/dto/GroupsContactsItem.kt
3769475813
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.groups.dto import com.google.gson.annotations.SerializedName import com.vk.dto.common.id.UserId import kotlin.String /** * @param userId - User ID * @param desc - Contact description * @param phone - Contact phone * @param email - Contact email */ data class GroupsContactsItem( @SerializedName("user_id") val userId: UserId? = null, @SerializedName("desc") val desc: String? = null, @SerializedName("phone") val phone: String? = null, @SerializedName("email") val email: String? = null )
build-plugin/common-dependencies/src/org/jetbrains/kotlinx/jupyter/common/httpUtil.kt
2780530869
package org.jetbrains.kotlinx.jupyter.common import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import org.http4k.asString import org.http4k.client.ApacheClient import org.http4k.client.PreCannedApacheHttpClients import org.http4k.core.Method import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.then import org.http4k.filter.ClientFilters import java.io.IOException import java.util.Base64 class ResponseWrapper( response: Response, val url: String, ) : Response by response fun httpRequest(request: Request): ResponseWrapper { PreCannedApacheHttpClients.defaultApacheHttpClient().use { closeableHttpClient -> val apacheClient = ApacheClient(client = closeableHttpClient) val client = ClientFilters.FollowRedirects().then(apacheClient) val response = client(request) return ResponseWrapper(response, request.uri.toString()) } } fun getHttp(url: String) = httpRequest(Request(Method.GET, url)) fun Request.withBasicAuth(username: String, password: String): Request { val b64 = Base64.getEncoder().encode("$username:$password".toByteArray()).toString(Charsets.UTF_8) return this.header("Authorization", "Basic $b64") } fun Request.withJson(json: JsonElement): Request { return this .body(Json.encodeToString(json)) .header("Content-Type", "application/json") } val Response.text: String get() { return body.payload.asString() } fun ResponseWrapper.assertSuccessful() { if (!status.successful) { throw IOException("Http request failed. Url = $url. Response = $text") } } inline fun <reified T> ResponseWrapper.decodeJson(): T { assertSuccessful() return Json.decodeFromString(text) } val ResponseWrapper.json: JsonElement get() = decodeJson() val ResponseWrapper.jsonObject: JsonObject get() = decodeJson() val ResponseWrapper.jsonArray: JsonArray get() = decodeJson() inline fun <reified T> ResponseWrapper.decodeJsonIfSuccessfulOrNull(): T? { return if (!status.successful) null else Json.decodeFromString(text) } val ResponseWrapper.jsonOrNull: JsonElement? get() = decodeJsonIfSuccessfulOrNull() val ResponseWrapper.jsonObjectOrNull: JsonObject? get() = decodeJsonIfSuccessfulOrNull() val ResponseWrapper.jsonArrayOrNull: JsonArray? get() = decodeJsonIfSuccessfulOrNull()
zpa-checks/src/main/kotlin/org/sonar/plsqlopen/checks/CheckList.kt
585015553
/** * Z PL/SQL Analyzer * Copyright (C) 2015-2022 Felipe Zorzo * mailto:felipe AT felipezorzo DOT com DOT br * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.plsqlopen.checks object CheckList { const val SONAR_WAY_PROFILE = "Sonar way" val checks: List<Class<*>> get() = listOf( EmptyBlockCheck::class.java, ParsingErrorCheck::class.java, CollapsibleIfStatementsCheck::class.java, InequalityUsageCheck::class.java, ComparisonWithNullCheck::class.java, TooManyRowsHandlerCheck::class.java, InsertWithoutColumnsCheck::class.java, DeclareSectionWithoutDeclarationsCheck::class.java, NvlWithNullParameterCheck::class.java, ComparisonWithBooleanCheck::class.java, CharacterDatatypeUsageCheck::class.java, SelectAllColumnsCheck::class.java, ColumnsShouldHaveTableNameCheck::class.java, SelectWithRownumAndOrderByCheck::class.java, ToDateWithoutFormatCheck::class.java, ExplicitInParameterCheck::class.java, VariableInitializationWithNullCheck::class.java, UselessParenthesisCheck::class.java, IdenticalExpressionCheck::class.java, EmptyStringAssignmentCheck::class.java, DuplicatedValueInInCheck::class.java, VariableInitializationWithFunctionCallCheck::class.java, IfWithExitCheck::class.java, FunctionWithOutParameterCheck::class.java, SameConditionCheck::class.java, AddParenthesesInNestedExpressionCheck::class.java, RaiseStandardExceptionCheck::class.java, NotFoundCheck::class.java, QueryWithoutExceptionHandlingCheck::class.java, UnusedVariableCheck::class.java, VariableHidingCheck::class.java, DbmsOutputPutCheck::class.java, ReturnOfBooleanExpressionCheck::class.java, UnnecessaryElseCheck::class.java, DeadCodeCheck::class.java, ConcatenationWithNullCheck::class.java, SameBranchCheck::class.java, UnusedParameterCheck::class.java, CommitRollbackCheck::class.java, UnnecessaryNullStatementCheck::class.java, DuplicateConditionIfElsifCheck::class.java, UnnecessaryAliasInQueryCheck::class.java, VariableInCountCheck::class.java, UnhandledUserDefinedExceptionCheck::class.java, UnusedCursorCheck::class.java, NotASelectedExpressionCheck::class.java, InvalidReferenceToObjectCheck::class.java, CursorBodyInPackageSpecCheck::class.java, XPathCheck::class.java, VariableNameCheck::class.java, ToCharInOrderByCheck::class.java, DisabledTestCheck::class.java, RedundantExpectationCheck::class.java, UnnecessaryLikeCheck::class.java) }
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/tasks/form/ReminderItemFormView.kt
2991693170
package com.habitrpg.android.habitica.ui.views.tasks.form import android.app.DatePickerDialog import android.app.TimePickerDialog import android.content.Context import android.util.AttributeSet import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.LinearInterpolator import android.view.animation.RotateAnimation import android.widget.DatePicker import android.widget.LinearLayout import android.widget.TimePicker import androidx.core.content.ContextCompat import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.TaskFormReminderItemBinding import com.habitrpg.android.habitica.models.tasks.RemindersItem import com.habitrpg.common.habitica.extensions.dpToPx import com.habitrpg.common.habitica.extensions.getThemeColor import com.habitrpg.common.habitica.extensions.layoutInflater import com.habitrpg.shared.habitica.models.tasks.TaskType import java.text.DateFormat import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.Date import java.util.Locale class ReminderItemFormView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : LinearLayout(context, attrs, defStyleAttr), TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener { private val formattedTime: CharSequence? get() { return if (item.time != null) { val time = Date.from(item.getLocalZonedDateTimeInstant()) formatter.format(time) } else { "" } } private val binding = TaskFormReminderItemBinding.inflate(context.layoutInflater, this) private val formatter: DateFormat get() { return if (taskType == TaskType.DAILY) { DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault()) } else { DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault()) } } var taskType = TaskType.DAILY var item: RemindersItem = RemindersItem() set(value) { field = value binding.textView.text = formattedTime } var firstDayOfWeek: Int? = null var tintColor: Int = context.getThemeColor(R.attr.taskFormTint) var valueChangedListener: ((Date) -> Unit)? = null var animDuration = 0L var isAddButton: Boolean = true set(value) { field = value binding.textView.text = if (value) context.getString(R.string.new_reminder) else formattedTime if (value) { val rotate = RotateAnimation(135f, 0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) rotate.duration = animDuration rotate.interpolator = LinearInterpolator() rotate.fillAfter = true binding.button.startAnimation(rotate) // This button is not clickable in this state, so make screen readers skip it. binding.button.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO } else { val rotate = RotateAnimation(0f, 135f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f) rotate.duration = animDuration rotate.interpolator = LinearInterpolator() rotate.fillAfter = true binding.button.startAnimation(rotate) // This button IS now clickable, so allow screen readers to focus it. binding.button.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES } } init { minimumHeight = 38.dpToPx(context) background = ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_task_form) background.mutate().setTint(ContextCompat.getColor(context, R.color.taskform_gray)) gravity = Gravity.CENTER_VERTICAL binding.button.setOnClickListener { if (!isAddButton) { (parent as? ViewGroup)?.removeView(this) } } // It's ok to make the description always be 'Delete Reminder' because when this button is // a plus button we set it as 'unimportant for accessibility' so it can't be focused. binding.button.contentDescription = context.getString(R.string.delete_reminder) binding.button.drawable.mutate().setTint(tintColor) binding.textView.setOnClickListener { if (taskType == TaskType.DAILY) { val timePickerDialog = TimePickerDialog( context, this, item.getZonedDateTime()?.hour ?: ZonedDateTime.now().hour, item.getZonedDateTime()?.minute ?: ZonedDateTime.now().minute, android.text.format.DateFormat.is24HourFormat(context) ) timePickerDialog.show() } else { val zonedDateTime = (item.getZonedDateTime() ?: ZonedDateTime.now()) val timePickerDialog = DatePickerDialog( context, this, zonedDateTime.year, zonedDateTime.monthValue - 1, zonedDateTime.dayOfMonth ) if ((firstDayOfWeek ?: -1) >= 0) { timePickerDialog.datePicker.firstDayOfWeek = firstDayOfWeek ?: 0 } timePickerDialog.show() } } binding.textView.labelFor = binding.button.id } override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) { valueChangedListener?.let { val zonedDateTime = (item.getZonedDateTime() ?: ZonedDateTime.now()) .withHour(hourOfDay) .withMinute(minute) item.time = zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) binding.textView.text = formattedTime it(Date.from(item.getLocalZonedDateTimeInstant())) } } override fun onDateSet(view: DatePicker?, year: Int, month: Int, dayOfMonth: Int) { valueChangedListener?.let { val zonedDateTime = ZonedDateTime.now() .withYear(year) .withMonth(month + 1) .withDayOfMonth(dayOfMonth) item.time = zonedDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) binding.textView.text = formattedTime it(Date.from(item.getLocalZonedDateTimeInstant())) val timePickerDialog = TimePickerDialog( context, this, ZonedDateTime.now().hour, ZonedDateTime.now().minute, android.text.format.DateFormat.is24HourFormat(context) ) timePickerDialog.show() } } }
app/src/main/java/com/themovielist/enums/RequestStatusDescriptor.kt
2251845359
package com.themovielist.enums import android.support.annotation.IntDef object RequestStatusDescriptor { @Retention(AnnotationRetention.SOURCE) @IntDef(LOADING, ERROR, EMPTY, HIDDEN) annotation class RequestStatus const val LOADING = 0 const val ERROR = 1 const val EMPTY = 2 const val HIDDEN = 3 }
Habitica/src/androidTest/java/com/habitrpg/android/habitica/ui/activities/TaskFormActivityTest.kt
2217548164
package com.habitrpg.android.habitica.ui.activities import android.content.Intent import android.os.Bundle import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import androidx.test.core.app.launchActivity import androidx.test.espresso.assertion.ViewAssertions import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.components.UserComponent import com.habitrpg.shared.habitica.models.tasks.Frequency import com.habitrpg.android.habitica.models.tasks.Task import com.habitrpg.shared.habitica.models.tasks.TaskType import io.github.kakaocup.kakao.common.assertions.BaseAssertions import io.github.kakaocup.kakao.common.matchers.ChildCountMatcher import io.github.kakaocup.kakao.common.views.KView import io.github.kakaocup.kakao.edit.KEditText import io.github.kakaocup.kakao.picker.date.KDatePickerDialog import io.github.kakaocup.kakao.screen.Screen import io.github.kakaocup.kakao.spinner.KSpinner import io.github.kakaocup.kakao.spinner.KSpinnerItem import io.github.kakaocup.kakao.text.KButton import io.github.kakaocup.kakao.toolbar.KToolbar import io.mockk.every import io.mockk.justRun import io.mockk.mockk import io.mockk.mockkObject import io.mockk.slot import io.mockk.verify import io.reactivex.rxjava3.core.Flowable import java.util.Date import java.util.UUID import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith class TaskFormScreen : Screen<TaskFormScreen>() { val toolbar = KToolbar { withId(R.id.toolbar) } val textEditText = KEditText { withId(R.id.text_edit_text) } val notesEditText = KEditText { withId(R.id.notes_edit_text) } val taskDifficultyButtons = KView { withId(R.id.task_difficulty_buttons) } val tagsWrapper = KView { withId(R.id.tags_wrapper) } } @LargeTest @RunWith(AndroidJUnit4::class) class TaskFormActivityTest : ActivityTestCase() { val screen = TaskFormScreen() lateinit var scenario: ActivityScenario<TaskFormActivity> val taskSlot = slot<Task>() @After fun cleanup() { scenario.close() } @Before fun setup() { every { sharedPreferences.getString("FirstDayOfTheWeek", any()) } returns "-1" val mockComponent: UserComponent = mockk(relaxed = true) every { mockComponent.inject(any<TaskFormActivity>()) } answers { initializeInjects(this.args.first()) } mockkObject(HabiticaBaseApplication) every { HabiticaBaseApplication.userComponent } returns mockComponent } private fun hasBasicTaskEditingViews() { screen { textEditText.isVisible() notesEditText.isVisible() taskDifficultyButtons.isVisible() tagsWrapper.isVisible() } } @Test fun showsHabitForm() { val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.HABIT.value) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { device.activities.isCurrent(TaskFormActivity::class.java) toolbar.hasTitle("Create Habit") hasBasicTaskEditingViews() KView { withId(R.id.habit_scoring_buttons) }.isVisible() KView { withId(R.id.habit_reset_streak_buttons) }.isVisible() } } @Test fun showsDailyForm() { val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { device.activities.isCurrent(TaskFormActivity::class.java) toolbar.hasTitle("Create Daily") hasBasicTaskEditingViews() KView { withId(R.id.checklist_container) }.isVisible() KView { withId(R.id.task_scheduling_controls) }.isVisible() KView { withId(R.id.reminders_container) }.isVisible() } } @Test fun showsToDoForm() { val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.TODO.value) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { device.activities.isCurrent(TaskFormActivity::class.java) toolbar.hasTitle("Create To Do") hasBasicTaskEditingViews() KView { withId(R.id.checklist_container) }.isVisible() KView { withId(R.id.task_scheduling_controls) }.isVisible() KView { withId(R.id.reminders_container) }.isVisible() } } @Test fun showsRewardForm() { val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.REWARD.value) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { device.activities.isCurrent(TaskFormActivity::class.java) toolbar.hasTitle("Create Reward") textEditText.isVisible() notesEditText.isVisible() tagsWrapper.isVisible() KView { withId(R.id.reward_value) }.isVisible() } } @Test fun savesNewTask() { val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.HABIT.value) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { device.activities.isCurrent(TaskFormActivity::class.java) textEditText.typeText("New Habit") KButton { withId(R.id.action_save) }.click() verify(exactly = 1) { taskRepository.createTaskInBackground(any()) } } } @Test fun savesExistingTask() { val task = Task() task.id = UUID.randomUUID().toString() task.text = "Task text" task.type = TaskType.HABIT task.priority = 1.0f val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.HABIT.value) bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id!!) every { taskRepository.getUnmanagedTask(any()) } returns Flowable.just(task) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { toolbar { KView { withId(R.id.action_save) }.click() verify(exactly = 1) { taskRepository.updateTaskInBackground(any()) } } } } @Test fun deletesExistingTask() { val task = Task() task.id = UUID.randomUUID().toString() task.text = "Task text" task.type = TaskType.DAILY task.priority = 1.0f val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value) bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value) bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id!!) every { taskRepository.getUnmanagedTask(any()) } returns Flowable.just(task) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { device.activities.isCurrent(TaskFormActivity::class.java) KButton { withId(R.id.action_delete) }.click() KButton { withText(R.string.delete_task) }.click() verify(exactly = 1) { taskRepository.deleteTask(task.id!!) } } } /* TODO: Revisit this. For some reason the matchers can't find the checklist add button @Test fun testChecklistItems() { before { val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value) val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) justRun { taskRepository.createTaskInBackground(capture(taskSlot)) } }.after { }.run { screen { KView { withId(R.id.checklist_container) } perform { val container = this step("Add new Checklist Item") { hasChildCount(1) KView { withIndex(0) { withParent { this.getViewMatcher() } } } perform { click() KEditText { withId(R.id.edit_text) }.typeText("test") container.hasChildCount(2) } KEditText { withIndex(1) { withId(R.id.edit_text) } } perform { click() typeText("test2") container.hasChildCount(3) } } step("Edit Checklist Item") { container.hasChildCount(3) KEditText { withIndex(0) { withId(R.id.edit_text) } } perform { clearText() typeText("Test Text") hasText("Test Text") } } step("Remove Checklist Item") { container.hasChildCount(3) KView { withContentDescription(R.string.delete_checklist_entry) }.click() container.hasChildCount(2) } step("Save Checklist") { KButton { withId(R.id.action_save) }.click() verify { taskRepository.createTaskInBackground(any()) } assert(taskSlot.captured.checklist!!.size == 1) assert(taskSlot.captured.checklist!!.first()!!.text == "Test Text") } } } } }*/ @Test fun changesScheduling() { val task = Task() task.id = UUID.randomUUID().toString() task.text = "Task text" task.type = TaskType.DAILY task.priority = 1.0f task.everyX = 1 task.frequency = Frequency.DAILY task.startDate = Date() val bundle = Bundle() bundle.putString(TaskFormActivity.TASK_TYPE_KEY, TaskType.DAILY.value) bundle.putString(TaskFormActivity.TASK_ID_KEY, task.id!!) every { taskRepository.getUnmanagedTask(any()) } returns Flowable.just(task) justRun { taskRepository.updateTaskInBackground(capture(taskSlot)) } val intent = Intent(ApplicationProvider.getApplicationContext(), TaskFormActivity::class.java) intent.putExtras(bundle) scenario = launchActivity(intent) screen { KView { withId(R.id.start_date_wrapper) }.click() KDatePickerDialog() perform { datePicker.setDate(2021, 10, 2) okButton.click() } KSpinner( builder = { withId(R.id.repeats_every_spinner) }, itemTypeBuilder = { itemType(::KSpinnerItem) } ) perform { open() childAt<KSpinnerItem>(1) { click() } } KEditText { withId(R.id.repeats_every_edittext) } perform { clearText() typeText("3") } KButton { withId(R.id.action_save) }.click() verify { taskRepository.updateTaskInBackground(any()) } assert(taskSlot.captured.everyX == 3) assert(taskSlot.captured.frequency == Frequency.WEEKLY) } } } private fun BaseAssertions.hasChildCount(count: Int) { matches { ViewAssertions.matches(ChildCountMatcher(count)) } }
app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateGui.kt
3426114289
package info.nightscout.androidaps.plugins.aps.openAPSMA.events import info.nightscout.androidaps.events.EventUpdateGui class EventOpenAPSUpdateGui : EventUpdateGui()
src/main/kotlin/assimp/Importer.kt
2683139323
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2017, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --------------------------------------------------------------------------- */ package assimp import assimp.format.ProgressHandler import assimp.postProcess.OptimizeMeshes import assimp.postProcess.ValidateDSProcess import glm_.i import kool.BYTES import kool.rem import java.net.URI import java.net.URL import java.nio.ByteBuffer import java.nio.file.Path import java.nio.file.Paths import kotlin.reflect.KMutableProperty0 import assimp.AiPostProcessStep as Pps /** CPP-API: The Importer class forms an C++ interface to the functionality of the Open Asset Import Library. * * Create an object of this class and call ReadFile() to import a file. * If the import succeeds, the function returns a pointer to the imported data. * The data remains property of the object, it is intended to be accessed read-only. The imported data will be destroyed * along with the Importer object. If the import fails, ReadFile() returns a NULL pointer. In this case you can retrieve * a human-readable error description be calling GetErrorString(). You can call ReadFile() multiple times with a single * Importer instance. Actually, constructing Importer objects involves quite many allocations and may take some time, so * it's better to reuse them as often as possible. * * If you need the Importer to do custom file handling to access the files, implement IOSystem and IOStream and supply * an instance of your custom IOSystem implementation by calling SetIOHandler() before calling ReadFile(). * If you do not assign a custion IO handler, a default handler using the standard C++ IO logic will be used. * * @note One Importer instance is not thread-safe. If you use multiple threads for loading, each thread should maintain * its own Importer instance. */ class Importer /** Constructor. Creates an empty importer object. * * Call readFile() to start the import process. The configuration property table is initially empty. */ constructor() { // Just because we don't want you to know how we're hacking around. internal val impl = ImporterPimpl() // allocate the pimpl first fun impl() = impl /** Copy constructor. * * This copies the configuration properties of another Importer. * If this Importer owns a scene it won't be copied. * Call readFile() to start the import process. */ constructor(other: Importer) : this() { impl.properties += other.impl.properties } /** Registers a new loader. * * @param imp Importer to be added. The Importer instance takes ownership of the pointer, so it will be * automatically deleted with the Importer instance. * @return AI_SUCCESS if the loader has been added. The registration fails if there is already a loader for a * specific file extension. */ fun registerLoader(imp: BaseImporter): AiReturn { /* -------------------------------------------------------------------- Check whether we would have two loaders for the same file extension This is absolutely OK, but we should warn the developer of the new loader that his code will probably never be called if the first loader is a bit too lazy in his file checking. -------------------------------------------------------------------- */ val st = imp.extensionList var baked = "" st.forEach { if (ASSIMP.DEBUG && isExtensionSupported(it)) logger.warn { "The file extension $it is already in use" } baked += "$it " } // add the loader impl.importer.add(imp) logger.info { "Registering custom importer for these file extensions: $baked" } return AiReturn.SUCCESS } /** Unregisters a loader. * * @param imp Importer to be unregistered. * @return AI_SUCCESS if the loader has been removed. The function fails if the loader is currently in use (this * could happen if the Importer instance is used by more than one thread) or if it has not yet been registered. */ fun unregisterLoader(imp: BaseImporter) = when (impl.importer.remove(imp)) { true -> logger.info { "Unregistering custom importer: " }.let { AiReturn.SUCCESS } else -> logger.warn { "Unable to remove custom importer: I can't find you ..." }.let { AiReturn.FAILURE } } /** Registers a new post-process step. * * At the moment, there's a small limitation: new post processing steps are added to end of the list, or in other * words, executed last, after all built-in steps. * @param imp Post-process step to be added. The Importer instance takes ownership of the pointer, so it will be * automatically deleted with the Importer instance. * @return AI_SUCCESS if the step has been added correctly. */ fun registerPPStep(imp: BaseProcess): AiReturn { impl.postProcessingSteps.add(imp) logger.info { "Registering custom post-processing step" } return AiReturn.SUCCESS } /** Unregisters a post-process step. * * @param imp Step to be unregistered. * @return AI_SUCCESS if the step has been removed. The function fails if the step is currently in use (this could happen * if the #Importer instance is used by more than one thread) or * if it has not yet been registered. */ fun unregisterPPStep(imp: BaseProcess) = when (impl.postProcessingSteps.remove(imp)) { true -> logger.info { "Unregistering custom post-processing step" }.let { AiReturn.SUCCESS } else -> logger.warn { "Unable to remove custom post-processing step: I can't find you .." }.let { AiReturn.FAILURE } } operator fun <T : Any> set(szName: String, value: T) = impl.properties.put(superFastHash(szName), value) inline operator fun <reified T> get(szName: String): T? = impl().properties[superFastHash(szName)] as? T var prograssHandler: ProgressHandler? /** Retrieves the progress handler that is currently set. * You can use #IsDefaultProgressHandler() to check whether the returned interface is the default handler * provided by ASSIMP. The default handler is active as long the application doesn't supply its own custom * handler via setProgressHandler(). * @return A valid ProgressHandler interface, never null. */ get() = impl.progressHandler /** Supplies a custom progress handler to the importer. This interface exposes a update() callback, which is * called more or less periodically (please don't sue us if it isn't as periodically as you'd like it to have * ...). * This can be used to implement progress bars and loading timeouts. * @param value Progress callback interface. Pass null to disable progress reporting. * @note Progress handlers can be used to abort the loading at almost any time.*/ set(value) { // If the new handler is zero, allocate a default implementation. if (value == null) { // Release pointer in the possession of the caller impl.progressHandler = DefaultProgressHandler() impl.isDefaultProgressHandler = true } else if (impl.progressHandler != value) { // Otherwise register the custom handler impl.progressHandler = value impl.isDefaultProgressHandler = false } } var ioHandler: IOSystem get() = impl.ioSystem set(value) { impl.ioSystem = value } /** Checks whether a default progress handler is active * A default handler is active as long the application doesn't supply its own custom progress handler via * setProgressHandler(). * @return true by default */ val isDefaultProgressHandler get() = impl.isDefaultProgressHandler /** @brief Check whether a given set of post-processing flags is supported. * * Some flags are mutually exclusive, others are probably not available because your excluded them from your * Assimp builds. Calling this function is recommended if you're unsure. * * @param pFlags Bitwise combination of the aiPostProcess flags. * @return true if this flag combination is fine. */ fun validateFlags(flags: Int) = when { flags has Pps.GenSmoothNormals && flags has Pps.GenNormals -> { logger.error { "#aiProcess_GenSmoothNormals and #aiProcess_GenNormals are incompatible" } false } flags has Pps.OptimizeGraph && flags has Pps.PreTransformVertices -> { logger.error { "#aiProcess_OptimizeGraph and #aiProcess_PreTransformVertices are incompatible" } false } else -> true } /** Get the currently set progress handler */ val progressHandler get() = impl.progressHandler @JvmOverloads fun readFile(url: URL, flags: AiPostProcessStepsFlags = 0) = readFile(url.toURI(), flags) @JvmOverloads fun readFile(uri: URI, flags: AiPostProcessStepsFlags = 0) = readFile(Paths.get(uri), flags) @JvmOverloads fun readFile(path: Path, flags: AiPostProcessStepsFlags = 0) = readFile(path.toAbsolutePath().toString(), flags) fun readFile(file: String, flags: AiPostProcessStepsFlags = 0) = readFile(file, ioHandler, flags) /** Reads the given file and returns its contents if successful. * * If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data * is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon * destruction. If the import fails, null is returned. * A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted * during this call. * @param file Path and filename to the file to be imported. * @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise * combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to * fine-tune your post-processing setup, consider to use applyPostProcessing(). * @return A pointer to the imported data, null if the import failed. * The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take * ownership of it. * * @note Assimp is able to determine the file format of a file automatically. */ @JvmOverloads fun readFile(file: String, ioSystem: IOSystem = this.ioHandler, flags: AiPostProcessStepsFlags = 0): AiScene? { writeLogOpening(file) // Check whether this Importer instance has already loaded a scene. In this case we need to delete the old one if (impl.scene != null) { logger.debug { "(Deleting previous scene)" } freeScene() } // First check if the file is accessible at all // handled by exception in IOSystem /*if (!file.exists()) { impl.errorString = "Unable to open file \"$file\"." logger.error { impl.errorString } return null }*/ // TODO std::unique_ptr<Profiler> profiler(GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME,0)?new Profiler():NULL); // if (profiler) { // profiler->BeginRegion("total"); // } // Find an worker class which can handle the file val imp = impl.importer.find { it.canRead(file, ioHandler, false) } if (imp == null) { logger.error { "Assimp could not find an importer for the file!" } return null // not so bad yet ... try format auto detection. // TODO() // const std::string::size_type s = pFile.find_last_of('.'); // if (s != std::string::npos) { // DefaultLogger::get()->info("File extension not known, trying signature-based detection"); // for( unsigned int a = 0; a < pimpl->mImporter.size(); a++) { // // if( pimpl->mImporter[a]->CanRead( pFile, pimpl->mIOHandler, true)) { // imp = pimpl->mImporter[a]; // break; // } // } // } // // Put a proper error message if no suitable importer was found // if( !imp) { // pimpl->mErrorString = "No suitable reader found for the file format of file \"" + pFile + "\"."; // DefaultLogger::get()->error(pimpl->mErrorString); // return NULL; // } } // Get file size for progress handler val fileSize = ioSystem.open(file).length.i // Dispatch the reading to the worker class for this format val desc = imp.info val ext = desc.name logger.info { "Found a matching importer for this file format: $ext." } impl.progressHandler.updateFileRead(0, fileSize) // if (profiler) { TODO // profiler->BeginRegion("import"); // } impl.scene = imp.readFile(this, ioHandler, file) impl.progressHandler.updateFileRead(fileSize, fileSize) // if (profiler) { TODO // profiler->EndRegion("import"); // } // If successful, apply all active post processing steps to the imported data if (impl.scene != null) { if (!ASSIMP.NO.VALIDATEDS_PROCESS) // The ValidateDS process is an exception. It is executed first, even before ScenePreprocessor is called. if (flags has Pps.ValidateDataStructure) { ValidateDSProcess().executeOnScene(this) if (impl.scene == null) return null } // Preprocess the scene and prepare it for post-processing // if (profiler) profiler.BeginRegion("preprocess") ScenePreprocessor.processScene(impl.scene!!) // if (profiler) profiler.EndRegion("preprocess") // Ensure that the validation process won't be called twice applyPostProcessing(flags wo Pps.ValidateDataStructure) } // if failed, extract the error string else if (impl.scene == null) impl.errorString = imp.errorText // if (profiler) { profiler -> // EndRegion("total"); // } return impl.scene } /** Reads the given file from a memory buffer and returns its contents if successful. * * If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data * is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon * destruction. If the import fails, null is returned. * A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted * during this call. * Calling this method doesn't affect the active IOSystem. * @param buffer Pointer to the file data * @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise * combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to * fine-tune your post-processing setup, consider to use applyPostProcessing(). * @param hint An additional hint to the library. If this is a non empty string, the library looks for a loader to * support the file extension specified by hint and passes the file to the first matching loader. If this loader is * unable to completely the request, the library continues and tries to determine the file format on its own, a * task that may or may not be successful. * Check the return value, and you'll know ... * @return A pointer to the imported data, null if the import failed. * The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take * ownership of it. * * @note This is a straightforward way to decode models from memory buffers, but it doesn't handle model formats * that spread their data across multiple files or even directories. Examples include OBJ or MD3, which outsource * parts of their material info into external scripts. If you need full functionality you can use [readFilesFromMemory] */ fun readFileFromMemory(buffer: ByteBuffer, flags: Int, name: String = AI_MEMORYIO_MAGIC_FILENAME, hint: String = ""): AiScene? { if (buffer.rem == 0 || hint.length > MaxLenHint) { impl.errorString = "Invalid parameters passed to ReadFileFromMemory()" return null } // prevent deletion of previous IOSystem val io = impl.ioSystem val fileName = "$name.$hint" ioHandler = MemoryIOSystem(fileName to buffer) readFile(fileName, flags) impl.ioSystem = io return impl.scene } /**Reads the given file from a memory buffer and returns its contents if successful. * * If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data * is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon * destruction. If the import fails, null is returned. * A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted * during this call. * Calling this method doesn't affect the active IOSystem. * * @param fileName name of the base file * @param files a map containing the names and all the files required to read the scene (base file, materials, * textures, etc). * @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise * combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to * fine-tune your post-processing setup, consider to use applyPostProcessing(). * @return A pointer to the imported data, null if the import failed. * The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take * ownership of it. */ fun readFilesFromMemory(fileName: String, files: Map<String, ByteBuffer>, flags: Int): AiScene? { for((name, buffer) in files) { if(buffer.rem == 0){ impl.errorString = "buffer $name is empty" return null } } if(!files.containsKey(fileName)){ impl.errorString = "fileName ($fileName) not in files" return null } val io = impl.ioSystem ioHandler = MemoryIOSystem(files) readFile(fileName, flags) impl.ioSystem = io return impl.scene } /**Reads the given file from a memory buffer and returns its contents if successful. * * If the call succeeds, the contents of the file are returned as a pointer to an AiScene object. The returned data * is intended to be read-only, the importer object keeps ownership of the data and will destroy it upon * destruction. If the import fails, null is returned. * A human-readable error description can be retrieved by accessing errorString. The previous scene will be deleted * during this call. * Calling this method doesn't affect the active IOSystem. * * @param fileName name of the base file * @param flags Optional post processing steps to be executed after a successful import. Provide a bitwise * combination of the AiPostProcessSteps flags. If you wish to inspect the imported scene first in order to * fine-tune your post-processing setup, consider to use applyPostProcessing(). * @param files the files required to read the scene (base file, materials, textures, etc) as a pair with their name. * @return A pointer to the imported data, null if the import failed. * The pointer to the scene remains in possession of the Importer instance. Use getOrphanedScene() to take * ownership of it. */ fun readFilesFromMemory(fileName: String, vararg files: Pair<String, ByteBuffer>, flags: Int = 0): AiScene? { return readFilesFromMemory(fileName, files.toMap(), flags) } /** Apply post-processing to an already-imported scene. * * This is strictly equivalent to calling readFile() with the same flags. However, you can use this separate * function to inspect the imported scene first to fine-tune your post-processing setup. * @param flags_ Provide a bitwise combination of the AiPostProcessSteps flags. * @return A pointer to the post-processed data. This is still the same as the pointer returned by readFile(). * However, if post-processing fails, the scene could now be null. * That's quite a rare case, post processing steps are not really designed to 'fail'. To be exact, the * AiProcess_ValidateDS flag is currently the only post processing step which can actually cause the scene to be * reset to null. * * @note The method does nothing if no scene is currently bound to the Importer instance. */ fun applyPostProcessing(flags_: Int): AiScene? { // Return immediately if no scene is active if (impl.scene == null) return null // If no flags are given, return the current scene with no further action if (flags_ == 0) return impl.scene // In debug builds: run basic flag validation assert(_validateFlags(flags_)) logger.info("Entering post processing pipeline") if (!ASSIMP.NO.VALIDATEDS_PROCESS) /* The ValidateDS process plays an exceptional role. It isn't contained in the global list of post-processing steps, so we need to call it manually. */ if (flags_ has Pps.ValidateDataStructure) { ValidateDSProcess().executeOnScene(this) if (impl.scene == null) return null } if (flags_ has Pps.OptimizeMeshes) { OptimizeMeshes().executeOnScene(this) if (impl.scene == null) return null } var flags = flags_ if (ASSIMP.DEBUG) { if (impl.extraVerbose) { if (ASSIMP.NO.VALIDATEDS_PROCESS) logger.error { "Verbose Import is not available due to build settings" } flags = flags or Pps.ValidateDataStructure } } else if (impl.extraVerbose) logger.warn("Not a debug build, ignoring extra verbose setting") // std::unique_ptr<Profiler> profiler (GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME, 0)?new Profiler():NULL); TODO for (a in impl.postProcessingSteps.indices) { val process = impl.postProcessingSteps[a] impl.progressHandler.updatePostProcess(a, impl.postProcessingSteps.size) if (process.isActive(flags)) { // if (profiler) { profiler -> TODO // BeginRegion("postprocess") // } process.executeOnScene(this) // if (profiler) { profiler -> // EndRegion("postprocess") // } } if (impl.scene == null) break if (ASSIMP.DEBUG) { if (ASSIMP.NO.VALIDATEDS_PROCESS) continue // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step if (impl.extraVerbose) { logger.debug { "Verbose Import: revalidating data structures" } ValidateDSProcess().executeOnScene(this) if (impl.scene == null) { logger.error { "Verbose Import: failed to revalidate data structures" } break } } } } impl.progressHandler.updatePostProcess(impl.postProcessingSteps.size, impl.postProcessingSteps.size) // update private scene flags if (impl.scene != null) // scenePriv(pimpl->mScene)->mPPStepsApplied | = pFlags TODO logger.info { "Leaving post processing pipeline" } return impl.scene } fun applyCustomizedPostProcessing(rootProcess: BaseProcess?, requestValidation: Boolean): AiScene? { // Return immediately if no scene is active if (null == impl.scene) return null // If no flags are given, return the current scene with no further action if (null == rootProcess) return impl.scene // In debug builds: run basic flag validation logger.info { "Entering customized post processing pipeline" } if (!ASSIMP.NO.VALIDATEDS_PROCESS) { // The ValidateDS process plays an exceptional role. It isn't contained in the global // list of post-processing steps, so we need to call it manually. if (requestValidation) { ValidateDSProcess().executeOnScene(this) if (impl.scene == null) return null } } if (ASSIMP.DEBUG && impl.extraVerbose && ASSIMP.NO.VALIDATEDS_PROCESS) logger.error { "Verbose Import is not available due to build settings" } else if (impl.extraVerbose) logger.warn { "Not a debug build, ignoring extra verbose setting" } // std::unique_ptr<Profiler> profiler (GetPropertyInteger(AI_CONFIG_GLOB_MEASURE_TIME, 0) ? new Profiler() : NULL); // if (profiler) { profiler -> // BeginRegion("postprocess"); // } rootProcess.executeOnScene(this) // if (profiler) { profiler -> // EndRegion("postprocess") // } // If the extra verbose mode is active, execute the ValidateDataStructureStep again - after each step if (impl.extraVerbose || requestValidation) { logger.debug { "Verbose Import: revalidating data structures" } ValidateDSProcess().executeOnScene(this) if (impl.scene == null) logger.error { "Verbose Import: failed to revalidate data structures" } } logger.info { "Leaving customized post processing pipeline" } return impl.scene } /** Frees the current scene. * * The function does nothing if no scene has previously been read via readFile(). freeScene() is called * automatically by the destructor and readFile() itself. */ fun freeScene() { impl.scene = null impl.errorString = "" } /** Returns an error description of an error that occurred in ReadFile(). * * Returns an empty string if no error occurred. * @return A description of the last error, an empty string if no error occurred. The string is never null. * * @note The returned function remains valid until one of the following methods is called: readFile(), * freeScene(). */ val errorString get() = impl.errorString /** Returns the scene loaded by the last successful call to readFile() * * @return Current scene or null if there is currently no scene loaded */ val scene get() = impl.scene /** Returns the scene loaded by the last successful call to readFile() and releases the scene from the ownership of * the Importer instance. The application is now responsible for deleting the scene. Any further calls to `scene` * or `orphanedScene` will return null - until a new scene has been loaded via readFile(). * * @return Current scene or null if there is currently no scene loaded * @note Use this method with maximal caution, and only if you have to. * By design, AiScene's are exclusively maintained, allocated and deallocated by Assimp and no one else. The * reasoning behind this is the golden rule that deallocations should always be done by the module that did the * original allocation because heaps are not necessarily shared. `orphanedScene` enforces you to delete the * returned scene by yourself, but this will only be fine if and only if you're using the same heap as assimp. * On Windows, it's typically fine provided everything is linked against the multithreaded-dll version of the * runtime library. * It will work as well for static linkage with Assimp. */ val orphanedScene: AiScene? get() { val s = impl.scene impl.scene = null impl.errorString = "" /* reset error string */ return s } /** Returns whether a given file extension is supported by ASSIMP. * * @param szExtension Extension to be checked. * Must include a trailing dot '.'. Example: ".3ds", ".md3". Cases-insensitive. * @return true if the extension is supported, false otherwise */ fun isExtensionSupported(szExtension: String) = null != getImporter(szExtension) /** Get a full list of all file extensions supported by ASSIMP. * * If a file extension is contained in the list this does of course not mean that ASSIMP is able to load all files * with this extension --- it simply means there is an importer loaded which claims to handle files with this * file extension. * @return String containing the extension list. * Format of the list: "*.3ds;*.obj;*.dae". This is useful for use with the WinAPI call GetOpenFileName(Ex). */ val extensionList get() = impl.importer.joinToString("", "*.", ";").substringBeforeLast(';') /** Get the number of importers currently registered with Assimp. */ val importerCount get() = impl.importer.size /** Get meta data for the importer corresponding to a specific index.. * * @param index Index to query, must be within [0, importerCount) * @return Importer meta data structure, null if the index does not exist or if the importer doesn't offer meta * information (importers may do this at the cost of being hated by their peers). TODO JVM DOESNT ALLOW THIS */ fun getImporterInfo(index: Int) = impl.importer[index].info /** Find the importer corresponding to a specific index. * * @param index Index to query, must be within [0, importerCount) * @return Importer instance. null if the index does not exist. */ fun getImporter(index: Int) = impl.importer.getOrNull(index) /** Find the importer corresponding to a specific file extension. * * This is quite similar to `isExtensionSupported` except a BaseImporter instance is returned. * @param szExtension Extension to check for. The following formats are recognized (BAH being the file extension): * "BAH" (comparison is case-insensitive), ".bah", "*.bah" (wild card and dot characters at the beginning of the * extension are skipped). * @return null if no importer is found*/ fun getImporter(szExtension: String) = getImporter(getImporterIndex(szExtension)) /** Find the importer index corresponding to a specific file extension. * * @param szExtension Extension to check for. The following formats are recognized (BAH being the file extension): * "BAH" (comparison is case-insensitive), ".bah", "*.bah" (wild card and dot characters at the beginning of the * extension are skipped). * @return -1 if no importer is found */ fun getImporterIndex(szExtension: String): Int { assert(szExtension.isNotEmpty()) // skip over wildcard and dot characters at string head -- var p = 0 while (szExtension[p] == '*' || szExtension[p] == '.') ++p var ext = szExtension.substring(p) if (ext.isEmpty()) return -1 ext = ext.toLowerCase() impl.importer.forEach { i -> i.extensionList.forEach { if (ext == it) return impl.importer.indexOf(i) } } return -1 } /** Returns the storage allocated by ASSIMP to hold the scene data in memory. * * This refers to the currently loaded file, see readFile(). * @param in Data structure to be filled. * @note The returned memory statistics refer to the actual size of the use data of the AiScene. Heap-related * overhead is (naturally) not included.*/ val memoryRequirements: AiMemoryInfo get() { val mem = AiMemoryInfo() val scene = impl.scene ?: return mem // return if we have no scene loaded mem.total = AiScene.size // add all meshes repeat(scene.numMeshes) { i -> mem.meshes += AiMesh.size if (scene.meshes[i].hasPositions) mem.meshes += AiVector3D.size * scene.meshes[i].numVertices if (scene.meshes[i].hasNormals) mem.meshes += AiVector3D.size * scene.meshes[i].numVertices if (scene.meshes[i].hasTangentsAndBitangents) mem.meshes += AiVector3D.size * scene.meshes[i].numVertices * 2 for (a in 0 until AI_MAX_NUMBER_OF_COLOR_SETS) if (scene.meshes[i].hasVertexColors(a)) mem.meshes += AiColor4D.size * scene.meshes[i].numVertices else break for (a in 0 until AI_MAX_NUMBER_OF_TEXTURECOORDS) if (scene.meshes[i].hasTextureCoords(a)) mem.meshes += AiVector3D.size * scene.meshes[i].numVertices else break if (scene.meshes[i].hasBones) { for (p in 0 until scene.meshes[i].numBones) { mem.meshes += AiBone.size mem.meshes += scene.meshes[i].bones[p].numWeights * AiVertexWeight.size } } mem.meshes += (3 * Int.BYTES) * scene.meshes[i].numFaces } mem.total += mem.meshes // add all embedded textures for (i in 0 until scene.numTextures) { val pc = scene.textures.values.elementAt(i) mem.textures += AiTexture.size mem.textures += with(pc.extent()) { if (y != 0) 4 * y * x else x } } mem.total += mem.textures // add all animations for (i in 0 until scene.numAnimations) { val pc = scene.animations[i] mem.animations += AiAnimation.size // add all bone anims for (a in 0 until pc.numChannels) { val pc2 = pc.channels[i]!! mem.animations += AiNodeAnim.size mem.animations += pc2.numPositionKeys * AiVectorKey.size mem.animations += pc2.numScalingKeys * AiVectorKey.size mem.animations += pc2.numRotationKeys * AiQuatKey.size } } mem.total += mem.animations // add all cameras and all lights mem.cameras = AiCamera.size * scene.numCameras mem.total += mem.cameras mem.lights = AiLight.size * scene.numLights mem.total += mem.lights // add all nodes addNodeWeight(mem::nodes, scene.rootNode) mem.total += mem.nodes // add all materials for (i in 0 until scene.numMaterials) mem.materials += AiMaterial.size mem.total += mem.materials return mem } /** Enables "extra verbose" mode. * * 'Extra verbose' means the data structure is validated after *every* single post processing step to make sure * everyone modifies the data structure in a well-defined manner. This is a debug feature and not intended for * use in production environments. */ fun setExtraVerbose(verbose: Boolean) { impl.extraVerbose = verbose } private fun writeLogOpening(file: String) { logger.info { "Load $file" } /* print a full version dump. This is nice because we don't need to ask the authors of incoming bug reports for the library version they're using - a log dump is sufficient. */ val flags = compileFlags logger.debug { val message = "Assimp $versionMajor.$versionMinor.$versionRevision" if (ASSIMP.DEBUG) "$message debug" else message } } private fun _validateFlags(flags: Int) = when { flags has Pps.GenSmoothNormals && flags has Pps.GenNormals -> { logger.error { "AiProcess_GenSmoothNormals and AiProcess_GenNormals are incompatible" } false } flags has Pps.OptimizeGraph && flags has Pps.PreTransformVertices -> { logger.error { "AiProcess_OptimizeGraph and AiProcess_PreTransformVertices are incompatible" } false } else -> true } /** Get the memory requirements of a single node */ private fun addNodeWeight(scene: KMutableProperty0<Int>, node: AiNode) { scene.set(scene() + AiNode.size) scene.set(scene() + Int.BYTES * node.numMeshes) for (i in 0 until node.numChildren) addNodeWeight(scene, node.children[i]) } companion object { /** The upper limit for hints. */ val MaxLenHint = 200 } }
app/src/main/java/org/stepic/droid/util/FragmentManagerExtensions.kt
1469657925
package org.stepic.droid.util import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction /** * Run [body] in a [FragmentTransaction] which is automatically committed if it completes without * exception. * * The transaction will be completed by calling [FragmentTransaction.commit] unless [allowStateLoss] * is set to `true` in which case [FragmentTransaction.commitAllowingStateLoss] will be used. */ inline fun FragmentManager.commit( allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit ) { val transaction = beginTransaction() transaction.body() if (allowStateLoss) { transaction.commitAllowingStateLoss() } else { transaction.commit() } } /** * Run [body] in a [FragmentTransaction] which is automatically committed if it completes without * exception. * * The transaction will be completed by calling [FragmentTransaction.commitNow] unless * [allowStateLoss] is set to `true` in which case [FragmentTransaction.commitNowAllowingStateLoss] * will be used. */ inline fun FragmentManager.commitNow( allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit ) { val transaction = beginTransaction() transaction.body() if (allowStateLoss) { transaction.commitNowAllowingStateLoss() } else { transaction.commitNow() } } /** * Run [body] in a [FragmentTransaction] which is automatically committed if it completes without * exception. * * One of four commit functions will be used based on the values of `now` and `allowStateLoss`: * * | now | allowStateLoss | Method | * | ----- | ---------------- | ------------------------------ | * | false | false | commit() | * | false | true | commitAllowingStateLoss() | * | true | false | commitNow() | * | true | true | commitNowAllowingStateLoss() | */ @Deprecated("Use commit { .. } or commitNow { .. } extensions") inline fun FragmentManager.transaction( now: Boolean = false, allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit ) { val transaction = beginTransaction() transaction.body() if (now) { if (allowStateLoss) { transaction.commitNowAllowingStateLoss() } else { transaction.commitNow() } } else { if (allowStateLoss) { transaction.commitAllowingStateLoss() } else { transaction.commit() } } }
test/org/jetbrains/plugins/ideavim/action/motion/object/MotionInnerBlockTagActionTest.kt
1494521454
/* * IdeaVim - Vim emulator for IDEs based on the IntelliJ platform * Copyright (C) 2003-2019 The IdeaVim authors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jetbrains.plugins.ideavim.action.motion.`object` import com.maddyhome.idea.vim.helper.StringHelper.parseKeys import org.jetbrains.plugins.ideavim.VimTestCase class MotionInnerBlockTagActionTest : VimTestCase() { //|d| |v_it| fun testDeleteInnerTagBlockCaretInHtml() { typeTextInFile(parseKeys("dit"), "<template ${c}name=\"hello\">\n" + " <button>Click Me</button>\n" + " <p>You've pressed the button {{counter}} times.</p>\n" + "</template>\n") myFixture.checkResult("<template name=\"hello\"></template>\n") } //|d| |v_it| fun testDeleteInnerTagBlockCaretInHtmlUnclosedTag() { typeTextInFile(parseKeys("dit"), "<template ${c}name=\"hello\">\n" + " <button>Click Me</button>\n" + " <br>\n" + " <p>You've pressed the button {{counter}} times.</p>\n" + "</template>\n") myFixture.checkResult("<template name=\"hello\"></template>\n") } fun testDeleteInnerTagBlockCaretEdgeTag() { typeTextInFile(parseKeys("dit"), "<template name=\"hello\"${c}>\n" + " <button>Click Me</button>\n" + " <br>\n" + " <p>You've pressed the button {{counter}} times.</p>\n" + "</template>\n") myFixture.checkResult("<template name=\"hello\"></template>\n") } //|d| |v_it| fun testDeleteInnerTagBlockBefore() { typeTextInFile(parseKeys("dit"), "abc${c}de<tag>fg</tag>hi") myFixture.checkResult("abcde<tag>fg</tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInOpen() { typeTextInFile(parseKeys("dit"), "abcde<ta${c}g>fg</tag>hi") myFixture.checkResult("abcde<tag></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInOpenEndOfLine() { typeTextInFile(parseKeys("dit"), "abcde<ta${c}g>fg</tag>") myFixture.checkResult("abcde<tag></tag>") } //|d| |v_it| fun testDeleteInnerTagBlockInOpenStartOfLine() { typeTextInFile(parseKeys("dit"), "<ta${c}g>fg</tag>hi") myFixture.checkResult("<tag></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInOpenWithArgs() { typeTextInFile(parseKeys("dit"), "abcde<ta${c}g name = \"name\">fg</tag>hi") myFixture.checkResult("abcde<tag name = \"name\"></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetween() { typeTextInFile(parseKeys("dit"), "abcde<tag>f${c}g</tag>hi") myFixture.checkResult("abcde<tag></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenTagWithRegex() { typeTextInFile(parseKeys("dit"), "abcde<[abc]*>af${c}gbc</[abc]*>hi") myFixture.checkResult("abcde<[abc]*></[abc]*>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenCamelCase() { typeTextInFile(parseKeys("dit"), "abcde<tAg>f${c}g</tag>hi") myFixture.checkResult("abcde<tAg></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenCaps() { typeTextInFile(parseKeys("dit"), "abcde<tag>f${c}g</TAG>hi") myFixture.checkResult("abcde<tag></TAG>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenWithSpaceBeforeTag() { typeTextInFile(parseKeys("dit"), "abcde< tag>f${c}g</ tag>hi") myFixture.checkResult("abcde< tag>fg</ tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenWithSpaceAfterTag() { typeTextInFile(parseKeys("dit"), "abcde<tag >f${c}g</tag>hi") myFixture.checkResult("abcde<tag ></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenWithArgs() { typeTextInFile(parseKeys("dit"), "abcde<tag name = \"name\">f${c}g</tag>hi") myFixture.checkResult("abcde<tag name = \"name\"></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInClose() { typeTextInFile(parseKeys("dit"), "abcde<tag>fg</ta${c}g>hi") myFixture.checkResult("abcde<tag></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockAfter() { typeTextInFile(parseKeys("dit"), "abcde<tag>fg</tag>h${c}i") myFixture.checkResult("abcde<tag>fg</tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInAlone() { typeTextInFile(parseKeys("dit"), "abcde<ta${c}g>fghi") myFixture.checkResult("abcde<tag>fghi") } //|d| |v_it| fun testDeleteInnerTagBlockWithoutTags() { typeTextInFile(parseKeys("dit"), "abc${c}de") myFixture.checkResult("abcde") } //|d| |v_it| fun testDeleteInnerTagBlockBeforeWithoutOpenTag() { typeTextInFile(parseKeys("dit"), "abc${c}defg</tag>hi") myFixture.checkResult("abcdefg</tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInCloseWithoutOpenTag() { typeTextInFile(parseKeys("dit"), "abcdefg</ta${c}g>hi") myFixture.checkResult("abcdefg</tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockAfterWithoutOpenTag() { typeTextInFile(parseKeys("dit"), "abcdefg</tag>h${c}i") myFixture.checkResult("abcdefg</tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBeforeWithoutCloseTag() { typeTextInFile(parseKeys("dit"), "abc${c}defg<tag>hi") myFixture.checkResult("abcdefg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInOpenWithoutCloseTag() { typeTextInFile(parseKeys("dit"), "abcdefg<ta${c}g>hi") myFixture.checkResult("abcdefg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockAfterWithoutCloseTag() { typeTextInFile(parseKeys("dit"), "abcdefg<tag>h${c}i") myFixture.checkResult("abcdefg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBeforeWrongOrder() { typeTextInFile(parseKeys("dit"), "abc${c}de</tag>fg<tag>hi") myFixture.checkResult("abcde</tag>fg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInOpenWrongOrder() { typeTextInFile(parseKeys("dit"), "abcde</ta${c}g>fg<tag>hi") myFixture.checkResult("abcde</tag>fg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBetweenWrongOrder() { typeTextInFile(parseKeys("dit"), "abcde</tag>f${c}g<tag>hi") myFixture.checkResult("abcde</tag>fg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockInCloseWrongOrder() { typeTextInFile(parseKeys("dit"), "abcde</tag>fg<ta${c}g>hi") myFixture.checkResult("abcde</tag>fg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockTwoTagsWrongOrder() { typeTextInFile(parseKeys("dit"), "<foo><html>t${c}ext</foo></html>") myFixture.checkResult("<foo></foo></html>") } //|d| |v_it| fun testDeleteInnerTagBlockTwoTagsWrongOrderInClosingTag() { typeTextInFile(parseKeys("dit"), "<foo><html>text</foo></htm${c}l>") myFixture.checkResult("<foo><html></html>") } //|d| |v_it| fun testDeleteInnerTagBlockAfterWrongOrder() { typeTextInFile(parseKeys("dit"), "abcde</tag>fg<tag>h${c}i") myFixture.checkResult("abcde</tag>fg<tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBracketInside() { typeTextInFile(parseKeys("dit"), "abcde<tag>f${c}<>g</tag>hi") myFixture.checkResult("abcde<tag></tag>hi") } //|d| |v_it| fun testDeleteInnerTagBlockBracketInsideString() { typeTextInFile(parseKeys("dit"), "abcde<tag>f${c}\"<>\"g</tag>hi") myFixture.checkResult("abcde<tag></tag>hi") } //|d| |v_it| fun testDeleteInnerTagIsCaseInsensitive() { typeTextInFile(parseKeys("dit"), "<a> <as${c}df> </A>") myFixture.checkResult("<a></A>") } //|d| |v_it| fun testDeleteInnerTagSlashesInAttribute() { typeTextInFile(parseKeys("dit"), "<a href=\"http://isitchristmas.com\" class=\"button\">Bing ${c}Bing bing</a>") myFixture.checkResult("<a href=\"http://isitchristmas.com\" class=\"button\"></a>") } // VIM-1090 |d| |v_it| // Adapted from vim source file "test_textobjects.vim" fun testDeleteInnerTagDuplicateTags() { typeTextInFile(parseKeys("dit"), "<b>as${c}d<i>as<b />df</i>asdf</b>") myFixture.checkResult("<b></b>") } // |v_it| fun testFileStartsWithSlash() { configureByText("/*hello\n" + "${c}foo\n" + "bar>baz\n") typeText(parseKeys("vit")) assertPluginError(true) } // |v_it| fun testSelectInnerTagEmptyTag() { configureByText("<a>${c}</a>") typeText(parseKeys("vit")) assertSelection("<a></a>") } fun `test single character`() { // The whole tag block is also selected if there is only a single character inside configureByText("<a>${c}a</a>") typeText(parseKeys("vit")) assertSelection("<a>a</a>") } fun `test single character inside tag`() { configureByText("<a${c}></a>") typeText(parseKeys("vit")) assertSelection("<") } // VIM-1633 |v_it| fun testNestedInTagSelection() { configureByText("<t>Outer\n" + " <t>${c}Inner</t>\n" + "</t>\n") typeText(parseKeys("vit")) assertSelection("Inner") } fun `test nested tag double motion`() { configureByText("<o>Outer\n" + " ${c} <t></t>\n" + "</o>\n") typeText(parseKeys("vitit")) assertSelection("<t></t>") } fun `test in inner tag double motion`() { configureByText("<o><t>${c}</t>\n</o>") typeText(parseKeys("vitit")) assertSelection("<o><t></t>\n</o>") } fun `test nested tags between tags`() { configureByText("<t>Outer\n" + " <t>Inner</t> ${c} <t>Inner</t>\n" + "</t>\n") typeText(parseKeys("vit")) assertSelection("Outer\n" + " <t>Inner</t> <t>Inner</t>") } fun `test nested tags number motion`() { configureByText("<t>Outer\n" + " <t>${c}Inner</t>\n" + "</t>\n") typeText(parseKeys("v2it")) assertSelection("Outer\n" + " <t>Inner</t>") } fun `test nested tags double motion`() { configureByText("<o>Outer\n" + " <t>${c}Inner</t>\n" + "</o>\n") typeText(parseKeys("vitit")) assertSelection("<t>Inner</t>") } fun `test nested tags triple motion`() { configureByText("<t>Outer\n" + " <t>${c}Inner</t>\n" + "</t>\n") typeText(parseKeys("vititit")) assertSelection("Outer\n" + " <t>Inner</t>") } fun `test nested tags in closing tag`() { configureByText("<t>Outer\n" + " <t>Inner</t>\n" + "</${c}t>\n") typeText(parseKeys("vit")) assertSelection("Outer\n" + " <t>Inner</t>") } fun `test nested tags in opening tag`() { configureByText("<${c}t>Outer\n" + " <t>Inner</t>\n" + "</t>\n") typeText(parseKeys("vit")) assertSelection("Outer\n" + " <t>Inner</t>") } fun `test nested tags ouside tag`() { configureByText("${c}<t>Outer\n" + " <t>Inner</t>\n" + "</t>\n") typeText(parseKeys("vit")) assertSelection("Outer\n" + " <t>Inner</t>") } fun `test skip whitespace at start of line`() { configureByText("<o>Outer\n" + " ${c} <t></t>\n" + "</o>\n") typeText(parseKeys("vit")) assertSelection("<") } }
backend.native/tests/runtime/workers/worker2.kt
1047230781
import konan.worker.* data class WorkerArgument(val intParam: Int, val stringParam: String) data class WorkerResult(val intResult: Int, val stringResult: String) fun main(args: Array<String>) { val COUNT = 5 val workers = Array(COUNT, { _ -> startWorker()}) for (attempt in 1 .. 3) { val futures = Array(workers.size, { workerIndex -> workers[workerIndex].schedule(TransferMode.CHECKED, { WorkerArgument(workerIndex, "attempt $attempt") }) { input -> var sum = 0 for (i in 0..input.intParam * 1000) { sum += i } WorkerResult(sum, input.stringParam + " result") } }) val futureSet = futures.toSet() var consumed = 0 while (consumed < futureSet.size) { val ready = futureSet.waitForMultipleFutures(10000) ready.forEach { it.consume { result -> if (result.stringResult != "attempt $attempt result") throw Error("Unexpected $result") consumed++ } } } } workers.forEach { it.requestTermination().consume { _ -> } } println("OK") }
src/main/java/exnihilocreatio/compatibility/crafttweaker/Compost.kt
1031013317
package exnihilocreatio.compatibility.crafttweaker import crafttweaker.IAction import crafttweaker.annotations.ZenRegister import crafttweaker.api.item.IIngredient import crafttweaker.api.item.IItemStack import crafttweaker.api.minecraft.CraftTweakerMC import exnihilocreatio.compatibility.crafttweaker.prefab.ENCRemoveAll import exnihilocreatio.registries.manager.ExNihiloRegistryManager import exnihilocreatio.registries.types.Compostable import exnihilocreatio.texturing.Color import exnihilocreatio.util.BlockInfo import net.minecraft.item.ItemStack import net.minecraft.item.crafting.Ingredient import stanhebben.zenscript.annotations.ZenClass import stanhebben.zenscript.annotations.ZenMethod @ZenClass("mods.exnihilocreatio.Compost") @ZenRegister object Compost { @ZenMethod @JvmStatic fun removeAll() { CrTIntegration.removeActions += ENCRemoveAll(ExNihiloRegistryManager.COMPOST_REGISTRY, "Compost") } @ZenMethod @JvmStatic fun addRecipe(input: IIngredient, value: Float, color: String, block: IItemStack) { CrTIntegration.addActions += AddRecipe(input, value, color, block) } private class AddRecipe( input: IIngredient, private val value: Float, color: String, block: IItemStack ) : IAction { private val input: Ingredient = CraftTweakerMC.getIngredient(input) private val color: Color = Color(color) private val block: BlockInfo = BlockInfo(block.internal as ItemStack) override fun apply() { ExNihiloRegistryManager.COMPOST_REGISTRY.register(input, Compostable(value, color, block)) } override fun describe() = "Adding Compost recipe for ${input.matchingStacks.joinToString(prefix = "[", postfix = "]")} with value $value and Color $color" } }
src/jp/kazhida/kotos2d/Kotos2dTextInputWrapper.kt
870538230
package jp.kazhida.kotos2d import android.text.TextWatcher import android.widget.TextView.OnEditorActionListener import android.text.Editable import android.widget.TextView import android.view.KeyEvent import android.content.Context import android.view.inputmethod.InputMethodManager import android.view.inputmethod.EditorInfo /** * * Created by kazhida on 2013/07/29. */ public class Kotos2dTextInputWrapper(val surfaceView: Kotos2dGLSurfaceView): TextWatcher, OnEditorActionListener { class object { private val TAG : String? = javaClass<Kotos2dTextInputWrapper>().getSimpleName() } private val isFullScreenEdit: Boolean get() { val textField: TextView? = surfaceView.editText val imm : InputMethodManager? = textField?.getContext()?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager? return imm?.isFullscreenMode()!! } private var text: String? = null private var originText: String? = null public fun setOriginText(pOriginText : String?) : Unit { this.originText = pOriginText } public override fun afterTextChanged(s: Editable?) { if (! isFullScreenEdit && s != null) { var nModified : Int = s.length() - (this.text?.length())!! if (nModified > 0) { val insertText : String? = s.subSequence((text?.length())!!, s.length()).toString() surfaceView.insertText(insertText) } else { while (nModified < 0) { surfaceView.deleteBackward() ++nModified } } text = s.toString() } } public override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { text = s?.toString() } public override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} public override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean { if (surfaceView.editText == v && isFullScreenEdit) { var i : Int = originText?.length() ?: 0 while (i > 0) { surfaceView.deleteBackward() i-- } var s : String = v?.getText()?.toString()!! if ((s.compareTo("")) == 0) { s = "\n" } if ('\n' != s.charAt((s.length()) - 1)) { s += '\n' } val insertText : String = s surfaceView.insertText(insertText) } if (actionId == EditorInfo.IME_ACTION_DONE) { surfaceView.requestFocus() } return false } }
mapper/src/test/kotlin/com/github/andrewoma/kwery/mappertest/example/DaoListenerPreCommitTest.kt
2543227985
/* * Copyright (c) 2015 Andrew O'Malley * * 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.github.andrewoma.kwery.mappertest.example import com.github.andrewoma.kwery.core.Session import com.github.andrewoma.kwery.mapper.Table import com.github.andrewoma.kwery.mapper.listener.* import com.github.andrewoma.kwery.mappertest.AbstractSessionTest import com.github.andrewoma.kwery.mappertest.example.test.initialiseFilmSchema import org.junit.Test import kotlin.properties.Delegates import kotlin.test.assertEquals /** * Demonstrates a pre commit listener the saves audit records of all changes */ class DaoListenerPreCommitTest : AbstractSessionTest() { var dao: ActorDao by Delegates.notNull() var nextTransactionId = 0 override var startTransactionByDefault = false override fun afterSessionSetup() { initialise("filmSchema") { initialiseFilmSchema(it) } initialise("audit") { it.update(""" create table audit( id identity, transaction numeric(10), table_name varchar(255), key numeric(10), operation varchar(255), changes varchar(4000) ) """) } super.afterSessionSetup() dao = ActorDao(session, FilmActorDao(session)) dao.addListener(AuditHandler()) session.update("delete from actor where actor_id > -1000") session.update("delete from audit") } @Test fun `Audit rows should be created for each transaction`() { val transactionId = nextTransactionId + 1 val (bruce, brandon) = session.transaction { val bruce = dao.insert(Actor(Name("Bruce", "Lee"))) val brandon = dao.insert(Actor(Name("Brandon", "Lee"))) dao.update(brandon, brandon.copy(name = (Name("Tex", "Lee")))) bruce to brandon } // Generates: // Audit(transactionId=1, table=actor, id=0, operation=Insert, changes=last_name: 'Lee', first_name: 'Bruce', last_update: '2015-02-26 05:44:49.796') // Audit(transactionId=1, table=actor, id=1, operation=Insert, changes=last_name: 'Lee', first_name: 'Brandon', last_update: '2015-02-26 05:44:49.796') // Audit(transactionId=1, table=actor, id=1, operation=Update, changes=first_name: 'Brandon' -> 'Tex', last_update: '2015-02-26 05:44:49.796' -> '2015-02-26 05:44:49.938') session.transaction { dao.delete(bruce.id) } // Generates: // Audit(transactionId=2, table=actor, id=0, operation=Delete, changes=) // This should have no effect as audits will be rolled back in the transaction too session.transaction { session.currentTransaction?.rollbackOnly = true dao.delete(brandon.id) } val audits = session.select("select transaction, count(*) as \"count\" from audit group by transaction") { row -> row.int("transaction") to row.int("count") }.toMap() assertEquals(2, audits.size) assertEquals(6, audits[transactionId]) assertEquals(1, audits[transactionId + 1]) } data class Audit(val transactionId: Int, val table: String, val id: Int, val operation: String, val changes: String) inner class AuditHandler : DeferredListener(false) { override fun onCommit(committed: Boolean, events: List<Event>) { println("AuditHandler invoked") val transactionId = ++nextTransactionId val audits = events.map { event -> @Suppress("UNCHECKED_CAST") // TODO ... grok projections, why is casting needed? val table = event.table as Table<Any, Any> val operation = event::class.java.simpleName.replace("Event$".toRegex(), "") Audit(transactionId, event.table.name, event.id as Int, operation, calculateChanges(event, session, table)) } println(audits.joinToString("\n")) saveAudits(audits, session) } private fun calculateChanges(event: Event, session: Session, table: Table<Any, Any>) = when (event) { is InsertEvent -> { table.objectMap(session, event.value, table.dataColumns).entries.map { "${it.key}: ${session.dialect.bind(it.value!!, -1)}" }.joinToString(", ") } is UpdateEvent -> { val old = table.objectMap(session, event.old!!, table.dataColumns) val new = table.objectMap(session, event.new, table.dataColumns) old.mapValues { it.value to new[it.key] }.filter { it.value.first != it.value.second }.map { "${it.key}: ${session.dialect.bind(it.value.first!!, -1)} -> ${session.dialect.bind(it.value.second!!, -1)}" }.joinToString(", ") } is DeleteEvent -> "" is PreInsertEvent -> "" is PreUpdateEvent -> "" else -> throw UnsupportedOperationException("Unknown event: $event") } private fun saveAudits(audits: List<Audit>, session: Session) { val insert = """ insert into audit(transaction, table_name, key, operation, changes) values (:transaction, :table_name, :key, :operation, :changes) """ val params = audits.map { mapOf("transaction" to it.transactionId, "table_name" to it.table, "key" to it.id, "operation" to it.operation, "changes" to it.changes) } session.batchUpdate(insert, params) } } }
app/src/main/java/info/hzvtc/hipixiv/vm/MainViewModel.kt
1661052849
package info.hzvtc.hipixiv.vm import android.databinding.DataBindingUtil import android.support.design.widget.TabLayout import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import com.afollestad.materialdialogs.MaterialDialog import info.hzvtc.hipixiv.R import info.hzvtc.hipixiv.adapter.BookmarkTagAdapter import info.hzvtc.hipixiv.adapter.IllustAdapter import info.hzvtc.hipixiv.adapter.SimplePagerAdapter import info.hzvtc.hipixiv.adapter.events.TagItemClick import info.hzvtc.hipixiv.data.Account import info.hzvtc.hipixiv.data.UserPreferences import info.hzvtc.hipixiv.data.ViewPagerBundle import info.hzvtc.hipixiv.databinding.* import info.hzvtc.hipixiv.net.ApiService import info.hzvtc.hipixiv.util.AppUtil import info.hzvtc.hipixiv.view.MainActivity import info.hzvtc.hipixiv.view.fragment.* import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject class MainViewModel @Inject constructor(val userPreferences: UserPreferences,val account: Account,val apiService: ApiService) : BaseViewModel<MainActivity,ActivityMainBinding>() { private var nowIdentifier = -1 //关注者 //restricts position private var restrictPos = 0 //collect restrict position private var collectRestrictPos = 0 //item[3]-> all public private private lateinit var restricts: Array<out String> //标签过滤 //item[2]-> public private private lateinit var doubleRestricts: Array<out String> private var lastPosition = 0 private var isPublicPage = true private var dialog : MaterialDialog? = null private lateinit var obsToken : Observable<String> private lateinit var newestFollowBundle : ViewPagerBundle<BaseFragment<*>> private lateinit var newestNewBundle : ViewPagerBundle<BaseFragment<*>> private lateinit var userPageBundle : ViewPagerBundle<BaseFragment<*>> private lateinit var pixivisionPageBundle : ViewPagerBundle<BaseFragment<*>> private lateinit var homeIllustFragment : IllustFragment private lateinit var homeMangaFragment : IllustFragment private lateinit var followVpFragment : ViewPagerFragment private lateinit var newVpFragment : ViewPagerFragment private lateinit var pixivisionVpFragment : ViewPagerFragment private lateinit var myPixivFragment : IllustFragment private lateinit var collectFragment : IllustFragment private lateinit var historyFragment : IllustFragment private lateinit var userVpFragment : ViewPagerFragment override fun initViewModel() { obsToken = account.obsToken(mView) restricts = mView.resources.getStringArray(R.array.restrict_parameters) doubleRestricts = mView.resources.getStringArray(R.array.double_restrict_parameters) //newest -> follow -> bundle newestFollowBundle = object : ViewPagerBundle<BaseFragment<*>>() { init { titles = mView.resources.getStringArray(R.array.newest_follow_tab) pagers = arrayOf( IllustLazyFragment(obsToken.flatMap({ token -> apiService.getFollowIllusts(token,restricts[0])}),account,IllustAdapter.Type.ILLUST), UserLazyFragment(obsToken.flatMap({ token -> apiService.getUserRecommended(token)}),account)) } override fun fabClick() { when(nowPosition) { 0 -> { showSingleFilterDialog(mView.resources.getStringArray(R.array.newest_follow_illust_items),object : Action{ override fun doAction() { (pagers[0] as IllustLazyFragment).viewModel.getData(obsToken. flatMap({token -> apiService.getFollowIllusts(token,restricts[restrictPos])})) } }) } } } override fun fabShow(position: Int) { super.fabShow(position) if(position != 1) mView.setFabVisible(true,true) else mView.setFabVisible(false,false) } } //newest -> new -> bundle newestNewBundle = object : ViewPagerBundle<BaseFragment<*>>(){ init { titles = mView.resources.getStringArray(R.array.newest_new_tab) pagers = arrayOf( IllustLazyFragment(obsToken.flatMap({ token -> apiService.getNewIllust(token,"illust")}),account,IllustAdapter.Type.ILLUST), IllustLazyFragment(obsToken.flatMap({ token -> apiService.getNewIllust(token,"manga")}),account,IllustAdapter.Type.MANGA)) } } //user userPageBundle = object : ViewPagerBundle<BaseFragment<*>>(){ init { titles = mView.resources.getStringArray(R.array.user_tab) pagers = arrayOf( UserLazyFragment(obsToken.flatMap({ token -> apiService.getUserFollowing(token,userPreferences.id?:0,doubleRestricts[0])}),account), UserLazyFragment(obsToken.flatMap({ token -> apiService.getUserFollower(token,userPreferences.id?:0)}),account), UserLazyFragment(obsToken.flatMap({ token -> apiService.getUserMyPixiv(token,userPreferences.id?:0)}),account) ) } override fun fabClick() { super.fabClick() when(nowPosition){ 0 ->{ showSingleFilterDialog(mView.resources.getStringArray(R.array.filter_items),object : Action{ override fun doAction() { (pagers[0] as UserLazyFragment).viewModel.getData(obsToken. flatMap({token -> apiService.getUserFollowing(token,userPreferences.id?:0,doubleRestricts[restrictPos])})) } }) } } } override fun fabShow(position: Int) { super.fabShow(position) if(position == 0) mView.setFabVisible(true,true) else mView.setFabVisible(false,false) } } //Pixivision pixivisionPageBundle = object : ViewPagerBundle<BaseFragment<*>>(){ init { titles = mView.resources.getStringArray(R.array.newest_new_tab) pagers = arrayOf( PixivisionLazyFragment(obsToken.flatMap({ token -> apiService.getPixivisionArticles(token,"illust")}),account), PixivisionLazyFragment(obsToken.flatMap({ token -> apiService.getPixivisionArticles(token,"manga")}),account) ) } } homeIllustFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getRecommendedIllusts(token, true) }),account,IllustAdapter.Type.ILLUST) homeMangaFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getRecommendedMangaList(token, true) }),account,IllustAdapter.Type.MANGA) followVpFragment = ViewPagerFragment(newestFollowBundle) newVpFragment = ViewPagerFragment(newestNewBundle) pixivisionVpFragment = ViewPagerFragment(pixivisionPageBundle) myPixivFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getMyPixivIllusts(token)}),account,IllustAdapter.Type.ILLUST) collectFragment = IllustFragment(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0])}),account,IllustAdapter.Type.ILLUST) historyFragment = IllustFragment(obsToken.flatMap({ token -> apiService.getIllustBrowsingHistory(token)}),account,IllustAdapter.Type.ILLUST) userVpFragment = ViewPagerFragment(userPageBundle) } fun switchPage(identifier : Int){ if(identifier != nowIdentifier){ nowIdentifier = identifier userPreferences.pageIdentifier = identifier.toLong() when(identifier){ //主页插画 MainActivity.Identifier.HOME_ILLUSTRATIONS.value -> { replaceFragment(homeIllustFragment) mView.setFabVisible(false,false) } //主页漫画 MainActivity.Identifier.HOME_MANGA.value -> { replaceFragment(homeMangaFragment) mView.setFabVisible(false,false) } //关注者 MainActivity.Identifier.NEWEST_FOLLOW.value -> { replaceFragment(followVpFragment) restrictPos = 0 mBind.fab.setImageDrawable(ContextCompat.getDrawable(mView,R.drawable.ic_filter)) mBind.fab.setOnClickListener({ newestFollowBundle.fabClick() }) mView.setFabVisible(true,true) } //最新 MainActivity.Identifier.NEWEST_NEW.value -> { replaceFragment(newVpFragment) mView.setFabVisible(false,false) } //Pixivision MainActivity.Identifier.PIXIVISION.value ->{ replaceFragment(pixivisionVpFragment) mView.setFabVisible(false,false) } //My Pixiv MainActivity.Identifier.NEWEST_MY_PIXIV.value ->{ replaceFragment(myPixivFragment) mView.setFabVisible(false,false) } //收集 MainActivity.Identifier.COLLECT.value ->{ replaceFragment(collectFragment) lastPosition = 0 isPublicPage = true dialog = null mBind.fab.setImageDrawable(ContextCompat.getDrawable(mView,R.drawable.ic_filter)) mBind.fab.setOnClickListener({ showTagViewPagerDialog()}) mView.setFabVisible(true,true) } //浏览历史 MainActivity.Identifier.BROWSING_HISTORY.value ->{ replaceFragment(historyFragment) mView.setFabVisible(false,false) } //用户 MainActivity.Identifier.USER.value ->{ replaceFragment(userVpFragment) restrictPos = 0 mBind.fab.setImageDrawable(ContextCompat.getDrawable(mView,R.drawable.ic_filter)) mBind.fab.setOnClickListener({ userPageBundle.fabClick() }) mView.setFabVisible(true,true) } } } } private fun replaceFragment(fragment : Fragment){ val transaction = mView.supportFragmentManager.beginTransaction() transaction.replace(R.id.contentFrame,fragment) transaction.addToBackStack(null) transaction.commit() } private fun showSingleFilterDialog(items: Array<String>, action : Action){ val dialog = MaterialDialog.Builder(mView) .title(getString(R.string.newest_follow_illust_name)) .customView(R.layout.dialog_single_filter, true) .positiveText(getString(R.string.app_dialog_ok)) .negativeText(getString(R.string.app_dialog_cancel)) .onPositive({ _, _ -> action.doAction()}) .build() val bind = DataBindingUtil.bind<DialogSingleFilterBinding>(dialog.customView!!) bind?.restrict?.adapter = ArrayAdapter<String>(mView,android.R.layout.simple_list_item_1,items) bind?.restrict?.setSelection(restrictPos) bind?.restrict?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{ override fun onNothingSelected(parent: AdapterView<*>?) { // } override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { restrictPos = position } } dialog.show() } //标签过滤 private fun showTagViewPagerDialog(){ if(dialog == null){ dialog = MaterialDialog.Builder(mView) .title(getString(R.string.collect_filter_name)) .negativeText(getString(R.string.app_dialog_cancel)) .customView(R.layout.dialog_view_pager, false) .build() val bind = DataBindingUtil.bind<DialogViewPagerBinding>(dialog?.customView!!) val publicPage = DataBindingUtil.bind<FragmentListBinding>(View.inflate(mView,R.layout.fragment_list,null)) val privatePage = DataBindingUtil.bind<FragmentListBinding>(View.inflate(mView,R.layout.fragment_list,null)) val adapter = SimplePagerAdapter(arrayOf(publicPage!!.root,privatePage!!.root), mView.resources.getStringArray(R.array.filter_items)) val publicPageAdapter = BookmarkTagAdapter(mView) val privatePageAdapter = BookmarkTagAdapter(mView) publicPage.recyclerView.adapter = publicPageAdapter publicPage.recyclerView.layoutManager = LinearLayoutManager(mView) publicPage.srLayout.setColorSchemeColors(ContextCompat.getColor(mView, R.color.primary)) publicPage.srLayout.setOnRefreshListener({ initPageData(publicPage,publicPageAdapter,true) }) privatePage.recyclerView.adapter = privatePageAdapter privatePage.recyclerView.layoutManager = LinearLayoutManager(mView) privatePage.srLayout.setColorSchemeColors(ContextCompat.getColor(mView, R.color.primary)) privatePage.srLayout.setOnRefreshListener({ initPageData(privatePage,privatePageAdapter,false) }) publicPageAdapter.setTagItemClick(object : TagItemClick { override fun itemClick(position: Int,tag : String) { if(!isPublicPage){ privatePageAdapter.updateLastPositionItem(lastPosition) }else{ publicPageAdapter.updateLastPositionItem(lastPosition) } publicPageAdapter.updatePositionItem(position) lastPosition = position isPublicPage = true when(position){ 0 ->{ collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0])})) } 1 ->{ collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0],"未分類")})) } else->{ collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[0],tag)})) } } dialog?.hide() } }) privatePageAdapter.setTagItemClick(object : TagItemClick { override fun itemClick(position: Int,tag : String) { if(isPublicPage){ publicPageAdapter.updateLastPositionItem(lastPosition) }else { privatePageAdapter.updateLastPositionItem(lastPosition) } privatePageAdapter.updatePositionItem(position) when(position){ 0 ->{ collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[1])})) } 1 ->{ collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[1],"未分類")})) } else->{ collectFragment.viewModel.getData(obsToken.flatMap({ token -> apiService .getLikeIllust(token,userPreferences.id?:0,doubleRestricts[1],tag)})) } } lastPosition = position isPublicPage = false dialog?.hide() } }) bind?.viewPager?.adapter = adapter bind?.viewPager?.currentItem = collectRestrictPos bind?.tab?.setupWithViewPager(bind.viewPager) bind?.tab?.tabMode = TabLayout.MODE_FIXED initPageData(publicPage,publicPageAdapter,true) initPageData(privatePage,privatePageAdapter,false) } dialog?.show() } //加载标签选择页面数据 private fun initPageData(page : FragmentListBinding,pageAdapter : BookmarkTagAdapter?,isPublic : Boolean){ val restrict = if(isPublic) doubleRestricts[0] else doubleRestricts[1] val mPos = if(isPublic){ if(isPublicPage) lastPosition else -1 }else{ if(isPublicPage) -1 else lastPosition } val isNetConnected = AppUtil.isNetworkConnected(mView) Observable.just(isNetConnected) .filter({connected -> connected}) .observeOn(AndroidSchedulers.mainThread()) .doOnNext({ page.srLayout.isRefreshing = true}) .observeOn(Schedulers.io()) .flatMap({ account.obsToken(mView) }) .flatMap({ token -> apiService.getIllustBookmarkTags(token,userPreferences.id?:0,restrict) }) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ response -> pageAdapter?.initNewData(response,mPos) },{ error -> Log.d("Error",error.printStackTrace().toString()) page.srLayout.isRefreshing = false },{ if(!isNetConnected) pageAdapter?.initNewData(null,mPos) page.srLayout.isRefreshing = false }) } interface Action{ fun doAction() } }
app/src/main/kotlin/views/adapters/drawer/drawerViewHolders.kt
3607456342
package com.michalfaber.drawertemplate.views.adapters.drawer import android.support.v7.widget.RecyclerView import android.view.View import android.widget.ImageView import android.widget.TextView import com.michalfaber.drawertemplate.R import com.michalfaber.drawertemplate.views.adapters.AdapterItem import com.michalfaber.drawertemplate.views.adapters.AdapterItemsSupervisor class ViewHolderMedium(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) { val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView val label: TextView = drawerItemView.findViewById(R.id.label) as TextView } class ViewHolderSmall(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) { val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView val label: TextView = drawerItemView.findViewById(R.id.label) as TextView } class ViewHolderSeparator(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) class ViewHolderHeader(drawerItemView: View) : RecyclerView.ViewHolder(drawerItemView) { val label: TextView = drawerItemView.findViewById(R.id.label) as TextView } class ViewHolderSpinner(drawerItemView: View, val supervisor: AdapterItemsSupervisor<AdapterItem>) : RecyclerView.ViewHolder(drawerItemView) { val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView val label: TextView = drawerItemView.findViewById(R.id.label) as TextView val action: ImageView = drawerItemView.findViewById(R.id.action) as ImageView } class ViewHolderSpinnerItem(drawerItemView: View, val supervisor: AdapterItemsSupervisor<AdapterItem>) : RecyclerView.ViewHolder(drawerItemView) { val icon: ImageView = drawerItemView.findViewById(R.id.icon) as ImageView val label: TextView = drawerItemView.findViewById(R.id.label) as TextView }
core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersions.kt
39342495
package info.nightscout.androidaps.plugins.constraints.versionChecker import org.joda.time.LocalDate import org.json.JSONArray import org.json.JSONException import org.json.JSONObject class AllowedVersions { fun findByApi(definition: String?, api: Int): JSONObject? { if (definition == null) return null try { val array = JSONArray(definition) for (i in 0 until array.length()) { val record = array[i] as JSONObject if (record.has("minAndroid") && record.has("maxAndroid")) if (api in record.getInt("minAndroid")..record.getInt("maxAndroid")) return record } } catch (e: JSONException) { } return null } fun findByVersion(definition: String?, version: String): JSONObject? { if (definition == null) return null try { val array = JSONArray(definition) for (i in 0 until array.length()) { val record = array[i] as JSONObject if (record.has("endDate") && record.has("version")) if (version == record.getString("version")) return record } } catch (e: JSONException) { } return null } fun endDateToMilliseconds(endDate: String): Long? { try { val dateTime = LocalDate.parse(endDate) return dateTime.toDate().time } catch (ignored: Exception) { } return null } }
features/settings/src/main/java/com/cryart/sabbathschool/settings/SSSettingsActivity.kt
1845686011
/* * Copyright (c) 2021. Adventech <[email protected]> * * 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.cryart.sabbathschool.settings import android.os.Bundle import android.view.MenuItem import com.cryart.sabbathschool.core.extensions.view.viewBinding import com.cryart.sabbathschool.core.misc.SSConstants import com.cryart.sabbathschool.core.misc.SSEvent import com.cryart.sabbathschool.core.ui.SSBaseActivity import com.cryart.sabbathschool.settings.databinding.SsSettingsActivityBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class SSSettingsActivity : SSBaseActivity() { private val binding by viewBinding(SsSettingsActivityBinding::inflate) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) setSupportActionBar(binding.ssToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportFragmentManager.beginTransaction().replace( R.id.ss_settings_frame, SSSettingsFragment.newInstance() ).commit() SSEvent.track(this, SSConstants.SS_EVENT_SETTINGS_OPEN) } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { finishAfterTransition() return true } else -> super.onOptionsItemSelected(item) } } }
src/main/kotlin/au/com/timmutton/redexplugin/DexFile.kt
64413387
/* * Copyright (C) 2015-2016 KeepSafe Software * * 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 au.com.timmutton.redexplugin import com.android.dexdeps.DexData import java.io.File import java.io.RandomAccessFile import java.util.* import java.util.Collections.emptyList import java.util.zip.ZipEntry import java.util.zip.ZipException import java.util.zip.ZipFile /** * A physical file and the {@link DexData} contained therein. * * A DexFile contains an open file, possibly a temp file. When consumers are * finished with the DexFile, it should be cleaned up with * {@link DexFile#dispose()}. */ class DexFile(val file: File, val isTemp: Boolean, val isInstantRun: Boolean = false) { val data: DexData val raf: RandomAccessFile = RandomAccessFile(file, "r") init { data = DexData(raf) data.load() } fun dispose() { raf.close() if (isTemp) { file.delete() } } companion object { /** * Extracts a list of {@link DexFile} instances from the given file. * * DexFiles can be extracted either from an Android APK file, or from a raw * {@code classes.dex} file. * * @param file the APK or dex file. * @return a list of DexFile objects representing data in the given file. */ fun extractDexData(file: File?): List<DexFile> { if (file == null || !file.exists()) { return emptyList() } try { return extractDexFromZip(file) } catch (e: ZipException) { // not a zip, no problem } return listOf(DexFile(file, false)) } /** * Attempts to unzip the file and extract all dex files inside of it. * * It is assumed that {@code file} is an APK file resulting from an Android * build, containing one or more appropriately-named classes.dex files. * * @param file the APK file from which to extract dex data. * @return a list of contained dex files. * @throws ZipException if {@code file} is not a zip file. */ fun extractDexFromZip(file: File): List<DexFile> = ZipFile(file).use { zipfile -> val entries = zipfile.entries().toList() val mainDexFiles = entries.filter { it.name.matches(Regex("classes.*\\.dex")) }.map { entry -> val temp = File.createTempFile("dexcount", ".dex") temp.deleteOnExit() zipfile.getInputStream(entry).use { input -> IOUtil.drainToFile(input, temp) } DexFile(temp, true) }.toMutableList() mainDexFiles.addAll(extractIncrementalDexFiles(zipfile, entries)) return mainDexFiles } /** * Attempts to extract dex files embedded in a nested instant-run.zip file * produced by Android Studio 2.0. If present, such files are extracted to * temporary files on disk and returned as a list. If not, an empty mutable * list is returned. * * @param apk the APK file from which to extract dex data. * @param zipEntries a list of ZipEntry objects inside of the APK. * @return a list, possibly empty, of instant-run dex data. */ fun extractIncrementalDexFiles(apk: ZipFile, zipEntries: List<ZipEntry>): List<DexFile> { val incremental = zipEntries.filter { (it.name == "instant-run.zip") } if (incremental.size != 1) { return emptyList() } val instantRunFile = File.createTempFile("instant-run", ".zip") instantRunFile.deleteOnExit() apk.getInputStream(incremental[0]).use { input -> IOUtil.drainToFile(input, instantRunFile) } ZipFile(instantRunFile).use { instantRunZip -> val entries = Collections.list(instantRunZip.entries()) val dexEntries = entries.filter { it.name.endsWith(".dex") } return dexEntries.map { entry -> val temp = File.createTempFile("dexcount", ".dex") temp.deleteOnExit() instantRunZip.getInputStream(entry).use { input -> IOUtil.drainToFile(input, temp) } DexFile(temp, true, true) } } } } }
wire-library/wire-runtime/src/nativeMain/kotlin/com/squareup/wire/internal/-Platform.kt
3953667716
/* * Copyright 2019 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. */ package com.squareup.wire.internal import okio.IOException actual interface Serializable actual abstract class ObjectStreamException : IOException() actual class ProtocolException actual constructor(host: String) : IOException(host) @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. actual inline fun <T> MutableList<T>.toUnmodifiableList(): List<T> = this @Suppress("NOTHING_TO_INLINE") // Syntactic sugar. actual inline fun <K, V> MutableMap<K, V>.toUnmodifiableMap(): Map<K, V> = this // TODO: Use code points to process each char. actual fun camelCase(string: String, upperCamel: Boolean): String { return buildString(string.length) { var index = 0 var uppercase = upperCamel while (index < string.length) { var char = string[index] index++ if (char == '_') { uppercase = true continue } if (uppercase) { if (char in 'a'..'z') char += 'A' - 'a' } append(char) uppercase = false } } }
app/core/src/main/java/com/fsck/k9/notification/NotificationStoreProvider.kt
4118326149
package com.fsck.k9.notification import com.fsck.k9.Account interface NotificationStoreProvider { fun getNotificationStore(account: Account): NotificationStore }
lib/src/main/java/ua/at/tsvetkov/files/FileDownloader.kt
1392377591
/** * **************************************************************************** * Copyright (c) 2014 Alexandr Tsvetkov. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * * Contributors: * Alexandr Tsvetkov - initial API and implementation * * * Project: * TAO Core * * * License agreement: * * * 1. This code is published AS IS. Author is not responsible for any damage that can be * caused by any application that uses this code. * 2. Author does not give a garantee, that this code is error free. * 3. This code can be used in NON-COMMERCIAL applications AS IS without any special * permission from author. * 4. This code can be modified without any special permission from author IF AND ONLY IF * this license agreement will remain unchanged. * **************************************************************************** */ package ua.at.tsvetkov.files import ua.at.tsvetkov.util.Log import java.io.* import java.net.HttpURLConnection import java.net.URL import java.net.URLEncoder /** * Methods for downloading files from the Internet * * @author A.Tsvetkov 2013 http://tsvetkov.at.ua mailto:[email protected] */ class FileDownloader { abstract inner class CompleteListener { abstract fun complete(fileName: String, result: Boolean) } companion object { val TIMEOUT = 10000 val BUFFER = 8192 /** * Returns the content length in bytes specified by the response header field content-length or -1 if this field is not set. * * @param url url path to file * @return the value of the response header field content-length */ @JvmStatic fun getFileLength(url: String): Int { var conn: HttpURLConnection? = null var length = 0 try { conn = URL(url).openConnection() as HttpURLConnection conn.setRequestProperty("keep-alive", "false") conn.doInput = true conn.connectTimeout = TIMEOUT conn.connect() length = conn.contentLength } catch (e: Exception) { Log.e(e) } finally { if (conn != null) conn.disconnect() } return length } /** * Async downloads a remote file and stores it locally. * * @param url Remote URL of the file to download * @param pathAndFileName Local path with file name where to store the file * @param rewrite If TRUE and file exist - rewrite the file. If FALSE and file exist and his length > 0 - not download and rewrite the * file. */ @JvmStatic fun download(url: String, pathAndFileName: String, rewrite: Boolean, listener: CompleteListener) { Thread(Runnable { val result = download(url, pathAndFileName, rewrite) listener.complete(url, result) }, "Download thread: $url").start() } /** * Downloads a remote file and stores it locally. * * @param url Remote URL of the file to download. If the string contains spaces, they are replaced by "%20". * @param pathAndFileName Local path with file name where to store the file * @param rewrite If TRUE and file exist - rewrite the file. If FALSE and file exist and his length > 0 - not download and rewrite the file. * @return true if success */ @JvmOverloads @JvmStatic fun download(url: String, pathAndFileName: String, rewrite: Boolean = true): Boolean { var urlEnc: String? = null var conn: HttpURLConnection? = null val input: InputStream var output: FileOutputStream? = null try { urlEnc = URLEncoder.encode(url, "UTF-8") } catch (e: UnsupportedEncodingException) { Log.e("Wrong url", e) } val f = File(pathAndFileName) if (!rewrite && f.exists() && f.length() > 0) { Log.w("File exist: $pathAndFileName") return true } try { conn = URL(urlEnc).openConnection() as HttpURLConnection conn.setRequestProperty("keep-alive", "false") conn.doInput = true conn.connectTimeout = TIMEOUT conn.connect() val fileLength = conn.contentLength if (fileLength == 0) { Log.v("File is empty, length = 0 > $url") } input = conn.inputStream output = FileOutputStream(pathAndFileName) val buffer = ByteArray(BUFFER) var bytesRead: Int while (true) { bytesRead = input.read(buffer) if (bytesRead < 0) break output.write(buffer, 0, bytesRead) } output.flush() } catch (e: IOException) { Log.w("Download error $url", e) return false } finally { if (conn != null) conn.disconnect() try { output!!.close() } catch (e: IOException) { Log.e("Error closing file > $pathAndFileName", e) return false } } return true } } }
app/storage/src/test/java/com/fsck/k9/storage/messages/FolderHelpers.kt
2641943784
package com.fsck.k9.storage.messages import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import com.fsck.k9.helper.getIntOrNull import com.fsck.k9.helper.getLongOrNull import com.fsck.k9.helper.getStringOrNull import com.fsck.k9.helper.map fun SQLiteDatabase.createFolder( name: String = "irrelevant", type: String = "regular", serverId: String? = null, isLocalOnly: Boolean = true, integrate: Boolean = false, inTopGroup: Boolean = false, displayClass: String = "NO_CLASS", syncClass: String? = "INHERITED", notifyClass: String? = "INHERITED", pushClass: String? = "SECOND_CLASS", lastUpdated: Long = 0L, unreadCount: Int = 0, visibleLimit: Int = 25, status: String? = null, flaggedCount: Int = 0, moreMessages: String = "unknown", ): Long { val values = ContentValues().apply { put("name", name) put("type", type) put("server_id", serverId) put("local_only", isLocalOnly) put("integrate", integrate) put("top_group", inTopGroup) put("display_class", displayClass) put("poll_class", syncClass) put("notify_class", notifyClass) put("push_class", pushClass) put("last_updated", lastUpdated) put("unread_count", unreadCount) put("visible_limit", visibleLimit) put("status", status) put("flagged_count", flaggedCount) put("more_messages", moreMessages) } return insert("folders", null, values) } fun SQLiteDatabase.readFolders(): List<FolderEntry> { val cursor = rawQuery("SELECT * FROM folders", null) return cursor.use { cursor.map { FolderEntry( id = cursor.getLongOrNull("id"), name = cursor.getStringOrNull("name"), type = cursor.getStringOrNull("type"), serverId = cursor.getStringOrNull("server_id"), isLocalOnly = cursor.getIntOrNull("local_only"), integrate = cursor.getIntOrNull("integrate"), inTopGroup = cursor.getIntOrNull("top_group"), displayClass = cursor.getStringOrNull("display_class"), syncClass = cursor.getStringOrNull("poll_class"), notifyClass = cursor.getStringOrNull("notify_class"), pushClass = cursor.getStringOrNull("push_class"), lastUpdated = cursor.getLongOrNull("last_updated"), unreadCount = cursor.getIntOrNull("unread_count"), visibleLimit = cursor.getIntOrNull("visible_limit"), status = cursor.getStringOrNull("status"), flaggedCount = cursor.getIntOrNull("flagged_count"), moreMessages = cursor.getStringOrNull("more_messages") ) } } } data class FolderEntry( val id: Long?, val name: String?, val type: String?, val serverId: String?, val isLocalOnly: Int?, val integrate: Int?, val inTopGroup: Int?, val displayClass: String?, val syncClass: String?, val notifyClass: String?, val pushClass: String?, val lastUpdated: Long?, val unreadCount: Int?, val visibleLimit: Int?, val status: String?, val flaggedCount: Int?, val moreMessages: String? )
bridgesample/src/main/java/com/livefront/bridgesample/base/NonBridgeBaseActivity.kt
2803990590
package com.livefront.bridgesample.base import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.evernote.android.state.StateSaver abstract class NonBridgeBaseActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) StateSaver.restoreInstanceState(this, savedInstanceState) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) StateSaver.saveInstanceState(this, outState) } }
plugins/git4idea/src/git4idea/pull/GitPullDialog.kt
80103580
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package git4idea.pull import com.intellij.codeInsight.hint.HintUtil import com.intellij.dvcs.DvcsUtil.sortRepositories import com.intellij.ide.actions.RefreshAction import com.intellij.ide.ui.laf.darcula.DarculaUIUtil.BW import com.intellij.openapi.actionSystem.* import com.intellij.openapi.components.service import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.Task.Backgroundable import com.intellij.openapi.project.Project import com.intellij.openapi.ui.ComboBox import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.ui.ValidationInfo import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.HtmlChunk import com.intellij.openapi.util.text.HtmlChunk.Element.html import com.intellij.openapi.vcs.VcsNotifier import com.intellij.openapi.vfs.VirtualFile import com.intellij.ui.MutableCollectionComboBoxModel import com.intellij.ui.SimpleListCellRenderer import com.intellij.ui.components.DropDownLink import com.intellij.util.ui.JBDimension import com.intellij.util.ui.JBUI import git4idea.GitNotificationIdsHolder.Companion.FETCH_ERROR import git4idea.GitRemoteBranch import git4idea.GitUtil import git4idea.GitVcs import git4idea.branch.GitBranchUtil import git4idea.config.GitExecutableManager import git4idea.config.GitPullSettings import git4idea.config.GitVersionSpecialty.NO_VERIFY_SUPPORTED import git4idea.fetch.GitFetchSupport import git4idea.i18n.GitBundle import git4idea.merge.GIT_REF_PROTOTYPE_VALUE import git4idea.merge.createRepositoryField import git4idea.merge.createSouthPanelWithOptionsDropDown import git4idea.merge.dialog.* import git4idea.merge.validateBranchExists import git4idea.repo.GitRemote import git4idea.repo.GitRepository import git4idea.repo.GitRepositoryManager import git4idea.ui.ComboBoxWithAutoCompletion import net.miginfocom.layout.AC import net.miginfocom.layout.CC import net.miginfocom.layout.LC import net.miginfocom.swing.MigLayout import java.awt.Insets import java.awt.event.ItemEvent import java.awt.event.KeyEvent import javax.swing.JComponent import javax.swing.JPanel import javax.swing.KeyStroke import javax.swing.SwingConstants class GitPullDialog(private val project: Project, private val roots: List<VirtualFile>, private val defaultRoot: VirtualFile) : DialogWrapper(project) { val selectedOptions = mutableSetOf<GitPullOption>() private val fetchSupport = project.service<GitFetchSupport>() private val pullSettings = project.service<GitPullSettings>() private val repositories = sortRepositories(GitRepositoryManager.getInstance(project).repositories) private val branches = collectBranches().toMutableMap() private val optionInfos = mutableMapOf<GitPullOption, OptionInfo<GitPullOption>>() private val popupBuilder = createPopupBuilder() private val repositoryField = createRepoField() private val remoteField = createRemoteField() private val branchField = createBranchField() private val commandPanel = createCommandPanel() private val optionsPanel = GitOptionsPanel(::optionChosen, ::getOptionInfo) private val panel = createPanel() private val isNoVerifySupported = NO_VERIFY_SUPPORTED.existsIn(GitExecutableManager.getInstance().getVersion(project)) init { updateTitle() setOKButtonText(GitBundle.message("pull.button")) loadSettings() updateRemotesField() init() updateUi() } override fun createCenterPanel() = panel override fun getPreferredFocusedComponent() = branchField override fun createSouthPanel() = createSouthPanelWithOptionsDropDown(super.createSouthPanel(), createOptionsDropDown()) override fun getHelpId() = "reference.VersionControl.Git.Pull" override fun doValidateAll() = listOf(::validateRepositoryField, ::validateRemoteField, ::validateBranchField).mapNotNull { it() } override fun doOKAction() { try { saveSettings() } finally { super.doOKAction() } } fun gitRoot() = getSelectedRepository()?.root ?: error("No selected repository found") fun getSelectedRemote(): GitRemote = remoteField.item ?: error("No selected remote found") fun getSelectedBranch(): GitRemoteBranch { val repository = getSelectedRepository() ?: error("No selected repository found") val remote = getSelectedRemote() val branchName = "${remote.name}/${branchField.item}" return repository.branches.findRemoteBranch(branchName) ?: error("Unable to find remote branch: $branchName") } fun isCommitAfterMerge() = GitPullOption.NO_COMMIT !in selectedOptions private fun getRemote(): GitRemote? = remoteField.item private fun loadSettings() { selectedOptions += pullSettings.options } private fun saveSettings() { pullSettings.options = selectedOptions } private fun collectBranches() = repositories.associateWith { repository -> getBranchesInRepo(repository) } private fun getBranchesInRepo(repository: GitRepository) = repository.branches.remoteBranches .sortedBy { branch -> branch.nameForRemoteOperations } .groupBy { branch -> branch.remote } private fun validateRepositoryField(): ValidationInfo? { return if (getSelectedRepository() != null) null else ValidationInfo(GitBundle.message("pull.repository.not.selected.error"), repositoryField) } private fun validateRemoteField(): ValidationInfo? { return if (getRemote() != null) null else ValidationInfo(GitBundle.message("pull.remote.not.selected"), remoteField) } private fun validateBranchField() = validateBranchExists(branchField, GitBundle.message("pull.branch.not.selected.error")) private fun getSelectedRepository(): GitRepository? = repositoryField.item private fun updateRemotesField() { val repository = getSelectedRepository() val model = remoteField.model as MutableCollectionComboBoxModel model.update(repository?.remotes?.toList() ?: emptyList()) model.selectedItem = getCurrentOrDefaultRemote(repository) } private fun updateBranchesField() { var branchToSelect = branchField.item val repository = getSelectedRepository() ?: return val remote = getRemote() ?: return val branches = GitBranchUtil.sortBranchNames(getRemoteBranches(repository, remote)) val model = branchField.model as MutableCollectionComboBoxModel model.update(branches) if (branchToSelect == null || branchToSelect !in branches) { branchToSelect = repository.currentBranch?.findTrackedBranch(repository)?.nameForRemoteOperations ?: branches.find { branch -> branch == repository.currentBranchName } ?: "" } if (branchToSelect.isEmpty()) { startTrackingValidation() } branchField.selectedItem = branchToSelect } private fun getRemoteBranches(repository: GitRepository, remote: GitRemote): List<String> { return branches[repository]?.get(remote)?.map { it.nameForRemoteOperations } ?: emptyList() } private fun getCurrentOrDefaultRemote(repository: GitRepository?): GitRemote? { val remotes = repository?.remotes ?: return null if (remotes.isEmpty()) { return null } return GitUtil.getTrackInfoForCurrentBranch(repository)?.remote ?: GitUtil.getDefaultOrFirstRemote(remotes) } private fun optionChosen(option: GitPullOption) { if (option !in selectedOptions) { selectedOptions += option } else { selectedOptions -= option } updateUi() } private fun performFetch() { if (fetchSupport.isFetchRunning) { return } val repository = getSelectedRepository() val remote = getRemote() if (repository == null || remote == null) { VcsNotifier.getInstance(project).notifyError(FETCH_ERROR, GitBundle.message("pull.fetch.failed.notification.title"), GitBundle.message("pull.fetch.failed.notification.text")) return } GitVcs.runInBackground(getFetchTask(repository, remote)) } private fun getFetchTask(repository: GitRepository, remote: GitRemote) = object : Backgroundable(project, GitBundle.message("fetching"), true) { override fun run(indicator: ProgressIndicator) { fetchSupport.fetch(repository, remote) } override fun onSuccess() { branches[repository] = getBranchesInRepo(repository) if (getSelectedRepository() == repository && getRemote() == remote) { updateBranchesField() } } } private fun createPopupBuilder() = GitOptionsPopupBuilder( project, GitBundle.message("pull.options.modify.popup.title"), ::getOptions, ::getOptionInfo, ::isOptionSelected, ::isOptionEnabled, ::optionChosen ) private fun isOptionSelected(option: GitPullOption) = option in selectedOptions private fun createOptionsDropDown() = DropDownLink(GitBundle.message("merge.options.modify")) { popupBuilder.createPopup() }.apply { mnemonic = KeyEvent.VK_M } private fun getOptionInfo(option: GitPullOption) = optionInfos.computeIfAbsent(option) { OptionInfo(option, option.option, option.description) } private fun getOptions(): List<GitPullOption> = GitPullOption.values().toMutableList().apply { if (!isNoVerifySupported) { remove(GitPullOption.NO_VERIFY) } } private fun updateUi() { optionsPanel.rerender(selectedOptions) rerender() } private fun rerender() { window.pack() window.revalidate() pack() repaint() } private fun isOptionEnabled(option: GitPullOption) = selectedOptions.all { it.isOptionSuitable(option) } private fun updateTitle() { val currentBranchName = getSelectedRepository()?.currentBranchName title = (if (currentBranchName.isNullOrEmpty()) GitBundle.message("pull.dialog.title") else GitBundle.message("pull.dialog.with.branch.title", currentBranchName)) } private fun createPanel() = JPanel().apply { layout = MigLayout(LC().insets("0").hideMode(3), AC().grow()) add(commandPanel, CC().growX()) add(optionsPanel, CC().newline().width("100%").alignY("top")) } private fun showRootField() = roots.size > 1 private fun createCommandPanel() = JPanel().apply { val colConstraints = if (showRootField()) AC().grow(100f, 0, 3) else AC().grow(100f, 2) layout = MigLayout( LC() .fillX() .insets("0") .gridGap("0", "0") .noVisualPadding(), colConstraints) if (showRootField()) { add(repositoryField, CC() .gapAfter("0") .minWidth("${JBUI.scale(115)}px") .growX()) } add(createCmdLabel(), CC() .gapAfter("0") .alignY("top") .minWidth("${JBUI.scale(85)}px")) add(remoteField, CC() .alignY("top") .minWidth("${JBUI.scale(90)}px")) add(branchField, CC() .alignY("top") .minWidth("${JBUI.scale(250)}px") .growX()) } private fun createCmdLabel() = CmdLabel("git pull", Insets(1, if (showRootField()) 0 else 1, 1, 0), JBDimension(JBUI.scale(85), branchField.preferredSize.height, true)) private fun createRepoField() = createRepositoryField(repositories, defaultRoot).apply { addActionListener { updateTitle() updateRemotesField() } } private fun createRemoteField() = ComboBox<GitRemote>(MutableCollectionComboBoxModel()).apply { isSwingPopup = false renderer = SimpleListCellRenderer.create( HtmlChunk.text(GitBundle.message("util.remote.renderer.none")).italic().wrapWith(html()).toString() ) { it.name } setUI(FlatComboBoxUI( outerInsets = Insets(BW.get(), 0, BW.get(), 0), popupEmptyText = GitBundle.message("pull.branch.no.matching.remotes"))) item = getCurrentOrDefaultRemote(getSelectedRepository()) addItemListener { e -> if (e.stateChange == ItemEvent.SELECTED) { updateBranchesField() } } } private fun createBranchField() = ComboBoxWithAutoCompletion(MutableCollectionComboBoxModel(mutableListOf<String>()), project).apply { prototypeDisplayValue = GIT_REF_PROTOTYPE_VALUE setPlaceholder(GitBundle.message("pull.branch.field.placeholder")) object : RefreshAction() { override fun actionPerformed(e: AnActionEvent) { popup?.hide() performFetch() } override fun update(e: AnActionEvent) { e.presentation.isEnabled = true } }.registerCustomShortcutSet(getFetchActionShortcut(), this) setUI(FlatComboBoxUI( Insets(1, 0, 1, 1), Insets(BW.get(), 0, BW.get(), BW.get()), GitBundle.message("pull.branch.nothing.to.pull"), this@GitPullDialog::createBranchFieldPopupComponent)) } private fun createBranchFieldPopupComponent(content: JComponent) = JPanel().apply { layout = MigLayout(LC().insets("0")) add(content, CC().width("100%")) val hintLabel = HintUtil.createAdComponent( GitBundle.message("pull.dialog.fetch.shortcuts.hint", getFetchActionShortcutText()), JBUI.CurrentTheme.BigPopup.advertiserBorder(), SwingConstants.LEFT) hintLabel.preferredSize = JBDimension.create(hintLabel.preferredSize, true) .withHeight(17) add(hintLabel, CC().newline().width("100%")) } private fun getFetchActionShortcut(): ShortcutSet { val refreshActionShortcut = ActionManager.getInstance().getAction(IdeActions.ACTION_REFRESH).shortcutSet if (refreshActionShortcut.shortcuts.isNotEmpty()) { return refreshActionShortcut } else { return FETCH_ACTION_SHORTCUT } } private fun getFetchActionShortcutText() = KeymapUtil.getPreferredShortcutText(getFetchActionShortcut().shortcuts) companion object { private val FETCH_ACTION_SHORTCUT = if (SystemInfo.isMac) CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.META_DOWN_MASK)) else CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_F5, KeyEvent.CTRL_DOWN_MASK)) } }
src/main/kotlin/failchat/chat/Link.kt
3033238335
package failchat.chat /** * Класс, сериализующийся в json для отправки к websocket клиентам. */ data class Link( val fullUrl: String, val domain: String, val shortUrl: String ) : MessageElement
src/main/java/com/maddyhome/idea/vim/ui/ex/ExEditorKit.kt
2809678845
/* * Copyright 2003-2022 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package com.maddyhome.idea.vim.ui.ex import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.diagnostic.logger import com.maddyhome.idea.vim.KeyHandler import com.maddyhome.idea.vim.helper.EditorDataContext import com.maddyhome.idea.vim.newapi.vim import org.jetbrains.annotations.NonNls import java.awt.event.ActionEvent import java.awt.event.KeyEvent import javax.swing.Action import javax.swing.KeyStroke import javax.swing.text.DefaultEditorKit import javax.swing.text.Document import javax.swing.text.TextAction object ExEditorKit : DefaultEditorKit() { @NonNls val CancelEntry: String = "cancel-entry" @NonNls val CompleteEntry: String = "complete-entry" @NonNls val EscapeChar: String = "escape" @NonNls val DeleteToCursor: String = "delete-to-cursor" @NonNls val ToggleInsertReplace: String = "toggle-insert" @NonNls val InsertRegister: String = "insert-register" @NonNls val HistoryUp: String = "history-up" @NonNls val HistoryDown: String = "history-down" @NonNls val HistoryUpFilter: String = "history-up-filter" @NonNls val HistoryDownFilter: String = "history-down-filter" @NonNls val StartDigraph: String = "start-digraph" @NonNls val StartLiteral: String = "start-literal" private val logger = logger<ExEditorKit>() /** * Gets the MIME type of the data that this * kit represents support for. * * @return the type */ @NonNls override fun getContentType(): String { return "text/ideavim" } /** * Fetches the set of commands that can be used * on a text component that is using a model and * view produced by this kit. * * @return the set of actions */ override fun getActions(): Array<Action> { val res = TextAction.augmentList(super.getActions(), exActions) logger.debug { "res.length=${res.size}" } return res } /** * Creates an uninitialized text storage model * that is appropriate for this type of editor. * * @return the model */ override fun createDefaultDocument(): Document { return ExDocument() } private val exActions = arrayOf<Action>( CancelEntryAction(), CompleteEntryAction(), EscapeCharAction(), DeleteNextCharAction(), DeletePreviousCharAction(), DeletePreviousWordAction(), DeleteToCursorAction(), HistoryUpAction(), HistoryDownAction(), HistoryUpFilterAction(), HistoryDownFilterAction(), ToggleInsertReplaceAction(), InsertRegisterAction() ) class DefaultExKeyHandler : DefaultKeyTypedAction() { override fun actionPerformed(e: ActionEvent) { val target = getTextComponent(e) as ExTextField val currentAction = target.currentAction if (currentAction != null) { currentAction.actionPerformed(e) } else { val key = convert(e) if (key != null) { val c = key.keyChar if (c.code > 0) { if (target.useHandleKeyFromEx) { val entry = ExEntryPanel.getInstance().entry val editor = entry.editor KeyHandler.getInstance().handleKey(editor.vim, key, EditorDataContext.init(editor, entry.context).vim) } else { val event = ActionEvent(e.source, e.id, c.toString(), e.getWhen(), e.modifiers) super.actionPerformed(event) } target.saveLastEntry() } } else { super.actionPerformed(e) target.saveLastEntry() } } } } fun convert(event: ActionEvent): KeyStroke? { val cmd = event.actionCommand val mods = event.modifiers if (cmd != null && cmd.isNotEmpty()) { val ch = cmd[0] if (ch < ' ') { if (mods and ActionEvent.CTRL_MASK != 0) { return KeyStroke.getKeyStroke(KeyEvent.VK_A + ch.code - 1, mods) } } else { return KeyStroke.getKeyStroke(Character.valueOf(ch), mods) } } return null } }
android/src/main/java/org/ligi/passandroid/model/comparator/PassByTimeComparator.kt
1790510558
package org.ligi.passandroid.model.comparator import org.ligi.passandroid.model.pass.Pass import org.threeten.bp.ZonedDateTime import java.util.* open class PassByTimeComparator : Comparator<Pass> { override fun compare(lhs: Pass, rhs: Pass): Int { return calculateCompareForNullValues(lhs, rhs) { leftDate: ZonedDateTime, rightDate: ZonedDateTime -> return@calculateCompareForNullValues leftDate.compareTo(rightDate) } } protected fun calculateCompareForNullValues(lhs: Pass, rhs: Pass, foo: (leftDate: ZonedDateTime, rightDate: ZonedDateTime) -> Int): Int { val leftDate = extractPassDate(lhs) val rightDate = extractPassDate(rhs) if (leftDate == rightDate) { return 0 } if (leftDate == null) { return 1 } if (rightDate == null) { return -1 } return foo(leftDate, rightDate) } private fun extractPassDate(pass: Pass): ZonedDateTime? { if (pass.calendarTimespan != null && pass.calendarTimespan!!.from != null) { return pass.calendarTimespan!!.from } if (pass.validTimespans != null && pass.validTimespans!!.isNotEmpty()) { return pass.validTimespans!![0].from } return null } }
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/alignment/AroundAlignmentStrategy.kt
184041063
package org.hexworks.zircon.internal.component.alignment import org.hexworks.zircon.api.behavior.Boundable import org.hexworks.zircon.api.component.AlignmentStrategy import org.hexworks.zircon.api.component.ComponentAlignment import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size /** * Can be used to align objects **around** an [other] [Boundable] * object. This means that [calculatePosition] will return a [Position] * for which [Boundable.containsPosition] will return `false` when * called on [other]. */ data class AroundAlignmentStrategy( private val other: Boundable, private val alignmentType: ComponentAlignment ) : AlignmentStrategy { override fun calculatePosition(size: Size): Position { return alignmentType.alignAround(other.rect, size) } }
MADSkillsNavigationSample/app/src/main/java/com/android/samples/donuttracker/DonutListViewModel.kt
3011761226
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.samples.donuttracker import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.samples.donuttracker.storage.DonutDao import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch /** * This ViewModel is used to access the underlying data and to observe changes to it. */ class DonutListViewModel(private val donutDao: DonutDao) : ViewModel() { // Users of this ViewModel will observe changes to its donuts list to know when // to redisplay those changes val donuts: LiveData<List<Donut>> = donutDao.getAll() fun delete(donut: Donut) = viewModelScope.launch(Dispatchers.IO) { donutDao.delete(donut) } }
WordPress/src/main/java/org/wordpress/android/ui/pages/SearchListFragment.kt
1902726588
package org.wordpress.android.ui.pages import android.os.Bundle import android.os.Parcelable import android.view.View import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.wordpress.android.R import org.wordpress.android.WordPress import org.wordpress.android.databinding.PagesListFragmentBinding import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.DisplayUtils import org.wordpress.android.viewmodel.pages.PagesViewModel import org.wordpress.android.viewmodel.pages.SearchListViewModel import org.wordpress.android.widgets.RecyclerItemDecoration import javax.inject.Inject class SearchListFragment : Fragment(R.layout.pages_list_fragment) { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory private lateinit var viewModel: SearchListViewModel private var linearLayoutManager: LinearLayoutManager? = null @Inject lateinit var uiHelper: UiHelpers private val listStateKey = "list_state" companion object { fun newInstance(): SearchListFragment { return SearchListFragment() } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val nonNullActivity = requireActivity() (nonNullActivity.application as? WordPress)?.component()?.inject(this) with(PagesListFragmentBinding.bind(view)) { initializeViews(savedInstanceState) initializeViewModels(nonNullActivity) } } override fun onSaveInstanceState(outState: Bundle) { linearLayoutManager?.let { outState.putParcelable(listStateKey, it.onSaveInstanceState()) } super.onSaveInstanceState(outState) } private fun PagesListFragmentBinding.initializeViewModels(activity: FragmentActivity) { val pagesViewModel = ViewModelProvider(activity, viewModelFactory).get(PagesViewModel::class.java) viewModel = ViewModelProvider(this@SearchListFragment, viewModelFactory).get(SearchListViewModel::class.java) viewModel.start(pagesViewModel) setupObservers() } private fun PagesListFragmentBinding.initializeViews(savedInstanceState: Bundle?) { val layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) savedInstanceState?.getParcelable<Parcelable>(listStateKey)?.let { layoutManager.onRestoreInstanceState(it) } linearLayoutManager = layoutManager recyclerView.layoutManager = linearLayoutManager recyclerView.addItemDecoration(RecyclerItemDecoration(0, DisplayUtils.dpToPx(activity, 1))) recyclerView.id = R.id.pages_search_recycler_view_id } private fun PagesListFragmentBinding.setupObservers() { viewModel.searchResult.observe(viewLifecycleOwner, Observer { data -> data?.let { setSearchResult(data) } }) } private fun PagesListFragmentBinding.setSearchResult(pages: List<PageItem>) { val adapter: PageSearchAdapter if (recyclerView.adapter == null) { adapter = PageSearchAdapter( { action, page -> viewModel.onMenuAction(action, page, requireContext()) }, { page -> viewModel.onItemTapped(page) }, uiHelper) recyclerView.adapter = adapter } else { adapter = recyclerView.adapter as PageSearchAdapter } adapter.update(pages) } }
app/src/main/java/forpdateam/ru/forpda/ui/fragments/qms/chat/QmsChatJsInterface.kt
2543395831
package forpdateam.ru.forpda.ui.fragments.qms.chat import android.webkit.JavascriptInterface import forpdateam.ru.forpda.presentation.qms.chat.IQmsChatPresenter import forpdateam.ru.forpda.ui.fragments.BaseJsInterface class QmsChatJsInterface( private val presenter: IQmsChatPresenter ) : BaseJsInterface() { @JavascriptInterface fun loadMoreMessages() = runInUiThread(Runnable { presenter.loadMoreMessages() }) }
test-app/app/src/main/java/com/tns/tests/kotlin/companions/BaseKotlinClassWithCompanion.kt
1141498642
package com.tns.tests.kotlin.companions abstract class BaseKotlinClassWithCompanion { companion object { public fun getString() = "someString" } }
mobile/app/src/main/kotlin/com/radikal/pcnotifications/model/validators/Validator.kt
2173214348
package com.radikal.pcnotifications.model.validators /** * Created by tudor on 27.12.2016. */ interface Validator<in T> { fun isValid(obj: T): Boolean }
plugins/kotlin/idea/tests/testData/multiplatform/languageConstructions/common/common.kt
2693934575
package sample expect class <!LINE_MARKER("descr='Has actuals in jvm module'")!>A<!> { fun <!LINE_MARKER("descr='Has actuals in jvm module'")!>commonFun<!>() val <!LINE_MARKER("descr='Has actuals in jvm module'")!>x<!>: Int val <!LINE_MARKER("descr='Has actuals in jvm module'")!>y<!>: Double val <!LINE_MARKER("descr='Has actuals in jvm module'")!>z<!>: String } fun getCommonA(): A = null!!
plugins/kotlin/frontend-independent/src/org/jetbrains/kotlin/idea/util/trackerUtils.kt
1497319486
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.util import com.intellij.openapi.project.Project import com.intellij.psi.util.CachedValue import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import com.intellij.psi.util.PsiModificationTracker import kotlin.reflect.KProperty @Suppress("NOTHING_TO_INLINE") inline operator fun <T> CachedValue<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value inline fun <T> cachedValue(project: Project, vararg dependencies: Any, crossinline createValue: () -> T) = CachedValuesManager.getManager(project).createCachedValue { CachedValueProvider.Result( createValue(), dependencies ) } /** * Creates a value which will be cached until until any physical PSI change happens * * @see com.intellij.psi.util.CachedValue * @see com.intellij.psi.util.PsiModificationTracker.MODIFICATION_COUNT */ fun <T> psiModificationTrackerBasedCachedValue(project: Project, createValue: () -> T) = cachedValue(project, PsiModificationTracker.MODIFICATION_COUNT, createValue = createValue)
feature/author/src/main/java/com/google/samples/apps/nowinandroid/feature/author/navigation/AuthorNavigation.kt
1952266938
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.nowinandroid.feature.author.navigation import android.net.Uri import androidx.annotation.VisibleForTesting import androidx.lifecycle.SavedStateHandle import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.NavType import androidx.navigation.compose.composable import androidx.navigation.navArgument import com.google.samples.apps.nowinandroid.core.decoder.StringDecoder import com.google.samples.apps.nowinandroid.feature.author.AuthorRoute @VisibleForTesting internal const val authorIdArg = "authorId" internal class AuthorArgs(val authorId: String) { constructor(savedStateHandle: SavedStateHandle, stringDecoder: StringDecoder) : this(stringDecoder.decodeString(checkNotNull(savedStateHandle[authorIdArg]))) } fun NavController.navigateToAuthor(authorId: String) { val encodedString = Uri.encode(authorId) this.navigate("author_route/$encodedString") } fun NavGraphBuilder.authorScreen( onBackClick: () -> Unit ) { composable( route = "author_route/{$authorIdArg}", arguments = listOf( navArgument(authorIdArg) { type = NavType.StringType } ) ) { AuthorRoute(onBackClick = onBackClick) } }
common/src/main/kotlin/rs/emulate/common/config/varbit/VarbitDefinition.kt
1709308912
package rs.emulate.common.config.varbit import rs.emulate.common.config.Definition /** * A definition for a bit variable ('varbit'). */ class VarbitDefinition( override val id: Int, var varp: Int = 0, var low: Int = 0, var high: Int = 0 ) : Definition { companion object { val MASKS = IntArray(32) { index -> (Math.pow(2.0, index.toDouble()) - 1).toInt() }.also { it[31] = -1 } } }
plugins/OrchidPosts/src/main/kotlin/com/eden/orchid/posts/permalink/pathtypes/MonthPathType.kt
1750960173
package com.eden.orchid.posts.permalink.pathtypes import com.eden.orchid.api.theme.pages.OrchidPage import com.eden.orchid.api.theme.permalinks.PermalinkPathType import com.eden.orchid.posts.pages.PostPage import javax.inject.Inject class MonthPathType @Inject constructor() : PermalinkPathType() { override fun acceptsKey(page: OrchidPage, key: String): Boolean { return key == "month" } override fun format(page: OrchidPage, key: String): String? { return if (page is PostPage) { "${page.month}" } else "${page.publishDate.monthValue}" } }
app/src/main/java/io/ipoli/android/planday/job/PlanDayScheduler.kt
4050626322
package io.ipoli.android.planday.job import android.app.NotificationManager import android.content.Context import android.graphics.BitmapFactory import android.net.Uri import android.widget.Toast import com.evernote.android.job.Job import com.evernote.android.job.JobRequest import io.ipoli.android.Constants import io.ipoli.android.MyPoliApp import io.ipoli.android.R import io.ipoli.android.common.IntentUtil import io.ipoli.android.common.datetime.Duration import io.ipoli.android.common.datetime.Minute import io.ipoli.android.common.datetime.minutes import io.ipoli.android.common.di.BackgroundModule import io.ipoli.android.common.job.FixedDailyJob import io.ipoli.android.common.job.FixedDailyJobScheduler import io.ipoli.android.common.notification.NotificationUtil import io.ipoli.android.common.notification.ScreenUtil import io.ipoli.android.common.view.asThemedWrapper import io.ipoli.android.dailychallenge.data.DailyChallenge import io.ipoli.android.pet.AndroidPetAvatar import io.ipoli.android.pet.Pet import io.ipoli.android.player.data.Player import io.ipoli.android.player.data.Player.Preferences.NotificationStyle import io.ipoli.android.quest.reminder.PetNotificationPopup import kotlinx.coroutines.experimental.Dispatchers import kotlinx.coroutines.experimental.GlobalScope import kotlinx.coroutines.experimental.launch import org.threeten.bp.LocalDate import space.traversal.kapsule.Kapsule import java.util.* /** * Created by Venelin Valkov <[email protected]> * on 05/18/2018. */ object PlanDayNotification { fun show( context: Context, player: Player, planDayScheduler: PlanDayScheduler ) { val pet = player.pet val c = context.asThemedWrapper() ScreenUtil.awakeScreen(c) val notificationManager = c.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val style = player.preferences.planDayNotificationStyle var notificationId: Int? = showNotification(c, pet, notificationManager) if (!(style == NotificationStyle.NOTIFICATION || style == NotificationStyle.ALL)) { notificationManager.cancel(notificationId!!) notificationId = null } if (style == NotificationStyle.POPUP || style == NotificationStyle.ALL) { val vm = PetNotificationPopup.ViewModel( headline = "Time to plan your day", title = null, body = null, petAvatar = pet.avatar, petState = pet.state, doTextRes = R.string.start, doImageRes = R.drawable.ic_play_arrow_white_32dp ) showPetPopup(vm, notificationId, notificationManager, planDayScheduler, c).show(c) } } private fun showPetPopup( vm: PetNotificationPopup.ViewModel, notificationId: Int?, notificationManager: NotificationManager, planDayScheduler: PlanDayScheduler, context: Context ) = PetNotificationPopup( vm, onDismiss = { notificationId?.let { notificationManager.cancel(it) } }, onSnooze = { notificationId?.let { notificationManager.cancel(it) } GlobalScope.launch(Dispatchers.IO) { planDayScheduler.scheduleAfter(15.minutes) } Toast .makeText(context, context.getString(R.string.remind_in_15), Toast.LENGTH_SHORT) .show() }, onDo = { notificationId?.let { notificationManager.cancel(it) } context.startActivity(IntentUtil.startPlanDay(context)) }) private fun showNotification( context: Context, pet: Pet, notificationManager: NotificationManager ): Int { val icon = BitmapFactory.decodeResource( context.resources, AndroidPetAvatar.valueOf(pet.avatar.name).headImage ) val sound = Uri.parse("android.resource://" + context.packageName + "/" + R.raw.notification) val notification = NotificationUtil.createDefaultNotification( context = context, icon = icon, title = "Time to plan your day", message = "Amazing new day ahead!", sound = sound, channelId = Constants.PLAN_DAY_NOTIFICATION_CHANNEL_ID, contentIntent = IntentUtil.getActivityPendingIntent( context, IntentUtil.startPlanDay(context) ) ) val notificationId = Random().nextInt() notificationManager.notify(notificationId, notification) return notificationId } } class SnoozedPlanDayJob : Job() { override fun onRunJob(params: Params): Result { val kap = Kapsule<BackgroundModule>() val playerRepository by kap.required { playerRepository } val planDayScheduler by kap.required { planDayScheduler } kap.inject(MyPoliApp.backgroundModule(context)) val p = playerRepository.find() requireNotNull(p) GlobalScope.launch(Dispatchers.Main) { PlanDayNotification.show(context, p!!, planDayScheduler) } return Result.SUCCESS } companion object { const val TAG = "job_snoozed_plan_day_tag" } } class PlanDayJob : FixedDailyJob(PlanDayJob.TAG) { override fun doRunJob(params: Params): Result { val kap = Kapsule<BackgroundModule>() val playerRepository by kap.required { playerRepository } val planDayScheduler by kap.required { planDayScheduler } val dailyChallengeRepository by kap.required { dailyChallengeRepository } kap.inject(MyPoliApp.backgroundModule(context)) val p = playerRepository.find() requireNotNull(p) if (!p!!.preferences.planDays.contains(LocalDate.now().dayOfWeek)) { return Job.Result.SUCCESS } dailyChallengeRepository.findForDate(LocalDate.now()) ?: dailyChallengeRepository.save(DailyChallenge(date = LocalDate.now())) GlobalScope.launch(Dispatchers.Main) { PlanDayNotification.show(context, p, planDayScheduler) } return Job.Result.SUCCESS } companion object { const val TAG = "job_plan_day_tag" } } interface PlanDayScheduler { fun scheduleAfter(minutes: Duration<Minute>) fun schedule() } class AndroidPlanDayScheduler(private val context: Context) : PlanDayScheduler { override fun scheduleAfter(minutes: Duration<Minute>) { JobRequest.Builder(SnoozedPlanDayJob.TAG) .setUpdateCurrent(true) .setExact(minutes.millisValue) .build() .schedule() } override fun schedule() { GlobalScope.launch(Dispatchers.IO) { val kap = Kapsule<BackgroundModule>() val playerRepository by kap.required { playerRepository } kap.inject(MyPoliApp.backgroundModule([email protected])) val p = playerRepository.find() requireNotNull(p) val pTime = p!!.preferences.planDayTime FixedDailyJobScheduler.schedule(PlanDayJob.TAG, pTime) } } }
app/src/main/java/com/kiwiandroiddev/sc2buildassistant/feature/translate/domain/LanguageCode.kt
3233640035
package com.kiwiandroiddev.sc2buildassistant.feature.translate.domain /** * Created by matthome on 31/07/17. */ typealias LanguageCode = String
platform/lang-impl/testSources/com/intellij/codeInsight/hints/InlayHintsPassFactoryTest.kt
1545318371
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.hints import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl import com.intellij.codeInsight.hints.presentation.SpacePresentation import com.intellij.openapi.editor.Editor import com.intellij.openapi.fileTypes.PlainTextLanguage import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbServiceImpl import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.testFramework.ExtensionTestUtil import com.intellij.testFramework.fixtures.BasePlatformTestCase class InlayHintsPassFactoryTest : BasePlatformTestCase() { fun testAlwaysEnabledWorksAfterDisabling() { myFixture.configureByText("file.txt", "text") val language = PlainTextLanguage.INSTANCE val key = SettingsKey<NoSettings>("key") ExtensionTestUtil.maskExtensions(InlayHintsProviderFactory.EP, listOf(object : InlayHintsProviderFactory { override fun getProvidersInfo(): List<ProviderInfo<out Any>> { return listOf(ProviderInfo(language, DummyProvider(key, object : InlayHintsCollector { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { sink.addInlineElement(0, true, SpacePresentation(1, 1), false) return false } }))) } }), testRootDisposable) InlayHintsSettings.instance().changeHintTypeStatus(key, language, false) InlayHintsPassFactory.setAlwaysEnabledHintsProviders(myFixture.editor, listOf(key)) val factory = InlayHintsPassFactory() val pass = factory.createHighlightingPass(myFixture.file, myFixture.editor) as InlayHintsPass pass.doCollectInformation(EmptyProgressIndicator()) pass.applyInformationToEditor() assertTrue(myFixture.editor.inlayModel.getInlineElementsInRange(0, 0).isNotEmpty()) } fun testDumbMode() { myFixture.configureByText("file.txt", "text") val language = PlainTextLanguage.INSTANCE ExtensionTestUtil.maskExtensions(InlayHintsProviderFactory.EP, listOf(object : InlayHintsProviderFactory { override fun getProvidersInfo(): List<ProviderInfo<out Any>> { val smart = ProviderInfo(language, DummyProvider(SettingsKey("smart.key"), object : InlayHintsCollector { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { sink.addInlineElement(1, true, SpacePresentation(1, 1), false) return false } })) val dumbAware = ProviderInfo(language, object : DummyProvider(SettingsKey("dumb.aware.key"), object : InlayHintsCollector { override fun collect(element: PsiElement, editor: Editor, sink: InlayHintsSink): Boolean { sink.addInlineElement(0, true, SpacePresentation(1, 1), false) return false } }), DumbAware {}) return listOf( dumbAware, smart, ) } }), testRootDisposable) (DaemonCodeAnalyzer.getInstance(project) as DaemonCodeAnalyzerImpl).mustWaitForSmartMode(false, testRootDisposable) DumbServiceImpl.getInstance(myFixture.project).isDumb = true myFixture.doHighlighting() assertEquals(1, myFixture.editor.inlayModel.getInlineElementsInRange(0, 1).size) (DaemonCodeAnalyzer.getInstance(project) as DaemonCodeAnalyzerImpl).mustWaitForSmartMode(true, testRootDisposable) DumbServiceImpl.getInstance(myFixture.project).isDumb = false myFixture.doHighlighting() assertEquals(2, myFixture.editor.inlayModel.getInlineElementsInRange(0, 1).size) } private open class DummyProvider(override val key: SettingsKey<NoSettings>, val collector: InlayHintsCollector): InlayHintsProvider<NoSettings> { override fun getCollectorFor(file: PsiFile, editor: Editor, settings: NoSettings, sink: InlayHintsSink): InlayHintsCollector { return collector } override fun createSettings(): NoSettings = NoSettings() override val name: String get() = throw NotImplementedError() override val previewText: String get() = throw NotImplementedError() override fun createConfigurable(settings: NoSettings): ImmediateConfigurable = throw NotImplementedError() } }
plugins/kotlin/idea/tests/testData/android/quickfix/viewConstructor/simple.before.Main.kt
1285576354
// "Add Android View constructors using '@JvmOverloads'" "true" // ERROR: This type has a constructor, and thus must be initialized here // WITH_STDLIB package com.myapp.activity import android.view.View class Foo : View<caret>
plugins/kotlin/idea/tests/testData/formatter/NotIs.after.kt
639463996
fun f() { if (1 !is Int) { } }
notebooks/notebook-ui/src/org/jetbrains/plugins/notebooks/ui/editor/actions/command/mode/NotebookEditorMode.kt
1554348705
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.notebooks.ui.editor.actions.command.mode import com.intellij.openapi.actionSystem.ex.ActionUtil import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.CaretVisualAttributes import com.intellij.openapi.editor.event.CaretEvent import com.intellij.openapi.editor.event.CaretListener import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.MarkupModelEx import com.intellij.openapi.editor.ex.RangeHighlighterEx import com.intellij.openapi.fileEditor.TextEditor import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.util.messages.Topic import org.jetbrains.annotations.CalledInAny import java.awt.Color /** * The Jupyter Notebook has a modal user interface. * This means that the keyboard does different things depending on which mode the Notebook is in. * There are two modes: edit mode and command mode. * * @see <a href="https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Notebook%20Basics.html#Modal-editor"> * Notebook Modal Editor * </a> */ enum class NotebookEditorMode { EDIT, COMMAND } val NOTEBOOK_EDITOR_MODE: Topic<NotebookEditorModeListener> = Topic.create("Notebook Editor Mode", NotebookEditorModeListener::class.java) @FunctionalInterface interface NotebookEditorModeListener { fun onModeChange(mode: NotebookEditorMode) } abstract class NotebookEditorModeListenerAdapter : TextEditor, NotebookEditorModeListener, CaretListener { private var currentEditorMode: NotebookEditorMode? = null private fun getCaretAttributes(mode: NotebookEditorMode): CaretVisualAttributes { return when (mode) { NotebookEditorMode.EDIT -> CaretVisualAttributes.DEFAULT NotebookEditorMode.COMMAND -> INVISIBLE_CARET } } private fun isCaretRowShown(mode: NotebookEditorMode): Boolean = when (mode) { NotebookEditorMode.EDIT -> true NotebookEditorMode.COMMAND -> false } private fun handleCarets(mode: NotebookEditorMode) { when (mode) { NotebookEditorMode.EDIT -> { // selection of multiple cells leads to multiple invisible carets, remove them editor.caretModel.removeSecondaryCarets() } NotebookEditorMode.COMMAND -> { // text selection shouldn't be visible in command mode for (caret in editor.caretModel.allCarets) { caret.removeSelection() } } } } override fun onModeChange(mode: NotebookEditorMode) { val modeWasChanged = currentEditorMode != mode currentEditorMode = mode editor.apply { (markupModel as MarkupModelEx).apply { allHighlighters.filterIsInstance<RangeHighlighterEx>().forEach { fireAttributesChanged(it, true, false) } } if (modeWasChanged) { handleCarets(mode) editor.settings.isCaretRowShown = isCaretRowShown(mode) } caretModel.allCarets.forEach { caret -> caret.visualAttributes = getCaretAttributes(mode) } editor.contentComponent.putClientProperty(ActionUtil.ALLOW_PlAIN_LETTER_SHORTCUTS, when (mode) { NotebookEditorMode.EDIT -> false NotebookEditorMode.COMMAND -> true }) } } override fun caretAdded(event: CaretEvent) { val mode = currentEditorMode ?: return event.caret?.visualAttributes = getCaretAttributes(mode) (editor as EditorEx).gutterComponentEx.repaint() } override fun caretRemoved(event: CaretEvent) { (editor as EditorEx).gutterComponentEx.repaint() } } @CalledInAny fun currentMode(): NotebookEditorMode = currentMode_ @RequiresEdt fun setMode(mode: NotebookEditorMode) { // Although LAB-50 is marked as closed, the checks still aren't added to classes written in Kotlin. ApplicationManager.getApplication().assertIsDispatchThread() currentMode_ = mode // may be call should be skipped if mode == currentMode_ ApplicationManager.getApplication().messageBus.syncPublisher(NOTEBOOK_EDITOR_MODE).onModeChange(mode) } @Volatile private var currentMode_: NotebookEditorMode = NotebookEditorMode.EDIT private val INVISIBLE_CARET = CaretVisualAttributes( Color(0, 0, 0, 0), CaretVisualAttributes.Weight.NORMAL)
plugins/terminal/src/com/intellij/ide/actions/runAnything/RunAnythingTerminalBridge.kt
1925990212
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions.runAnything import com.intellij.execution.Executor import com.intellij.ide.actions.runAnything.activity.RunAnythingCommandProvider import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider import com.intellij.ide.actions.runAnything.activity.RunAnythingRecentProjectProvider import com.intellij.internal.statistic.collectors.fus.ClassNameRuleValidator import com.intellij.internal.statistic.collectors.fus.TerminalFusAwareHandler import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.terminal.TerminalShellCommandHandler private class RunAnythingTerminalBridge : TerminalShellCommandHandler, TerminalFusAwareHandler { override fun matches(project: Project, workingDirectory: String?, localSession: Boolean, command: String): Boolean { val dataContext = createDataContext(project, localSession, workingDirectory) return RunAnythingProvider.EP_NAME.extensionList .asSequence() .filter { checkForCLI(it) } .any { provider -> provider.findMatchingValue(dataContext, command) != null } } override fun execute(project: Project, workingDirectory: String?, localSession: Boolean, command: String, executor: Executor): Boolean { val dataContext = createDataContext(project, localSession, workingDirectory, executor) return RunAnythingProvider.EP_NAME.extensionList .asSequence() .filter { checkForCLI(it) } .any { provider -> provider.findMatchingValue(dataContext, command)?.let { provider.execute(dataContext, it); return true } ?: false } } companion object { private fun createDataContext(project: Project, localSession: Boolean, workingDirectory: String?, executor: Executor? = null): DataContext { val virtualFile = if (localSession && workingDirectory != null) LocalFileSystem.getInstance().findFileByPath(workingDirectory) else null return SimpleDataContext.builder() .add(CommonDataKeys.PROJECT, project) .add(RunAnythingAction.EXECUTOR_KEY, executor) .apply { if (virtualFile != null) { add(CommonDataKeys.VIRTUAL_FILE, virtualFile) add(RunAnythingProvider.EXECUTING_CONTEXT, RunAnythingContext.RecentDirectoryContext(virtualFile.path)) } } .build() } private fun checkForCLI(it: RunAnythingProvider<*>?): Boolean { return (it !is RunAnythingCommandProvider && it !is RunAnythingRecentProjectProvider && it !is RunAnythingRunConfigurationProvider) } } override fun fillData(project: Project, workingDirectory: String?, localSession: Boolean, command: String, data: MutableList<EventPair<*>>) { val dataContext = createDataContext(project, localSession, workingDirectory) val runAnythingProvider = RunAnythingProvider.EP_NAME.extensionList .filter { checkForCLI(it) } .ifEmpty { return } .first { provider -> provider.findMatchingValue(dataContext, command) != null } data.add(EventFields.StringValidatedByCustomRule("runAnythingProvider", ClassNameRuleValidator::class.java).with(runAnythingProvider::class.java.name)) } }
plugins/kotlin/idea/tests/testData/intentions/convertConcatenationToBuildString/withComments5.kt
1447220677
// WITH_STDLIB // AFTER-WARNING: Variable 's' is never used fun test(foo: String, bar: Int, baz: Int) { val s = <caret>"${foo.length}, " + // comment1 // comment2 /* comment3 */ "$bar, " + // comment4 // comment5 // comment6 "$baz" // comment7 /* This is a test comment: - This is a test bullet point. - This is another test bullet point. */ }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/toHashSet.kt
228757505
// WITH_STDLIB fun test(list: List<Int>) { val toHashSet: HashSet<Int> = list.<caret>filter { it > 1 }.toHashSet() }
plugins/full-line/python/test/org/jetbrains/completion/full/line/python/formatters/PythonElementsFormatterTest.kt
3211824661
package org.jetbrains.completion.full.line.python.formatters class PythonElementsFormatterTest : PythonCodeFormatterTest() { fun `test numerical`() { testFile("test-elements/numerical.py") } fun `test parameter list without closed bracket`() { testCodeFragment("def nginx(_config ", "def nginx(_config ", 18) } fun `test function params without type`() { testCodeFragment("def checkout_branch(branch):\n return None", "def checkout_branch(branch):\n\treturn None") } fun `test function params with type`() { testCodeFragment("def checkout_branch(branch: str):\n return None", "def checkout_branch(branch: str):\n\treturn None") } fun `test function params with type and default value`() { testCodeFragment("def checkout_branch(branch: str=\"master\"):\n return None", "def checkout_branch(branch: str=\"master\"):\n\treturn None") } fun `test not fully filled import`() { testCodeFragment("import ", "import ") } fun `test not fully filled from import`() { testCodeFragment("from tqdm import ", "from tqdm import ") } fun `test inside not fully filled from import`() { testCodeFragment("from import tqdm", "from ", 5) } fun `test strings`() { testFile("test-elements/strings.py") } fun `test imports`() { testFile("test-elements/imports.py") } }
app/src/main/java/org/thoughtcrime/securesms/database/model/PendingRetryReceiptModel.kt
1771381721
package org.thoughtcrime.securesms.database.model import org.thoughtcrime.securesms.recipients.RecipientId /** A model for [org.thoughtcrime.securesms.database.PendingRetryReceiptDatabase] */ data class PendingRetryReceiptModel( val id: Long, val author: RecipientId, val authorDevice: Int, val sentTimestamp: Long, val receivedTimestamp: Long, val threadId: Long )
libCore/src/main/java/com/kanawish/di/ActivityInjectionLifecycle.kt
4233783029
package com.kanawish.di import android.app.Activity import android.app.Application.ActivityLifecycleCallbacks import android.os.Bundle import toothpick.Scope import toothpick.Toothpick /** */ class ActivityInjectionLifecycle(private val scopeBuilder: (Activity) -> Scope) : ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity?, bundle: Bundle?) { activity?.apply { Toothpick.inject(this, scopeBuilder(activity)) } } override fun onActivityStarted(activity: Activity?) { } override fun onActivityPaused(activity: Activity?) { } override fun onActivityResumed(activity: Activity?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivityDestroyed(activity: Activity?) { activity?.apply { Toothpick.closeScope(this) } } override fun onActivitySaveInstanceState(activity: Activity?, bundle: Bundle?) { } }
src/main/java/com/fluxxy/MainActivity.kt
1351980274
package com.fluxxy import android.app.Activity import android.os.Bundle import android.util.Log import android.view.View import com.androidnetworking.AndroidNetworking import com.androidnetworking.common.Priority import com.androidnetworking.error.ANError import com.androidnetworking.interfaces.StringRequestListener import com.facebook.stetho.okhttp3.StethoInterceptor import okhttp3.OkHttpClient class MainActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val okHttpClient = OkHttpClient().newBuilder() .addNetworkInterceptor(StethoInterceptor()) .build() AndroidNetworking.initialize(applicationContext, okHttpClient) setContentView(R.layout.activity_main) } fun sendMessage(view: View) { Log.i(Constants.LOG, "Button clicked!") AndroidNetworking.get("http://18.221.145.123:8000/") .setTag("test") .setPriority(Priority.LOW) .build() .getAsString(object : StringRequestListener { override fun onResponse(response: String) { Log.i(Constants.LOG, "Response: $response") } override fun onError(error: ANError) { Log.i(Constants.LOG, "Error: ${error.errorBody}") } }) } }
app/src/androidTest/java/org/fedorahosted/freeotp/uitest/RecyclerViewAction.kt
1374740691
package org.fedorahosted.freeotp.uitest import android.view.View import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import org.hamcrest.Matcher import org.hamcrest.Matchers object RecyclerViewAction { fun clickChildViewWithId(id: Int) = object: ViewAction { override fun getConstraints(): Matcher<View> { return Matchers.any(View::class.java) } override fun getDescription(): String { return "Click on recycler view child" } override fun perform(uiController: UiController?, view: View?) { val child = view?.findViewById<View>(id) child?.performClick()?: throw AssertionError("Cannot find view with id: $id") } } }
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/misc/GithubApi2.kt
3450409132
package com.beust.kobalt.misc import com.beust.kobalt.KobaltException import com.beust.kobalt.internal.DocUrl import com.beust.kobalt.internal.KobaltSettings import com.beust.kobalt.maven.Http import com.google.gson.Gson import com.google.gson.annotations.SerializedName import com.google.inject.Inject import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.* import rx.Observable import java.io.File import java.util.* import java.util.concurrent.Callable import java.util.concurrent.Future class GithubApi2 @Inject constructor( val executors: KobaltExecutors, val localProperties: LocalProperties, val http: Http, val settings:KobaltSettings) { companion object { const val PROPERTY_ACCESS_TOKEN = "github.accessToken" const val PROPERTY_USERNAME = "github.username" } private val DOC_URL = DocUrl.PUBLISH_PLUGIN_URL // // JSON mapped classes that get sent up and down // class CreateRelease(@SerializedName("tag_name") var tagName: String? = null, var name: String? = tagName) class CreateReleaseResponse(var id: String? = null, @SerializedName("upload_url") var uploadUrl: String?) class UploadAssetResponse(var id: String? = null, val name: String? = null) class ReleasesResponse(@SerializedName("tag_name") var tagName: String? = null, var name: String? = tagName) interface Api { @POST("/repos/{owner}/{repo}/releases") fun createRelease(@Path("owner") owner: String, @Path("repo") repo: String, @Query("access_token") accessToken: String, @Body createRelease: CreateRelease): Call<CreateReleaseResponse> @GET("/repos/{owner}/{repo}/releases") fun getReleases(@Path("owner") owner: String, @Path("repo") repo: String, @Query("access_token") accessToken: String): Call<List<ReleasesResponse>> @GET("/repos/{owner}/{repo}/releases") fun getReleasesNoAuth(@Path("owner") owner: String, @Path("repo") repo: String): Call<List<ReleasesResponse>> } // // Read only Api // private val service = Retrofit.Builder() .client(OkHttpClient.Builder().proxy(settings.proxyConfig?.toProxy()).build()) .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .build() .create(Api::class.java) // JSON Retrofit error class Error(val code: String) class RetrofitError(var message: String = "", var errors : List<Error> = arrayListOf()) fun uploadRelease(packageName: String, tagName: String, zipFile: File) { log(1, "Uploading release ${zipFile.name}") val username = localProperties.get(PROPERTY_USERNAME, DOC_URL) val accessToken = localProperties.get(PROPERTY_ACCESS_TOKEN, DOC_URL) val response = service.createRelease(username, packageName, accessToken, CreateRelease(tagName)) .execute() val code = response.code() if (code != Http.CREATED) { val error = Gson().fromJson(response.errorBody().string(), RetrofitError::class.java) throw KobaltException("Couldn't upload release, ${error.message}: " + error.errors[0].code) } else { val body = response.body() uploadAsset(accessToken, body.uploadUrl!!, Http.TypedFile("application/zip", zipFile), tagName) .toBlocking() .forEach { action -> log(1, "\n${zipFile.name} successfully uploaded") } } } private fun uploadAsset(token: String, uploadUrl: String, typedFile: Http.TypedFile, tagName: String) : Observable<UploadAssetResponse> { val strippedUrl = uploadUrl.substring(0, uploadUrl.indexOf("{")) val fileName = typedFile.file.name val url = "$strippedUrl?name=$fileName&label=$fileName" val headers = okhttp3.Headers.of("Authorization", "token $token") val totalSize = typedFile.file.length() http.uploadFile(url = url, file = typedFile, headers = headers, post = true, // Github requires POST progressCallback = http.percentProgressCallback(totalSize)) return Observable.just(UploadAssetResponse(tagName, tagName)) } val latestKobaltVersion: Future<String> get() { val callable = Callable<String> { var result = "0" val username = localProperties.getNoThrows(PROPERTY_USERNAME, DOC_URL) val accessToken = localProperties.getNoThrows(PROPERTY_ACCESS_TOKEN, DOC_URL) try { val req = if (username != null && accessToken != null) { service.getReleases(username, "kobalt", accessToken) } else { service.getReleasesNoAuth("cbeust", "kobalt") } val releases = req.execute().body() if (releases != null) { releases.firstOrNull()?.let { try { result = listOf(it.name, it.tagName).filterNotNull().first { !it.isBlank() } } catch(ex: NoSuchElementException) { throw KobaltException("Couldn't find the latest release") } } } else { warn("Didn't receive any body in the response to GitHub.getReleases()") } } catch(e: Exception) { log(1, "Couldn't retrieve releases from github: " + e.message) e.printStackTrace() // val error = parseRetrofitError(e) // val details = if (error.errors != null) { // error.errors[0] // } else { // null // } // // TODO: If the credentials didn't work ("bad credentials"), should start again // // using cbeust/kobalt, like above. Right now, just bailing. // log(2, "Couldn't retrieve releases from github, ${error.message ?: e}: " // + details?.code + " field: " + details?.field) } result } return executors.miscExecutor.submit(callable) } }
ktor-http/ktor-http-cio/common/src/io/ktor/http/cio/internals/Tokenizer.kt
499569444
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.http.cio.internals internal fun nextToken(text: CharSequence, range: MutableRange): CharSequence { val spaceOrEnd = findSpaceOrEnd(text, range) val s = text.subSequence(range.start, spaceOrEnd) range.start = spaceOrEnd return s } internal fun skipSpacesAndHorizontalTabs( text: CharArrayBuilder, start: Int, end: Int ): Int { var index = start while (index < end) { val ch = text[index] if (!ch.isWhitespace() && ch != HTAB) break index++ } return index } internal fun skipSpaces(text: CharSequence, range: MutableRange) { var idx = range.start val end = range.end if (idx >= end || !text[idx].isWhitespace()) return idx++ while (idx < end) { if (!text[idx].isWhitespace()) break idx++ } range.start = idx } internal fun findSpaceOrEnd(text: CharSequence, range: MutableRange): Int { var idx = range.start val end = range.end if (idx >= end || text[idx].isWhitespace()) return idx idx++ while (idx < end) { if (text[idx].isWhitespace()) return idx idx++ } return idx }
kernelip/reordex/src/dispatch_buffer.kt
2691594072
/* * dispatch_buffer.kt * * Created on: 24.12.2020 * Author: Alexander Antonov <[email protected]> * License: See LICENSE file for details */ package reordex import hwast.* internal open class dispatch_buffer(cyclix_gen : cyclix.Generic, name_prefix : String, TRX_BUF_SIZE : Int, MultiExu_CFG : Reordex_CFG, ExecUnits_size : Int, cdb_num : Int, val IQ_insts : ArrayList<iq_buffer>, val control_structures: __control_structures) : uop_buffer(cyclix_gen, name_prefix, TRX_BUF_SIZE, MultiExu_CFG.DataPath_width, MultiExu_CFG, cdb_num) { var exu_id = AdduStageVar("exu_id", GetWidthToContain(ExecUnits_size), 0, "0") var rds_ctrl = ArrayList<ROB_rd_ctrl>() var cf_can_alter = AdduStageVar("cf_can_alter", 0, 0, "0") val io_req = AdduStageVar("io_req", 0, 0, "0") var mem_we = AdduStageVar("mem_we",0, 0, "1") var dispatch_active = cyclix_gen.ulocal("gendispatch_dispatch_active", 0, 0, "1") var entry_toproc_mask = cyclix_gen.uglobal("gendispatch_entry_toproc_mask", TRX_BUF_MULTIDIM-1, 0, hw_imm_ones(TRX_BUF_MULTIDIM)) var iq_free_mask = cyclix_gen.ulocal("gendispatch_iq_free_mask", IQ_insts.size-1, 0, hw_imm_ones(IQ_insts.size)) var store_iq_free_mask = cyclix_gen.ulocal("gendispatch_store_iq_free_mask", 0, 0, "1") init { Fill_ROB_rds_ctrl_StageVars(this, MultiExu_CFG.rds.size, rds_ctrl, MultiExu_CFG.PRF_addr_width) control_structures.states_toRollBack.add(entry_toproc_mask) } fun Process(rob : rob, PRF_src : hw_var, store_iq : iq_buffer, ExecUnits : MutableMap<String, Exu_CFG>, CDB_RISC_LSU_POS : Int) { cyclix_gen.MSG_COMMENT("sending new operations to IQs...") preinit_ctrls() init_locals() var rob_push_trx_total = rob.GetPushTrx() var store_push_trx = store_iq.GetPushTrx() cyclix_gen.begif(cyclix_gen.band(ctrl_active, rob.ctrl_rdy)) run { for (entry_num in 0 until MultiExu_CFG.DataPath_width) { cyclix_gen.begif(TRX_LOCAL_PARALLEL.GetFracRef(entry_num).GetFracRef("enb")) run { switch_to_local(entry_num) var rob_push_trx = rob_push_trx_total.GetFracRef(entry_num) cyclix_gen.begif(cyclix_gen.band(dispatch_active, entry_toproc_mask.GetFracRef(entry_num), enb)) run { for (rsrv in src_rsrv) { cyclix_gen.assign(rsrv.src_src, PRF_src.GetFracRef(rsrv.src_tag)) } cyclix_gen.assign(dispatch_active, 0) cyclix_gen.begif(io_req) run { cyclix_gen.begif(cyclix_gen.band(store_iq_free_mask, store_iq.ctrl_rdy)) run { // pushing trx to IQ cyclix_gen.assign(store_iq.push, 1) cyclix_gen.assign_subStructs(store_push_trx, TRX_LOCAL) cyclix_gen.assign(store_push_trx.GetFracRef("trx_id"), rob.TRX_ID_COUNTER) store_iq.push_trx(store_push_trx) // marking rd src cyclix_gen.begif(!mem_we) run { cyclix_gen.assign(PRF_src.GetFracRef(rds_ctrl[0].tag), CDB_RISC_LSU_POS) }; cyclix_gen.endif() // marking RRB for ROB cyclix_gen.assign(rob_push_trx.GetFracRef("cdb_id"), store_iq.CDB_index) // marking op as scheduled cyclix_gen.assign(entry_toproc_mask.GetFracRef(entry_num), 0) // marking IQ as busy cyclix_gen.assign(store_iq_free_mask, 0) // marking ready to schedule next trx cyclix_gen.assign(dispatch_active, 1) }; cyclix_gen.endif() }; cyclix_gen.endif() cyclix_gen.begelse() run { for (IQ_inst_idx in 0 until IQ_insts.size-1) { var IQ_inst = IQ_insts[IQ_inst_idx] cyclix_gen.begif(cyclix_gen.band(entry_toproc_mask.GetFracRef(entry_num), iq_free_mask.GetFracRef(IQ_inst_idx))) run { cyclix_gen.begif(cyclix_gen.eq2(exu_id, IQ_inst.exu_id_num)) run { cyclix_gen.begif(IQ_inst.ctrl_rdy) run { // pushing trx to IQ cyclix_gen.assign(IQ_inst.push, 1) var iq_push_trx = IQ_inst.GetPushTrx() cyclix_gen.assign_subStructs(iq_push_trx, TRX_LOCAL) cyclix_gen.assign(iq_push_trx.GetFracRef("trx_id"), rob.TRX_ID_COUNTER) IQ_inst.push_trx(iq_push_trx) // marking rd src cyclix_gen.assign(PRF_src.GetFracRef(rds_ctrl[0].tag), IQ_inst.CDB_index) // marking RRB for ROB cyclix_gen.assign(rob_push_trx.GetFracRef("cdb_id"), IQ_inst.CDB_index) // marking op as scheduled cyclix_gen.assign(entry_toproc_mask.GetFracRef(entry_num), 0) // marking IQ as busy cyclix_gen.assign(iq_free_mask.GetFracRef(IQ_inst_idx), 0) // marking ready to schedule next trx cyclix_gen.assign(dispatch_active, 1) }; cyclix_gen.endif() }; cyclix_gen.endif() }; cyclix_gen.endif() } }; cyclix_gen.endif() cyclix_gen.begif(dispatch_active) run { // pushing to ROB cyclix_gen.assign_subStructs(rob_push_trx, TRX_LOCAL) cyclix_gen.assign(rob_push_trx.GetFracRef("trx_id"), rob.TRX_ID_COUNTER) cyclix_gen.assign(rob_push_trx.GetFracRef("rdy"), 0) cyclix_gen.add_gen(rob.TRX_ID_COUNTER, rob.TRX_ID_COUNTER, 1) cyclix_gen.assign(rob.push, 1) }; cyclix_gen.endif() }; cyclix_gen.endif() }; cyclix_gen.endif() } cyclix_gen.begif(dispatch_active) run { cyclix_gen.assign(pop, 1) }; cyclix_gen.endif() }; cyclix_gen.endif() cyclix_gen.begif(rob.push) run { rob.push_trx(rob_push_trx_total) }; cyclix_gen.endif() cyclix_gen.begif(pop) run { pop_trx() cyclix_gen.assign(entry_toproc_mask, hw_imm_ones(TRX_BUF_MULTIDIM)) }; cyclix_gen.endif() finalize_ctrls() // TODO: cleanup cyclix_gen.MSG_COMMENT("sending new operation to IQs: done") } } internal class dispatch_buffer_risc(cyclix_gen : cyclix.Generic, name_prefix : String, TRX_BUF_SIZE : Int, MultiExu_CFG : Reordex_CFG, ExecUnits_size : Int, cdb_num : Int, IQ_insts : ArrayList<iq_buffer>, control_structures: __control_structures) : dispatch_buffer(cyclix_gen, name_prefix, TRX_BUF_SIZE, MultiExu_CFG, ExecUnits_size, cdb_num, IQ_insts, control_structures) { var curinstr_addr = AdduStageVar("curinstr_addr", 31, 0, "0") var nextinstr_addr = AdduStageVar("nextinstr_addr", 31, 0, "0") var rss = ArrayList<RISCDecoder_rs>() var rds = ArrayList<RISCDecoder_rd>() var csr_rdata = AdduStageVar("csr_rdata", 31, 0, "0") var immediate = AdduStageVar("immediate", 31, 0, "0") var fencereq = AdduStageVar("fencereq", 0, 0, "0") var pred = AdduStageVar("pred", 3, 0, "0") var succ = AdduStageVar("succ", 3, 0, "0") var ecallreq = AdduStageVar("ecallreq", 0, 0, "0") var ebreakreq = AdduStageVar("ebreakreq", 0, 0, "0") var csrreq = AdduStageVar("csrreq", 0, 0, "0") var csrnum = AdduStageVar("csrnum", 11, 0, "0") var zimm = AdduStageVar("zimm", 4, 0, "0") var op1_source = AdduStageVar("op1_source", 1, 0, "0") var op2_source = AdduStageVar("op2_source", 1, 0, "0") // ALU control var alu_req = AdduStageVar("alu_req", 0, 0, "0") var alu_op1 = AdduStageVar("alu_op1", 31, 0, "0") var alu_op2 = AdduStageVar("alu_op2", 31, 0, "0") var alu_op1_wide = AdduStageVar("alu_op1_wide", 32, 0, "0") var alu_op2_wide = AdduStageVar("alu_op2_wide", 32, 0, "0") var alu_result_wide = AdduStageVar("alu_result_wide", 32, 0, "0") var alu_result = AdduStageVar("alu_result", 31, 0, "0") var alu_CF = AdduStageVar("alu_CF", 0, 0, "0") var alu_SF = AdduStageVar("alu_SF", 0, 0, "0") var alu_ZF = AdduStageVar("alu_ZF", 0, 0, "0") var alu_OF = AdduStageVar("alu_OF", 0, 0, "0") var alu_overflow = AdduStageVar("alu_overflow", 0, 0, "0") // data memory control var mem_req = AdduStageVar("mem_req", 0, 0, "0") //var mem_cmd = AdduStageVar("mem_cmd", 0, 0, "0") var mem_addr = AdduStageVar("mem_addr", 31, 0, "0") var mem_be = AdduStageVar("mem_be", 3, 0, "0") var mem_wdata = AdduStageVar("mem_wdata", 31, 0, "0") var mem_rdata = AdduStageVar("mem_rdata", 31, 0, "0") var mem_rshift = AdduStageVar("mem_rshift", 0, 0, "0") var mem_load_signext = AdduStageVar("mem_load_signext", 0, 0, "0") var mret_req = AdduStageVar("mret_req", 0, 0, "0") init { Fill_RISCDecoder_rss_StageVars(this, MultiExu_CFG.srcs.size, rss, MultiExu_CFG.ARF_addr_width, MultiExu_CFG.RF_width) Fill_RISCDecoder_rds_StageVars(this, MultiExu_CFG.rds.size, rds, MultiExu_CFG.ARF_addr_width) } }
app/src/main/java/eu/kanade/tachiyomi/source/model/SMangaImpl.kt
1213023735
package eu.kanade.tachiyomi.source.model class SMangaImpl : SManga { override lateinit var url: String override lateinit var title: String override var artist: String? = null override var author: String? = null override var description: String? = null override var genre: String? = null override var status: Int = 0 override var thumbnail_url: String? = null override var initialized: Boolean = false }
src/main/kotlin/com/demonwav/mcdev/platform/mcp/at/psi/mixins/impl/AtKeywordImplMixin.kt
3550216426
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.at.psi.mixins.impl import com.demonwav.mcdev.platform.mcp.at.AtElementFactory import com.demonwav.mcdev.platform.mcp.at.psi.mixins.AtKeywordMixin import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode abstract class AtKeywordImplMixin(node: ASTNode) : ASTWrapperPsiElement(node), AtKeywordMixin { override val keywordValue get() = AtElementFactory.Keyword.match(keywordElement.text)!! override fun setKeyword(keyword: AtElementFactory.Keyword) { replace(AtElementFactory.createKeyword(project, keyword)) } }
src/main/java/net/winsion/cohttp/ConverterFactory.kt
1670019283
package net.winsion.cohttp import okhttp3.RequestBody import okhttp3.ResponseBody import java.lang.reflect.Type interface ConverterFactory { fun responseBodyConverter(type: Type, annotations: Array<Annotation>): Converter<ResponseBody, *>? fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>): Converter<*, RequestBody>? } class ResponseBodyConverterFactory : ConverterFactory { override fun responseBodyConverter(type: Type, annotations: Array<Annotation>): Converter<ResponseBody, *>? { if (type == ResponseBody::class.java) { return object : Converter<ResponseBody, ResponseBody> { override fun convert(value: ResponseBody): ResponseBody { return value } } } return null } override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>): Converter<*, RequestBody>? { return null } } class StringConverterFactory : ConverterFactory { override fun responseBodyConverter(type: Type, annotations: Array<Annotation>): Converter<ResponseBody, *>? { if (type == String::class.java) { return object : Converter<ResponseBody, String> { override fun convert(value: ResponseBody): String { return value.string() } } } return null } override fun requestBodyConverter(type: Type, parameterAnnotations: Array<Annotation>, methodAnnotations: Array<Annotation>): Converter<*, RequestBody>? { return null } }
api/src/main/java/it/codingjam/github/api/util/RetrofitFactory.kt
3725298344
package it.codingjam.github.api.util import com.google.gson.GsonBuilder import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory import okhttp3.HttpUrl import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object RetrofitFactory { inline fun <reified T> createService(debug: Boolean, baseUrl: HttpUrl): T { val httpClient = OkHttpClient.Builder() if (debug) { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY httpClient.addInterceptor(logging) } val gson = GsonBuilder().create() return Retrofit.Builder() .baseUrl(baseUrl) .addConverterFactory(DenvelopingConverter(gson)) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(CoroutineCallAdapterFactory()) .client(httpClient.build()) .build() .create(T::class.java) } }
platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/GuiTestUtilKt.kt
2569049664
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.impl import com.intellij.diagnostic.MessagePool import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.Ref import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.framework.toPrintable import com.intellij.testGuiFramework.util.FinderPredicate import com.intellij.testGuiFramework.util.Predicate import com.intellij.ui.EngravedLabel import org.fest.swing.core.ComponentMatcher import org.fest.swing.core.GenericTypeMatcher import org.fest.swing.core.Robot import org.fest.swing.edt.GuiActionRunner import org.fest.swing.edt.GuiQuery import org.fest.swing.edt.GuiTask import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.WaitTimedOutError import org.fest.swing.timing.Condition import org.fest.swing.timing.Pause import org.fest.swing.timing.Timeout import org.fest.swing.timing.Wait import java.awt.Component import java.awt.Container import java.awt.Window import java.util.* import java.util.concurrent.TimeUnit import javax.swing.JCheckBox import javax.swing.JDialog import javax.swing.JLabel import javax.swing.JRadioButton import kotlin.collections.ArrayList /** * @author Sergey Karashevich */ object GuiTestUtilKt { fun createTree(string: String): ImmutableTree<String> { val currentPath = ArrayList<String>() var lines = string.split("\n") if (lines.last().isEmpty()) lines = lines.subList(0, lines.lastIndex - 1) val tree: ImmutableTree<String> = ImmutableTree() var lastNode: ImmutableTreeNode<String>? = null try { for (line in lines) { if (currentPath.isEmpty()) { currentPath.add(line) tree.root = ImmutableTreeNode(line.withoutIndent(), null) lastNode = tree.root } else { if (currentPath.last() hasDiffIndentFrom line) { if (currentPath.last().getIndent() > line.getIndent()) { while (currentPath.last() hasDiffIndentFrom line) { currentPath.removeAt(currentPath.lastIndex) lastNode = lastNode!!.parent } currentPath.removeAt(currentPath.lastIndex) currentPath.add(line) lastNode = lastNode!!.parent!!.createChild(line.withoutIndent()) } else { currentPath.add(line) lastNode = lastNode!!.createChild(line.withoutIndent()) } } else { currentPath.removeAt(currentPath.lastIndex) currentPath.add(line) lastNode = lastNode!!.parent!!.createChild(line.withoutIndent()) } } } return tree } catch (e: Exception) { throw Exception("Unable to build a tree from given data. Check indents and ") } } private infix fun String.hasDiffIndentFrom(s: String): Boolean { return this.getIndent() != s.getIndent() } private fun String.getIndent() = this.indexOfFirst { it != ' ' } private fun String.withoutIndent() = this.substring(this.getIndent()) private operator fun String.times(n: Int): String { val sb = StringBuilder(n) for (i in 1..n) { sb.append(this) } return sb.toString() } class ImmutableTree<Value> { var root: ImmutableTreeNode<Value>? = null fun print() { if (root == null) throw Exception("Unable to print tree without root (or if root is null)") printRecursive(root!!, 0) } fun printRecursive(root: ImmutableTreeNode<Value>, indent: Int) { println(" " * indent + root.value) if (!root.isLeaf()) root.children.forEach { printRecursive(it, indent + 2) } } } data class ImmutableTreeNode<Value>(val value: Value, val parent: ImmutableTreeNode<Value>?, val children: LinkedList<ImmutableTreeNode<Value>> = LinkedList()) { fun createChild(childValue: Value): ImmutableTreeNode<Value> { val child = ImmutableTreeNode<Value>(childValue, this) children.add(child) return child } fun countChildren(): Int = children.count() fun isLeaf(): Boolean = (children.count() == 0) } fun Component.isTextComponent(): Boolean { val textComponentsTypes = arrayOf(JLabel::class.java, JRadioButton::class.java, JCheckBox::class.java) return textComponentsTypes.any { it.isInstance(this) } } fun Component.getComponentText(): String? { when (this) { is JLabel -> return this.text is JRadioButton -> return this.text is JCheckBox -> return this.text else -> return null } } private fun findComponentByText(robot: Robot, container: Container, text: String, timeout: Timeout = Timeouts.seconds30): Component { return withPauseWhenNull(timeout = timeout) { robot.finder().findAll(container, ComponentMatcher { component -> component!!.isShowing && component.isTextComponent() && component.getComponentText() == text }).firstOrNull() } } fun <BoundedComponent> findBoundedComponentByText(robot: Robot, container: Container, text: String, componentType: Class<BoundedComponent>, timeout: Timeout = Timeouts.seconds30): BoundedComponent { val componentWithText = findComponentByText(robot, container, text, timeout) if (componentWithText is JLabel && componentWithText.labelFor != null) { val labeledComponent = componentWithText.labelFor if (componentType.isInstance(labeledComponent)) return labeledComponent as BoundedComponent return robot.finder().find(labeledComponent as Container) { component -> componentType.isInstance(component) } as BoundedComponent } try { return withPauseWhenNull(timeout = timeout) { val componentsOfInstance = robot.finder().findAll(container, ComponentMatcher { component -> componentType.isInstance(component) }) componentsOfInstance.filter { it.isShowing && it.onHeightCenter(componentWithText, true) } .sortedBy { it.bounds.x } .firstOrNull() } as BoundedComponent } catch (e: WaitTimedOutError) { throw ComponentLookupException("Unable to find component of type: ${componentType.simpleName} in $container by text: $text") } } //Does the textComponent intersects horizontal line going through the center of this component and lays lefter than this component fun Component.onHeightCenter(textComponent: Component, onLeft: Boolean): Boolean { val centerXAxis = this.bounds.height / 2 + this.locationOnScreen.y val sideCheck = if (onLeft) textComponent.locationOnScreen.x < this.locationOnScreen.x else textComponent.locationOnScreen.x > this.locationOnScreen.x return (textComponent.locationOnScreen.y <= centerXAxis) && (textComponent.locationOnScreen.y + textComponent.bounds.height >= centerXAxis) && (sideCheck) } fun runOnEdt(task: () -> Unit) { GuiActionRunner.execute(object : GuiTask() { override fun executeInEDT() { task() } }) } /** * waits for 30 sec timeout when functionProbeToNull() not return null * * @throws WaitTimedOutError with the text: "Timed out waiting for $timeout second(s) until {@code conditionText} will be not null" */ fun <ReturnType> withPauseWhenNull(conditionText: String = "function to probe will", timeout: Timeout = Timeouts.defaultTimeout, functionProbeToNull: () -> ReturnType?): ReturnType { var result: ReturnType? = null waitUntil("$conditionText will be not null", timeout) { result = functionProbeToNull() result != null } return result!! } fun waitUntil(condition: String, timeout: Timeout = Timeouts.defaultTimeout, conditionalFunction: () -> Boolean) { Pause.pause(object : Condition("${timeout.toPrintable()} until $condition") { override fun test() = conditionalFunction() }, timeout) } fun <R> tryWithPause(exceptionClass: Class<out Exception>, condition: String = "try block will not throw ${exceptionClass.name} exception", timeout: Timeout, tryBlock: () -> R): R { val exceptionRef: Ref<Exception> = Ref.create() try { return withPauseWhenNull (condition, timeout) { try { tryBlock() } catch (e: Exception) { if (exceptionClass.isInstance(e)) { exceptionRef.set(e) return@withPauseWhenNull null } throw e } } } catch (e: WaitTimedOutError) { throw Exception("Timeout for $condition exceeded ${timeout.toPrintable()}", exceptionRef.get()) } } fun silentWaitUntil(condition: String, timeoutInSeconds: Int = 60, conditionalFunction: () -> Boolean) { try { Pause.pause(object : Condition("$timeoutInSeconds second(s) until $condition silently") { override fun test() = conditionalFunction() }, Timeout.timeout(timeoutInSeconds.toLong(), TimeUnit.SECONDS)) } catch (ignore: WaitTimedOutError) { } } fun <ComponentType : Component> findAllWithBFS(container: Container, clazz: Class<ComponentType>): List<ComponentType> { val result = LinkedList<ComponentType>() val queue: Queue<Component> = LinkedList() @Suppress("UNCHECKED_CAST") fun check(container: Component) { if (clazz.isInstance(container)) result.add(container as ComponentType) } queue.add(container) while (queue.isNotEmpty()) { val polled = queue.poll() check(polled) if (polled is Container) queue.addAll(polled.components) } return result } fun <ComponentType : Component> waitUntilGone(robot: Robot, timeout: Timeout = Timeouts.seconds30, root: Container? = null, matcher: GenericTypeMatcher<ComponentType>) { return GuiTestUtil.waitUntilGone(root, timeout, matcher) } fun GuiTestCase.waitProgressDialogUntilGone(dialogTitle: String, predicate: FinderPredicate = Predicate.equality, timeoutToAppear: Timeout = Timeouts.seconds05, timeoutToGone: Timeout = Timeouts.defaultTimeout) { waitProgressDialogUntilGone(this.robot(), dialogTitle, predicate, timeoutToAppear, timeoutToGone) } fun waitProgressDialogUntilGone(robot: Robot, progressTitle: String, predicate: FinderPredicate = Predicate.equality, timeoutToAppear: Timeout = Timeouts.seconds30, timeoutToGone: Timeout = Timeouts.defaultTimeout) { //wait dialog appearance. In a bad case we could pass dialog appearance. var dialog: JDialog? = null try { waitUntil("progress dialog with title $progressTitle will appear", timeoutToAppear) { dialog = findProgressDialog(robot, progressTitle, predicate) dialog != null } } catch (timeoutError: WaitTimedOutError) { return } waitUntil("progress dialog with title $progressTitle will gone", timeoutToGone) { dialog == null || !dialog!!.isShowing } } fun findProgressDialog(robot: Robot, progressTitle: String, predicate: FinderPredicate = Predicate.equality): JDialog? { return robot.finder().findAll(typeMatcher(JDialog::class.java) { dialog: JDialog -> findAllWithBFS(dialog, EngravedLabel::class.java).filter { it.isShowing && predicate(it.text, progressTitle) }.any() }).firstOrNull() } fun <ComponentType : Component?> typeMatcher(componentTypeClass: Class<ComponentType>, matcher: (ComponentType) -> Boolean): GenericTypeMatcher<ComponentType> { return object : GenericTypeMatcher<ComponentType>(componentTypeClass) { override fun isMatching(component: ComponentType): Boolean = matcher(component) } } fun <ReturnType> computeOnEdt(query: () -> ReturnType): ReturnType? = GuiActionRunner.execute(object : GuiQuery<ReturnType>() { override fun executeInEDT(): ReturnType = query() }) fun <ReturnType> computeOnEdtWithTry(query: () -> ReturnType?): ReturnType? { val result = GuiActionRunner.execute(object : GuiQuery<Pair<ReturnType?, Throwable?>>() { override fun executeInEDT(): kotlin.Pair<ReturnType?, Throwable?> { return try { Pair(query(), null) } catch (e: Exception) { Pair(null, e) } } }) if (result?.second != null) throw result.second!! return result?.first } inline fun <T> ignoreComponentLookupException(action: () -> T): T? = try { action() } catch (ignore: ComponentLookupException) { null } fun ensureCreateHasDone(guiTestCase: GuiTestCase) { try { com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntilGone(robot = guiTestCase.robot(), matcher = com.intellij.testGuiFramework.impl.GuiTestUtilKt.typeMatcher( com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame::class.java) { it.isShowing }) } catch (timeoutError: WaitTimedOutError) { with(guiTestCase) { welcomeFrame { button("Create").clickWhenEnabled() } } } } fun windowsShowing(): List<Window> { val listBuilder = ArrayList<Window>() Window.getWindows().filterTo(listBuilder) { it.isShowing } return listBuilder } fun fatalErrorsFromIde(afterDate: Date = Date(0)): List<Error> { val errorMessages = MessagePool.getInstance().getFatalErrors(true, true) val freshErrorMessages = errorMessages.filter { it.date > afterDate } val errors = mutableListOf<Error>() for (errorMessage in freshErrorMessages) { val messageBuilder = StringBuilder(errorMessage.message ?: "") val additionalInfo: String? = errorMessage.additionalInfo if (additionalInfo != null && additionalInfo.isNotEmpty()) messageBuilder.append(System.getProperty("line.separator")).append("Additional Info: ").append(additionalInfo) val error = Error(messageBuilder.toString(), errorMessage.throwable) errors.add(error) } return Collections.unmodifiableList(errors) } fun waitForBackgroundTasks(robot: Robot, timeoutInSeconds: Int = 120) { Wait.seconds(timeoutInSeconds.toLong()).expecting("background tasks to finish") .until { robot.waitForIdle() val progressManager = ProgressManager.getInstance() !progressManager.hasModalProgressIndicator() && !progressManager.hasProgressIndicator() && !progressManager.hasUnsafeProgressIndicator() } } } fun main(args: Array<String>) { val tree = GuiTestUtilKt.createTree("project\n" + " src\n" + " com.username\n" + " Test1.java\n" + " Test2.java\n" + " lib\n" + " someLib1\n" + " someLib2") tree.print() }
codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/classtree/ObjCMethod.kt
1203319124
package com.stanfy.helium.handler.codegen.objectivec.entity.classtree import java.util.* /** * Created by paultaykalo on 12/18/15. */ class ObjCMethod(val name: String, val methodType: ObjCMethod.ObjCMethodType, var returnType: String) { enum class ObjCMethodType { CLASS, INSTANCE } constructor(name: String) : this(name, ObjCMethodType.INSTANCE, "void") data class ParameterPair(val type: String, val name: String) /** * List of parameters * Enry key is a type * Entry value is parameter name */ val parameters = ArrayList<ParameterPair>(); /** * Adds parameter to the list of parameters * @param type parameter type * @param name parameter name */ fun addParameter(type: String, name: String) { parameters.add(ParameterPair(type, name)) } }
core/src/test/java/org/hisp/dhis/android/core/trackedentity/ownership/ProgramOwnerShould.kt
3240903912
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.ownership import com.google.common.truth.Truth.assertThat import org.hisp.dhis.android.core.common.BaseObjectShould import org.hisp.dhis.android.core.common.ObjectShould import org.junit.Test class ProgramOwnerShould : BaseObjectShould("trackedentity/ownership/program_owner.json"), ObjectShould { @Test override fun map_from_json_string() { val programOwner = objectMapper.readValue(jsonStream, ProgramOwner::class.java) assertThat(programOwner.program()).isEqualTo("lxAQ7Zs9VYR") assertThat(programOwner.trackedEntityInstance()).isEqualTo("PgmUFEQYZdt") assertThat(programOwner.ownerOrgUnit()).isEqualTo("DiszpKrYNg8") } }
generator/src/main/kotlin/com/android/gradle/replicator/generator/AndroidInfoGenerator.kt
888734533
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.android.gradle.replicator.generator import com.android.gradle.replicator.generator.manifest.ManifestGenerator import com.android.gradle.replicator.generator.writer.DslWriter import com.android.gradle.replicator.model.AndroidInfo import com.android.gradle.replicator.model.BuildFeaturesInfo import java.io.File internal fun AndroidInfo.generate( folder: File, dslWriter: DslWriter, manifestGenerator: ManifestGenerator, gradlePath: String, hasKotlin: Boolean) { // generate the android block dslWriter.block("android") { // FIXME? assign("compileSdkVersion", asString(compileSdkVersion)) block("defaultConfig") { call("minSdkVersion", minSdkVersion) call("targetSdkVersion", targetSdkVersion) } block("compileOptions") { assign("sourceCompatibility", "JavaVersion.VERSION_1_8") assign("targetCompatibility", "JavaVersion.VERSION_1_8") } // For Kotlin projects if (hasKotlin) { block("kotlinOptions") { assign("jvmTarget", asString("1.8")) } } buildFeatures.generateBuildFeatures(dslWriter) } // generate a main manifest. // compute package name based on gradle path // add "pkg.android." prefix to package in order to guarantee at least 2 segments to the package since it's // by aapt val packageName = "pkg.android.${gradlePath.split(":").filter { it.isNotBlank() }.joinToString(".")}" manifestGenerator.generateManifest(folder, packageName) } private fun BuildFeaturesInfo.generateBuildFeatures(dslWriter: DslWriter) { if (!hasFeatures()) return dslWriter.block("buildFeatures") { aidl?.let { assign("aidl", it) } buildConfig?.let { assign("buildConfig", it) } androidResources?.let { assign("androidResources", it) } compose?.let { assign("compose", it) } dataBinding?.let { assign("dataBinding", it) } mlModelBinding?.let { assign("mlModelBinding", it) } prefab?.let { assign("prefab", it) } prefabPublishing?.let { assign("prefabPublishing", it) } renderScript?.let { assign("renderScript", it) } resValues?.let { assign("resValues", it) } shaders?.let { assign("shaders", it) } viewBinding?.let { assign("viewBinding", it) } } }
src/test/kotlin/me/serce/solidity/lang/completion/SolCompletionTestBase.kt
3453533113
package me.serce.solidity.lang.completion import me.serce.solidity.utils.SolTestBase import org.intellij.lang.annotations.Language abstract class SolCompletionTestBase : SolTestBase() { protected fun checkCompletion(required: Set<String>, @Language("Solidity") code: String, strict: Boolean = false) { InlineFile(code).withCaret() val variants = myFixture.completeBasic() checkNotNull(variants) { "Expected completions that contain $required, but no completions found" } val completions = variants.map { it.lookupString }.toHashSet() if (strict) { assertEquals(required.toHashSet(), completions) } else { assertTrue("$completions doesn't contain all $required", completions.containsAll(required)) } } }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/GradleImportHelper.kt
3093314968
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleJava.scripting import com.intellij.diff.util.DiffUtil import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.components.service import com.intellij.openapi.editor.Editor import com.intellij.openapi.externalSystem.importing.ImportSpecBuilder import com.intellij.openapi.externalSystem.util.ExternalSystemUtil import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.Project import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightVirtualFileBase import org.gradle.tooling.model.kotlin.dsl.KotlinDslModelsParameters import org.gradle.util.GradleVersion import org.jetbrains.annotations.Nls import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle import org.jetbrains.kotlin.idea.gradleJava.scripting.importing.KotlinDslScriptModelResolver import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRoot import org.jetbrains.kotlin.idea.gradleJava.scripting.roots.GradleBuildRootsManager import org.jetbrains.kotlin.idea.util.isKotlinFileType import org.jetbrains.kotlin.scripting.definitions.ScriptDefinitionProvider import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition import org.jetbrains.plugins.gradle.service.GradleInstallationManager import org.jetbrains.plugins.gradle.service.project.GradlePartialResolverPolicy import org.jetbrains.plugins.gradle.settings.GradleProjectSettings import org.jetbrains.plugins.gradle.util.GradleConstants val scriptConfigurationsNeedToBeUpdatedBalloon get() = Registry.`is`("kotlin.gradle.scripts.scriptConfigurationsNeedToBeUpdatedFloatingNotification", true) fun runPartialGradleImportForAllRoots(project: Project) { GradleBuildRootsManager.getInstance(project)?.getAllRoots()?.forEach { root -> runPartialGradleImport(project, root) } } fun runPartialGradleImport(project: Project, root: GradleBuildRoot) { if (root.isImportingInProgress()) return ExternalSystemUtil.refreshProject( root.pathPrefix, ImportSpecBuilder(project, GradleConstants.SYSTEM_ID) .withVmOptions( "-D${KotlinDslModelsParameters.PROVIDER_MODE_SYSTEM_PROPERTY_NAME}=" + KotlinDslModelsParameters.CLASSPATH_MODE_SYSTEM_PROPERTY_VALUE ) .projectResolverPolicy( GradlePartialResolverPolicy { it is KotlinDslScriptModelResolver } ) ) } @Nls fun configurationsAreMissingRequestNeeded() = KotlinIdeaGradleBundle.message("notification.wasNotImportedAfterCreation.text") @Nls fun getConfigurationsActionText() = KotlinIdeaGradleBundle.message("action.text.load.script.configurations") @Nls fun configurationsAreMissingRequestNeededHelp(): String = KotlinIdeaGradleBundle.message("notification.wasNotImportedAfterCreation.help") @Nls fun configurationsAreMissingAfterRequest(): String = KotlinIdeaGradleBundle.message("notification.notEvaluatedInLastImport.text") fun autoReloadScriptConfigurations(project: Project, file: VirtualFile): Boolean { val definition = file.findScriptDefinition(project) ?: return false return KotlinScriptingSettings.getInstance(project).autoReloadConfigurations(definition) } fun scriptConfigurationsNeedToBeUpdated(project: Project, file: VirtualFile) { if (autoReloadScriptConfigurations(project, file)) { GradleBuildRootsManager.getInstance(project)?.getScriptInfo(file)?.buildRoot?.let { runPartialGradleImport(project, it) } } else { // notification is shown in LoadConfigurationAction } } fun scriptConfigurationsAreUpToDate(project: Project): Boolean = true class LoadConfigurationAction : AnAction( KotlinIdeaGradleBundle.message("action.text.load.script.configurations"), KotlinIdeaGradleBundle.message("action.description.load.script.configurations"), KotlinIcons.LOAD_SCRIPT_CONFIGURATION ) { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val editor = e.getData(CommonDataKeys.EDITOR) ?: return val file = getKotlinScriptFile(editor) ?: return val root = GradleBuildRootsManager.getInstance(project)?.getScriptInfo(file)?.buildRoot ?: return runPartialGradleImport(project, root) } override fun update(e: AnActionEvent) { ensureValidActionVisibility(e) } private fun ensureValidActionVisibility(e: AnActionEvent) { val editor = e.getData(CommonDataKeys.EDITOR) ?: return e.presentation.isVisible = getNotificationVisibility(editor) } private fun getNotificationVisibility(editor: Editor): Boolean { if (!scriptConfigurationsNeedToBeUpdatedBalloon) return false if (DiffUtil.isDiffEditor(editor)) return false val project = editor.project ?: return false // prevent services initialization // (all services actually initialized under the ScriptDefinitionProvider during startup activity) if (ScriptDefinitionProvider.getServiceIfCreated(project) == null) return false val file = getKotlinScriptFile(editor) ?: return false if (autoReloadScriptConfigurations(project, file)) { return false } return GradleBuildRootsManager.getInstance(project)?.isConfigurationOutOfDate(file) ?: false } private fun getKotlinScriptFile(editor: Editor): VirtualFile? { return FileDocumentManager.getInstance() .getFile(editor.document) ?.takeIf { it !is LightVirtualFileBase && it.isValid && it.isKotlinFileType() && isGradleKotlinScript(it) } } } fun getGradleVersion(project: Project, settings: GradleProjectSettings): String { return GradleInstallationManager.getGradleVersion( service<GradleInstallationManager>().getGradleHome(project, settings.externalProjectPath)?.path ) ?: GradleVersion.current().version }
plugins/kotlin/idea/tests/testData/intentions/introduceImportAlias/notApplicableLocalVariable.kt
2002662345
// IS_APPLICABLE: false class Test() { fun test() { val i = Test() val b = i<caret> } }
plugins/kotlin/j2k/new/tests/testData/newJ2k/arrayType/methodArrayArgs.kt
3491315209
fun fromArrayToCollection(a: Array<Foo?>?) {}
app/src/main/java/soutvoid/com/DsrWeatherApp/ui/screen/weather/widgets/TimeOfDayWeatherView.kt
4235571942
package soutvoid.com.DsrWeatherApp.ui.screen.weather.widgets import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.FrameLayout import butterknife.ButterKnife import com.mikepenz.iconics.IconicsDrawable import soutvoid.com.DsrWeatherApp.R import soutvoid.com.DsrWeatherApp.domain.ThreeHoursForecast import soutvoid.com.DsrWeatherApp.ui.screen.weather.data.TimeOfDay import soutvoid.com.DsrWeatherApp.ui.util.UnitsUtils import soutvoid.com.DsrWeatherApp.ui.util.WeatherIconsHelper import soutvoid.com.DsrWeatherApp.ui.util.getThemeColor import java.util.* import kotlinx.android.synthetic.main.view_time_of_day_weather.view.* import soutvoid.com.DsrWeatherApp.ui.util.CalendarUtils /** * view для отображения погоды в определенное время дня (утро, день и тд) */ class TimeOfDayWeatherView : FrameLayout { constructor(context: Context) : super(context) constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) init { View.inflate(context, R.layout.view_time_of_day_weather, this) ButterKnife.bind(this) } fun setWeather(threeHoursForecast: ThreeHoursForecast, locale: Locale = Locale.getDefault()) { with(threeHoursForecast) { val calendar: Calendar = Calendar.getInstance(locale) calendar.timeInMillis = timeOfData * 1000 view_tod_weather_date.text = getDateString(threeHoursForecast.timeOfData) view_tod_weather_name.text = getTimeOfDayNameByHour(calendar.get(Calendar.HOUR_OF_DAY)) view_tod_weather_icon.setImageDrawable(IconicsDrawable(context) .icon(WeatherIconsHelper.getWeatherIcon(weather[0].id, timeOfData)) .color(context.getThemeColor(android.R.attr.textColorPrimary)) .sizeDp(32)) view_tod_weather_temperature.text = "${Math.round(main.temperature)} ${UnitsUtils.getDegreesUnits(context)}" view_tod_weather_wind_icon.setImageDrawable(IconicsDrawable(context) .icon(WeatherIconsHelper.getDirectionalIcon(wind.degrees)) .color(context.getThemeColor(android.R.attr.textColorPrimary)) .sizeDp(16)) view_tod_weather_wind.text = wind.speed.toString() view_tod_weather_wind_units.text = UnitsUtils.getVelocityUnits(context) } } private fun getTimeOfDayNameByHour(hour: Int): String { val timeOfDay = TimeOfDay.getByTime(hour) when(timeOfDay) { TimeOfDay.MORNING -> return context.getString(R.string.morning) TimeOfDay.DAY -> return context.getString(R.string.day) TimeOfDay.EVENING -> return context.getString(R.string.evening) else -> return context.getString(R.string.night) } } private fun getDateString(dt: Long): String { var dateStr = CalendarUtils.getNumericDate(dt) if (CalendarUtils.isToday(dt)) dateStr = context.getString(R.string.today) else if (CalendarUtils.isTomorrow(dt)) dateStr = context.getString(R.string.tomorrow) return dateStr } }
app/src/test/java/co/smartreceipts/android/autocomplete/receipt/ReceiptAutoCompleteResultsCheckerTest.kt
3129516195
package co.smartreceipts.android.autocomplete.receipt import co.smartreceipts.android.autocomplete.AutoCompleteField import co.smartreceipts.android.model.Receipt import com.nhaarman.mockitokotlin2.whenever import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.MockitoAnnotations import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class ReceiptAutoCompleteResultsCheckerTest { companion object { private const val NAME = "name" private const val COMMENT = "comment" } private val resultsChecker: ReceiptAutoCompleteResultsChecker = ReceiptAutoCompleteResultsChecker() @Mock private lateinit var receipt: Receipt @Before fun setUp() { MockitoAnnotations.initMocks(this) whenever(receipt.name).thenReturn(NAME) whenever(receipt.comment).thenReturn(COMMENT) } @Test fun matchesInput() { assertTrue(resultsChecker.matchesInput("n", ReceiptAutoCompleteField.Name, receipt)) assertTrue(resultsChecker.matchesInput("na", ReceiptAutoCompleteField.Name, receipt)) assertTrue(resultsChecker.matchesInput("nam", ReceiptAutoCompleteField.Name, receipt)) assertTrue(resultsChecker.matchesInput("name", ReceiptAutoCompleteField.Name, receipt)) assertTrue(resultsChecker.matchesInput("c", ReceiptAutoCompleteField.Comment, receipt)) assertTrue(resultsChecker.matchesInput("co", ReceiptAutoCompleteField.Comment, receipt)) assertTrue(resultsChecker.matchesInput("com", ReceiptAutoCompleteField.Comment, receipt)) assertTrue(resultsChecker.matchesInput("comm", ReceiptAutoCompleteField.Comment, receipt)) assertTrue(resultsChecker.matchesInput("comme", ReceiptAutoCompleteField.Comment, receipt)) assertTrue(resultsChecker.matchesInput("commen", ReceiptAutoCompleteField.Comment, receipt)) assertTrue(resultsChecker.matchesInput("comment", ReceiptAutoCompleteField.Comment, receipt)) assertFalse(resultsChecker.matchesInput("comment", ReceiptAutoCompleteField.Name, receipt)) assertFalse(resultsChecker.matchesInput("name", ReceiptAutoCompleteField.Comment, receipt)) assertFalse(resultsChecker.matchesInput("name", mock(AutoCompleteField::class.java), receipt)) assertFalse(resultsChecker.matchesInput("comment", mock(AutoCompleteField::class.java), receipt)) } @Test fun getValue() { assertEquals(NAME, resultsChecker.getValue(ReceiptAutoCompleteField.Name, receipt)) assertEquals(COMMENT, resultsChecker.getValue(ReceiptAutoCompleteField.Comment, receipt)) } @Test(expected = IllegalArgumentException::class) fun getValueForUnknownField() { resultsChecker.getValue(mock(AutoCompleteField::class.java), receipt) } }