repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/sync/GivenASetOfStoredItems/WhenSyncingTheStoredItemsAndAnErrorOccursDownloading.kt
1
4046
package com.lasthopesoftware.bluewater.client.stored.library.sync.GivenASetOfStoredItems import com.lasthopesoftware.bluewater.client.browsing.items.Item import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.ProvideLibraryFiles import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.FileListParameters import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.stored.library.items.IStoredItemAccess import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItem import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItemServiceFileCollector import com.lasthopesoftware.bluewater.client.stored.library.items.files.AccessStoredFiles import com.lasthopesoftware.bluewater.client.stored.library.items.files.PruneStoredFiles import com.lasthopesoftware.bluewater.client.stored.library.items.files.StoredFileSystemFileProducer import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobProcessor import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobState import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile import com.lasthopesoftware.bluewater.client.stored.library.items.files.updates.UpdateStoredFiles import com.lasthopesoftware.bluewater.client.stored.library.sync.LibrarySyncsHandler import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import com.namehillsoftware.handoff.promises.Promise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.Test import java.io.ByteArrayInputStream import java.io.IOException class WhenSyncingTheStoredItemsAndAnErrorOccursDownloading { companion object { private val storedFileJobResults by lazy { val storedItemAccessMock = mockk<IStoredItemAccess>() every { storedItemAccessMock.promiseStoredItems(LibraryId(42)) } returns Promise( setOf( StoredItem(1, 14, StoredItem.ItemType.ITEM) ) ) val fileListParameters = FileListParameters.getInstance() val mockFileProvider = mockk<ProvideLibraryFiles>() every { mockFileProvider.promiseFiles(LibraryId(42), FileListParameters.Options.None, *fileListParameters.getFileListParameters(Item(14))) } returns Promise( listOf( ServiceFile(1), ServiceFile(2), ServiceFile(4), ServiceFile(10) ) ) val storedFilesPruner = mockk<PruneStoredFiles>() every { storedFilesPruner.pruneDanglingFiles() } returns Unit.toPromise() every { storedFilesPruner.pruneStoredFiles(any()) } returns Unit.toPromise() val storedFilesUpdater = mockk<UpdateStoredFiles>() every { storedFilesUpdater.promiseStoredFileUpdate(any(), any()) } answers { Promise( StoredFile( firstArg(), 1, secondArg(), "fake-file-name", true ) ) } val accessStoredFiles = mockk<AccessStoredFiles>() every { accessStoredFiles.markStoredFileAsDownloaded(any()) } answers { Promise(firstArg<StoredFile>()) } val librarySyncHandler = LibrarySyncsHandler( StoredItemServiceFileCollector( storedItemAccessMock, mockFileProvider, fileListParameters ), storedFilesPruner, storedFilesUpdater, StoredFileJobProcessor( StoredFileSystemFileProducer(), accessStoredFiles, { _, f -> if (f.serviceId == 2) Promise(IOException()) else Promise(ByteArrayInputStream(ByteArray(0))) }, { true }, { true }, { _, _ -> }) ) librarySyncHandler.observeLibrarySync(LibraryId(42)) .filter { j -> j.storedFileJobState == StoredFileJobState.Downloaded } .map { j -> j.storedFile } .toList() .blockingGet() } } @Test fun thenTheOtherFilesInTheStoredItemsAreSynced() { assertThat(storedFileJobResults.map { it.serviceId }).containsExactly(1, 4, 10) } }
lgpl-3.0
ce4a795edbb9da30ab9e9234803173c4
39.059406
160
0.782996
4.171134
false
false
false
false
GeoffreyMetais/vlc-android
application/vlc-android/src/org/videolan/vlc/gui/browser/FileBrowserFragment.kt
1
6745
/* * ************************************************************************* * FileBrowserFragment.java * ************************************************************************** * Copyright © 2015 VLC authors and VideoLAN * Author: Geoffrey Métais * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * *************************************************************************** */ package org.videolan.vlc.gui.browser import android.net.Uri import android.os.Bundle import android.text.TextUtils import android.view.Menu import android.view.MenuInflater import android.view.View import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.* import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.first import org.videolan.medialibrary.MLServiceLocator import org.videolan.medialibrary.interfaces.media.MediaWrapper import org.videolan.medialibrary.media.MediaLibraryItem import org.videolan.resources.AndroidDevices import org.videolan.resources.CTX_FAV_ADD import org.videolan.tools.removeFileProtocole import org.videolan.vlc.ExternalMonitor import org.videolan.vlc.R import org.videolan.vlc.gui.helpers.MedialibraryUtils import org.videolan.vlc.gui.helpers.hf.OtgAccess import org.videolan.vlc.gui.helpers.hf.requestOtgRoot import org.videolan.vlc.util.FileUtils import org.videolan.vlc.viewmodels.browser.TYPE_FILE import org.videolan.vlc.viewmodels.browser.getBrowserModel @ObsoleteCoroutinesApi @ExperimentalCoroutinesApi open class FileBrowserFragment : BaseBrowserFragment() { private var needsRefresh: Boolean = false override val categoryTitle: String get() = getString(R.string.directories) override fun createFragment(): Fragment { return FileBrowserFragment() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupBrowser() } override fun onStart() { super.onStart() if (needsRefresh) viewModel.browseRoot() } override fun onStop() { super.onStop() if (isRootDirectory && adapter.isEmpty()) needsRefresh = true } override fun registerSwiperRefreshlayout() { if (!isRootDirectory) super.registerSwiperRefreshlayout() else swipeRefreshLayout.isEnabled = false } protected open fun setupBrowser() { viewModel = getBrowserModel(category = TYPE_FILE, url = if (!isRootDirectory) mrl else null, showHiddenFiles = showHiddenFiles) } override fun getTitle(): String = if (isRootDirectory) categoryTitle else { when { currentMedia != null -> when { TextUtils.equals(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY, mrl?.removeFileProtocole()) -> getString(R.string.internal_memory) this is FilePickerFragment -> currentMedia!!.uri.toString() else -> currentMedia!!.title } this is FilePickerFragment -> mrl ?: "" else -> FileUtils.getFileNameFromPath(mrl) } } public override fun browseRoot() { viewModel.browseRoot() } override fun onClick(v: View, position: Int, item: MediaLibraryItem) { if (item.itemType == MediaLibraryItem.TYPE_MEDIA) { val mw = item as MediaWrapper if ("otg://" == mw.location) { val title = getString(R.string.otg_device_title) val rootUri = OtgAccess.otgRoot.value if (rootUri != null && ExternalMonitor.devices.size == 1) { browseOtgDevice(rootUri, title) } else { lifecycleScope.launchWhenStarted { val uri = OtgAccess.otgRoot.filterNotNull().first() browseOtgDevice(uri, title) } requireActivity().requestOtgRoot() } return } } super.onClick(v, position, item) } override fun onCtxAction(position: Int, option: Long) { val mw = this.adapter.getItem(position) as MediaWrapper? when (option) { CTX_FAV_ADD -> lifecycleScope.launch { browserFavRepository.addLocalFavItem(mw!!.uri, mw.title, mw.artworkURL) } else -> super.onCtxAction(position, option) } } override fun onMainActionClick(v: View, position: Int, item: MediaLibraryItem) {} override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { if (!(this is FilePickerFragment || this is StorageBrowserFragment)) inflater.inflate(R.menu.fragment_option_network, menu) super.onCreateOptionsMenu(menu, inflater) } override fun containerActivity() = requireActivity() override val isNetwork = false override val isFile = true override fun onPrepareOptionsMenu(menu: Menu) { super.onPrepareOptionsMenu(menu) val item = menu.findItem(R.id.ml_menu_save) ?: return item.isVisible = !isRootDirectory && mrl!!.startsWith("file") lifecycleScope.launchWhenStarted { mrl?.let { val isScanned = withContext(Dispatchers.IO) { MedialibraryUtils.isScanned(it) } menu.findItem(R.id.ml_menu_scan)?.isVisible = !isRootDirectory && it.startsWith("file") && !isScanned } val isFavorite = mrl != null && browserFavRepository.browserFavExists(Uri.parse(mrl)) item.setIcon(if (isFavorite) R.drawable.ic_menu_bookmark_w else R.drawable.ic_menu_bookmark_outline_w) item.setTitle(if (isFavorite) R.string.favorites_remove else R.string.favorites_add) } } private fun browseOtgDevice(uri: Uri, title: String) { val mw = MLServiceLocator.getAbstractMediaWrapper(uri) mw.type = MediaWrapper.TYPE_DIR mw.title = title handler.post { browse(mw, true) } } }
gpl-2.0
9161afd849845ba3d52054abf379d86b
37.096045
141
0.647041
4.712089
false
false
false
false
tasks/tasks
app/src/main/java/org/tasks/data/UpgraderDao.kt
1
1030
package org.tasks.data import androidx.room.Dao import androidx.room.Query @Dao interface UpgraderDao { @Query(""" SELECT task.*, caldav_task.* FROM tasks AS task INNER JOIN caldav_tasks AS caldav_task ON _id = cd_task WHERE cd_deleted = 0 """) suspend fun tasksWithVtodos(): List<CaldavTaskContainer> @Query(""" SELECT tasks._id FROM tasks INNER JOIN tags ON tags.task = tasks._id INNER JOIN caldav_tasks ON cd_task = tasks._id GROUP BY tasks._id """) suspend fun tasksWithTags(): List<Long> @Query(""" SELECT task.*, caldav_task.* FROM tasks AS task INNER JOIN caldav_tasks AS caldav_task ON _id = cd_task INNER JOIN caldav_lists ON cd_calendar = cdl_uuid WHERE cd_deleted = 0 AND cdl_account = :account AND cdl_url = :url """) suspend fun getOpenTasksForList(account: String, url: String): List<CaldavTaskContainer> @Query("UPDATE tasks SET hideUntil = :startDate WHERE _id = :task") fun setStartDate(task: Long, startDate: Long) }
gpl-3.0
c47d22561f97e152cbf129d773523fa9
26.864865
92
0.673786
3.639576
false
false
false
false
fallGamlet/DnestrCinema
app/src/main/java/com/fallgamlet/dnestrcinema/ui/news/NewsViewModelImpl.kt
1
1272
package com.fallgamlet.dnestrcinema.ui.news import androidx.lifecycle.ViewModel import com.fallgamlet.dnestrcinema.app.AppFacade import com.fallgamlet.dnestrcinema.domain.models.NewsItem import com.fallgamlet.dnestrcinema.utils.LiveDataUtils import com.fallgamlet.dnestrcinema.utils.reactive.mapTrue import com.fallgamlet.dnestrcinema.utils.reactive.schedulersIoToUi import com.fallgamlet.dnestrcinema.utils.reactive.subscribeDisposable class NewsViewModelImpl : ViewModel() { val viewState = NewsViewState() private var newsItems: List<NewsItem> = emptyList() init { loadData() } fun loadData() { val client = AppFacade.instance.netClient ?: return viewState.loading.value = true client.news .schedulersIoToUi() .doOnNext { newsItems = it } .doOnError { viewState.error.value = it } .mapTrue() .doOnComplete { viewState.items.value = newsItems viewState.loading.value = false } .subscribeDisposable() } fun refreshViewState() { LiveDataUtils.refreshSignal( viewState.error, viewState.loading ) viewState.items.value = newsItems } }
gpl-3.0
712e2af3699084c0345d64372235ff56
26.06383
69
0.66195
4.8
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/table/Column.kt
1
1407
/* ParaTask Copyright (C) 2017 Nick Robinson This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.table import javafx.beans.value.ObservableValue import javafx.scene.control.TableColumn import uk.co.nickthecoder.paratask.util.Labelled import uk.co.nickthecoder.paratask.util.uncamel open class Column<R, T>( val name: String, width: Int? = null, override val label: String = name.uncamel(), val getter: (R) -> T, val filterGetter: (R) -> Any? = getter) : TableColumn<WrappedRow<R>, T>(label), Labelled { init { @Suppress("UNCHECKED_CAST") setCellValueFactory { p -> p.value.observable(name, getter) as ObservableValue<T> } isEditable = false if (width != null) { prefWidth = width.toDouble() } } }
gpl-3.0
43d3eecaae0ecba3d678bf9ede839c42
32.5
91
0.707178
4.102041
false
false
false
false
MimiReader/mimi-reader
mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/dao/BoardAccess.kt
1
2102
package com.emogoth.android.phone.mimi.db.dao import androidx.room.Dao import androidx.room.Query import androidx.room.Update import com.emogoth.android.phone.mimi.db.MimiDatabase import com.emogoth.android.phone.mimi.db.models.Board import io.reactivex.Flowable import io.reactivex.Single @Dao abstract class BoardAccess : BaseDao<Board>() { @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE}") abstract fun getAll(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1") abstract fun getVisibleBoards(): Flowable<List<Board>> @Query(value = "SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.NAME} ASC") abstract fun getAllOrderByName(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.TITLE} ASC") abstract fun getAllOrderByTitle(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.ACCESS_COUNT} DESC") abstract fun getAllOrderByAccessCount(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.POST_COUNT} DESC") abstract fun getAllOrderByPostCount(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.LAST_ACCESSED} DESC") abstract fun getAllOrderByLastAccessed(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.FAVORITE} DESC") abstract fun getAllOrderByFavorite(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.ORDER_INDEX} ASC") abstract fun getAllOrderByCustom(): Flowable<List<Board>> @Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.NAME} = :boardName") abstract fun getBoard(boardName: String): Single<Board> @Update abstract fun updateBoard(vararg board: Board): Int }
apache-2.0
26f49c0abbecd378a0870ceb85677d53
45.711111
121
0.721218
3.856881
false
false
false
false
stripe/stripe-android
paymentsheet-example/src/androidTestDebug/java/com/stripe/android/test/core/TestConstants.kt
1
688
package com.stripe.android.test.core import androidx.test.platform.app.InstrumentationRegistry import java.io.File import java.text.SimpleDateFormat import java.util.Date const val INDIVIDUAL_TEST_TIMEOUT_SECONDS = 90L const val HOOKS_PAGE_LOAD_TIMEOUT = 60L const val TEST_IBAN_NUMBER = "DE89370400440532013000" val testArtifactDirectoryOnDevice by lazy { val pattern = "yyyy-MM-dd-HH-mm" val simpleDateFormat = SimpleDateFormat(pattern) val date = simpleDateFormat.format(Date()) File( // Path is /data/user/0/com.stripe.android.paymentsheet.example/files/ InstrumentationRegistry.getInstrumentation().targetContext.filesDir, "$date/" ) }
mit
d5d07fba2f92ffe13f4e0fb2a26b306b
31.761905
78
0.757267
3.801105
false
true
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/model/parsers/Stripe3ds2AuthResultJsonParser.kt
1
7051
package com.stripe.android.model.parsers import com.stripe.android.core.model.StripeJsonUtils.optString import com.stripe.android.core.model.parsers.ModelJsonParser import com.stripe.android.model.Stripe3ds2AuthResult import org.json.JSONArray import org.json.JSONObject internal class Stripe3ds2AuthResultJsonParser : ModelJsonParser<Stripe3ds2AuthResult> { override fun parse(json: JSONObject): Stripe3ds2AuthResult { return Stripe3ds2AuthResult( id = json.getString(FIELD_ID), created = json.getLong(FIELD_CREATED), liveMode = json.getBoolean(FIELD_LIVEMODE), source = json.getString(FIELD_SOURCE), state = json.optString(FIELD_STATE), ares = json.optJSONObject(FIELD_ARES)?.let { AresJsonParser().parse(it) }, error = json.optJSONObject(FIELD_ERROR)?.let { ThreeDS2ErrorJsonParser().parse(it) }, fallbackRedirectUrl = optString(json, FIELD_FALLBACK_REDIRECT_URL), creq = optString(json, FIELD_CREQ) ) } internal class AresJsonParser : ModelJsonParser<Stripe3ds2AuthResult.Ares> { override fun parse(json: JSONObject): Stripe3ds2AuthResult.Ares { return Stripe3ds2AuthResult.Ares( threeDSServerTransId = optString(json, FIELD_THREE_DS_SERVER_TRANS_ID), acsChallengeMandated = optString(json, FIELD_ACS_CHALLENGE_MANDATED), acsSignedContent = optString(json, FIELD_ACS_SIGNED_CONTENT), acsTransId = json.getString(FIELD_ACS_TRANS_ID), acsUrl = optString(json, FIELD_ACS_URL), authenticationType = optString(json, FIELD_AUTHENTICATION_TYPE), cardholderInfo = optString(json, FIELD_CARDHOLDER_INFO), messageType = json.getString(FIELD_MESSAGE_TYPE), messageVersion = json.getString(FIELD_MESSAGE_VERSION), sdkTransId = optString(json, FIELD_SDK_TRANS_ID), transStatus = optString(json, FIELD_TRANS_STATUS), messageExtension = json.optJSONArray(FIELD_MESSAGE_EXTENSION)?.let { MessageExtensionJsonParser().parse(it) } ) } private companion object { private const val FIELD_ACS_CHALLENGE_MANDATED = "acsChallengeMandated" private const val FIELD_ACS_SIGNED_CONTENT = "acsSignedContent" private const val FIELD_ACS_TRANS_ID = "acsTransID" private const val FIELD_ACS_URL = "acsURL" private const val FIELD_AUTHENTICATION_TYPE = "authenticationType" private const val FIELD_CARDHOLDER_INFO = "cardholderInfo" private const val FIELD_MESSAGE_EXTENSION = "messageExtension" private const val FIELD_MESSAGE_TYPE = "messageType" private const val FIELD_MESSAGE_VERSION = "messageVersion" private const val FIELD_SDK_TRANS_ID = "sdkTransID" private const val FIELD_TRANS_STATUS = "transStatus" private const val FIELD_THREE_DS_SERVER_TRANS_ID = "threeDSServerTransID" } } internal class MessageExtensionJsonParser : ModelJsonParser<Stripe3ds2AuthResult.MessageExtension> { fun parse(jsonArray: JSONArray): List<Stripe3ds2AuthResult.MessageExtension> { return (0 until jsonArray.length()) .mapNotNull { jsonArray.optJSONObject(it) } .map { parse(it) } } override fun parse(json: JSONObject): Stripe3ds2AuthResult.MessageExtension { val dataJson = json.optJSONObject(FIELD_DATA) val data = if (dataJson != null) { val keys = dataJson.names() ?: JSONArray() (0 until keys.length()) .map { idx -> keys.getString(idx) } .map { key -> mapOf(key to dataJson.getString(key)) } .fold(emptyMap<String, String>()) { acc, map -> acc.plus(map) } } else { emptyMap() } return Stripe3ds2AuthResult.MessageExtension( name = optString(json, FIELD_NAME), criticalityIndicator = json.optBoolean(FIELD_CRITICALITY_INDICATOR), id = optString(json, FIELD_ID), data = data.toMap() ) } private companion object { private const val FIELD_NAME = "name" private const val FIELD_ID = "id" private const val FIELD_CRITICALITY_INDICATOR = "criticalityIndicator" private const val FIELD_DATA = "data" } } internal class ThreeDS2ErrorJsonParser : ModelJsonParser<Stripe3ds2AuthResult.ThreeDS2Error> { override fun parse(json: JSONObject): Stripe3ds2AuthResult.ThreeDS2Error { return Stripe3ds2AuthResult.ThreeDS2Error( threeDSServerTransId = json.getString(FIELD_THREE_DS_SERVER_TRANS_ID), acsTransId = optString(json, FIELD_ACS_TRANS_ID), dsTransId = optString(json, FIELD_DS_TRANS_ID), errorCode = json.getString(FIELD_ERROR_CODE), errorComponent = json.getString(FIELD_ERROR_COMPONENT), errorDescription = json.getString(FIELD_ERROR_DESCRIPTION), errorDetail = json.getString(FIELD_ERROR_DETAIL), errorMessageType = optString(json, FIELD_ERROR_MESSAGE_TYPE), messageType = json.getString(FIELD_MESSAGE_TYPE), messageVersion = json.getString(FIELD_MESSAGE_VERSION), sdkTransId = optString(json, FIELD_SDK_TRANS_ID) ) } private companion object { private const val FIELD_THREE_DS_SERVER_TRANS_ID = "threeDSServerTransID" private const val FIELD_ACS_TRANS_ID = "acsTransID" private const val FIELD_DS_TRANS_ID = "dsTransID" private const val FIELD_ERROR_CODE = "errorCode" private const val FIELD_ERROR_COMPONENT = "errorComponent" private const val FIELD_ERROR_DESCRIPTION = "errorDescription" private const val FIELD_ERROR_DETAIL = "errorDetail" private const val FIELD_ERROR_MESSAGE_TYPE = "errorMessageType" private const val FIELD_MESSAGE_TYPE = "messageType" private const val FIELD_MESSAGE_VERSION = "messageVersion" private const val FIELD_SDK_TRANS_ID = "sdkTransID" } } private companion object { private const val FIELD_ID = "id" private const val FIELD_ARES = "ares" private const val FIELD_CREATED = "created" private const val FIELD_CREQ = "creq" private const val FIELD_ERROR = "error" private const val FIELD_FALLBACK_REDIRECT_URL = "fallback_redirect_url" private const val FIELD_LIVEMODE = "livemode" private const val FIELD_SOURCE = "source" private const val FIELD_STATE = "state" } }
mit
548762d7203d21e63e15be87b305821e
48.307692
98
0.624592
4.473985
false
false
false
false
stripe/stripe-android
example/src/main/java/com/stripe/example/service/ExampleEphemeralKeyProvider.kt
1
1746
package com.stripe.example.service import android.content.Context import androidx.annotation.Size import com.stripe.android.EphemeralKeyProvider import com.stripe.android.EphemeralKeyUpdateListener import com.stripe.example.Settings import com.stripe.example.module.BackendApiFactory import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.CoroutineContext /** * An implementation of [EphemeralKeyProvider] that can be used to generate * ephemeral keys on the backend. */ internal class ExampleEphemeralKeyProvider( backendUrl: String, private val workContext: CoroutineContext ) : EphemeralKeyProvider { constructor(context: Context) : this( Settings(context).backendUrl, Dispatchers.IO ) private val backendApi = BackendApiFactory(backendUrl).create() override fun createEphemeralKey( @Size(min = 4) apiVersion: String, keyUpdateListener: EphemeralKeyUpdateListener ) { CoroutineScope(workContext).launch { val response = kotlin.runCatching { backendApi .createEphemeralKey(hashMapOf("api_version" to apiVersion)) .string() } withContext(Dispatchers.Main) { response.fold( onSuccess = { keyUpdateListener.onKeyUpdate(it) }, onFailure = { keyUpdateListener .onKeyUpdateFailure(0, it.message.orEmpty()) } ) } } } }
mit
c1a966e0ea69f55c5cf560a7f2132227
30.745455
83
0.629439
5.45625
false
false
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/card/PanFormatter.kt
1
6266
package com.stripe.android.stripecardscan.payment.card /* * The following are known PAN formats. The information in this table was taken from * https://baymard.com/checkout-usability/credit-card-patterns and indirectly from * https://web.archive.org/web/20170822221741/https://www.discovernetwork.com/downloads/IPP_VAR_Compliance.pdf * * | ------------------------- | ------- | ------------------------------------ | * | Issuer | PAN Len | Display Format | * | ------------------------- | ------- | ------------------------------------ | * | American Express | 15 | 4 - 6 - 5 | * | Diners Club International | 14 | 4 - 6 - 4 | * | Diners Club International | 15 | Unknown | * | Diners Club International | 16 | 4 - 4 - 4 - 4 | * | Diners Club International | 17 | Unknown | * | Diners Club International | 18 | Unknown | * | Diners Club International | 19 | Unknown | * | Discover | 16 | 4 - 4 - 4 - 4 | * | Discover | 17 | Unknown | * | Discover | 18 | Unknown | * | Discover | 19 | Unknown | * | MasterCard | 16 | 4 - 4 - 4 - 4 | * | MasterCard (Maestro) | 12 | Unknown | * | MasterCard (Maestro) | 13 | 4 - 4 - 5 | * | MasterCard (Maestro) | 14 | Unknown | * | MasterCard (Maestro) | 15 | 4 - 6 - 5 | * | MasterCard (Maestro) | 16 | 4 - 4 - 4 - 4 | * | MasterCard (Maestro) | 17 | Unknown | * | MasterCard (Maestro) | 18 | Unknown | * | MasterCard (Maestro) | 19 | 4 - 4 - 4 - 4 - 3 | * | UnionPay | 16 | 4 - 4 - 4 - 4 | * | UnionPay | 17 | Unknown | * | UnionPay | 18 | Unknown | * | UnionPay | 19 | 6 - 13 | * | Visa | 16 | 4 - 4 - 4 - 4 | * | ------------------------- | ------- | ------------------------------------ | */ /** * Format a card PAN for display. */ internal fun formatPan(pan: String) = normalizeCardNumber(pan).let { val issuer = getCardIssuer(pan) val formatter = CUSTOM_PAN_FORMAT_TABLE[issuer]?.get(pan.length) ?: PAN_FORMAT_TABLE[issuer]?.get(pan.length) ?: DEFAULT_PAN_FORMATTERS[pan.length] formatter?.formatPan(pan) ?: pan } /** * Add a new way to format a PAN */ internal fun addFormatPan(cardIssuer: CardIssuer, length: Int, vararg blockSizes: Int) { CUSTOM_PAN_FORMAT_TABLE.getOrPut(cardIssuer, { mutableMapOf() })[length] = PanFormatter(*blockSizes) } /** * A class that can format a PAN for display given a list of number block sizes. */ private class PanFormatter(vararg blockSizes: Int) { private val blockIndices = blockSizesToIndicies(blockSizes) private fun blockSizesToIndicies(blockSizes: IntArray): List<Int> { var currentIndex = 0 return blockSizes.map { val newValue = it + currentIndex currentIndex = newValue newValue } } /** * Format the PAN for display using the number block sizes. */ fun formatPan(pan: String): String { val builder = StringBuilder() for (i in pan.indices) { if (i in blockIndices) { builder.append(' ') } builder.append(pan[i]) } return builder.toString() } } /** * A mapping of [CardIssuer] to length and [PanFormatter] */ private val PAN_FORMAT_TABLE: Map<CardIssuer, Map<Int, PanFormatter>> = mapOf( CardIssuer.AmericanExpress to mapOf( 15 to PanFormatter(4, 6, 5) ), CardIssuer.DinersClub to mapOf( 14 to PanFormatter(4, 6, 4), 15 to PanFormatter(4, 6, 5), // Best guess 16 to PanFormatter(4, 4, 4, 4), 17 to PanFormatter(4, 4, 4, 5), // Best guess 18 to PanFormatter(4, 4, 4, 6), // Best guess 19 to PanFormatter(4, 4, 4, 4, 3) // Best guess ), CardIssuer.Discover to mapOf( 16 to PanFormatter(4, 4, 4, 4), 17 to PanFormatter(4, 4, 4, 4, 1), // Best guess 18 to PanFormatter(4, 4, 4, 4, 2), // Best guess 19 to PanFormatter(4, 4, 4, 4, 3) // Best guess ), CardIssuer.MasterCard to mapOf( 12 to PanFormatter(4, 4, 4), // Best guess 13 to PanFormatter(4, 4, 5), 14 to PanFormatter(4, 6, 4), // Best guess 15 to PanFormatter(4, 6, 5), 16 to PanFormatter(4, 4, 4, 4), 17 to PanFormatter(4, 4, 4, 5), // Best guess 18 to PanFormatter(4, 4, 4, 6), // Best guess 19 to PanFormatter(4, 4, 4, 4, 3) // Best guess ), CardIssuer.UnionPay to mapOf( 16 to PanFormatter(4, 4, 4, 4), 17 to PanFormatter(4, 4, 4, 5), // Best guess 18 to PanFormatter(4, 4, 4, 6), // Best guess 19 to PanFormatter(6, 13) ), CardIssuer.Visa to mapOf( 16 to PanFormatter(4, 4, 4, 4) ) ) /** * Default length [PanFormatter] mappings. */ private val DEFAULT_PAN_FORMATTERS: Map<Int, PanFormatter> = mapOf( 12 to PanFormatter(4, 4, 4), 13 to PanFormatter(4, 4, 5), 14 to PanFormatter(4, 6, 4), 15 to PanFormatter(4, 6, 5), 16 to PanFormatter(4, 4, 4, 4), 17 to PanFormatter(4, 4, 4, 5), 18 to PanFormatter(4, 4, 4, 2), 19 to PanFormatter(4, 4, 4, 4, 3) ) /** * A mapping of [CardIssuer] to length and [PanFormatter] */ private val CUSTOM_PAN_FORMAT_TABLE: MutableMap<CardIssuer, MutableMap<Int, PanFormatter>> = mutableMapOf()
mit
3dbfbb5ef0d98eb71f5dd7d27b5ff814
39.954248
110
0.474306
3.875077
false
false
false
false
Nunnery/MythicDrops
src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/language/command/MythicCustomCreateMessages.kt
1
2428
/* * This file is part of MythicDrops, licensed under the MIT License. * * Copyright (C) 2019 Richard Harrah * * 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.tealcube.minecraft.bukkit.mythicdrops.settings.language.command import com.squareup.moshi.JsonClass import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command.CustomCreateMessages import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString import org.bukkit.configuration.ConfigurationSection @JsonClass(generateAdapter = true) data class MythicCustomCreateMessages internal constructor( override val success: String = "", override val failure: String = "", override val requiresItem: String = "", override val requiresItemMeta: String = "", override val requiresDisplayName: String = "" ) : CustomCreateMessages { companion object { fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicCustomCreateMessages( success = configurationSection.getNonNullString("success"), failure = configurationSection.getNonNullString("failure"), requiresItem = configurationSection.getNonNullString("requires-item"), requiresItemMeta = configurationSection.getNonNullString("requires-item-meta"), requiresDisplayName = configurationSection.getNonNullString("requires-display-name") ) } }
mit
a4eef358116c942c8b94a817f7801b6e
51.782609
110
0.765239
5.058333
false
true
false
false
charleskorn/batect
app/src/unitTest/kotlin/batect/docker/client/DockerImagesClientSpec.kt
1
18648
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.docker.client import batect.docker.DockerImage import batect.docker.DockerRegistryCredentialsException import batect.docker.ImageBuildFailedException import batect.docker.ImagePullFailedException import batect.docker.api.ImagesAPI import batect.docker.build.DockerImageBuildContext import batect.docker.build.DockerImageBuildContextFactory import batect.docker.build.DockerfileParser import batect.docker.pull.DockerImageProgress import batect.docker.pull.DockerImageProgressReporter import batect.docker.pull.DockerRegistryCredentials import batect.docker.pull.DockerRegistryCredentialsProvider import batect.execution.CancellationContext import batect.testutils.createForEachTest import batect.testutils.createLoggerForEachTest import batect.testutils.equalTo import batect.testutils.given import batect.testutils.on import batect.testutils.runForEachTest import batect.testutils.withCause import batect.testutils.withMessage import batect.utils.Json import com.google.common.jimfs.Configuration import com.google.common.jimfs.Jimfs import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.throws import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doAnswer import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.never import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import kotlinx.serialization.json.JsonObject import okio.Sink import org.mockito.invocation.InvocationOnMock import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.nio.file.Files object DockerImagesClientSpec : Spek({ describe("a Docker images client") { val api by createForEachTest { mock<ImagesAPI>() } val credentialsProvider by createForEachTest { mock<DockerRegistryCredentialsProvider>() } val imageBuildContextFactory by createForEachTest { mock<DockerImageBuildContextFactory>() } val dockerfileParser by createForEachTest { mock<DockerfileParser>() } val logger by createLoggerForEachTest() val imageProgressReporter by createForEachTest { mock<DockerImageProgressReporter>() } val imageProgressReporterFactory = { imageProgressReporter } val client by createForEachTest { DockerImagesClient(api, credentialsProvider, imageBuildContextFactory, dockerfileParser, logger, imageProgressReporterFactory) } describe("building an image") { val fileSystem by createForEachTest { Jimfs.newFileSystem(Configuration.unix()) } val buildDirectory by createForEachTest { fileSystem.getPath("/path/to/build/dir") } val buildArgs = mapOf( "some_name" to "some_value", "some_other_name" to "some_other_value" ) val dockerfilePath = "some-Dockerfile-path" val imageTags = setOf("some_image_tag", "some_other_image_tag") val outputSink by createForEachTest { mock<Sink>() } val cancellationContext by createForEachTest { mock<CancellationContext>() } val context = DockerImageBuildContext(emptySet()) given("the Dockerfile exists") { val resolvedDockerfilePath by createForEachTest { buildDirectory.resolve(dockerfilePath) } beforeEachTest { Files.createDirectories(buildDirectory) Files.createFile(resolvedDockerfilePath) whenever(imageBuildContextFactory.createFromDirectory(buildDirectory, dockerfilePath)).doReturn(context) whenever(dockerfileParser.extractBaseImageNames(resolvedDockerfilePath)).doReturn(setOf("nginx:1.13.0", "some-other-image:2.3.4")) } given("getting the credentials for the base image succeeds") { val image1Credentials = mock<DockerRegistryCredentials>() val image2Credentials = mock<DockerRegistryCredentials>() beforeEachTest { whenever(credentialsProvider.getCredentials("nginx:1.13.0")).doReturn(image1Credentials) whenever(credentialsProvider.getCredentials("some-other-image:2.3.4")).doReturn(image2Credentials) } on("a successful build") { val output = """ |{"stream":"Step 1/5 : FROM nginx:1.13.0"} |{"status":"pulling the image"} |{"stream":"\n"} |{"stream":" ---\u003e 3448f27c273f\n"} |{"stream":"Step 2/5 : RUN apt update \u0026\u0026 apt install -y curl \u0026\u0026 rm -rf /var/lib/apt/lists/*"} |{"stream":"\n"} |{"stream":" ---\u003e Using cache\n"} |{"stream":" ---\u003e 0ceae477da9d\n"} |{"stream":"Step 3/5 : COPY index.html /usr/share/nginx/html"} |{"stream":"\n"} |{"stream":" ---\u003e b288a67b828c\n"} |{"stream":"Step 4/5 : COPY health-check.sh /tools/"} |{"stream":"\n"} |{"stream":" ---\u003e 951e32ae4f76\n"} |{"stream":"Step 5/5 : HEALTHCHECK --interval=2s --retries=1 CMD /tools/health-check.sh"} |{"stream":"\n"} |{"stream":" ---\u003e Running in 3de7e4521d69\n"} |{"stream":"Removing intermediate container 3de7e4521d69\n"} |{"stream":" ---\u003e 24125bbc6cbe\n"} |{"aux":{"ID":"sha256:24125bbc6cbe08f530e97c81ee461357fa3ba56f4d7693d7895ec86671cf3540"}} |{"stream":"Successfully built 24125bbc6cbe\n"} """.trimMargin() val imagePullProgress = DockerImageProgress("Doing something", 10, 20) beforeEachTest { stubProgressUpdate(imageProgressReporter, output.lines()[0], imagePullProgress) whenever(api.build(any(), any(), any(), any(), any(), any(), any(), any())).doAnswer(sendProgressAndReturnImage(output, DockerImage("some-image-id"))) } val statusUpdates by createForEachTest { mutableListOf<DockerImageBuildProgress>() } val onStatusUpdate = fun(p: DockerImageBuildProgress) { statusUpdates.add(p) } val result by runForEachTest { client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, onStatusUpdate) } it("builds the image") { verify(api).build(eq(context), eq(buildArgs), eq(dockerfilePath), eq(imageTags), eq(setOf(image1Credentials, image2Credentials)), eq(outputSink), eq(cancellationContext), any()) } it("returns the ID of the created image") { assertThat(result.id, equalTo("some-image-id")) } it("sends status updates as the build progresses") { assertThat( statusUpdates, equalTo( listOf( DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", null), DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", imagePullProgress), DockerImageBuildProgress(2, 5, "RUN apt update && apt install -y curl && rm -rf /var/lib/apt/lists/*", null), DockerImageBuildProgress(3, 5, "COPY index.html /usr/share/nginx/html", null), DockerImageBuildProgress(4, 5, "COPY health-check.sh /tools/", null), DockerImageBuildProgress(5, 5, "HEALTHCHECK --interval=2s --retries=1 CMD /tools/health-check.sh", null) ) ) ) } } on("the daemon sending image pull information before sending any step progress information") { val output = """ |{"status":"pulling the image"} |{"stream":"Step 1/5 : FROM nginx:1.13.0"} |{"status":"pulling the image"} |{"stream":"\n"} |{"stream":" ---\u003e 3448f27c273f\n"} |{"stream":"Step 2/5 : RUN apt update \u0026\u0026 apt install -y curl \u0026\u0026 rm -rf /var/lib/apt/lists/*"} """.trimMargin() val imagePullProgress = DockerImageProgress("Doing something", 10, 20) val statusUpdates by createForEachTest { mutableListOf<DockerImageBuildProgress>() } beforeEachTest { stubProgressUpdate(imageProgressReporter, output.lines()[0], imagePullProgress) whenever(api.build(any(), any(), any(), any(), any(), any(), any(), any())).doAnswer(sendProgressAndReturnImage(output, DockerImage("some-image-id"))) val onStatusUpdate = fun(p: DockerImageBuildProgress) { statusUpdates.add(p) } client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, onStatusUpdate) } it("sends status updates only once the first step is started") { assertThat( statusUpdates, equalTo( listOf( DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", null), DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", imagePullProgress), DockerImageBuildProgress(2, 5, "RUN apt update && apt install -y curl && rm -rf /var/lib/apt/lists/*", null) ) ) ) } } } given("getting credentials for the base image fails") { val exception = DockerRegistryCredentialsException("Could not load credentials: something went wrong.") beforeEachTest { whenever(credentialsProvider.getCredentials("nginx:1.13.0")).thenThrow(exception) } on("building the image") { it("throws an appropriate exception") { assertThat( { client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, {}) }, throws<ImageBuildFailedException>( withMessage("Could not build image: Could not load credentials: something went wrong.") and withCause(exception) ) ) } } } } given("the Dockerfile does not exist") { on("building the image") { it("throws an appropriate exception") { assertThat( { client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, {}) }, throws<ImageBuildFailedException>(withMessage("Could not build image: the Dockerfile 'some-Dockerfile-path' does not exist in '/path/to/build/dir'")) ) } } } given("the Dockerfile exists but is not a child of the build directory") { val dockerfilePathOutsideBuildDir = "../some-Dockerfile" val resolvedDockerfilePath by createForEachTest { buildDirectory.resolve(dockerfilePathOutsideBuildDir) } beforeEachTest { Files.createDirectories(buildDirectory) Files.createFile(resolvedDockerfilePath) } on("building the image") { it("throws an appropriate exception") { assertThat( { client.build(buildDirectory, buildArgs, dockerfilePathOutsideBuildDir, imageTags, outputSink, cancellationContext, {}) }, throws<ImageBuildFailedException>(withMessage("Could not build image: the Dockerfile '../some-Dockerfile' is not a child of '/path/to/build/dir'")) ) } } } } describe("pulling an image") { val cancellationContext by createForEachTest { mock<CancellationContext>() } given("the image does not exist locally") { beforeEachTest { whenever(api.hasImage("some-image")).thenReturn(false) } given("getting credentials for the image succeeds") { val credentials = mock<DockerRegistryCredentials>() beforeEachTest { whenever(credentialsProvider.getCredentials("some-image")).thenReturn(credentials) } on("pulling the image") { val firstProgressUpdate = Json.parser.parseJson("""{"thing": "value"}""").jsonObject val secondProgressUpdate = Json.parser.parseJson("""{"thing": "other value"}""").jsonObject beforeEachTest { whenever(imageProgressReporter.processProgressUpdate(firstProgressUpdate)).thenReturn(DockerImageProgress("Doing something", 10, 20)) whenever(imageProgressReporter.processProgressUpdate(secondProgressUpdate)).thenReturn(null) whenever(api.pull(any(), any(), any(), any())).then { invocation -> @Suppress("UNCHECKED_CAST") val onProgressUpdate = invocation.arguments[3] as (JsonObject) -> Unit onProgressUpdate(firstProgressUpdate) onProgressUpdate(secondProgressUpdate) null } } val progressUpdatesReceived by createForEachTest { mutableListOf<DockerImageProgress>() } val image by runForEachTest { client.pull("some-image", cancellationContext) { progressUpdatesReceived.add(it) } } it("calls the Docker CLI to pull the image") { verify(api).pull(eq("some-image"), eq(credentials), eq(cancellationContext), any()) } it("sends notifications for all relevant progress updates") { assertThat(progressUpdatesReceived, equalTo(listOf(DockerImageProgress("Doing something", 10, 20)))) } it("returns the Docker image") { assertThat(image, equalTo(DockerImage("some-image"))) } } } given("getting credentials for the image fails") { val exception = DockerRegistryCredentialsException("Could not load credentials: something went wrong.") beforeEachTest { whenever(credentialsProvider.getCredentials("some-image")).thenThrow(exception) } on("pulling the image") { it("throws an appropriate exception") { assertThat({ client.pull("some-image", cancellationContext, {}) }, throws<ImagePullFailedException>( withMessage("Could not pull image 'some-image': Could not load credentials: something went wrong.") and withCause(exception) )) } } } } on("when the image already exists locally") { beforeEachTest { whenever(api.hasImage("some-image")).thenReturn(true) } val image by runForEachTest { client.pull("some-image", cancellationContext, {}) } it("does not call the Docker CLI to pull the image again") { verify(api, never()).pull(any(), any(), any(), any()) } it("returns the Docker image") { assertThat(image, equalTo(DockerImage("some-image"))) } } } } }) private fun stubProgressUpdate(reporter: DockerImageProgressReporter, input: String, update: DockerImageProgress) { val json = Json.parser.parseJson(input).jsonObject whenever(reporter.processProgressUpdate(eq(json))).thenReturn(update) } private fun sendProgressAndReturnImage(progressUpdates: String, image: DockerImage) = { invocation: InvocationOnMock -> @Suppress("UNCHECKED_CAST") val onProgressUpdate = invocation.arguments.last() as (JsonObject) -> Unit progressUpdates.lines().forEach { line -> onProgressUpdate(Json.parser.parseJson(line).jsonObject) } image }
apache-2.0
3bd0f2758f008dae8602969564a6972b
51.089385
205
0.560543
5.454226
false
true
false
false
androidx/androidx
camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/adapter/CamcorderProfileProviderAdapter.kt
3
3469
/* * 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.camera.camera2.pipe.integration.adapter import android.media.CamcorderProfile import android.os.Build import androidx.annotation.Nullable import androidx.annotation.RequiresApi import androidx.camera.core.Logger import androidx.camera.core.impl.CamcorderProfileProvider import androidx.camera.core.impl.CamcorderProfileProxy /** * Adapt the [CamcorderProfileProvider] interface to [CameraPipe]. */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) class CamcorderProfileProviderAdapter(cameraIdString: String) : CamcorderProfileProvider { private val hasValidCameraId: Boolean private val cameraId: Int init { var hasValidCameraId = false var intCameraId = -1 try { intCameraId = cameraIdString.toInt() hasValidCameraId = true } catch (e: NumberFormatException) { Logger.w( TAG, "Camera id is not an integer: " + "$cameraIdString, unable to create CamcorderProfileProvider" ) } this.hasValidCameraId = hasValidCameraId cameraId = intCameraId // TODO(b/241296464): CamcorderProfileResolutionQuirk and CamcorderProfileResolutionValidator } override fun hasProfile(quality: Int): Boolean { if (!hasValidCameraId) { return false } return CamcorderProfile.hasProfile(cameraId, quality) // TODO: b241296464 CamcorderProfileResolutionQuirk and // CamcorderProfileResolutionValidator. If has quick, check if the proxy profile has // valid video resolution } override fun get(quality: Int): CamcorderProfileProxy? { if (!hasValidCameraId) { return null } return if (!CamcorderProfile.hasProfile(cameraId, quality)) { null } else getProfileInternal(quality) // TODO: b241296464 CamcorderProfileResolutionQuirk and // CamcorderProfileResolutionValidator. If has quick, check if the proxy profile has // valid video resolution } @Nullable @Suppress("DEPRECATION") private fun getProfileInternal(quality: Int): CamcorderProfileProxy? { var profile: CamcorderProfile? = null try { profile = CamcorderProfile.get(cameraId, quality) } catch (e: RuntimeException) { // CamcorderProfile.get() will throw // - RuntimeException if not able to retrieve camcorder profile params. // - IllegalArgumentException if quality is not valid. Logger.w(TAG, "Unable to get CamcorderProfile by quality: $quality", e) } return if (profile != null) CamcorderProfileProxy.fromCamcorderProfile(profile) else null } companion object { private const val TAG = "CamcorderProfileProviderAdapter" } }
apache-2.0
5198341c5fab9f278d8c55005f3b3dfc
36.311828
101
0.685212
5.049491
false
false
false
false
nrizzio/Signal-Android
app/src/main/java/org/thoughtcrime/securesms/contacts/sync/CdsTemporaryErrorBottomSheet.kt
1
2552
package org.thoughtcrime.securesms.contacts.sync import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.view.ContextThemeWrapper import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.fragment.app.FragmentManager import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment import org.thoughtcrime.securesms.databinding.CdsTemporaryErrorBottomSheetBinding import org.thoughtcrime.securesms.keyvalue.SignalStore import org.thoughtcrime.securesms.util.BottomSheetUtil import org.thoughtcrime.securesms.util.CommunicationActions import kotlin.time.Duration.Companion.milliseconds /** * Bottom sheet shown when CDS is rate-limited, preventing us from temporarily doing a refresh. */ class CdsTemporaryErrorBottomSheet : FixedRoundedCornerBottomSheetDialogFragment() { private lateinit var binding: CdsTemporaryErrorBottomSheetBinding override val peekHeightPercentage: Float = 0.75f override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { binding = CdsTemporaryErrorBottomSheetBinding.inflate(inflater.cloneInContext(ContextThemeWrapper(inflater.context, themeResId)), container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val days: Int = (SignalStore.misc().cdsBlockedUtil - System.currentTimeMillis()).milliseconds.inWholeDays.toInt() binding.timeText.text = resources.getQuantityString(R.plurals.CdsTemporaryErrorBottomSheet_body1, days, days) binding.learnMoreButton.setOnClickListener { CommunicationActions.openBrowserLink(requireContext(), "https://support.signal.org/hc/articles/360007319011#android_contacts_error") } binding.settingsButton.setOnClickListener { val intent = Intent().apply { action = Intent.ACTION_VIEW data = android.provider.ContactsContract.Contacts.CONTENT_URI } try { startActivity(intent) } catch (e: ActivityNotFoundException) { Toast.makeText(context, R.string.CdsPermanentErrorBottomSheet_no_contacts_toast, Toast.LENGTH_SHORT).show() } } } companion object { @JvmStatic fun show(fragmentManager: FragmentManager) { val fragment = CdsTemporaryErrorBottomSheet() fragment.show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG) } } }
gpl-3.0
2e389e2b125699732e51ce8c6198bac7
40.16129
151
0.795455
4.888889
false
false
false
false
klazuka/intellij-elm
src/test/kotlin/org/elm/lang/core/lexer/ElmLexerTestCaseBase.kt
1
2832
/* The MIT License (MIT) Derived from intellij-rust Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors Copyright (c) 2016 JetBrains 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 org.elm.lang.core.lexer import com.intellij.lexer.Lexer import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.testFramework.LexerTestCase import com.intellij.testFramework.UsefulTestCase import org.elm.lang.ElmTestCase import org.elm.lang.pathToGoldTestFile import org.elm.lang.pathToSourceTestFile import org.jetbrains.annotations.NonNls import java.io.IOException abstract class ElmLexerTestCaseBase : LexerTestCase(), ElmTestCase { override fun getDirPath(): String = throw UnsupportedOperationException() // NOTE(matkad): this is basically a copy-paste of doFileTest. // The only difference is that encoding is set to utf-8 protected fun doTest(lexer: Lexer = createLexer()) { val filePath = pathToSourceTestFile(getTestName(false)) var text = "" try { val fileText = FileUtil.loadFile(filePath.toFile(), CharsetToolkit.UTF8) text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText) } catch (e: IOException) { fail("can't load file " + filePath + ": " + e.message) } doTest(text, null, lexer) } override fun doTest(@NonNls text: String, expected: String?, lexer: Lexer) { val result = printTokens(text, 0, lexer) if (expected != null) { UsefulTestCase.assertSameLines(expected, result) } else { UsefulTestCase.assertSameLinesWithFile(pathToGoldTestFile(getTestName(false)).toFile().canonicalPath, result) } } }
mit
d1c50cce7fde00181d987ddf38459a83
41.268657
121
0.748588
4.502385
false
true
false
false
DemonWav/StatCraft
src/main/kotlin/com/demonwav/statcraft/ExtFunctions.kt
1
8491
/* * StatCraft Bukkit Plugin * * Copyright (c) 2016 Kyle Wood (DemonWav) * https://www.demonwav.com * * MIT License */ package com.demonwav.statcraft import com.mysema.query.QueryException import com.mysema.query.sql.RelationalPath import com.mysema.query.sql.SQLQuery import com.mysema.query.sql.dml.SQLInsertClause import com.mysema.query.sql.dml.SQLUpdateClause import java.nio.ByteBuffer import java.sql.Connection import java.util.UUID inline fun <T : AutoCloseable, R> T.use(block: T.() -> R): R { var closed = false try { return block() } catch (e: Exception) { closed = true try { close() } catch (closeException: Exception) {} throw e } finally { if (!closed) { close() } } } fun UUID.toByte(): ByteArray { val byteBuffer = ByteBuffer.wrap(ByteArray(16)) byteBuffer.putLong(mostSignificantBits) byteBuffer.putLong(leastSignificantBits) return byteBuffer.array() } fun ByteArray.toUUID(): UUID { val buffer = ByteBuffer.wrap(this) return UUID(buffer.long, buffer.long) } inline fun <T> MutableIterable<T>.iter(func: MutableIterator<T>.(T) -> Unit) { val iter = iterator() while (iter.hasNext()) { val item = iter.next() iter.func(item) } } /** * Run an insert/update query on the given table. This method handles the clause object creation and fall-through * to update when insert fails. This method run on the thread it is called, all threading must be managed by the * caller. * * @param insertClause The action to run for the insert query * @param updateClause The action to run for the update query if the insert fails * @param plugin The StatCraft object */ /* TODO inline */ fun <T : RelationalPath<*>> T.runQuery(insertClause: (T, SQLInsertClause) -> Unit, updateClause: (T, SQLUpdateClause) -> Unit, connection: Connection, plugin: StatCraft) { try { val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return insertClause(this, clause) } catch (e: QueryException) { val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return updateClause(this, clause) } } /** * Run an insert/update query on the given table. This method handles the clause object creation and fall-through * to update when insert fails. This method run on the thread it is called, all threading must be managed by the * caller. This also allows work to be done before the insert and update queries. The work function can return any * object, and this object will be passed to the insert and update functions, and in that order. Because of this, if * the object is modified in the insert function, these modifications will be present in the update function. * * @param workBefore The action to run before the queries, returning an object which will be passed to the two queries * @param insertClause The action to run for the insert query * @param updateClause The action to run for the update query if the insert fails * @param plugin The StatCraft object */ /* TODO inline */ fun <T : RelationalPath<*>, R> T.runQuery(workBefore: (T, SQLQuery) -> R, insertClause: (T, SQLInsertClause, R) -> Unit, updateClause: (T, SQLUpdateClause, R) -> Unit, connection: Connection, plugin: StatCraft) { val r = workBefore(this, plugin.databaseManager.getNewQuery(connection) ?: return) try { val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return insertClause(this, clause, r) } catch (e: QueryException) { val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return updateClause(this, clause, r) } } /** * Run an insert/update query on the given table. This method handles the clause object creation and fall-through * to update when insert fails. This method run on the thread it is called, all threading must be managed by the * caller. * * For convenience this method also allows a player's UUID and world UUID to be passed in. The database id of the * player and world will be fetched before the insert and update functions are called, and the id will be passed to * them. This is not an expensive operation as both of these values are cached. * * Thanks to type inferencing no type parameters should need to be explicitly provided. * * @param playerId The UUID of the relevant player * @param worldName The UUID of the relevant world * @param insertClause The action to run for the insert query * @param updateClause The action to run for the update query if the insert fails * @param plugin The StatCraft object */ /* TODO inline */ fun <T : RelationalPath<*>> T.runQuery(playerId: UUID, worldName: String, insertClause: (T, SQLInsertClause, Int, Int) -> Unit, updateClause: (T, SQLUpdateClause, Int, Int) -> Unit, connection: Connection, plugin: StatCraft) { val id = plugin.databaseManager.getPlayerId(playerId) ?: return val wid = plugin.databaseManager.getWorldId(worldName) ?: return try { val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return insertClause(this, clause, id, wid) } catch (e: QueryException) { val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return updateClause(this, clause, id, wid) } } /** * Run an insert/update query on the given table. This method handles the clause object creation and fall-through * to update when insert fails. This method run on the thread it is called, all threading must be managed by the * caller. This also allows work to be done before the insert and update queries. The work function can return any * object, and this object will be passed to the insert and update functions, and in that order. Because of this, if * the object is modified in the insert function, these modifications will be present in the update function. * * For convenience this method also allows a player's UUID and a world's UUID to be passed in. The database id of * the player and world will be fetched before the insert and update functions are called, and the id will be * passed to them. This is not an expensive operation as both of these values are cached. * * Thanks to type inferencing no type parameters should need to be explicitly provided. * * @param playerId The UUID of the relevant player * @param worldName The UUID of the relevant world * @param workBefore The action to run before the queries, returning an object which will be passed to the two queries * @param insertClause The action to run for the insert query * @param updateClause The action to run for the update query if the insert fails * @param plugin The StatCraft object */ /* TODO inline */ fun <T : RelationalPath<*>, R> T.runQuery(playerId: UUID, worldName: String, workBefore: (T, SQLQuery, Int, Int) -> R, insertClause: (T, SQLInsertClause, Int, Int, R) -> Unit, updateClause: (T, SQLUpdateClause, Int, Int, R) -> Unit, connection: Connection, plugin: StatCraft) { val id = plugin.databaseManager.getPlayerId(playerId) ?: return val wid = plugin.databaseManager.getWorldId(worldName) ?: return val r = workBefore(this, plugin.databaseManager.getNewQuery(connection) ?: return, id, wid) try { val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return insertClause(this, clause, id, wid, r) } catch (e: QueryException) { val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return updateClause(this, clause, id, wid, r) } }
mit
3d17363f94c4aa41a4cb6e01c17452b0
42.54359
118
0.644329
4.543071
false
false
false
false
bsmr-java/lwjgl3
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_occlusion_query.kt
1
6228
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val ARB_occlusion_query = "ARBOcclusionQuery".nativeClassGL("ARB_occlusion_query", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. This extension defines a mechanism whereby an application can query the number of pixels (or, more precisely, samples) drawn by a primitive or group of primitives. The primary purpose of such a query (hereafter referred to as an "occlusion query") is to determine the visibility of an object. Typically, the application will render the major occluders in the scene, then perform an occlusion query for the bounding box of each detail object in the scene. Only if said bounding box is visible, i.e., if at least one sample is drawn, should the corresponding object be drawn. The earlier ${registryLinkTo("HP", "occlusion_test")} extension defined a similar mechanism, but it had two major shortcomings. ${ul( "It returned the result as a simple GL11#TRUE/GL11#FALSE result, when in fact it is often useful to know exactly how many samples were drawn.", """ It provided only a simple "stop-and-wait" model for using multiple queries. The application begins an occlusion test and ends it; then, at some later point, it asks for the result, at which point the driver must stop and wait until the result from the previous test is back before the application can even begin the next one. This is a very simple model, but its performance is mediocre when an application wishes to perform many queries, and it eliminates most of the opportunities for parallelism between the CPU and GPU. """ )} This extension solves both of those problems. It returns as its result the number of samples that pass the depth and stencil tests, and it encapsulates occlusion queries in "query objects" that allow applications to issue many queries before asking for the result of any one. As a result, they can overlap the time it takes for the occlusion query results to be returned with other, more useful work, such as rendering other parts of the scene or performing other computations on the CPU. There are many situations where a pixel/sample count, rather than a boolean result, is useful. ${ul( "Objects that are visible but cover only a very small number of pixels can be skipped at a minimal reduction of image quality.", """ Knowing exactly how many pixels an object might cover may help the application decide which level-of-detail model should be used. If only a few pixels are visible, a low-detail model may be acceptable. """, """ "Depth peeling" techniques, such as order-independent transparency, need to know when to stop rendering more layers; it is difficult to determine a priori how many layers are needed. A boolean result allows applications to stop when more layers will not affect the image at all, but this will likely result in unacceptable performance. Instead, it makes more sense to stop rendering when the number of pixels in each layer falls below a given threshold. """, """ Occlusion queries can replace glReadPixels of the depth buffer to determine whether (for example) a light source is visible for the purposes of a lens flare effect or a halo to simulate glare. Pixel counts allow you to compute the percentage of the light source that is visible, and the brightness of these effects can be modulated accordingly. """ )} ${GL15.promoted} """ IntConstant( "Accepted by the {@code target} parameter of BeginQueryARB, EndQueryARB, and GetQueryivARB.", "SAMPLES_PASSED_ARB"..0x8914 ) val QUERY_PARAMETERS = IntConstant( "Accepted by the {@code pname} parameter of GetQueryivARB.", "QUERY_COUNTER_BITS_ARB"..0x8864, "CURRENT_QUERY_ARB"..0x8865 ).javaDocLinks val QUERY_OBJECT_PARAMETERS = IntConstant( "Accepted by the {@code pname} parameter of GetQueryObjectivARB and GetQueryObjectuivARB.", "QUERY_RESULT_ARB"..0x8866, "QUERY_RESULT_AVAILABLE_ARB"..0x8867 ).javaDocLinks void( "GenQueriesARB", "Generates query object names.", AutoSize("ids")..GLsizei.IN("n", "the number of query object names to be generated"), ReturnParam..GLuint_p.OUT("ids", "a buffer in which the generated query object names are stored") ) void( "DeleteQueriesARB", "Deletes named query objects.", AutoSize("ids")..GLsizei.IN("n", "the number of query objects to be deleted"), SingleValue("id")..const..GLuint_p.IN("ids", "an array of query objects to be deleted") ) GLboolean( "IsQueryARB", "Determine if a name corresponds to a query object.", GLuint.IN("id", "a value that may be the name of a query object") ) void( "BeginQueryARB", "Creates a query object and makes it active.", GLenum.IN("target", "the target type of query object established", QUERY_TARGETS), GLuint.IN("id", "the name of a query object") ) void( "EndQueryARB", "Marks the end of the sequence of commands to be tracked for the active query specified by {@code target}.", GLenum.IN("target", "the query object target", QUERY_TARGETS) ) void( "GetQueryivARB", "Returns parameters of a query object target.", GLenum.IN("target", "the query object target", QUERY_TARGETS), GLenum.IN("pname", "the symbolic name of a query object target parameter", QUERY_PARAMETERS), Check(1)..ReturnParam..GLint_p.OUT("params", "the requested data") ) void( "GetQueryObjectivARB", "Returns the integer value of a query object parameter.", GLuint.IN("id", "the name of a query object"), GLenum.IN("pname", "the symbolic name of a query object parameter", QUERY_OBJECT_PARAMETERS), Check(1)..ReturnParam..GLint_p.OUT("params", "the requested data") ) void( "GetQueryObjectuivARB", "Unsigned version of #GetQueryObjectivARB().", GLuint.IN("id", "the name of a query object"), GLenum.IN("pname", "the symbolic name of a query object parameter", QUERY_OBJECT_PARAMETERS), Check(1)..ReturnParam..GLuint_p.OUT("params", "the requested data") ) }
bsd-3-clause
25eceecacb222185e78c0223d730fb60
41.958621
159
0.732498
4.010303
false
false
false
false
edx/edx-app-android
OpenEdXMobile/src/main/java/org/edx/mobile/util/Version.kt
1
5302
package org.edx.mobile.util import java.text.ParseException import java.util.* import kotlin.math.abs import kotlin.math.min /** * Simple representation of the app's version. */ class Version /** * Create a new instance from the provided version string. * * @param version The version string. The first three present dot-separated * tokens will be parsed as major, minor, and patch version * numbers respectively, and any further tokens will be * discarded. * @throws ParseException If one or more of the first three present dot- * separated tokens contain non-numeric characters. */ @Throws(ParseException::class) constructor(version: String) : Comparable<Version> { /** * The version numbers */ private val numbers = IntArray(3) /** * @return The major version. */ val majorVersion: Int get() = getVersionAt(0) /** * @return The minor version. */ val minorVersion: Int get() = getVersionAt(1) /** * @return The patch version. */ val patchVersion: Int get() = getVersionAt(2) init { val numberStrings = version.split("\\.".toRegex()) val versionsCount = min(NUMBERS_COUNT, numberStrings.size) for (i in 0 until versionsCount) { val numberString = numberStrings[i] /* Integer.parseInt() parses a string as a signed integer value, and * there is no available method for parsing as unsigned instead. * Therefore, we first check the first character manually to see * whether it's a plus or minus sign, and throw a ParseException if * it is. */ val firstChar = numberString[0] if (firstChar == '-' || firstChar == '+') { throw VersionParseException(0) } try { numbers[i] = Integer.parseInt(numberString) } catch (e: NumberFormatException) { // Rethrow as a checked ParseException throw VersionParseException(version.indexOf(numberString)) } } } /** * Returns the version number at the provided index. * * @param index The index at which to get the version number * @return The version number. */ private fun getVersionAt(index: Int): Int { return if (index < numbers.size) numbers[index] else 0 } override fun equals(other: Any?): Boolean { return this === other || (other is Version && Arrays.equals(numbers, other.numbers)) } override fun compareTo(other: Version): Int { for (i in 0 until NUMBERS_COUNT) { val number = numbers[i] val otherNumber = other.numbers[i] if (number != otherNumber) { return if (number < otherNumber) -1 else 1 } } return 0 } override fun hashCode(): Int { return Arrays.hashCode(numbers) } override fun toString(): String { when (numbers.size) { 0 -> return "" 1 -> return numbers[0].toString() } val sb = StringBuilder() sb.append(numbers[0]) for (i in 1 until numbers.size) { sb.append(".") sb.append(numbers[i]) } return sb.toString() } /** * Convenience subclass of [ParseException], with the detail * message already provided. */ private class VersionParseException /** * Constructs a new instance of this class with its stack * trace, detail message and the location of the error filled * in. * * @param location The location of the token at which the parse * exception occurred. */ (location: Int) : ParseException("Token couldn't be parsed as a valid number.", location) /** * Compares this version with the specified version, to determine if minor versions' * difference between both is greater than or equal to the specified value. * * @param otherVersion The version to compare to this instance. * @param minorVersionsDiff Value difference to compare between versions. * @return `true` if difference is greater than or equal to the specified value, * `false` otherwise. */ fun isNMinorVersionsDiff(otherVersion: Version, minorVersionsDiff: Int): Boolean { // Difference in major version is consider to be valid for any minor versions difference return abs(this.majorVersion - otherVersion.majorVersion) >= 1 || abs(this.minorVersion - otherVersion.minorVersion) >= minorVersionsDiff } /** * Compares this version with the specified version and determine if both have same major and * minor versions. * * @param otherVersion The version to compare to this instance. * @return `true` if both have same major and minor versions, `false` otherwise. */ fun hasSameMajorMinorVersion(otherVersion: Version): Boolean { return this.majorVersion == otherVersion.majorVersion && this.minorVersion == otherVersion.minorVersion } companion object { /** * The number of version number tokens to parse. */ private const val NUMBERS_COUNT = 3 } }
apache-2.0
d06c0210e3897b8c0fad2305fa61dc1d
31.527607
145
0.615051
4.708703
false
false
false
false
EventFahrplan/EventFahrplan
commons/src/test/java/info/metadude/android/eventfahrplan/commons/temporal/DateFormatterFormattedTime24HourTest.kt
1
5000
package info.metadude.android.eventfahrplan.commons.temporal import com.google.common.truth.Truth.assertThat import info.metadude.android.eventfahrplan.commons.temporal.DateFormatterFormattedTime24HourTest.TestParameter.Companion.parse import info.metadude.android.eventfahrplan.commons.testing.withTimeZone import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.threeten.bp.ZoneOffset /** * Covers the time zone aware time rendering of [DateFormatter.getFormattedTime24Hour]. * - Iterating all valid time zone offsets * - Iterating all hours of a day * - Testing with summer and winter time * * Regardless which time zone is set at the device always the time zone of the event/session will * be rendered. * * TODO: TechDebt: Once the app offers an option to render sessions in the device time zone this test must be adapted. */ @RunWith(Parameterized::class) class DateFormatterFormattedTime24HourTest( private val timeZoneId: String ) { companion object { private val timeZoneOffsets = -12..14 @JvmStatic @Parameterized.Parameters(name = "{index}: timeZoneId = {0}") fun data() = timeZoneOffsets.map { arrayOf("GMT$it") } } @Test fun `getFormattedTime24Hour 2021-03-27`() = testEach(listOf( "2021-03-27T00:01:00+01:00" to "00:01", "2021-03-27T01:00:00+01:00" to "01:00", "2021-03-27T02:00:00+01:00" to "02:00", "2021-03-27T03:00:00+01:00" to "03:00", "2021-03-27T04:00:00+01:00" to "04:00", "2021-03-27T05:00:00+01:00" to "05:00", "2021-03-27T06:00:00+01:00" to "06:00", "2021-03-27T07:00:00+01:00" to "07:00", "2021-03-27T08:00:00+01:00" to "08:00", "2021-03-27T09:00:00+01:00" to "09:00", "2021-03-27T10:00:00+01:00" to "10:00", "2021-03-27T11:00:00+01:00" to "11:00", "2021-03-27T12:00:00+01:00" to "12:00", "2021-03-27T13:00:00+01:00" to "13:00", "2021-03-27T14:00:00+01:00" to "14:00", "2021-03-27T15:00:00+01:00" to "15:00", "2021-03-27T16:00:00+01:00" to "16:00", "2021-03-27T17:00:00+01:00" to "17:00", "2021-03-27T18:00:00+01:00" to "18:00", "2021-03-27T19:00:00+01:00" to "19:00", "2021-03-27T20:00:00+01:00" to "20:00", "2021-03-27T21:00:00+01:00" to "21:00", "2021-03-27T22:00:00+01:00" to "22:00", "2021-03-27T23:00:00+01:00" to "23:00", "2021-03-27T23:59:00+01:00" to "23:59", )) @Test fun `getFormattedTime24Hour 2021-03-28`() = testEach(listOf( "2021-03-28T00:01:00+02:00" to "00:01", "2021-03-28T01:00:00+02:00" to "01:00", "2021-03-28T02:00:00+02:00" to "02:00", // TechDebt: Daylight saving time is ignored here. "2021-03-28T03:00:00+02:00" to "03:00", "2021-03-28T04:00:00+02:00" to "04:00", "2021-03-28T05:00:00+02:00" to "05:00", "2021-03-28T06:00:00+02:00" to "06:00", "2021-03-28T07:00:00+02:00" to "07:00", "2021-03-28T08:00:00+02:00" to "08:00", "2021-03-28T09:00:00+02:00" to "09:00", "2021-03-28T10:00:00+02:00" to "10:00", "2021-03-28T11:00:00+02:00" to "11:00", "2021-03-28T12:00:00+02:00" to "12:00", "2021-03-28T13:00:00+02:00" to "13:00", "2021-03-28T14:00:00+02:00" to "14:00", "2021-03-28T15:00:00+02:00" to "15:00", "2021-03-28T16:00:00+02:00" to "16:00", "2021-03-28T17:00:00+02:00" to "17:00", "2021-03-28T18:00:00+02:00" to "18:00", "2021-03-28T19:00:00+02:00" to "19:00", "2021-03-28T20:00:00+02:00" to "20:00", "2021-03-28T21:00:00+02:00" to "21:00", "2021-03-28T22:00:00+02:00" to "22:00", "2021-03-28T23:00:00+02:00" to "23:00", "2021-03-28T23:59:00+02:00" to "23:59", )) private fun testEach(pairs: List<Pair<String, String>>) { pairs.forEach { (dateTime, expectedFormattedTime) -> val (moment, offset) = parse(dateTime) withTimeZone(timeZoneId) { val formattedTime = DateFormatter.newInstance(useDeviceTimeZone = false).getFormattedTime24Hour(moment, offset) assertThat(formattedTime).isEqualTo(expectedFormattedTime) } } } private data class TestParameter(val moment: Moment, val offset: ZoneOffset) { companion object { fun parse(dateTime: String) = TestParameter( parseMoment(dateTime), parseTimeZoneOffset(dateTime) ) private fun parseMoment(text: String): Moment { val milliseconds = DateParser.parseDateTime(text) return Moment.ofEpochMilli(milliseconds) } private fun parseTimeZoneOffset(text: String): ZoneOffset { val seconds = DateParser.parseTimeZoneOffset(text) return ZoneOffset.ofTotalSeconds(seconds) } } } }
apache-2.0
ccbf014055a59ad1d3fb8ba30ceaff7f
37.75969
127
0.6042
2.816901
false
true
false
false
IRA-Team/VKPlayer
app/src/main/java/com/irateam/vkplayer/api/service/UserService.kt
1
3584
/* * Copyright (C) 2015 IRA-Team * * 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.irateam.vkplayer.api.service import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager import com.irateam.vkplayer.api.AbstractQuery import com.irateam.vkplayer.api.Query import com.irateam.vkplayer.api.VKQuery import com.irateam.vkplayer.model.User import com.irateam.vkplayer.util.extension.isNetworkAvailable import com.vk.sdk.api.VKApiConst import com.vk.sdk.api.VKParameters import com.vk.sdk.api.VKRequest import com.vk.sdk.api.VKResponse import com.vk.sdk.api.methods.VKApiUsers import com.vk.sdk.api.model.VKApiUser class UserService { private val context: Context private val sharedPreferences: SharedPreferences constructor(context: Context) { this.context = context this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) } fun getCurrentCached(): Query<User> { return CachedCurrentUserQuery() } fun getCurrent(): Query<User> = if (context.isNetworkAvailable()) { val params = VKParameters.from(VKApiConst.FIELDS, VKApiUser.FIELD_PHOTO_100) val request = VKApiUsers().get(params) CurrentUserQuery(request) } else { CachedCurrentUserQuery() } private fun parseFromPreferences(): User { val id = sharedPreferences.getInt(USER_ID, -1) val firstName = sharedPreferences.getString(USER_FIRST_NAME, "") val lastName = sharedPreferences.getString(USER_SECOND_NAME, "") val photo100px = sharedPreferences.getString(USER_PHOTO_URL, "") return User(id, firstName, lastName, photo100px) } private fun parseFromVKResponse(response: VKResponse): User { val responseBody = response.json.getJSONArray("response") val rawUser = responseBody.getJSONObject(0) return User( rawUser.optInt("id"), rawUser.optString("first_name"), rawUser.optString("last_name"), rawUser.optString("photo_100")) } private fun saveToPreferences(user: User) = sharedPreferences.edit() .putInt(USER_ID, user.id) .putString(USER_FIRST_NAME, user.firstName) .putString(USER_SECOND_NAME, user.lastName) .putString(USER_PHOTO_URL, user.photo100px) .apply() private inner class CurrentUserQuery(request: VKRequest) : VKQuery<User>(request) { override fun parse(response: VKResponse): User { val user = parseFromVKResponse(response) saveToPreferences(user) return user } } private inner class CachedCurrentUserQuery : AbstractQuery<User>() { override fun query(): User = parseFromPreferences() } companion object { private val USER_ID = "user_id" private val USER_FIRST_NAME = "user_first_name" private val USER_SECOND_NAME = "user_second_name" private val USER_PHOTO_URL = "user_photo_url" } }
apache-2.0
0f249d452ae77dcbb820f9495d776b44
33.461538
87
0.691127
4.287081
false
false
false
false
andstatus/andstatus
app/src/main/kotlin/org/andstatus/app/database/table/ActorEndpointTable.kt
1
1706
/* * Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.andstatus.app.database.table import android.database.sqlite.SQLiteDatabase import org.andstatus.app.data.DbUtils /** Collections of URIs for Actors */ object ActorEndpointTable { val TABLE_NAME: String = "actorendpoints" val ACTOR_ID: String = ActorTable.ACTOR_ID /** [org.andstatus.app.net.social.ActorEndpointType] */ val ENDPOINT_TYPE: String = "endpoint_type" /** Index of an endpoint of a particular [.ENDPOINT_TYPE], starting from 0 */ val ENDPOINT_INDEX: String = "endpoint_index" val ENDPOINT_URI: String = "endpoint_uri" fun create(db: SQLiteDatabase) { DbUtils.execSQL(db, "CREATE TABLE " + TABLE_NAME + " (" + ACTOR_ID + " INTEGER NOT NULL," + ENDPOINT_TYPE + " INTEGER NOT NULL," + ENDPOINT_INDEX + " INTEGER NOT NULL DEFAULT 0," + ENDPOINT_URI + " TEXT NOT NULL," + " CONSTRAINT pk_" + TABLE_NAME + " PRIMARY KEY (" + ACTOR_ID + " ASC, " + ENDPOINT_TYPE + " ASC, " + ENDPOINT_INDEX + " ASC)" + ")") } }
apache-2.0
e841d4fce0fda88d4212c80c91c00298
40.609756
143
0.654748
4.014118
false
false
false
false
esofthead/mycollab
mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/ProjectRiskRelayEmailNotificationActionImpl.kt
3
13235
/** * 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.module.project.schedule.email.service import com.hp.gagawa.java.elements.A import com.hp.gagawa.java.elements.Span import com.hp.gagawa.java.elements.Text import com.mycollab.common.MonitorTypeConstants import com.mycollab.common.i18n.GenericI18Enum import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum import com.mycollab.core.MyCollabException import com.mycollab.core.utils.StringUtils import com.mycollab.html.FormatUtils import com.mycollab.html.LinkUtils import com.mycollab.module.mail.MailUtils import com.mycollab.module.project.ProjectLinkGenerator import com.mycollab.module.project.ProjectResources import com.mycollab.module.project.ProjectTypeConstants import com.mycollab.module.project.domain.ProjectRelayEmailNotification import com.mycollab.module.project.domain.Risk import com.mycollab.module.project.domain.SimpleRisk import com.mycollab.module.project.i18n.MilestoneI18nEnum import com.mycollab.module.project.i18n.OptionI18nEnum.RiskConsequence import com.mycollab.module.project.i18n.OptionI18nEnum.RiskProbability import com.mycollab.module.project.i18n.RiskI18nEnum import com.mycollab.module.project.service.MilestoneService import com.mycollab.module.project.service.RiskService import com.mycollab.module.user.AccountLinkGenerator import com.mycollab.module.user.service.UserService import com.mycollab.schedule.email.ItemFieldMapper import com.mycollab.schedule.email.MailContext import com.mycollab.schedule.email.format.DateFieldFormat import com.mycollab.schedule.email.format.FieldFormat import com.mycollab.schedule.email.format.I18nFieldFormat import com.mycollab.schedule.email.project.ProjectRiskRelayEmailNotificationAction import com.mycollab.spring.AppContextUtil import org.springframework.beans.factory.annotation.Autowired import org.springframework.beans.factory.config.BeanDefinition import org.springframework.context.annotation.Scope import org.springframework.stereotype.Component /** * @author MyCollab Ltd * @since 6.0.0 */ @Component @Scope(BeanDefinition.SCOPE_PROTOTYPE) class ProjectRiskRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleRisk>(), ProjectRiskRelayEmailNotificationAction { @Autowired private lateinit var riskService: RiskService private val mapper = ProjectFieldNameMapper() override fun getItemName(): String = StringUtils.trim(bean!!.name, 100) override fun getProjectName(): String = bean!!.projectName override fun getCreateSubject(context: MailContext<SimpleRisk>): String = context.getMessage( RiskI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getCreateSubjectNotification(context: MailContext<SimpleRisk>): String = context.getMessage(RiskI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), riskLink()) override fun getUpdateSubject(context: MailContext<SimpleRisk>): String = context.getMessage( RiskI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getUpdateSubjectNotification(context: MailContext<SimpleRisk>): String = context.getMessage(RiskI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), riskLink()) override fun getCommentSubject(context: MailContext<SimpleRisk>): String = context.getMessage( RiskI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName()) override fun getCommentSubjectNotification(context: MailContext<SimpleRisk>): String = context.getMessage(RiskI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), riskLink()) private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)). appendText(StringUtils.trim(bean!!.projectName, 50)).setType(bean!!.projectName).write() private fun userLink(context: MailContext<SimpleRisk>) = A(AccountLinkGenerator.generateUserLink(context.user.username)). appendText(StringUtils.trim(context.changeByUserFullName, 50)).write() private fun riskLink() = A(ProjectLinkGenerator.generateRiskPreviewLink(bean!!.projectShortName, bean!!.ticketKey)).appendText(getItemName()).write() override fun getItemFieldMapper(): ItemFieldMapper = mapper override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleRisk? = riskService.findById(notification.typeid.toInt(), notification.saccountid) override fun getType(): String = ProjectTypeConstants.RISK override fun getTypeId(): String = "${bean!!.id}" override fun buildExtraTemplateVariables(context: MailContext<SimpleRisk>) { val emailNotification = context.emailNotification val summary = bean!!.name val summaryLink = ProjectLinkGenerator.generateRiskPreviewFullLink(siteUrl, bean!!.projectShortName, bean!!.ticketKey) val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else "" val userAvatar = LinkUtils.newAvatar(avatarId) val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}" val actionEnum = when (emailNotification.action) { MonitorTypeConstants.CREATE_ACTION -> RiskI18nEnum.MAIL_CREATE_ITEM_HEADING MonitorTypeConstants.UPDATE_ACTION -> RiskI18nEnum.MAIL_UPDATE_ITEM_HEADING MonitorTypeConstants.ADD_COMMENT_ACTION -> RiskI18nEnum.MAIL_COMMENT_ITEM_HEADING else -> throw MyCollabException("Not support action ${emailNotification.action}") } contentGenerator.putVariable("projectName", bean!!.projectName) contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid)) contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser)) contentGenerator.putVariable("name", summary) contentGenerator.putVariable("summaryLink", summaryLink) } class ProjectFieldNameMapper : ItemFieldMapper() { init { put(Risk.Field.name, GenericI18Enum.FORM_NAME, true) put(Risk.Field.description, GenericI18Enum.FORM_DESCRIPTION, true) put(Risk.Field.probability, I18nFieldFormat(Risk.Field.probability.name, RiskI18nEnum.FORM_PROBABILITY, RiskProbability::class.java)) put(Risk.Field.consequence, I18nFieldFormat(Risk.Field.consequence.name, RiskI18nEnum.FORM_CONSEQUENCE, RiskConsequence::class.java)) put(Risk.Field.startdate, DateFieldFormat(Risk.Field.startdate.name, GenericI18Enum.FORM_START_DATE)) put(Risk.Field.enddate, DateFieldFormat(Risk.Field.enddate.name, GenericI18Enum.FORM_END_DATE)) put(Risk.Field.duedate, DateFieldFormat(Risk.Field.duedate.name, GenericI18Enum.FORM_DUE_DATE)) put(Risk.Field.status, I18nFieldFormat(Risk.Field.status.name, GenericI18Enum.FORM_STATUS, StatusI18nEnum::class.java)) put(Risk.Field.milestoneid, MilestoneFieldFormat(Risk.Field.milestoneid.name, MilestoneI18nEnum.SINGLE)) put(Risk.Field.assignuser, AssigneeFieldFormat(Risk.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE)) put(Risk.Field.createduser, RaisedByFieldFormat(Risk.Field.createduser.name, RiskI18nEnum.FORM_RAISED_BY)) put(Risk.Field.response, RiskI18nEnum.FORM_RESPONSE, true) } } class AssigneeFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) { override fun formatField(context: MailContext<*>): String { val risk = context.wrappedBean as SimpleRisk return if (risk.assignuser != null) { val userAvatarLink = MailUtils.getAvatarLink(risk.assignToUserAvatarId, 16) val img = FormatUtils.newImg("avatar", userAvatarLink) val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(risk.saccountid), risk.assignuser) val link = FormatUtils.newA(userLink, risk.assignedToUserFullName) FormatUtils.newLink(img, link).write() } else Span().write() } override fun formatField(context: MailContext<*>, value: String): String { return if (StringUtils.isBlank(value)) { Span().write() } else { val userService = AppContextUtil.getSpringBean(UserService::class.java) val user = userService.findUserByUserNameInAccount(value, context.saccountid) if (user != null) { val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16) val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid), user.username) val img = FormatUtils.newImg("avatar", userAvatarLink) val link = FormatUtils.newA(userLink, user.displayName!!) FormatUtils.newLink(img, link).write() } else value } } } class RaisedByFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) { override fun formatField(context: MailContext<*>): String { val risk = context.wrappedBean as SimpleRisk return if (risk.createduser != null) { val userAvatarLink = MailUtils.getAvatarLink(risk.raisedByUserAvatarId, 16) val img = FormatUtils.newImg("avatar", userAvatarLink) val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(risk.saccountid), risk.createduser) val link = FormatUtils.newA(userLink, risk.raisedByUserFullName) FormatUtils.newLink(img, link).write() } else Span().write() } override fun formatField(context: MailContext<*>, value: String): String { if (StringUtils.isBlank(value)) { return Span().write() } val userService = AppContextUtil.getSpringBean(UserService::class.java) val user = userService.findUserByUserNameInAccount(value, context.saccountid) return if (user != null) { val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16) val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid), user.username) val img = FormatUtils.newImg("avatar", userAvatarLink) val link = FormatUtils.newA(userLink, user.displayName!!) FormatUtils.newLink(img, link).write() } else value } } class MilestoneFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) { override fun formatField(context: MailContext<*>): String { val risk = context.wrappedBean as SimpleRisk return if (risk.milestoneid != null) { val img = Text(ProjectResources.getFontIconHtml(ProjectTypeConstants.MILESTONE)) val milestoneLink = ProjectLinkGenerator.generateMilestonePreviewFullLink(context.siteUrl, risk.projectid, risk.milestoneid) val link = FormatUtils.newA(milestoneLink, risk.milestoneName!!) FormatUtils.newLink(img, link).write() } else Span().write() } override fun formatField(context: MailContext<*>, value: String): String { if (StringUtils.isBlank(value)) { return Span().write() } val milestoneId = value.toInt() val milestoneService = AppContextUtil.getSpringBean(MilestoneService::class.java) val milestone = milestoneService.findById(milestoneId, context.saccountid) return if (milestone != null) { val img = Text(ProjectResources.getFontIconHtml(ProjectTypeConstants.MILESTONE)) val milestoneLink = ProjectLinkGenerator.generateMilestonePreviewFullLink(context.siteUrl, milestone.projectid, milestone.id) val link = FormatUtils.newA(milestoneLink, milestone.name) return FormatUtils.newLink(img, link).write() } else value } } }
agpl-3.0
0fe1696f9482e42e61bc3de396af696e
54.609244
153
0.71339
4.674673
false
false
false
false
hidroh/tldroid
app/src/test/kotlin/io/github/hidroh/tldroid/NetworkConnectionTest.kt
1
2268
package io.github.hidroh.tldroid import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okio.Okio import org.assertj.core.api.Assertions import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class NetworkConnectionTest { private val server: MockWebServer = MockWebServer() @Before fun setUp() { server.start() } @Test fun testGetResponseCode() { server.enqueue(MockResponse().setResponseCode(200)) val connection = NetworkConnection(server.url("/index.json").toString()) connection.connect() Assertions.assertThat(connection.getResponseCode()).isEqualTo(200) connection.disconnect() } @Test fun testGetInputStream() { server.enqueue(MockResponse().setBody("{}")) val connection = NetworkConnection(server.url("/index.json").toString()) connection.connect() Assertions.assertThat(Okio.buffer(Okio.source(connection.getInputStream())).readUtf8()) .isEqualTo("{}") connection.disconnect() } @Test fun testNoInputStream() { server.enqueue(MockResponse().setResponseCode(404)) val connection = NetworkConnection(server.url("/index.json").toString()) connection.connect() Assertions.assertThat(connection.getInputStream()).isNull() connection.disconnect() } @Test fun testModified() { server.enqueue(MockResponse().setResponseCode(304).setHeader("Last-Modified", "Fri, 03 Jun 2016 17:11:33 GMT")) val connection = NetworkConnection(server.url("/index.json").toString()) connection.setIfModifiedSince(0L) connection.connect() Assertions.assertThat(connection.getLastModified()).isEqualTo(1464973893000L) connection.disconnect() } @Test fun testMissingConnect() { val connection = NetworkConnection("/index.json") connection.setIfModifiedSince(0L) // should ignore Assertions.assertThat(connection.getResponseCode()).isEqualTo(0) Assertions.assertThat(connection.getInputStream()).isNull() Assertions.assertThat(connection.getLastModified()).isEqualTo(0L) connection.disconnect() // should fail silently } @After fun tearDown() { server.shutdown() } }
apache-2.0
271ec57af9da9c3de5160408fe31ffee
29.253333
91
0.733686
4.421053
false
true
false
false
REDNBLACK/advent-of-code2016
src/main/kotlin/day08/Advent8.kt
1
5056
package day08 import array2d import day08.Operation.Type.* import parseInput import splitToLines /** You come across a door implementing what you can only assume is an implementation of two-factor authentication after a long game of requirements telephone. To get past the door, you first swipe a keycard (no problem; there was one on a nearby desk). Then, it displays a code on a little screen, and you type that code on a keypad. Then, presumably, the door unlocks. Unfortunately, the screen has been smashed. After a few minutes, you've taken everything apart and figured out how it works. Now you just have to work out what the screen would have displayed. The magnetic strip on the card you swiped encodes a series of instructions for the screen; these instructions are your puzzle input. The screen is 50 pixels wide and 6 pixels tall, all of which start off, and is capable of three somewhat peculiar operations: rect AxB turns on all of the pixels in a rectangle at the top-left of the screen which is A wide and B tall. rotate row y=A by B shifts all of the pixels in row A (0 is the top row) right by B pixels. Pixels that would fall off the right end appear at the left end of the row. rotate column x=A by B shifts all of the pixels in column A (0 is the left column) down by B pixels. Pixels that would fall off the bottom appear at the top of the column. For example, here is a simple sequence on a smaller screen: rect 3x2 creates a small rectangle in the top-left corner: ###.... ###.... ....... rotate column x=1 by 1 rotates the second column down by one pixel: #.#.... ###.... .#..... rotate row y=0 by 4 rotates the top row right by four pixels: ....#.# ###.... .#..... rotate column x=1 by 1 again rotates the second column down by one pixel, causing the bottom pixel to wrap back to the top: .#..#.# #.#.... .#..... As you can see, this display technology is extremely powerful, and will soon dominate the tiny-code-displaying-screen market. That's what the advertisement on the back of the display tries to convince you, anyway. There seems to be an intermediate check of the voltage used by the display: after you swipe your card, if the screen did work, how many pixels should be lit? --- Part Two --- You notice that the screen is only capable of displaying capital letters; in the font it uses, each letter is 5 pixels wide and 6 tall. After you swipe your card, what code is the screen trying to display? */ fun main(args: Array<String>) { val test = """rect 3x2 |rotate column x=1 by 1 |rotate row y=0 by 4 |rotate column x=1 by 1""".trimMargin() val resultMatrix1 = execute(test, array2d(3, 7) { false }) println(resultMatrix1.countFilled() == 6) val input = parseInput("day8-input.txt") val resultMatrix2 = execute(input, array2d(6, 50) { false }) println(resultMatrix2.countFilled()) resultMatrix2.drawMatrix() } data class Operation(val type: Operation.Type, val payload1: Int, val payload2: Int) { enum class Type { CREATE, ROTATE_ROW, ROTATE_COLUMN } } fun execute(input: String, matrix: Array<Array<Boolean>>): Array<Array<Boolean>> { fun <T> Array<Array<T>>.shiftDown(x: Int) { val height = size - 1 val bottom = this[height][x] for (y in height downTo 0) { this[y][x] = if (y > 0) this[y - 1][x] else bottom } } fun <T> Array<Array<T>>.shiftRight(y: Int) { val width = this[0].size - 1 val right = this[y][width] for (x in width downTo 0) { this[y][x] = if (x > 0) this[y][x - 1] else right } } fun <T> Array<Array<T>>.fill(value: T, maxWidth: Int, maxHeight: Int) { for (w in 0 until maxWidth) { for (h in 0 until maxHeight) { this[h][w] = value } } } for ((type, p1, p2) in parseOperations(input)) { when (type) { CREATE -> matrix.fill(true, p1, p2) ROTATE_COLUMN -> repeat(p2, { matrix.shiftDown(p1) }) ROTATE_ROW -> repeat(p2, { matrix.shiftRight(p1) }) } } return matrix } private fun Array<Array<Boolean>>.drawMatrix() = map { it.map { if (it) '█' else '▒' }.joinToString("") } .joinToString(System.lineSeparator()) .let(::println) private fun Array<Array<Boolean>>.countFilled() = sumBy { it.sumBy { if (it) 1 else 0 } } private fun parseOperations(input: String) = input.splitToLines() .map { val (payload1, payload2) = Regex("""(\d+)""") .findAll(it) .map { it.value } .map(String::toInt) .toList() val type = when { "rect" in it -> CREATE "rotate row" in it -> ROTATE_ROW "rotate column" in it -> ROTATE_COLUMN else -> throw IllegalArgumentException() } Operation(type = type, payload1 = payload1, payload2 = payload2) }
mit
5169161cfe56af753d295e2b89cfa6de
38.46875
258
0.63361
3.798496
false
false
false
false
Schlangguru/paperless-uploader
app/src/main/java/de/schlangguru/paperlessuploader/services/remote/PaperlessServiceProvider.kt
1
1954
package de.schlangguru.paperlessuploader.services.remote import de.schlangguru.paperlessuploader.BuildConfig import de.schlangguru.paperlessuploader.services.local.Settings import okhttp3.Credentials import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Response import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory /** * Returns a [PaperlessService] using retrofit. */ class PaperlessServiceProvider { companion object { fun createService ( settings: Settings = Settings(), baseURL: String = settings.apiURL ) : PaperlessService { val httpLoggingInterceptor = HttpLoggingInterceptor() httpLoggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE val client = OkHttpClient.Builder() .addInterceptor(httpLoggingInterceptor) .addInterceptor(BasicAuthInterceptor(settings)) .build() val retrofit = Retrofit.Builder() .baseUrl(baseURL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build() return retrofit.create(PaperlessService::class.java) } } class BasicAuthInterceptor( private val settings: Settings ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val credentials = Credentials.basic(settings.username, settings.password) val authRequest = chain.request().newBuilder().addHeader("Authorization", credentials).build() return chain.proceed(authRequest) } } }
mit
b865b4c1d0927d3d8f25d1e92d476ae4
35.886792
138
0.677584
5.458101
false
false
false
false
saki4510t/libcommon
app/src/main/java/com/serenegiant/widget/CameraDelegator.kt
1
10214
@file:Suppress("DEPRECATION") package com.serenegiant.widget /* * libcommon * utility/helper classes for myself * * Copyright (c) 2014-2022 saki [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. */ import android.annotation.SuppressLint import android.graphics.SurfaceTexture import android.hardware.Camera import android.os.Handler import android.util.Log import android.view.View import androidx.annotation.WorkerThread import com.serenegiant.camera.CameraConst import com.serenegiant.camera.CameraUtils import com.serenegiant.utils.HandlerThreadHandler import com.serenegiant.utils.HandlerUtils import java.io.IOException import java.util.concurrent.CopyOnWriteArraySet /** * カメラプレビュー処理の委譲クラス */ class CameraDelegator( view: View, width: Int, height: Int, cameraRenderer: ICameraRenderer) { /** * 映像が更新されたときの通知用コールバックリスナー */ interface OnFrameAvailableListener { fun onFrameAvailable() } /** * カメラ映像をGLSurfaceViewへ描画するためのGLSurfaceView.Rendererインターフェース */ interface ICameraRenderer { fun hasSurface(): Boolean fun onPreviewSizeChanged(width: Int, height: Int) /** * カメラ映像受け取り用のSurface/SurfaceHolder/SurfaceTexture/SurfaceViewを取得 * @return */ fun getInputSurface(): Any } //-------------------------------------------------------------------------------- private val mView: View private val mSync = Any() val cameraRenderer: ICameraRenderer private val mListeners: MutableSet<OnFrameAvailableListener> = CopyOnWriteArraySet() private var mCameraHandler: Handler? = null /** * カメラ映像幅を取得 * @return */ var requestWidth: Int private set /** * カメラ映像高さを取得 * @return */ var requestHeight: Int private set var previewWidth: Int private set var previewHeight: Int private set var isPreviewing: Boolean private set private var mScaleMode = SCALE_STRETCH_FIT private var mCamera: Camera? = null @Volatile private var mResumed = false init { if (DEBUG) Log.v(TAG, String.format("コンストラクタ:(%dx%d)", width, height)) mView = view @Suppress("LeakingThis") this.cameraRenderer = cameraRenderer this.requestWidth = width this.requestHeight = height this.previewWidth = width this.previewHeight = height isPreviewing = false } @Throws(Throwable::class) protected fun finalize() { release() } /** * 関連するリソースを廃棄する */ fun release() { synchronized(mSync) { if (mCameraHandler != null) { if (DEBUG) Log.v(TAG, "release:") mCameraHandler!!.removeCallbacksAndMessages(null) HandlerUtils.NoThrowQuit(mCameraHandler) mCameraHandler = null } } } /** * GLSurfaceView#onResumeが呼ばれたときの処理 */ fun onResume() { if (DEBUG) Log.v(TAG, "onResume:") mResumed = true if (cameraRenderer.hasSurface()) { if (mCameraHandler == null) { if (DEBUG) Log.v(TAG, "surface already exist") startPreview(requestWidth, requestHeight) } } } /** * GLSurfaceView#onPauseが呼ばれたときの処理 */ fun onPause() { if (DEBUG) Log.v(TAG, "onPause:") mResumed = false // just request stop previewing stopPreview() } /** * 映像が更新されたときのコールバックリスナーを登録 * @param listener */ fun addListener(listener: OnFrameAvailableListener?) { if (DEBUG) Log.v(TAG, "addListener:$listener") if (listener != null) { mListeners.add(listener) } } /** * 映像が更新されたときのコールバックリスナーの登録を解除 * @param listener */ fun removeListener(listener: OnFrameAvailableListener) { if (DEBUG) Log.v(TAG, "removeListener:$listener") mListeners.remove(listener) } /** * 映像が更新されたときのコールバックを呼び出す */ fun callOnFrameAvailable() { for (listener in mListeners) { try { listener.onFrameAvailable() } catch (e: Exception) { mListeners.remove(listener) } } } var scaleMode: Int /** * 現在のスケールモードを取得 * @return */ get() { if (DEBUG) Log.v(TAG, "getScaleMode:$mScaleMode") return mScaleMode } /** * スケールモードをセット * @param mode */ set(mode) { if (DEBUG) Log.v(TAG, "setScaleMode:$mode") if (mScaleMode != mode) { mScaleMode = mode } } /** * カメラ映像サイズを変更要求 * @param width * @param height */ fun setVideoSize(width: Int, height: Int) { if (DEBUG) Log.v(TAG, String.format("setVideoSize:(%dx%d)", width, height)) if (requestWidth != width || (requestHeight != height)) { requestWidth = width requestHeight = height // FIXME 既にカメラから映像取得中ならカメラを再設定しないといけない if (isPreviewing) { stopPreview() startPreview(width, height) } } } /** * プレビュー開始 * @param width * @param height */ fun startPreview(width: Int, height: Int) { if (DEBUG) Log.v(TAG, String.format("startPreview:(%dx%d)", width, height)) synchronized(mSync) { if (mCameraHandler == null) { mCameraHandler = HandlerThreadHandler.createHandler("CameraHandler") } isPreviewing = true mCameraHandler!!.post { handleStartPreview(width, height) } } } /** * プレビュー終了 */ fun stopPreview() { if (DEBUG) Log.v(TAG, "stopPreview:$mCamera") synchronized(mSync) { isPreviewing = false if (mCamera != null) { mCamera!!.stopPreview() if (mCameraHandler != null) { mCameraHandler!!.post { handleStopPreview() release() } } } } } //-------------------------------------------------------------------------------- /** * カメラプレビュー開始の実体 * @param width * @param height */ @SuppressLint("WrongThread") @WorkerThread private fun handleStartPreview(width: Int, height: Int) { if (DEBUG) Log.v(TAG, "CameraThread#handleStartPreview:(${width}x${height})") var camera: Camera? synchronized(mSync) { camera = mCamera } if (camera == null) { // This is a sample project so just use 0 as camera ID. // it is better to selecting camera is available try { val cameraId = CameraUtils.findCamera(CameraConst.FACING_BACK) camera = Camera.open(cameraId) val params = camera!!.parameters if (params != null) { val focusModes = params.supportedFocusModes if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { params.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO if (DEBUG) Log.i(TAG, "handleStartPreview:FOCUS_MODE_CONTINUOUS_VIDEO") } else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { params.focusMode = Camera.Parameters.FOCUS_MODE_AUTO if (DEBUG) Log.i(TAG, "handleStartPreview:FOCUS_MODE_AUTO") } else { if (DEBUG) Log.i(TAG, "handleStartPreview:Camera does not support autofocus") } params.setRecordingHint(true) CameraUtils.chooseVideoSize(params, width, height) val fps = CameraUtils.chooseFps(params, 1.0f, 120.0f) // rotate camera preview according to the device orientation val degrees = CameraUtils.setupRotation(cameraId, mView, camera!!, params) camera!!.parameters = params // get the actual preview size val previewSize = camera!!.parameters.previewSize // 画面の回転状態に合わせてプレビューの映像サイズの縦横を入れ替える if (degrees % 180 == 0) { previewWidth = previewSize.width previewHeight = previewSize.height } else { previewWidth = previewSize.height previewHeight = previewSize.width } Log.d(TAG, String.format("handleStartPreview:(%dx%d)→rot%d(%dx%d),fps(%d-%d)", previewSize.width, previewSize.height, degrees, previewWidth, previewHeight, fps?.get(0), fps?.get(1))) // adjust view size with keeping the aspect ration of camera preview. // here is not a UI thread and we should request parent view to execute. mView.post { cameraRenderer.onPreviewSizeChanged(previewWidth, previewHeight) } // カメラ映像受け取り用Surfaceをセット val surface = cameraRenderer.getInputSurface() if (surface is SurfaceTexture) { surface.setDefaultBufferSize(previewWidth, previewHeight) } CameraUtils.setPreviewSurface(camera!!, surface) } } catch (e: IOException) { Log.e(TAG, "handleStartPreview:", e) if (camera != null) { camera!!.release() camera = null } } catch (e: RuntimeException) { Log.e(TAG, "handleStartPreview:", e) if (camera != null) { camera!!.release() camera = null } } // start camera preview display camera?.startPreview() synchronized(mSync) { mCamera = camera } } } /** * カメラプレビュー終了の実体 */ @WorkerThread private fun handleStopPreview() { if (DEBUG) Log.v(TAG, "CameraThread#handleStopPreview:") synchronized(mSync) { if (mCamera != null) { mCamera!!.stopPreview() mCamera!!.release() mCamera = null } } } companion object { private const val DEBUG = true // TODO set false on release private val TAG = CameraDelegator::class.java.simpleName const val SCALE_STRETCH_FIT = 0 const val SCALE_KEEP_ASPECT_VIEWPORT = 1 const val SCALE_KEEP_ASPECT = 2 const val SCALE_CROP_CENTER = 3 const val DEFAULT_PREVIEW_WIDTH = 1280 const val DEFAULT_PREVIEW_HEIGHT = 720 private const val TARGET_FPS_MS = 60 * 1000 } }
apache-2.0
081c523a90c70a339ca4cacfb84320e2
24.312
85
0.672566
3.241803
false
false
false
false
westnordost/StreetComplete
app/src/main/java/de/westnordost/streetcomplete/view/StreetSideSelectPuzzle.kt
1
7562
package de.westnordost.streetcomplete.view import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import android.graphics.Shader import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet import android.view.* import android.widget.FrameLayout import android.widget.ImageView import android.widget.RelativeLayout import androidx.core.view.doOnPreDraw import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.ktx.getBitmapDrawable import de.westnordost.streetcomplete.ktx.showTapHint import kotlinx.android.synthetic.main.side_select_puzzle.view.* import kotlin.math.* /** A very custom view that conceptually shows the left and right side of a street. Both sides * are clickable.<br> * It is possible to set an image for the left and for the right side individually, the image set * is repeated vertically (repeated along the street). Setting a text for each side is also * possible.<br> * The whole displayed street can be rotated and it is possible to only show the right side, for * example for one-way streets. */ class StreetSideSelectPuzzle @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr), StreetRotateable { var onClickSideListener: ((isRight: Boolean) -> Unit)? = null set(value) { field = value if (value == null) { leftSideContainer.setOnClickListener(null) rightSideContainer.setOnClickListener(null) leftSideContainer.isClickable = false rightSideContainer.isClickable = false } else { rotateContainer.isClickable = false leftSideContainer.setOnClickListener { value.invoke(false) } rightSideContainer.setOnClickListener { value.invoke(true) } } } var onClickListener: (() -> Unit)? = null set(value) { field = value if (value == null) { rotateContainer.setOnClickListener(null) rotateContainer.isClickable = false } else { leftSideContainer.isClickable = false rightSideContainer.isClickable = false rotateContainer.setOnClickListener { value.invoke() } } } private var leftImage: Image? = null private var rightImage: Image? = null private var isLeftImageSet: Boolean = false private var isRightImageSet: Boolean = false private var onlyShowingOneSide: Boolean = false init { LayoutInflater.from(context).inflate(R.layout.side_select_puzzle, this, true) doOnPreDraw { leftSideImage.pivotX = leftSideContainer.width.toFloat() rightSideImage.pivotX = 0f } addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ -> val width = min(bottom - top, right - left) val height = max(bottom - top, right - left) val params = rotateContainer.layoutParams if(width != params.width || height != params.height) { params.width = width params.height = height rotateContainer.layoutParams = params } val streetWidth = if (onlyShowingOneSide) width else width / 2 val leftImage = leftImage if (!isLeftImageSet && leftImage != null) { setStreetDrawable(leftImage, streetWidth, leftSideImage, true) isLeftImageSet = true } val rightImage = rightImage if (!isRightImageSet && rightImage != null) { setStreetDrawable(rightImage, streetWidth, rightSideImage, false) isRightImageSet = true } } } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) foreground = if (enabled) null else resources.getDrawable(R.drawable.background_transparent_grey) leftSideContainer.isEnabled = enabled rightSideContainer.isEnabled = enabled } override fun setStreetRotation(rotation: Float) { rotateContainer.rotation = rotation val scale = abs(cos(rotation * PI / 180)).toFloat() rotateContainer.scaleX = 1 + scale * 2 / 3f rotateContainer.scaleY = 1 + scale * 2 / 3f } fun setLeftSideImage(image: Image?) { leftImage = image replace(image, leftSideImage, true) } fun setRightSideImage(image: Image?) { rightImage = image replace(image, rightSideImage, false) } fun replaceLeftSideImage(image: Image?) { leftImage = image replaceAnimated(image, leftSideImage, true) } fun replaceRightSideImage(image: Image?) { rightImage = image replaceAnimated(image, rightSideImage, false) } fun setLeftSideText(text: String?) { leftSideTextView.setText(text) } fun setRightSideText(text: String?) { rightSideTextView.setText(text) } fun showLeftSideTapHint() { leftSideContainer.showTapHint(300) } fun showRightSideTapHint() { rightSideContainer.showTapHint(1200) } fun showOnlyRightSide() { isRightImageSet = false onlyShowingOneSide = true val params = RelativeLayout.LayoutParams(0, 0) params.addRule(RelativeLayout.ALIGN_PARENT_LEFT) strut.layoutParams = params } fun showOnlyLeftSide() { isLeftImageSet = false onlyShowingOneSide = true val params = RelativeLayout.LayoutParams(0, 0) params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) strut.layoutParams = params } fun showBothSides() { isRightImageSet = false isLeftImageSet = isRightImageSet onlyShowingOneSide = false val params = RelativeLayout.LayoutParams(0, 0) params.addRule(RelativeLayout.CENTER_HORIZONTAL) strut.layoutParams = params } private fun replace(image: Image?, imgView: ImageView, flip180Degrees: Boolean) { val width = if (onlyShowingOneSide) rotateContainer.width else rotateContainer.width / 2 if (width == 0) return setStreetDrawable(image, width, imgView, flip180Degrees) } private fun replaceAnimated(image: Image?, imgView: ImageView, flip180Degrees: Boolean) { replace(image, imgView, flip180Degrees) (imgView.parent as View).bringToFront() imgView.scaleX = 3f imgView.scaleY = 3f imgView.animate().scaleX(1f).scaleY(1f) } private fun setStreetDrawable(image: Image?, width: Int, imageView: ImageView, flip180Degrees: Boolean) { if (image == null) { imageView.setImageDrawable(null) } else { val drawable = scaleToWidth(resources.getBitmapDrawable(image), width, flip180Degrees) drawable.tileModeY = Shader.TileMode.REPEAT imageView.setImageDrawable(drawable) } } private fun scaleToWidth(drawable: BitmapDrawable, width: Int, flip180Degrees: Boolean): BitmapDrawable { val m = Matrix() val scale = width.toFloat() / drawable.intrinsicWidth m.postScale(scale, scale) if (flip180Degrees) m.postRotate(180f) val bitmap = Bitmap.createBitmap( drawable.bitmap, 0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight, m, true ) return BitmapDrawable(resources, bitmap) } } interface StreetRotateable { fun setStreetRotation(rotation: Float) }
gpl-3.0
7cb9738081c9ef551c732328a1bfcd9a
34.172093
109
0.658688
4.77399
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_list/ui/fragment/CourseListVisitedHorizontalFragment.kt
1
5217
package org.stepik.android.view.course_list.ui.fragment import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.ViewModelProvider import androidx.recyclerview.widget.LinearLayoutManager import kotlinx.android.synthetic.main.item_course_list.* import org.stepic.droid.R import org.stepic.droid.analytic.Analytic import org.stepic.droid.base.App import org.stepic.droid.core.ScreenManager import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepic.droid.ui.util.CoursesSnapHelper import org.stepik.android.domain.course.analytic.CourseViewSource import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource import org.stepik.android.presentation.course_list.CourseListView import org.stepik.android.presentation.course_list.CourseListVisitedPresenter import org.stepik.android.view.course.mapper.DisplayPriceMapper import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate import org.stepik.android.view.course_list.delegate.CourseListViewDelegate import org.stepik.android.view.ui.delegate.ViewStateDelegate import javax.inject.Inject class CourseListVisitedHorizontalFragment : Fragment(R.layout.item_course_list) { companion object { fun newInstance(): Fragment = CourseListVisitedHorizontalFragment() } @Inject internal lateinit var analytic: Analytic @Inject internal lateinit var screenManager: ScreenManager @Inject internal lateinit var viewModelFactory: ViewModelProvider.Factory @Inject internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper @Inject internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper @Inject internal lateinit var displayPriceMapper: DisplayPriceMapper private lateinit var courseListViewDelegate: CourseListViewDelegate private val courseListVisitedPresenter: CourseListVisitedPresenter by viewModels { viewModelFactory } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) injectComponent() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) containerCarouselCount.isVisible = false courseListPlaceholderNoConnection.isVisible = false courseListPlaceholderEmpty.isVisible = false containerTitle.text = resources.getString(R.string.visited_courses_title) with(courseListCoursesRecycler) { val rowCount = 1 layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false) itemAnimator?.changeDuration = 0 val snapHelper = CoursesSnapHelper(rowCount) snapHelper.attachToRecyclerView(this) } catalogBlockContainer.setOnClickListener { screenManager.showVisitedCourses(requireContext()) } val viewStateDelegate = ViewStateDelegate<CourseListView.State>() viewStateDelegate.addState<CourseListView.State.Idle>() viewStateDelegate.addState<CourseListView.State.Loading>(view, catalogBlockContainer, courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Content>(view, catalogBlockContainer, courseListCoursesRecycler) viewStateDelegate.addState<CourseListView.State.Empty>() viewStateDelegate.addState<CourseListView.State.NetworkError>() courseListViewDelegate = CourseListViewDelegate( analytic = analytic, courseContinueViewDelegate = CourseContinueViewDelegate( activity = requireActivity(), analytic = analytic, screenManager = screenManager ), courseListTitleContainer = catalogBlockContainer, courseItemsRecyclerView = courseListCoursesRecycler, courseListViewStateDelegate = viewStateDelegate, onContinueCourseClicked = { courseListItem -> courseListVisitedPresenter .continueCourse( course = courseListItem.course, viewSource = CourseViewSource.Visited, interactionSource = CourseContinueInteractionSource.COURSE_WIDGET ) }, defaultPromoCodeMapper = defaultPromoCodeMapper, displayPriceMapper = displayPriceMapper, itemAdapterDelegateType = CourseListViewDelegate.ItemAdapterDelegateType.SMALL ) courseListVisitedPresenter.fetchCourses() } private fun injectComponent() { App.component() .courseListVisitedComponentBuilder() .build() .inject(this) } override fun onStart() { super.onStart() courseListVisitedPresenter.attachView(courseListViewDelegate) } override fun onStop() { courseListVisitedPresenter.detachView(courseListViewDelegate) super.onStop() } }
apache-2.0
30a89d56a02639fdc1bd9795f2a69f19
39.138462
120
0.737014
5.83557
false
false
false
false
Akjir/WiFabs
src/main/kotlin/net/kejira/wifabs/util/TFXExtensions.kt
1
2187
/* * Copyright (c) 2017 Stefan Neubert * * 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 net.kejira.wifabs.util import javafx.event.EventTarget import javafx.scene.Node import javafx.scene.control.TitledPane import javafx.scene.layout.HBox import javafx.scene.layout.Priority import javafx.scene.layout.Region import javafx.scene.layout.VBox import tornadofx.* import kotlin.reflect.KClass fun EventTarget.hspacer(width: Double): Region { val spacer = Region() spacer.prefWidth = width return opcr(this, spacer, null) } fun EventTarget.hspacer(): Region { val spacer = Region() HBox.setHgrow(spacer, Priority.ALWAYS) return opcr(this, spacer) } fun EventTarget.titledpane(title: String, node: Node, collapsible: Boolean): TitledPane { val pane = TitledPane(title, node) pane.isCollapsible = collapsible return opcr(this, pane) } fun EventTarget.vspacer(height: Double): Region { val spacer = Region() spacer.prefHeight = height return opcr(this, spacer) } fun EventTarget.vspacer(): Region { val spacer = Region() VBox.setVgrow(spacer, Priority.ALWAYS) return opcr(this, spacer) }
mit
821accc9d5dfcd8ece1b11999ca621ea
33.171875
89
0.749886
4.103189
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/datagen/literals/strdedup2.kt
1
147
fun main(args : Array<String>) { val str1 = "" val str2 = "hello".subSequence(2, 2) println(str1 == str2) println(str1 === str2) }
apache-2.0
f2056f952216adbfd3ad4cee03b2ae89
23.5
40
0.571429
2.882353
false
false
false
false
PolymerLabs/arcs
java/arcs/core/util/performance/CounterStatistics.kt
1
2828
/* * Copyright 2020 Google LLC. * * This code may only be used under the BSD style license found at * http://polymer.github.io/LICENSE.txt * * Code distributed by Google as part of this project is also subject to an additional IP rights * grant found at * http://polymer.github.io/PATENTS.txt */ package arcs.core.util.performance import arcs.core.util.RunningStatistics /** * Accumulator of [RunningStatistics] about a collection of [Counters]. * * **Note:** Not thread-safe. */ class CounterStatistics private constructor( private val statistics: Map<String, RunningStatistics> ) { /** Creates a [CounterStatistics] object for the given [counterNames]. */ constructor(vararg counterNames: String) : this(counterNames.toSet()) /** Creates a [CounterStatistics] object for the given [counterNames]. */ constructor(counterNames: Set<String>) : this(counterNames.associateWith { RunningStatistics() }) /** Creates a [CounterStatistics] object based on a previous [Snapshot]. */ constructor(previous: Snapshot) : this(previous.statistics.mapValues { RunningStatistics(it.value) }) /** Creates a new [Counters] object for this [CounterStatistics]' counter names. */ fun createCounters(): Counters = Counters(statistics.keys) /** Absorbs the provided [newCounts] [Counters] into the [CounterStatistics]. */ fun append(newCounts: Counters) { statistics.forEach { (key, stats) -> stats.logStat(newCounts[key].toDouble()) } } /** Takes a snapshot of the current [RunningStatistics] for each counter. */ fun snapshot(): Snapshot = Snapshot(statistics.mapValues { it.value.snapshot() }) /** Frozen snapshot of [CounterStatistics]. */ data class Snapshot(val statistics: Map<String, RunningStatistics.Snapshot>) { /** Names of the registered counters. */ val counterNames = statistics.keys /** Creates a new/empty [Snapshot] for the provided [counterNames]. */ constructor(counterNames: Set<String>) : this(counterNames.associateWith { RunningStatistics.Snapshot() }) /** * Returns a [Snapshot] with the current [RunningStatistics.Snapshot] values for names * within [counterNames], and new/empty values for names not found within this snapshot. * * **Note:** * For counters with names not in [counterNames], their statistics will be dropped. */ fun withNames(counterNames: Set<String>): Snapshot { val newStats = mutableMapOf<String, RunningStatistics.Snapshot>() counterNames.forEach { newStats[it] = statistics[it] ?: RunningStatistics.Snapshot() } return Snapshot(newStats) } operator fun get(counterName: String): RunningStatistics.Snapshot = requireNotNull(statistics[counterName]) { "Counter with name \"$counterName\" not registered" } } }
bsd-3-clause
dff043ff80aed3202a09f40b21ce9016
36.706667
96
0.707567
4.304414
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantRequireNotNullCallInspection.kt
1
4517
// 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.inspections import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.CallableDescriptor import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.inspections.collections.isCalling import org.jetbrains.kotlin.idea.resolve.ResolutionFacade import org.jetbrains.kotlin.idea.resolve.dataFlowValueFactory import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtCallExpression import org.jetbrains.kotlin.psi.KtReferenceExpression import org.jetbrains.kotlin.psi.callExpressionVisitor import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.referenceExpression import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.bindingContextUtil.getDataFlowInfoBefore import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable class RedundantRequireNotNullCallInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(callExpression) { val callee = callExpression.calleeExpression ?: return val resolutionFacade = callExpression.getResolutionFacade() val context = callExpression.safeAnalyzeNonSourceRootCode(resolutionFacade, BodyResolveMode.PARTIAL) if (!callExpression.isCalling(FqName("kotlin.requireNotNull"), context) && !callExpression.isCalling(FqName("kotlin.checkNotNull"), context) ) return val argument = callExpression.valueArguments.firstOrNull()?.getArgumentExpression()?.referenceExpression() ?: return val descriptor = argument.getResolvedCall(context)?.resultingDescriptor ?: return val type = descriptor.returnType ?: return if (argument.isNullable(descriptor, type, context, resolutionFacade)) return val functionName = callee.text holder.registerProblem( callee, KotlinBundle.message("redundant.0.call", functionName), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, RemoveRequireNotNullCallFix(functionName) ) }) private fun KtReferenceExpression.isNullable( descriptor: CallableDescriptor, type: KotlinType, context: BindingContext, resolutionFacade: ResolutionFacade, ): Boolean { if (!type.isNullable()) return false val dataFlowValueFactory = resolutionFacade.dataFlowValueFactory val dataFlow = dataFlowValueFactory.createDataFlowValue(this, type, context, descriptor) val stableTypes = context.getDataFlowInfoBefore(this).getStableTypes(dataFlow, this.languageVersionSettings) return stableTypes.none { !it.isNullable() } } } private class RemoveRequireNotNullCallFix(private val functionName: String) : LocalQuickFix { override fun getName() = KotlinBundle.message("remove.require.not.null.call.fix.text", functionName) override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val callExpression = descriptor.psiElement.getStrictParentOfType<KtCallExpression>() ?: return val argument = callExpression.valueArguments.firstOrNull()?.getArgumentExpression() ?: return val target = callExpression.getQualifiedExpressionForSelector() ?: callExpression if (callExpression.isUsedAsExpression(callExpression.analyze(BodyResolveMode.PARTIAL_WITH_CFA))) { target.replace(argument) } else { target.delete() } } }
apache-2.0
f03f104b45d0ebed1e074a299f147439
51.534884
158
0.784149
5.409581
false
false
false
false
slesar/Layers
app/src/main/java/com/psliusar/layers/sample/screen/child/ChildrenContainerLayer.kt
1
1373
package com.psliusar.layers.sample.screen.child import android.os.Bundle import android.view.View import com.psliusar.layers.Layer import com.psliusar.layers.sample.R class ChildrenContainerLayer : Layer(R.layout.screen_children_container) { override fun onBindView(savedState: Bundle?, view: View) { super.onBindView(savedState, view) if (!isFromSavedState) { layers.at(R.id.children_container_top) .add<ChildLayer> { withLayer { setParameters("Top layer") } name = "Top" } layers.at(R.id.children_container_middle) .add<ChildLayer> { withLayer { setParameters("Middle layer") } name = "Middle" } layers.at(R.id.children_container_bottom) .add<ChildLayer> { withLayer { setParameters("Bottom layer") } name = "Bottom" } } getView<View>(R.id.children_container_add_layer).setOnClickListener { val number = layers.stackSize + 1 layers .add<ChildLayer> { withLayer { setParameters("Stack layer $number") } name = "Stack #$number" opaque = false } } } }
apache-2.0
a57e7612702b04c5a8f76317e891a222
31.690476
77
0.525127
4.516447
false
false
false
false
Tiofx/semester_6
TRPSV/src/main/kotlin/task2/graph/util.kt
1
2942
package task2.graph val INFINITE = Int.MAX_VALUE val NO_EDGE = INFINITE typealias AdjacencyMatrix = Array<IntArray> typealias AdjacencyMatrix1D = IntArray typealias AdjacencyList = Array<Adjacency> typealias PlainAdjacencyList = IntArray typealias Adjacency = Triple<Int, Int, Int> data class InputGraph(val adjacencyMatrix: AdjacencyMatrix, val sourceVertex: Int, val vertexNumber: Int = adjacencyMatrix.size) enum class PlainAdjacency(val number: Int) { SOURCE(0), DESTINATION(1), WEIGHT(2) } object Util { object AdjacencyUtil { val Adjacency.source: Int get() = this.first val Adjacency.destination: Int get() = this.second val Adjacency.weight: Int get() = this.third } object AdjacencyMatrixUtil { inline fun AdjacencyMatrix.vertexNumber() = this.size inline fun AdjacencyMatrix.toIntArray(): AdjacencyMatrix1D = this.reduce { acc, ints -> acc + ints } fun AdjacencyMatrix.toPlainAdjacencyList(): PlainAdjacencyList = this.mapIndexed { rowNum, row -> row.mapIndexed { colNum, weight -> if (weight != INFINITE) intArrayOf(rowNum, colNum, weight) else null } .filterNotNull() .reduce { acc, ints -> acc + ints } } .reduce { acc, list -> acc + list } fun AdjacencyMatrix.toAdjacencyList() = this.mapIndexed { row, ints -> ints.mapIndexed { col, w -> if (w != INFINITE) Triple(row, col, w) else null } .filterNotNull() } .reduce { acc, list -> acc + list } .toTypedArray() } object AdjacencyMatrix1DUtil { inline fun AdjacencyMatrix1D.toAdjacencyMatrix(rowColNum: Int = Math.sqrt(this.size.toDouble()).toInt()): AdjacencyMatrix = Array(rowColNum, { this.copyOfRange(it * rowColNum, (it + 1) * rowColNum) }) } object AdjacencyListUtil { val AdjacencyList.edgeNumber: Int get() = this.size inline fun AdjacencyList.toIntArray(): PlainAdjacencyList = this.map { it.toList().toIntArray() }.reduce { acc, ints -> acc + ints } } object PlainAdjacencyListUtil { inline operator fun PlainAdjacencyList.get(index: Int, col: Int) = this[3 * index + col] inline operator fun PlainAdjacencyList.get(index: Int, content: PlainAdjacency) = this[index, content.number] val PlainAdjacencyList.edgeNumber: Int get() = (this.size + 1) / 3 inline fun PlainAdjacencyList.toAdjacencyList(): AdjacencyList = this .mapIndexed { index, value -> index to value } .groupBy({ it.first / 3 }, { it.second }) .map { (_, value) -> Triple(value[0], value[1], value[2]) } .toTypedArray() } }
gpl-3.0
a1358f92ec7f0abd4fdd3e8e9c08c24c
34.878049
129
0.597553
4.220947
false
false
false
false
Hexworks/zircon
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/data/Size.kt
1
5470
package org.hexworks.zircon.api.data import org.hexworks.zircon.internal.data.DefaultSize import kotlin.jvm.JvmStatic /** * Represents a rectangular area in a 2D space. * This class is immutable and cannot change its internal state after creation. * [Size] supports destructuring to [width] and [height]. */ @Suppress("JVM_STATIC_IN_INTERFACE_1_6") interface Size : Comparable<Size> { val width: Int val height: Int operator fun plus(other: Size): Size operator fun minus(other: Size): Size operator fun component1() = width operator fun component2() = height /** * Tells whether this [Size] **is** the same as [Size.unknown]. */ val isUnknown: Boolean /** * Tells whether this [Size] **is not** the same as [Size.unknown]. */ val isNotUnknown: Boolean /** * Returns this [Size] or [other] if this size [isUnknown]. */ fun orElse(other: Size) = if (isUnknown) other else this /** * Creates a list of [Position]s in the order in which they should * be iterated when drawing (first rows, then columns in those rows). */ fun fetchPositions(): Iterable<Position> /** * Creates a list of [Position]s which represent the * bounding box of this size. So for example a size of (3x3) * will have a bounding box of * `[(0, 0), (1, 0), (2, 0), (0, 1), (2, 1), (0, 2), (1, 2), (2, 2)]` */ fun fetchBoundingBoxPositions(): Set<Position> fun fetchTopLeftPosition(): Position fun fetchTopRightPosition(): Position fun fetchBottomLeftPosition(): Position fun fetchBottomRightPosition(): Position /** * Creates a new size based on this size, but with a different width. */ fun withWidth(width: Int): Size /** * Creates a new size based on this size, but with a different height. */ fun withHeight(height: Int): Size /** * Creates a new [Size] object representing a size with the same number of height, but with * a width size offset by a supplied value. Calling this method with delta 0 will return this, * calling it with a positive delta will return * a grid size <code>delta</code> number of width wider and for negative numbers shorter. */ fun withRelativeWidth(delta: Int): Size /** * Creates a new [Size] object representing a size with the same number of width, but with a height * size offset by a supplied value. Calling this method with delta 0 will return this, calling * it with a positive delta will return * a grid size <code>delta</code> number of height longer and for negative numbers shorter. */ fun withRelativeHeight(delta: Int): Size /** * Creates a new [Size] object representing a size based on this object's size but with a delta applied. * This is the same as calling `withRelativeXLength(delta.getXLength()).withRelativeYLength(delta.getYLength())` */ fun withRelative(delta: Size): Size /** * Takes a different [Size] and returns a new [Size] that has the largest dimensions of the two, * measured separately. So calling 3x5 on a 5x3 will return 5x5. */ fun max(other: Size): Size /** * Takes a different [Size] and returns a new [Size] that has the smallest dimensions of the two, * measured separately. So calling 3x5 on a 5x3 will return 3x3. */ fun min(other: Size): Size /** * Returns itself if it is equal to the supplied size, otherwise the supplied size. * You can use this if you have a size field which is frequently recalculated but often resolves * to the same size; it will keep the same object * in memory instead of swapping it out every cycle. */ fun with(size: Size): Size /** * Tells whether this [Size] contains the given [Position]. * Works in the same way as [Rect.containsPosition]. */ fun containsPosition(position: Position): Boolean /** * Converts this [Size] to a [Position]: * [Size.width] to [Position.x] and [Size.height] to [Position.y] */ fun toPosition(): Position /** * Converts this [Size] to a [Rect] using [Position.zero]. */ fun toRect(): Rect /** * Converts this [Size] to a [Rect] with the given [Position]. */ fun toRect(position: Position): Rect /** * Creates a new [Size3D] from this [Size] and the given [zLength]. */ fun toSize3D(zLength: Int = 0) = Size3D.from2DSize(this, zLength) companion object { /** * Represents a [Size] which is an unknown (can be used instead of a `null` value). */ @JvmStatic fun unknown() = UNKNOWN /** * The default grid size is (80 * 24) */ @JvmStatic fun defaultGridSize() = DEFAULT_GRID_SIZE /** * Size of (0 * 0). */ @JvmStatic fun zero() = ZERO /** * Size of (1 * 1). */ @JvmStatic fun one() = ONE /** * Creates a new [Size] using the given `width` (width) and `height` (height). */ @JvmStatic fun create(width: Int, height: Int): Size = DefaultSize(width, height) private val UNKNOWN = create(Int.MAX_VALUE, Int.MAX_VALUE) private val DEFAULT_GRID_SIZE = create(60, 30) private val ZERO = create(0, 0) private val ONE = create(1, 1) } }
apache-2.0
3559d68de3168b5ee3015002ad210d01
29.730337
116
0.621389
4.063893
false
false
false
false
JohnnyShieh/Gank
app/src/main/kotlin/com/johnny/gank/adapter/CategoryGankAdapter.kt
1
2871
package com.johnny.gank.adapter /* * Copyright (C) 2016 Johnny Shieh 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. */ import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.johnny.gank.R import com.johnny.gank.model.ui.GankNormalItem import kotlinx.android.synthetic.main.recycler_item_gank.view.* /** * description * * @author Johnny Shieh ([email protected]) * @version 1.0 */ class CategoryGankAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private val items = mutableListOf<GankNormalItem>() var curPage = 0 private set var onItemClickListener: OnItemClickListener? = null interface OnItemClickListener { fun onClickNormalItem(view: View, normalItem: GankNormalItem) } fun updateData(page: Int, list: List<GankNormalItem>?) { if (null == list || list.isEmpty()) return if (page - curPage > 1) return if (page <= 1) { if (!items.containsAll(list)) { items.clear() items.addAll(list) curPage = page notifyDataSetChanged() } } else if (1 == page - curPage) { val oldSize = items.size items.addAll(oldSize, list) notifyItemRangeInserted(oldSize, list.size) curPage = page } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return NormalViewHolder(parent) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is NormalViewHolder) { val normalItem = items[position] holder.itemView.title.text = getGankTitleStr(normalItem.gank.desc, normalItem.gank.who) holder.itemView.title.setOnClickListener { view -> onItemClickListener?.onClickNormalItem(view, normalItem) } } } override fun getItemCount(): Int { return items.size } class NormalViewHolder constructor(parent: ViewGroup) : RecyclerView.ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.recycler_item_gank, parent, false)) { init { itemView.align_pic.visibility = View.GONE } } }
apache-2.0
26b6b4aa3430fe7b286bfbcff9eb2c0f
32
155
0.668757
4.52126
false
false
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/ui/sitecreation/misc/SearchInputWithHeader.kt
1
3589
package org.wordpress.android.ui.sitecreation.misc import android.content.Context import android.os.Handler import android.os.Looper import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import org.wordpress.android.R import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.ActivityUtils class SearchInputWithHeader(private val uiHelpers: UiHelpers, rootView: View, onClear: () -> Unit) { private val headerLayout = rootView.findViewById<ViewGroup>(R.id.site_creation_header_item) private val headerTitle = rootView.findViewById<TextView>(R.id.title) private val headerSubtitle = rootView.findViewById<TextView>(R.id.subtitle) private val searchInput = rootView.findViewById<EditText>(R.id.input) private val progressBar = rootView.findViewById<View>(R.id.progress_bar) private val clearAllLayout = rootView.findViewById<View>(R.id.clear_all_layout) private val divider = rootView.findViewById<View>(R.id.divider) private val showKeyboardHandler = Handler(Looper.getMainLooper()) var onTextChanged: ((String) -> Unit)? = null init { clearAllLayout.setOnClickListener { onClear() } searchInput.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(s: Editable?) {} override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { onTextChanged?.invoke(s?.toString() ?: "") } }) } fun setInputText(text: String) { // If the text hasn't changed avoid triggering the text watcher if (searchInput.text.toString() != text) { searchInput.setText(text) } } fun updateHeader(context: Context, uiState: SiteCreationHeaderUiState?) { val headerShouldBeVisible = uiState != null if (!headerShouldBeVisible && headerLayout.visibility == View.VISIBLE) { headerLayout.animate().translationY(-headerLayout.height.toFloat()) } else if (headerShouldBeVisible && headerLayout.visibility == View.GONE) { headerLayout.animate().translationY(0f) } uiState?.let { uiHelpers.updateVisibility(headerLayout, true) headerTitle.text = uiHelpers.getTextOfUiString(context, uiState.title) headerSubtitle.text = uiHelpers.getTextOfUiString(context, uiState.subtitle) } ?: uiHelpers.updateVisibility(headerLayout, false) } fun updateSearchInput(context: Context, uiState: SiteCreationSearchInputUiState) { searchInput.hint = uiHelpers.getTextOfUiString(context, uiState.hint) uiHelpers.updateVisibility(progressBar, uiState.showProgress) uiHelpers.updateVisibility(clearAllLayout, uiState.showClearButton) uiHelpers.updateVisibility(divider, uiState.showDivider) showKeyboard(uiState.showKeyboard) } private fun showKeyboard(shouldShow: Boolean) { if (shouldShow) { searchInput.requestFocus() /** * This workaround handles the case where the SiteCreationDomainsFragment appears after the * DesignPreviewFragment dismisses and the keyboard fails to appear */ showKeyboardHandler.postDelayed({ ActivityUtils.showKeyboard(searchInput) }, 200) } } }
gpl-2.0
3d29bcd0d078b0c92ffdcfcb1f7e8833
42.240964
103
0.696294
4.869742
false
false
false
false
TomsUsername/Phoenix
src/main/kotlin/phoenix/bot/pogo/nRnMK9r/tasks/HatchEggs.kt
1
3376
/** * Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information) * This program comes with ABSOLUTELY NO WARRANTY; * This is free software, and you are welcome to redistribute it under certain conditions. * * For more information, refer to the LICENSE file in this repositories root directory */ package phoenix.bot.pogo.nRnMK9r.tasks import POGOProtos.Networking.Responses.UseItemEggIncubatorResponseOuterClass import phoenix.bot.pogo.api.request.GetHatchedEggs import phoenix.bot.pogo.api.request.UseItemEggIncubator import phoenix.bot.pogo.nRnMK9r.Bot import phoenix.bot.pogo.nRnMK9r.Context import phoenix.bot.pogo.nRnMK9r.Settings import phoenix.bot.pogo.nRnMK9r.Task import phoenix.bot.pogo.nRnMK9r.util.Log import phoenix.bot.pogo.nRnMK9r.util.pokemon.getIvPercentage import phoenix.bot.pogo.nRnMK9r.util.pokemon.incubated class HatchEggs : Task { override fun run(bot: Bot, ctx: Context, settings: Settings) { // not necessary, update profile is executed before this already in the tasks //bot.api.queueRequest(GetInventory().withLastTimestampMs(0)) bot.api.queueRequest(GetHatchedEggs()).subscribe { val response = it.response response.pokemonIdList.forEachIndexed { index, it -> val newPokemon = ctx.api.inventory.pokemon[it] val candy = response.candyAwardedList[index] val experience = response.experienceAwardedList[index] val stardust = response.stardustAwardedList[index] val stats = "+${candy} candy; +${experience} XP; +${stardust} stardust" if (newPokemon == null) { Log.cyan("Hatched pokemon; $stats") } else { Log.cyan("Hatched ${newPokemon.pokemonData.pokemonId.name} with ${newPokemon.pokemonData.cp} CP " + "and ${newPokemon.pokemonData.getIvPercentage()}% IV; $stats") } } } val incubators = ctx.api.inventory.eggIncubators val eggs = ctx.api.inventory.eggs val freeIncubators = incubators.map { it.value } .filter { it.targetKmWalked < bot.api.inventory.playerStats.kmWalked } .sortedByDescending { it.usesRemaining } val filteredEggs = eggs.map { it.value } .filter { !it.pokemonData.incubated } .sortedByDescending { it.pokemonData.eggKmWalkedTarget } if (freeIncubators.isNotEmpty() && filteredEggs.isNotEmpty() && settings.autoFillIncubator) { var eggResult = filteredEggs.first() if (freeIncubators.first().usesRemaining == 0) { eggResult = filteredEggs.last() } val use = UseItemEggIncubator().withPokemonId(eggResult.pokemonData.id).withItemId(freeIncubators.first().id) bot.api.queueRequest(use).subscribe { val response = it.response if (response.result == UseItemEggIncubatorResponseOuterClass.UseItemEggIncubatorResponse.Result.SUCCESS) { Log.cyan("Put egg of ${eggResult.pokemonData.eggKmWalkedTarget}km in unused incubator") } else { Log.red("Failed to put egg in incubator; error: ${response.result}") } } } } }
gpl-3.0
b7036e61b3c806f9653182789d513edf
47.228571
122
0.651066
4.167901
false
false
false
false
DiUS/pact-jvm
core/matchers/src/main/kotlin/au/com/dius/pact/core/matchers/util/CollectionUtils.kt
1
725
package au.com.dius.pact.core.matchers.util fun tails(col: List<String>): List<List<String>> { val result = mutableListOf<List<String>>() var acc = col while (acc.isNotEmpty()) { result.add(acc) acc = acc.drop(1) } result.add(acc) return result } fun <A, B> corresponds(l1: List<A>, l2: List<B>, fn: (a: A, b: B) -> Boolean): Boolean { return if (l1.size == l2.size) { l1.zip(l2).all { fn(it.first, it.second) } } else { false } } fun <E> List<E>.padTo(size: Int, item: E): List<E> { return if (size < this.size) { this.dropLast(this.size - size) } else { val list = this.toMutableList() for (i in this.size.until(size)) { list.add(item) } return list } }
apache-2.0
c8f3648e3f144a9ca4a84384b288abb3
21.65625
88
0.593103
2.746212
false
false
false
false
ingokegel/intellij-community
python/src/com/jetbrains/python/inspections/PyRelativeImportInspection.kt
5
6185
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.command.undo.BasicUndoableAction import com.intellij.openapi.command.undo.UndoManager import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.project.Project import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElementVisitor import com.intellij.psi.util.PsiTreeUtil import com.jetbrains.python.PyBundle import com.jetbrains.python.PyPsiBundle import com.jetbrains.python.PyTokenTypes import com.jetbrains.python.namespacePackages.PyNamespacePackagesService import com.jetbrains.python.psi.LanguageLevel import com.jetbrains.python.psi.PyElementGenerator import com.jetbrains.python.psi.PyFromImportStatement import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.types.TypeEvalContext class PyRelativeImportInspection : PyInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor { if (!PyNamespacePackagesService.isEnabled() || LanguageLevel.forElement(holder.file).isOlderThan(LanguageLevel.PYTHON34)) { return PsiElementVisitor.EMPTY_VISITOR } return Visitor(holder, PyInspectionVisitor.getContext(session)) } private class Visitor(holder: ProblemsHolder, context: TypeEvalContext) : PyInspectionVisitor(holder, context) { override fun visitPyFromImportStatement(node: PyFromImportStatement) { val directory = node.containingFile?.containingDirectory ?: return if (node.relativeLevel > 0 && !PyUtil.isExplicitPackage(directory) && !isInsideOrdinaryPackage(directory)) { handleRelativeImportNotInsidePackage(node, directory) } } private fun isInsideOrdinaryPackage(directory: PsiDirectory): Boolean { var curDir: PsiDirectory? = directory while (curDir != null) { if (PyUtil.isOrdinaryPackage(curDir)) return true curDir = curDir.parentDirectory } return false } private fun handleRelativeImportNotInsidePackage(node: PyFromImportStatement, directory: PsiDirectory) { val fixes = mutableListOf<LocalQuickFix>() getMarkAsNamespacePackageQuickFix(directory) ?.let { fixes.add(it) } if (node.relativeLevel == 1) { fixes.add(PyChangeToSameDirectoryImportQuickFix()) } val message = PyPsiBundle.message("INSP.relative.import.relative.import.outside.package") registerProblem(node, message, *fixes.toTypedArray()) } private fun getMarkAsNamespacePackageQuickFix(directory: PsiDirectory): PyMarkAsNamespacePackageQuickFix? { val module = ModuleUtilCore.findModuleForPsiElement(directory) ?: return null var curDir: PsiDirectory? = directory while (curDir != null) { val virtualFile = curDir.virtualFile if (PyUtil.isRoot(curDir)) return null val parentDir = curDir.parentDirectory if (parentDir != null && (PyUtil.isRoot(parentDir) || PyUtil.isOrdinaryPackage(parentDir))) { return PyMarkAsNamespacePackageQuickFix(module, virtualFile) } curDir = parentDir } return null } } private class PyMarkAsNamespacePackageQuickFix(val module: Module, val directory: VirtualFile) : LocalQuickFix { override fun getFamilyName(): String = PyBundle.message("QFIX.mark.as.namespace.package", directory.name) override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val document = PsiDocumentManager.getInstance(project).getDocument(descriptor.psiElement.containingFile) val undoableAction = object: BasicUndoableAction(document) { override fun undo() { PyNamespacePackagesService.getInstance(module).toggleMarkingAsNamespacePackage(directory) } override fun redo() { PyNamespacePackagesService.getInstance(module).toggleMarkingAsNamespacePackage(directory) } } undoableAction.redo() UndoManager.getInstance(project).undoableActionPerformed(undoableAction) } override fun generatePreview(project: Project, previewDescriptor: ProblemDescriptor): IntentionPreviewInfo { // The quick fix updates a directory's properties in the project structure, nothing changes in the current file return IntentionPreviewInfo.EMPTY } } private class PyChangeToSameDirectoryImportQuickFix : LocalQuickFix { override fun getFamilyName(): String = PyBundle.message("QFIX.change.to.same.directory.import") override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val oldImport = descriptor.psiElement as? PyFromImportStatement ?: return assert(oldImport.relativeLevel == 1) val qualifier = oldImport.importSource if (qualifier != null) { val possibleDot = PsiTreeUtil.prevVisibleLeaf(qualifier) assert(possibleDot != null && possibleDot.node.elementType == PyTokenTypes.DOT) possibleDot?.delete() } else { replaceByImportStatements(oldImport) } } private fun replaceByImportStatements(oldImport: PyFromImportStatement) { val project = oldImport.project val generator = PyElementGenerator.getInstance(project) val names = oldImport.importElements.map { it.text } if (names.isEmpty()) return val langLevel = LanguageLevel.forElement(oldImport) for (name in names.reversed()) { val newImport = generator.createImportStatement(langLevel, name, null) oldImport.parent.addAfter(newImport, oldImport) } oldImport.delete() } } }
apache-2.0
44ed2b26c1258fe53e14e30699911067
42.87234
140
0.747777
4.893196
false
false
false
false
GunoH/intellij-community
plugins/gradle/java/testSources/execution/test/GradleJavaTestEventsIntegrationTestCase.kt
2
3765
// 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.gradle.execution.test import com.intellij.openapi.externalSystem.model.task.* import com.intellij.openapi.externalSystem.model.task.event.ExternalSystemTaskExecutionEvent import com.intellij.openapi.externalSystem.model.task.event.TestOperationDescriptor import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.util.registry.Registry import org.assertj.core.api.AbstractThrowableAssert import org.assertj.core.api.Condition import org.gradle.util.GradleVersion import org.jetbrains.plugins.gradle.service.task.GradleTaskManager import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings import org.jetbrains.plugins.gradle.testFramework.GradleProjectTestCase import org.jetbrains.plugins.gradle.testFramework.GradleTestFixtureBuilder import org.jetbrains.plugins.gradle.util.GradleConstants.SYSTEM_ID abstract class GradleJavaTestEventsIntegrationTestCase : GradleProjectTestCase() { override fun test(gradleVersion: GradleVersion, fixtureBuilder: GradleTestFixtureBuilder, test: () -> Unit) { super.test(gradleVersion, fixtureBuilder) { val testLauncherApi = Registry.get("gradle.testLauncherAPI.enabled") if (testLauncherAPISupported()) { testLauncherApi.setValue(true) } try { test() } finally { if (testLauncherAPISupported()) { testLauncherApi.setValue(false) } } } } fun testLauncherAPISupported(): Boolean { return isGradleAtLeast("6.1") } fun executeTasks(vararg tasks: String, configure: GradleExecutionSettings.() -> Unit = {}): LoggingESOutputListener { val listener = LoggingESOutputListener() executeTasks(listener, *tasks, configure = configure) return listener } fun executeTasks( listener: LoggingESOutputListener, vararg tasks: String, configure: GradleExecutionSettings.() -> Unit = {} ) { val id = ExternalSystemTaskId.create(SYSTEM_ID, ExternalSystemTaskType.EXECUTE_TASK, project) val settings = ExternalSystemApiUtil.getExecutionSettings<GradleExecutionSettings>(project, projectPath, SYSTEM_ID) settings.configure() GradleTaskManager().executeTasks(id, tasks.toList(), projectPath, settings, null, listener) } class LoggingESOutputListener( private val delegate: LoggingESStatusChangeListener = LoggingESStatusChangeListener() ) : ExternalSystemTaskNotificationListenerAdapter(delegate) { val eventLog = mutableListOf<String>() val testsDescriptors: List<TestOperationDescriptor> get() = delegate.testsDescriptors override fun onTaskOutput(id: ExternalSystemTaskId, text: String, stdOut: Boolean) { addEventLogLines(text, eventLog) } private fun addEventLogLines(text: String, eventLog: MutableList<String>) { text.split("<ijLogEol/>").mapTo(eventLog) { it.trim('\r', '\n', ' ') } } } class LoggingESStatusChangeListener : ExternalSystemTaskNotificationListenerAdapter() { private val eventLog = mutableListOf<ExternalSystemTaskNotificationEvent>() val testsDescriptors: List<TestOperationDescriptor> get() = eventLog .filterIsInstance<ExternalSystemTaskExecutionEvent>() .map { it.progressEvent.descriptor } .filterIsInstance<TestOperationDescriptor>() override fun onStatusChange(event: ExternalSystemTaskNotificationEvent) { eventLog.add(event) } } companion object { fun <T : AbstractThrowableAssert<*, *>> T.`is`(message: String, predicate: (String) -> Boolean): T = apply { `is`(Condition({ predicate(it.message ?: "") }, message)) } } }
apache-2.0
4eec6c6f17f942c7e056c151c00475a7
38.631579
120
0.75166
4.694514
false
true
false
false
GunoH/intellij-community
platform/lang-impl/src/com/intellij/lang/documentation/classes.kt
5
2090
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.lang.documentation import com.intellij.model.Pointer import com.intellij.openapi.progress.blockingContext import com.intellij.util.AsyncSupplier import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.buffer import kotlinx.coroutines.flow.channelFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.withContext import org.jetbrains.annotations.Nls import java.awt.Image import java.util.function.Supplier internal data class DocumentationContentData internal constructor( val html: @Nls String, val imageResolver: DocumentationImageResolver?, ) : DocumentationContent internal data class LinkData( val externalUrl: String? = null, val linkUrls: List<String> = emptyList(), ) internal class AsyncDocumentation( val supplier: AsyncSupplier<DocumentationResult.Data?> ) : DocumentationResult internal class ResolvedTarget( val target: DocumentationTarget, ) : LinkResolveResult internal class AsyncLinkResolveResult( val supplier: AsyncSupplier<LinkResolveResult.Async?>, ) : LinkResolveResult internal class AsyncResolvedTarget( val pointer: Pointer<out DocumentationTarget>, ) : LinkResolveResult.Async internal fun <X> Supplier<X>.asAsyncSupplier(): AsyncSupplier<X> = { withContext(Dispatchers.IO) { blockingContext { [email protected]() } } } internal fun imageResolver(map: Map<String, Image>): DocumentationImageResolver? { if (map.isEmpty()) { return null } return DocumentationImageResolver(map.toMap()::get) } internal fun DocumentationContentUpdater.asFlow(): Flow<DocumentationContent> { val flow = channelFlow { blockingContext { updateContent { content -> check(trySend(content).isSuccess) // sanity check } } } return flow .buffer(capacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) .flowOn(Dispatchers.IO) }
apache-2.0
8baeef01693ba323e7f4af09b4b0429c
28.857143
120
0.779904
4.418605
false
false
false
false
GunoH/intellij-community
plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleJvmUtil.kt
10
1799
// 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. @file:JvmName("GradleJvmUtil") @file:ApiStatus.Internal package org.jetbrains.plugins.gradle.util import com.intellij.openapi.externalSystem.service.execution.createJdkInfo import com.intellij.openapi.externalSystem.service.execution.nonblockingResolveJdkInfo import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider.SdkInfo import org.jetbrains.annotations.ApiStatus import java.nio.file.Paths const val USE_GRADLE_JAVA_HOME = "#GRADLE_JAVA_HOME" fun SdkLookupProvider.nonblockingResolveGradleJvmInfo(project: Project, externalProjectPath: String?, gradleJvm: String?): SdkInfo { val projectSdk = ProjectRootManager.getInstance(project).projectSdk return nonblockingResolveGradleJvmInfo(project, projectSdk, externalProjectPath, gradleJvm) } fun SdkLookupProvider.nonblockingResolveGradleJvmInfo(project: Project, projectSdk: Sdk?, externalProjectPath: String?, gradleJvm: String?): SdkInfo { return when (gradleJvm) { USE_GRADLE_JAVA_HOME -> createJdkInfo(GRADLE_JAVA_HOME_PROPERTY, getGradleJavaHome(project, externalProjectPath)) else -> nonblockingResolveJdkInfo(projectSdk, gradleJvm) } } fun getGradleJavaHome(project: Project, externalProjectPath: String?): String? { if (externalProjectPath == null) { return null } val properties = getGradleProperties(project, Paths.get(externalProjectPath)) val javaHomeProperty = properties.javaHomeProperty ?: return null return javaHomeProperty.value }
apache-2.0
16cc0bdc3abdd1dd25c75dec102a9fcb
47.648649
150
0.8199
4.45297
false
true
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/ScriptResidenceExceptionProvider.kt
2
1450
// 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.script.configuration import com.intellij.openapi.vfs.VirtualFile internal open class ScriptResidenceExceptionProvider( private val suffix: String, private val supportedUnderSourceRoot: Boolean = false ) { open fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean = virtualFile.name.endsWith(suffix) fun isSupportedUnderSourceRoot(virtualFile: VirtualFile): Boolean = if (supportedUnderSourceRoot) isSupportedScriptExtension(virtualFile) else false } internal val scriptResidenceExceptionProviders = listOf( ScriptResidenceExceptionProvider(".gradle.kts", true), ScriptResidenceExceptionProvider(".main.kts"), ScriptResidenceExceptionProvider(".space.kts"), ScriptResidenceExceptionProvider(".ws.kts", true), object : ScriptResidenceExceptionProvider(".teamcity.kts", true) { override fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean { if (!virtualFile.name.endsWith(".kts")) return false var parent = virtualFile.parent while (parent != null) { if (parent.isDirectory && parent.name == ".teamcity") { return true } parent = parent.parent } return false } } )
apache-2.0
9b963941dc39b37c8939859dfe347da1
37.184211
120
0.694483
4.982818
false
false
false
false
GunoH/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInspection/DuplicateExpressionsFixTest.kt
8
3794
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.java.codeInspection import com.intellij.JavaTestUtil import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInspection.duplicateExpressions.DuplicateExpressionsInspection import com.intellij.java.JavaBundle import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import com.intellij.ui.ChooserInterceptor import com.intellij.ui.UiInterceptors import java.util.regex.Pattern /** * @author Pavel.Dolgov */ class DuplicateExpressionsFixTest : LightJavaCodeInsightFixtureTestCase() { val inspection = DuplicateExpressionsInspection() override fun setUp() { super.setUp() myFixture.enableInspections(inspection) } override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/inspection/duplicateExpressionsFix" fun testIntroduceVariable() { UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences"))) doTest(introduce("s.substring(s.length() - 9)")) } fun testReuseVariable() = doTest(reuse("substr", "s.substring(s.length() - 9)")) fun testReplaceOthers() = doTest(replace("substr", "s.substring(s.length() - 9)")) fun testIntroduceVariableOtherVariableNotInScope() { UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences"))) doTest(introduce("s.substring(s.length() - 9)")) } fun testVariableNotInScopeCantReplaceOthers() = doNegativeTest(replace("substr", "s.substring(s.length() - 9)")) fun testIntroducePathVariableTwoPathOf() { UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences"))) doTest(introduce("Path.of(fileName)")) } fun testIntroducePathVariableTwoPathsGet() { UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences"))) doTest(introduce("Paths.get(fileName)")) } fun testIntroducePathVariablePathOfPathsGet() { UiInterceptors.register(ChooserInterceptor(null, Pattern.quote("Replace all 0 occurrences"))) doTest(introduce("Paths.get(fileName)")) } fun testRandomUUIDIsNotReplaced() { doNegativeTest(replace("s1", "String.valueOf(UUID.randomUUID().getMostSignificantBits())")) } private fun doTest(message: String, threshold: Int = 50) = withThreshold(threshold) { myFixture.configureByFile("${getTestName(false)}.java") myFixture.launchAction(myFixture.findSingleIntention(message)) myFixture.checkResultByFile("${getTestName(false)}_after.java") } private fun doNegativeTest(message: String, threshold: Int = 50) = withThreshold(threshold) { myFixture.configureByFile("${getTestName(false)}.java") val intentions = myFixture.filterAvailableIntentions(message) assertEquals(emptyList<IntentionAction>(), intentions) } private fun withThreshold(threshold: Int, block: () -> Unit) { val oldThreshold = inspection.complexityThreshold try { inspection.complexityThreshold = threshold block() } finally { inspection.complexityThreshold = oldThreshold } } override fun getProjectDescriptor(): LightProjectDescriptor { return JAVA_11 } private fun introduce(expr: String) = JavaBundle.message("inspection.duplicate.expressions.introduce.variable.fix.name", expr) private fun reuse(name: String, expr: String) = JavaBundle.message("inspection.duplicate.expressions.reuse.variable.fix.name", name, expr) private fun replace(name: String, expr: String) = JavaBundle.message("inspection.duplicate.expressions.replace.other.occurrences.fix.name", name, expr) }
apache-2.0
c8651127e93ea3c2ade550cb52e2974e
40.692308
120
0.75883
4.565584
false
true
false
false
mvmike/min-cal-widget
app/src/main/kotlin/cat/mvmike/minimalcalendarwidget/domain/Instance.kt
1
1659
// Copyright (c) 2016, Miquel Martí <[email protected]> // See LICENSE for licensing information package cat.mvmike.minimalcalendarwidget.domain import android.content.Context import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.CalendarResolver import cat.mvmike.minimalcalendarwidget.infrastructure.resolver.SystemResolver import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneId data class Instance( val eventId: Int, val start: Instant, val end: Instant, val zoneId: ZoneId, val isDeclined: Boolean ) { // take out 5 milliseconds to avoid erratic behaviour events that end at midnight fun isInDay(day: LocalDate): Boolean { val instanceStartLocalDate = LocalDateTime.ofInstant(start, zoneId).toLocalDate() val instanceEndLocalDate = LocalDateTime.ofInstant(end.minusMillis(5), zoneId).toLocalDate() return !instanceStartLocalDate.isAfter(day) && !instanceEndLocalDate.isBefore(day) } } fun getInstances(context: Context, from: LocalDate, to: LocalDate): Set<Instance> { return when (CalendarResolver.isReadCalendarPermitted(context)) { false -> HashSet() true -> { val systemZoneId = SystemResolver.getSystemZoneId() CalendarResolver.getInstances( context = context, begin = from.toStartOfDayInEpochMilli(systemZoneId), end = to.toStartOfDayInEpochMilli(systemZoneId) ) } } } private fun LocalDate.toStartOfDayInEpochMilli(zoneId: ZoneId) = this.atStartOfDay(zoneId).toInstant().toEpochMilli()
bsd-3-clause
bc1ecec91a3dea6b63435fca986e2d13
36.681818
100
0.721351
4.657303
false
false
false
false
mdanielwork/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/util/FinderPredicate.kt
7
769
// 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.util typealias FinderPredicate = (String, String) -> Boolean object Predicate{ val equality: FinderPredicate = { found: String, wanted: String -> found == wanted } val notEquality: FinderPredicate = { found: String, wanted: String -> found != wanted } val withVersion: FinderPredicate = { found: String, wanted: String -> val pattern = Regex("\\s+\\(.*\\)$") if (found.contains(pattern)) { pattern.split(found).first().trim() == wanted } else found == wanted } val startWith: FinderPredicate = {found: String, wanted: String -> found.startsWith(wanted)} }
apache-2.0
6a22ad27127ca1a2cb9ad4b2bdafa66a
41.777778
140
0.695709
4.202186
false
true
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/util/conversion/ConversionResolve.kt
1
3201
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * 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.jonathanxd.kores.util.conversion import com.github.jonathanxd.kores.base.FieldDeclaration import com.github.jonathanxd.kores.base.MethodDeclaration import com.github.jonathanxd.kores.base.TypeDeclaration import com.github.jonathanxd.kores.type.`is` import com.github.jonathanxd.kores.type.koresType import java.lang.reflect.Field import java.lang.reflect.Method /** * Searches [methodDeclaration] in this [Class]. */ fun <T : Any> Class<T>.find(methodDeclaration: MethodDeclaration): Method? { val filter = filter@ { it: Method -> val name = it.name val returnType = it.returnType.koresType val parameterTypes = it.parameterTypes.map { it.koresType } return@filter name == methodDeclaration.name && returnType.`is`(methodDeclaration.returnType) && parameterTypes.isEqual(methodDeclaration.parameters) } return this.declaredMethods.first(filter) ?: this.methods.first(filter) } /** * Searches [fieldDeclaration] in this [Class]. */ fun <T : Any> Class<T>.find(fieldDeclaration: FieldDeclaration): Field? { val filter = filter@ { it: Field -> val name = it.name val type = it.type.koresType return@filter name == fieldDeclaration.name && type.`is`(fieldDeclaration.type) } return this.declaredFields.first(filter) ?: this.fields.first(filter) } /** * Searches the [typeDeclaration] in this [Class]. */ fun <T : Any> Class<T>.find(typeDeclaration: TypeDeclaration): Class<*>? { val filter = filter@ { it: Class<*> -> val type = it.koresType return@filter type.`is`(typeDeclaration) } return this.declaredClasses.first(filter) ?: this.classes.first(filter) }
mit
4f198ea36760eb0ab429d70d42c0731b
37.119048
118
0.696657
4.206307
false
false
false
false
dahlstrom-g/intellij-community
platform/platform-impl/src/com/intellij/openapi/wm/impl/customFrameDecorations/header/toolbar/ToolbarFrameHeader.kt
2
6058
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.wm.impl.customFrameDecorations.header.toolbar import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettingsListener import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.wm.IdeFrame import com.intellij.openapi.wm.impl.IdeMenuBar import com.intellij.openapi.wm.impl.ToolbarHolder import com.intellij.openapi.wm.impl.customFrameDecorations.header.FrameHeader import com.intellij.openapi.wm.impl.customFrameDecorations.header.MainFrameCustomHeader import com.intellij.openapi.wm.impl.headertoolbar.MainToolbar import com.intellij.openapi.wm.impl.headertoolbar.isToolbarInHeader import com.intellij.ui.awt.RelativeRectangle import com.intellij.ui.components.panels.NonOpaquePanel import com.intellij.util.ui.GridBag import com.intellij.util.ui.JBUI import com.intellij.util.ui.JBUI.CurrentTheme.CustomFrameDecorations import com.jetbrains.CustomWindowDecoration.MENU_BAR import java.awt.* import java.awt.GridBagConstraints.* import java.awt.event.ComponentAdapter import java.awt.event.ComponentEvent import javax.swing.Box import javax.swing.JComponent import javax.swing.JFrame import javax.swing.JPanel import kotlin.math.roundToInt private enum class ShowMode { MENU, TOOLBAR } internal class ToolbarFrameHeader(frame: JFrame, ideMenu: IdeMenuBar) : FrameHeader(frame), UISettingsListener, ToolbarHolder, MainFrameCustomHeader { private val myMenuBar = ideMenu private val mainMenuButton = MainMenuButton() private var myToolbar : MainToolbar? = null private val myToolbarPlaceholder = NonOpaquePanel() private val myHeaderContent = createHeaderContent() private val contentResizeListener = object : ComponentAdapter() { override fun componentResized(e: ComponentEvent?) { updateCustomDecorationHitTestSpots() } } private var mode = ShowMode.MENU init { layout = GridBagLayout() val gb = GridBag().anchor(WEST) updateLayout(UISettings.getInstance()) productIcon.border = JBUI.Borders.empty(V, 0, V, 0) add(productIcon, gb.nextLine().next().anchor(WEST).insetLeft(H)) add(myHeaderContent, gb.next().fillCell().anchor(CENTER).weightx(1.0).weighty(1.0)) val buttonsView = buttonPanes.getView() if (SystemInfo.isWindows) buttonsView.border = JBUI.Borders.emptyLeft(8) add(buttonsView, gb.next().anchor(EAST)) setCustomFrameTopBorder({ false }, {true}) Disposer.register(this, mainMenuButton.menuShortcutHandler) } override fun updateToolbar() { removeToolbar() val toolbar = MainToolbar() toolbar.init((frame as? IdeFrame)?.project) toolbar.isOpaque = false toolbar.addComponentListener(contentResizeListener) myToolbar = toolbar myToolbarPlaceholder.add(myToolbar) myToolbarPlaceholder.revalidate() } override fun removeToolbar() { myToolbar?.removeComponentListener(contentResizeListener) myToolbarPlaceholder.removeAll() myToolbarPlaceholder.revalidate() } override fun installListeners() { super.installListeners() mainMenuButton.menuShortcutHandler.registerShortcuts(frame.rootPane) myMenuBar.addComponentListener(contentResizeListener) } override fun uninstallListeners() { super.uninstallListeners() mainMenuButton.menuShortcutHandler.unregisterShortcuts() myMenuBar.removeComponentListener(contentResizeListener) myToolbar?.removeComponentListener(contentResizeListener) } override fun updateMenuActions(forceRebuild: Boolean) {} //todo remove override fun getComponent(): JComponent = this override fun uiSettingsChanged(uiSettings: UISettings) { updateLayout(uiSettings) when (mode) { ShowMode.TOOLBAR -> updateToolbar() ShowMode.MENU -> removeToolbar() } } override fun getHitTestSpots(): List<Pair<RelativeRectangle, Int>> { val result = super.getHitTestSpots().toMutableList() when (mode) { ShowMode.MENU -> { result.add(Pair(getElementRect(myMenuBar) { rect -> val state = frame.extendedState if (state != Frame.MAXIMIZED_VERT && state != Frame.MAXIMIZED_BOTH) { val topGap = (rect.height / 3).toFloat().roundToInt() rect.y += topGap rect.height -= topGap } }, MENU_BAR)) } ShowMode.TOOLBAR -> { result.add(Pair(getElementRect(mainMenuButton.button), MENU_BAR)) myToolbar?.components?.filter { it.isVisible }?.forEach { result.add(Pair(getElementRect(it), MENU_BAR)) } } } return result } override fun getHeaderBackground(active: Boolean) = CustomFrameDecorations.mainToolbarBackground(active) private fun getElementRect(comp: Component, rectProcessor: ((Rectangle) -> Unit)? = null): RelativeRectangle { val rect = Rectangle(comp.size) rectProcessor?.invoke(rect) return RelativeRectangle(comp, rect) } fun createHeaderContent(): JPanel { val res = NonOpaquePanel(CardLayout()) res.border = JBUI.Borders.empty() val menuPnl = NonOpaquePanel(GridBagLayout()).apply { val gb = GridBag().anchor(WEST).nextLine() add(myMenuBar, gb.next().insetLeft(JBUI.scale(20)).fillCellVertically().weighty(1.0)) add(Box.createHorizontalGlue(), gb.next().weightx(1.0).fillCell()) } val toolbarPnl = NonOpaquePanel(GridBagLayout()).apply { val gb = GridBag().anchor(WEST).nextLine() add(mainMenuButton.button, gb.next().insetLeft(JBUI.scale(20))) add(myToolbarPlaceholder, gb.next().weightx(1.0).fillCellHorizontally().insetLeft(JBUI.scale(16))) } res.add(ShowMode.MENU.name, menuPnl) res.add(ShowMode.TOOLBAR.name, toolbarPnl) return res } private fun updateLayout(settings: UISettings) { mode = if (isToolbarInHeader(settings)) ShowMode.TOOLBAR else ShowMode.MENU val layout = myHeaderContent.layout as CardLayout layout.show(myHeaderContent, mode.name) } }
apache-2.0
9579678c05274ab4d129276bf141f64b
34.846154
150
0.742984
4.269204
false
false
false
false
kingargyle/serenity-android
serenity-app/src/main/kotlin/us/nineworlds/serenity/ui/activity/login/LoginUserPresenter.kt
2
2460
package us.nineworlds.serenity.ui.activity.login import com.birbit.android.jobqueue.JobManager import moxy.InjectViewState import moxy.MvpPresenter import moxy.viewstate.strategy.SkipStrategy import moxy.viewstate.strategy.StateStrategyType import org.greenrobot.eventbus.EventBus import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode.MAIN import toothpick.Toothpick import us.nineworlds.serenity.common.Server import us.nineworlds.serenity.common.annotations.InjectionConstants import us.nineworlds.serenity.common.rest.SerenityClient import us.nineworlds.serenity.common.rest.SerenityUser import us.nineworlds.serenity.core.logger.Logger import us.nineworlds.serenity.events.users.AllUsersEvent import us.nineworlds.serenity.events.users.AuthenticatedUserEvent import us.nineworlds.serenity.jobs.AuthenticateUserJob import us.nineworlds.serenity.jobs.RetrieveAllUsersJob import us.nineworlds.serenity.ui.activity.login.LoginUserContract.LoginUserView import javax.inject.Inject @InjectViewState @StateStrategyType(SkipStrategy::class) class LoginUserPresenter : MvpPresenter<LoginUserView>(), LoginUserContract.LoginUserPresnter { @Inject lateinit var logger: Logger @Inject lateinit var client: SerenityClient var eventBus = EventBus.getDefault() @Inject lateinit var jobManager: JobManager lateinit var server: Server init { Toothpick.inject(this, Toothpick.openScope(InjectionConstants.APPLICATION_SCOPE)) } override fun attachView(view: LoginUserView?) { super.attachView(view) eventBus.register(this) } override fun detachView(view: LoginUserView?) { super.detachView(view) eventBus.unregister(this) } override fun initPresenter(server: Server) { this.server = server if (server.port != null) { client.updateBaseUrl("http://${server.ipAddress}:${server.port}/") } else { client.updateBaseUrl("http://${server.ipAddress}:8096/") } } override fun retrieveAllUsers() { jobManager.addJobInBackground(RetrieveAllUsersJob()) } override fun loadUser(user: SerenityUser) { jobManager.addJobInBackground(AuthenticateUserJob(user)) } @Subscribe(threadMode = MAIN) fun processAllUsersEvent(allUsersEvent: AllUsersEvent) { viewState.displayUsers(allUsersEvent.users) } @Subscribe(threadMode = MAIN) fun showUsersStartScreen(authenticatUserEvent: AuthenticatedUserEvent) { viewState.launchNextScreen() } }
mit
30a0f6c34166bd26eac2e7e1b73a8c0b
29.012195
95
0.793089
4.353982
false
false
false
false
dahlstrom-g/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ReturnSaver.kt
6
2919
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.util.Key import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunction import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class ReturnSaver(val function: KtNamedFunction) { companion object { private val RETURN_KEY = Key<Unit>("RETURN_KEY") } val isEmpty: Boolean init { var hasReturn = false val body = function.bodyExpression!! body.forEachDescendantOfType<KtReturnExpression> { if (it.getTargetFunction(it.analyze(BodyResolveMode.PARTIAL)) == function) { hasReturn = true it.putCopyableUserData(RETURN_KEY, Unit) } } isEmpty = !hasReturn } private fun clear() { val body = function.bodyExpression!! body.forEachDescendantOfType<KtReturnExpression> { it.putCopyableUserData(RETURN_KEY, null) } } fun restore(lambda: KtLambdaExpression, label: Name) { clear() val factory = KtPsiFactory(lambda) val lambdaBody = lambda.bodyExpression!! val returnToReplace = lambda.collectDescendantsOfType<KtReturnExpression>() { it.getCopyableUserData(RETURN_KEY) != null } for (returnExpression in returnToReplace) { val value = returnExpression.returnedExpression val replaceWith = if (value != null && returnExpression.isValueOfBlock(lambdaBody)) { value } else if (value != null) { factory.createExpressionByPattern("return@$0 $1", label, value) } else { factory.createExpressionByPattern("return@$0", label) } returnExpression.replace(replaceWith) } } private fun KtExpression.isValueOfBlock(inBlock: KtBlockExpression): Boolean = when (val parent = parent) { inBlock -> { this == inBlock.statements.last() } is KtBlockExpression -> { isValueOfBlock(parent) && parent.isValueOfBlock(inBlock) } is KtContainerNode -> { val owner = parent.parent if (owner is KtIfExpression) { (this == owner.then || this == owner.`else`) && owner.isValueOfBlock(inBlock) } else false } is KtWhenEntry -> { this == parent.expression && (parent.parent as KtWhenExpression).isValueOfBlock(inBlock) } else -> false } }
apache-2.0
48ffcefe4add01d6267988bd69a859e6
33.352941
158
0.645084
4.981229
false
false
false
false
jaredsburrows/android-gif-example
app/src/main/java/com/burrowsapps/gif/search/data/source/network/GifDto.kt
1
301
package com.burrowsapps.gif.search.data.source.network import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) internal data class GifDto( @field:Json(name = "url") val url: String = "", @field:Json(name = "preview") val preview: String = "", )
apache-2.0
870d4eddf934b8898116be176bb142dd
24.083333
54
0.727575
3.344444
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/eventLog/FeatureUsageData.kt
1
6391
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.eventLog import com.intellij.internal.statistic.service.fus.collectors.FUSUsageContext import com.intellij.internal.statistic.utils.PluginInfo import com.intellij.internal.statistic.utils.getPluginType import com.intellij.internal.statistic.utils.getProjectId import com.intellij.lang.Language import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.Version import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.wm.impl.content.ToolWindowContentUi import com.intellij.psi.PsiFile import com.intellij.util.containers.ContainerUtil import java.awt.event.KeyEvent import java.awt.event.MouseEvent import java.util.* /** * <p>FeatureUsageData represents additional data for reported event.</p> * * <h3>Example</h3> * * <p>My usage collector collects actions invocations. <i>"my.foo.action"</i> could be invoked from one of the following contexts: * "main.menu", "context.menu", "my.dialog", "all-actions-run".</p> * * <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar")}, I'll know how many times the action "bar" was invoked (e.g. 239)</p> * * <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar", new FeatureUsageData().addPlace(place))}, I'll get the same * total count of action invocations (239), but I'll also know that the action was called 3 times from "main.menu", 235 times from "my.dialog" and only once from "context.menu". * <br/> * </p> */ class FeatureUsageData { private var data: MutableMap<String, Any> = ContainerUtil.newHashMap<String, Any>() fun addFeatureContext(context: FUSUsageContext?): FeatureUsageData { if (context != null) { data.putAll(context.data) } return this } fun addProject(project: Project?): FeatureUsageData { if (project != null) { data["project"] = getProjectId(project) } return this } fun addVersionByString(version: String?): FeatureUsageData { if (version == null) { data["version"] = "unknown" } else { addVersion(Version.parseVersion(version)) } return this } fun addVersion(version: Version?): FeatureUsageData { data["version"] = if (version != null) "${version.major}.${version.minor}" else "unknown.format" return this } fun addOS(): FeatureUsageData { data["os"] = getOS() return this } private fun getOS(): String { if (SystemInfo.isWindows) return "Windows" if (SystemInfo.isMac) return "Mac" return if (SystemInfo.isLinux) "Linux" else "Other" } fun addPluginInfo(info: PluginInfo): FeatureUsageData { data["plugin_type"] = info.type.name if (info.type.isSafeToReport() && info.id != null && StringUtil.isNotEmpty(info.id)) { data["plugin"] = info.id } return this } fun addLanguage(language: Language): FeatureUsageData { val type = getPluginType(language.javaClass) if (type.isSafeToReport()) { data["lang"] = language.id } return this } fun addCurrentFile(language: Language): FeatureUsageData { val type = getPluginType(language.javaClass) if (type.isSafeToReport()) { data["current_file"] = language.id } return this } fun addInputEvent(event: AnActionEvent): FeatureUsageData { val inputEvent = ShortcutDataProvider.getActionEventText(event) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addInputEvent(event: KeyEvent): FeatureUsageData { val inputEvent = ShortcutDataProvider.getKeyEventText(event) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addInputEvent(event: MouseEvent): FeatureUsageData { val inputEvent = ShortcutDataProvider.getMouseEventText(event) if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) { data["input_event"] = inputEvent } return this } fun addPlace(place: String?): FeatureUsageData { if (place == null) return this var reported = ActionPlaces.UNKNOWN if (isCommonPlace(place)) { reported = place } else if (ActionPlaces.isPopupPlace(place)) { reported = ActionPlaces.POPUP } data["place"] = reported return this } private fun isCommonPlace(place: String): Boolean { return ActionPlaces.isCommonPlace(place) || ToolWindowContentUi.POPUP_PLACE == place } fun addData(key: String, value: Boolean): FeatureUsageData { return addDataInternal(key, value) } fun addData(key: String, value: Int): FeatureUsageData { return addDataInternal(key, value) } fun addData(key: String, value: Long): FeatureUsageData { return addDataInternal(key, value) } fun addData(key: String, value: String): FeatureUsageData { return addDataInternal(key, value) } private fun addDataInternal(key: String, value: Any): FeatureUsageData { data[key] = value return this } fun build(): Map<String, Any> { if (data.isEmpty()) { return Collections.emptyMap() } return data } fun merge(next: FeatureUsageData, prefix: String): FeatureUsageData { for ((key, value) in next.build()) { val newKey = if (key.startsWith("data_")) "$prefix$key" else key addDataInternal(newKey, value) } return this } fun copy(): FeatureUsageData { val result = FeatureUsageData() for ((key, value) in data) { result.addDataInternal(key, value) } return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as FeatureUsageData if (data != other.data) return false return true } override fun hashCode(): Int { return data.hashCode() } } fun newData(project: Project?, context: FUSUsageContext?): Map<String, Any> { if (project == null && context == null) return Collections.emptyMap() return FeatureUsageData().addProject(project).addFeatureContext(context).build() }
apache-2.0
2553da2f088ee70c746e98f3b93baae1
29.438095
177
0.697387
4.1581
false
false
false
false
paplorinc/intellij-community
platform/platform-impl/src/com/intellij/ide/actions/SaveAllAction.kt
2
1588
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.ide.SaveAndSyncHandler import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ex.EditorSettingsExternalizable import com.intellij.openapi.editor.impl.TrailingSpacesStripper import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.project.DumbAware // class is "open" due to backward compatibility - do not extend it. open class SaveAllAction : AnAction(), DumbAware { override fun actionPerformed(e: AnActionEvent) { CommonDataKeys.EDITOR.getData(e.dataContext)?.let(::stripSpacesFromCaretLines) val project = CommonDataKeys.PROJECT.getData(e.dataContext) FileDocumentManager.getInstance().saveAllDocuments() (SaveAndSyncHandler.getInstance()).scheduleSave(SaveAndSyncHandler.SaveTask(onlyProject = project, forceSavingAllSettings = true, saveDocuments = false), forceExecuteImmediately = true) } } private fun stripSpacesFromCaretLines(editor: Editor) { val document = editor.document val options = TrailingSpacesStripper.getOptions(editor.document) if (options != null) { if (options.isStripTrailingSpaces && !options.isKeepTrailingSpacesOnCaretLine) { TrailingSpacesStripper.strip(document, options.isChangedLinesOnly, false) } } }
apache-2.0
ca9891df86923a0a1b422446e751da02
47.121212
189
0.808564
4.550143
false
false
false
false
google/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/firstStep/ProjectTemplateSettingComponent.kt
2
5154
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard.wizard.ui.firstStep import com.intellij.ui.ScrollPaneFactory import com.intellij.ui.SimpleTextAttributes import com.intellij.util.ui.JBUI import org.jetbrains.kotlin.idea.KotlinIcons import org.jetbrains.kotlin.tools.projectWizard.core.Context import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.DropDownSettingType import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.reference import org.jetbrains.kotlin.tools.projectWizard.plugins.projectTemplates.ProjectTemplatesPlugin import org.jetbrains.kotlin.tools.projectWizard.plugins.projectTemplates.applyProjectTemplate import org.jetbrains.kotlin.tools.projectWizard.projectTemplates.* import org.jetbrains.kotlin.tools.projectWizard.wizard.OnUserSettingChangeStatisticsLogger import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.* import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.SettingComponent import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.setting.ValidationIndicator import java.awt.Dimension import javax.swing.Icon import javax.swing.JComponent class ProjectTemplateSettingComponent( context: Context ) : SettingComponent<ProjectTemplate, DropDownSettingType<ProjectTemplate>>( ProjectTemplatesPlugin.template.reference, context ) { override val validationIndicator: ValidationIndicator? get() = null private val templateDescriptionComponent = TemplateDescriptionComponent().asSubComponent() private val templateGroups = setting.type.values .groupBy { it.projectKind } .map { (group, templates) -> ListWithSeparators.ListGroup(group.text, templates) } private val list = ListWithSeparators( templateGroups, render = { value -> icon = value.icon append(value.title) value.projectKind.message?.let { message -> append(" ") append(message, SimpleTextAttributes.GRAYED_ATTRIBUTES) } }, onValueSelected = { newValue -> newValue?.let { OnUserSettingChangeStatisticsLogger.logSettingValueChangedByUser( context.contextComponents.get(), ProjectTemplatesPlugin.template.path, it ) } value = newValue } ) override val alignment: TitleComponentAlignment get() = TitleComponentAlignment.AlignFormTopWithPadding(4) private val scrollPane = ScrollPaneFactory.createScrollPane(list) override val component: JComponent = borderPanel { addToCenter(borderPanel { addToCenter(scrollPane) }.addBorder(JBUI.Borders.empty(0,/*left*/ 3, 0, /*right*/ 3))) addToBottom(templateDescriptionComponent.component.addBorder(JBUI.Borders.empty(/*top*/8,/*left*/ 3, 0, 0))) } private fun applySelectedTemplate() = modify { value?.let(::applyProjectTemplate) } override fun onValueUpdated(reference: SettingReference<*, *>?) { super.onValueUpdated(reference) if (reference == ProjectTemplatesPlugin.template.reference) { applySelectedTemplate() updateHint() } } override fun onInit() { super.onInit() if (setting.type.values.isNotEmpty()) { list.selectedIndex = 0 value = setting.type.values.firstOrNull() applySelectedTemplate() updateHint() } } private fun updateHint() { value?.let { template -> list.setSelectedValue(template, true) templateDescriptionComponent.setTemplate(template) } } } private val ProjectTemplate.icon: Icon? get() = when (this) { ConsoleApplicationProjectTemplateWithSample -> KotlinIcons.Wizard.CONSOLE MultiplatformLibraryProjectTemplate -> KotlinIcons.Wizard.MULTIPLATFORM_LIBRARY FullStackWebApplicationProjectTemplate -> KotlinIcons.Wizard.WEB NativeApplicationProjectTemplate -> KotlinIcons.Wizard.NATIVE FrontendApplicationProjectTemplate -> KotlinIcons.Wizard.JS ReactApplicationProjectTemplate -> KotlinIcons.Wizard.REACT_JS NodeJsApplicationProjectTemplate -> KotlinIcons.Wizard.NODE_JS ComposeDesktopApplicationProjectTemplate -> KotlinIcons.Wizard.COMPOSE ComposeMultiplatformApplicationProjectTemplate -> KotlinIcons.Wizard.COMPOSE ComposeWebApplicationProjectTemplate -> KotlinIcons.Wizard.COMPOSE else -> null } class TemplateDescriptionComponent : Component() { private val descriptionLabel = CommentLabel().apply { preferredSize = Dimension(preferredSize.width, 45) } fun setTemplate(template: ProjectTemplate) { descriptionLabel.text = template.description.asHtml() } override val component: JComponent = descriptionLabel }
apache-2.0
763498f2a5e91f828a676ea51fc8b000
40.24
158
0.717501
5.179899
false
false
false
false
google/intellij-community
platform/testFramework/src/com/intellij/testFramework/PsiTestUtil.kt
3
1794
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.testFramework import com.intellij.injected.editor.DocumentWindow import com.intellij.lang.injection.InjectedLanguageManager import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiReference import com.intellij.refactoring.suggested.startOffset import com.intellij.util.castSafelyTo import com.intellij.util.text.allOccurrencesOf @JvmOverloads fun PsiFile.findReferenceByText(str: String, refOffset: Int = str.length / 2): PsiReference = findAllReferencesByText(str, refOffset).firstOrNull() ?: throw AssertionError("can't find reference for '$str'") @JvmOverloads fun PsiFile.findAllReferencesByText(str: String, refOffset: Int = str.length / 2): Sequence<PsiReference> { var offset = refOffset if (offset < 0) { offset += str.length } return this.text.allOccurrencesOf(str).map { index -> val pos = index + offset val element = findElementAt(pos) ?: throw AssertionError("can't find element for '$str' at $pos") element.findReferenceAt(pos - element.startOffset) ?: findInInjected(this, pos) ?: throw AssertionError("can't find reference for '$str' at $pos") } } private fun findInInjected(psiFile: PsiFile, pos: Int): PsiReference? { val injected = InjectedLanguageManager.getInstance(psiFile.project).findInjectedElementAt(psiFile, pos) ?: return null val documentWindow = PsiDocumentManager.getInstance(psiFile.project).getDocument(injected.containingFile).castSafelyTo<DocumentWindow>() ?: return null val hostToInjected = documentWindow.hostToInjected(pos) return injected.findReferenceAt(hostToInjected - injected.startOffset) }
apache-2.0
714654524d046627ac0e4d0fd19780cb
46.236842
138
0.772575
4.397059
false
false
false
false
avram/zandy
src/main/java/com/gimranov/zandy/app/DrawerNavigationActivity.kt
1
4681
package com.gimranov.zandy.app import android.content.Intent import android.os.Bundle import androidx.core.view.GravityCompat import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import android.view.Menu import android.view.MenuItem import com.gimranov.zandy.app.data.Database import com.gimranov.zandy.app.data.Item import com.gimranov.zandy.app.data.ItemCollection import kotlinx.android.synthetic.main.activity_drawer_navigation.* import kotlinx.android.synthetic.main.app_bar_drawer_navigation.* import kotlinx.android.synthetic.main.content_drawer_navigation.* class DrawerNavigationActivity : AppCompatActivity() { private val collectionKey = "com.gimranov.zandy.app.collectionKey" private val database = Database(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_drawer_navigation) setSupportActionBar(toolbar) } override fun onResume() { super.onResume() val itemListingRule = intent?.extras?.getString(collectionKey)?.let { Children(ItemCollection.load(it, database), true) } ?: AllItems title = when (itemListingRule::class) { Children::class -> { (itemListingRule as Children).parent?.title ?: this.getString(R.string.all_items) } else -> { this.getString(R.string.all_items) } } val itemAdapter = ItemAdapter(database, itemListingRule) { item: Item, itemAction: ItemAction -> run { when (itemAction) { ItemAction.EDIT -> { val i = Intent(baseContext, ItemDataActivity::class.java) i.putExtra("com.gimranov.zandy.app.itemKey", item.key) i.putExtra("com.gimranov.zandy.app.itemDbId", item.dbId) startActivity(i) } ItemAction.ORGANIZE -> { val i = Intent(baseContext, CollectionMembershipActivity::class.java) i.putExtra("com.gimranov.zandy.app.itemKey", item.key) startActivity(i) } ItemAction.VIEW -> TODO() } } } val collectionAdapter = CollectionAdapter(database, itemListingRule) { collection: ItemCollection, itemAction: ItemAction -> run { when (itemAction) { ItemAction.VIEW -> { val i = Intent(baseContext, DrawerNavigationActivity::class.java) i.putExtra(collectionKey, collection.key) startActivity(i) } ItemAction.EDIT -> TODO() ItemAction.ORGANIZE -> TODO() } } } navigation_drawer_sidebar_recycler.adapter = collectionAdapter navigation_drawer_sidebar_recycler.setHasFixedSize(true) navigation_drawer_sidebar_recycler.layoutManager = LinearLayoutManager(this) navigation_drawer_content_recycler.adapter = itemAdapter navigation_drawer_content_recycler.setHasFixedSize(true) navigation_drawer_content_recycler.layoutManager = LinearLayoutManager(this) val toggle = ActionBarDrawerToggle( this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawer_layout.addDrawerListener(toggle) toggle.syncState() } override fun onBackPressed() { if (drawer_layout.isDrawerOpen(GravityCompat.START)) { drawer_layout.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.drawer_navigation, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> { startActivity(Intent(baseContext, SettingsActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } } }
agpl-3.0
c22313e586e4a7a01e44de3a1ca41a1b
38.336134
132
0.621021
5.022532
false
false
false
false
vhromada/Catalog
core/src/test/kotlin/com/github/vhromada/catalog/utils/EpisodeUtils.kt
1
13887
package com.github.vhromada.catalog.utils import com.github.vhromada.catalog.domain.io.EpisodeStatistics import com.github.vhromada.catalog.entity.ChangeEpisodeRequest import com.github.vhromada.catalog.entity.Episode import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.SoftAssertions.assertSoftly import javax.persistence.EntityManager /** * Updates episode fields. * * @return updated episode */ fun com.github.vhromada.catalog.domain.Episode.updated(): com.github.vhromada.catalog.domain.Episode { number = 2 name = "Name" length = 5 note = "Note" return this } /** * Updates episode fields. * * @return updated episode */ fun Episode.updated(): Episode { return copy( number = 2, name = "Name", length = 5, note = "Note" ) } /** * A class represents utility class for episodes. * * @author Vladimir Hromada */ object EpisodeUtils { /** * Count of episodes */ const val EPISODES_COUNT = 27 /** * Count of episodes in season */ const val EPISODES_PER_SEASON_COUNT = 3 /** * Count of episodes in show */ const val EPISODES_PER_SHOW_COUNT = 9 /** * Multipliers for length */ private val LENGTH_MULTIPLIERS = intArrayOf(1, 10, 100) /** * Returns episodes. * * @param show show ID * @param season season ID * @return episodes */ fun getDomainEpisodes(show: Int, season: Int): MutableList<com.github.vhromada.catalog.domain.Episode> { val episodes = mutableListOf<com.github.vhromada.catalog.domain.Episode>() for (i in 1..EPISODES_PER_SEASON_COUNT) { episodes.add(getDomainEpisode(showIndex = show, seasonIndex = season, episodeIndex = i)) } return episodes } /** * Returns episodes. * * @param show show ID * @param season season ID * @return episodes */ fun getEpisodes(show: Int, season: Int): List<Episode> { val episodes = mutableListOf<Episode>() for (i in 1..EPISODES_PER_SEASON_COUNT) { episodes.add(getEpisode(showIndex = show, seasonIndex = season, episodeIndex = i)) } return episodes } /** * Returns episode for indexes. * * @param showIndex show index * @param seasonIndex season index * @param episodeIndex episode index * @return episode for indexes */ private fun getDomainEpisode(showIndex: Int, seasonIndex: Int, episodeIndex: Int): com.github.vhromada.catalog.domain.Episode { return com.github.vhromada.catalog.domain.Episode( id = (showIndex - 1) * EPISODES_PER_SHOW_COUNT + (seasonIndex - 1) * EPISODES_PER_SEASON_COUNT + episodeIndex, uuid = getUuid(index = (showIndex - 1) * EPISODES_PER_SHOW_COUNT + (seasonIndex - 1) * EPISODES_PER_SEASON_COUNT + episodeIndex), number = episodeIndex, name = "Show $showIndex Season $seasonIndex Episode $episodeIndex", length = episodeIndex * LENGTH_MULTIPLIERS[seasonIndex - 1], note = if (episodeIndex != 3) "Show $showIndex Season $seasonIndex Episode $episodeIndex note" else null ).fillAudit(audit = AuditUtils.getAudit()) } /** * Returns UUID for index. * * @param index index * @return UUID for index */ private fun getUuid(index: Int): String { return when (index) { 1 -> "29f94c0f-aa0e-48b2-a74d-68991778871b" 2 -> "fa623148-896d-40be-9702-9cb2d30c4f3e" 3 -> "b58bb43c-b391-4de2-8972-08e13b8ab059" 4 -> "71a04e1f-3218-4797-b9c0-de68f16262bf" 5 -> "b4fad1a0-3f67-435a-8dd9-e27ae090dd17" 6 -> "806f59b5-5e3d-478f-aeb8-fc2c7158801f" 7 -> "77661951-c3ec-431f-a3a4-b7db93009504" 8 -> "2aea5877-cee1-42d2-a421-f048409baaf6" 9 -> "ccff3e04-25d2-4141-8a66-b2fd0c8938ec" 10 -> "724861fb-43ac-450e-9ca4-f6454d16bd5a" 11 -> "40fdfeb7-04df-4a02-a23a-4a5fb5927671" 12 -> "ee456688-196e-4389-9e54-3aa31e3d8e8e" 13 -> "5c272380-3c38-43f1-9726-226a9f182942" 14 -> "4269d91c-4d36-4fd8-9de3-1134f09f6e4e" 15 -> "3b35f6e3-e8e0-4677-a79a-c3b89f43345a" 16 -> "6b602097-5072-422c-9691-93b074fc6cee" 17 -> "c77e013c-bea9-4679-8e4e-df9aa622caa1" 18 -> "9b9d0874-a483-4677-b90f-7b604c07926b" 19 -> "057f61ef-0e20-497e-a0c0-4fc964a2ca0c" 20 -> "8be0b3cd-30cf-4d47-8d67-c39f0bf6eb04" 21 -> "a8a29438-e615-4721-8857-f92aad24b3f5" 22 -> "abe105ee-6d9d-4c1e-a900-087555da3fb5" 23 -> "2333c9e3-c9dc-4e40-8a42-4a6a7a079078" 24 -> "b7111ede-c022-4967-bd2a-55d9d73d4cf7" 25 -> "418234ed-59e8-4277-90ea-0e4ba87685e9" 26 -> "05fe7e5f-0b5b-4cd3-91b9-d3b1d5ec203d" 27 -> "54e645db-697c-45b1-8335-e4d65a0fd547" else -> throw IllegalArgumentException("Bad index") } } /** * Returns episode. * * @param entityManager entity manager * @param id episode ID * @return episode */ fun getDomainEpisode(entityManager: EntityManager, id: Int): com.github.vhromada.catalog.domain.Episode? { return entityManager.find(com.github.vhromada.catalog.domain.Episode::class.java, id) } /** * Returns episode for index. * * @param index episode index * @return episode for index */ fun getEpisode(index: Int): Episode { val showNumber = (index - 1) / EPISODES_PER_SHOW_COUNT + 1 val seasonNumber = (index - 1) % EPISODES_PER_SHOW_COUNT / EPISODES_PER_SEASON_COUNT + 1 val episodeNumber = (index - 1) % EPISODES_PER_SEASON_COUNT + 1 return getEpisode(showIndex = showNumber, seasonIndex = seasonNumber, episodeIndex = episodeNumber) } /** * Returns episode for indexes. * * @param showIndex show index * @param seasonIndex season index * @param episodeIndex episode index * @return episode for indexes */ private fun getEpisode(showIndex: Int, seasonIndex: Int, episodeIndex: Int): Episode { return Episode( uuid = getUuid(index = (showIndex - 1) * EPISODES_PER_SHOW_COUNT + (seasonIndex - 1) * EPISODES_PER_SEASON_COUNT + episodeIndex), number = episodeIndex, name = "Show $showIndex Season $seasonIndex Episode $episodeIndex", length = episodeIndex * LENGTH_MULTIPLIERS[seasonIndex - 1], note = if (episodeIndex != 3) "Show $showIndex Season $seasonIndex Episode $episodeIndex note" else null, ) } /** * Returns statistics for episodes. * * @return statistics for episodes */ fun getStatistics(): EpisodeStatistics { return EpisodeStatistics(count = EPISODES_COUNT.toLong(), length = 1998L) } /** * Returns count of episodes. * * @param entityManager entity manager * @return count of episodes */ fun getEpisodesCount(entityManager: EntityManager): Int { return entityManager.createQuery("SELECT COUNT(e.id) FROM Episode e", java.lang.Long::class.java).singleResult.toInt() } /** * Returns episode. * * @param id ID * @return episode */ fun newDomainEpisode(id: Int?): com.github.vhromada.catalog.domain.Episode { return com.github.vhromada.catalog.domain.Episode( id = id, uuid = TestConstants.UUID, number = 0, name = "", length = 0, note = null ).updated() } /** * Returns episode. * * @return episode */ fun newEpisode(): Episode { return Episode( uuid = TestConstants.UUID, number = 0, name = "", length = 0, note = null ).updated() } /** * Returns request for changing episode. * * @return request for changing episode */ fun newRequest(): ChangeEpisodeRequest { return ChangeEpisodeRequest( name = "Name", number = 2, length = 5, note = "Note" ) } /** * Asserts list of episodes deep equals. * * @param expected expected list of episodes * @param actual actual list of episodes */ fun assertDomainEpisodesDeepEquals(expected: List<com.github.vhromada.catalog.domain.Episode>, actual: List<com.github.vhromada.catalog.domain.Episode>) { assertThat(expected.size).isEqualTo(actual.size) if (expected.isNotEmpty()) { for (i in expected.indices) { assertEpisodeDeepEquals(expected = expected[i], actual = actual[i]) } } } /** * Asserts episode deep equals. * * @param expected expected episode * @param actual actual episode */ fun assertEpisodeDeepEquals(expected: com.github.vhromada.catalog.domain.Episode?, actual: com.github.vhromada.catalog.domain.Episode?) { if (expected == null) { assertThat(actual).isNull() } else { assertThat(actual).isNotNull assertSoftly { it.assertThat(actual!!.id).isEqualTo(expected.id) it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.number).isEqualTo(expected.number) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.length).isEqualTo(expected.length) it.assertThat(actual.note).isEqualTo(expected.note) } AuditUtils.assertAuditDeepEquals(expected = expected, actual = actual!!) if (expected.season != null) { assertThat(actual.season).isNotNull assertThat(actual.season!!.episodes).hasSameSizeAs(expected.season!!.episodes) SeasonUtils.assertSeasonDeepEquals(expected = expected.season!!, actual = actual.season!!, checkEpisodes = false) } } } /** * Asserts list of episodes deep equals. * * @param expected expected list of episodes * @param actual actual list of episodes */ fun assertEpisodesDeepEquals(expected: List<com.github.vhromada.catalog.domain.Episode>, actual: List<Episode>) { assertThat(expected.size).isEqualTo(actual.size) if (expected.isNotEmpty()) { for (i in expected.indices) { assertEpisodeDeepEquals(expected = expected[i], actual = actual[i]) } } } /** * Asserts episode deep equals. * * @param expected expected episode * @param actual actual episode */ fun assertEpisodeDeepEquals(expected: com.github.vhromada.catalog.domain.Episode, actual: Episode) { assertSoftly { it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.number).isEqualTo(expected.number) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.length).isEqualTo(expected.length) it.assertThat(actual.note).isEqualTo(expected.note) } } /** * Asserts list of episodes deep equals. * * @param expected expected list of episodes * @param actual actual list of episodes */ fun assertEpisodeListDeepEquals(expected: List<Episode>, actual: List<Episode>) { assertThat(expected.size).isEqualTo(actual.size) if (expected.isNotEmpty()) { for (i in expected.indices) { assertEpisodeDeepEquals(expected = expected[i], actual = actual[i]) } } } /** * Asserts episode deep equals. * * @param expected expected episode * @param actual actual episode */ fun assertEpisodeDeepEquals(expected: Episode, actual: Episode) { assertSoftly { it.assertThat(actual.uuid).isEqualTo(expected.uuid) it.assertThat(actual.number).isEqualTo(expected.number) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.length).isEqualTo(expected.length) it.assertThat(actual.note).isEqualTo(expected.note) } } /** * Asserts request and episode deep equals. * * @param expected expected request for changing episode * @param actual actual episode * @param uuid UUID */ fun assertRequestDeepEquals(expected: ChangeEpisodeRequest, actual: com.github.vhromada.catalog.domain.Episode, uuid: String) { assertSoftly { it.assertThat(actual.id).isNull() it.assertThat(actual.uuid).isEqualTo(uuid) it.assertThat(actual.number).isEqualTo(expected.number) it.assertThat(actual.name).isEqualTo(expected.name) it.assertThat(actual.length).isEqualTo(expected.length) it.assertThat(actual.note).isEqualTo(expected.note) it.assertThat(actual.season).isNull() it.assertThat(actual.createdUser).isNull() it.assertThat(actual.createdTime).isNull() it.assertThat(actual.updatedUser).isNull() it.assertThat(actual.updatedTime).isNull() } } /** * Asserts statistics for episodes deep equals. * * @param expected expected statistics for episodes * @param actual actual statistics for episodes */ fun assertStatisticsDeepEquals(expected: EpisodeStatistics, actual: EpisodeStatistics) { assertSoftly { it.assertThat(actual.count).isEqualTo(expected.count) it.assertThat(actual.length).isEqualTo(expected.length) } } }
mit
a88ad7aa6db1caec7dc4645414329b60
33.459057
158
0.613307
3.870401
false
false
false
false
JetBrains/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/checkin/TodoCheckinHandler.kt
1
9519
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.checkin import com.intellij.CommonBundle.getCancelButtonText import com.intellij.ide.todo.* import com.intellij.openapi.actionSystem.ActionPlaces import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.runInEdt import com.intellij.openapi.components.service import com.intellij.openapi.progress.ProgressSink import com.intellij.openapi.progress.asContextElement import com.intellij.openapi.progress.coroutineToIndicator import com.intellij.openapi.progress.progressSink import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.ui.JBPopupMenu import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNo import com.intellij.openapi.ui.MessageDialogBuilder.Companion.yesNoCancel import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.Messages.YesNoCancelResult import com.intellij.openapi.util.NlsContexts.* import com.intellij.openapi.vcs.CheckinProjectPanel import com.intellij.openapi.vcs.VcsBundle.message import com.intellij.openapi.vcs.VcsConfiguration import com.intellij.openapi.vcs.changes.Change import com.intellij.openapi.vcs.changes.CommitContext import com.intellij.openapi.vcs.changes.ui.BooleanCommitOption import com.intellij.openapi.vcs.checkin.TodoCheckinHandler.Companion.showDialog import com.intellij.openapi.vcs.ui.RefreshableOnComponent import com.intellij.openapi.wm.ToolWindowId.TODO_VIEW import com.intellij.openapi.wm.ToolWindowManager import com.intellij.psi.search.TodoItem import com.intellij.ui.components.labels.LinkLabel import com.intellij.ui.components.labels.LinkListener import com.intellij.util.text.DateFormatUtil.formatDateTime import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.UIUtil.getWarningIcon import com.intellij.vcs.commit.isPostCommitCheck import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import javax.swing.JComponent import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlin.coroutines.coroutineContext class TodoCheckinHandlerFactory : CheckinHandlerFactory() { override fun createHandler(panel: CheckinProjectPanel, commitContext: CommitContext): CheckinHandler { return TodoCheckinHandler(panel.project) } } class TodoCommitProblem(val worker: TodoCheckinHandlerWorker, val isPostCommit: Boolean) : CommitProblemWithDetails { override val text: String get() = message("label.todo.items.found", worker.inOneList().size) override fun showDetails(project: Project) { TodoCheckinHandler.showTodoItems(project, worker.changes, worker.inOneList(), isPostCommit) } override fun showModalSolution(project: Project, commitInfo: CommitInfo): CheckinHandler.ReturnResult { return showDialog(project, worker, commitInfo.commitActionText) } override val showDetailsAction: String get() = message("todo.in.new.review.button") } class TodoCheckinHandler(private val project: Project) : CheckinHandler(), CommitCheck, DumbAware { private val settings: VcsConfiguration get() = VcsConfiguration.getInstance(project) private val todoSettings: TodoPanelSettings get() = settings.myTodoPanelSettings override fun getExecutionOrder(): CommitCheck.ExecutionOrder = CommitCheck.ExecutionOrder.POST_COMMIT override fun isEnabled(): Boolean = settings.CHECK_NEW_TODO override suspend fun runCheck(commitInfo: CommitInfo): TodoCommitProblem? { val sink = coroutineContext.progressSink sink?.text(message("progress.text.checking.for.todo")) val isPostCommit = commitInfo.isPostCommitCheck val todoFilter = settings.myTodoPanelSettings.todoFilterName?.let { TodoConfiguration.getInstance().getTodoFilter(it) } val changes = commitInfo.committedChanges val worker = TodoCheckinHandlerWorker(project, changes, todoFilter) withContext(Dispatchers.Default + textToDetailsSinkContext(sink)) { coroutineToIndicator { worker.execute() } } val noTodo = worker.inOneList().isEmpty() val noSkipped = worker.skipped.isEmpty() if (noTodo && noSkipped) return null return TodoCommitProblem(worker, isPostCommit) } override fun getBeforeCheckinConfigurationPanel(): RefreshableOnComponent = TodoCommitOption().withCheckinHandler(this) private inner class TodoCommitOption : BooleanCommitOption(project, "", false, settings::CHECK_NEW_TODO) { override fun getComponent(): JComponent { val filter = TodoConfiguration.getInstance().getTodoFilter(todoSettings.todoFilterName) setFilterText(filter?.name) val showFiltersPopup = LinkListener<Any> { sourceLink, _ -> val group = SetTodoFilterAction.createPopupActionGroup(project, todoSettings, true) { setFilter(it) } JBPopupMenu.showBelow(sourceLink, ActionPlaces.TODO_VIEW_TOOLBAR, group) } val configureFilterLink = LinkLabel(message("settings.filter.configure.link"), null, showFiltersPopup) return simplePanel(4, 0).addToLeft(checkBox).addToCenter(configureFilterLink) } private fun setFilter(filter: TodoFilter?) { todoSettings.todoFilterName = filter?.name setFilterText(filter?.name) } private fun setFilterText(filterName: String?) { if (filterName != null) { val text = message("checkin.filter.filter.name", filterName) checkBox.text = message("before.checkin.new.todo.check", text) } else { checkBox.text = message("before.checkin.new.todo.check.no.filter") } } } companion object { internal fun showDialog(project: Project, worker: TodoCheckinHandlerWorker, @Button commitActionText: String): ReturnResult { val noTodo = worker.addedOrEditedTodos.isEmpty() && worker.inChangedTodos.isEmpty() val noSkipped = worker.skipped.isEmpty() if (noTodo && noSkipped) return ReturnResult.COMMIT if (noTodo) { val commit = confirmCommitWithSkippedFiles(worker, commitActionText) if (commit) { return ReturnResult.COMMIT } else { return ReturnResult.CANCEL } } when (askReviewCommitCancel(worker, commitActionText)) { Messages.YES -> { showTodoItems(project, worker.changes, worker.inOneList(), isPostCommit = false) return ReturnResult.CLOSE_WINDOW } Messages.NO -> return ReturnResult.COMMIT else -> return ReturnResult.CANCEL } } internal fun showTodoItems(project: Project, changes: Collection<Change>, todoItems: Collection<TodoItem>, isPostCommit: Boolean) { val todoView = project.service<TodoView>() val content = todoView.addCustomTodoView( { tree, _ -> if (isPostCommit) { PostCommitChecksTodosTreeBuilder(tree, project, changes, todoItems) } else { CommitChecksTodosTreeBuilder(tree, project, changes, todoItems) } }, message("checkin.title.for.commit.0", formatDateTime(System.currentTimeMillis())), TodoPanelSettings(VcsConfiguration.getInstance(project).myTodoPanelSettings) ) if (content == null) return runInEdt(ModalityState.NON_MODAL) { if (project.isDisposed) return@runInEdt val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(TODO_VIEW) ?: return@runInEdt toolWindow.show { toolWindow.contentManager.setSelectedContent(content, true) } } } } } internal fun textToDetailsSinkContext(sink: ProgressSink?): CoroutineContext { if (sink == null) { return EmptyCoroutineContext } else { return TextToDetailsProgressSink(sink).asContextElement() } } internal class TextToDetailsProgressSink(private val original: ProgressSink) : ProgressSink { override fun update(text: @ProgressText String?, details: @ProgressDetails String?, fraction: Double?) { original.update( text = null, details = text, // incoming text will be shown as details in the original sink fraction = fraction, ) } } private fun confirmCommitWithSkippedFiles(worker: TodoCheckinHandlerWorker, @Button commitActionText: String) = yesNo(message("checkin.dialog.title.todo"), getDescription(worker)) .icon(getWarningIcon()) .yesText(commitActionText) .noText(getCancelButtonText()) .ask(worker.project) @YesNoCancelResult private fun askReviewCommitCancel(worker: TodoCheckinHandlerWorker, @Button commitActionText: String): Int = yesNoCancel(message("checkin.dialog.title.todo"), getDescription(worker)) .icon(getWarningIcon()) .yesText(message("todo.in.new.review.button")) .noText(commitActionText) .cancelText(getCancelButtonText()) .show(worker.project) @DialogMessage private fun getDescription(worker: TodoCheckinHandlerWorker): String { val added = worker.addedOrEditedTodos.size val changed = worker.inChangedTodos.size val skipped = worker.skipped.size return when { added == 0 && changed == 0 -> message("todo.handler.only.skipped", skipped) changed == 0 -> message("todo.handler.only.added", added, skipped) added == 0 -> message("todo.handler.only.in.changed", changed, skipped) else -> message("todo.handler.only.both", added, changed, skipped) } }
apache-2.0
fe7c877efa8b6baa4dca6694793677da
39.683761
135
0.747663
4.563279
false
false
false
false
Hexworks/snap
src/main/kotlin/org/codetome/snap/service/impl/SnapService.kt
1
1138
package org.codetome.snap.service.impl import com.vladsch.flexmark.parser.Parser import com.vladsch.flexmark.parser.ParserEmulationProfile import com.vladsch.flexmark.util.options.MutableDataSet import org.codetome.snap.adapter.parser.MarkdownParser import org.codetome.snap.model.rest.RestService import org.codetome.snap.service.RestServiceGenerator import java.io.File /** * Creates REST services based on a service description markdown file * (see sample_config.md for example) using <code>linkContent</code> as the * access linkContent. */ class SnapService(private val restServiceGenerator: RestServiceGenerator, private val markdownParser: MarkdownParser) { fun run(descriptor: File): RestService { val options = MutableDataSet() options.setFrom(ParserEmulationProfile.MARKDOWN) val parser: Parser = Parser.builder(options).build() val md = descriptor.readText() val document = parser.parse(md) val restService = markdownParser.parse(document).blockingGet() restServiceGenerator.generateServiceFrom(restService) return restService } }
agpl-3.0
b41f197fb4b3a65eb453185049de5b0e
38.275862
75
0.757469
4.445313
false
false
false
false
EddyArellanes/Kotlin
Hello-World-Scripts/Singleton.kt
1
700
/**/ object Validations{ /* fun password(psw:String):Boolean{ if(psw.length>0 && psw.length>10){ return true }else{ return false } } */ fun password(psw:String) =psw.isNotEmpty() && psw.length>10 fun isNumeric(dato:Any)= dato is Int } class UniversalClass{ companion object{ fun create():UniversalClass= UniversalClass() } } fun main(args:Array<String>){ println("Ingresa tu contraseña" ) val pass:String= readLine()!! //!! = No importa si es nulo println(Validations.password(pass)) val number:Int= readLine()?.toInt() ?:0 println(number) println(Validations.isNumeric(number)) val universe:UniversalClass= UniversalClass.create() }
mit
e8c0b6722875eeda6d35479bc0c1fb9a
19.90625
60
0.669528
2.936975
false
false
false
false
allotria/intellij-community
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XThreadsView.kt
4
3830
// 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.xdebugger.impl.frame import com.intellij.openapi.project.Project import com.intellij.ui.SimpleColoredComponent import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.frame.* import com.intellij.xdebugger.frame.presentation.XRegularValuePresentation import com.intellij.xdebugger.impl.XDebugSessionImpl import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import com.intellij.xdebugger.impl.ui.tree.XDebuggerTree import com.intellij.xdebugger.impl.ui.tree.XDebuggerTreePanel import com.intellij.xdebugger.impl.ui.tree.nodes.XValueContainerNode import javax.swing.JPanel class XThreadsView(val project: Project, session: XDebugSessionImpl) : XDebugView() { private val treePanel = XDebuggerTreePanel(project, session.debugProcess.editorsProvider, this, null, "", null) private fun getTree() = treePanel.tree fun getPanel(): JPanel = treePanel.mainPanel fun getDefaultFocusedComponent(): XDebuggerTree = treePanel.tree override fun clear() { DebuggerUIUtil.invokeLater { getTree().setRoot(object : XValueContainerNode<XValueContainer>(getTree(), null, true, object : XValueContainer() {}) {}, false) } } override fun processSessionEvent(event: XDebugView.SessionEvent, session: XDebugSession) { if (event == XDebugView.SessionEvent.BEFORE_RESUME) { return } val suspendContext = session.suspendContext if (suspendContext == null) { requestClear() return } if (event == XDebugView.SessionEvent.PAUSED) { // clear immediately cancelClear() clear() } DebuggerUIUtil.invokeLater { getTree().setRoot(XThreadsRootNode(getTree(), suspendContext), false) } } override fun dispose() { } class ThreadsContainer(val suspendContext: XSuspendContext) : XValueContainer() { override fun computeChildren(node: XCompositeNode) { suspendContext.computeExecutionStacks(object : XSuspendContext.XExecutionStackContainer { override fun errorOccurred(errorMessage: String) { } override fun addExecutionStack(executionStacks: MutableList<out XExecutionStack>, last: Boolean) { val children = XValueChildrenList() executionStacks.map { FramesContainer(it) }.forEach { children.add("", it) } node.addChildren(children, last) } }) } } class FramesContainer(private val executionStack: XExecutionStack) : XValue() { override fun computeChildren(node: XCompositeNode) { executionStack.computeStackFrames(0, object : XExecutionStack.XStackFrameContainer { override fun errorOccurred(errorMessage: String) { } override fun addStackFrames(stackFrames: MutableList<out XStackFrame>, last: Boolean) { val children = XValueChildrenList() stackFrames.forEach { children.add("", FrameValue(it)) } node.addChildren(children, last) } }) } override fun computePresentation(node: XValueNode, place: XValuePlace) { node.setPresentation(executionStack.icon, XRegularValuePresentation(executionStack.displayName, null, ""), true) } } class FrameValue(val frame : XStackFrame) : XValue() { override fun computePresentation(node: XValueNode, place: XValuePlace) { val component = SimpleColoredComponent() frame.customizePresentation(component) node.setPresentation(component.icon, XRegularValuePresentation(component.getCharSequence(false).toString(), null, ""), false) } } class XThreadsRootNode(tree: XDebuggerTree, suspendContext: XSuspendContext) : XValueContainerNode<ThreadsContainer>(tree, null, false, ThreadsContainer(suspendContext)) }
apache-2.0
99d04aa7b2fd3b4d706f7bfa5dbf62c0
38.484536
140
0.734726
4.722565
false
false
false
false
ursjoss/sipamato
core/core-logic/src/test/kotlin/ch/difty/scipamato/core/logic/parsing/AuthorParsingTest.kt
2
3971
@file:Suppress("SpellCheckingInspection") package ch.difty.scipamato.core.logic.parsing import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeInstanceOf import org.amshove.kluent.shouldBeNull import org.amshove.kluent.shouldContain import org.amshove.kluent.shouldContainAll import org.junit.jupiter.api.Test internal class PubmedAuthorParserTest { private lateinit var p: PubmedAuthorParser @Test fun withNoAuthor_firstAuthorIsNull() { p = PubmedAuthorParser("") p.firstAuthor.shouldBeNull() } @Test fun canReturnOriginalAuthorsString() { val authorsString = "Bond J." p = PubmedAuthorParser(authorsString) p.authorsString shouldBeEqualTo authorsString } private fun assertFirstAuthorOf(input: String, expected: String) { p = PubmedAuthorParser(input) p.firstAuthor shouldBeEqualTo expected } @Test fun canReturnFirstAuthor_withSingleAuthorOnly() { // proper format assertFirstAuthorOf("Bond J.", "Bond") // unclean format assertFirstAuthorOf("Bond J.", "Bond") assertFirstAuthorOf("Bond J", "Bond") assertFirstAuthorOf("Bond ", "Bond") assertFirstAuthorOf(" Bond ", "Bond") assertFirstAuthorOf(" Bond.", "Bond") } @Test fun canReturnFirstAuthor_withMultipleAuthors() { // proper format assertFirstAuthorOf( """Turner MC, Cohen A, Jerret M, Gapstur SM, Driver WR, Pope CA 3rd, Krewsky D |, Beckermann BS, Samet JM.""".trimMargin(), "Turner" ) } @Test fun canReturnFirstAuthor_withMultipleLastNames() { assertFirstAuthorOf("Lloyd Webber A.", "Lloyd Webber") assertFirstAuthorOf("Lloyd Webber A", "Lloyd Webber") assertFirstAuthorOf("Lloyd Webber Andrew", "Lloyd Webber") } @Test fun canParseNameWithCardinality() { p = PubmedAuthorParser("Ln FN 1st, Ln FN 2nd, Ln FN 3rd, Ln FN 4th, Ln FN 5th, Ln FN 100th, Ln FN.") p.firstAuthor shouldBeEqualTo "Ln" p.authors.map { it.lastName } shouldContain "Ln" p.authors.map { it.firstName } shouldContainAll listOf( "FN 1st", "FN 2nd", "FN 3rd", "FN 4th", "FN 5th", "FN 100th", "FN" ) } @Test fun canReturnFirstAuthor_evenWhenCardinalityStandsAfterFirstName() { assertFirstAuthorOf("Pope CA 3rd, Lloyd Webber A.", "Pope") } @Test fun canReturnFirstAuthor_evenWhenNameContainsJunior() { assertFirstAuthorOf("Cox LA Jr.", "Cox") } @Test fun canReturnFirstAuthor_letsNotBeFooledByInitialsLookingLikeJunior() { assertFirstAuthorOf("Cox JR.", "Cox") } @Test fun cannotProperlyReturnFirstAuthor_withInitialsAndCapitalJR() { // this is probably not a valid case, but let's state it explicitly here assertFirstAuthorOf("Cox LA JR.", "Cox LA") } @Test fun canReturnAuthors() { p = PubmedAuthorParser( "Turner MC, Cohen A, Jerret M, Gapstur SM, Driver WR, Krewsky D, Beckermann BS, Samet JM." ) p.authors.map { it.lastName } shouldContainAll listOf( "Turner", "Cohen", "Jerret", "Gapstur", "Driver", "Krewsky", "Beckermann", "Samet" ) p.authors.map { it.firstName } shouldContainAll listOf("MC", "A", "M", "SM", "WR", "D", "BS", "JM") } @Test fun canDoUmlaute() { p = PubmedAuthorParser("Flückiger P, Bäni HU.") p.authors.map { it.lastName } shouldContainAll listOf("Flückiger", "Bäni") p.authors.map { it.firstName } shouldContainAll listOf("P", "HU") } } internal class AuthorParserFactoryTest { @Test fun cratingParser_withNoSetting_usesDefaultAuthorParser() { val parser = AuthorParserFactory.create(AuthorParserStrategy.PUBMED).createParser("Turner MC.") parser shouldBeInstanceOf PubmedAuthorParser::class } }
gpl-3.0
c294fd2eabe8ed278227bd509734f201
32.058333
108
0.650366
3.785305
false
true
false
false
bmunzenb/feed-buddy
src/test/kotlin/com/munzenberger/feed/FeedTest.kt
1
789
package com.munzenberger.feed import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import java.time.Instant class FeedTest { @Test fun `it can parse a valid timestamp in ISO format`() { val timestamp = "2003-12-13T18:30:02Z" val instant = Instant.ofEpochSecond(1071340202) assertEquals(instant, timestamp.toInstant()) } @Test fun `it can parse timestamp in RFC format`() { val timestamp = "Thu, 23 Apr 2020 04:01:23 +0000" val instant = Instant.ofEpochSecond(1587614483) assertEquals(instant, timestamp.toInstant()) } @Test fun `it does not parse an invalid timestamp format`() { val timestamp = "" assertNull(timestamp.toInstant()) } }
apache-2.0
5df55c96caaf69e603451d75c9097471
21.542857
59
0.66033
4.06701
false
true
false
false
ursjoss/sipamato
common/common-wicket/src/main/kotlin/ch/difty/scipamato/common/web/AbstractPage.kt
1
6886
package ch.difty.scipamato.common.web import ch.difty.scipamato.common.DateTimeService import ch.difty.scipamato.common.config.ApplicationProperties import ch.difty.scipamato.common.web.component.SerializableSupplier import de.agilecoders.wicket.core.markup.html.bootstrap.button.BootstrapAjaxButton import de.agilecoders.wicket.core.markup.html.bootstrap.button.Buttons import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar import org.apache.wicket.ajax.AjaxRequestTarget import org.apache.wicket.authroles.authentication.AuthenticatedWebSession import org.apache.wicket.bean.validation.PropertyValidator import org.apache.wicket.devutils.debugbar.DebugBar import org.apache.wicket.markup.head.IHeaderResponse import org.apache.wicket.markup.head.MetaDataHeaderItem import org.apache.wicket.markup.head.PriorityHeaderItem import org.apache.wicket.markup.head.filter.HeaderResponseContainer import org.apache.wicket.markup.html.GenericWebPage import org.apache.wicket.markup.html.basic.Label import org.apache.wicket.markup.html.form.FormComponent import org.apache.wicket.markup.html.panel.EmptyPanel import org.apache.wicket.model.IModel import org.apache.wicket.model.Model import org.apache.wicket.model.StringResourceModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.settings.DebugSettings import org.apache.wicket.spring.injection.annot.SpringBean @Suppress("SameParameterValue") abstract class AbstractPage<T> : GenericWebPage<T> { @SpringBean lateinit var dateTimeService: DateTimeService private set lateinit var feedbackPanel: NotificationPanel private set lateinit var navBar: Navbar private set open val debugSettings: DebugSettings get() = application.debugSettings /** * Override if you do not want to show the navbar or only conditionally. * @return whether to show the Navbar or not. */ open val isNavbarVisible: Boolean get() = true protected val isSignedIn: Boolean get() = AuthenticatedWebSession.get().isSignedIn protected abstract val properties: ApplicationProperties private val title: IModel<String> get() = Model.of(properties.titleOrBrand) constructor(parameters: PageParameters?) : super(parameters) constructor(model: IModel<T>?) : super(model) override fun renderHead(response: IHeaderResponse) { response.apply { super.renderHead(this) render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("charset", "utf-8"))) render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("X-UA-Compatible", "IE=edge"))) render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("viewport", "width=device-width, initial-scale=1"))) render(PriorityHeaderItem(MetaDataHeaderItem.forMetaTag("Content-Type", "text/html; charset=UTF-8"))) } } override fun onInitialize() { super.onInitialize() createAndAddTitle("pageTitle") createAndAddNavBar("navbar") createAndAddFeedbackPanel("feedback") createAndAddDebugBar("debug") createAndAddFooterContainer(FOOTER_CONTAINER) } private fun createAndAddTitle(id: String) { queue(Label(id, title)) } private fun createAndAddNavBar(id: String) { navBar = newNavbar(id).also { queue(it) } extendNavBar() } /** * Override if you need to extend the [Navbar] */ private fun extendNavBar() { // no default implementation } private fun createAndAddFeedbackPanel(label: String) { feedbackPanel = NotificationPanel(label).apply { outputMarkupId = true }.also { queue(it) } } private fun createAndAddDebugBar(label: String) { if (debugSettings.isDevelopmentUtilitiesEnabled) queue(DebugBar(label).positionBottom()) else queue(EmptyPanel(label).setVisible(false)) } private fun createAndAddFooterContainer(id: String) { queue(HeaderResponseContainer(id, id)) } private fun newNavbar(markupId: String): Navbar = object : Navbar(markupId) { override fun onConfigure() { super.onConfigure() isVisible = isNavbarVisible } }.apply { fluid() position = Navbar.Position.STATIC_TOP setBrandName(Model.of(getBrandName(properties.brand))) setInverted(true) }.also { addLinksTo(it) } fun getBrandName(brand: String?): String = if (brand == null || brand.isBlank() || "n.a." == brand) StringResourceModel("brandname", this, null).string else brand protected open fun addLinksTo(nb: Navbar) {} @JvmOverloads fun queueFieldAndLabel(field: FormComponent<*>, pv: PropertyValidator<*>? = null) { val id = field.id val labelModel = StringResourceModel(id + LABEL_RESOURCE_TAG, this, null) val label = Label(id + LABEL_TAG, labelModel) queue(label) field.label = labelModel queue(field) pv?.let { field.add(it) } label.isVisible = field.isVisible } protected fun newResponsePageButton( id: String, responsePage: SerializableSupplier<AbstractPage<*>?>, ): BootstrapAjaxButton = object : BootstrapAjaxButton( id, StringResourceModel(id + LABEL_RESOURCE_TAG, this@AbstractPage, null), Buttons.Type.Default ) { override fun onSubmit(target: AjaxRequestTarget) { super.onSubmit(target) setResponsePage(responsePage.get()) } override fun onConfigure() { super.onConfigure() isEnabled = setResponsePageButtonEnabled() } } /** * Controls the enabled status of the response page button. Override if needed. * * @return true if response page button shall be enabled (default). false otherwise. */ protected open fun setResponsePageButtonEnabled(): Boolean = true protected fun queuePanelHeadingFor(id: String) { queue( Label( id + LABEL_TAG, StringResourceModel(id + PANEL_HEADER_RESOURCE_TAG, this, null) ) ) } protected fun signIn(username: String?, password: String?): Boolean = AuthenticatedWebSession.get().signIn(username, password) protected fun signOutAndInvalidate() { AuthenticatedWebSession.get().invalidate() } companion object { private const val serialVersionUID = 1L const val FOOTER_CONTAINER = "footer-container" } }
gpl-3.0
cb02f32b06e2364c9e26ad2237db4f3d
33.954315
120
0.675864
4.652703
false
false
false
false
CORDEA/MackerelClient
app/src/main/java/jp/cordea/mackerelclient/activity/LicenseActivity.kt
1
1345
package jp.cordea.mackerelclient.activity import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import dagger.android.AndroidInjection import io.reactivex.disposables.Disposable import jp.cordea.mackerelclient.R import jp.cordea.mackerelclient.databinding.ActivityLicenseBinding import jp.cordea.mackerelclient.viewmodel.LicenseViewModel class LicenseActivity : AppCompatActivity() { private val viewModel by lazy { LicenseViewModel(this) } private var disposable: Disposable? = null override fun onCreate(savedInstanceState: Bundle?) { AndroidInjection.inject(this) super.onCreate(savedInstanceState) val binding = DataBindingUtil .setContentView<ActivityLicenseBinding>(this, R.layout.activity_license) disposable = viewModel.licensesObservable .subscribe({ binding.licenseTextView.text = it binding.container.visibility = View.VISIBLE binding.progress.visibility = View.GONE }, { binding.errorLayout.root.visibility = View.VISIBLE binding.progress.visibility = View.GONE }) } override fun onDestroy() { super.onDestroy() disposable?.dispose() } }
apache-2.0
721e5dc970b1cc6366022f60427b9c24
32.625
84
0.707807
5.253906
false
false
false
false
F43nd1r/acra-backend
acrarium/src/main/kotlin/com/faendir/acra/ui/view/app/tabs/BugTab.kt
1
7351
/* * (C) Copyright 2018 Lukas Morawietz (https://github.com/F43nd1r) * * 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.faendir.acra.ui.view.app.tabs import com.faendir.acra.i18n.Messages import com.faendir.acra.model.App import com.faendir.acra.model.Permission import com.faendir.acra.model.QBug import com.faendir.acra.model.QReport import com.faendir.acra.model.QStacktrace import com.faendir.acra.model.Version import com.faendir.acra.model.view.VBug import com.faendir.acra.navigation.ParseAppParameter import com.faendir.acra.navigation.View import com.faendir.acra.security.SecurityUtils import com.faendir.acra.service.BugMerger import com.faendir.acra.service.DataService import com.faendir.acra.settings.LocalSettings import com.faendir.acra.ui.component.Translatable import com.faendir.acra.ui.component.dialog.createButton import com.faendir.acra.ui.component.dialog.showFluentDialog import com.faendir.acra.ui.component.grid.AcrariumGridView import com.faendir.acra.ui.component.grid.TimeSpanRenderer import com.faendir.acra.ui.component.grid.column import com.faendir.acra.ui.component.grid.grid import com.faendir.acra.ui.ext.content import com.faendir.acra.ui.view.app.AppView import com.faendir.acra.ui.view.bug.tabs.BugTab import com.faendir.acra.ui.view.bug.tabs.ReportTab import com.querydsl.jpa.impl.JPAQuery import com.vaadin.flow.component.AbstractField.ComponentValueChangeEvent import com.vaadin.flow.component.button.ButtonVariant import com.vaadin.flow.component.grid.Grid import com.vaadin.flow.component.grid.GridSortOrder import com.vaadin.flow.component.notification.Notification import com.vaadin.flow.component.radiobutton.RadioButtonGroup import com.vaadin.flow.component.select.Select import com.vaadin.flow.data.renderer.ComponentRenderer import com.vaadin.flow.router.Route /** * @author lukas * @since 14.07.18 */ @View @Route(value = "bug", layout = AppView::class) class BugTab( private val dataService: DataService, private val bugMerger: BugMerger, private val localSettings: LocalSettings, @ParseAppParameter private val app: App ) : AppTab<AcrariumGridView<VBug>>(app) { init { content { val mergeButton = Translatable.createButton(Messages.MERGE_BUGS) { val selectedItems: List<VBug> = ArrayList(grid.selectedItems) if (selectedItems.size > 1) { val titles = RadioButtonGroup<String>() titles.setItems(selectedItems.map { bug: VBug -> bug.bug.title }) titles.value = selectedItems[0].bug.title showFluentDialog { header(Messages.CHOOSE_BUG_GROUP_TITLE) add(titles) createButton { bugMerger.mergeBugs(selectedItems.map { it.bug }, titles.value) grid.deselectAll() grid.dataProvider.refreshAll() } } } else { Notification.show(Messages.ONLY_ONE_BUG_SELECTED) } }.with { isEnabled = false removeThemeVariants(ButtonVariant.LUMO_PRIMARY) } header.addComponentAsFirst(mergeButton) grid { setSelectionMode(Grid.SelectionMode.MULTI) asMultiSelect().addSelectionListener { mergeButton.content.isEnabled = it.allSelectedItems.size >= 2 } column({ it.reportCount }) { setSortable(QReport.report.count()) setCaption(Messages.REPORTS) } column(TimeSpanRenderer { it.lastReport }) { setSortable(QReport.report.date.max()) setCaption(Messages.LATEST_REPORT) sort(GridSortOrder.desc(this).build()) } val versions = dataService.findAllVersions(app) val versionCodeNameMap = versions.associate { it.code to it.name } column({ versionCodeNameMap[it.highestVersionCode] }) { setSortable(QReport.report.stacktrace.version.code.max()) setCaption(Messages.LATEST_VERSION) } column({ it.userCount }) { setSortable(QReport.report.installationId.countDistinct()) setCaption(Messages.AFFECTED_USERS) } column({ it.bug.title }) { setSortableAndFilterable(QBug.bug.title, Messages.TITLE) setCaption(Messages.TITLE) isAutoWidth = false flexGrow = 1 } column(ComponentRenderer { bug: VBug -> Select(*versions.toTypedArray()).apply { setTextRenderer { it.name } isEmptySelectionAllowed = true emptySelectionCaption = getTranslation(Messages.NOT_SOLVED) value = bug.bug.solvedVersion isEnabled = SecurityUtils.hasPermission(app, Permission.Level.EDIT) addValueChangeListener { e: ComponentValueChangeEvent<Select<Version?>?, Version?> -> dataService.setBugSolved(bug.bug, e.value) style["--select-background-color"] = if (bug.highestVersionCode > bug.bug.solvedVersion?.code ?: Int.MAX_VALUE) "var(--lumo-error-color-50pct)" else null } if (bug.highestVersionCode > bug.bug.solvedVersion?.code ?: Int.MAX_VALUE) { style["--select-background-color"] = "var(--lumo-error-color-50pct)" } } }) { setSortable(QBug.bug.solvedVersion) setFilterable( //not solved or regression QBug.bug.solvedVersion.isNull.or( QBug.bug.solvedVersion.code.lt( JPAQuery<Any>().select(QStacktrace.stacktrace1.version.code.max()).from(QStacktrace.stacktrace1) .where(QStacktrace.stacktrace1.bug.eq(QBug.bug)) ) ), true, Messages.HIDE_SOLVED ) setCaption(Messages.SOLVED) } addOnClickNavigation(ReportTab::class.java) { BugTab.getNavigationParams(it.bug) } } } } override fun initContent() = AcrariumGridView(dataService.getBugProvider(app), localSettings::bugGridSettings) }
apache-2.0
d009294f6f006df35cfaebf3bfc021df
45.828025
148
0.606176
4.603006
false
false
false
false
googlecodelabs/android-sleep
start/src/main/java/com/android/example/sleepcodelab/data/db/SleepClassifyEventEntity.kt
2
1921
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.sleepcodelab.data.db import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.google.android.gms.location.SleepClassifyEvent /** * Entity class (table version of the class) for [SleepClassifyEvent] which represents a sleep * classification event including the classification timestamp, the sleep confidence, and the * supporting data such as device motion and ambient light level. Classification events are * reported regularly. */ @Entity(tableName = "sleep_classify_events_table") data class SleepClassifyEventEntity( @PrimaryKey @ColumnInfo(name = "time_stamp_seconds") val timestampSeconds: Int, @ColumnInfo(name = "confidence") val confidence: Int, @ColumnInfo(name = "motion") val motion: Int, @ColumnInfo(name = "light") val light: Int ) { companion object { fun from(sleepClassifyEvent: SleepClassifyEvent): SleepClassifyEventEntity { return SleepClassifyEventEntity( timestampSeconds = (sleepClassifyEvent.timestampMillis / 1000).toInt(), confidence = sleepClassifyEvent.confidence, motion = sleepClassifyEvent.motion, light = sleepClassifyEvent.light ) } } }
apache-2.0
2b7457cd57d00696621734c5fa05561c
34.574074
94
0.716814
4.53066
false
false
false
false
zdary/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/columns/editors/PackageVersionTableCellEditor.kt
1
2854
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.editors import com.intellij.ui.components.editors.JBComboBoxTableCellEditorComponent import com.intellij.ui.table.JBTable import com.intellij.util.ui.AbstractTableCellEditor import com.jetbrains.packagesearch.intellij.plugin.ui.components.ComboBoxTableCellEditorComponent import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.VersionViewModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.colors import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages.columns.renderers.PopupMenuListItemCellRenderer import java.awt.Component import javax.swing.JTable internal class PackageVersionTableCellEditor : AbstractTableCellEditor() { private val comboBox = JBComboBoxTableCellEditorComponent() private var onlyStable = false fun updateData(onlyStable: Boolean) { this.onlyStable = onlyStable } override fun getCellEditorValue(): Any? = comboBox.editorValue override fun getTableCellEditorComponent(table: JTable, value: Any, isSelected: Boolean, row: Int, column: Int): Component { val viewModel = value as VersionViewModel<*> val versionViewModels = when (viewModel) { is VersionViewModel.InstalledPackage -> viewModel.packageModel.getAvailableVersions(onlyStable) .map { viewModel.copy(selectedVersion = it) } is VersionViewModel.InstallablePackage -> viewModel.packageModel.getAvailableVersions(onlyStable) .map { viewModel.copy(selectedVersion = it) } } return createComboBoxEditor(table, versionViewModels, viewModel.selectedVersion).apply { table.colors.applyTo(this, isSelected = true) setCell(row, column) } } private fun createComboBoxEditor( table: JTable, versionViewModels: List<VersionViewModel<*>>, selectedVersion: PackageVersion ): ComboBoxTableCellEditorComponent<*> { require(table is JBTable) { "The packages list table is expected to be a JBTable, but was a ${table::class.qualifiedName}" } val selectedViewModel = versionViewModels.find { it.selectedVersion == selectedVersion } val cellRenderer = PopupMenuListItemCellRenderer(selectedViewModel, table.colors) { it.selectedVersion.displayName } return ComboBoxTableCellEditorComponent(table, cellRenderer).apply { isShowBelowCell = false isForcePopupMatchCellWidth = false options = versionViewModels value = selectedViewModel } } }
apache-2.0
ebbcab01bad938caa5d24800c6f3547a
45.786885
139
0.742467
5.294991
false
false
false
false
zdary/intellij-community
plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxEventHandlerReferenceQuickFixProvider.kt
12
3489
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.javaFX.fxml.refs import com.intellij.codeInsight.daemon.QuickFixActionRegistrar import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.psi.PsiJvmSubstitutor import com.intellij.psi.PsiModifier import com.intellij.psi.PsiSubstitutor import com.intellij.psi.PsiType import com.intellij.psi.codeStyle.JavaCodeStyleSettings import com.intellij.psi.util.createSmartPointer import com.intellij.psi.xml.XmlAttribute import com.intellij.psi.xml.XmlAttributeValue import com.intellij.util.VisibilityUtil import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonNames import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil class JavaFxEventHandlerReferenceQuickFixProvider : UnresolvedReferenceQuickFixProvider<JavaFxEventHandlerReference>() { override fun getReferenceClass(): Class<JavaFxEventHandlerReference> = JavaFxEventHandlerReference::class.java override fun registerFixes(ref: JavaFxEventHandlerReference, registrar: QuickFixActionRegistrar) { val controller = ref.myController ?: return if (ref.myEventHandler != null) return val element = ref.element val request = CreateEventHandlerRequest(element) createMethodActions(controller, request).forEach(registrar::register) } } class CreateEventHandlerRequest(element: XmlAttributeValue) : CreateMethodRequest { private val myProject = element.project private val myVisibility = getVisibility(element) private val myPointer = element.createSmartPointer(myProject) override fun isValid(): Boolean = myPointer.element.let { it != null && it.value.let { value -> value != null && value.length > 2 } } private val myElement get() = myPointer.element!! override fun getMethodName(): String = myElement.value!!.substring(1) override fun getReturnType(): List<ExpectedType> = listOf(expectedType(PsiType.VOID, ExpectedType.Kind.EXACT)) override fun getExpectedParameters(): List<ExpectedParameter> { val eventType = expectedType(getEventType(myElement), ExpectedType.Kind.EXACT) val parameter = expectedParameter(eventType) return listOf(parameter) } override fun getModifiers(): Set<JvmModifier> = setOf(myVisibility) override fun getAnnotations(): List<AnnotationRequest> = if (myVisibility != JvmModifier.PUBLIC) { listOf(annotationRequest(JavaFxCommonNames.JAVAFX_FXML_ANNOTATION)) } else { emptyList() } override fun getTargetSubstitutor(): PsiJvmSubstitutor = PsiJvmSubstitutor(myProject, PsiSubstitutor.EMPTY) } private fun getVisibility(element: XmlAttributeValue): JvmModifier { val visibility = JavaCodeStyleSettings.getInstance(element.containingFile).VISIBILITY if (VisibilityUtil.ESCALATE_VISIBILITY == visibility) return JvmModifier.PRIVATE if (visibility == PsiModifier.PACKAGE_LOCAL) return JvmModifier.PACKAGE_LOCAL return JvmModifier.valueOf(visibility.toUpperCase()) } private fun getEventType(element: XmlAttributeValue): PsiType { val parent = element.parent if (parent is XmlAttribute) { val eventType = JavaFxPsiUtil.getDeclaredEventType(parent) if (eventType != null) { return eventType } } return PsiType.getTypeByName(JavaFxCommonNames.JAVAFX_EVENT, element.project, element.resolveScope) }
apache-2.0
550538cdc5a8ae851975b9989777da5c
40.047059
140
0.793924
4.670683
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/args/ArgsSchema.kt
1
8317
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.common.args import slatekit.common.Types import slatekit.results.Try import slatekit.results.builders.Tries /** * stores and builds a list of 1 or more arguments which collectively represent the schema. * * @note this schema is immutable and returns a schema when adding additional arguments * @param items : the list of arguments. */ class ArgsSchema(val items: List<Arg> = listOf(), val builder:ArgsWriter? = null) { val any: Boolean get() = items.isNotEmpty() /** * Adds a argument of type text to the schema * * @param alias : Short hand alias for the name * @param name : Name of argument * @param desc : Description * @param required : Whether this is required or not * @param defaultVal : Default value for argument * @param example : Example of value shown for help text * @param exampleMany : Examples of values shown for help text * @param group : Used to group arguments into categories * @return */ fun text( alias: String = "", name: String, desc: String = "", required: Boolean = false, defaultVal: String = "", example: String = "", exampleMany: String = "", group: String = "" ): ArgsSchema = add(alias, name, desc, Types.JStringClass, required, defaultVal, example, exampleMany, group) /** * Adds a argument of type boolean to the schema * * @param alias : Short hand alias for the name * @param name : Name of argument * @param desc : Description * @param required : Whether this is required or not * @param defaultVal : Default value for argument * @param example : Example of value shown for help text * @param exampleMany : Examples of values shown for help text * @param group : Used to group arguments into categories * @return */ fun flag( alias: String = "", name: String, desc: String = "", required: Boolean = false, defaultVal: String = "", example: String = "", exampleMany: String = "", group: String = "" ): ArgsSchema = add(alias, name, desc, Types.JBoolClass, required, defaultVal, example, exampleMany, group) /** * Adds a argument of type number to the schema * * @param alias : Short hand alias for the name * @param name : Name of argument * @param desc : Description * @param required : Whether this is required or not * @param defaultVal : Default value for argument * @param example : Example of value shown for help text * @param exampleMany : Examples of values shown for help text * @param group : Used to group arguments into categories * @return */ fun number( alias: String = "", name: String, desc: String = "", required: Boolean = false, defaultVal: String = "", example: String = "", exampleMany: String = "", group: String = "" ): ArgsSchema = add(alias, name, desc, Types.JIntClass, required, defaultVal, example, exampleMany, group) /** * Adds a argument to the schema * * @param alias : Short hand alias for the name * @param name : Name of argument * @param desc : Description * @param dataType : Data type of the argument * @param required : Whether this is required or not * @param defaultVal : Default value for argument * @param example : Example of value shown for help text * @param exampleMany : Examples of values shown for help text * @param group : Used to group arguments into categories * @return */ fun add( alias: String = "", name: String, desc: String = "", dataType: Class<*>, required: Boolean = false, defaultVal: String = "", example: String = "", exampleMany: String = "", group: String = "" ): ArgsSchema { val typeName = dataType.simpleName val arg = Arg(alias, name, desc, typeName ?: "string", required, false, false, false, group, "", defaultVal, example, exampleMany) val newList = items.plus(arg) return ArgsSchema(newList) } /** * whether or not the argument supplied is missing * * @param args * @param arg * @return */ fun missing(args: Args, arg: Arg): Boolean = arg.isRequired && !args.containsKey(arg.name) fun buildHelp(prefix: String? = "-", separator: String? = "=") { val maxLen = maxLengthOfName() items.forEach { arg -> when(builder) { null -> { val nameLen = maxLen ?: arg.name.length val nameFill = arg.name.padEnd(nameLen) val namePart = (prefix ?: "-") + nameFill println(namePart) print(separator ?: "=") println(arg.desc) print(" ".repeat(nameLen + 6)) if (arg.isRequired) { println("!" ) println("required ") } else { println("?" ) println("optional ") } println("[${arg.dataType}] " ) println("e.g. ${arg.example}") } else -> { builder.write(arg, prefix, separator, maxLen) } } } } /** * gets the maximum length of an argument name from all arguments * * @return */ private fun maxLengthOfName(): Int = if (items.isEmpty()) 0 else items.maxByOrNull { it.name.length }?.name ?.length ?: 0 companion object { @JvmStatic val empty:ArgsSchema = ArgsSchema() /** * Parses the line against the schema and transforms any aliases into canonical names */ @JvmStatic fun parse(schema:ArgsSchema, line:String):Try<Args> { val parsed = Args.parse(line, "-", "=", true) return parsed.map { transform(schema, it) } } /** * Transforms the arguments which may have aliases into their canonical names * @param schema: The argument schema to transform aliases against * @param args : The parsed arguments */ @JvmStatic fun transform(schema: ArgsSchema?, args: Args): Args { if(schema == null) return args val canonical = args.named.toMutableMap() val aliased = schema.items.filter { !it.alias.isNullOrBlank() } if(aliased.isEmpty()) { return args } aliased.forEach { arg -> if(canonical.containsKey(arg.alias)){ val value = canonical.get(arg.alias) if(value != null){ canonical.remove(arg.alias) canonical[arg.name] = value } } } val finalArgs = args.copy(namedArgs = canonical) return finalArgs } /** * Validates the arguments against this schema * @param schema: The argument schema to validate against * @param args : The parsed arguments */ @JvmStatic fun validate(schema: ArgsSchema, args: Args): Try<Boolean> { val missing = schema.items.filter { arg -> arg.isRequired && !args.containsKey(arg.name) } return if (missing.isNotEmpty()) { Tries.errored("invalid arguments supplied: Missing : " + missing.first().name) } else { Tries.success(true) } } } }
apache-2.0
aad10ecde14bfa76c2d39c7d1905fd29
33.945378
125
0.549717
4.747146
false
false
false
false
zdary/intellij-community
python/python-psi-impl/src/com/jetbrains/python/psi/impl/stubs/PyDataclassFieldStubImpl.kt
4
5545
/* * Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.psi.impl.stubs import com.intellij.psi.stubs.StubInputStream import com.intellij.psi.stubs.StubOutputStream import com.intellij.psi.util.QualifiedName import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.PyDataclassParameters import com.jetbrains.python.codeInsight.resolvesToOmittedDefault import com.jetbrains.python.psi.PyCallExpression import com.jetbrains.python.psi.PyReferenceExpression import com.jetbrains.python.psi.PyTargetExpression import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.resolve.PyResolveUtil import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import java.io.IOException class PyDataclassFieldStubImpl private constructor(private val calleeName: QualifiedName, private val parameters: FieldParameters) : PyDataclassFieldStub { companion object { fun create(expression: PyTargetExpression): PyDataclassFieldStub? { val value = expression.findAssignedValue() as? PyCallExpression ?: return null val callee = value.callee as? PyReferenceExpression ?: return null val calleeNameAndType = calculateCalleeNameAndType(callee) ?: return null val parameters = analyzeArguments(value, calleeNameAndType.second) ?: return null return PyDataclassFieldStubImpl(calleeNameAndType.first, parameters) } @Throws(IOException::class) fun deserialize(stream: StubInputStream): PyDataclassFieldStub? { val calleeName = stream.readNameString() ?: return null val hasDefault = stream.readBoolean() val hasDefaultFactory = stream.readBoolean() val initValue = stream.readBoolean() val kwOnly = stream.readBoolean() return PyDataclassFieldStubImpl( QualifiedName.fromDottedString(calleeName), FieldParameters(hasDefault, hasDefaultFactory, initValue, kwOnly) ) } private fun calculateCalleeNameAndType(callee: PyReferenceExpression): Pair<QualifiedName, PyDataclassParameters.PredefinedType>? { val qualifiedName = callee.asQualifiedName() ?: return null val dataclassesField = QualifiedName.fromComponents("dataclasses", "field") val attrIb = QualifiedName.fromComponents("attr", "ib") val attrAttr = QualifiedName.fromComponents("attr", "attr") val attrAttrib = QualifiedName.fromComponents("attr", "attrib") for (originalQName in PyResolveUtil.resolveImportedElementQNameLocally(callee)) { when (originalQName) { dataclassesField -> return qualifiedName to PyDataclassParameters.PredefinedType.STD attrIb, attrAttr, attrAttrib -> return qualifiedName to PyDataclassParameters.PredefinedType.ATTRS } } return null } private fun analyzeArguments(call: PyCallExpression, type: PyDataclassParameters.PredefinedType): FieldParameters? { val initValue = PyEvaluator.evaluateAsBooleanNoResolve(call.getKeywordArgument("init"), true) if (type == PyDataclassParameters.PredefinedType.STD) { val default = call.getKeywordArgument("default") val defaultFactory = call.getKeywordArgument("default_factory") return FieldParameters(default != null && !resolvesToOmittedDefault(default, type), defaultFactory != null && !resolvesToOmittedDefault(defaultFactory, type), initValue, false) } else if (type == PyDataclassParameters.PredefinedType.ATTRS) { val default = call.getKeywordArgument("default") val hasFactory = call.getKeywordArgument("factory").let { it != null && it.text != PyNames.NONE } val kwOnly = PyEvaluator.evaluateAsBooleanNoResolve(call.getKeywordArgument("kw_only"), false) if (default != null && !resolvesToOmittedDefault(default, type)) { val callee = (default as? PyCallExpression)?.callee as? PyReferenceExpression val hasFactoryInDefault = callee != null && QualifiedName.fromComponents("attr", "Factory") in PyResolveUtil.resolveImportedElementQNameLocally(callee) return FieldParameters(!hasFactoryInDefault, hasFactory || hasFactoryInDefault, initValue, kwOnly) } return FieldParameters(false, hasFactory, initValue, kwOnly) } return null } } override fun getTypeClass(): Class<out CustomTargetExpressionStubType<out CustomTargetExpressionStub>> { return PyDataclassFieldStubType::class.java } override fun serialize(stream: StubOutputStream) { stream.writeName(calleeName.toString()) stream.writeBoolean(parameters.hasDefault) stream.writeBoolean(parameters.hasDefaultFactory) stream.writeBoolean(parameters.initValue) stream.writeBoolean(parameters.kwOnly) } override fun getCalleeName(): QualifiedName = calleeName override fun hasDefault(): Boolean = parameters.hasDefault override fun hasDefaultFactory(): Boolean = parameters.hasDefaultFactory override fun initValue(): Boolean = parameters.initValue override fun kwOnly(): Boolean = parameters.kwOnly private data class FieldParameters(val hasDefault: Boolean, val hasDefaultFactory: Boolean, val initValue: Boolean, val kwOnly: Boolean) }
apache-2.0
119ea7a86d8439ed8c91ee42b34e2f0b
45.208333
140
0.72101
5.373062
false
false
false
false
leafclick/intellij-community
java/java-impl/src/com/intellij/codeInsight/daemon/problems/UsageSink.kt
1
4434
// 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.daemon.problems import com.intellij.openapi.module.ModuleUtil import com.intellij.openapi.project.Project import com.intellij.pom.Navigatable import com.intellij.psi.* import com.intellij.psi.search.GlobalSearchScope import com.intellij.psi.search.PsiSearchHelper class UsageSink(private val project: Project) { internal fun checkUsages(prevMember: Member?, curMember: Member?, containingFile: PsiFile): List<Problem>? { // member properties were changed if (prevMember != null && curMember != null && prevMember.name == curMember.name) { return processMemberChange(prevMember, curMember, containingFile) } /** * In other cases we need to use module scope since we might already have some problems * that are outside of current member scope but that might resolve after the change. * @see com.intellij.java.codeInsight.daemon.problems.MethodProblemsTest#testMethodOverrideScopeIsChanged * as an example how it might happen. */ val problems = mutableListOf<Problem>() // member was renamed or removed if (prevMember != null) { val memberProblems = processUsages(prevMember, containingFile) ?: return null problems.addAll(memberProblems) } // member was renamed or created if (curMember != null) { val memberProblems = processUsages(curMember, containingFile) ?: return null problems.addAll(memberProblems) } return problems } private fun processUsages(member: Member, containingFile: PsiFile, scope: GlobalSearchScope? = extractScope(member, containingFile)): List<Problem>? { if (scope == null) return null val memberName = member.name val isMethodSearch = member.psiMember is PsiMethod val usageExtractor: (PsiFile, Int) -> PsiElement? = { psiFile, index -> val elementAt = psiFile.findElementAt(index) as? PsiIdentifier if (elementAt != null) extractMemberUsage(elementAt, isMethodSearch) else null } val collector = MemberUsageCollector(memberName, containingFile, usageExtractor) PsiSearchHelper.getInstance(project).processAllFilesWithWord(memberName, scope, collector, true) val usages = collector.collectedUsages ?: return null val problems = mutableListOf<Problem>() for (usage in usages) { problems.addAll(ProblemMatcher.getProblems(usage)) } return problems } private fun processMemberChange(prevMember: Member, curMember: Member, containingFile: PsiFile): List<Problem>? { val prevScope = prevMember.scope val curScope = curMember.scope if (prevScope == curScope) return processUsages(curMember, containingFile, curScope) val unionScope = prevScope.union(curScope) val problems = processUsages(curMember, containingFile, unionScope) if (problems != null) return problems /** * If we reported errors for this member previously and union scope is too big and cannot be analysed, * then we stuck with already reported problems even after the fix. * To prevent that we need to remove all previously reported problems for this element (even though they are still valid). * @see com.intellij.java.codeInsight.daemon.problems.FieldProblemsTest#testErrorsRemovedAfterScopeChanged as an example. */ val prevProblems = processUsages(curMember, containingFile, prevScope) // ok, we didn't analyse this element before if (prevProblems == null) return null return prevProblems.map { if (it.message == null) it else Problem(it.file, null, it.place) } } companion object { private fun extractScope(member: Member, containingFile: PsiFile): GlobalSearchScope? = ModuleUtil.findModuleForFile(containingFile)?.moduleScope ?: member.scope private fun extractMemberUsage(identifier: PsiIdentifier, isMethodSearch: Boolean): PsiElement? { val parent = identifier.parent val usage = when { parent is PsiReference -> { val javaReference = parent.element as? PsiJavaReference if (javaReference != null) javaReference as? PsiElement else null } parent is PsiMethod && isMethodSearch -> parent else -> null } return if (usage is Navigatable) usage else null } } }
apache-2.0
2f0057d21d3abb4a3e55bb6bb296c782
45.684211
140
0.720794
4.672287
false
false
false
false
JuliusKunze/kotlin-native
Interop/StubGenerator/src/main/kotlin/org/jetbrains/kotlin/native/interop/gen/TypeUtils.kt
1
2642
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.native.interop.gen import org.jetbrains.kotlin.native.interop.indexer.* val EnumDef.isAnonymous: Boolean get() = spelling.contains("(anonymous ") // TODO: it is a hack /** * Returns the expression which could be used for this type in C code. * Note: the resulting string doesn't exactly represent this type, but it is enough for current purposes. * * TODO: use libclang to implement? */ fun Type.getStringRepresentation(): String = when (this) { is VoidType -> "void" is CharType -> "char" is BoolType -> "BOOL" is IntegerType -> this.spelling is FloatingType -> this.spelling is PointerType, is ArrayType -> "void*" is RecordType -> this.decl.spelling is EnumType -> if (this.def.isAnonymous) { this.def.baseType.getStringRepresentation() } else { this.def.spelling } is Typedef -> this.def.aliased.getStringRepresentation() is ObjCPointer -> when (this) { is ObjCIdType -> "id$protocolQualifier" is ObjCClassPointer -> "Class$protocolQualifier" is ObjCObjectPointer -> "${def.name}$protocolQualifier*" is ObjCInstanceType -> TODO(this.toString()) // Must have already been handled. is ObjCBlockPointer -> "id" } else -> throw kotlin.NotImplementedError() } private val ObjCQualifiedPointer.protocolQualifier: String get() = if (this.protocols.isEmpty()) "" else " <${protocols.joinToString { it.name }}>" tailrec fun Type.unwrapTypedefs(): Type = if (this is Typedef) { this.def.aliased.unwrapTypedefs() } else { this } fun blockTypeStringRepresentation(type: ObjCBlockPointer): String { return buildString { append(type.returnType.getStringRepresentation()) append("(^)") append("(") val blockParameters = if (type.parameterTypes.isEmpty()) { "void" } else { type.parameterTypes.joinToString { it.getStringRepresentation() } } append(blockParameters) append(")") } }
apache-2.0
452b538ef35f992388113d8753f1735b
31.219512
105
0.679031
4.302932
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/call/incorrectNumberOfArguments.kt
2
2694
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.jvm.isAccessible import kotlin.reflect.KCallable import kotlin.reflect.KFunction import kotlin.reflect.KMutableProperty var foo: String = "" class A(private var bar: String = "") { fun getBar() = A::bar } object O { @JvmStatic private var baz: String = "" @JvmStatic fun getBaz() = (O::class.members.single { it.name == "baz" } as KMutableProperty<*>).apply { isAccessible = true } fun getGetBaz() = O::class.members.single { it.name == "getBaz" } as KFunction<*> } fun check(callable: KCallable<*>, vararg args: Any?) { val expected = callable.parameters.size val actual = args.size if (expected == actual) { throw AssertionError("Bad test case: expected and actual number of arguments should differ (was $expected vs $actual)") } val expectedExceptionMessage = "Callable expects $expected arguments, but $actual were provided." try { callable.call(*args) throw AssertionError("Fail: an IllegalArgumentException should have been thrown") } catch (e: IllegalArgumentException) { if (e.message != expectedExceptionMessage) { // This most probably means that we don't check number of passed arguments in reflection // and the default check from Java reflection yields an IllegalArgumentException, but with a not that helpful message throw AssertionError("Fail: an exception with an unrecognized message was thrown: \"${e.message}\"" + "\nExpected message was: $expectedExceptionMessage") } } } fun box(): String { check(::box, null) check(::box, "") check(::A) check(::A, null, "") check(O.getGetBaz()) check(O.getGetBaz(), null, "") val f = ::foo check(f, null) check(f, null, null) check(f, arrayOf<Any?>(null)) check(f, "") check(f.getter, null) check(f.getter, null, null) check(f.getter, arrayOf<Any?>(null)) check(f.getter, "") check(f.setter) check(f.setter, null, null) check(f.setter, null, "") val b = A().getBar() check(b) check(b, null, null) check(b, "", "") check(b.getter) check(b.getter, null, null) check(b.getter, "", "") check(b.setter) check(b.setter, null) check(b.setter, "") val z = O.getBaz() check(z) check(z, null, null) check(z, "", "") check(z.getter) check(z.getter, null, null) check(z.getter, "", "") check(z.setter) check(z.setter, null) check(z.setter, "") return "OK" }
apache-2.0
236a4aff49a1769a1e3f97572cdc6c6c
23.944444
129
0.618411
3.826705
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/properties/lateinit/isInitializedAndDeinitialize/sideEffects.kt
1
435
// IGNORE_BACKEND: NATIVE // LANGUAGE_VERSION: 1.2 // WITH_RUNTIME class Foo { lateinit var bar: String fun test(): String { var state = 0 if (run { state++; this }::bar.isInitialized) return "Fail 1" bar = "A" if (!run { state++; this }::bar.isInitialized) return "Fail 3" return if (state == 2) "OK" else "Fail: state=$state" } } fun box(): String { return Foo().test() }
apache-2.0
2c655a803a2009bbd2b2071b605eaeab
19.714286
70
0.556322
3.48
false
true
false
false
codeka/wwmmo
client/src/main/kotlin/au/com/codeka/warworlds/client/game/world/EmpireManager.kt
1
4570
package au.com.codeka.warworlds.client.game.world import au.com.codeka.warworlds.client.App import au.com.codeka.warworlds.client.R import au.com.codeka.warworlds.client.concurrency.Threads import au.com.codeka.warworlds.client.store.ProtobufStore import au.com.codeka.warworlds.client.util.eventbus.EventHandler import au.com.codeka.warworlds.common.Log import au.com.codeka.warworlds.common.proto.Empire import au.com.codeka.warworlds.common.proto.EmpireDetailsPacket import au.com.codeka.warworlds.common.proto.Packet import au.com.codeka.warworlds.common.proto.RequestEmpirePacket import com.google.common.collect.Lists import java.util.* /** Manages empires. */ object EmpireManager { private val log = Log("EmpireManager") /** * The number of milliseconds to delay sending the empire request to the server, so that we can * batch them up a bit in case of a burst of requests (happens when you open chat for example). */ private const val EMPIRE_REQUEST_DELAY_MS: Long = 150 private val empires: ProtobufStore<Empire> = App.dataStore.empires() /** The list of pending empire requests. */ private val pendingEmpireRequests: MutableSet<Long> = HashSet() /** An object to synchronize on when updating [.pendingEmpireRequests]. */ private val pendingRequestLock = Any() /** Whether a request for empires is currently pending. */ private var requestPending = false /** Our current empire, will be null before we're connected. */ private var myEmpire: Empire? = null /** A placeholder [Empire] for native empires. */ private val nativeEmpire = Empire( id = 0, display_name = App.getString(R.string.native_colony), state = Empire.EmpireState.ACTIVE) private val eventListener: Any = object : Any() { @EventHandler(thread = Threads.BACKGROUND) fun handleEmpireUpdatedPacket(pkt: EmpireDetailsPacket) { for (empire in pkt.empires) { val startTime = System.nanoTime() empires.put(empire.id, empire) App.eventBus.publish(empire) val endTime = System.nanoTime() log.debug("Refreshed empire %d [%s] in %dms.", empire.id, empire.display_name, (endTime - startTime) / 1000000L) } } } init { App.eventBus.register(eventListener) } /** Called by the server when we get the 'hello', and lets us know the empire. */ fun onHello(empire: Empire) { empires.put(empire.id, empire) myEmpire = empire App.eventBus.publish(empire) } /** Returns [true] if my empire has been set, or false if it's not ready yet. */ fun hasMyEmpire(): Boolean { return myEmpire != null } /** Gets my empire, if my empire hasn't been set yet, IllegalStateException is thrown. */ fun getMyEmpire(): Empire { return myEmpire!! } /** @return true if the given empire is mine. */ fun isMyEmpire(empire: Empire?): Boolean { return if (empire?.id == null) { false } else empire.id == getMyEmpire().id } /** @return true if the given empire is an enemy of us. */ fun isEnemy(empire: Empire?): Boolean { if (empire == null) { return false } return myEmpire != null && empire.id != myEmpire!!.id } /** * Gets the [Empire] with the given id. If the id is 0, returns a pseudo-Empire that * can be used for native colonies/fleets. */ fun getEmpire(id: Long): Empire? { if (id == 0L) { return nativeEmpire } if (myEmpire != null && myEmpire!!.id == id) { return myEmpire } val empire = empires[id] if (empire == null) { requestEmpire(id) } return empire } /** * Request the [Empire] with the given ID from the server. To save a storm of requests when * showing the chat screen (and others), we delay sending the request by a couple hundred * milliseconds. */ private fun requestEmpire(id: Long) { synchronized(pendingRequestLock) { pendingEmpireRequests.add(id) if (!requestPending) { App.taskRunner.runTask({ sendPendingEmpireRequests() }, Threads.BACKGROUND, EMPIRE_REQUEST_DELAY_MS) } } } /** Called on a background thread to actually send the request empire request to the server. */ private fun sendPendingEmpireRequests() { var empireIds: List<Long> synchronized(pendingRequestLock) { empireIds = Lists.newArrayList(pendingEmpireRequests) pendingEmpireRequests.clear() requestPending = false } App.server.send(Packet(request_empire = RequestEmpirePacket(empire_id = empireIds))) } }
mit
ba776bcc95cbaae153e5b95ea58290bd
31.183099
98
0.682057
3.953287
false
false
false
false
smmribeiro/intellij-community
plugins/ide-features-trainer/src/training/featuresSuggester/actions/EditorActions.kt
7
5052
package training.featuresSuggester.actions import com.intellij.lang.Language import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import training.featuresSuggester.TextFragment sealed class EditorAction : Action() { abstract val editor: Editor abstract val psiFile: PsiFile? override val language: Language? get() = psiFile?.language override val project: Project? get() = editor.project val document: Document get() = editor.document protected fun getPsiFileFromEditor(): PsiFile? { val project = editor.project ?: return null return PsiDocumentManager.getInstance(project).getPsiFile(editor.document) } } // -------------------------------------EDITOR AFTER ACTIONS------------------------------------- data class EditorBackspaceAction( val textFragment: TextFragment?, val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorCopyAction( val text: String, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorCutAction( val text: String, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorPasteAction( val text: String, val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorTextInsertedAction( val text: String, val caretOffset: Int, override val editor: Editor, override val timeMillis: Long ) : EditorAction() { override val psiFile: PsiFile? get() = getPsiFileFromEditor() } data class EditorTextRemovedAction( val textFragment: TextFragment, val caretOffset: Int, override val editor: Editor, override val timeMillis: Long ) : EditorAction() { override val psiFile: PsiFile? get() = getPsiFileFromEditor() } data class EditorFindAction( override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorCodeCompletionAction( val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class CompletionChooseItemAction( val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorEscapeAction( val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class EditorFocusGainedAction( override val editor: Editor, override val timeMillis: Long ) : EditorAction() { override val psiFile: PsiFile? get() = getPsiFileFromEditor() } // -------------------------------------EDITOR BEFORE ACTIONS------------------------------------- data class BeforeEditorBackspaceAction( val textFragment: TextFragment?, val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeEditorCopyAction( val text: String, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeEditorCutAction( val textFragment: TextFragment?, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeEditorPasteAction( val text: String, val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeEditorTextInsertedAction( val text: String, val caretOffset: Int, override val editor: Editor, override val timeMillis: Long ) : EditorAction() { override val psiFile: PsiFile? get() = getPsiFileFromEditor() } data class BeforeEditorTextRemovedAction( val textFragment: TextFragment, val caretOffset: Int, override val editor: Editor, override val timeMillis: Long ) : EditorAction() { override val psiFile: PsiFile? get() = getPsiFileFromEditor() } data class BeforeEditorFindAction( override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeEditorCodeCompletionAction( val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeCompletionChooseItemAction( val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction() data class BeforeEditorEscapeAction( val caretOffset: Int, override val editor: Editor, override val psiFile: PsiFile?, override val timeMillis: Long ) : EditorAction()
apache-2.0
04a88fc7c1fc033c0938db532061376d
25.3125
98
0.732779
4.576087
false
false
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/repositories/RepositoryManagementPanel.kt
2
2408
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.project.Project import com.intellij.ui.AutoScrollToSourceHandler import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.actions.ShowSettingsAction import com.jetbrains.packagesearch.intellij.plugin.configuration.PackageSearchGeneralConfiguration import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import javax.swing.JScrollPane internal class RepositoryManagementPanel( private val project: Project ) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.repositories.title")) { private val repositoriesTree = RepositoryTree(project) private val autoScrollToSourceHandler = object : AutoScrollToSourceHandler() { override fun isAutoScrollMode(): Boolean { return PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource } override fun setAutoScrollMode(state: Boolean) { PackageSearchGeneralConfiguration.getInstance(project).autoScrollToSource = state } } private val mainSplitter = JBScrollPane(repositoriesTree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER).apply { border = emptyBorder() verticalScrollBar.unitIncrement = 16 UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true) } init { project.packageSearchProjectService.allInstalledKnownRepositoriesFlow .onEach { repositoriesTree.display(it) } .launchIn(project.lifecycleScope) } override fun build() = mainSplitter override fun buildGearActions() = DefaultActionGroup( ShowSettingsAction(project), autoScrollToSourceHandler.createToggleAction() ) }
apache-2.0
2e98d6ddf3908a3fa5c3e23145e85c20
42.781818
128
0.791113
5.280702
false
true
false
false
Helabs/generator-he-kotlin-mvp
app/templates/app_arch_comp/src/main/kotlin/data/SchedulerProviderContract.kt
1
934
package <%= appPackage %>.data import io.reactivex.Scheduler import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.internal.schedulers.ImmediateThinScheduler import io.reactivex.schedulers.Schedulers interface SchedulerProviderContract { val io: Scheduler val ui: Scheduler val computation: Scheduler } class SchedulerProvider : SchedulerProviderContract { override val io: Scheduler get() = Schedulers.io() override val ui: Scheduler get() = AndroidSchedulers.mainThread() override val computation: Scheduler get() = Schedulers.computation() } class ImmediateSchedulerProvider : SchedulerProviderContract { override val io: Scheduler get() = ImmediateThinScheduler.INSTANCE override val ui: Scheduler get() = ImmediateThinScheduler.INSTANCE override val computation: Scheduler get() = ImmediateThinScheduler.INSTANCE }
mit
42f441dd84bbdd42a74e07972d3d6fc4
26.5
62
0.747323
5.276836
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/preferences/PreferencesFragment.kt
1
14068
package com.habitrpg.android.habitica.ui.fragments.preferences import android.annotation.SuppressLint import android.app.ProgressDialog import android.content.Intent import android.content.SharedPreferences import android.content.res.Configuration import android.os.Build import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.PreferenceScreen import com.habitrpg.android.habitica.BuildConfig import com.habitrpg.android.habitica.HabiticaBaseApplication import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.data.ApiClient import com.habitrpg.android.habitica.data.ContentRepository import com.habitrpg.android.habitica.helpers.* import com.habitrpg.android.habitica.helpers.notifications.PushNotificationManager import com.habitrpg.android.habitica.models.ContentResult import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.prefs.TimePreference import com.habitrpg.android.habitica.ui.activities.ClassSelectionActivity import com.habitrpg.android.habitica.ui.activities.FixCharacterValuesActivity import com.habitrpg.android.habitica.ui.activities.MainActivity import com.habitrpg.android.habitica.ui.activities.PrefsActivity import io.reactivex.functions.Consumer import java.util.* import javax.inject.Inject class PreferencesFragment : BasePreferencesFragment(), SharedPreferences.OnSharedPreferenceChangeListener { @Inject lateinit var contentRepository: ContentRepository @Inject lateinit var soundManager: SoundManager @Inject lateinit var pushNotificationManager: PushNotificationManager @Inject lateinit var configManager: AppConfigManager @Inject lateinit var apiClient: ApiClient private var timePreference: TimePreference? = null private var pushNotificationsPreference: PreferenceScreen? = null private var emailNotificationsPreference: PreferenceScreen? = null private var classSelectionPreference: Preference? = null private var serverUrlPreference: ListPreference? = null override fun onCreate(savedInstanceState: Bundle?) { HabiticaBaseApplication.userComponent?.inject(this) super.onCreate(savedInstanceState) } override fun setupPreferences() { timePreference = findPreference("reminder_time") as? TimePreference val useReminder = preferenceManager.sharedPreferences.getBoolean("use_reminder", false) timePreference?.isEnabled = useReminder pushNotificationsPreference = findPreference("pushNotifications") as? PreferenceScreen val usePushNotifications = preferenceManager.sharedPreferences.getBoolean("usePushNotifications", true) pushNotificationsPreference?.isEnabled = usePushNotifications emailNotificationsPreference = findPreference("emailNotifications") as? PreferenceScreen val useEmailNotifications = preferenceManager.sharedPreferences.getBoolean("useEmailNotifications", true) emailNotificationsPreference?.isEnabled = useEmailNotifications classSelectionPreference = findPreference("choose_class") classSelectionPreference?.isVisible = false serverUrlPreference = findPreference("server_url") as? ListPreference serverUrlPreference?.isVisible = false serverUrlPreference?.summary = preferenceManager.sharedPreferences.getString("server_url", "") val themePreference = findPreference("theme_name") as? ListPreference themePreference?.isVisible = configManager.testingLevel() == AppTestingLevel.ALPHA || BuildConfig.DEBUG themePreference?.summary = themePreference?.entry } override fun onResume() { super.onResume() preferenceManager.sharedPreferences.registerOnSharedPreferenceChangeListener(this) } override fun onPause() { preferenceManager.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this) super.onPause() } override fun onPreferenceTreeClick(preference: Preference): Boolean { when(preference.key) { "logout" -> { context?.let { HabiticaBaseApplication.logout(it) } activity?.finish() } "choose_class" -> { val bundle = Bundle() bundle.putBoolean("isInitialSelection", user?.flags?.classSelected == false) val intent = Intent(activity, ClassSelectionActivity::class.java) intent.putExtras(bundle) if (user?.flags?.classSelected == true && user?.preferences?.disableClasses == false) { context?.let { context -> val builder = AlertDialog.Builder(context) .setMessage(getString(R.string.change_class_confirmation)) .setNegativeButton(getString(R.string.dialog_go_back)) { dialog, _ -> dialog.dismiss() } .setPositiveButton(getString(R.string.change_class)) { _, _ -> startActivityForResult(intent, MainActivity.SELECT_CLASS_RESULT) } val alert = builder.create() alert.show() } } else { startActivityForResult(intent, MainActivity.SELECT_CLASS_RESULT) } return true } "reload_content" -> { @Suppress("DEPRECATION") val dialog = ProgressDialog.show(context, context?.getString(R.string.reloading_content), null, true) contentRepository.retrieveContent(context,true).subscribe({ if (dialog.isShowing) { dialog.dismiss() } }) { throwable -> if (dialog.isShowing) { dialog.dismiss() } RxErrorHandler.reportError(throwable) } } "fixCharacterValues" -> { val intent = Intent(activity, FixCharacterValuesActivity::class.java) activity?.startActivity(intent) } } return super.onPreferenceTreeClick(preference) } @SuppressLint("ObsoleteSdkInt") override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { "use_reminder" -> { val useReminder = sharedPreferences.getBoolean(key, false) timePreference?.isEnabled = useReminder if (useReminder) { TaskAlarmManager.scheduleDailyReminder(context) } else { TaskAlarmManager.removeDailyReminder(context) } } "reminder_time" -> { TaskAlarmManager.removeDailyReminder(context) TaskAlarmManager.scheduleDailyReminder(context) } "usePushNotifications" -> { val userPushNotifications = sharedPreferences.getBoolean(key, false) pushNotificationsPreference?.isEnabled = userPushNotifications if (userPushNotifications) { pushNotificationManager.addPushDeviceUsingStoredToken() } else { pushNotificationManager.removePushDeviceUsingStoredToken() } } "useEmailNotifications" -> { val useEmailNotifications = sharedPreferences.getBoolean(key, false) emailNotificationsPreference?.isEnabled = useEmailNotifications } "cds_time" -> { val timeval = sharedPreferences.getString("cds_time", "00:00") val pieces = timeval?.split(":".toRegex())?.dropLastWhile { it.isEmpty() }?.toTypedArray() if (pieces != null) { val hour = Integer.parseInt(pieces[0]) userRepository.changeCustomDayStart(hour).subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) } } "language" -> { val languageHelper = LanguageHelper(sharedPreferences.getString(key, "en")) Locale.setDefault(languageHelper.locale) val configuration = Configuration() if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { @Suppress("Deprecation") configuration.locale = languageHelper.locale } else { configuration.setLocale(languageHelper.locale) } @Suppress("DEPRECATION") activity?.resources?.updateConfiguration(configuration, activity?.resources?.displayMetrics) userRepository.updateLanguage(user, languageHelper.languageCode ?: "en") .flatMap<ContentResult> { contentRepository.retrieveContent(context,true) } .subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) { val intent = Intent(activity, MainActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(intent) } else { val intent = Intent(activity, MainActivity::class.java) this.startActivity(intent) activity?.finishAffinity() } } "audioTheme" -> { val newAudioTheme = sharedPreferences.getString(key, "off") if (newAudioTheme != null) { compositeSubscription.add(userRepository.updateUser(user, "preferences.sound", newAudioTheme) .subscribe(Consumer { }, RxErrorHandler.handleEmptyError())) soundManager.soundTheme = newAudioTheme soundManager.preloadAllFiles() } } "theme_name" -> { val activity = activity as? PrefsActivity ?: return activity.reload() } "dailyDueDefaultView" -> userRepository.updateUser(user, "preferences.dailyDueDefaultView", sharedPreferences.getBoolean(key, false)) .subscribe(Consumer { }, RxErrorHandler.handleEmptyError()) "server_url" -> { apiClient.updateServerUrl(sharedPreferences.getString(key, "")) findPreference(key).summary = sharedPreferences.getString(key, "") } } } override fun onDisplayPreferenceDialog(preference: Preference) { if (preference is TimePreference) { if (preference.getKey() == "cds_time") { if (fragmentManager?.findFragmentByTag(DayStartPreferenceDialogFragment.TAG) == null) { fragmentManager?.let { DayStartPreferenceDialogFragment.newInstance(this, preference.getKey()) .show(it, DayStartPreferenceDialogFragment.TAG) } } } else { if (fragmentManager?.findFragmentByTag(TimePreferenceDialogFragment.TAG) == null) { fragmentManager?.let { TimePreferenceDialogFragment.newInstance(this, preference.getKey()) .show(it, TimePreferenceDialogFragment.TAG) } } } } else { super.onDisplayPreferenceDialog(preference) } } override fun setUser(user: User?) { super.setUser(user) if (10 <= user?.stats?.lvl ?: 0) { if (user?.flags?.classSelected == true) { if (user.preferences?.disableClasses == true) { classSelectionPreference?.title = getString(R.string.enable_class) } else { classSelectionPreference?.title = getString(R.string.change_class) classSelectionPreference?.summary = getString(R.string.change_class_description) } classSelectionPreference?.isVisible = true } else { classSelectionPreference?.title = getString(R.string.enable_class) classSelectionPreference?.isVisible = true } } val cdsTimePreference = findPreference("cds_time") as? TimePreference cdsTimePreference?.text = user?.preferences?.dayStart.toString() + ":00" findPreference("dailyDueDefaultView").setDefaultValue(user?.preferences?.dailyDueDefaultView) val languagePreference = findPreference("language") as? ListPreference languagePreference?.value = user?.preferences?.language languagePreference?.summary = languagePreference?.entry val audioThemePreference = findPreference("audioTheme") as? ListPreference audioThemePreference?.value = user?.preferences?.sound audioThemePreference?.summary = audioThemePreference?.entry val preference = findPreference("authentication") if (user?.flags?.isVerifiedUsername == true) { preference.layoutResource = R.layout.preference_child_summary preference.summary = context?.getString(R.string.authentication_summary) } else { preference.layoutResource = R.layout.preference_child_summary_error preference.summary = context?.getString(R.string.username_not_confirmed) } if (user?.contributor?.admin == true) { serverUrlPreference?.isVisible = true } } }
gpl-3.0
d0c236337c39d09423b5c9460df82d99
46.343643
161
0.617145
5.89359
false
false
false
false
michaelkourlas/voipms-sms-client
voipms-sms/src/main/kotlin/net/kourlas/voipms_sms/conversation/MessageTextView.kt
1
3583
/* * VoIP.ms SMS * Copyright (C) 2020 Michael Kourlas * * Portions copyright (C) 2006 The Android Open Source Project (taken from * LinkMovementMethod.java) * Portions copyright (C) saket (taken from BetterLinkMovementMethod.java) * * 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 net.kourlas.voipms_sms.conversation import android.annotation.SuppressLint import android.content.Context import android.text.Selection import android.text.Spannable import android.text.style.ClickableSpan import android.util.AttributeSet import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration import androidx.appcompat.widget.AppCompatTextView class MessageTextView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : AppCompatTextView( context, attrs, defStyleAttr ) { private var longClick = false var messageLongClickListener: (() -> Unit)? = null @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent?): Boolean { if (!(event?.action == MotionEvent.ACTION_UP || event?.action == MotionEvent.ACTION_DOWN) ) { if (event?.action == MotionEvent.ACTION_CANCEL) { longClick = false } return super.onTouchEvent(event) } val x = event.x.toInt() - totalPaddingLeft + scrollX val y = event.y.toInt() - totalPaddingTop + scrollY val line = layout?.getLineForVertical(y) ?: return super.onTouchEvent(event) val off = layout?.getOffsetForHorizontal(line, x.toFloat()) ?: return super.onTouchEvent(event) val buffer = text if (buffer !is Spannable) { return super.onTouchEvent(event) } val links = buffer.getSpans(off, off, ClickableSpan::class.java) if (links.isNotEmpty()) { val link = links[0] when (event.action) { MotionEvent.ACTION_UP -> { if (!longClick) { link.onClick(this) } longClick = false } MotionEvent.ACTION_DOWN -> { Selection.setSelection( buffer, buffer.getSpanStart(link), buffer.getSpanEnd(link) ) postDelayed( { longClick = true performHapticFeedback( HapticFeedbackConstants.LONG_PRESS ) messageLongClickListener?.invoke() }, ViewConfiguration.getLongPressTimeout().toLong() ) } } return true } else { Selection.removeSelection(buffer) } return super.onTouchEvent(event) } }
apache-2.0
0284d9ac7d362beabb855e8019f6d71f
33.461538
75
0.589171
5.185239
false
false
false
false
siosio/intellij-community
java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/ModuleHighlightingTest.kt
1
28812
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.java.codeInsight.daemon import com.intellij.codeInsight.daemon.impl.JavaHighlightInfoTypes import com.intellij.codeInsight.daemon.impl.analysis.JavaModuleGraphUtil import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInspection.deprecation.DeprecationInspection import com.intellij.codeInspection.deprecation.MarkedForRemovalInspection import com.intellij.java.testFramework.fixtures.LightJava9ModulesCodeInsightFixtureTestCase import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor import com.intellij.java.testFramework.fixtures.MultiModuleJava9ProjectDescriptor.ModuleDescriptor.* import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiManager import com.intellij.psi.search.ProjectScope import org.assertj.core.api.Assertions.assertThat import java.util.jar.JarFile class ModuleHighlightingTest : LightJava9ModulesCodeInsightFixtureTestCase() { override fun setUp() { super.setUp() addFile("module-info.java", "module M2 { }", M2) addFile("module-info.java", "module M3 { }", M3) } fun testPackageStatement() { highlight("package pkg;") highlight(""" <error descr="A module file should not have 'package' statement">package pkg;</error> module M { }""".trimIndent()) fixes("<caret>package pkg;\nmodule M { }", arrayOf("DeleteElementFix", "FixAllHighlightingProblems")) } fun testSoftKeywords() { addFile("pkg/module/C.java", "package pkg.module;\npublic class C { }") myFixture.configureByText("module-info.java", "module M { exports pkg.module; }") val keywords = myFixture.doHighlighting().filter { it.type == JavaHighlightInfoTypes.JAVA_KEYWORD } assertEquals(2, keywords.size) assertEquals(TextRange(0, 6), TextRange(keywords[0].startOffset, keywords[0].endOffset)) assertEquals(TextRange(11, 18), TextRange(keywords[1].startOffset, keywords[1].endOffset)) } fun testWrongFileName() { highlight("M.java", """/* ... */ <error descr="Module declaration should be in a file named 'module-info.java'">module M</error> { }""") } fun testFileDuplicate() { addFile("pkg/module-info.java", """module M.bis { }""") highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""") } fun testFileDuplicateInTestRoot() { addTestFile("module-info.java", """module M.test { }""") highlight("""<error descr="'module-info.java' already exists in the module">module M</error> { }""") } fun testWrongFileLocation() { highlight("pkg/module-info.java", """<error descr="Module declaration should be located in a module's source root">module M</error> { }""") } fun testIncompatibleModifiers() { highlight(""" module M { requires static transitive M2; requires <error descr="Modifier 'private' not allowed here">private</error> <error descr="Modifier 'volatile' not allowed here">volatile</error> M3; }""".trimIndent()) } fun testAnnotations() { highlight("""@Deprecated <error descr="'@Override' not applicable to module">@Override</error> module M { }""") } fun testDuplicateStatements() { addFile("pkg/main/C.java", "package pkg.main;\npublic class C { }") addFile("pkg/main/Impl.java", "package pkg.main;\npublic class Impl extends C { }") highlight(""" import pkg.main.C; module M { requires M2; <error descr="Duplicate 'requires': M2">requires M2;</error> exports pkg.main; <error descr="Duplicate 'exports': pkg.main">exports pkg. main;</error> opens pkg.main; <error descr="Duplicate 'opens': pkg.main">opens pkg. main;</error> uses C; <error descr="Duplicate 'uses': pkg.main.C">uses pkg. main . /*...*/ C;</error> provides pkg .main .C with pkg.main.Impl; <error descr="Duplicate 'provides': pkg.main.C">provides C with pkg. main. Impl;</error> }""".trimIndent()) } fun testUnusedServices() { addFile("pkg/main/C1.java", "package pkg.main;\npublic class C1 { }") addFile("pkg/main/C2.java", "package pkg.main;\npublic class C2 { }") addFile("pkg/main/C3.java", "package pkg.main;\npublic class C3 { }") addFile("pkg/main/Impl1.java", "package pkg.main;\npublic class Impl1 extends C1 { }") addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 extends C2 { }") addFile("pkg/main/Impl3.java", "package pkg.main;\npublic class Impl3 extends C3 { }") highlight(""" import pkg.main.C2; import pkg.main.C3; module M { uses C2; uses pkg.main.C3; provides pkg.main.<warning descr="Service interface provided but not exported or used">C1</warning> with pkg.main.Impl1; provides pkg.main.C2 with pkg.main.Impl2; provides C3 with pkg.main.Impl3; }""".trimIndent()) } fun testRequires() { addFile("module-info.java", "module M2 { requires M1 }", M2) addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\nAutomatic-Module-Name: all.fours\n", M4) highlight(""" module M1 { requires <error descr="Module not found: M.missing">M.missing</error>; requires <error descr="Cyclic dependence: M1">M1</error>; requires <error descr="Cyclic dependence: M1, M2">M2</error>; requires <error descr="Module is not in dependencies: M3">M3</error>; requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>; requires lib.multi.release; requires lib.named; requires lib.claimed; requires all.fours; }""".trimIndent()) addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\n", M4) highlight("""module M1 { requires <error descr="Module not found: all.fours">all.fours</error>; }""") addFile(JarFile.MANIFEST_NAME, "Manifest-Version: 1.0\nAutomatic-Module-Name: all.fours\n", M4) highlight("""module M1 { requires all.fours; }""") } fun testExports() { addFile("pkg/empty/package-info.java", "package pkg.empty;") addFile("pkg/main/C.java", "package pkg.main;\nclass C { }") highlight(""" module M { exports <error descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</error>; exports <error descr="Package is empty: pkg.empty">pkg.empty</error>; exports pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'exports' target: M2">M2</error>; }""".trimIndent()) addTestFile("pkg/tests/T.java", "package pkg.tests;\nclass T { }", M_TEST) highlight("module-info.java", "module M { exports pkg.tests; }".trimIndent(), M_TEST, true) } fun testOpens() { addFile("pkg/main/C.java", "package pkg.main;\nclass C { }") addFile("pkg/resources/resource.txt", "...") highlight(""" module M { opens <warning descr="Package not found: pkg.missing.unknown">pkg.missing.unknown</warning>; opens pkg.main to <warning descr="Module not found: M.missing">M.missing</warning>, M2, <error descr="Duplicate 'opens' target: M2">M2</error>; opens pkg.resources; }""".trimIndent()) addTestFile("pkg/tests/T.java", "package pkg.tests;\nclass T { }", M_TEST) highlight("module-info.java", "module M { opens pkg.tests; }".trimIndent(), M_TEST, true) } fun testWeakModule() { highlight("""open module M { <error descr="'opens' is not allowed in an open module">opens pkg.missing;</error> }""") } fun testUses() { addFile("pkg/main/C.java", "package pkg.main;\nclass C { void m(); }") addFile("pkg/main/O.java", "package pkg.main;\npublic class O {\n public class I { void m(); }\n}") addFile("pkg/main/E.java", "package pkg.main;\npublic enum E { }") highlight(""" module M { uses pkg.<error descr="Cannot resolve symbol 'main'">main</error>; uses pkg.main.<error descr="Cannot resolve symbol 'X'">X</error>; uses pkg.main.<error descr="'pkg.main.C' is not public in 'pkg.main'. Cannot be accessed from outside package">C</error>; uses pkg.main.<error descr="The service definition is an enum: E">E</error>; uses pkg.main.O.I; uses pkg.main.O.I.<error descr="Cannot resolve symbol 'm'">m</error>; }""".trimIndent()) } fun testProvides() { addFile("pkg/main/C.java", "package pkg.main;\npublic interface C { }") addFile("pkg/main/CT.java", "package pkg.main;\npublic interface CT<T> { }") addFile("pkg/main/Impl1.java", "package pkg.main;\nclass Impl1 { }") addFile("pkg/main/Impl2.java", "package pkg.main;\npublic class Impl2 { }") addFile("pkg/main/Impl3.java", "package pkg.main;\npublic abstract class Impl3 implements C { }") addFile("pkg/main/Impl4.java", "package pkg.main;\npublic class Impl4 implements C {\n public Impl4(String s) { }\n}") addFile("pkg/main/Impl5.java", "package pkg.main;\npublic class Impl5 implements C {\n protected Impl5() { }\n}") addFile("pkg/main/Impl6.java", "package pkg.main;\npublic class Impl6 implements C { }") addFile("pkg/main/Impl7.java", "package pkg.main;\npublic class Impl7 {\n public static void provider();\n}") addFile("pkg/main/Impl8.java", "package pkg.main;\npublic class Impl8 {\n public static C provider();\n}") addFile("pkg/main/Impl9.java", "package pkg.main;\npublic class Impl9 {\n public class Inner implements C { }\n}") addFile("pkg/main/Impl10.java", "package pkg.main;\npublic class Impl10<T> implements CT<T> {\n private Impl10() { }\n public static CT provider();\n}") addFile("module-info.java", "module M2 {\n exports pkg.m2;\n}", M2) addFile("pkg/m2/C.java", "package pkg.m2;\npublic class C { }", M2) addFile("pkg/m2/Impl.java", "package pkg.m2;\npublic class Impl extends C { }", M2) highlight(""" import pkg.main.Impl6; module M { requires M2; provides pkg.main.C with pkg.main.<error descr="Cannot resolve symbol 'NoImpl'">NoImpl</error>; provides pkg.main.C with pkg.main.<error descr="'pkg.main.Impl1' is not public in 'pkg.main'. Cannot be accessed from outside package">Impl1</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation type must be a subtype of the service interface type, or have a public static no-args 'provider' method">Impl2</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation is an abstract class: Impl3">Impl3</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl4">Impl4</error>; provides pkg.main.C with pkg.main.<error descr="The service implementation does not have a public default constructor: Impl5">Impl5</error>; provides pkg.main.C with pkg.main.Impl6, <error descr="Duplicate implementation: pkg.main.Impl6">Impl6</error>; provides pkg.main.C with pkg.main.<error descr="The 'provider' method return type must be a subtype of the service interface type: Impl7">Impl7</error>; provides pkg.main.C with pkg.main.Impl8; provides pkg.main.C with pkg.main.Impl9.<error descr="The service implementation is an inner class: Inner">Inner</error>; provides pkg.main.CT with pkg.main.Impl10; provides pkg.m2.C with pkg.m2.<error descr="The service implementation must be defined in the same module as the provides directive">Impl</error>; }""".trimIndent()) } fun testQuickFixes() { addFile("pkg/main/impl/X.java", "package pkg.main.impl;\npublic class X { }") addFile("module-info.java", "module M2 { exports pkg.m2; }", M2) addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2) addFile("pkg/m3/C3.java", "package pkg.m3;\npublic class C3 { }", M3) addFile("module-info.java", "module M6 { exports pkg.m6; }", M6) addFile("pkg/m6/C6.java", "package pkg.m6;\nimport pkg.m8.*;\nimport java.util.function.*;\npublic class C6 { public void m(Consumer<C8> c) { } }", M6) addFile("module-info.java", "module M8 { exports pkg.m8; }", M8) addFile("pkg/m8/C8.java", "package pkg.m8;\npublic class C8 { }", M8) fixes("module M { requires <caret>M.missing; }", arrayOf()) fixes("module M { requires <caret>M3; }", arrayOf("AddModuleDependencyFix")) fixes("module M { exports pkg.main.impl to <caret>M3; }", arrayOf()) fixes("module M { exports <caret>pkg.missing; }", arrayOf("CreateClassInPackageInModuleFix")) fixes("module M { exports <caret>pkg.m3; }", arrayOf()) fixes("module M { uses pkg.m3.<caret>C3; }", arrayOf("AddModuleDependencyFix")) fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddRequiresDirectiveFix")) addFile("module-info.java", "module M { requires M6; }") addFile("pkg/main/Util.java", "package pkg.main;\nclass Util {\n static <T> void sink(T t) { }\n}") fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>Util::sink); }}", arrayOf("AddRequiresDirectiveFix")) fixes("pkg/main/C.java", "package pkg.main;\nimport pkg.m6.*;class C {{ new C6().m(<caret>t -> Util.sink(t)); }}", arrayOf("AddRequiresDirectiveFix")) addFile("module-info.java", "module M2 { }", M2) fixes("module M { requires M2; uses <caret>pkg.m2.C2; }", arrayOf("AddExportsDirectiveFix")) fixes("pkg/main/C.java", "package pkg.main;\nimport <caret>pkg.m2.C2;", arrayOf("AddExportsDirectiveFix")) addFile("pkg/main/S.java", "package pkg.main;\npublic class S { }") fixes("module M { provides pkg.main.<caret>S with pkg.main.S; }", arrayOf("AddExportsDirectiveFix", "AddUsesDirectiveFix")) } fun testPackageAccessibility() = doTestPackageAccessibility(moduleFileInTests = false, checkFileInTests = false) fun testPackageAccessibilityInNonModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = false) fun testPackageAccessibilityInModularTest() = doTestPackageAccessibility(moduleFileInTests = true, checkFileInTests = true) private fun doTestPackageAccessibility(moduleFileInTests: Boolean = false, checkFileInTests: Boolean = false) { val moduleFileText = "module M { requires M2; requires M6; requires lib.named; requires lib.auto; }" if (moduleFileInTests) addTestFile("module-info.java", moduleFileText) else addFile("module-info.java", moduleFileText) addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2) addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2) addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2) addFile("pkg/sub/C2X.java", "package pkg.sub;\npublic class C2X { }", M2) addFile("pkg/unreachable/C3.java", "package pkg.unreachable;\npublic class C3 { }", M3) addFile("pkg/m4/C4.java", "package pkg.m4;\npublic class C4 { }", M4) addFile("module-info.java", "module M5 { exports pkg.m5; }", M5) addFile("pkg/m5/C5.java", "package pkg.m5;\npublic class C5 { }", M5) addFile("module-info.java", "module M6 { requires transitive M7; exports pkg.m6.inner; }", M6) addFile("pkg/sub/C6X.java", "package pkg.sub;\npublic class C6X { }", M6) addFile("pkg/m6/C6_1.java", "package pkg.m6.inner;\npublic class C6_1 {}", M6) //addFile("pkg/m6/C6_2.kt", "package pkg.m6.inner\n class C6_2", M6) TODO: uncomment to fail the test addFile("module-info.java", "module M7 { exports pkg.m7; }", M7) addFile("pkg/m7/C7.java", "package pkg.m7;\npublic class C7 { }", M7) var checkFileText = """ import pkg.m2.C2; import pkg.m2.*; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.*; import <error descr="Package 'pkg.m4' is declared in the unnamed module, but module 'M' does not read it">pkg.m4</error>.C4; import <error descr="Package 'pkg.m5' is declared in module 'M5', but module 'M' does not read it">pkg.m5</error>.C5; import pkg.m7.C7; import <error descr="Package 'pkg.sub' is declared in module 'M2', which does not export it to module 'M'">pkg.sub</error>.*; import <error descr="Package not found: pkg.unreachable">pkg.unreachable</error>.*; import pkg.lib1.LC1; import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.LC1Impl; import <error descr="Package 'pkg.lib1.impl' is declared in module 'lib.named', which does not export it to module 'M'">pkg.lib1.impl</error>.*; import pkg.lib2.LC2; import pkg.lib2.impl.LC2Impl; import static <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make; import java.util.List; import java.util.function.Supplier; import <error descr="Package 'pkg.libInvalid' is declared in module with an invalid name ('lib.invalid.1.2')">pkg.libInvalid</error>.LCInv; import pkg.m6.inner.C6_1; //import pkg.m6.inner.C6_2; /** See also {@link C2Impl#I} and {@link C2Impl#make} */ class C {{ <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.I = 0; <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>.make(); <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.I = 1; <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl.make(); List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>> l1 = null; List<<error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl> l2 = null; Supplier<C2> s1 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">C2Impl</error>::make; Supplier<C2> s2 = <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M'">pkg.m2.impl</error>.C2Impl::make; }} """.trimIndent() if (moduleFileInTests != checkFileInTests) { checkFileText = Regex("(<error [^>]+>)([^<]+)(</error>)").replace(checkFileText) { if (it.value.contains("unreachable")) it.value else it.groups[2]!!.value } } highlight("test.java", checkFileText, isTest = checkFileInTests) } fun testPackageAccessibilityOverTestScope() { addFile("module-info.java", "module M2 { exports pkg.m2; exports pkg.m2.impl to close.friends.only; }", M2) addFile("pkg/m2/C2.java", "package pkg.m2;\npublic class C2 { }", M2) addFile("pkg/m2/impl/C2Impl.java", "package pkg.m2.impl;\nimport pkg.m2.C2;\npublic class C2Impl { public static int I; public static C2 make() {} }", M2) highlight("module-info.java", "module M.test { requires M2; }", M_TEST, isTest = true) val highlightText = """ import pkg.m2.C2; import pkg.m2.*; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M.test'">pkg.m2.impl</error>.C2Impl; import <error descr="Package 'pkg.m2.impl' is declared in module 'M2', which does not export it to module 'M.test'">pkg.m2.impl</error>.*; """.trimIndent() highlight("test.java", highlightText, M_TEST, isTest = true) } fun testPrivateJdkPackage() { addFile("module-info.java", "module M { }") highlight("test.java", """ import <error descr="Package 'jdk.internal' is declared in module 'java.base', which does not export it to module 'M'">jdk.internal</error>.*; """.trimIndent()) } fun testPrivateJdkPackageFromUnnamed() { highlight("test.java", """ import <error descr="Package 'jdk.internal' is declared in module 'java.base', which does not export it to the unnamed module">jdk.internal</error>.*; """.trimIndent()) } fun testNonRootJdkModule() { highlight("test.java", """ import <error descr="Package 'java.non.root' is declared in module 'java.non.root', which is not in the module graph">java.non.root</error>.*; """.trimIndent()) } fun testUpgradeableModuleOnClasspath() { highlight("test.java", """ import java.xml.bind.*; import java.xml.bind.C; """.trimIndent()) } fun testUpgradeableModuleOnModulePath() { myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection()) highlight(""" module M { requires <error descr="'java.xml.bind' is deprecated and marked for removal">java.xml.bind</error>; requires java.xml.ws; }""".trimIndent()) } fun testLinearModuleGraphBug() { addFile("module-info.java", "module M6 { requires M7; }", M6) addFile("module-info.java", "module M7 { }", M7) highlight("module M { requires M6; }") } fun testCorrectedType() { addFile("module-info.java", "module M { requires M6; requires lib.named; }") addFile("module-info.java", "module M6 { requires lib.named; exports pkg;}", M6) addFile("pkg/A.java", "package pkg; public class A {public static void foo(java.util.function.Supplier<pkg.lib1.LC1> f){}}", M6) highlight("pkg/Usage.java","import pkg.lib1.LC1; class Usage { {pkg.A.foo(LC1::new);} }") } fun testDeprecations() { myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection()) addFile("module-info.java", "@Deprecated module M2 { }", M2) highlight("""module M { requires <warning descr="'M2' is deprecated">M2</warning>; }""") } fun testMarkedForRemoval() { myFixture.enableInspections(DeprecationInspection(), MarkedForRemovalInspection()) addFile("module-info.java", "@Deprecated(forRemoval=true) module M2 { }", M2) highlight("""module M { requires <error descr="'M2' is deprecated and marked for removal">M2</error>; }""") } fun testPackageConflicts() { addFile("pkg/collision2/C2.java", "package pkg.collision2;\npublic class C2 { }", M2) addFile("pkg/collision4/C4.java", "package pkg.collision4;\npublic class C4 { }", M4) addFile("pkg/collision7/C7.java", "package pkg.collision7;\npublic class C7 { }", M7) addFile("module-info.java", "module M2 { exports pkg.collision2; }", M2) addFile("module-info.java", "module M4 { exports pkg.collision4 to M88; }", M4) addFile("module-info.java", "module M6 { requires transitive M7; }", M6) addFile("module-info.java", "module M7 { exports pkg.collision7 to M6; }", M7) addFile("module-info.java", "module M { requires M2; requires M4; requires M6; requires lib.auto; }") highlight("test1.java", """<error descr="Package 'pkg.collision2' exists in another module: M2">package pkg.collision2;</error>""") highlight("test2.java", """package pkg.collision4;""") highlight("test3.java", """package pkg.collision7;""") highlight("test4.java", """<error descr="Package 'java.util' exists in another module: java.base">package java.util;</error>""") highlight("test5.java", """<error descr="Package 'pkg.lib2' exists in another module: lib.auto">package pkg.lib2;</error>""") } fun testClashingReads1() { addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2) addFile("pkg/collision/C7.java", "package pkg.collision;\npublic class C7 { }", M7) addFile("module-info.java", "module M2 { exports pkg.collision; }", M2) addFile("module-info.java", "module M6 { requires transitive M7; }", M6) addFile("module-info.java", "module M7 { exports pkg.collision; }", M7) highlight(""" <error descr="Module 'M' reads package 'pkg.collision' from both 'M2' and 'M7'">module M</error> { requires M2; requires M6; }""".trimIndent()) } fun testClashingReads2() { addFile("pkg/collision/C2.java", "package pkg.collision;\npublic class C2 { }", M2) addFile("pkg/collision/C4.java", "package pkg.collision;\npublic class C4 { }", M4) addFile("module-info.java", "module M2 { exports pkg.collision; }", M2) addFile("module-info.java", "module M4 { exports pkg.collision to somewhere; }", M4) highlight("module M { requires M2; requires M4; }") } fun testClashingReads3() { addFile("pkg/lib2/C2.java", "package pkg.lib2;\npublic class C2 { }", M2) addFile("module-info.java", "module M2 { exports pkg.lib2; }", M2) highlight(""" <error descr="Module 'M' reads package 'pkg.lib2' from both 'M2' and 'lib.auto'">module M</error> { requires M2; requires <warning descr="Ambiguous module reference: lib.auto">lib.auto</warning>; }""".trimIndent()) } fun testClashingReads4() { addFile("module-info.java", "module M2 { requires transitive lib.auto; }", M2) addFile("module-info.java", "module M4 { requires transitive lib.auto; }", M4) highlight("module M { requires M2; requires M4; }") } fun testInaccessibleMemberType() { addFile("module-info.java", "module C { exports pkg.c; }", M8) addFile("module-info.java", "module B { requires C; exports pkg.b; }", M6) addFile("module-info.java", "module A { requires B; }") addFile("pkg/c/C.java", "package pkg.c;\npublic class C { }", M8) addFile("pkg/b/B.java", """ package pkg.b; import pkg.c.C; public class B { private static class I { } public C f1; public I f2; public C m1(C p1, Class<? extends C> p2) { return new C(); } public I m2(I p1, Class<? extends I> p2) { return new I(); } }""".trimIndent(), M6) highlight("pkg/a/A.java", """ package pkg.a; import pkg.b.B; public class A { void test() { B exposer = new B(); exposer.f1 = null; exposer.f2 = null; Object o1 = exposer.m1(null, null); Object o2 = exposer.m2(null, null); } }""".trimIndent()) } fun testAccessingDefaultPackage() { addFile("X.java", "public class X {\n public static class XX extends X { }\n}") highlight(""" module M { uses <error descr="Class 'X' is in the default package">X</error>; provides <error descr="Class 'X' is in the default package">X</error> with <error descr="Class 'X' is in the default package">X</error>.XX; }""".trimIndent()) } fun testLightModuleDescriptorCaching() { val libClass = myFixture.javaFacade.findClass("pkg.lib2.LC2", ProjectScope.getLibrariesScope(project))!! val libModule = JavaModuleGraphUtil.findDescriptorByElement(libClass)!! PsiManager.getInstance(project).dropPsiCaches() assertSame(libModule, JavaModuleGraphUtil.findDescriptorByElement(libClass)!!) ProjectRootManager.getInstance(project).incModificationCount() assertNotSame(libModule, JavaModuleGraphUtil.findDescriptorByElement(libClass)!!) } //<editor-fold desc="Helpers."> private fun highlight(text: String) = highlight("module-info.java", text) private fun highlight(path: String, text: String, module: ModuleDescriptor = MAIN, isTest: Boolean = false) { myFixture.configureFromExistingVirtualFile(if (isTest) addTestFile(path, text, module) else addFile(path, text, module)) myFixture.checkHighlighting() } private fun fixes(text: String, fixes: Array<String>) = fixes("module-info.java", text, fixes) private fun fixes(path: String, text: String, fixes: Array<String>) { myFixture.configureFromExistingVirtualFile(addFile(path, text)) val available = myFixture.availableIntentions .map { IntentionActionDelegate.unwrap(it)::class.java } .filter { it.name.startsWith("com.intellij.codeInsight.") } .map { it.simpleName } assertThat(available).containsExactlyInAnyOrder(*fixes) } //</editor-fold> }
apache-2.0
7c19fbf2478c59bed4e1e939977ccd7b
54.729207
204
0.664133
3.631002
false
true
false
false
kivensolo/UiUsingListView
library/network/src/main/java/com/zeke/reactivehttp/exception/HttpException.kt
1
2025
package com.zeke.reactivehttp.exception import com.zeke.reactivehttp.bean.IHttpWrapBean /** * @Author: leavesC * @Date: 2020/10/22 10:37 * @Desc: Exception * @GitHub:https://github.com/leavesC * 对网络请求过程中发生的各类异常情况的包装类, * 任何透传到外部的异常信息均会被封装为 BaseHttpException 类型。 * BaseHttpException 有两个默认子类,分别用于表示服务器异常和本地异常. * * @param errorCode 服务器返回的错误码 或者是 HttpConfig 中定义的本地错误码 * @param errorMessage 服务器返回的异常信息 或者是 请求过程中抛出的信息,是最原始的异常信息 * @param realException 用于当 code 是本地错误码时,存储真实的运行时异常 */ open class BaseHttpException( val errorCode: Int, val errorMessage: String, val realException: Throwable? ) : Exception(errorMessage) { companion object { /** * 此变量用于表示在网络请求过程过程中抛出了异常 */ const val CODE_ERROR_LOCAL_UNKNOWN = -1024520 } /** * 是否是由于服务器返回的 code != successCode 导致的异常 */ val isServerCodeBadException: Boolean get() = this is ServerCodeBadException /** * 是否是由于网络请求过程中抛出的异常(例如:服务器返回的 Json 解析失败) */ val isLocalBadException: Boolean get() = this is LocalBadException } /** * API 请求成功了,但 code != successCode * @param errorCode * @param errorMessage */ class ServerCodeBadException( errorCode: Int, errorMessage: String ) : BaseHttpException(errorCode, errorMessage, null) { constructor(bean: IHttpWrapBean<*>) : this(bean.httpCode, bean.httpMsg) } /** * 请求过程抛出异常 * @param throwable */ class LocalBadException(throwable: Throwable) : BaseHttpException( CODE_ERROR_LOCAL_UNKNOWN, throwable.message ?: "", throwable)
gpl-2.0
1920e1f7540c441c208fdfe9cec56803
22.432836
75
0.687699
3.303158
false
false
false
false
feelfreelinux/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/helpers/EndlessScrollListener.kt
1
794
package io.github.feelfreelinux.wykopmobilny.ui.helpers class EndlessScrollListener( private val linearLayoutManager: androidx.recyclerview.widget.LinearLayoutManager, val listener: () -> Unit ) : androidx.recyclerview.widget.RecyclerView.OnScrollListener() { private val visibleThreshold = 2 private var lastVisibleItem = 0 private var totalItemCount = 0 override fun onScrolled(recyclerView: androidx.recyclerview.widget.RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) totalItemCount = linearLayoutManager.itemCount lastVisibleItem = linearLayoutManager.findLastVisibleItemPosition() // End has been reached. Do something if (totalItemCount <= (lastVisibleItem + visibleThreshold)) listener() } }
mit
61fc477dbff4f325931dd13f31ffc834
40.842105
104
0.748111
5.475862
false
false
false
false
alexeev/jboss-fuse-mirror
tooling/archetype-builder/src/main/kotlin/org/fusesource/tooling/archetype.builder/ArchetypeBuilder.kt
3
13840
package org.fusesource.tooling.archetype.builder import java.io.File import kotlin.dom.* import org.w3c.dom.Element import org.w3c.dom.Node import org.w3c.dom.Document import org.xml.sax.InputSource import java.io.StringReader import java.io.FileWriter import java.util.TreeSet val sourceFileExtensions = hashSet( "bpmn", "drl", "html", "groovy", "jade", "java", "jbpm", "js", "json", "jsp", "kotlin", "ks", "md", "properties", "scala", "ssp", "ts", "txt", "xml" ) val excludeExtensions = hashSet("iml", "iws", "ipr") val sourceCodeDirNames = arrayList("java", "kotlin", "scala") val sourceCodeDirPaths = ( sourceCodeDirNames.map { "src/main/$it" } + sourceCodeDirNames.map { "src/test/$it" } + arrayList("target", "build", "pom.xml", "archetype-metadata.xml")).toSet() public open class ArchetypeBuilder() { public open fun configure(args: Array<String>): Unit { } public open fun generateArchetypes(sourceDir: File, outputDir: File): Unit { println("Generating archetypes from sourceDir: ${sourceDir.canonicalPath}") val files = sourceDir.listFiles() if (files != null) { for (file in files) { if (file.isDirectory()) { var pom = File(file, "pom.xml") if (pom.exists()) { val outputName = file.name.replace("example", "archetype") generateArchetype(file, pom, File(outputDir, outputName)) } } } } } protected open fun generateArchetype(directory: File, pom: File, outputDir: File): Unit { println("Generating archetype at ${outputDir.canonicalPath} from ${directory.canonicalPath}") val srcDir = File(directory, "src/main") val testDir = File(directory, "src/test") var archetypeOutputDir = File(outputDir, "src/main/resources/archetype-resources") var metadataXmlFile = File(directory, "archetype-metadata.xml") var metadataXmlOutFile = File(outputDir, "src/main/resources-filtered/META-INF/maven/archetype-metadata.xml") var replaceFunction = {(s: String) -> s } val mainSrcDir = sourceCodeDirNames.map{ File(srcDir, it) }.find { it.exists() } if (mainSrcDir != null) { // lets find the first directory which contains more than one child // to find the root-most package val rootPackage = findRootPackage(mainSrcDir) if (rootPackage != null) { val packagePath = mainSrcDir.relativePath(rootPackage) val packageName = packagePath.replaceAll("/", ".") // .replaceAll("/", "\\\\.") val regex = packageName.replaceAll("\\.", "\\\\.") replaceFunction = {(s: String) -> s.replaceAll(regex, "\\\${package}") } // lets recursively copy files replacing the package names val outputMainSrc = File(archetypeOutputDir, directory.relativePath(mainSrcDir)) copyCodeFiles(rootPackage, outputMainSrc, replaceFunction) val testSrcDir = sourceCodeDirNames.map{ File(testDir, it) }.find { it.exists() } if (testSrcDir != null) { val rootTestDir = File(testSrcDir, packagePath) val outputTestSrc = File(archetypeOutputDir, directory.relativePath(testSrcDir)) if (rootTestDir.exists()) { copyCodeFiles(rootTestDir, outputTestSrc, replaceFunction) } else { copyCodeFiles(testSrcDir, outputTestSrc, replaceFunction) } } } } copyPom(pom, File(archetypeOutputDir, "pom.xml"), metadataXmlFile, metadataXmlOutFile, replaceFunction) // now lets copy all non-ignored files across copyOtherFiles(directory, directory, archetypeOutputDir, replaceFunction) } /** * Copies all java/kotlin/scala code */ protected open fun copyCodeFiles(srcDir: File, outDir: File,replaceFn: (String) -> String): Unit { if (srcDir.isFile()) { copyFile(srcDir, outDir, replaceFn) } else { outDir.mkdirs() val names = srcDir.list() if (names != null) { for (name in names) { copyCodeFiles(File(srcDir, name), File(outDir, name), replaceFn) } } } } protected open fun copyPom(pom: File, outFile: File, metadataXmlFile: File, metadataXmlOutFile: File, replaceFn: (String) -> String): Unit { val text = replaceFn(pom.readText()) // lets update the XML val doc = parseXml(InputSource(StringReader(text))) val root = doc.documentElement // TODO would be more concise when this fixed http://youtrack.jetbrains.com/issue/KT-2922 //val propertyNameSet = sortedSet<String>() val propertyNameSet: MutableSet<String> = sortedSet<String>() if (root != null) { // remove the parent element val parents = root.elements("parent") if (parents.notEmpty()) { root.removeChild(parents[0]) } // lets find all the property names for (e in root.elements("*")) { val text = e.childrenText val prefix = "\${" if (text.startsWith(prefix)) { val offset = prefix.size val idx = text.indexOf('}', offset + 1) if (idx > 0) { val name = text.substring(offset, idx) if (isValidRequiredPropertyName(name)) { propertyNameSet.add(name) } } } } // now lets replace the contents of some elements (adding new elements if they are not present) val beforeNames = arrayList("artifactId", "version", "packaging", "name", "properties") replaceOrAddElementText(doc, root, "version", "\${version}", beforeNames) replaceOrAddElementText(doc, root, "artifactId", "\${artifactId}", beforeNames) replaceOrAddElementText(doc, root, "groupId", "\${groupId}", beforeNames) } outFile.getParentFile()?.mkdirs() doc.writeXmlString(FileWriter(outFile), true) // lets update the archetype-metadata.xml file val archetypeXmlText = if (metadataXmlFile.exists()) metadataXmlFile.readText() else defaultArchetypeXmlText() val archDoc = parseXml(InputSource(StringReader(archetypeXmlText))) val archRoot = archDoc.documentElement println("Found property names $propertyNameSet") if (archRoot != null) { // lets add all the properties val requiredProperties = replaceOrAddElement(archDoc, archRoot, "requiredProperties", arrayList("fileSets")) // lets add the various properties in for (propertyName in propertyNameSet) { requiredProperties.addText("\n ") requiredProperties.addElement("requiredProperty") { setAttribute("key", propertyName) addText("\n ") addElement("defaultValue") { addText("\${$propertyName}") } addText("\n ") } } requiredProperties.addText("\n ") } metadataXmlOutFile.getParentFile()?.mkdirs() archDoc.writeXmlString(FileWriter(metadataXmlOutFile), true) } protected fun replaceOrAddElementText(doc: Document, parent: Element, name: String, content: String, beforeNames: Iterable<String>): Element { val element = replaceOrAddElement(doc, parent, name, beforeNames) element.text = content return element } protected fun replaceOrAddElement(doc: Document, parent: Element, name: String, beforeNames: Iterable<String>): Element { val children = parent.children() val elements = children.filter { it.nodeName == name } val element = if (elements.isEmpty()) { val newElement = doc.createElement(name)!! var first: Node? = null; for (n in beforeNames) { first = findChild(parent, n) if (first != null) break } /* val before = beforeNames.map{ n -> findChild(parent, n)} val first = before.first */ val node: Node = if (first != null) first!! else parent.getFirstChild()!! val text = doc.createTextNode("\n ")!! parent.insertBefore(text, node) parent.insertBefore(newElement, text) newElement } else { elements[0] } return element as Element } protected fun findChild(parent: Element, n: String): Node? { val children = parent.children() return children.find { it.nodeName == n } } protected fun copyFile(src: File, dest: File, replaceFn: (String) -> String): Unit { if (isSourceFile(src)) { val text = replaceFn(src.readText()) dest.writeText(text) } else { println("Not a source dir as the extention is ${src.extension}") src.copyTo(dest) } } /** * Copies all other source files which are not excluded */ protected open fun copyOtherFiles(projectDir: File, srcDir: File, outDir: File, replaceFn: (String) -> String): Unit { if (isValidFileToCopy(projectDir, srcDir)) { if (srcDir.isFile()) { copyFile(srcDir, outDir, replaceFn) } else { outDir.mkdirs() val names = srcDir.list() if (names != null) { for (name in names) { copyOtherFiles(projectDir, File(srcDir, name), File(outDir, name), replaceFn) } } } } } protected open fun findRootPackage(directory: File): File? { val children = directory.listFiles { isValidSourceFileOrDir(it) } if (children != null) { val results = children.map { findRootPackage(it) }.filter { it != null } if (results.size == 1) { return results[0] } else { return directory } } return null } /** * Returns true if this file is a valid source file; so * excluding things like .svn directories and whatnot */ protected open fun isValidSourceFileOrDir(file: File): Boolean { val name = file.name return !name.startsWith(".") && !excludeExtensions.contains(file.extension) } /** * Returns true if this file is a valid source file name */ protected open fun isSourceFile(file: File): Boolean { val name = file.extension.toLowerCase() return sourceFileExtensions.contains(name) } /** * Is the file a valid file to copy (excludes files starting with a dot, build output * or java/kotlin/scala source code */ protected open fun isValidFileToCopy(projectDir: File, src: File): Boolean { if (isValidSourceFileOrDir(src)) { if (src == projectDir) return true val relative = projectDir.relativePath(src) return !sourceCodeDirPaths.contains(relative) } return false } /** * Returns true if this is a valid archetype property name, so excluding * basedir and maven "project." names */ protected open fun isValidRequiredPropertyName(name: String): Boolean { return name != "basedir" && !name.startsWith("project.") } protected open fun defaultArchetypeXmlText(): String = """<?xml version="1.0" encoding="UTF-8"?> <archetype-descriptor xsi:schemaLocation="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0 http://maven.apache.org/xsd/archetype-descriptor-1.0.0.xsd" name="camel-archetype-java" xmlns="http://maven.apache.org/plugins/maven-archetype-plugin/archetype-descriptor/1.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <requiredProperties/> <fileSets> <fileSet filtered="true" packaged="true" encoding="UTF-8"> <directory>src/main/java</directory> <includes> <include>**/*.java</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory>src/main/resources</directory> <includes> <include>**/*.bpm*</include> <include>**/*.drl</include> <include>**/*.wsdl</include> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </fileSet> <fileSet filtered="true" packaged="true" encoding="UTF-8"> <directory>src/test/java</directory> <includes> <include>**/*.java</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory>src/test/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory>src/data</directory> <includes> <include>**/*.xml</include> </includes> </fileSet> <fileSet filtered="true" encoding="UTF-8"> <directory></directory> <includes> <include>ReadMe.*</include> </includes> </fileSet> </fileSets> </archetype-descriptor> """ }
apache-2.0
ffa92c9c7284e47fb9cfe9f43aa9012c
37.126722
211
0.576951
4.505208
false
false
false
false
JetBrains/kotlin-native
runtime/src/main/kotlin/kotlin/internal/ProgressionUtil.kt
2
2705
/* * Copyright 2010-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 kotlin.internal // a mod b (in arithmetical sense) private fun mod(a: Int, b: Int): Int { val mod = a % b return if (mod >= 0) mod else mod + b } private fun mod(a: Long, b: Long): Long { val mod = a % b return if (mod >= 0) mod else mod + b } // (a - b) mod c private fun differenceModulo(a: Int, b: Int, c: Int): Int { return mod(mod(a, c) - mod(b, c), c) } private fun differenceModulo(a: Long, b: Long, c: Long): Long { return mod(mod(a, c) - mod(b, c), c) } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: * * - either `step > 0` and `start <= end`, * - or `step < 0` and `start >= end`. * * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ @PublishedApi internal fun getProgressionLastElement(start: Int, end: Int, step: Int): Int = when { step > 0 -> if (start >= end) end else end - differenceModulo(end, start, step) step < 0 -> if (start <= end) end else end + differenceModulo(start, end, -step) else -> throw kotlin.IllegalArgumentException("Step is zero.") } /** * Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range * from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative * [step]. * * No validation on passed parameters is performed. The given parameters should satisfy the condition: * * - either `step > 0` and `start <= end`, * - or `step < 0` and `start >= end`. * * @param start first element of the progression * @param end ending bound for the progression * @param step increment, or difference of successive elements in the progression * @return the final element of the progression * @suppress */ @PublishedApi internal fun getProgressionLastElement(start: Long, end: Long, step: Long): Long = when { step > 0 -> if (start >= end) end else end - differenceModulo(end, start, step) step < 0 -> if (start <= end) end else end + differenceModulo(start, end, -step) else -> throw kotlin.IllegalArgumentException("Step is zero.") }
apache-2.0
96223be53e1279373101309907ba6803
36.569444
131
0.678743
3.573316
false
false
false
false
jwren/intellij-community
plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateFieldAction.kt
4
5800
// 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.plugins.groovy.annotator.intentions.elements import com.intellij.codeInsight.daemon.QuickFixBundle.message import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.positionCursor import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageBaseFix.startTemplate import com.intellij.codeInsight.template.Template import com.intellij.codeInsight.template.TemplateEditingAdapter import com.intellij.lang.jvm.JvmLong import com.intellij.lang.jvm.JvmModifier import com.intellij.lang.jvm.actions.* import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiFile import com.intellij.psi.PsiType import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.presentation.java.ClassPresentationUtil.getNameForClass import com.intellij.psi.util.JavaElementKind import com.intellij.psi.util.PsiTreeUtil import com.intellij.psi.util.PsiUtil import org.jetbrains.plugins.groovy.annotator.intentions.GroovyCreateFieldFromUsageHelper import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames internal class CreateFieldAction( target: GrTypeDefinition, request: CreateFieldRequest, private val constantField: Boolean ) : CreateFieldActionBase(target, request), JvmGroupIntentionAction { override fun getActionGroup(): JvmActionGroup = if (constantField) CreateConstantActionGroup else CreateFieldActionGroup override fun getText(): String { val what = request.fieldName val where = getNameForClass(target, false) val kind = if (constantField) JavaElementKind.CONSTANT else JavaElementKind.FIELD return message("create.element.in.class", kind.`object`(), what, where) } override fun invoke(project: Project, editor: Editor?, file: PsiFile?) { GroovyFieldRenderer(project, constantField, target, request).doRender() } } internal val constantModifiers = setOf( JvmModifier.STATIC, JvmModifier.FINAL ) private class GroovyFieldRenderer( val project: Project, val constantField: Boolean, val targetClass: GrTypeDefinition, val request: CreateFieldRequest ) { val helper = GroovyCreateFieldFromUsageHelper() val typeConstraints = createConstraints(project, request.fieldType).toTypedArray() private val modifiersToRender: Collection<JvmModifier> get() { return if (constantField) { if (targetClass.isInterface) { // interface fields are public static final implicitly, so modifiers don't have to be rendered request.modifiers - constantModifiers - visibilityModifiers } else { // render static final explicitly request.modifiers + constantModifiers } } else { // render as is request.modifiers } } fun doRender() { var field = renderField() field = insertField(field) startTemplate(field) } private fun renderField(): GrField { val elementFactory = GroovyPsiElementFactory.getInstance(project) val field = elementFactory.createField(request.fieldName, PsiType.INT) // clean template modifiers field.modifierList?.let { list -> list.firstChild?.let { list.deleteChildRange(it, list.lastChild) } } for (annotation in request.annotations) { field.modifierList?.addAnnotation(annotation.qualifiedName) } // setup actual modifiers for (modifier in modifiersToRender.map(JvmModifier::toPsiModifier)) { PsiUtil.setModifierProperty(field, modifier, true) } if (targetClass is GroovyScriptClass) field.modifierList?.addAnnotation(GroovyCommonClassNames.GROOVY_TRANSFORM_FIELD) if (constantField) { field.initializerGroovy = elementFactory.createExpressionFromText("0", null) } val requestInitializer = request.initializer if (requestInitializer is JvmLong) { field.initializerGroovy = elementFactory.createExpressionFromText("${requestInitializer.longValue}L", null) } return field } private fun insertField(field: GrField): GrField { return helper.insertFieldImpl(targetClass, field, null) } private fun startTemplate(field: GrField) { val targetFile = targetClass.containingFile ?: return val newEditor = positionCursor(field.project, targetFile, field) ?: return val substitutor = request.targetSubstitutor.toPsiSubstitutor(project) val template = helper.setupTemplateImpl(field, typeConstraints, targetClass, newEditor, null, constantField, substitutor) val listener = MyTemplateListener(project, newEditor, targetFile) startTemplate(newEditor, template, project, listener, null) } } private class MyTemplateListener(val project: Project, val editor: Editor, val file: PsiFile) : TemplateEditingAdapter() { override fun templateFinished(template: Template, brokenOff: Boolean) { PsiDocumentManager.getInstance(project).commitDocument(editor.document) val offset = editor.caretModel.offset val psiField = PsiTreeUtil.findElementOfClassAtOffset(file, offset, GrField::class.java, false) ?: return runWriteAction { CodeStyleManager.getInstance(project).reformat(psiField) } editor.caretModel.moveToOffset(psiField.textRange.endOffset - 1) } }
apache-2.0
32f921a7815a39eacd8c503a154e5982
37.926174
158
0.771207
4.707792
false
false
false
false
nimakro/tornadofx
src/main/java/tornadofx/Component.kt
1
49838
@file:Suppress("UNCHECKED_CAST") package tornadofx import javafx.application.HostServices import javafx.beans.binding.BooleanExpression import javafx.beans.property.* import javafx.collections.FXCollections import javafx.concurrent.Task import javafx.event.EventDispatchChain import javafx.event.EventHandler import javafx.event.EventTarget import javafx.fxml.FXMLLoader import javafx.geometry.Orientation import javafx.scene.Node import javafx.scene.Parent import javafx.scene.Scene import javafx.scene.control.* import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.input.Clipboard import javafx.scene.input.KeyCode import javafx.scene.input.KeyCombination import javafx.scene.input.KeyEvent import javafx.scene.input.KeyEvent.KEY_PRESSED import javafx.scene.layout.BorderPane import javafx.scene.layout.Pane import javafx.scene.layout.StackPane import javafx.scene.paint.Paint import javafx.stage.Modality import javafx.stage.Stage import javafx.stage.StageStyle import javafx.stage.Window import javafx.util.Duration import java.io.Closeable import java.io.InputStream import java.io.StringReader import java.net.URL import java.nio.file.Files import java.nio.file.Path import java.util.* import java.util.logging.Logger import java.util.prefs.Preferences import javax.json.Json import kotlin.properties.ReadOnlyProperty import kotlin.reflect.* @Deprecated("Injectable was a misnomer", ReplaceWith("ScopedInstance")) interface Injectable : ScopedInstance interface ScopedInstance interface Configurable { val config: ConfigProperties val configPath: Path fun loadConfig() = ConfigProperties(this).apply { if (Files.exists(configPath)) Files.newInputStream(configPath).use { load(it) } } } class ConfigProperties(val configurable: Configurable) : Properties(), Closeable { fun set(pair: Pair<String, Any?>) { val value = pair.second?.let { (it as? JsonModel)?.toJSON()?.toString() ?: it.toString() } set(pair.first, value) } fun string(key: String, defaultValue: String? = null) = getProperty(key, defaultValue) fun boolean(key: String, defaultValue: Boolean? = false) = getProperty(key)?.toBoolean() ?: defaultValue fun double(key: String, defaultValue: Double? = null) = getProperty(key)?.toDouble() ?: defaultValue fun int(key: String, defaultValue: Int? = null) = getProperty(key)?.toInt() ?: defaultValue fun jsonObject(key: String) = getProperty(key)?.let { Json.createReader(StringReader(it)).readObject() } fun jsonArray(key: String) = getProperty(key)?.let { Json.createReader(StringReader(it)).readArray() } inline fun <reified M : JsonModel> jsonModel(key: String) = jsonObject(key)?.toModel<M>() fun save() { val path = configurable.configPath.apply { if (!Files.exists(parent)) Files.createDirectories(parent) } Files.newOutputStream(path).use { output -> store(output, "") } } override fun close() { save() } } abstract class Component : Configurable { open val scope: Scope = FX.inheritScopeHolder.get() val workspace: Workspace get() = scope.workspace val paramsProperty = SimpleObjectProperty<Map<String, Any?>>(FX.inheritParamHolder.get() ?: mapOf()) val params: Map<String, Any?> get() = paramsProperty.value val subscribedEvents = HashMap<KClass<out FXEvent>, ArrayList<FXEventRegistration>>() /** * Path to component specific configuration settings. Defaults to javaClass.properties inside * the configured configBasePath of the application (By default conf in the current directory). */ override val configPath: Path get() = app.configBasePath.resolve("${javaClass.name}.properties") override val config: ConfigProperties by lazy { loadConfig() } val clipboard: Clipboard by lazy { Clipboard.getSystemClipboard() } val hostServices: HostServices by lazy { FX.application.hostServices } inline fun <reified T : Component> find(vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {}): T = find(T::class, scope, params.toMap()).apply(op) inline fun <reified T : Component> find(params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {}): T = find(T::class, scope, params).apply(op) fun <T : Component> find(type: KClass<T>, params: Map<*, Any?>? = null, op: T.() -> Unit = {}) = find(type, scope, params).apply(op) fun <T : Component> find(type: KClass<T>, vararg params: Pair<*, Any?>, op: T.() -> Unit = {}) = find(type, scope, params.toMap()).apply(op) @JvmOverloads fun <T : Component> find(componentType: Class<T>, params: Map<*, Any?>? = null, scope: Scope = [email protected]): T = find(componentType.kotlin, scope, params) fun <T : Any> k(javaClass: Class<T>): KClass<T> = javaClass.kotlin /** * Store and retrieve preferences. * * Preferences are stored automatically in a OS specific way. * <ul> * <li>Windows stores it in the registry at HKEY_CURRENT_USER/Software/JavaSoft/....</li> * <li>Mac OS stores it at ~/Library/Preferences/com.apple.java.util.prefs.plist</li> * <li>Linux stores it at ~/.java</li> * </ul> */ fun preferences(nodename: String? = null, op: Preferences.() -> Unit) { val node = if (nodename != null) Preferences.userRoot().node(nodename) else Preferences.userNodeForPackage(FX.getApplication(scope)!!.javaClass) op(node) } val properties by lazy { FXCollections.observableHashMap<Any, Any>() } val log by lazy { Logger.getLogger([email protected]) } val app: App get() = FX.application as App private val _messages: SimpleObjectProperty<ResourceBundle> = object : SimpleObjectProperty<ResourceBundle>() { override fun get(): ResourceBundle? { if (super.get() == null) { try { val bundle = ResourceBundle.getBundle([email protected], FX.locale, [email protected], FXResourceBundleControl) (bundle as? FXPropertyResourceBundle)?.inheritFromGlobal() set(bundle) } catch (ex: Exception) { FX.log.fine("No Messages found for ${javaClass.name} in locale ${FX.locale}, using global bundle") set(FX.messages) } } return super.get() } } var messages: ResourceBundle get() = _messages.get() set(value) = _messages.set(value) val resources: ResourceLookup by lazy { ResourceLookup(this) } inline fun <reified T> inject( overrideScope: Scope = scope, vararg params: Pair<String, Any?> ): ReadOnlyProperty<Component, T> where T : Component, T : ScopedInstance = inject(overrideScope, params.toMap()) inline fun <reified T> inject( overrideScope: Scope = scope, params: Map<String, Any?>? = null ): ReadOnlyProperty<Component, T> where T : Component, T : ScopedInstance = object : ReadOnlyProperty<Component, T> { override fun getValue(thisRef: Component, property: KProperty<*>) = find<T>(overrideScope, params) } inline fun <reified T> param(defaultValue: T? = null): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { override fun getValue(thisRef: Component, property: KProperty<*>): T { val param = thisRef.params[property.name] as? T if (param == null) { if (defaultValue != null) return defaultValue @Suppress("ALWAYS_NULL") if (property.returnType.isMarkedNullable) return defaultValue as T throw IllegalStateException("param for name [$property.name] has not been set") } else { return param } } } fun <T : ScopedInstance> setInScope(value: T, scope: Scope = this.scope) = FX.getComponents(scope).put(value.javaClass.kotlin, value) @Deprecated("No need to use the nullableParam anymore, use param instead", ReplaceWith("param(defaultValue)")) inline fun <reified T> nullableParam(defaultValue: T? = null) = param(defaultValue) inline fun <reified T : Fragment> fragment(overrideScope: Scope = scope, vararg params: Pair<String, Any?>): ReadOnlyProperty<Component, T> = fragment(overrideScope, params.toMap()) inline fun <reified T : Fragment> fragment(overrideScope: Scope = scope, params: Map<String, Any?>): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { val fragment: T by lazy { find<T>(overrideScope, params) } override fun getValue(thisRef: Component, property: KProperty<*>): T = fragment } inline fun <reified T : Any> di(name: String? = null): ReadOnlyProperty<Component, T> = object : ReadOnlyProperty<Component, T> { var injected: T? = null override fun getValue(thisRef: Component, property: KProperty<*>): T { val dicontainer = FX.dicontainer ?: throw AssertionError( "Injector is not configured, so bean of type ${T::class} cannot be resolved") return dicontainer.let { if (name != null) { it.getInstance<T>(name) } else { it.getInstance() } }.also { injected = it } } } val primaryStage: Stage get() = FX.getPrimaryStage(scope)!! // This is here for backwards compatibility. Removing it would require an import for the tornadofx.ui version infix fun <T> Task<T>.ui(func: (T) -> Unit) = success(func) @Deprecated("Clashes with Region.background, so runAsync is a better name", ReplaceWith("runAsync"), DeprecationLevel.WARNING) fun <T> background(func: FXTask<*>.() -> T) = task(func = func) /** * Perform the given operation on an ScopedInstance of the specified type asynchronousyly. * * MyController::class.runAsync { functionOnMyController() } ui { processResultOnUiThread(it) } */ inline fun <reified T, R> KClass<T>.runAsync(noinline op: T.() -> R) where T : Component, T : ScopedInstance = task { op(find(scope)) } /** * Perform the given operation on an ScopedInstance class function member asynchronousyly. * * CustomerController::listContacts.runAsync(customerId) { processResultOnUiThread(it) } */ inline fun <reified InjectableType, reified ReturnType> KFunction1<InjectableType, ReturnType>.runAsync(noinline doOnUi: (ReturnType) -> Unit = {}): Task<ReturnType> where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope)) }.apply { ui(doOnUi) } /** * Perform the given operation on an ScopedInstance class function member asynchronousyly. * * CustomerController::listCustomers.runAsync { processResultOnUiThread(it) } */ inline fun <reified InjectableType, reified P1, reified ReturnType> KFunction2<InjectableType, P1, ReturnType>.runAsync(p1: P1, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1) }.apply { ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified ReturnType> KFunction3<InjectableType, P1, P2, ReturnType>.runAsync(p1: P1, p2: P2, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2) }.apply { ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified P3, reified ReturnType> KFunction4<InjectableType, P1, P2, P3, ReturnType>.runAsync(p1: P1, p2: P2, p3: P3, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2, p3) }.apply { ui(doOnUi) } inline fun <reified InjectableType, reified P1, reified P2, reified P3, reified P4, reified ReturnType> KFunction5<InjectableType, P1, P2, P3, P4, ReturnType>.runAsync(p1: P1, p2: P2, p3: P3, p4: P4, noinline doOnUi: (ReturnType) -> Unit = {}) where InjectableType : Component, InjectableType : ScopedInstance = task { invoke(find(scope), p1, p2, p3, p4) }.apply { ui(doOnUi) } /** * Find the given property inside the given ScopedInstance. Useful for assigning a property from a View or Controller * in any Component. Example: * * val person = find(UserController::currentPerson) */ inline fun <reified InjectableType, T> get(prop: KProperty1<InjectableType, T>): T where InjectableType : Component, InjectableType : ScopedInstance { val injectable = find<InjectableType>(scope) return prop.get(injectable) } inline fun <reified InjectableType, T> set(prop: KMutableProperty1<InjectableType, T>, value: T) where InjectableType : Component, InjectableType : ScopedInstance { val injectable = find<InjectableType>(scope) return prop.set(injectable, value) } /** * Runs task in background. If not set directly, looks for `TaskStatus` instance in current scope. */ fun <T> runAsync(status: TaskStatus? = find(scope), func: FXTask<*>.() -> T) = task(status, func) fun <T> runAsync(daemon: Boolean = false, status: TaskStatus? = find(scope), func: FXTask<*>.() -> T) = task(daemon, status, func) @Suppress("UNCHECKED_CAST") inline fun <reified T : FXEvent> subscribe(times: Number? = null, noinline action: EventContext.(T) -> Unit): FXEventRegistration { val registration = FXEventRegistration(T::class, this, times?.toLong(), action as EventContext.(FXEvent) -> Unit) subscribedEvents.getOrPut(T::class) { ArrayList() }.add(registration) val fireNow = (this as? UIComponent)?.isDocked ?: true if (fireNow) FX.eventbus.subscribe<T>(scope, registration) return registration } @Suppress("UNCHECKED_CAST") inline fun <reified T : FXEvent> unsubscribe(noinline action: EventContext.(T) -> Unit) { subscribedEvents[T::class]?.removeAll { it.action == action } FX.eventbus.unsubscribe(action) } fun <T : FXEvent> fire(event: T) { FX.eventbus.fire(event) } } abstract class Controller : Component(), ScopedInstance const val UI_COMPONENT_PROPERTY = "tornadofx.uicomponent" abstract class UIComponent(viewTitle: String? = "", icon: Node? = null) : Component(), EventTarget { override fun buildEventDispatchChain(tail: EventDispatchChain?): EventDispatchChain { throw UnsupportedOperationException("not implemented") } val iconProperty: ObjectProperty<Node> = SimpleObjectProperty(icon) var icon by iconProperty val isDockedProperty: ReadOnlyBooleanProperty = SimpleBooleanProperty() val isDocked by isDockedProperty lateinit var fxmlLoader: FXMLLoader var modalStage: Stage? = null internal var muteDocking = false abstract val root: Parent internal val wrapperProperty = SimpleObjectProperty<Parent>() internal fun getRootWrapper(): Parent = wrapperProperty.value ?: root private var isInitialized = false val currentWindow: Window? get() = modalStage ?: root.scene?.window ?: FX.primaryStage open val refreshable: BooleanExpression get() = properties.getOrPut("tornadofx.refreshable") { SimpleBooleanProperty(Workspace.defaultRefreshable) } as BooleanExpression open val savable: BooleanExpression get() = properties.getOrPut("tornadofx.savable") { SimpleBooleanProperty(Workspace.defaultSavable) } as BooleanExpression open val closeable: BooleanExpression get() = properties.getOrPut("tornadofx.closeable") { SimpleBooleanProperty(Workspace.defaultCloseable) } as BooleanExpression open val deletable: BooleanExpression get() = properties.getOrPut("tornadofx.deletable") { SimpleBooleanProperty(Workspace.defaultDeletable) } as BooleanExpression open val creatable: BooleanExpression get() = properties.getOrPut("tornadofx.creatable") { SimpleBooleanProperty(Workspace.defaultCreatable) } as BooleanExpression open val complete: BooleanExpression get() = properties.getOrPut("tornadofx.complete") { SimpleBooleanProperty(Workspace.defaultComplete) } as BooleanExpression var isComplete: Boolean get() = complete.value set(value) { (complete as? BooleanProperty)?.value = value } fun wrapper(op: () -> Parent) { FX.ignoreParentBuilder = FX.IgnoreParentBuilder.Once wrapperProperty.value = op() } fun savableWhen(savable: () -> BooleanExpression) { properties["tornadofx.savable"] = savable() } fun completeWhen(complete: () -> BooleanExpression) { properties["tornadofx.complete"] = complete() } fun deletableWhen(deletable: () -> BooleanExpression) { properties["tornadofx.deletable"] = deletable() } fun creatableWhen(creatable: () -> BooleanExpression) { properties["tornadofx.creatable"] = creatable() } fun closeableWhen(closeable: () -> BooleanExpression) { properties["tornadofx.closeable"] = closeable() } fun refreshableWhen(refreshable: () -> BooleanExpression) { properties["tornadofx.refreshable"] = refreshable() } fun whenSaved(onSave: () -> Unit) { properties["tornadofx.onSave"] = onSave } fun whenCreated(onCreate: () -> Unit) { properties["tornadofx.onCreate"] = onCreate } fun whenDeleted(onDelete: () -> Unit) { properties["tornadofx.onDelete"] = onDelete } fun whenRefreshed(onRefresh: () -> Unit) { properties["tornadofx.onRefresh"] = onRefresh } /** * Forward the Workspace button states and actions to the TabPane, which * in turn will forward these states and actions to whatever View is represented * by the currently active Tab. */ fun TabPane.connectWorkspaceActions() { savableWhen { savable } whenSaved { onSave() } creatableWhen { creatable } whenCreated { onCreate() } deletableWhen { deletable } whenDeleted { onDelete() } refreshableWhen { refreshable } whenRefreshed { onRefresh() } } /** * Forward the Workspace button states and actions to the TabPane, which * in turn will forward these states and actions to whatever View is represented * by the currently active Tab. */ fun StackPane.connectWorkspaceActions() { savableWhen { savable } whenSaved { onSave() } creatableWhen { creatable } whenCreated { onCreate() } deletableWhen { deletable } whenDeleted { onDelete() } refreshableWhen { refreshable } whenRefreshed { onRefresh() } } /** * Forward the Workspace button states and actions to the given UIComponent. * This will override the currently active forwarding to the docked UIComponent. * * When another UIComponent is docked, that UIComponent will be the new receiver for the * Workspace states and actions, hence voiding this call. */ fun forwardWorkspaceActions(uiComponent: UIComponent) { savableWhen { uiComponent.savable } whenSaved { uiComponent.onSave() } deletableWhen { uiComponent.deletable } whenDeleted { uiComponent.onDelete() } refreshableWhen { uiComponent.refreshable } whenRefreshed { uiComponent.onRefresh() } } /** * Callback that runs before the Workspace navigates back in the View stack. Return false to veto the navigation. */ open fun onNavigateBack() = true /** * Callback that runs before the Workspace navigates forward in the View stack. Return false to veto the navigation. */ open fun onNavigateForward() = true var onDockListeners: MutableList<(UIComponent) -> Unit>? = null var onUndockListeners: MutableList<(UIComponent) -> Unit>? = null val accelerators = HashMap<KeyCombination, () -> Unit>() fun disableSave() { properties["tornadofx.savable"] = SimpleBooleanProperty(false) } fun disableRefresh() { properties["tornadofx.refreshable"] = SimpleBooleanProperty(false) } fun disableCreate() { properties["tornadofx.creatable"] = SimpleBooleanProperty(false) } fun disableDelete() { properties["tornadofx.deletable"] = SimpleBooleanProperty(false) } fun disableClose() { properties["tornadofx.closeable"] = SimpleBooleanProperty(false) } fun init() { if (isInitialized) return root.properties[UI_COMPONENT_PROPERTY] = this root.parentProperty().addListener({ _, oldParent, newParent -> if (modalStage != null) return@addListener if (newParent == null && oldParent != null && isDocked) callOnUndock() if (newParent != null && newParent != oldParent && !isDocked) { callOnDock() // Call `onTabSelected` if/when we are connected to a Tab and it's selected // Note that this only works for builder constructed tabpanes owningTab?.let { it.selectedProperty()?.onChange { if (it) onTabSelected() } if (it.isSelected) onTabSelected() } } }) root.sceneProperty().addListener({ _, oldParent, newParent -> if (modalStage != null || root.parent != null) return@addListener if (newParent == null && oldParent != null && isDocked) callOnUndock() if (newParent != null && newParent != oldParent && !isDocked) { // Call undock when window closes newParent.windowProperty().onChangeOnce { it?.showingProperty()?.onChange { if (!it && isDocked) callOnUndock() } } callOnDock() } }) isInitialized = true } val currentStage: Stage? get() { val stage = (currentWindow as? Stage) if (stage == null) FX.log.warning { "CurrentStage not available for $this" } return stage } fun setWindowMinSize(width: Number, height: Number) = currentStage?.apply { minWidth = width.toDouble() minHeight = height.toDouble() } fun setWindowMaxSize(width: Number, height: Number) = currentStage?.apply { maxWidth = width.toDouble() maxHeight = height.toDouble() } private val acceleratorListener: EventHandler<KeyEvent> by lazy { EventHandler<KeyEvent> { event -> accelerators.keys.asSequence().find { it.match(event) }?.apply { accelerators[this]?.invoke() event.consume() } } } /** * Add a key listener to the current scene and look for matches against the * `accelerators` map in this UIComponent. */ private fun enableAccelerators() { root.scene?.addEventFilter(KEY_PRESSED, acceleratorListener) root.sceneProperty().addListener { obs, old, new -> old?.removeEventFilter(KEY_PRESSED, acceleratorListener) new?.addEventFilter(KEY_PRESSED, acceleratorListener) } } private fun disableAccelerators() { root.scene?.removeEventFilter(KEY_PRESSED, acceleratorListener) } /** * Called when a Component is detached from the Scene */ open fun onUndock() { } /** * Called when a Component becomes the Scene root or * when its root node is attached to another Component. * @see UIComponent.add */ open fun onDock() { } /** * Called when this Component is hosted by a Tab and the corresponding tab is selected */ open fun onTabSelected() { } open fun onRefresh() { (properties["tornadofx.onRefresh"] as? () -> Unit)?.invoke() } /** * Save callback which is triggered when the Save button in the Workspace * is clicked, or when the Next button in a Wizard is clicked. * * For Wizard pages, you should set the complete state of the Page after save * to signal whether the Wizard can move to the next page or finish. * * For Wizards, you should set the complete state of the Wizard * after save to signal whether the Wizard can be closed. */ open fun onSave() { (properties["tornadofx.onSave"] as? () -> Unit)?.invoke() } /** * Create callback which is triggered when the Creaste button in the Workspace * is clicked. */ open fun onCreate() { (properties["tornadofx.onCreate"] as? () -> Unit)?.invoke() } open fun onDelete() { (properties["tornadofx.onDelete"] as? () -> Unit)?.invoke() } open fun onGoto(source: UIComponent) { source.replaceWith(this) } fun goto(target: UIComponent) { target.onGoto(this) } inline fun <reified T : UIComponent> goto(params: Map<String, Any?>? = null) = find<T>(params).onGoto(this) inline fun <reified T : UIComponent> goto(vararg params: Pair<String, Any?>) { goto<T>(params.toMap()) } internal fun callOnDock() { if (!isInitialized) init() if (muteDocking) return if (!isDocked) attachLocalEventBusListeners() (isDockedProperty as SimpleBooleanProperty).value = true enableAccelerators() onDock() onDockListeners?.forEach { it.invoke(this) } } private fun attachLocalEventBusListeners() { subscribedEvents.forEach { event, actions -> actions.forEach { FX.eventbus.subscribe(event, scope, it) } } } private fun detachLocalEventBusListeners() { subscribedEvents.forEach { event, actions -> actions.forEach { FX.eventbus.unsubscribe(event, it.action) } } } internal fun callOnUndock() { if (muteDocking) return detachLocalEventBusListeners() (isDockedProperty as SimpleBooleanProperty).value = false disableAccelerators() onUndock() onUndockListeners?.forEach { it.invoke(this) } } fun Button.shortcut(combo: String) = shortcut(KeyCombination.valueOf(combo)) @Deprecated("Use shortcut instead", ReplaceWith("shortcut(combo)")) fun Button.accelerator(combo: KeyCombination) = shortcut(combo) /** * Add the key combination as a shortcut for this Button's action. */ fun Button.shortcut(combo: KeyCombination) { accelerators[combo] = { fire() } } /** * Configure an action for a key combination. */ fun shortcut(combo: KeyCombination, action: () -> Unit) { accelerators[combo] = action } fun <T> shortcut(combo: KeyCombination, command: Command<T>, param: T? = null) { accelerators[combo] = { command.execute(param) } } /** * Configure an action for a key combination. */ fun shortcut(combo: String, action: () -> Unit) = shortcut(KeyCombination.valueOf(combo), action) inline fun <reified T : UIComponent> TabPane.tab(scope: Scope = [email protected], noinline op: Tab.() -> Unit = {}) = tab(find<T>(scope), op) inline fun <reified C : UIComponent> BorderPane.top() = top(C::class) fun <C : UIComponent> BorderPane.top(nodeType: KClass<C>) = setRegion(scope, BorderPane::topProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.right() = right(C::class) fun <C : UIComponent> BorderPane.right(nodeType: KClass<C>) = setRegion(scope, BorderPane::rightProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.bottom() = bottom(C::class) fun <C : UIComponent> BorderPane.bottom(nodeType: KClass<C>) = setRegion(scope, BorderPane::bottomProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.left() = left(C::class) fun <C : UIComponent> BorderPane.left(nodeType: KClass<C>) = setRegion(scope, BorderPane::leftProperty, nodeType) inline fun <reified C : UIComponent> BorderPane.center() = center(C::class) fun <C : UIComponent> BorderPane.center(nodeType: KClass<C>) = setRegion(scope, BorderPane::centerProperty, nodeType) fun <S, T> TableColumn<S, T>.cellFormat(formatter: TableCell<S, T>.(T) -> Unit) = cellFormat(scope, formatter) fun <S, T, F : TableCellFragment<S, T>> TableColumn<S, T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) fun <T, F : TreeCellFragment<T>> TreeView<T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) /** * Calculate a unique Node per item and set this Node as the graphic of the TableCell. * * To support this feature, a custom cellFactory is automatically installed, unless an already * compatible cellFactory is found. The cellFactories installed via #cellFormat already knows * how to retrieve cached values. */ fun <S, T> TableColumn<S, T>.cellCache(cachedGraphicProvider: (T) -> Node) = cellCache(scope, cachedGraphicProvider) fun EventTarget.slideshow(defaultTimeout: Duration? = null, scope: Scope = [email protected], op: Slideshow.() -> Unit) = opcr(this, Slideshow(scope, defaultTimeout), op) fun <T, F : ListCellFragment<T>> ListView<T>.cellFragment(fragment: KClass<F>) = cellFragment(scope, fragment) fun <T> ListView<T>.cellFormat(formatter: (ListCell<T>.(T) -> Unit)) = cellFormat(scope, formatter) fun <T> ListView<T>.onEdit(eventListener: ListCell<T>.(EditEventType, T?) -> Unit) = onEdit(scope, eventListener) fun <T> ListView<T>.cellCache(cachedGraphicProvider: (T) -> Node) = cellCache(scope, cachedGraphicProvider) fun <S> TableColumn<S, out Number?>.useProgressBar(afterCommit: (TableColumn.CellEditEvent<S, Number?>) -> Unit = {}) = useProgressBar(scope, afterCommit) fun <T> ComboBox<T>.cellFormat(formatButtonCell: Boolean = true, formatter: ListCell<T>.(T) -> Unit) = cellFormat(scope, formatButtonCell, formatter) inline fun <reified T : UIComponent> Drawer.item( scope: Scope = [email protected], vararg params: Pair<*, Any?>, expanded: Boolean = false, showHeader: Boolean = false, noinline op: DrawerItem.() -> Unit = {} ) = item(T::class, scope, params.toMap(), expanded, showHeader, op) inline fun <reified T : UIComponent> Drawer.item( scope: Scope = [email protected], params: Map<*, Any?>? = null, expanded: Boolean = false, showHeader: Boolean = false, noinline op: DrawerItem.() -> Unit = {} ) = item(T::class, scope, params, expanded, showHeader, op) inline fun <reified T : UIComponent> TableView<*>.placeholder( scope: Scope = [email protected], params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {} ) { placeholder = find(T::class, scope, params).apply(op).root } inline fun <reified T : UIComponent> TableView<*>.placeholder( scope: Scope = [email protected], vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {} ) { placeholder(scope, params.toMap(), op) } inline fun <reified T : UIComponent> ListView<*>.placeholder( scope: Scope = [email protected], params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {} ) { placeholder = find(T::class, scope, params).apply(op).root } inline fun <reified T : UIComponent> ListView<*>.placeholder( scope: Scope = [email protected], vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {} ) { placeholder(scope, params.toMap(), op) } inline fun <reified T : UIComponent> TreeTableView<*>.placeholder( scope: Scope = [email protected], params: Map<*, Any?>? = null, noinline op: T.() -> Unit = {} ) { placeholder = find(T::class, scope, params).apply(op).root } inline fun <reified T : UIComponent> TreeTableView<*>.placeholder( scope: Scope = [email protected], vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {} ) { placeholder(scope, params.toMap(), op) } fun Drawer.item( uiComponent: KClass<out UIComponent>, scope: Scope = [email protected], params: Map<*, Any?>? = null, expanded: Boolean = false, showHeader: Boolean = false, op: DrawerItem.() -> Unit = {} ) = item(find(uiComponent, scope, params), expanded, showHeader, op) fun Drawer.item( uiComponent: KClass<out UIComponent>, scope: Scope = [email protected], vararg params: Pair<*, Any?>, expanded: Boolean = false, showHeader: Boolean = false, op: DrawerItem.() -> Unit = {} ) { item(uiComponent, scope, params.toMap(), expanded, showHeader, op) } fun <T : UIComponent> EventTarget.add(type: KClass<T>, params: Map<*, Any?>? = null, op: T.() -> Unit = {}) { val view = find(type, scope, params) plusAssign(view.root) op(view) } inline fun <reified T : UIComponent> EventTarget.add(vararg params: Pair<*, Any?>, noinline op: T.() -> Unit = {}) = add(T::class, params.toMap(), op) fun <T : UIComponent> EventTarget.add(uiComponent: Class<T>) = add(find(uiComponent)) fun EventTarget.add(uiComponent: UIComponent) = plusAssign(uiComponent.root) fun EventTarget.add(child: Node) = plusAssign(child) operator fun <T : UIComponent> EventTarget.plusAssign(type: KClass<T>) = plusAssign(find(type, scope).root) protected inline fun <reified T : UIComponent> openInternalWindow( scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), params: Map<*, Any?>? = null ) = openInternalWindow(T::class, scope, icon, modal, owner, escapeClosesWindow, closeButton, overlayPaint, params) protected inline fun <reified T : UIComponent> openInternalWindow( scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), vararg params: Pair<*, Any?> ) { openInternalWindow<T>(scope, icon, modal, owner, escapeClosesWindow, closeButton, overlayPaint, params.toMap()) } protected fun openInternalWindow( view: KClass<out UIComponent>, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), params: Map<*, Any?>? = null ) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(find(view, scope, params), owner) protected fun openInternalWindow( view: KClass<out UIComponent>, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), vararg params: Pair<*, Any?> ) { openInternalWindow(view, scope, icon, modal, owner, escapeClosesWindow, closeButton, overlayPaint, params.toMap()) } protected fun openInternalWindow( view: UIComponent, icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4) ) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(view, owner) protected fun openInternalBuilderWindow( title: String, scope: Scope = [email protected], icon: Node? = null, modal: Boolean = true, owner: Node = root, escapeClosesWindow: Boolean = true, closeButton: Boolean = true, overlayPaint: Paint = c("#000", 0.4), rootBuilder: UIComponent.() -> Parent ) = InternalWindow(icon, modal, escapeClosesWindow, closeButton, overlayPaint).open(BuilderFragment(scope, title, rootBuilder), owner) @JvmOverloads fun openWindow( stageStyle: StageStyle = StageStyle.DECORATED, modality: Modality = Modality.NONE, escapeClosesWindow: Boolean = true, owner: Window? = currentWindow, block: Boolean = false, resizable: Boolean? = null) = openModal(stageStyle, modality, escapeClosesWindow, owner, block, resizable) @JvmOverloads fun openModal(stageStyle: StageStyle = StageStyle.DECORATED, modality: Modality = Modality.APPLICATION_MODAL, escapeClosesWindow: Boolean = true, owner: Window? = currentWindow, block: Boolean = false, resizable: Boolean? = null): Stage? { if (modalStage == null) { require(getRootWrapper() is Parent) { "Only Parent Fragments can be opened in a Modal" } modalStage = Stage(stageStyle) // modalStage needs to be set before this code to make close() work in blocking mode with(modalStage!!) { aboutToBeShown = true if (resizable != null) isResizable = resizable titleProperty().bind(titleProperty) initModality(modality) if (owner != null) initOwner(owner) if (getRootWrapper().scene != null) { scene = getRootWrapper().scene [email protected]["tornadofx.scene"] = getRootWrapper().scene } else { Scene(getRootWrapper()).apply { if (escapeClosesWindow) { addEventFilter(KeyEvent.KEY_PRESSED) { if (it.code == KeyCode.ESCAPE) close() } } FX.applyStylesheetsTo(this) val primaryStage = FX.getPrimaryStage(scope) if (primaryStage != null) icons += primaryStage.icons scene = this [email protected]["tornadofx.scene"] = this } } hookGlobalShortcuts() showingProperty().onChange { if (it) { if (owner != null) { x = owner.x + (owner.width / 2) - (scene.width / 2) y = owner.y + (owner.height / 2) - (scene.height / 2) } callOnDock() if (FX.reloadStylesheetsOnFocus || FX.reloadViewsOnFocus) { configureReloading() } aboutToBeShown } else { modalStage = null callOnUndock() } } if (block) showAndWait() else show() } } else { if (!modalStage!!.isShowing) modalStage!!.show() } return modalStage } private fun Stage.configureReloading() { if (FX.reloadStylesheetsOnFocus) reloadStylesheetsOnFocus() if (FX.reloadViewsOnFocus) reloadViewsOnFocus() } @Deprecated("Use close() instead", replaceWith = ReplaceWith("close()")) fun closeModal() = close() fun close() { val internalWindow = root.findParent<InternalWindow>() if (internalWindow != null) { internalWindow.close() return } (modalStage ?: currentStage)?.apply { close() modalStage = null } owningTab?.apply { tabPane?.tabs?.remove(this) } } val owningTab: Tab? get() = properties["tornadofx.tab"] as? Tab open val titleProperty: StringProperty = SimpleStringProperty(viewTitle) var title: String get() = titleProperty.get() ?: "" set(value) = titleProperty.set(value) open val headingProperty: StringProperty = SimpleStringProperty().apply { bind(titleProperty) } var heading: String get() = headingProperty.get() ?: "" set(value) { if (headingProperty.isBound) headingProperty.unbind() headingProperty.set(value) } /** * Load an FXML file from the specified location, or from a file with the same package and name as this UIComponent * if not specified. If the FXML file specifies a controller (handy for content completion in FXML editors) * set the `hasControllerAttribute` parameter to true. This ensures that the `fx:controller` attribute is ignored * by the loader so that this UIComponent can still be the controller for the FXML file. * * Important: If you specify `hasControllerAttribute = true` when infact no `fx:controller` attribute is present, * no controller will be set at all. Make sure to only specify this parameter if you actually have the `fx:controller` * attribute in your FXML. */ fun <T : Node> fxml(location: String? = null, hasControllerAttribute: Boolean = false, root: Any? = null): ReadOnlyProperty<UIComponent, T> = object : ReadOnlyProperty<UIComponent, T> { val value: T = loadFXML(location, hasControllerAttribute, root) override fun getValue(thisRef: UIComponent, property: KProperty<*>) = value } @JvmOverloads fun <T : Node> loadFXML(location: String? = null, hasControllerAttribute: Boolean = false, root: Any? = null): T { val componentType = [email protected] val targetLocation = location ?: componentType.simpleName+".fxml" val fxml = requireNotNull(componentType.getResource(targetLocation)) { "FXML not found for $componentType in $targetLocation" } fxmlLoader = FXMLLoader(fxml).apply { resources = [email protected] if (root != null) setRoot(root) if (hasControllerAttribute) { setControllerFactory { this@UIComponent } } else { setController(this@UIComponent) } } return fxmlLoader.load() } fun <T : Any> fxid(propName: String? = null) = object : ReadOnlyProperty<UIComponent, T> { override fun getValue(thisRef: UIComponent, property: KProperty<*>): T { val key = propName ?: property.name val value = thisRef.fxmlLoader.namespace[key] if (value == null) { log.warning("Property $key of $thisRef was not resolved because there is no matching fx:id in ${thisRef.fxmlLoader.location}") } else { return value as T } throw IllegalArgumentException("Property $key does not match fx:id declaration") } } inline fun <reified T : Parent> EventTarget.include(scope: Scope = [email protected], hasControllerAttribute: Boolean = false, location: String): T { val loader = object : Fragment() { override val scope = scope override val root: T by fxml(location, hasControllerAttribute) } addChildIfPossible(loader.root) return loader.root } /** * Create an fragment by supplying an inline builder expression and optionally open it if the openModality is specified. A fragment can also be assigned * to an existing node hierarchy using `add()` or `this += inlineFragment {}`, or you can specify the behavior inside it using `Platform.runLater {}` before * you return the root node for the builder fragment. */ fun builderFragment( title: String = "", scope: Scope = [email protected], rootBuilder: UIComponent.() -> Parent ) = BuilderFragment(scope, title, rootBuilder) fun builderWindow( title: String = "", modality: Modality = Modality.APPLICATION_MODAL, stageStyle: StageStyle = StageStyle.DECORATED, scope: Scope = [email protected], owner: Window? = currentWindow, rootBuilder: UIComponent.() -> Parent ) = builderFragment(title, scope, rootBuilder).apply { openWindow(modality = modality, stageStyle = stageStyle, owner = owner) } fun dialog( title: String = "", modality: Modality = Modality.APPLICATION_MODAL, stageStyle: StageStyle = StageStyle.DECORATED, scope: Scope = [email protected], owner: Window? = currentWindow, labelPosition: Orientation = Orientation.HORIZONTAL, builder: StageAwareFieldset.() -> Unit ): Stage? { val fragment = builderFragment(title, scope, { form() }) val fieldset = StageAwareFieldset(title, labelPosition) fragment.root.add(fieldset) fieldset.stage = fragment.openWindow(modality = modality, stageStyle = stageStyle, owner = owner)!! builder(fieldset) fieldset.stage.sizeToScene() return fieldset.stage } inline fun <reified T : UIComponent> replaceWith( transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false ) = replaceWith(T::class, transition, sizeToScene, centerOnScreen) fun <T : UIComponent> replaceWith( component: KClass<T>, transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false ) = replaceWith(find(component, scope), transition, sizeToScene, centerOnScreen) /** * Replace this component with another, optionally using a transition animation. * * @param replacement The component that will replace this one * @param transition The [ViewTransition] used to animate the transition * @return Whether or not the transition will run */ fun replaceWith( replacement: UIComponent, transition: ViewTransition? = null, sizeToScene: Boolean = false, centerOnScreen: Boolean = false ) = root.replaceWith(replacement.root, transition, sizeToScene, centerOnScreen) { if (root == root.scene?.root) (root.scene.window as? Stage)?.titleProperty()?.cleanBind(replacement.titleProperty) } private fun undockFromParent(replacement: UIComponent) { (replacement.root.parent as? Pane)?.children?.remove(replacement.root) } } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenDocked(listener: (U) -> Unit) { if (onDockListeners == null) onDockListeners = mutableListOf() onDockListeners!!.add(listener as (UIComponent) -> Unit) } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenDockedOnce(listener: (U) -> Unit) { if (onDockListeners == null) onDockListeners = mutableListOf() onDockListeners!!.add { onDockListeners!!.remove(listener) listener(this) } } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenUndocked(listener: (U) -> Unit) { if (onUndockListeners == null) onUndockListeners = mutableListOf() onUndockListeners!!.add(listener as (UIComponent) -> Unit) } @Suppress("UNCHECKED_CAST") fun <U : UIComponent> U.whenUndockedOnce(listener: (U) -> Unit) { if (onUndockListeners == null) onUndockListeners = mutableListOf() onUndockListeners!!.add { onUndockListeners!!.remove(listener) listener(this) } } abstract class Fragment @JvmOverloads constructor(title: String? = null, icon: Node? = null) : UIComponent(title, icon) abstract class View @JvmOverloads constructor(title: String? = null, icon: Node? = null) : UIComponent(title, icon), ScopedInstance class ResourceLookup(val component: Any) { operator fun get(resource: String): String = component.javaClass.getResource(resource).toExternalForm() fun url(resource: String): URL = component.javaClass.getResource(resource) fun stream(resource: String): InputStream = component.javaClass.getResourceAsStream(resource) fun image(resource: String): Image = Image(stream(resource)) fun imageview(resource: String, lazyload: Boolean = false): ImageView = ImageView(Image(url(resource).toExternalForm(), lazyload)) fun json(resource: String) = stream(resource).toJSON() fun jsonArray(resource: String) = stream(resource).toJSONArray() fun text(resource: String): String = stream(resource).use { it.bufferedReader().readText() } } class BuilderFragment(overrideScope: Scope, title: String, rootBuilder: Fragment.() -> Parent) : Fragment(title) { override val scope = overrideScope override val root = rootBuilder(this) }
apache-2.0
e97741736ab50091cc345a32cb44a2ed
41.092905
247
0.636101
4.519224
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/paste/EditorFileDropHandler.kt
2
4608
// 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.intellij.plugins.markdown.editor.paste import com.intellij.ide.dnd.FileCopyPasteUtil import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.* import com.intellij.openapi.editor.actionSystem.EditorActionManager import com.intellij.openapi.fileTypes.FileTypeRegistry import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiFile import com.intellij.psi.util.PsiEditorUtil import com.intellij.refactoring.RefactoringBundle import org.intellij.images.fileTypes.ImageFileTypeManager import org.intellij.images.fileTypes.impl.SvgFileType import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.editor.images.ImageUtils import org.intellij.plugins.markdown.editor.runForEachCaret import org.intellij.plugins.markdown.lang.MarkdownLanguageUtils.isMarkdownLanguage import java.awt.datatransfer.Transferable import java.net.URLEncoder import java.nio.charset.Charset import java.nio.file.Path import kotlin.io.path.extension import kotlin.io.path.name import kotlin.io.path.relativeTo internal class EditorFileDropHandler: CustomFileDropHandler() { override fun canHandle(transferable: Transferable, editor: Editor?): Boolean { if (editor == null || !editor.document.isWritable) { return false } val file = PsiEditorUtil.getPsiFile(editor) return file.language.isMarkdownLanguage() } override fun handleDrop(transferable: Transferable, editor: Editor?, project: Project?): Boolean { if (editor == null || project == null) { return false } val file = PsiEditorUtil.getPsiFile(editor) if (!file.language.isMarkdownLanguage() || !editor.document.isWritable) { return false } val files = FileCopyPasteUtil.getFiles(transferable)?.asSequence() ?: return false val content = buildTextContent(files, file) val document = editor.document runWriteAction { handleReadOnlyModificationException(project, document) { executeCommand(project, commandName) { editor.caretModel.runForEachCaret(reverseOrder = true) { caret -> document.insertString(caret.offset, content) caret.moveToOffset(content.length) } } } } return true } companion object { private val commandName get() = MarkdownBundle.message("markdown.image.file.drop.handler.drop.command.name") internal fun buildTextContent(files: Sequence<Path>, file: PsiFile): String { val imageFileType = ImageFileTypeManager.getInstance().imageFileType val registry = FileTypeRegistry.getInstance() val currentDirectory = file.containingDirectory?.virtualFile?.toNioPath() val relativePaths = files.map { obtainRelativePath(it, currentDirectory) } return relativePaths.joinToString(separator = "\n") { path -> when (registry.getFileTypeByExtension(path.extension)) { imageFileType, SvgFileType.INSTANCE -> createImageLink(path) else -> createFileLink(path) } } } private fun obtainRelativePath(path: Path, currentDirectory: Path?): Path { if (currentDirectory == null) { return path } return path.relativeTo(currentDirectory) } private fun createUri(url: String): String { return URLEncoder.encode(url, Charset.defaultCharset()).replace("+", "%20") } private fun createImageLink(file: Path): String { return ImageUtils.createMarkdownImageText( description = file.name, path = createUri(FileUtil.toSystemIndependentName(file.toString())) ) } private fun createFileLink(file: Path): String { val independentPath = createUri(FileUtil.toSystemIndependentName (file.toString())) return "[${file.name}]($independentPath)" } internal fun handleReadOnlyModificationException(project: Project, document: Document, block: () -> Unit) { try { block.invoke() } catch (exception: ReadOnlyModificationException) { Messages.showErrorDialog(project, exception.localizedMessage, RefactoringBundle.message("error.title")) } catch (exception: ReadOnlyFragmentModificationException) { EditorActionManager.getInstance().getReadonlyFragmentModificationHandler(document).handle(exception) } } } }
apache-2.0
df0b4acef18d3ffa68b693f93738748f
39.778761
158
0.738932
4.687691
false
false
false
false
550609334/Twobbble
app/src/main/java/com/twobbble/view/activity/ImageFullActivity.kt
1
1862
package com.twobbble.view.activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.twobbble.R import com.twobbble.tools.Constant import com.twobbble.tools.DownloadUtils import com.twobbble.tools.ImageLoad import kotlinx.android.synthetic.main.activity_image_full.* import java.io.File class ImageFullActivity : AppCompatActivity() { companion object { val KEY_URL_NORMAL: String = "key_url_normal" val KEY_URL_LOW: String = "KEY_URL_LOW" val KEY_TITLE: String = "key_title" } private var mUrlNormal: String? = null private var mUrlLow: String? = null private var mTitle: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_image_full) mUrlNormal = intent.getStringExtra(KEY_URL_NORMAL) mUrlLow = intent.getStringExtra(KEY_URL_LOW) mTitle = intent.getStringExtra(KEY_TITLE) initView() } private fun initView() { toolbar.inflateMenu(R.menu.image_full_menu) if (mUrlNormal != null) ImageLoad.frescoLoadZoom(mImage, mProgress, mUrlNormal.toString(), mUrlLow, true) } override fun onStart() { super.onStart() bindEvent() } private fun bindEvent() { toolbar.setNavigationOnClickListener { finish() } toolbar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.mDownload -> { val urls = mUrlNormal?.split(".") DownloadUtils.downloadImg(this@ImageFullActivity, mUrlNormal.toString(), "${Constant.IMAGE_DOWNLOAD_PATH}${File.separator}$mTitle.${urls!![urls.size - 1]}") } } true } } }
apache-2.0
4dc3f1a227ed4ed735d65ce5a3b7f27f
30.559322
111
0.629431
4.28046
false
false
false
false
vovagrechka/fucking-everything
alraune/alraune/src/main/java/alraune/fuckaround/FuckAround_doSendOrderForApproval_1.kt
1
4042
package alraune.fuckaround import alraune.* import alraune.entity.* import pieces100.* import vgrechka.* object FuckAround_doSendOrderForApproval_1 { @JvmStatic fun main(args: Array<String>) { clog("--- ${FuckAround_doSendOrderForApproval_1::class.fqnWithoutPackage()} ---") initStandaloneToolMode__envyAda1__drop_create_fuck1() val orderUuid = "f86f0fc4-c7c5-4a97-bf60-1e206a566aa4" val f2 = Fartus2(orderUuid = orderUuid) var approvalTask1 by notNullOnce<Task>() AlDebug.kindaRequest_wait { AlDebug.deleteOrderIfExists(uuid = orderUuid) } AlDebug.kindaRequest_wait { f2.byAnonymousCustomer.fart {ctx-> Context1.get().withProjectStuff({it.copy( newOrder_uuid = orderUuid)}) { val fields = useFields(OrderFields3__killme(), FieldSource.Initial()) CreateOrderPage__killme().let { it.fields = fields fields.accept( contactName = {it.debug_set("Регина Дубовицкая")}, email = {it.debug_set("[email protected]")}, phone = {it.debug_set("+38 (091) 9284485")}, documentType = {it.set(Order.DocumentType.Course)}, documentTitle = {it.debug_set("Пространство и время: сопоставительный анализ предлогов и послелогов")}, documentDetails = {it.debug_set("В любом языке один и тот же предлог может иметь несколько значений, ассоциируемых с ним, и данные значения хранятся в когнитивной базе носителя языка. Категории служебных слов давно ждут серьезных исследований в рамках современной лингвистической парадигмы, поскольку развитие лингвистики предполагает не только появление новых аспектов и новых объектов, но и возврат к давно описанным категориям языка, которые, однако, в свете современных представлений и при использовании современных методик способны дать нам новые знания об уже известном явлении. Такими категориями являются послелог в корейском языке и предлог в русском и английском языках.\n\nКорейский язык является агглютинирующим языком (имеется тенденция к усилению флективности) номинативного строя. Важно отметить, что в корейском языке в передаче грамматических значений велика роль служебных слов, в том числе послелогов.")}, numPages = {it.debug_set("50")}, numSources = {it.debug_set("10")}, documentCategory = {it.set(AlUADocumentCategories.linguisticsID)}, deadline = {it.debug_set(TimePile.daysFromRealNow_stamp(5))})} doCreateOrder__killme(fields) } } } AlDebug.kindaRequest_wait { approvalTask1 = f2.byAnonymousCustomer.sendOrderForReview() } AlDebug.kindaRequest_wait { clog("approvalTask1.id =", approvalTask1.id) val order = dbSelectMaybeOrderByUUID(orderUuid)!! clog("order.data.approvalTaskId =", order.data.approvalTaskID) } clog("\nOK") } }
apache-2.0
8b77e755482c2eca77025ebd3f0fb28b
53.525424
952
0.630401
3.157017
false
false
false
false
smmribeiro/intellij-community
plugins/editorconfig/src/org/editorconfig/language/psi/base/EditorConfigDescribableElementBase.kt
8
2885
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.editorconfig.language.psi.base import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil import com.intellij.psi.PsiReference import org.editorconfig.language.psi.EditorConfigOption import org.editorconfig.language.psi.EditorConfigSection import org.editorconfig.language.psi.interfaces.EditorConfigDescribableElement import org.editorconfig.language.psi.reference.EditorConfigConstantReference import org.editorconfig.language.psi.reference.EditorConfigDeclarationReference import org.editorconfig.language.psi.reference.EditorConfigIdentifierReference import org.editorconfig.language.schema.descriptors.impl.EditorConfigConstantDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigDeclarationDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigReferenceDescriptor import org.editorconfig.language.schema.descriptors.impl.EditorConfigUnionDescriptor import org.editorconfig.language.util.EditorConfigDescriptorUtil import org.editorconfig.language.util.EditorConfigPsiTreeUtil.getParentOfType abstract class EditorConfigDescribableElementBase(node: ASTNode) : ASTWrapperPsiElement(node), EditorConfigDescribableElement { final override val option: EditorConfigOption get() = getParentOfType() ?: throw IllegalStateException() final override val section: EditorConfigSection get() = getParentOfType() ?: throw IllegalStateException() override val describableParent: EditorConfigDescribableElement? get() = parent as? EditorConfigDescribableElement override val declarationSite: String get() { val project = project val header = section.header.text val virtualFile = containingFile.virtualFile ?: return header val fileName = VfsPresentationUtil.getPresentableNameForUI(project, virtualFile) return "$header ($fileName)" } override fun getReference(): PsiReference? { val descriptor = getDescriptor(false) return when (descriptor) { is EditorConfigDeclarationDescriptor -> EditorConfigDeclarationReference(this) is EditorConfigReferenceDescriptor -> EditorConfigIdentifierReference(this, descriptor.id) is EditorConfigConstantDescriptor -> EditorConfigConstantReference(this) is EditorConfigUnionDescriptor -> { if (EditorConfigDescriptorUtil.isConstant(descriptor)) { EditorConfigConstantReference(this) } else { logger<EditorConfigDescribableElementBase>().warn("Got non-constant union") null } } else -> null } } final override fun toString(): String = text }
apache-2.0
a49e0f8fc560b835f8489eb0e15f95cd
45.532258
140
0.8
5.433145
false
true
false
false
smmribeiro/intellij-community
plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/run/configuration/MavenRunConfigurationSettingsEditor.kt
1
27640
// 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.idea.maven.execution.run.configuration import com.intellij.compiler.options.CompileStepBeforeRun import com.intellij.diagnostic.logging.LogsGroupFragment import com.intellij.execution.ExecutionBundle import com.intellij.execution.configurations.RuntimeConfigurationError import com.intellij.execution.impl.RunnerAndConfigurationSettingsImpl import com.intellij.execution.ui.* import com.intellij.ide.plugins.newui.HorizontalLayout import com.intellij.ide.wizard.getCanonicalPath import com.intellij.openapi.externalSystem.service.execution.configuration.* import com.intellij.openapi.externalSystem.service.ui.getSelectedJdkReference import com.intellij.openapi.externalSystem.service.ui.project.path.WorkingDirectoryField import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesFiled import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesInfo import com.intellij.openapi.externalSystem.service.ui.properties.PropertiesTable import com.intellij.openapi.externalSystem.service.ui.setSelectedJdkReference import com.intellij.openapi.externalSystem.service.ui.util.LabeledSettingsFragmentInfo import com.intellij.openapi.externalSystem.service.ui.util.PathFragmentInfo import com.intellij.openapi.externalSystem.service.ui.util.SettingsFragmentInfo import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace import com.intellij.openapi.observable.operations.AnonymousParallelOperationTrace.Companion.task import com.intellij.openapi.options.ShowSettingsUtil import com.intellij.openapi.roots.ui.configuration.SdkComboBox import com.intellij.openapi.roots.ui.configuration.SdkComboBoxModel.Companion.createProjectJdkComboBoxModel import com.intellij.openapi.roots.ui.configuration.SdkLookupProvider import com.intellij.openapi.roots.ui.distribution.DistributionComboBox import com.intellij.openapi.roots.ui.distribution.FileChooserInfo import com.intellij.openapi.ui.TextFieldWithBrowseButton import com.intellij.openapi.util.NlsContexts import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBTextField import com.intellij.ui.dsl.builder.columns import com.intellij.ui.dsl.builder.impl.CollapsibleTitledSeparator import com.intellij.openapi.observable.util.lockOrSkip import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.Nls import org.jetbrains.idea.maven.execution.MavenRunConfiguration import org.jetbrains.idea.maven.execution.MavenRunner import org.jetbrains.idea.maven.execution.MavenRunnerSettings import org.jetbrains.idea.maven.execution.RunnerBundle import org.jetbrains.idea.maven.execution.run.configuration.MavenDistributionsInfo.Companion.asDistributionInfo import org.jetbrains.idea.maven.execution.run.configuration.MavenDistributionsInfo.Companion.asMavenHome import org.jetbrains.idea.maven.project.MavenConfigurableBundle import org.jetbrains.idea.maven.project.MavenGeneralSettings import org.jetbrains.idea.maven.project.MavenProjectBundle import org.jetbrains.idea.maven.project.MavenProjectsManager import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.utils.MavenUtil import org.jetbrains.idea.maven.utils.MavenWslUtil import java.awt.Component import java.util.concurrent.atomic.AtomicBoolean import javax.swing.JCheckBox import javax.swing.JComponent import javax.swing.JLabel import javax.swing.JPanel class MavenRunConfigurationSettingsEditor( runConfiguration: MavenRunConfiguration ) : RunConfigurationFragmentedEditor<MavenRunConfiguration>( runConfiguration, runConfiguration.extensionsManager ) { private val resetOperation = AnonymousParallelOperationTrace() override fun resetEditorFrom(s: RunnerAndConfigurationSettingsImpl) { resetOperation.task { super.resetEditorFrom(s) } } override fun resetEditorFrom(settings: MavenRunConfiguration) { resetOperation.task { super.resetEditorFrom(settings) } } override fun createRunFragments() = SettingsFragmentsContainer.fragments<MavenRunConfiguration> { add(CommonParameterFragments.createRunHeader()) addBeforeRunFragment(CompileStepBeforeRun.ID) addAll(BeforeRunFragment.createGroup()) add(CommonTags.parallelRun()) val workingDirectoryField = addWorkingDirectoryFragment().component().component addCommandLineFragment(workingDirectoryField) addProfilesFragment(workingDirectoryField) addMavenOptionsGroupFragment() addJavaOptionsGroupFragment() add(LogsGroupFragment()) } private val MavenRunConfiguration.generalSettingsOrDefault: MavenGeneralSettings get() = generalSettings ?: MavenProjectsManager.getInstance(project).generalSettings.clone() private val MavenRunConfiguration.runnerSettingsOrDefault: MavenRunnerSettings get() = runnerSettings ?: MavenRunner.getInstance(project).settings.clone() private fun SettingsFragmentsContainer<MavenRunConfiguration>.addMavenOptionsGroupFragment() = addOptionsGroup( "maven.general.options.group", MavenConfigurableBundle.message("maven.run.configuration.general.options.group.name"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenProjectBundle.message("configurable.MavenSettings.display.name"), { generalSettings }, { generalSettingsOrDefault }, { generalSettings = it } ) { val distributionComponent = addDistributionFragment().component().component val userSettingsComponent = addUserSettingsFragment().component().component addLocalRepositoryFragment(distributionComponent, userSettingsComponent) addOutputLevelFragment() addThreadsFragment() addUsePluginRegistryTag() addPrintStacktracesTag() addUpdateSnapshotsTag() addExecuteNonRecursivelyTag() addWorkOfflineTag() addCheckSumPolicyTag() addMultiProjectBuildPolicyTag() } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addJavaOptionsGroupFragment() = addOptionsGroup( "maven.runner.options.group", MavenConfigurableBundle.message("maven.run.configuration.runner.options.group.name"), MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"), RunnerBundle.message("maven.tab.runner"), { runnerSettings }, { runnerSettingsOrDefault }, { runnerSettings = it } ) { addJreFragment() addEnvironmentFragment() addVmOptionsFragment() addPropertiesFragment() addSkipTestsTag() addResolveWorkspaceArtifactsTag() } private fun <S : FragmentedSettings, Settings> SettingsFragmentsContainer<S>.addOptionsGroup( id: String, name: @Nls(capitalization = Nls.Capitalization.Sentence) String, group: @Nls(capitalization = Nls.Capitalization.Title) String, settingsName: @NlsContexts.ConfigurableName String, getSettings: S.() -> Settings?, getDefaultSettings: S.() -> Settings, setSettings: S.(Settings?) -> Unit, configure: SettingsFragmentsContainer<S>.() -> Unit ) = add(object : NestedGroupFragment<S>(id, name, group, { true }) { private val separator = CollapsibleTitledSeparator(group) private val checkBox: JCheckBox private val checkBoxWithLink: JComponent init { val labelText = MavenConfigurableBundle.message("maven.run.configuration.options.group.inherit") @Suppress("HardCodedStringLiteral") val leadingLabelText = labelText.substringBefore("<a>") @Suppress("HardCodedStringLiteral") val linkLabelText = labelText.substringAfter("<a>").substringBefore("</a>") @Suppress("HardCodedStringLiteral") val trailingLabelText = labelText.substringAfter("</a>") checkBox = JCheckBox(leadingLabelText) checkBoxWithLink = JPanel().apply { layout = HorizontalLayout(0) add(checkBox) add(ActionLink(linkLabelText) { val showSettingsUtil = ShowSettingsUtil.getInstance() showSettingsUtil.showSettingsDialog(project, settingsName) }) add(JLabel(trailingLabelText)) } } override fun createChildren() = SettingsFragmentsContainer.fragments<S> { addSettingsEditorFragment( checkBoxWithLink, object : SettingsFragmentInfo { override val settingsId: String = "$id.checkbox" override val settingsName: String? = null override val settingsGroup: String? = null override val settingsPriority: Int = 0 override val settingsType = SettingsEditorFragmentType.EDITOR override val settingsHint: String? = null override val settingsActionHint: String? = null }, { it, _ -> checkBox.isSelected = it.getSettings() == null }, { it, _ -> it.setSettings(if (checkBox.isSelected) null else (it.getSettings() ?: it.getDefaultSettings())) } ) for (fragment in SettingsFragmentsContainer.fragments(configure)) { bind(checkBox, fragment) add(fragment) } } override fun getBuilder() = object : FragmentedSettingsBuilder<S>(children, this, this) { override fun createHeaderSeparator() = separator override fun addLine(component: Component, top: Int, left: Int, bottom: Int) { if (component === checkBoxWithLink) { super.addLine(component, top, left, bottom + TOP_INSET) myGroupInset += LEFT_INSET } else { super.addLine(component, top, left, bottom) } } init { children.forEach { bind(separator, it) } resetOperation.afterOperation { separator.expanded = !checkBox.isSelected } } } }).apply { isRemovable = false } private fun bind(checkBox: JCheckBox, fragment: SettingsEditorFragment<*, *>) { checkBox.addItemListener { val component = fragment.component() if (component != null) { UIUtil.setEnabledRecursively(component, !checkBox.isSelected) } } fragment.addSettingsEditorListener { if (resetOperation.isOperationCompleted()) { checkBox.isSelected = false } } } private fun bind(separator: CollapsibleTitledSeparator, fragment: SettingsEditorFragment<*, *>) { val mutex = AtomicBoolean() separator.onAction { mutex.lockOrSkip { fragment.component.isVisible = fragment.isSelected && separator.expanded fragment.hintComponent?.isVisible = fragment.isSelected && separator.expanded } } fragment.addSettingsEditorListener { mutex.lockOrSkip { if (resetOperation.isOperationCompleted()) { separator.expanded = true } } } } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addSkipTestsTag() { addTag( "maven.skip.tests.tag", MavenConfigurableBundle.message("maven.settings.runner.skip.tests"), MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"), null, { runnerSettingsOrDefault.isSkipTests }, { runnerSettingsOrDefault.isSkipTests = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUsePluginRegistryTag() { addTag( "maven.use.plugin.registry.tag", MavenConfigurableBundle.message("maven.settings.general.use.plugin.registry"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.use.plugin.registry.tooltip"), { generalSettingsOrDefault.isUsePluginRegistry }, { generalSettingsOrDefault.isUsePluginRegistry = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addPrintStacktracesTag() { addTag( "maven.print.stacktraces.tag", MavenConfigurableBundle.message("maven.settings.general.print.stacktraces"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.print.stacktraces.tooltip"), { generalSettingsOrDefault.isPrintErrorStackTraces }, { generalSettingsOrDefault.isPrintErrorStackTraces = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUpdateSnapshotsTag() { addTag( "maven.update.snapshots.tag", MavenConfigurableBundle.message("maven.settings.general.update.snapshots"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.update.snapshots.tooltip"), { generalSettingsOrDefault.isAlwaysUpdateSnapshots }, { generalSettingsOrDefault.isAlwaysUpdateSnapshots = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addResolveWorkspaceArtifactsTag() { addTag( "maven.workspace.artifacts.tag", MavenConfigurableBundle.message("maven.settings.runner.resolve.workspace.artifacts"), MavenConfigurableBundle.message("maven.run.configuration.runner.options.group"), MavenConfigurableBundle.message("maven.settings.runner.resolve.workspace.artifacts.tooltip"), { runnerParameters.isResolveToWorkspace }, { runnerParameters.isResolveToWorkspace = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addExecuteNonRecursivelyTag() { addTag( "maven.execute.non.recursively.tag", MavenConfigurableBundle.message("maven.settings.general.execute.non.recursively"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.execute.recursively.tooltip"), { generalSettingsOrDefault.isNonRecursive }, { generalSettingsOrDefault.isNonRecursive = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addWorkOfflineTag() { addTag( "maven.work.offline.tag", MavenConfigurableBundle.message("maven.settings.general.work.offline"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), MavenConfigurableBundle.message("maven.settings.general.work.offline.tooltip"), { generalSettingsOrDefault.isWorkOffline }, { generalSettingsOrDefault.isWorkOffline = it } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addCheckSumPolicyTag() { addVariantTag( "maven.checksum.policy.tag", MavenConfigurableBundle.message("maven.run.configuration.checksum.policy"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), { generalSettingsOrDefault.checksumPolicy }, { generalSettingsOrDefault.checksumPolicy = it }, { it.displayString } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addOutputLevelFragment() = addVariantFragment( object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.output.level.label") override val settingsId: String = "maven.output.level.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.output.level.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val settingsHint: String? = null override val settingsActionHint: String? = null }, { generalSettingsOrDefault.outputLevel }, { generalSettingsOrDefault.outputLevel = it }, { it.displayString } ).modifyLabeledComponentSize { columns(10) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addMultiProjectBuildPolicyTag() { addVariantTag( "maven.multi.project.build.policy.tag", MavenConfigurableBundle.message("maven.run.configuration.multi.project.build.policy"), MavenConfigurableBundle.message("maven.run.configuration.general.options.group"), { generalSettingsOrDefault.failureBehavior }, { generalSettingsOrDefault.failureBehavior = it }, { it.displayString } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addDistributionFragment() = addDistributionFragment( project, MavenDistributionsInfo(), { asDistributionInfo(generalSettingsOrDefault.mavenHome.ifEmpty { MavenServerManager.BUNDLED_MAVEN_3 }) }, { generalSettingsOrDefault.mavenHome = it?.let(::asMavenHome) ?: MavenServerManager.BUNDLED_MAVEN_3 } ).addValidation { if (!MavenUtil.isValidMavenHome(it.generalSettingsOrDefault.mavenHome)) { throw RuntimeConfigurationError(MavenConfigurableBundle.message("maven.run.configuration.distribution.invalid.home.error")) } } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addWorkingDirectoryFragment() = addWorkingDirectoryFragment( project, MavenWorkingDirectoryInfo(project), { runnerParameters.workingDirPath }, { runnerParameters.workingDirPath = it } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addCommandLineFragment( workingDirectoryField: WorkingDirectoryField ) = addCommandLineFragment( project, MavenCommandLineInfo(project, workingDirectoryField), { runnerParameters.commandLine }, { runnerParameters.commandLine = it } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addEnvironmentFragment() = addEnvironmentFragment( object : LabeledSettingsFragmentInfo { override val editorLabel: String = ExecutionBundle.message("environment.variables.component.title") override val settingsId: String = "maven.environment.variables.fragment" override val settingsName: String = ExecutionBundle.message("environment.variables.fragment.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String = ExecutionBundle.message("environment.variables.fragment.hint") override val settingsActionHint: String = ExecutionBundle.message("set.custom.environment.variables.for.the.process") }, { runnerSettingsOrDefault.environmentProperties }, { runnerSettingsOrDefault.environmentProperties = it }, { runnerSettingsOrDefault.isPassParentEnv }, { runnerSettingsOrDefault.isPassParentEnv = it }, hideWhenEmpty = true ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addVmOptionsFragment() = addVmOptionsFragment( object : LabeledSettingsFragmentInfo { override val editorLabel: String = ExecutionBundle.message("run.configuration.java.vm.parameters.label") override val settingsId: String = "maven.vm.options.fragment" override val settingsName: String = ExecutionBundle.message("run.configuration.java.vm.parameters.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String = ExecutionBundle.message("run.configuration.java.vm.parameters.hint") override val settingsActionHint: String = ExecutionBundle.message("specify.vm.options.for.running.the.application") }, { runnerSettingsOrDefault.vmOptions.ifEmpty { null } }, { runnerSettingsOrDefault.setVmOptions(it) } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addJreFragment() = SdkLookupProvider.getInstance(project, object : SdkLookupProvider.Id {}) .let { sdkLookupProvider -> addRemovableLabeledSettingsEditorFragment( SdkComboBox(createProjectJdkComboBoxModel(project, this@MavenRunConfigurationSettingsEditor)), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.jre.label") override val settingsId: String = "maven.jre.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.jre.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String? = null override val settingsActionHint: String = MavenConfigurableBundle.message("maven.run.configuration.jre.action.hint") }, { getSelectedJdkReference(sdkLookupProvider) }, { setSelectedJdkReference(sdkLookupProvider, it) }, { runnerSettingsOrDefault.jreName }, { runnerSettingsOrDefault.setJreName(it) }, { MavenRunnerSettings.USE_PROJECT_JDK } ) } private fun SettingsFragmentsContainer<MavenRunConfiguration>.addPropertiesFragment() = addLabeledSettingsEditorFragment( PropertiesFiled(project, object : PropertiesInfo { override val dialogTitle: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.title") override val dialogTooltip: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.tooltip") override val dialogLabel: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.label") override val dialogEmptyState: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.empty.state") override val dialogOkButton: String = MavenConfigurableBundle.message("maven.run.configuration.properties.dialog.ok.button") }), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.properties.label") override val settingsId: String = "maven.properties.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.properties.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.runner.options.group") override val settingsHint: String? = null override val settingsActionHint: String? = null }, { it, c -> c.properties = it.runnerSettingsOrDefault.mavenProperties.map { PropertiesTable.Property(it.key, it.value) } }, { it, c -> it.runnerSettingsOrDefault.mavenProperties = c.properties.associate { it.name to it.value } }, { it.runnerSettingsOrDefault.mavenProperties.isNotEmpty() } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addProfilesFragment( workingDirectoryField: WorkingDirectoryField ) = addLabeledSettingsEditorFragment( MavenProfilesFiled(project, workingDirectoryField), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.label") override val settingsId: String = "maven.profiles.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.name") override val settingsGroup: String? = null override val settingsHint: String = MavenConfigurableBundle.message("maven.run.configuration.profiles.hint") override val settingsActionHint: String? = null }, { it, c -> c.profiles = it.runnerParameters.profilesMap }, { it, c -> it.runnerParameters.profilesMap = c.profiles } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addUserSettingsFragment() = addPathFragment( project, object : PathFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.label") override val settingsId: String = "maven.user.settings.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val fileChooserTitle: String = MavenConfigurableBundle.message("maven.run.configuration.user.settings.title") override val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor() override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH }, { generalSettingsOrDefault.userSettingsFile }, { generalSettingsOrDefault.setUserSettingsFile(it) }, { val mavenConfig = MavenProjectsManager.getInstance(project)?.generalSettings?.mavenConfig val userSettings = MavenWslUtil.getUserSettings(project, "", mavenConfig) getCanonicalPath(userSettings.path) } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addLocalRepositoryFragment( distributionComponent: DistributionComboBox, userSettingsComponent: TextFieldWithBrowseButton ) = addPathFragment( project, object : PathFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.label") override val settingsId: String = "maven.local.repository.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val fileChooserTitle: String = MavenConfigurableBundle.message("maven.run.configuration.local.repository.title") override val fileChooserDescriptor = FileChooserDescriptorFactory.createSingleFolderDescriptor() override val fileChooserMacroFilter = FileChooserInfo.DIRECTORY_PATH }, { generalSettingsOrDefault.localRepository }, { generalSettingsOrDefault.setLocalRepository(it) }, { val mavenConfig = MavenProjectsManager.getInstance(project)?.generalSettings?.mavenConfig val distributionInfo = distributionComponent.selectedDistribution val distribution = distributionInfo?.let(::asMavenHome) ?: MavenServerManager.BUNDLED_MAVEN_3 val userSettingsPath = getCanonicalPath(userSettingsComponent.text.trim()) val userSettingsFile = MavenWslUtil.getUserSettings(project, userSettingsPath, mavenConfig) val userSettings = getCanonicalPath(userSettingsFile.path) val localRepository = MavenWslUtil.getLocalRepo(project, "", distribution, userSettings, mavenConfig) getCanonicalPath(localRepository.path) } ) private fun SettingsFragmentsContainer<MavenRunConfiguration>.addThreadsFragment() = addRemovableLabeledTextSettingsEditorFragment( JBTextField(), object : LabeledSettingsFragmentInfo { override val editorLabel: String = MavenConfigurableBundle.message("maven.run.configuration.threads.label") override val settingsId: String = "maven.threads.fragment" override val settingsName: String = MavenConfigurableBundle.message("maven.run.configuration.threads.name") override val settingsGroup: String = MavenConfigurableBundle.message("maven.run.configuration.general.options.group") override val settingsHint: String? = null override val settingsActionHint: String = MavenConfigurableBundle.message("maven.settings.general.thread.count.tooltip") }, { generalSettingsOrDefault.threads }, { generalSettingsOrDefault.threads = it } ).modifyLabeledComponentSize { columns(10) } }
apache-2.0
da69b6c07c90e73ca927b58f8c8b63be
49.347905
158
0.761035
5.187688
false
true
false
false
kerubistan/kerub
src/main/kotlin/com/github/kerubistan/kerub/services/socket/SpringSocketClientConnection.kt
1
2251
package com.github.kerubistan.kerub.services.socket import com.fasterxml.jackson.databind.ObjectMapper import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.messages.EntityMessage import com.github.kerubistan.kerub.model.messages.Message import com.github.kerubistan.kerub.security.EntityAccessController import com.github.kerubistan.kerub.utils.getLogger import io.github.kerubistan.kroki.collections.upsert import org.apache.shiro.subject.Subject import org.springframework.web.socket.CloseStatus import org.springframework.web.socket.TextMessage import org.springframework.web.socket.WebSocketSession import kotlin.reflect.KClass class SpringSocketClientConnection( private val session: WebSocketSession, private val mapper: ObjectMapper, private val entityAccessController: EntityAccessController, private val subject: Subject) : ClientConnection { override fun close() { session.close(CloseStatus.NORMAL) } private var subscriptions: Map<KClass<*>, List<ChannelSubscription>> = services.map { it.key to listOf<ChannelSubscription>() }.toMap() private companion object { private val logger = getLogger() } @Synchronized override fun removeSubscription(channel: String) { val sub = ChannelSubscription.fromChannel(channel) subscriptions = subscriptions.upsert( sub.entityClass, { it - sub }, { listOf() } ) } @Synchronized override fun addSubscription(channel: String) { val sub = ChannelSubscription.fromChannel(channel) subscriptions = subscriptions.upsert( sub.entityClass, { it + sub }, { listOf(sub) } ) } override fun filterAndSend(msg: Message) { if (msg is EntityMessage) { val entity = msg.obj subject.associateWith { entityAccessController.checkAndDo(entity) { val entityClass = entity.javaClass.kotlin as KClass<out Entity<out Any>> val classChannel = channels[entityClass] if (classChannel == null) { logger.warn("Entity type not handled: {}", entityClass) } else { synchronized(subscriptions) { if (subscriptions[entityClass]?.any { it.interested(msg) } == true) session.sendMessage(TextMessage(mapper.writeValueAsString(msg))) } } } }.run() } } }
apache-2.0
37ca1e8599a6f6bf5ad1b6c581b17fbb
29.432432
77
0.749889
3.881034
false
false
false
false
pvarry/intra42
app/src/main/java/com/paulvarry/intra42/ui/galaxy/Galaxy.kt
1
24609
package com.paulvarry.intra42.ui.galaxy import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.graphics.* import android.os.Build import android.util.AttributeSet import android.util.SparseArray import android.view.GestureDetector import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.View import android.widget.Scroller import com.paulvarry.intra42.R import com.paulvarry.intra42.ui.galaxy.model.CircleToDraw import com.paulvarry.intra42.ui.galaxy.model.ProjectDataIntra import java.util.* import kotlin.Comparator import kotlin.math.pow import kotlin.math.roundToInt class Galaxy(context: Context, attrs: AttributeSet) : View(context, attrs) { private var weightPath: Float = 0f private var backgroundColor: Int = 0 private var colorProjectUnavailable: Int = 0 private var colorProjectAvailable: Int = 0 private var colorProjectValidated: Int = 0 private var colorProjectInProgress: Int = 0 private var colorProjectFailed: Int = 0 private var colorProjectTextUnavailable: Int = 0 private var colorProjectTextAvailable: Int = 0 private var colorProjectTextValidated: Int = 0 private var colorProjectTextInProgress: Int = 0 private var colorProjectTextFailed: Int = 0 private val mGestureDetector: GestureDetector private val mScroller: Scroller private val mScrollAnimator: ValueAnimator private val mScaleDetector: ScaleGestureDetector /** * Data for current Galaxy. */ private var data: List<ProjectDataIntra>? = null private var dataCircle: MutableList<CircleToDraw>? = null private var noDataMessage: String = context.getString(R.string.galaxy_not_found) /** * Current scale factor. */ private var mScaleFactor = 1f set(value) { // Don't let the object get too small or too large. field = value.coerceIn(0.1f, 2.5f) } private val mPaintBackground: Paint private val mPaintPath: Paint private val mPaintProject: Paint private val mPaintText: Paint private val position = PointF(0f, 0f) /** * semiWidth is the height of the view divided by 2. */ private var semiHeight: Float = 0.toFloat() /** * semiWidth is the width of the view divided by 2. */ private var semiWidth: Float = 0.toFloat() /** * Compute title of each project once when data is added. * This split the title in multi line to display inside of the circle. */ private var projectTitleComputed: SparseArray<List<String>> = SparseArray(0) /** * Save cache for project position. This is computed once per call of onDraw(); */ private var drawPosComputed: SparseArray<PointF> = SparseArray() /** * Listener for project clicks. */ private var onClickListener: OnProjectClickListener? = null private val isAnimationRunning: Boolean get() = !mScroller.isFinished private var projectDataFirstInternship: ProjectDataIntra? = null private var projectDataFinalInternship: ProjectDataIntra? = null init { val attributes = context.theme.obtainStyledAttributes( attrs, R.styleable.Galaxy, 0, 0) try { val defaultTextColor = Color.parseColor("#3F51B5") backgroundColor = attributes.getColor(R.styleable.Galaxy_colorProjectBackground, 0) colorProjectUnavailable = attributes.getColor(R.styleable.Galaxy_colorProjectUnavailable, 0) colorProjectAvailable = attributes.getColor(R.styleable.Galaxy_colorProjectAvailable, 0) colorProjectValidated = attributes.getColor(R.styleable.Galaxy_colorProjectValidated, 0) colorProjectFailed = attributes.getColor(R.styleable.Galaxy_colorProjectFailed, 0) colorProjectInProgress = attributes.getColor(R.styleable.Galaxy_colorProjectInProgress, 0) colorProjectTextUnavailable = attributes.getColor(R.styleable.Galaxy_colorProjectOnUnavailable, defaultTextColor) colorProjectTextAvailable = attributes.getColor(R.styleable.Galaxy_colorProjectOnAvailable, defaultTextColor) colorProjectTextValidated = attributes.getColor(R.styleable.Galaxy_colorProjectOnValidated, defaultTextColor) colorProjectTextFailed = attributes.getColor(R.styleable.Galaxy_colorProjectOnFailed, defaultTextColor) colorProjectTextInProgress = attributes.getColor(R.styleable.Galaxy_colorProjectOnInProgress, defaultTextColor) weightPath = attributes.getDimension(R.styleable.Galaxy_weightPath, 1f) } finally { attributes.recycle() } mPaintBackground = Paint(Paint.ANTI_ALIAS_FLAG) mPaintBackground.color = backgroundColor mPaintBackground.style = Paint.Style.FILL mPaintPath = Paint(Paint.ANTI_ALIAS_FLAG) mPaintPath.isAntiAlias = true mPaintPath.color = colorProjectUnavailable mPaintPath.strokeWidth = weightPath mPaintPath.style = Paint.Style.STROKE mPaintProject = Paint(Paint.ANTI_ALIAS_FLAG) mPaintProject.isAntiAlias = true mPaintProject.color = colorProjectUnavailable mPaintText = Paint(Paint.ANTI_ALIAS_FLAG) mPaintText.isAntiAlias = true mPaintText.isFakeBoldText = true mPaintText.textAlign = Paint.Align.CENTER mPaintText.textSize = TEXT_HEIGHT * mScaleFactor // Create a Scroller to handle the fling gesture. mScroller = Scroller(context, null, true) // The scroller doesn't have any built-in animation functions--it just supplies // values when we ask it to. So we have to have a way to call it every frame // until the fling ends. This code (ab)uses a ValueAnimator object to generate // a callback on every animation frame. We don't use the animated value at all. mScrollAnimator = ValueAnimator.ofInt(0, 1) mScrollAnimator.addUpdateListener { tickScrollAnimation() } // Create a gesture detector to handle onTouch messages mGestureDetector = GestureDetector(this.context, GestureListener()) // Turn off long press--this control doesn't use it, and if long press is enabled, // you can't scroll for a bit, pause, then scroll some more (the pause is interpreted // as a long press, apparently) mGestureDetector.setIsLongpressEnabled(false) mScaleDetector = ScaleGestureDetector(context, ScaleListener()) onUpdateData() } private fun tickScrollAnimation() { if (!mScroller.isFinished) { mScroller.computeScrollOffset() position.set(mScroller.currX.toFloat(), mScroller.currY.toFloat()) } else { mScrollAnimator.cancel() onScrollFinished() } } private fun onUpdateData() { data?.let { mPaintText.textSize = TEXT_HEIGHT * mScaleFactor projectTitleComputed = SparseArray(it.size) drawPosComputed = SparseArray() it.forEach { projectData -> projectTitleComputed.put(projectData.id, TextCalculator.split(projectData, mPaintText, mScaleFactor)) drawPosComputed.put(projectData.id, PointF()) } } } /** * Called when the user finishes a scroll action. */ private fun onScrollFinished() { decelerate() } /** * Disable hardware acceleration (releases memory) */ private fun decelerate() { setLayerToSW(this) } private fun setLayerToSW(v: View) { if (!v.isInEditMode) { setLayerType(LAYER_TYPE_SOFTWARE, null) } } fun setOnProjectClickListener(onClickListener: OnProjectClickListener) { this.onClickListener = onClickListener } fun setData(data: List<ProjectDataIntra>?, cursusId: Int) { val c = Hack.computeData(data, cursusId) this.data = c?.first this.dataCircle = c?.second if (this.data.isNullOrEmpty()) this.data = null if (data != null) { for (projectData in data) { if (projectData.kind == ProjectDataIntra.Kind.FIRST_INTERNSHIP) projectDataFirstInternship = projectData else if (projectData.kind == ProjectDataIntra.Kind.SECOND_INTERNSHIP) projectDataFinalInternship = projectData } projectDataFirstInternship?.let { it.x = 3680 it.y = 3750 } projectDataFinalInternship?.let { it.x = 4600 it.y = 4600 } try { Collections.sort(data, Comparator { o1, o2 -> if (o1.state == null || o2.state == null) return@Comparator 0 o1.state!!.layerIndex.compareTo(o2.state!!.layerIndex) //TODO }) } catch (e: IllegalArgumentException) { e.printStackTrace() } } onUpdateData() onScrollFinished() invalidate() } fun setMessage(string: String) { data = null this.noDataMessage = string onScrollFinished() invalidate() } /** * Enable hardware acceleration (consumes memory) */ fun accelerate() { setLayerToHW(/*this*/) } private fun setLayerToHW(/*v: View*/) { // if (!v.isInEditMode) { // setLayerType(View.LAYER_TYPE_HARDWARE, null); // } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { // Let the GestureDetector interpret this event var resultGesture = mGestureDetector.onTouchEvent(event) val resultScale = mScaleDetector.onTouchEvent(event) // If the GestureDetector doesn't want this event, do some custom processing. // This code just tries to detect when the user is done scrolling by looking // for ACTION_UP events. if (!resultGesture && !resultScale) { if (event.action == MotionEvent.ACTION_UP) { // User is done scrolling, it's now safe to do things like autocenter stopScrolling() resultGesture = true } } return resultGesture } /** * Force a stop to all motion. Called when the user taps during a fling. */ private fun stopScrolling() { mScroller.forceFinished(true) onScrollFinished() } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { semiHeight = h / 2f semiWidth = w / 2f position.set(0f, 0f) super.onSizeChanged(w, h, oldw, oldh) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) canvas.drawPaint(mPaintBackground) data?.let { onDrawData(canvas, it) } ?: run { onDrawEmpty(canvas) } } private fun onDrawData(canvas: Canvas, data: List<ProjectDataIntra>) { mPaintPath.strokeWidth = weightPath * mScaleFactor mPaintText.textSize = TEXT_HEIGHT * mScaleFactor onDrawDataPath(canvas, data) onDrawDataCircle(canvas) onDrawDataContent(canvas, data) if (mScrollAnimator.isRunning) { tickScrollAnimation() postInvalidate() } } private fun onDrawDataPath(canvas: Canvas, data: List<ProjectDataIntra>) { var startX: Float var startY: Float var stopX: Float var stopY: Float for (projectData in data) { projectData.by?.forEach { by -> by.points?.let { points -> startX = getDrawPosX(points[0][0]) startY = getDrawPosY(points[0][1]) stopX = getDrawPosX(points[1][0]) stopY = getDrawPosY(points[1][1]) canvas.drawLine(startX, startY, stopX, stopY, getPaintPath(projectData.state)) } } } } private fun onDrawDataCircle(canvas: Canvas) { projectDataFirstInternship?.let { canvas.drawCircle( getDrawPosX(3000f), getDrawPosY(3000f), 1000 * mScaleFactor, getPaintPath(it.state)) } projectDataFinalInternship?.let { canvas.drawCircle( getDrawPosX(3000f), getDrawPosY(3000f), 2250 * mScaleFactor, getPaintPath(it.state)) } dataCircle?.forEach { canvas.drawCircle( getDrawPosX(3000f), getDrawPosY(3000f), it.radius * mScaleFactor, getPaintPath(it.state ?: ProjectDataIntra.State.UNAVAILABLE)) } } private fun onDrawDataContent(canvas: Canvas, data: List<ProjectDataIntra>) { for (projectData in data) { projectData.kind?.data?.let { when (it) { is ProjectDataIntra.Kind.DrawType.Rectangle -> drawRectangle(canvas, projectData, it) is ProjectDataIntra.Kind.DrawType.RoundRect -> drawRoundRect(canvas, projectData, it) is ProjectDataIntra.Kind.DrawType.Circle -> drawCircle(canvas, projectData, it) } } } } private fun onDrawEmpty(canvas: Canvas) { mPaintText.color = colorProjectTextAvailable mPaintText.textSize = 50 * mScaleFactor canvas.drawText(noDataMessage, width / 2f, height * 0.8f, mPaintText) } override fun setBackgroundColor(color: Int) { backgroundColor = color invalidate() requestLayout() } private fun getPaintProject(projectState: ProjectDataIntra.State?): Paint { mPaintProject.color = getColorProject(projectState) return mPaintProject } private fun getPaintPath(projectState: ProjectDataIntra.State?): Paint { mPaintPath.color = getColorProject(projectState) return mPaintPath } private fun getPaintProjectText(projectData: ProjectDataIntra): Paint { mPaintText.color = getColorText(projectData.state) mPaintText.textSize = TEXT_HEIGHT * mScaleFactor if (projectData.kind == ProjectDataIntra.Kind.INNER_SATELLITE) { mPaintText.textSize = TEXT_HEIGHT * mScaleFactor * 0.5f } return mPaintText } private fun getColorProject(projectState: ProjectDataIntra.State?): Int { return when (projectState) { ProjectDataIntra.State.DONE -> colorProjectValidated ProjectDataIntra.State.AVAILABLE -> colorProjectAvailable ProjectDataIntra.State.IN_PROGRESS -> colorProjectInProgress ProjectDataIntra.State.UNAVAILABLE -> colorProjectUnavailable ProjectDataIntra.State.FAIL -> colorProjectFailed null -> colorProjectUnavailable } } private fun getColorText(projectState: ProjectDataIntra.State?): Int { return when (projectState) { ProjectDataIntra.State.DONE -> colorProjectTextValidated ProjectDataIntra.State.AVAILABLE -> colorProjectTextAvailable ProjectDataIntra.State.IN_PROGRESS -> colorProjectTextInProgress ProjectDataIntra.State.UNAVAILABLE -> colorProjectTextUnavailable ProjectDataIntra.State.FAIL -> colorProjectTextFailed null -> colorProjectTextUnavailable } } private fun drawProjectTitle(canvas: Canvas, projectData: ProjectDataIntra) { val paintText = getPaintProjectText(projectData) val textToDraw = projectTitleComputed.get(projectData.id) val textHeight = paintText.textSize val posYStartDraw = getDrawPosY(projectData) - textHeight * (textToDraw.size - 1) / 2 var heightTextDraw: Float for (i in textToDraw.indices) { heightTextDraw = posYStartDraw + textHeight * i - (paintText.descent() + paintText.ascent()) / 2 canvas.drawText( textToDraw[i], getDrawPosX(projectData), heightTextDraw, paintText) } } private fun drawCircle(canvas: Canvas, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Circle) { canvas.drawCircle( getDrawPosX(projectData, true), getDrawPosY(projectData, true), data.radius * mScaleFactor, getPaintProject(projectData.state)) drawProjectTitle(canvas, projectData) } private fun drawRectangle(canvas: Canvas, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Rectangle) { val x = getDrawPosX(projectData, true) val y = getDrawPosY(projectData, true) val width = data.width * mScaleFactor val height = data.height * mScaleFactor val left = x - width / 2 val top = y + height / 2 val right = x + width / 2 val bottom = y - height / 2 canvas.drawRect(left, top, right, bottom, getPaintProject(projectData.state)) drawProjectTitle(canvas, projectData) } private fun drawRoundRect(canvas: Canvas, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.RoundRect) { val x = getDrawPosX(projectData, true) val y = getDrawPosY(projectData, true) val width = data.width * mScaleFactor val height = data.height * mScaleFactor val left = x - width / 2 val top = y + height / 2 val right = x + width / 2 val bottom = y - height / 2 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) canvas.drawRoundRect(left, top, right, bottom, 100f, 100f, getPaintProject(projectData.state)) else canvas.drawRect(left, top, right, bottom, getPaintProject(projectData.state)) drawProjectTitle(canvas, projectData) } private fun getDrawPosX(projectData: ProjectDataIntra, forceReCompute: Boolean = false): Float { if (forceReCompute) drawPosComputed.get(projectData.id).x = getDrawPosX(projectData.x.toFloat()) return drawPosComputed.get(projectData.id).x } private fun getDrawPosX(pos: Float): Float { return (pos - centerPoint.x + position.x) * mScaleFactor + semiWidth } private fun getDrawPosY(projectData: ProjectDataIntra, forceReCompute: Boolean = false): Float { if (forceReCompute) drawPosComputed.get(projectData.id).y = getDrawPosY(projectData.y.toFloat()) return drawPosComputed.get(projectData.id).y } private fun getDrawPosY(pos: Float): Float { return (pos - centerPoint.y + position.y) * mScaleFactor + semiHeight } internal fun ptInsideCircle(x: Float, y: Float, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Circle): Boolean { val projectCenterX = getDrawPosX(projectData) val projectCenterY = getDrawPosY(projectData) val distanceBetween = (x - projectCenterX).pow(2f) + (y - projectCenterY).pow(2f) val radius = data.radius.times(mScaleFactor).pow(2f) return distanceBetween <= radius } internal fun ptInsideRectangle(clickX: Float, clickY: Float, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.Rectangle): Boolean { val x = getDrawPosX(projectData) val y = getDrawPosY(projectData) val semiWidth = data.width * mScaleFactor / 2f val semiHeight = data.height * mScaleFactor / 2f return clickX >= x - semiWidth && clickX <= x + semiWidth / 2 && clickY >= y - semiHeight / 2 && clickY <= y + semiHeight / 2 } internal fun ptInsideRoundRect(clickX: Float, clickY: Float, projectData: ProjectDataIntra, data: ProjectDataIntra.Kind.DrawType.RoundRect): Boolean { val x = getDrawPosX(projectData) val y = getDrawPosY(projectData) val semiWidth = data.width * mScaleFactor / 2f val semiHeight = data.height * mScaleFactor / 2f return clickX >= x - semiWidth && clickX <= x + semiWidth / 2 && clickY >= y - semiHeight / 2 && clickY <= y + semiHeight / 2 } /* ********** interfaces and classes ********** */ interface OnProjectClickListener { fun onClick(projectData: ProjectDataIntra) } /** * Extends [GestureDetector.SimpleOnGestureListener] to provide custom gesture * processing. */ private inner class GestureListener : GestureDetector.SimpleOnGestureListener() { override fun onScroll(e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean { var tmpX = position.x - distanceX * (1 / mScaleFactor) var tmpY = position.y - distanceY * (1 / mScaleFactor) tmpX = tmpX.coerceIn(GRAPH_MAP_LIMIT_MIN.toFloat(), GRAPH_MAP_LIMIT_MAX.toFloat()) tmpY = tmpY.coerceIn(GRAPH_MAP_LIMIT_MIN.toFloat(), GRAPH_MAP_LIMIT_MAX.toFloat()) position.set(tmpX, tmpY) postInvalidate() return true } override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean { mScroller.fling( position.x.roundToInt(), position.y.roundToInt(), velocityX.toInt(), velocityY.toInt(), GRAPH_MAP_LIMIT_MIN, GRAPH_MAP_LIMIT_MAX, GRAPH_MAP_LIMIT_MIN, GRAPH_MAP_LIMIT_MAX) // Start the animator and tell it to animate for the expected duration of the fling. mScrollAnimator.duration = mScroller.duration.toLong() mScrollAnimator.start() return true } override fun onDown(e: MotionEvent): Boolean { // The user is interacting with the pie, so we want to turn on acceleration // so that the interaction is smooth. accelerate() if (isAnimationRunning) { stopScrolling() } return true } override fun onDoubleTap(e: MotionEvent): Boolean { mScaleFactor *= 1.5f postInvalidate() return true } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { var clicked = false data?.forEach { projectData -> projectData.kind?.let { val x = e.x val y = e.y when (it.data) { is ProjectDataIntra.Kind.DrawType.Circle -> { if (ptInsideCircle(x, y, projectData, it.data)) { clicked = true onClickListener?.onClick(projectData) } } is ProjectDataIntra.Kind.DrawType.RoundRect -> { if (ptInsideRoundRect(x, y, projectData, it.data)) { clicked = true onClickListener?.onClick(projectData) } } is ProjectDataIntra.Kind.DrawType.Rectangle -> { if (ptInsideRectangle(x, y, projectData, it.data)) { clicked = true onClickListener?.onClick(projectData) } } } } } return clicked } } private inner class ScaleListener : ScaleGestureDetector.SimpleOnScaleGestureListener() { override fun onScale(detector: ScaleGestureDetector): Boolean { mScaleFactor *= detector.scaleFactor invalidate() return true } } companion object { val centerPoint = Point(3000, 3000) val graphSize = Point(6000, 6000) var GRAPH_MAP_LIMIT_MIN = -2000 var GRAPH_MAP_LIMIT_MAX = 2000 var TEXT_HEIGHT = 25 } }
apache-2.0
9f4000c1764041429665040ae454d799
34.979532
154
0.614856
4.811144
false
false
false
false
Nice3point/ScheduleMVP
app/src/main/java/nice3point/by/schedule/CardSheduleFragment/VCardFragment.kt
1
2208
package nice3point.by.schedule.CardSheduleFragment import android.app.Activity import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import nice3point.by.schedule.Adapters.RVAdapter import nice3point.by.schedule.R import nice3point.by.schedule.TechnicalModule class VCardFragment : Fragment(), iVCardFragment { private lateinit var day_ofWeek: TextView private lateinit var presenter: PCardFragment private lateinit var instanceBundle: Bundle private lateinit var activity: Activity private lateinit var rv: RecyclerView override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.recyclerview_activity, container, false) rv = view.findViewById(R.id.rv) day_ofWeek = view.findViewById(R.id.day_ofWeek) presenter = PCardFragment(this) instanceBundle = this.arguments activity = getActivity() presenter.requestAdapter() day_ofWeek.text = TechnicalModule.dayInString(presenter.getLoadDay()) return view } override fun getInstanceBundle(): Bundle { return instanceBundle } override fun getFragmentActivity(): Activity { return activity } override fun setRVAdapter(adapter: RVAdapter) { rv.layoutManager = LinearLayoutManager(context) rv.setHasFixedSize(true) rv.adapter = adapter } override fun activityDestroyed() { presenter.activityDestroyed() } companion object { private val ARG_POS = "Position" private val ARG_DAY = "Day" fun newInstance(day_of_week: Int, pos: Int): VCardFragment { val fragment = VCardFragment() val args = Bundle() args.putInt(ARG_DAY, day_of_week) args.putInt(ARG_POS, pos) fragment.arguments = args return fragment } } }
apache-2.0
6092e26b4e3eb339891a2581672ccd01
28.052632
87
0.687953
4.580913
false
false
false
false
Jire/Acelta
src/main/kotlin/com/acelta/world/mob/Movement.kt
1
2048
package com.acelta.world.mob import com.acelta.world.mob.player.Player import it.unimi.dsi.fastutil.ints.IntArrayFIFOQueue import java.lang.Math.abs import java.lang.Math.max class Movement(val mob: Mob) { private val xList = IntArrayFIFOQueue(64) private val yList = IntArrayFIFOQueue(64) var direction = Direction.NONE val moving: Boolean get() = direction != Direction.NONE var running = false var teleporting = false var regionChanging = false fun reset() { xList.clear() yList.clear() } fun addFirstStep(nextX: Int, nextY: Int) { reset() addStep(nextX, nextY) } fun addStep(nextX: Int, nextY: Int) { val currentX = if (xList.isEmpty) mob.position.x else xList.firstInt() val currentY = if (yList.isEmpty) mob.position.y else yList.firstInt() addStep(currentX, currentY, nextX, nextY) } private fun addStep(currentX: Int, currentY: Int, nextX: Int, nextY: Int) { var deltaX = nextX - currentX var deltaY = nextY - currentY val max = max(abs(deltaX), abs(deltaY)) repeat(max) { if (deltaX < 0) deltaX++ else if (deltaX > 0) deltaX-- if (deltaY < 0) deltaY++ else if (deltaY > 0) deltaY-- val x = nextX - deltaX val y = nextY - deltaY xList.enqueueFirst(x) yList.enqueueFirst(y) } } fun tick() = with(mob.position) { if (xList.isEmpty) direction = Direction.NONE else { var nextX = xList.dequeueLastInt() var nextY = yList.dequeueLastInt() direction = Direction.between(x, y, nextX, nextY) x = nextX y = nextY if (running && !xList.isEmpty) { nextX = xList.dequeueLastInt() nextY = yList.dequeueLastInt() direction = Direction.between(x, y, nextX, nextY) x = nextX y = nextY } val diffX = x - (centerX /* should really be last center X */ * 8) val diffY = y - (centerY /* should really be last center Y */ * 8) if (diffX < 16 || diffX >= 88 || diffY < 16 || diffY >= 88) { //regionChanging = true // TODO: set last region X and Y } } if (regionChanging && mob is Player) mob.send.sector() } }
gpl-3.0
f300d608b6121651ada4098d321d4618
23.105882
76
0.660156
3.007342
false
false
false
false
tangying91/profit
src/main/java/org/profit/app/analyse/StockDownAnalyzer.kt
1
1330
package org.profit.app.analyse import org.profit.app.StockHall import org.profit.app.pojo.StockHistory import org.profit.util.DateUtils import org.profit.util.FileUtils import org.profit.util.StockUtils import java.lang.Exception /** * 【积】周期内,连续下跌天数较多 */ class StockDownAnalyzer(code: String, private val statCount: Int, private val downPercent: Double) : StockAnalyzer(code) { /** * 1.周期内总天数 * 2.周期内连续下跌最大天数 * 3.周内总下跌天数 */ override fun analyse(results: MutableList<String>) { // 获取数据,后期可以限制天数 val list = readHistories(statCount) // 如果没有数据 if (list.size < statCount) { return } val totalDay = list.size val downDays = list.count { it.close < it.open } val percent = (list[0].close - list[statCount - 1].open).div(list[statCount - 1].open) * 100 if (downDays > totalDay * downPercent) { val content = "$code${StockHall.stockName(code)} 一共$totalDay 天,累计一共下跌$downDays 天,区间涨幅${StockUtils.twoDigits(percent)}% ,快速查看: http://stockpage.10jqka.com.cn/$code/" FileUtils.writeStat(content) } } }
apache-2.0
40828368dd137cfdec6d0010aac2399f
29.837838
176
0.627551
3.20436
false
false
false
false
bk138/multivnc
android/app/src/main/java/com/coboltforge/dontmind/multivnc/ConnectionBean.kt
1
4363
package com.coboltforge.dontmind.multivnc import android.os.Parcelable import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import kotlinx.parcelize.Parcelize import kotlinx.serialization.Serializable @Parcelize @Serializable @Entity(tableName = "CONNECTION_BEAN") data class ConnectionBean( @JvmField @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") var id: Long = 0, @JvmField @ColumnInfo(name = "NICKNAME") var nickname: String? = "", @JvmField @ColumnInfo(name = "ADDRESS") var address: String? = "", @JvmField @ColumnInfo(name = "PORT") var port: Int = 5900, @JvmField @ColumnInfo(name = "PASSWORD") var password: String? = "", @JvmField @ColumnInfo(name = "COLORMODEL") var colorModel: String? = COLORMODEL.C24bit.nameString(), @JvmField @ColumnInfo(name = "FORCEFULL") var forceFull: Long = 0, @JvmField @ColumnInfo(name = "REPEATERID") var repeaterId: String? = "", @JvmField @ColumnInfo(name = "INPUTMODE") var inputMode: String? = null, @JvmField @ColumnInfo(name = "SCALEMODE") var scalemode: String? = null, @JvmField @ColumnInfo(name = "USELOCALCURSOR") var useLocalCursor: Boolean = false, @JvmField @ColumnInfo(name = "KEEPPASSWORD") var keepPassword: Boolean = true, @JvmField @ColumnInfo(name = "FOLLOWMOUSE") var followMouse: Boolean = true, @JvmField @ColumnInfo(name = "USEREPEATER") var useRepeater: Boolean = false, @JvmField @ColumnInfo(name = "METALISTID") var metaListId: Long = 1, @JvmField @ColumnInfo(name = "LAST_META_KEY_ID") var lastMetaKeyId: Long = 0, @JvmField @ColumnInfo(name = "FOLLOWPAN", defaultValue = "0") var followPan: Boolean = false, @JvmField @ColumnInfo(name = "USERNAME") var userName: String? = "", @JvmField @ColumnInfo(name = "SECURECONNECTIONTYPE") var secureConnectionType: String? = null, @JvmField @ColumnInfo(name = "SHOWZOOMBUTTONS", defaultValue = "1") var showZoomButtons: Boolean = false, @JvmField @ColumnInfo(name = "DOUBLE_TAP_ACTION") var doubleTapAction: String? = null ) : Comparable<ConnectionBean>, Parcelable { override fun toString(): String { return "$id $nickname: $address, port $port" } override fun compareTo(other: ConnectionBean): Int { var result = nickname!!.compareTo(other.nickname!!) if (result == 0) { result = address!!.compareTo(other.address!!) if (result == 0) { result = port - other.port } } return result } /** * parse host:port or [host]:port and split into address and port fields * @param hostport_str * @return true if there was a port, false if not */ fun parseHostPort(hostport_str: String): Boolean { val nr_colons = hostport_str.replace("[^:]".toRegex(), "").length val nr_endbrackets = hostport_str.replace("[^]]".toRegex(), "").length if (nr_colons == 1) { // IPv4 val p = hostport_str.substring(hostport_str.indexOf(':') + 1) try { port = p.toInt() } catch (e: Exception) { } address = hostport_str.substring(0, hostport_str.indexOf(':')) return true } if (nr_colons > 1 && nr_endbrackets == 1) { val p = hostport_str.substring(hostport_str.indexOf(']') + 2) // it's [addr]:port try { port = p.toInt() } catch (e: Exception) { } address = hostport_str.substring(0, hostport_str.indexOf(']') + 1) return true } return false } companion object { //These are used by ConnectionListActivity const val GEN_FIELD_NICKNAME = "NICKNAME" const val GEN_FIELD_ADDRESS = "ADDRESS" const val GEN_FIELD_PORT = "PORT" const val GEN_FIELD_REPEATERID = "REPEATERID" } }
gpl-3.0
28a044d0a7aced26f812fb9c141a0bb9
27.51634
93
0.565437
4.240039
false
false
false
false